instance_id
stringlengths 10
57
| base_commit
stringlengths 40
40
| created_at
stringdate 2014-04-30 14:58:36
2025-04-30 20:14:11
| environment_setup_commit
stringlengths 40
40
| hints_text
stringlengths 0
273k
| patch
stringlengths 251
7.06M
| problem_statement
stringlengths 11
52.5k
| repo
stringlengths 7
53
| test_patch
stringlengths 231
997k
| meta
dict | version
stringclasses 864
values | install_config
dict | requirements
stringlengths 93
34.2k
⌀ | environment
stringlengths 760
20.5k
⌀ | FAIL_TO_PASS
sequencelengths 1
9.39k
| FAIL_TO_FAIL
sequencelengths 0
2.69k
| PASS_TO_PASS
sequencelengths 0
7.87k
| PASS_TO_FAIL
sequencelengths 0
192
| license_name
stringclasses 56
values | __index_level_0__
int64 0
21.4k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
typesafehub__conductr-cli-47 | e6196516227db9bb9b2027e1d2aa1bd8cb082337 | 2015-04-16 09:38:43 | e5561a7e43d92a0c19e7b6e31a36448455a17fba | diff --git a/conductr_cli/conduct_services.py b/conductr_cli/conduct_services.py
index cacec60..2b07544 100644
--- a/conductr_cli/conduct_services.py
+++ b/conductr_cli/conduct_services.py
@@ -34,10 +34,11 @@ def services(args):
service_endpoints = {}
for service in data:
url = urlparse(service['service'])
- try:
- service_endpoints[url.path] |= {service['service']}
- except KeyError:
- service_endpoints[url.path] = {service['service']}
+ if not (url.path == '' or url.path == '/'):
+ try:
+ service_endpoints[url.path] |= {service['service']}
+ except KeyError:
+ service_endpoints[url.path] = {service['service']}
duplicate_endpoints = [service for (service, endpoint) in service_endpoints.items() if len(endpoint) > 1] if len(service_endpoints) > 0 else []
data.insert(0, {'service': 'SERVICE', 'bundle_id': 'BUNDLE ID', 'bundle_name': 'BUNDLE NAME', 'status': 'STATUS'})
| Distinct authorities causing spurious warnings on service cmd
@edwardcallahan Discovered the following warnings when performing `conduct services` having `http://:8080` and `http://milo.typesafe.com` as endpoint services:
```bash
ubuntu@10:~$ conduct services
SERVICE BUNDLE ID BUNDLE NAME STATUS
http://:8080 d248907 visualizer Running
http://milo.typesafe.com 353a913-bbb42aa project-doc Running
WARNING: Multiple endpoints found for the following services:
WARNING: Service resolution for these services is undefined.
```
Those warnings shouldn't be appearing here as different authorities are used. | typesafehub/conductr-cli | diff --git a/conductr_cli/test/data/two_bundles_no_path.json b/conductr_cli/test/data/two_bundles_no_path.json
new file mode 100644
index 0000000..5199179
--- /dev/null
+++ b/conductr_cli/test/data/two_bundles_no_path.json
@@ -0,0 +1,144 @@
+[
+ {
+ "attributes": {
+ "bundleName": "multi-comp-multi-endp-1.0.0",
+ "diskSpace": 100,
+ "memory": 200,
+ "nrOfCpus": 1.0,
+ "roles": []
+ },
+ "bundleConfig": {
+ "endpoints": {
+ "comp1-endp1": {
+ "protocol": "http",
+ "services": ["http://:8010/comp1-endp1"]
+ },
+ "comp1-endp2": {
+ "protocol": "http",
+ "services": ["http://:8011/comp1-endp2"]
+ },
+ "comp2-endp1": {
+ "protocol": "http",
+ "services": ["http://:9010/comp2-endp1"]
+ },
+ "comp2-endp2": {
+ "protocol": "http",
+ "services": ["http://:9011"]
+ }
+ }
+ },
+ "bundleDigest": "f804d644a01a5ab9f679f76939f5c7e28301e1aecc83627877065cef26de12db",
+ "bundleExecutions": [
+ {
+ "endpoints": {
+ "comp1-endp1": {
+ "bindPort": 8000,
+ "hostPort": 8000
+ },
+ "comp1-endp2": {
+ "bindPort": 8001,
+ "hostPort": 8001
+ },
+ "comp2-endp1": {
+ "bindPort": 9000,
+ "hostPort": 9000
+ },
+ "comp2-endp2": {
+ "bindPort": 9001,
+ "hostPort": 9001
+ }
+ },
+ "host": "172.17.0.4",
+ "isStarted": true
+ }
+ ],
+ "bundleId": "f804d644a01a5ab9f679f76939f5c7e2",
+ "bundleInstallations": [
+ {
+ "bundleFile": "file:///tmp/f804d644a01a5ab9f679f76939f5c7e28301e1aecc83627877065cef26de12db.zip",
+ "uniqueAddress": {
+ "address": "akka.tcp://[email protected]:9004",
+ "uid": -29020887
+ }
+ },
+ {
+ "bundleFile": "file:///tmp/f804d644a01a5ab9f679f76939f5c7e28301e1aecc83627877065cef26de12db.zip",
+ "uniqueAddress": {
+ "address": "akka.tcp://[email protected]:9004",
+ "uid": 247035768
+ }
+ }
+ ]
+ },
+ {
+ "attributes": {
+ "bundleName": "multi2-comp-multi-endp-1.0.0",
+ "diskSpace": 100,
+ "memory": 200,
+ "nrOfCpus": 1.0,
+ "roles": []
+ },
+ "bundleConfig": {
+ "endpoints": {
+ "comp2-endp1": {
+ "protocol": "http",
+ "services": ["http://:9010/comp2-endp1"]
+ },
+ "comp2-endp2": {
+ "protocol": "http",
+ "services": ["http://:6011"]
+ },
+ "comp3-endp1": {
+ "protocol": "http",
+ "services": ["http://:7010/comp3-endp1"]
+ },
+ "comp3-endp2": {
+ "protocol": "http",
+ "services": ["http://:7011/comp3-endp2"]
+ }
+ }
+ },
+ "bundleDigest": "6e4560ef252cd57322f595627c881c48b2f8bf98c3b6d08073c0b9b5db1e5068",
+ "bundleExecutions": [
+ {
+ "endpoints": {
+ "comp2-endp1": {
+ "bindPort": 6000,
+ "hostPort": 6000
+ },
+ "comp2-endp2": {
+ "bindPort": 6001,
+ "hostPort": 6001
+ },
+ "comp3-endp1": {
+ "bindPort": 7000,
+ "hostPort": 7000
+ },
+ "comp3-endp2": {
+ "bindPort": 7001,
+ "hostPort": 7001
+ }
+ },
+ "host": "172.17.0.4",
+ "isStarted": true
+ }
+ ],
+ "bundleId": "6e4560ef252cd57322f595627c881c48",
+ "bundleInstallations": [
+ {
+ "bundleFile": "file:///tmp/6e4560ef252cd57322f595627c881c48b2f8bf98c3b6d08073c0b9b5db1e5068.zip",
+ "uniqueAddress": {
+ "address": "akka.tcp://[email protected]:9004",
+ "uid": -29020887
+ }
+ },
+ {
+ "bundleFile": "file:///tmp/6e4560ef252cd57322f595627c881c48b2f8bf98c3b6d08073c0b9b5db1e5068.zip",
+ "uniqueAddress": {
+ "address": "akka.tcp://[email protected]:9004",
+ "uid": 247035768
+ }
+ }
+ ]
+ }
+]
diff --git a/conductr_cli/test/test_conduct_services.py b/conductr_cli/test/test_conduct_services.py
index 8fc4fc8..590794e 100644
--- a/conductr_cli/test/test_conduct_services.py
+++ b/conductr_cli/test/test_conduct_services.py
@@ -52,6 +52,27 @@ class TestConductServicesCommand(TestCase, CliTestCase):
|"""),
self.output(stdout))
+ def test_two_bundles_mult_components_endpoints_no_path(self):
+ http_method = self.respond_with_file_contents('data/two_bundles_no_path.json')
+ stdout = MagicMock()
+
+ with patch('requests.get', http_method), patch('sys.stdout', stdout):
+ conduct_services.services(MagicMock(**self.default_args))
+
+ http_method.assert_called_with(self.default_url)
+ self.assertEqual(
+ strip_margin("""|SERVICE BUNDLE ID BUNDLE NAME STATUS
+ |http://:6011 6e4560e multi2-comp-multi-endp-1.0.0 Running
+ |http://:7010/comp3-endp1 6e4560e multi2-comp-multi-endp-1.0.0 Running
+ |http://:7011/comp3-endp2 6e4560e multi2-comp-multi-endp-1.0.0 Running
+ |http://:8010/comp1-endp1 f804d64 multi-comp-multi-endp-1.0.0 Running
+ |http://:8011/comp1-endp2 f804d64 multi-comp-multi-endp-1.0.0 Running
+ |http://:9010/comp2-endp1 f804d64 multi-comp-multi-endp-1.0.0 Running
+ |http://:9010/comp2-endp1 6e4560e multi2-comp-multi-endp-1.0.0 Running
+ |http://:9011 f804d64 multi-comp-multi-endp-1.0.0 Running
+ |"""),
+ self.output(stdout))
+
def test_one_bundle_starting(self):
http_method = self.respond_with_file_contents('data/one_bundle_starting.json')
stdout = MagicMock()
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_hyperlinks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 0,
"issue_text_score": 1,
"test_score": 0
},
"num_modified_files": 1
} | 0.13 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "pytest",
"pip_packages": [
"requests>=2.3.0",
"argcomplete>=0.8.1",
"pyhocon==0.2.1",
"pytest"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.9",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | argcomplete==3.6.1
certifi==2025.1.31
charset-normalizer==3.4.1
-e git+https://github.com/typesafehub/conductr-cli.git@e6196516227db9bb9b2027e1d2aa1bd8cb082337#egg=conductr_cli
exceptiongroup @ file:///croot/exceptiongroup_1706031385326/work
idna==3.10
iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work
packaging @ file:///croot/packaging_1734472117206/work
pluggy @ file:///croot/pluggy_1733169602837/work
pyhocon==0.2.1
pyparsing==2.0.3
pytest @ file:///croot/pytest_1738938843180/work
requests==2.32.3
tomli @ file:///opt/conda/conda-bld/tomli_1657175507142/work
urllib3==2.3.0
| name: conductr-cli
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- exceptiongroup=1.2.0=py39h06a4308_0
- iniconfig=1.1.1=pyhd3eb1b0_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=3.0.16=h5eee18b_0
- packaging=24.2=py39h06a4308_0
- pip=25.0=py39h06a4308_0
- pluggy=1.5.0=py39h06a4308_0
- pytest=8.3.4=py39h06a4308_0
- python=3.9.21=he870216_1
- readline=8.2=h5eee18b_0
- setuptools=75.8.0=py39h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- tomli=2.0.1=py39h06a4308_0
- tzdata=2025a=h04d1e81_0
- wheel=0.45.1=py39h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- argcomplete==3.6.1
- certifi==2025.1.31
- charset-normalizer==3.4.1
- idna==3.10
- pyhocon==0.2.1
- pyparsing==2.0.3
- requests==2.32.3
- urllib3==2.3.0
prefix: /opt/conda/envs/conductr-cli
| [
"conductr_cli/test/test_conduct_services.py::TestConductServicesCommand::test_two_bundles_mult_components_endpoints_no_path"
] | [] | [
"conductr_cli/test/test_conduct_services.py::TestConductServicesCommand::test_no_bundles",
"conductr_cli/test/test_conduct_services.py::TestConductServicesCommand::test_one_bundle_starting",
"conductr_cli/test/test_conduct_services.py::TestConductServicesCommand::test_one_bundle_starting_long_ids",
"conductr_cli/test/test_conduct_services.py::TestConductServicesCommand::test_two_bundles_mult_components_endpoints"
] | [] | Apache License 2.0 | 100 |
|
mkdocs__mkdocs-464 | 852996e7e1e17e83ac650a5c5be6834323cca94e | 2015-04-18 10:10:36 | 463c5b647e9ce5992b519708a0b9c4cba891d65c | diff --git a/mkdocs/nav.py b/mkdocs/nav.py
index 5a215b28..ee7d6b34 100644
--- a/mkdocs/nav.py
+++ b/mkdocs/nav.py
@@ -224,6 +224,13 @@ def _generate_site_navigation(pages_config, url_context, use_directory_urls=True
filename = path.split(os.path.sep)[0]
title = filename_to_title(filename)
+ # If we don't have a child title but the other title is the same, we
+ # should be within a section and the child title needs to be inferred
+ # from the filename.
+ if len(nav_items) and title == nav_items[-1].title == title and child_title is None:
+ filename = path.split(os.path.sep)[-1]
+ child_title = filename_to_title(filename)
+
url = utils.get_url_path(path, use_directory_urls)
if not child_title:
| Regression when building docs
I got this when building the Django REST Framework docs with 0.12.1
$ mkdocs build
Building documentation to directory: site
Directory site contains stale files. Use --clean to remove them.
Traceback (most recent call last):
File "/home/dougalmatthews/.virtualenvs/mkdocs/bin/mkdocs", line 9, in <module>
load_entry_point('mkdocs==0.12.1', 'console_scripts', 'mkdocs')()
File "/home/dougalmatthews/.virtualenvs/mkdocs/lib/python2.7/site-packages/mkdocs/main.py", line 77, in run_main
main(cmd, args=sys.argv[2:], options=dict(opts))
File "/home/dougalmatthews/.virtualenvs/mkdocs/lib/python2.7/site-packages/mkdocs/main.py", line 52, in main
build(config, clean_site_dir=clean_site_dir)
File "/home/dougalmatthews/.virtualenvs/mkdocs/lib/python2.7/site-packages/mkdocs/build.py", line 252, in build
build_pages(config)
File "/home/dougalmatthews/.virtualenvs/mkdocs/lib/python2.7/site-packages/mkdocs/build.py", line 209, in build_pages
site_navigation = nav.SiteNavigation(config['pages'], config['use_directory_urls'])
File "/home/dougalmatthews/.virtualenvs/mkdocs/lib/python2.7/site-packages/mkdocs/nav.py", line 37, in __init__
_generate_site_navigation(pages_config, self.url_context, use_directory_urls)
File "/home/dougalmatthews/.virtualenvs/mkdocs/lib/python2.7/site-packages/mkdocs/nav.py", line 243, in _generate_site_navigation
header.children.append(page)
AttributeError: 'Page' object has no attribute 'children'
| mkdocs/mkdocs | diff --git a/mkdocs/tests/nav_tests.py b/mkdocs/tests/nav_tests.py
index 4e8531cd..cdd2bf9f 100644
--- a/mkdocs/tests/nav_tests.py
+++ b/mkdocs/tests/nav_tests.py
@@ -63,6 +63,30 @@ class SiteNavigationTests(unittest.TestCase):
self.assertEqual(len(site_navigation.nav_items), 3)
self.assertEqual(len(site_navigation.pages), 6)
+ def test_indented_toc_missing_child_title(self):
+ pages = [
+ ('index.md', 'Home'),
+ ('api-guide/running.md', 'API Guide', 'Running'),
+ ('api-guide/testing.md', 'API Guide'),
+ ('api-guide/debugging.md', 'API Guide', 'Debugging'),
+ ('about/release-notes.md', 'About', 'Release notes'),
+ ('about/license.md', 'About', 'License')
+ ]
+ expected = dedent("""
+ Home - /
+ API Guide
+ Running - /api-guide/running/
+ Testing - /api-guide/testing/
+ Debugging - /api-guide/debugging/
+ About
+ Release notes - /about/release-notes/
+ License - /about/license/
+ """)
+ site_navigation = nav.SiteNavigation(pages)
+ self.assertEqual(str(site_navigation).strip(), expected)
+ self.assertEqual(len(site_navigation.nav_items), 3)
+ self.assertEqual(len(site_navigation.pages), 6)
+
def test_nested_ungrouped(self):
pages = [
('index.md', 'Home'),
| {
"commit_name": "head_commit",
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true,
"llm_score": {
"difficulty_score": 2,
"issue_text_score": 1,
"test_score": 0
},
"num_modified_files": 1
} | 0.12 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[dev]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest",
"mock",
"click"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.9",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | click==8.1.8
exceptiongroup==1.2.2
ghp-import==2.1.0
importlib_metadata==8.6.1
iniconfig==2.1.0
Jinja2==3.1.6
livereload==2.7.1
Markdown==3.7
MarkupSafe==3.0.2
-e git+https://github.com/mkdocs/mkdocs.git@852996e7e1e17e83ac650a5c5be6834323cca94e#egg=mkdocs
mock==5.2.0
packaging==24.2
pluggy==1.5.0
pytest==8.3.5
python-dateutil==2.9.0.post0
PyYAML==6.0.2
six==1.17.0
tomli==2.2.1
tornado==6.4.2
zipp==3.21.0
| name: mkdocs
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=3.0.16=h5eee18b_0
- pip=25.0=py39h06a4308_0
- python=3.9.21=he870216_1
- readline=8.2=h5eee18b_0
- setuptools=75.8.0=py39h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- tzdata=2025a=h04d1e81_0
- wheel=0.45.1=py39h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- click==8.1.8
- exceptiongroup==1.2.2
- ghp-import==2.1.0
- importlib-metadata==8.6.1
- iniconfig==2.1.0
- jinja2==3.1.6
- livereload==2.7.1
- markdown==3.7
- markupsafe==3.0.2
- mock==5.2.0
- packaging==24.2
- pluggy==1.5.0
- pytest==8.3.5
- python-dateutil==2.9.0.post0
- pyyaml==6.0.2
- six==1.17.0
- tomli==2.2.1
- tornado==6.4.2
- zipp==3.21.0
prefix: /opt/conda/envs/mkdocs
| [
"mkdocs/tests/nav_tests.py::SiteNavigationTests::test_indented_toc_missing_child_title"
] | [] | [
"mkdocs/tests/nav_tests.py::SiteNavigationTests::test_ancestors",
"mkdocs/tests/nav_tests.py::SiteNavigationTests::test_base_url",
"mkdocs/tests/nav_tests.py::SiteNavigationTests::test_empty_toc_item",
"mkdocs/tests/nav_tests.py::SiteNavigationTests::test_generate_site_navigation",
"mkdocs/tests/nav_tests.py::SiteNavigationTests::test_generate_site_navigation_windows",
"mkdocs/tests/nav_tests.py::SiteNavigationTests::test_indented_toc",
"mkdocs/tests/nav_tests.py::SiteNavigationTests::test_invalid_pages_config",
"mkdocs/tests/nav_tests.py::SiteNavigationTests::test_nested_ungrouped",
"mkdocs/tests/nav_tests.py::SiteNavigationTests::test_nested_ungrouped_no_titles",
"mkdocs/tests/nav_tests.py::SiteNavigationTests::test_nested_ungrouped_no_titles_windows",
"mkdocs/tests/nav_tests.py::SiteNavigationTests::test_relative_md_links_have_slash",
"mkdocs/tests/nav_tests.py::SiteNavigationTests::test_simple_toc",
"mkdocs/tests/nav_tests.py::SiteNavigationTests::test_walk_empty_toc",
"mkdocs/tests/nav_tests.py::SiteNavigationTests::test_walk_indented_toc",
"mkdocs/tests/nav_tests.py::SiteNavigationTests::test_walk_simple_toc"
] | [] | BSD 2-Clause "Simplified" License | 101 |
|
mahmoud__boltons-31 | c9b3d2452e4ffe43920874f4f6f2e8fe425ebf00 | 2015-04-19 07:14:14 | c9b3d2452e4ffe43920874f4f6f2e8fe425ebf00 | asottile: I guess I'll fix tbutils to work under python3? Kinda unfortunate for the build to fail because I added tests :( (when it wouldn't have worked before then!) | diff --git a/.travis.yml b/.travis.yml
index 9f97722..0df3b47 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -6,4 +6,4 @@ python:
- "pypy"
install: "pip install -r requirements-test.txt"
-script: "py.test --doctest-modules boltons"
+script: "py.test --doctest-modules boltons tests"
diff --git a/boltons/tbutils.py b/boltons/tbutils.py
index 2ff476d..6f402e9 100644
--- a/boltons/tbutils.py
+++ b/boltons/tbutils.py
@@ -27,6 +27,12 @@ import sys
import linecache
+if str is bytes: # py2
+ text = unicode
+else: # py3
+ text = str
+
+
# TODO: chaining primitives? what are real use cases where these help?
# TODO: print_* for backwards compatability
@@ -691,7 +697,7 @@ class ParsedException(object):
Args:
tb_str (str): The traceback text (:class:`unicode` or UTF-8 bytes)
"""
- if not isinstance(tb_str, unicode):
+ if not isinstance(tb_str, text):
tb_str = tb_str.decode('utf-8')
tb_lines = tb_str.lstrip().splitlines()
@@ -717,21 +723,35 @@ class ParsedException(object):
raise ValueError('unrecognized traceback string format')
frames = []
- for pair_idx in range(start_line, len(tb_lines), 2):
- frame_line = tb_lines[pair_idx].strip()
+ line_no = start_line
+ while True:
+ frame_line = tb_lines[line_no].strip()
frame_match = frame_re.match(frame_line)
if frame_match:
frame_dict = frame_match.groupdict()
+ next_line = tb_lines[line_no + 1]
+ next_line_stripped = next_line.strip()
+ if (
+ frame_re.match(next_line_stripped) or
+ # The exception message will not be indented
+ # This check is to avoid overrunning on eval-like
+ # tracebacks where the last frame doesn't have source
+ # code in the traceback
+ not next_line.startswith(' ')
+ ):
+ frame_dict['source_line'] = ''
+ else:
+ frame_dict['source_line'] = next_line_stripped
+ line_no += 1
else:
break
- frame_dict['source_line'] = tb_lines[pair_idx + 1].strip()
+ line_no += 1
frames.append(frame_dict)
- exc_line_offset = start_line + len(frames) * 2
try:
- exc_line = tb_lines[exc_line_offset]
+ exc_line = tb_lines[line_no]
exc_type, _, exc_msg = exc_line.partition(':')
- except:
+ except Exception:
exc_type, exc_msg = '', ''
return cls(exc_type, exc_msg, frames)
diff --git a/tox.ini b/tox.ini
index 928a1dc..e99092f 100644
--- a/tox.ini
+++ b/tox.ini
@@ -2,4 +2,4 @@
envlist = py27,py34,pypy
[testenv]
deps = -rrequirements-test.txt
-commands = py.test --doctest-modules boltons
+commands = py.test --doctest-modules boltons tests
| ParsedException.from_string produces wrong result when a frame is missing source (such as from eval)
Take this (modified from the original) trace:
```
Traceback (most recent call last):
File "<string>", line 2, in _some_function
File "myfile.py", line 3, in some_other_function
return foo(bar, baz)
MyException: ExceptionValue
```
ParsedException gives me an incorrect result:
```
>>> ParsedException.from_string(x)
ParsedException(u' return foo(bar, baz)', u'', frames=[{'source_line': u'File "myfile.py", line 3, in some_other_function', 'filepath': u'<string>', 'lineno': u'2', 'funcname': u'_some_function'}])
```
| mahmoud/boltons | diff --git a/tests/__init__.py b/tests/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/tests/tbutils_test.py b/tests/tbutils_test.py
new file mode 100644
index 0000000..64eb17a
--- /dev/null
+++ b/tests/tbutils_test.py
@@ -0,0 +1,54 @@
+from __future__ import absolute_import
+from __future__ import unicode_literals
+
+from boltons.tbutils import ParsedException
+
+
+def test_normal_tb():
+ tb = '''\
+Traceback (most recent call last):
+ File "<string>", line 2, in _some_function
+ return some_other_function(1)
+ File "myfile.py", line 3, in some_other_function
+ return foo(bar, baz)
+MyException: ExceptionValue
+'''
+ parsed = ParsedException.from_string(tb)
+ assert parsed.exc_type == 'MyException'
+ assert parsed.exc_msg == ' ExceptionValue'
+ assert parsed.frames == [
+ {
+ 'source_line': 'return some_other_function(1)',
+ 'filepath': '<string>',
+ 'lineno': '2',
+ 'funcname': '_some_function'
+ },
+ {
+ 'source_line': 'return foo(bar, baz)',
+ 'filepath': 'myfile.py',
+ 'lineno': '3',
+ 'funcname': 'some_other_function',
+ }
+ ]
+
+
+def test_eval_tb():
+ tb = '''\
+Traceback (most recent call last):
+ File "<string>", line 2, in _some_function
+ File "myfile.py", line 3, in some_other_function
+ return foo(bar, baz)
+MyException: ExceptionValue
+'''
+ parsed = ParsedException.from_string(tb)
+ assert parsed.exc_type == 'MyException'
+
+
+def test_last_line_is_eval_like():
+ tb = '''\
+Traceback (most recent call last):
+ File "<string>", line 2, in _some_function
+MyException: ExceptionValue
+'''
+ parsed = ParsedException.from_string(tb)
+ assert parsed.exc_type == 'MyException'
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 1,
"issue_text_score": 0,
"test_score": 1
},
"num_modified_files": 3
} | 0.6 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "pytest",
"pip_packages": [
"py",
"pytest"
],
"pre_install": null,
"python": "3.4",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | attrs @ file:///opt/conda/conda-bld/attrs_1642510447205/work
-e git+https://github.com/mahmoud/boltons.git@c9b3d2452e4ffe43920874f4f6f2e8fe425ebf00#egg=boltons
certifi==2021.5.30
importlib-metadata @ file:///tmp/build/80754af9/importlib-metadata_1631916693255/work
iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work
more-itertools @ file:///tmp/build/80754af9/more-itertools_1637733554872/work
packaging @ file:///tmp/build/80754af9/packaging_1637314298585/work
pluggy @ file:///tmp/build/80754af9/pluggy_1615976315926/work
py @ file:///opt/conda/conda-bld/py_1644396412707/work
pyparsing @ file:///tmp/build/80754af9/pyparsing_1635766073266/work
pytest==6.2.4
toml @ file:///tmp/build/80754af9/toml_1616166611790/work
typing_extensions @ file:///opt/conda/conda-bld/typing_extensions_1647553014482/work
zipp @ file:///tmp/build/80754af9/zipp_1633618647012/work
| name: boltons
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- attrs=21.4.0=pyhd3eb1b0_0
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- importlib-metadata=4.8.1=py36h06a4308_0
- importlib_metadata=4.8.1=hd3eb1b0_0
- iniconfig=1.1.1=pyhd3eb1b0_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- more-itertools=8.12.0=pyhd3eb1b0_0
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- packaging=21.3=pyhd3eb1b0_0
- pip=21.2.2=py36h06a4308_0
- pluggy=0.13.1=py36h06a4308_0
- py=1.11.0=pyhd3eb1b0_0
- pyparsing=3.0.4=pyhd3eb1b0_0
- pytest=6.2.4=py36h06a4308_2
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_0
- setuptools=58.0.4=py36h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- toml=0.10.2=pyhd3eb1b0_0
- typing_extensions=4.1.1=pyh06a4308_0
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- zipp=3.6.0=pyhd3eb1b0_0
- zlib=1.2.13=h5eee18b_1
prefix: /opt/conda/envs/boltons
| [
"tests/tbutils_test.py::test_normal_tb",
"tests/tbutils_test.py::test_eval_tb",
"tests/tbutils_test.py::test_last_line_is_eval_like"
] | [] | [] | [] | BSD License | 102 |
Pylons__webob-197 | 9b79f5f913fb1f07c68102a2279ed757a2a9abf6 | 2015-04-23 02:49:34 | 9b79f5f913fb1f07c68102a2279ed757a2a9abf6 | diff --git a/webob/response.py b/webob/response.py
index a164938..9579b7e 100644
--- a/webob/response.py
+++ b/webob/response.py
@@ -116,16 +116,13 @@ class Response(object):
if 'charset' in kw:
charset = kw.pop('charset')
elif self.default_charset:
- if (content_type
- and 'charset=' not in content_type
- and (content_type == 'text/html'
- or content_type.startswith('text/')
- or content_type.startswith('application/xml')
- or content_type.startswith('application/json')
- or (content_type.startswith('application/')
- and (content_type.endswith('+xml') or content_type.endswith('+json'))))):
- charset = self.default_charset
- if content_type and charset:
+ if content_type and 'charset=' not in content_type:
+ if (content_type == 'text/html'
+ or content_type.startswith('text/')
+ or _is_xml(content_type)
+ or _is_json(content_type)):
+ charset = self.default_charset
+ if content_type and charset and not _is_json(content_type):
content_type += '; charset=' + charset
elif self._headerlist and charset:
self.charset = charset
@@ -1231,6 +1228,16 @@ class EmptyResponse(object):
__next__ = next # py3
+def _is_json(content_type):
+ return (content_type.startswith('application/json')
+ or (content_type.startswith('application/')
+ and content_type.endswith('+json')))
+
+def _is_xml(content_type):
+ return (content_type.startswith('application/xml')
+ or (content_type.startswith('application/')
+ and content_type.endswith('+xml')))
+
def _request_uri(environ):
"""Like wsgiref.url.request_uri, except eliminates :80 ports
| JSON content shouldn't need a UTF-8 on the content-type
Fix this issue: https://github.com/Pylons/pyramid/issues/1611#issuecomment-93073442 | Pylons/webob | diff --git a/tests/test_response.py b/tests/test_response.py
index d9c1cd3..6425a22 100644
--- a/tests/test_response.py
+++ b/tests/test_response.py
@@ -104,6 +104,7 @@ def test_set_response_status_code_generic_reason():
assert res.status_code == 299
assert res.status == '299 Success'
+
def test_content_type():
r = Response()
# default ctype and charset
@@ -121,6 +122,21 @@ def test_init_content_type_w_charset():
v = 'text/plain;charset=ISO-8859-1'
eq_(Response(content_type=v).headers['content-type'], v)
+def test_init_adds_default_charset_when_not_json():
+ content_type = 'text/plain'
+ expected = 'text/plain; charset=UTF-8'
+ eq_(Response(content_type=content_type).headers['content-type'], expected)
+
+def test_init_no_charset_when_json():
+ content_type = 'application/json'
+ expected = content_type
+ eq_(Response(content_type=content_type).headers['content-type'], expected)
+
+def test_init_keeps_specified_charset_when_json():
+ content_type = 'application/json;charset=ISO-8859-1'
+ expected = content_type
+ eq_(Response(content_type=content_type).headers['content-type'], expected)
+
def test_cookies():
res = Response()
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_short_problem_statement",
"has_hyperlinks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 1,
"issue_text_score": 2,
"test_score": 2
},
"num_modified_files": 1
} | 1.4 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[dev]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "pytest",
"pip_packages": [
"nose",
"coverage",
"pytest"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.9",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | coverage==7.8.0
exceptiongroup @ file:///croot/exceptiongroup_1706031385326/work
iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work
nose==1.3.7
packaging @ file:///croot/packaging_1734472117206/work
pluggy @ file:///croot/pluggy_1733169602837/work
pytest @ file:///croot/pytest_1738938843180/work
tomli @ file:///opt/conda/conda-bld/tomli_1657175507142/work
-e git+https://github.com/Pylons/webob.git@9b79f5f913fb1f07c68102a2279ed757a2a9abf6#egg=WebOb
| name: webob
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- exceptiongroup=1.2.0=py39h06a4308_0
- iniconfig=1.1.1=pyhd3eb1b0_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=3.0.16=h5eee18b_0
- packaging=24.2=py39h06a4308_0
- pip=25.0=py39h06a4308_0
- pluggy=1.5.0=py39h06a4308_0
- pytest=8.3.4=py39h06a4308_0
- python=3.9.21=he870216_1
- readline=8.2=h5eee18b_0
- setuptools=75.8.0=py39h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- tomli=2.0.1=py39h06a4308_0
- tzdata=2025a=h04d1e81_0
- wheel=0.45.1=py39h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- coverage==7.8.0
- nose==1.3.7
prefix: /opt/conda/envs/webob
| [
"tests/test_response.py::test_init_no_charset_when_json"
] | [] | [
"tests/test_response.py::test_response",
"tests/test_response.py::test_set_response_status_binary",
"tests/test_response.py::test_set_response_status_str_no_reason",
"tests/test_response.py::test_set_response_status_str_generic_reason",
"tests/test_response.py::test_set_response_status_code",
"tests/test_response.py::test_set_response_status_bad",
"tests/test_response.py::test_set_response_status_code_generic_reason",
"tests/test_response.py::test_content_type",
"tests/test_response.py::test_init_content_type_w_charset",
"tests/test_response.py::test_init_adds_default_charset_when_not_json",
"tests/test_response.py::test_init_keeps_specified_charset_when_json",
"tests/test_response.py::test_cookies",
"tests/test_response.py::test_unicode_cookies_error_raised",
"tests/test_response.py::test_unicode_cookies_warning_issued",
"tests/test_response.py::test_http_only_cookie",
"tests/test_response.py::test_headers",
"tests/test_response.py::test_response_copy",
"tests/test_response.py::test_response_copy_content_md5",
"tests/test_response.py::test_HEAD_closes",
"tests/test_response.py::test_HEAD_conditional_response_returns_empty_response",
"tests/test_response.py::test_HEAD_conditional_response_range_empty_response",
"tests/test_response.py::test_conditional_response_if_none_match_false",
"tests/test_response.py::test_conditional_response_if_none_match_true",
"tests/test_response.py::test_conditional_response_if_none_match_weak",
"tests/test_response.py::test_conditional_response_if_modified_since_false",
"tests/test_response.py::test_conditional_response_if_modified_since_true",
"tests/test_response.py::test_conditional_response_range_not_satisfiable_response",
"tests/test_response.py::test_HEAD_conditional_response_range_not_satisfiable_response",
"tests/test_response.py::test_md5_etag",
"tests/test_response.py::test_md5_etag_set_content_md5",
"tests/test_response.py::test_decode_content_defaults_to_identity",
"tests/test_response.py::test_decode_content_with_deflate",
"tests/test_response.py::test_content_length",
"tests/test_response.py::test_app_iter_range",
"tests/test_response.py::test_app_iter_range_inner_method",
"tests/test_response.py::test_content_type_in_headerlist",
"tests/test_response.py::test_str_crlf",
"tests/test_response.py::test_from_file",
"tests/test_response.py::test_from_file2",
"tests/test_response.py::test_from_text_file",
"tests/test_response.py::test_from_file_w_leading_space_in_header",
"tests/test_response.py::test_file_bad_header",
"tests/test_response.py::test_from_file_not_unicode_headers",
"tests/test_response.py::test_set_status",
"tests/test_response.py::test_set_headerlist",
"tests/test_response.py::test_request_uri_no_script_name",
"tests/test_response.py::test_request_uri_https",
"tests/test_response.py::test_app_iter_range_starts_after_iter_end",
"tests/test_response.py::test_resp_write_app_iter_non_list",
"tests/test_response.py::test_response_file_body_writelines",
"tests/test_response.py::test_response_write_non_str",
"tests/test_response.py::test_response_file_body_write_empty_app_iter",
"tests/test_response.py::test_response_file_body_write_empty_body",
"tests/test_response.py::test_response_file_body_close_not_implemented",
"tests/test_response.py::test_response_file_body_repr",
"tests/test_response.py::test_body_get_is_none",
"tests/test_response.py::test_body_get_is_unicode_notverylong",
"tests/test_response.py::test_body_get_is_unicode",
"tests/test_response.py::test_body_set_not_unicode_or_str",
"tests/test_response.py::test_body_set_unicode",
"tests/test_response.py::test_body_set_under_body_doesnt_exist",
"tests/test_response.py::test_body_del",
"tests/test_response.py::test_text_get_no_charset",
"tests/test_response.py::test_unicode_body",
"tests/test_response.py::test_text_get_decode",
"tests/test_response.py::test_text_set_no_charset",
"tests/test_response.py::test_text_set_not_unicode",
"tests/test_response.py::test_text_del",
"tests/test_response.py::test_body_file_del",
"tests/test_response.py::test_write_unicode",
"tests/test_response.py::test_write_unicode_no_charset",
"tests/test_response.py::test_write_text",
"tests/test_response.py::test_app_iter_del",
"tests/test_response.py::test_charset_set_no_content_type_header",
"tests/test_response.py::test_charset_del_no_content_type_header",
"tests/test_response.py::test_content_type_params_get_no_semicolon_in_content_type_header",
"tests/test_response.py::test_content_type_params_get_semicolon_in_content_type_header",
"tests/test_response.py::test_content_type_params_set_value_dict_empty",
"tests/test_response.py::test_content_type_params_set_ok_param_quoting",
"tests/test_response.py::test_set_cookie_overwrite",
"tests/test_response.py::test_set_cookie_value_is_None",
"tests/test_response.py::test_set_cookie_expires_is_None_and_max_age_is_int",
"tests/test_response.py::test_set_cookie_expires_is_None_and_max_age_is_timedelta",
"tests/test_response.py::test_set_cookie_expires_is_not_None_and_max_age_is_None",
"tests/test_response.py::test_set_cookie_expires_is_timedelta_and_max_age_is_None",
"tests/test_response.py::test_delete_cookie",
"tests/test_response.py::test_delete_cookie_with_path",
"tests/test_response.py::test_delete_cookie_with_domain",
"tests/test_response.py::test_unset_cookie_not_existing_and_not_strict",
"tests/test_response.py::test_unset_cookie_not_existing_and_strict",
"tests/test_response.py::test_unset_cookie_key_in_cookies",
"tests/test_response.py::test_merge_cookies_no_set_cookie",
"tests/test_response.py::test_merge_cookies_resp_is_Response",
"tests/test_response.py::test_merge_cookies_resp_is_wsgi_callable",
"tests/test_response.py::test_body_get_body_is_None_len_app_iter_is_zero",
"tests/test_response.py::test_cache_control_get",
"tests/test_response.py::test_location",
"tests/test_response.py::test_request_uri_http",
"tests/test_response.py::test_request_uri_no_script_name2",
"tests/test_response.py::test_cache_control_object_max_age_ten",
"tests/test_response.py::test_cache_control_set_object_error",
"tests/test_response.py::test_cache_expires_set",
"tests/test_response.py::test_status_code_set",
"tests/test_response.py::test_cache_control_set_dict",
"tests/test_response.py::test_cache_control_set_None",
"tests/test_response.py::test_cache_control_set_unicode",
"tests/test_response.py::test_cache_control_set_control_obj_is_not_None",
"tests/test_response.py::test_cache_control_del",
"tests/test_response.py::test_body_file_get",
"tests/test_response.py::test_body_file_write_no_charset",
"tests/test_response.py::test_body_file_write_unicode_encodes",
"tests/test_response.py::test_repr",
"tests/test_response.py::test_cache_expires_set_timedelta",
"tests/test_response.py::test_cache_expires_set_int",
"tests/test_response.py::test_cache_expires_set_None",
"tests/test_response.py::test_cache_expires_set_zero",
"tests/test_response.py::test_encode_content_unknown",
"tests/test_response.py::test_encode_content_identity",
"tests/test_response.py::test_encode_content_gzip_already_gzipped",
"tests/test_response.py::test_encode_content_gzip_notyet_gzipped",
"tests/test_response.py::test_encode_content_gzip_notyet_gzipped_lazy",
"tests/test_response.py::test_encode_content_gzip_buffer_coverage",
"tests/test_response.py::test_decode_content_identity",
"tests/test_response.py::test_decode_content_weird",
"tests/test_response.py::test_decode_content_gzip",
"tests/test_response.py::test__abs_headerlist_location_with_scheme",
"tests/test_response.py::test__abs_headerlist_location_no_scheme",
"tests/test_response.py::test_response_set_body_file1",
"tests/test_response.py::test_response_set_body_file2",
"tests/test_response.py::test_response_json_body",
"tests/test_response.py::test_cache_expires_set_zero_then_nonzero"
] | [] | null | 103 |
|
joblib__joblib-204 | 21cb6f3fd32b11a9b6bc1528b86bbf83fce7bb1f | 2015-04-23 08:08:27 | 21cb6f3fd32b11a9b6bc1528b86bbf83fce7bb1f | lesteve: Forgot to say, but I checked that this fix didn't affect the hash of non datetime-like numpy arrays.
ogrisel: Other than my comment, LGTM. | diff --git a/joblib/hashing.py b/joblib/hashing.py
index 564817c..d3d783a 100644
--- a/joblib/hashing.py
+++ b/joblib/hashing.py
@@ -154,14 +154,21 @@ class NumpyHasher(Hasher):
if isinstance(obj, self.np.ndarray) and not obj.dtype.hasobject:
# Compute a hash of the object:
try:
- self._hash.update(self._getbuffer(obj))
+ # memoryview is not supported for some dtypes,
+ # e.g. datetime64, see
+ # https://github.com/numpy/numpy/issues/4983. The
+ # workaround is to view the array as bytes before
+ # taking the memoryview
+ obj_bytes_view = obj.view(self.np.uint8)
+ self._hash.update(self._getbuffer(obj_bytes_view))
except (TypeError, BufferError, ValueError):
# Cater for non-single-segment arrays: this creates a
# copy, and thus aleviates this issue.
# XXX: There might be a more efficient way of doing this
# Python 3.2's memoryview raise a ValueError instead of a
# TypeError or a BufferError
- self._hash.update(self._getbuffer(obj.flatten()))
+ obj_bytes_view = obj.flatten().view(self.np.uint8)
+ self._hash.update(self._getbuffer(obj_bytes_view))
# We store the class, to be able to distinguish between
# Objects with the same binary content, but different
| Cannot hash datetime64
```
In [59]: joblib.hashing.hash(numpy.zeros(dtype="<m8[s]", shape=(10,)))
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-59-8b9b8a0f034d> in <module>()
----> 1 joblib.hashing.hash(numpy.zeros(dtype="<m8[s]", shape=(10,)))
/export/data/home/gholl/venv/bleeding/lib/python3.4/site-packages/joblib/hashing.py in hash(obj, hash_name, coerce_mmap)
199 else:
200 hasher = Hasher(hash_name=hash_name)
--> 201 return hasher.hash(obj)
/export/data/home/gholl/venv/bleeding/lib/python3.4/site-packages/joblib/hashing.py in hash(self, obj, return_digest)
51 def hash(self, obj, return_digest=True):
52 try:
---> 53 self.dump(obj)
54 except pickle.PicklingError as e:
55 warnings.warn('PicklingError while hashing %r: %r' % (obj, e))
/usr/lib64/python3.4/pickle.py in dump(self, obj)
408 if self.proto >= 4:
409 self.framer.start_framing()
--> 410 self.save(obj)
411 self.write(STOP)
412 self.framer.end_framing()
/export/data/home/gholl/venv/bleeding/lib/python3.4/site-packages/joblib/hashing.py in save(self, obj)
162 # Python 3.2's memoryview raise a ValueError instead of a
163 # TypeError or a BufferError
--> 164 self._hash.update(self._getbuffer(obj.flatten()))
165
166 # We store the class, to be able to distinguish between
ValueError: cannot include dtype 'm' in a buffer
``` | joblib/joblib | diff --git a/joblib/test/test_hashing.py b/joblib/test/test_hashing.py
index 15a5da9..a1f52b1 100644
--- a/joblib/test/test_hashing.py
+++ b/joblib/test/test_hashing.py
@@ -133,6 +133,18 @@ def test_hash_numpy():
yield nose.tools.assert_not_equal, hash(arr1), hash(arr1.T)
+@with_numpy
+def test_numpy_datetime_array():
+ # memoryview is not supported for some dtypes e.g. datetime64
+ # see https://github.com/joblib/joblib/issues/188 for more details
+ dtypes = ['datetime64[s]', 'timedelta64[D]']
+
+ a_hash = hash(np.arange(10))
+ arrays = (np.arange(0, 10, dtype=dtype) for dtype in dtypes)
+ for array in arrays:
+ nose.tools.assert_not_equal(hash(array), a_hash)
+
+
@with_numpy
def test_hash_numpy_noncontiguous():
a = np.asarray(np.arange(6000).reshape((1000, 2, 3)),
| {
"commit_name": "head_commit",
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true,
"llm_score": {
"difficulty_score": 0,
"issue_text_score": 1,
"test_score": 2
},
"num_modified_files": 1
} | 0.8 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "",
"pip_packages": [
"nose",
"coverage",
"numpy>=1.6.1",
"pytest"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.5",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | attrs==22.2.0
certifi==2021.5.30
coverage==6.2
importlib-metadata==4.8.3
iniconfig==1.1.1
-e git+https://github.com/joblib/joblib.git@21cb6f3fd32b11a9b6bc1528b86bbf83fce7bb1f#egg=joblib
nose==1.3.7
numpy==1.19.5
packaging==21.3
pluggy==1.0.0
py==1.11.0
pyparsing==3.1.4
pytest==7.0.1
tomli==1.2.3
typing_extensions==4.1.1
zipp==3.6.0
| name: joblib
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- pip=21.2.2=py36h06a4308_0
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_0
- setuptools=58.0.4=py36h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- attrs==22.2.0
- coverage==6.2
- importlib-metadata==4.8.3
- iniconfig==1.1.1
- nose==1.3.7
- numpy==1.19.5
- packaging==21.3
- pluggy==1.0.0
- py==1.11.0
- pyparsing==3.1.4
- pytest==7.0.1
- tomli==1.2.3
- typing-extensions==4.1.1
- zipp==3.6.0
prefix: /opt/conda/envs/joblib
| [
"joblib/test/test_hashing.py::test_numpy_datetime_array"
] | [] | [
"joblib/test/test_hashing.py::test_memory_setup_func",
"joblib/test/test_hashing.py::test_memory_teardown_func",
"joblib/test/test_hashing.py::test_hash_methods",
"joblib/test/test_hashing.py::test_hash_numpy_noncontiguous",
"joblib/test/test_hashing.py::test_hash_numpy_performance",
"joblib/test/test_hashing.py::test_bound_methods_hash",
"joblib/test/test_hashing.py::test_bound_cached_methods_hash",
"joblib/test/test_hashing.py::test_hash_object_dtype",
"joblib/test/test_hashing.py::test_numpy_scalar",
"joblib/test/test_hashing.py::test_dict_hash",
"joblib/test/test_hashing.py::test_set_hash"
] | [] | BSD 3-Clause "New" or "Revised" License | 104 |
softlayer__softlayer-python-531 | 05ca114d4cf35597182051d5acb4db74fc333cfc | 2015-04-23 15:10:47 | 1195b2020ef6efc40462d59eb079f26e5f39a6d8 | diff --git a/SoftLayer/CLI/config/setup.py b/SoftLayer/CLI/config/setup.py
index 30ba070a..f9b37d55 100644
--- a/SoftLayer/CLI/config/setup.py
+++ b/SoftLayer/CLI/config/setup.py
@@ -13,14 +13,12 @@
import click
-def get_api_key(client, username, secret, endpoint_url=None):
+def get_api_key(client, username, secret):
"""Attempts API-Key and password auth to get an API key.
This will also generate an API key if one doesn't exist
"""
- client.endpoint_url = endpoint_url
- client.auth = None
# Try to use a client with username/api key
if len(secret) == 64:
try:
@@ -50,8 +48,8 @@ def cli(env):
username, secret, endpoint_url, timeout = get_user_input(env)
- api_key = get_api_key(env.client, username, secret,
- endpoint_url=endpoint_url)
+ env.client.transport.transport.endpoint_url = endpoint_url
+ api_key = get_api_key(env.client, username, secret)
path = '~/.softlayer'
if env.config_file:
@@ -79,6 +77,7 @@ def cli(env):
parsed_config.set('softlayer', 'username', username)
parsed_config.set('softlayer', 'api_key', api_key)
parsed_config.set('softlayer', 'endpoint_url', endpoint_url)
+ parsed_config.set('softlayer', 'timeout', timeout)
config_fd = os.fdopen(os.open(config_path,
(os.O_WRONLY | os.O_CREAT | os.O_TRUNC),
@@ -96,47 +95,28 @@ def get_user_input(env):
"""Ask for username, secret (api_key or password) and endpoint_url."""
defaults = config.get_settings_from_client(env.client)
- timeout = defaults['timeout']
# Ask for username
- for _ in range(3):
- username = (env.input('Username [%s]: ' % defaults['username']) or
- defaults['username'])
- if username:
- break
- else:
- raise exceptions.CLIAbort('Aborted after 3 attempts')
+ username = env.input('Username', default=defaults['username'])
# Ask for 'secret' which can be api_key or their password
- for _ in range(3):
- secret = (env.getpass('API Key or Password [%s]: '
- % defaults['api_key']) or
- defaults['api_key'])
- if secret:
- break
- else:
- raise exceptions.CLIAbort('Aborted after 3 attempts')
+ secret = env.getpass('API Key or Password', default=defaults['api_key'])
# Ask for which endpoint they want to use
- for _ in range(3):
- endpoint_type = env.input(
- 'Endpoint (public|private|custom): ')
- endpoint_type = endpoint_type.lower()
- if not endpoint_type:
- endpoint_url = SoftLayer.API_PUBLIC_ENDPOINT
- break
- if endpoint_type == 'public':
- endpoint_url = SoftLayer.API_PUBLIC_ENDPOINT
- break
- elif endpoint_type == 'private':
- endpoint_url = SoftLayer.API_PRIVATE_ENDPOINT
- break
- elif endpoint_type == 'custom':
- endpoint_url = env.input(
- 'Endpoint URL [%s]: ' % defaults['endpoint_url']
- ) or defaults['endpoint_url']
- break
- else:
- raise exceptions.CLIAbort('Aborted after 3 attempts')
+ endpoint_type = env.input(
+ 'Endpoint (public|private|custom)', default='public')
+ endpoint_type = endpoint_type.lower()
+ if endpoint_type is None:
+ endpoint_url = SoftLayer.API_PUBLIC_ENDPOINT
+ if endpoint_type == 'public':
+ endpoint_url = SoftLayer.API_PUBLIC_ENDPOINT
+ elif endpoint_type == 'private':
+ endpoint_url = SoftLayer.API_PRIVATE_ENDPOINT
+ elif endpoint_type == 'custom':
+ endpoint_url = env.input('Endpoint URL',
+ default=defaults['endpoint_url'])
+
+ # Ask for timeout
+ timeout = env.input('Timeout', default=defaults['timeout'] or 0)
return username, secret, endpoint_url, timeout
diff --git a/SoftLayer/CLI/core.py b/SoftLayer/CLI/core.py
index d2278394..a6839522 100644
--- a/SoftLayer/CLI/core.py
+++ b/SoftLayer/CLI/core.py
@@ -138,17 +138,19 @@ def cli(ctx,
if env.client is None:
# Environment can be passed in explicitly. This is used for testing
if fixtures:
- transport = SoftLayer.FixtureTransport()
+ client = SoftLayer.BaseClient(
+ transport=SoftLayer.FixtureTransport(),
+ auth=None,
+ )
else:
# Create SL Client
- transport = SoftLayer.XmlRpcTransport()
-
- wrapped_transport = SoftLayer.TimingTransport(transport)
- env.client = SoftLayer.create_client_from_env(
- proxy=proxy,
- config_file=config,
- transport=wrapped_transport,
- )
+ client = SoftLayer.create_client_from_env(
+ proxy=proxy,
+ config_file=config,
+ )
+
+ client.transport = SoftLayer.TimingTransport(client.transport)
+ env.client = client
@cli.resultcallback()
diff --git a/SoftLayer/CLI/environment.py b/SoftLayer/CLI/environment.py
index b67b8c24..f5800590 100644
--- a/SoftLayer/CLI/environment.py
+++ b/SoftLayer/CLI/environment.py
@@ -44,13 +44,13 @@ def fmt(self, output):
"""Format output based on current the environment format."""
return formatting.format_output(output, fmt=self.format)
- def input(self, prompt):
+ def input(self, prompt, default=None):
"""Provide a command prompt."""
- return click.prompt(prompt)
+ return click.prompt(prompt, default=default)
- def getpass(self, prompt):
+ def getpass(self, prompt, default=None):
"""Provide a password prompt."""
- return click.prompt(prompt, hide_input=True)
+ return click.prompt(prompt, hide_input=True, default=default)
# Command loading methods
def list_commands(self, *path):
diff --git a/SoftLayer/CLI/formatting.py b/SoftLayer/CLI/formatting.py
index 1f7e495a..f1554af0 100644
--- a/SoftLayer/CLI/formatting.py
+++ b/SoftLayer/CLI/formatting.py
@@ -160,27 +160,6 @@ def transaction_status(transaction):
transaction['transactionStatus'].get('friendlyName'))
-def valid_response(prompt, *valid):
- """Prompt user for input.
-
- Will display a prompt for a command-line user. If the input is in the
- valid given valid list then it will return True. Otherwise, it will
- return False. If no input is received from the user, None is returned
- instead.
-
- :param string prompt: string prompt to give to the user
- :param string \\*valid: valid responses
- """
- ans = click.prompt(prompt).lower()
-
- if ans in valid:
- return True
- elif ans == '':
- return None
-
- return False
-
-
def confirm(prompt_str, default=False):
"""Show a confirmation prompt to a command-line user.
@@ -188,16 +167,17 @@ def confirm(prompt_str, default=False):
:param bool default: Default value to True or False
"""
if default:
+ default_str = 'y'
prompt = '%s [Y/n]' % prompt_str
else:
+ default_str = 'n'
prompt = '%s [y/N]' % prompt_str
- response = valid_response(prompt, 'y', 'yes', 'yeah', 'yup', 'yolo')
-
- if response is None:
- return default
+ ans = click.prompt(prompt, default=default_str, show_default=False)
+ if ans.lower() in ('y', 'yes', 'yeah', 'yup', 'yolo'):
+ return True
- return response
+ return False
def no_going_back(confirmation):
@@ -209,10 +189,14 @@ def no_going_back(confirmation):
if not confirmation:
confirmation = 'yes'
- return valid_response(
- 'This action cannot be undone! '
- 'Type "%s" or press Enter to abort' % confirmation,
- str(confirmation))
+ prompt = ('This action cannot be undone! Type "%s" or press Enter '
+ 'to abort' % confirmation)
+
+ ans = click.confirm(prompt, default='', show_default=False).lower()
+ if ans == str(confirmation):
+ return True
+
+ return False
class SequentialOutput(list):
diff --git a/SoftLayer/config.py b/SoftLayer/config.py
index 8c679e6c..120cadab 100644
--- a/SoftLayer/config.py
+++ b/SoftLayer/config.py
@@ -16,9 +16,12 @@ def get_client_settings_args(**kwargs):
:param \\*\\*kwargs: Arguments that are passed into the client instance
"""
+ timeout = kwargs.get('timeout')
+ if timeout is not None:
+ timeout = float(timeout)
return {
'endpoint_url': kwargs.get('endpoint_url'),
- 'timeout': float(kwargs.get('timeout') or 0),
+ 'timeout': timeout,
'proxy': kwargs.get('proxy'),
'username': kwargs.get('username'),
'api_key': kwargs.get('api_key'),
| [Bug] slcli config setup doesnt accept default value when one is already present
When you already have a `.softlayer` configured, and you `slcli config setup`, it loads previous values from `.softlayer` and shows them to you, but pressing enter at the prompt doesnt keep the previous value and move on to the next setting, it sits there and forces you to retype it and it shouldnt do that.
It also doesnt prompt for a timeout value, it should prompt and accept no value provided as meaning dont set and use default.
Using 4.0.0 | softlayer/softlayer-python | diff --git a/SoftLayer/tests/CLI/environment_tests.py b/SoftLayer/tests/CLI/environment_tests.py
index e1ebf0e2..b3826df8 100644
--- a/SoftLayer/tests/CLI/environment_tests.py
+++ b/SoftLayer/tests/CLI/environment_tests.py
@@ -43,13 +43,13 @@ def test_get_command(self):
@mock.patch('click.prompt')
def test_input(self, prompt_mock):
r = self.env.input('input')
- prompt_mock.assert_called_with('input')
+ prompt_mock.assert_called_with('input', default=None)
self.assertEqual(prompt_mock(), r)
@mock.patch('click.prompt')
def test_getpass(self, prompt_mock):
r = self.env.getpass('input')
- prompt_mock.assert_called_with('input', hide_input=True)
+ prompt_mock.assert_called_with('input', default=None, hide_input=True)
self.assertEqual(prompt_mock(), r)
def test_resolve_alias(self):
diff --git a/SoftLayer/tests/CLI/helper_tests.py b/SoftLayer/tests/CLI/helper_tests.py
index 80ae0bd6..d75e8e2b 100644
--- a/SoftLayer/tests/CLI/helper_tests.py
+++ b/SoftLayer/tests/CLI/helper_tests.py
@@ -41,50 +41,21 @@ def test_fail(self):
class PromptTests(testing.TestCase):
- @mock.patch('click.prompt')
- def test_invalid_response(self, prompt_mock):
- prompt_mock.return_value = 'y'
- result = formatting.valid_response('test', 'n')
- prompt_mock.assert_called_with('test')
- self.assertFalse(result)
-
- prompt_mock.return_value = 'wakakwakwaka'
- result = formatting.valid_response('test', 'n')
- prompt_mock.assert_called_with('test')
- self.assertFalse(result)
-
- prompt_mock.return_value = ''
- result = formatting.valid_response('test', 'n')
- prompt_mock.assert_called_with('test')
- self.assertEqual(result, None)
-
- @mock.patch('click.prompt')
- def test_valid_response(self, prompt_mock):
- prompt_mock.return_value = 'n'
- result = formatting.valid_response('test', 'n')
- prompt_mock.assert_called_with('test')
- self.assertTrue(result)
-
- prompt_mock.return_value = 'N'
- result = formatting.valid_response('test', 'n')
- prompt_mock.assert_called_with('test')
- self.assertTrue(result)
-
- @mock.patch('click.prompt')
- def test_do_or_die(self, prompt_mock):
+ @mock.patch('click.confirm')
+ def test_do_or_die(self, confirm_mock):
confirmed = '37347373737'
- prompt_mock.return_value = confirmed
+ confirm_mock.return_value = confirmed
result = formatting.no_going_back(confirmed)
self.assertTrue(result)
# no_going_back should cast int's to str()
confirmed = '4712309182309'
- prompt_mock.return_value = confirmed
+ confirm_mock.return_value = confirmed
result = formatting.no_going_back(int(confirmed))
self.assertTrue(result)
confirmed = None
- prompt_mock.return_value = ''
+ confirm_mock.return_value = ''
result = formatting.no_going_back(confirmed)
self.assertFalse(result)
@@ -98,9 +69,19 @@ def test_confirmation(self, prompt_mock):
res = formatting.confirm('Confirm?', default=False)
self.assertFalse(res)
- prompt_mock.return_value = ''
+ prompt_mock.return_value = 'Y'
res = formatting.confirm('Confirm?', default=True)
self.assertTrue(res)
+ prompt_mock.assert_called_with('Confirm? [Y/n]',
+ default='y',
+ show_default=False)
+
+ prompt_mock.return_value = 'N'
+ res = formatting.confirm('Confirm?', default=False)
+ self.assertFalse(res)
+ prompt_mock.assert_called_with('Confirm? [y/N]',
+ default='n',
+ show_default=False)
class FormattedItemTests(testing.TestCase):
diff --git a/SoftLayer/tests/CLI/modules/config_tests.py b/SoftLayer/tests/CLI/modules/config_tests.py
index 630cfa4c..fe835799 100644
--- a/SoftLayer/tests/CLI/modules/config_tests.py
+++ b/SoftLayer/tests/CLI/modules/config_tests.py
@@ -48,7 +48,7 @@ def test_setup(self, input, getpass, confirm_mock):
with tempfile.NamedTemporaryFile() as config_file:
confirm_mock.return_value = True
getpass.return_value = 'A' * 64
- input.side_effect = ['user', 'public']
+ input.side_effect = ['user', 'public', 0]
result = self.run_command(['--config=%s' % config_file.name,
'config', 'setup'])
@@ -71,7 +71,7 @@ def test_setup_cancel(self, input, getpass, confirm_mock):
with tempfile.NamedTemporaryFile() as config_file:
confirm_mock.return_value = False
getpass.return_value = 'A' * 64
- input.side_effect = ['user', 'public']
+ input.side_effect = ['user', 'public', 0]
result = self.run_command(['--config=%s' % config_file.name,
'config', 'setup'])
@@ -83,7 +83,7 @@ def test_setup_cancel(self, input, getpass, confirm_mock):
@mock.patch('SoftLayer.CLI.environment.Environment.input')
def test_get_user_input_private(self, input, getpass):
getpass.return_value = 'A' * 64
- input.side_effect = ['user', 'private']
+ input.side_effect = ['user', 'private', 0]
username, secret, endpoint_url, timeout = (
config.get_user_input(self.env))
@@ -96,7 +96,7 @@ def test_get_user_input_private(self, input, getpass):
@mock.patch('SoftLayer.CLI.environment.Environment.input')
def test_get_user_input_custom(self, input, getpass):
getpass.return_value = 'A' * 64
- input.side_effect = ['user', 'custom', 'custom-endpoint']
+ input.side_effect = ['user', 'custom', 'custom-endpoint', 0]
_, _, endpoint_url, _ = config.get_user_input(self.env)
@@ -106,7 +106,7 @@ def test_get_user_input_custom(self, input, getpass):
@mock.patch('SoftLayer.CLI.environment.Environment.input')
def test_get_user_input_default(self, input, getpass):
self.env.getpass.return_value = 'A' * 64
- self.env.input.side_effect = ['user', '']
+ self.env.input.side_effect = ['user', 'public', 0]
_, _, endpoint_url, _ = config.get_user_input(self.env)
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 1,
"issue_text_score": 0,
"test_score": 2
},
"num_modified_files": 5
} | 4.0 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[dev]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.6",
"reqs_path": [
"tools/test-requirements.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | alabaster==0.7.13
attrs==22.2.0
Babel==2.11.0
certifi==2021.5.30
charset-normalizer==2.0.12
click==8.0.4
coverage==6.2
distlib==0.3.9
docutils==0.18.1
filelock==3.4.1
fixtures==4.0.1
idna==3.10
imagesize==1.4.1
importlib-metadata==4.8.3
importlib-resources==5.4.0
iniconfig==1.1.1
Jinja2==3.0.3
MarkupSafe==2.0.1
mock==5.2.0
nose==1.3.7
packaging==21.3
pbr==6.1.1
platformdirs==2.4.0
pluggy==1.0.0
prettytable==2.5.0
py==1.11.0
Pygments==2.14.0
pyparsing==3.1.4
pytest==7.0.1
pytz==2025.2
requests==2.27.1
six==1.17.0
snowballstemmer==2.2.0
-e git+https://github.com/softlayer/softlayer-python.git@05ca114d4cf35597182051d5acb4db74fc333cfc#egg=SoftLayer
Sphinx==5.3.0
sphinxcontrib-applehelp==1.0.2
sphinxcontrib-devhelp==1.0.2
sphinxcontrib-htmlhelp==2.0.0
sphinxcontrib-jsmath==1.0.1
sphinxcontrib-qthelp==1.0.3
sphinxcontrib-serializinghtml==1.1.5
testtools==2.6.0
toml==0.10.2
tomli==1.2.3
tox==3.28.0
typing_extensions==4.1.1
urllib3==1.26.20
virtualenv==20.17.1
wcwidth==0.2.13
zipp==3.6.0
| name: softlayer-python
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- pip=21.2.2=py36h06a4308_0
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_0
- setuptools=58.0.4=py36h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- alabaster==0.7.13
- attrs==22.2.0
- babel==2.11.0
- charset-normalizer==2.0.12
- click==8.0.4
- coverage==6.2
- distlib==0.3.9
- docutils==0.18.1
- filelock==3.4.1
- fixtures==4.0.1
- idna==3.10
- imagesize==1.4.1
- importlib-metadata==4.8.3
- importlib-resources==5.4.0
- iniconfig==1.1.1
- jinja2==3.0.3
- markupsafe==2.0.1
- mock==5.2.0
- nose==1.3.7
- packaging==21.3
- pbr==6.1.1
- platformdirs==2.4.0
- pluggy==1.0.0
- prettytable==2.5.0
- py==1.11.0
- pygments==2.14.0
- pyparsing==3.1.4
- pytest==7.0.1
- pytz==2025.2
- requests==2.27.1
- six==1.17.0
- snowballstemmer==2.2.0
- sphinx==5.3.0
- sphinxcontrib-applehelp==1.0.2
- sphinxcontrib-devhelp==1.0.2
- sphinxcontrib-htmlhelp==2.0.0
- sphinxcontrib-jsmath==1.0.1
- sphinxcontrib-qthelp==1.0.3
- sphinxcontrib-serializinghtml==1.1.5
- testtools==2.6.0
- toml==0.10.2
- tomli==1.2.3
- tox==3.28.0
- typing-extensions==4.1.1
- urllib3==1.26.20
- virtualenv==20.17.1
- wcwidth==0.2.13
- zipp==3.6.0
prefix: /opt/conda/envs/softlayer-python
| [
"SoftLayer/tests/CLI/environment_tests.py::EnvironmentTests::test_getpass",
"SoftLayer/tests/CLI/environment_tests.py::EnvironmentTests::test_input",
"SoftLayer/tests/CLI/helper_tests.py::PromptTests::test_confirmation",
"SoftLayer/tests/CLI/helper_tests.py::PromptTests::test_do_or_die"
] | [] | [
"SoftLayer/tests/CLI/environment_tests.py::EnvironmentTests::test_get_command",
"SoftLayer/tests/CLI/environment_tests.py::EnvironmentTests::test_get_command_invalid",
"SoftLayer/tests/CLI/environment_tests.py::EnvironmentTests::test_list_commands",
"SoftLayer/tests/CLI/environment_tests.py::EnvironmentTests::test_resolve_alias",
"SoftLayer/tests/CLI/helper_tests.py::CLIJSONEncoderTest::test_default",
"SoftLayer/tests/CLI/helper_tests.py::CLIJSONEncoderTest::test_fail",
"SoftLayer/tests/CLI/helper_tests.py::FormattedItemTests::test_blank",
"SoftLayer/tests/CLI/helper_tests.py::FormattedItemTests::test_gb",
"SoftLayer/tests/CLI/helper_tests.py::FormattedItemTests::test_init",
"SoftLayer/tests/CLI/helper_tests.py::FormattedItemTests::test_mb_to_gb",
"SoftLayer/tests/CLI/helper_tests.py::FormattedListTests::test_init",
"SoftLayer/tests/CLI/helper_tests.py::FormattedListTests::test_str",
"SoftLayer/tests/CLI/helper_tests.py::FormattedListTests::test_to_python",
"SoftLayer/tests/CLI/helper_tests.py::FormattedTxnTests::test_active_txn",
"SoftLayer/tests/CLI/helper_tests.py::FormattedTxnTests::test_active_txn_empty",
"SoftLayer/tests/CLI/helper_tests.py::FormattedTxnTests::test_active_txn_missing",
"SoftLayer/tests/CLI/helper_tests.py::FormattedTxnTests::test_transaction_status",
"SoftLayer/tests/CLI/helper_tests.py::FormattedTxnTests::test_transaction_status_missing",
"SoftLayer/tests/CLI/helper_tests.py::CLIAbortTests::test_init",
"SoftLayer/tests/CLI/helper_tests.py::ResolveIdTests::test_resolve_id_multiple",
"SoftLayer/tests/CLI/helper_tests.py::ResolveIdTests::test_resolve_id_none",
"SoftLayer/tests/CLI/helper_tests.py::ResolveIdTests::test_resolve_id_one",
"SoftLayer/tests/CLI/helper_tests.py::TestFormatOutput::test_format_output_formatted_item",
"SoftLayer/tests/CLI/helper_tests.py::TestFormatOutput::test_format_output_json",
"SoftLayer/tests/CLI/helper_tests.py::TestFormatOutput::test_format_output_json_keyvaluetable",
"SoftLayer/tests/CLI/helper_tests.py::TestFormatOutput::test_format_output_list",
"SoftLayer/tests/CLI/helper_tests.py::TestFormatOutput::test_format_output_python",
"SoftLayer/tests/CLI/helper_tests.py::TestFormatOutput::test_format_output_python_keyvaluetable",
"SoftLayer/tests/CLI/helper_tests.py::TestFormatOutput::test_format_output_raw",
"SoftLayer/tests/CLI/helper_tests.py::TestFormatOutput::test_format_output_string",
"SoftLayer/tests/CLI/helper_tests.py::TestFormatOutput::test_format_output_table",
"SoftLayer/tests/CLI/helper_tests.py::TestFormatOutput::test_sequentialoutput",
"SoftLayer/tests/CLI/helper_tests.py::TestFormatOutput::test_unknown",
"SoftLayer/tests/CLI/helper_tests.py::TestTemplateArgs::test_no_template_option",
"SoftLayer/tests/CLI/helper_tests.py::TestTemplateArgs::test_template_options",
"SoftLayer/tests/CLI/helper_tests.py::TestExportToTemplate::test_export_to_template",
"SoftLayer/tests/CLI/modules/config_tests.py::TestHelpShow::test_show",
"SoftLayer/tests/CLI/modules/config_tests.py::TestHelpSetup::test_get_user_input_custom",
"SoftLayer/tests/CLI/modules/config_tests.py::TestHelpSetup::test_get_user_input_default",
"SoftLayer/tests/CLI/modules/config_tests.py::TestHelpSetup::test_get_user_input_private",
"SoftLayer/tests/CLI/modules/config_tests.py::TestHelpSetup::test_setup",
"SoftLayer/tests/CLI/modules/config_tests.py::TestHelpSetup::test_setup_cancel"
] | [] | MIT License | 105 |
|
mne-tools__mne-python-2018 | 0bf2f433842c26436fc8f1ee168dfa49b07c45c3 | 2015-04-24 12:26:56 | edceb8f38349d6dc0cade1c9f8384cc0707ce3e8 | diff --git a/mne/report.py b/mne/report.py
index a8e0d21a6..892aab074 100644
--- a/mne/report.py
+++ b/mne/report.py
@@ -554,7 +554,12 @@ image_template = Template(u"""
{{if comment is not None}}
<br><br>
<div style="text-align:center;">
- {{comment}}
+ <style>
+ p.test {word-wrap: break-word;}
+ </style>
+ <p class="test">
+ {{comment}}
+ </p>
</div>
{{endif}}
{{else}}
@@ -698,10 +703,16 @@ class Report(object):
if not isinstance(captions, (list, tuple)):
captions = [captions]
if not isinstance(comments, (list, tuple)):
- comments = [comments]
- if not len(items) == len(captions):
- raise ValueError('Captions and report items must have the same'
- ' length.')
+ if comments is None:
+ comments = [comments] * len(captions)
+ else:
+ comments = [comments]
+ if len(comments) != len(items):
+ raise ValueError('Comments and report items must have the same '
+ 'length or comments should be None.')
+ elif len(captions) != len(items):
+ raise ValueError('Captions and report items must have the same '
+ 'length.')
# Book-keeping of section names
if section not in self.sections:
| BUG: Adding more than one figure to Report is broken
If a call to `add_figs_to_section` is made with a list of figures, only the first one is added.
In this example, only the first figure appears on the report.
```Python
import numpy as np
import matplotlib.pyplot as plt
from mne.report import Report
r = Report('test')
fig1 = plt.figure()
plt.plot([1, 2], [1, 1])
fig2 = plt.figure()
plt.plot([1, 2], [2, 2])
r.add_figs_to_section([fig1, fig2], section='ts', captions=['fig1', 'fig2'])
r.save('test.html', overwrite=True)
``` | mne-tools/mne-python | diff --git a/mne/tests/test_report.py b/mne/tests/test_report.py
index 500f408b4..dd0d02ffe 100644
--- a/mne/tests/test_report.py
+++ b/mne/tests/test_report.py
@@ -212,4 +212,21 @@ def test_add_htmls_to_section():
assert_equal(html, html_compare)
+def test_validate_input():
+ report = Report()
+ items = ['a', 'b', 'c']
+ captions = ['Letter A', 'Letter B', 'Letter C']
+ section = 'ABCs'
+ comments = ['First letter of the alphabet.',
+ 'Second letter of the alphabet',
+ 'Third letter of the alphabet']
+ assert_raises(ValueError, report._validate_input, items, captions[:-1],
+ section, comments=None)
+ assert_raises(ValueError, report._validate_input, items, captions, section,
+ comments=comments[:-1])
+ values = report._validate_input(items, captions, section, comments=None)
+ items_new, captions_new, comments_new = values
+ assert_equal(len(comments_new), len(items))
+
+
run_tests_if_main()
| {
"commit_name": "head_commit",
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true,
"llm_score": {
"difficulty_score": 1,
"issue_text_score": 1,
"test_score": 3
},
"num_modified_files": 1
} | 0.8 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[dev]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"numpy>=1.16.0",
"pandas>=1.0.0",
"scikit-learn",
"h5py",
"pysurfer",
"nose",
"nose-timer",
"pytest"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.7",
"reqs_path": [
"requirements/base.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | apptools==5.2.1
certifi @ file:///croot/certifi_1671487769961/work/certifi
configobj==5.0.9
cycler==0.11.0
envisage==7.0.3
exceptiongroup==1.2.2
fonttools==4.38.0
h5py==3.8.0
importlib-metadata==6.7.0
importlib-resources==5.12.0
iniconfig==2.0.0
joblib==1.3.2
kiwisolver==1.4.5
matplotlib==3.5.3
mayavi==4.8.1
-e git+https://github.com/mne-tools/mne-python.git@0bf2f433842c26436fc8f1ee168dfa49b07c45c3#egg=mne
nibabel==4.0.2
nose==1.3.7
nose-timer==1.0.1
numpy==1.21.6
packaging==24.0
pandas==1.3.5
Pillow==9.5.0
pluggy==1.2.0
pyface==8.0.0
Pygments==2.17.2
pyparsing==3.1.4
pysurfer==0.11.2
pytest==7.4.4
python-dateutil==2.9.0.post0
pytz==2025.2
scikit-learn==1.0.2
scipy==1.7.3
six==1.17.0
threadpoolctl==3.1.0
tomli==2.0.1
traits==6.4.3
traitsui==8.0.0
typing_extensions==4.7.1
vtk==9.3.1
zipp==3.15.0
| name: mne-python
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2022.12.7=py37h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- pip=22.3.1=py37h06a4308_0
- python=3.7.16=h7a1cb2a_0
- readline=8.2=h5eee18b_0
- setuptools=65.6.3=py37h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- wheel=0.38.4=py37h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- apptools==5.2.1
- configobj==5.0.9
- cycler==0.11.0
- envisage==7.0.3
- exceptiongroup==1.2.2
- fonttools==4.38.0
- h5py==3.8.0
- importlib-metadata==6.7.0
- importlib-resources==5.12.0
- iniconfig==2.0.0
- joblib==1.3.2
- kiwisolver==1.4.5
- matplotlib==3.5.3
- mayavi==4.8.1
- nibabel==4.0.2
- nose==1.3.7
- nose-timer==1.0.1
- numpy==1.21.6
- packaging==24.0
- pandas==1.3.5
- pillow==9.5.0
- pluggy==1.2.0
- pyface==8.0.0
- pygments==2.17.2
- pyparsing==3.1.4
- pysurfer==0.11.2
- pytest==7.4.4
- python-dateutil==2.9.0.post0
- pytz==2025.2
- scikit-learn==1.0.2
- scipy==1.7.3
- six==1.17.0
- threadpoolctl==3.1.0
- tomli==2.0.1
- traits==6.4.3
- traitsui==8.0.0
- typing-extensions==4.7.1
- vtk==9.3.1
- zipp==3.15.0
prefix: /opt/conda/envs/mne-python
| [
"mne/tests/test_report.py::test_validate_input"
] | [] | [] | [] | BSD 3-Clause "New" or "Revised" License | 106 |
|
sympy__sympy-9346 | 8c8594a311b22602b3c6f00f69c28c57012569f1 | 2015-04-24 12:45:51 | 0241b35cae5f2adc04dc37b25f7dc9c5f00bd746 | diff --git a/sympy/core/numbers.py b/sympy/core/numbers.py
index 13bbc6ab06..3b65841c01 100644
--- a/sympy/core/numbers.py
+++ b/sympy/core/numbers.py
@@ -719,7 +719,17 @@ def __new__(cls, num, prec=None):
elif isinstance(num, str):
_mpf_ = mlib.from_str(num, prec, rnd)
elif isinstance(num, decimal.Decimal):
- _mpf_ = mlib.from_str(str(num), prec, rnd)
+ if num.is_finite():
+ _mpf_ = mlib.from_str(str(num), prec, rnd)
+ elif num.is_nan():
+ _mpf_ = _mpf_nan
+ elif num.is_infinite():
+ if num > 0:
+ _mpf_ = _mpf_inf
+ else:
+ _mpf_ = _mpf_ninf
+ else:
+ raise ValueError("unexpected decimal value %s" % str(num))
elif isinstance(num, Rational):
_mpf_ = mlib.from_rational(num.p, num.q, prec, rnd)
elif isinstance(num, tuple) and len(num) in (3, 4):
diff --git a/sympy/functions/elementary/exponential.py b/sympy/functions/elementary/exponential.py
index c11f07e62e..01559e77d8 100644
--- a/sympy/functions/elementary/exponential.py
+++ b/sympy/functions/elementary/exponential.py
@@ -676,7 +676,13 @@ def _eval_is_finite(self):
return arg.is_finite
def _eval_is_positive(self):
- return (self.args[0] - 1).is_positive
+ arg = self.args[0]
+ if arg.is_positive:
+ if arg.is_infinite:
+ return True
+ if arg.is_zero:
+ return False
+ return (arg - 1).is_positive
def _eval_is_zero(self):
return (self.args[0] - 1).is_zero
diff --git a/sympy/functions/elementary/integers.py b/sympy/functions/elementary/integers.py
index 47464f9f91..e1062e0fa4 100644
--- a/sympy/functions/elementary/integers.py
+++ b/sympy/functions/elementary/integers.py
@@ -86,32 +86,25 @@ class floor(RoundFunction):
value not greater than its argument. However this implementation
generalizes floor to complex numbers.
- Examples
- ========
-
- >>> from sympy import floor, E, I, Float, Rational
- >>> floor(17)
- 17
- >>> floor(Rational(23, 10))
- 2
- >>> floor(2*E)
- 5
- >>> floor(-Float(0.567))
- -1
- >>> floor(-I/2)
- -I
+ More information can be found in "Concrete mathematics" by Graham,
+ pp. 87 or visit http://mathworld.wolfram.com/FloorFunction.html.
+
+ >>> from sympy import floor, E, I, Float, Rational
+ >>> floor(17)
+ 17
+ >>> floor(Rational(23, 10))
+ 2
+ >>> floor(2*E)
+ 5
+ >>> floor(-Float(0.567))
+ -1
+ >>> floor(-I/2)
+ -I
See Also
========
- sympy.functions.elementary.integers.ceiling
-
- References
- ==========
-
- .. [1] "Concrete mathematics" by Graham, pp. 87
- .. [2] http://mathworld.wolfram.com/FloorFunction.html
-
+ ceiling
"""
_dir = -1
@@ -157,32 +150,25 @@ class ceiling(RoundFunction):
value not less than its argument. Ceiling function is generalized
in this implementation to complex numbers.
- Examples
- ========
-
- >>> from sympy import ceiling, E, I, Float, Rational
- >>> ceiling(17)
- 17
- >>> ceiling(Rational(23, 10))
- 3
- >>> ceiling(2*E)
- 6
- >>> ceiling(-Float(0.567))
- 0
- >>> ceiling(I/2)
- I
+ More information can be found in "Concrete mathematics" by Graham,
+ pp. 87 or visit http://mathworld.wolfram.com/CeilingFunction.html.
+
+ >>> from sympy import ceiling, E, I, Float, Rational
+ >>> ceiling(17)
+ 17
+ >>> ceiling(Rational(23, 10))
+ 3
+ >>> ceiling(2*E)
+ 6
+ >>> ceiling(-Float(0.567))
+ 0
+ >>> ceiling(I/2)
+ I
See Also
========
- sympy.functions.elementary.integers.floor
-
- References
- ==========
-
- .. [1] "Concrete mathematics" by Graham, pp. 87
- .. [2] http://mathworld.wolfram.com/CeilingFunction.html
-
+ floor
"""
_dir = 1
| proper conversion from decimal to float for nan and +/- inf
Conversion from decimal.Decimal to sympy.Float should work for nan and +/- infinity. Currently, conversion throws an exception for all of them.
import decimal
import sympy
x = sympy.symbols('x')
c_finite = decimal.Decimal('1.34551')
c_nan = decimal.Decimal('nan')
c_inf = decimal.Decimal('Infinity')
c_neg_inf = decimal.Decimal('-Infinity')
c_finite*x
c_nan*x # ValueError: invalid literal for int() with base 10: 'nan'
c_inf*x # ValueError: invalid literal for int() with base 10: 'infinity'
c_neg_inf*x # ValueError: invalid literal for int() with base 10: '-infinity'
This issue is being created coincident with a pull request to fix this, per development workflow guidelines. | sympy/sympy | diff --git a/sympy/core/tests/test_numbers.py b/sympy/core/tests/test_numbers.py
index caf229226c..c5f5537266 100644
--- a/sympy/core/tests/test_numbers.py
+++ b/sympy/core/tests/test_numbers.py
@@ -453,6 +453,9 @@ def teq(a):
assert Float(S.One) == Float(1.0)
assert Float(decimal.Decimal('0.1'), 3) == Float('.1', 3)
+ assert Float(decimal.Decimal('nan')) == S.NaN
+ assert Float(decimal.Decimal('Infinity')) == S.Infinity
+ assert Float(decimal.Decimal('-Infinity')) == S.NegativeInfinity
assert '{0:.3f}'.format(Float(4.236622)) == '4.237'
assert '{0:.35f}'.format(Float(pi.n(40), 40)) == '3.14159265358979323846264338327950288'
diff --git a/sympy/functions/elementary/tests/test_exponential.py b/sympy/functions/elementary/tests/test_exponential.py
index 708937531d..a2057365d8 100644
--- a/sympy/functions/elementary/tests/test_exponential.py
+++ b/sympy/functions/elementary/tests/test_exponential.py
@@ -261,10 +261,6 @@ def test_log_assumptions():
p = symbols('p', positive=True)
n = symbols('n', negative=True)
z = symbols('z', zero=True)
- x = symbols('x', infinite=True, positive=True)
-
- assert log(z).is_positive is False
- assert log(x).is_positive is True
assert log(2) > 0
assert log(1, evaluate=False).is_zero
assert log(1 + z).is_zero
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 1,
"issue_text_score": 0,
"test_score": 0
},
"num_modified_files": 3
} | 0.7 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "pytest",
"pip_packages": [
"mpmath>=0.19",
"pytest"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.6",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | attrs @ file:///opt/conda/conda-bld/attrs_1642510447205/work
certifi==2021.5.30
importlib-metadata @ file:///tmp/build/80754af9/importlib-metadata_1631916693255/work
iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work
more-itertools @ file:///tmp/build/80754af9/more-itertools_1637733554872/work
mpmath==1.3.0
packaging @ file:///tmp/build/80754af9/packaging_1637314298585/work
pluggy @ file:///tmp/build/80754af9/pluggy_1615976315926/work
py @ file:///opt/conda/conda-bld/py_1644396412707/work
pyparsing @ file:///tmp/build/80754af9/pyparsing_1635766073266/work
pytest==6.2.4
-e git+https://github.com/sympy/sympy.git@8c8594a311b22602b3c6f00f69c28c57012569f1#egg=sympy
toml @ file:///tmp/build/80754af9/toml_1616166611790/work
typing_extensions @ file:///opt/conda/conda-bld/typing_extensions_1647553014482/work
zipp @ file:///tmp/build/80754af9/zipp_1633618647012/work
| name: sympy
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- attrs=21.4.0=pyhd3eb1b0_0
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- importlib-metadata=4.8.1=py36h06a4308_0
- importlib_metadata=4.8.1=hd3eb1b0_0
- iniconfig=1.1.1=pyhd3eb1b0_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- more-itertools=8.12.0=pyhd3eb1b0_0
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- packaging=21.3=pyhd3eb1b0_0
- pip=21.2.2=py36h06a4308_0
- pluggy=0.13.1=py36h06a4308_0
- py=1.11.0=pyhd3eb1b0_0
- pyparsing=3.0.4=pyhd3eb1b0_0
- pytest=6.2.4=py36h06a4308_2
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_0
- setuptools=58.0.4=py36h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- toml=0.10.2=pyhd3eb1b0_0
- typing_extensions=4.1.1=pyh06a4308_0
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- zipp=3.6.0=pyhd3eb1b0_0
- zlib=1.2.13=h5eee18b_1
- pip:
- mpmath==1.3.0
prefix: /opt/conda/envs/sympy
| [
"sympy/core/tests/test_numbers.py::test_Float"
] | [] | [
"sympy/core/tests/test_numbers.py::test_integers_cache",
"sympy/core/tests/test_numbers.py::test_seterr",
"sympy/core/tests/test_numbers.py::test_mod",
"sympy/core/tests/test_numbers.py::test_divmod",
"sympy/core/tests/test_numbers.py::test_igcd",
"sympy/core/tests/test_numbers.py::test_ilcm",
"sympy/core/tests/test_numbers.py::test_igcdex",
"sympy/core/tests/test_numbers.py::test_Integer_new",
"sympy/core/tests/test_numbers.py::test_Rational_new",
"sympy/core/tests/test_numbers.py::test_Number_new",
"sympy/core/tests/test_numbers.py::test_Rational_cmp",
"sympy/core/tests/test_numbers.py::test_Float_default_to_highprec_from_str",
"sympy/core/tests/test_numbers.py::test_Float_eval",
"sympy/core/tests/test_numbers.py::test_Float_issue_2107",
"sympy/core/tests/test_numbers.py::test_Infinity",
"sympy/core/tests/test_numbers.py::test_Infinity_2",
"sympy/core/tests/test_numbers.py::test_Mul_Infinity_Zero",
"sympy/core/tests/test_numbers.py::test_Div_By_Zero",
"sympy/core/tests/test_numbers.py::test_Infinity_inequations",
"sympy/core/tests/test_numbers.py::test_NaN",
"sympy/core/tests/test_numbers.py::test_special_numbers",
"sympy/core/tests/test_numbers.py::test_powers",
"sympy/core/tests/test_numbers.py::test_integer_nthroot_overflow",
"sympy/core/tests/test_numbers.py::test_powers_Integer",
"sympy/core/tests/test_numbers.py::test_powers_Rational",
"sympy/core/tests/test_numbers.py::test_powers_Float",
"sympy/core/tests/test_numbers.py::test_abs1",
"sympy/core/tests/test_numbers.py::test_accept_int",
"sympy/core/tests/test_numbers.py::test_dont_accept_str",
"sympy/core/tests/test_numbers.py::test_int",
"sympy/core/tests/test_numbers.py::test_long",
"sympy/core/tests/test_numbers.py::test_real_bug",
"sympy/core/tests/test_numbers.py::test_bug_sqrt",
"sympy/core/tests/test_numbers.py::test_pi_Pi",
"sympy/core/tests/test_numbers.py::test_no_len",
"sympy/core/tests/test_numbers.py::test_issue_3321",
"sympy/core/tests/test_numbers.py::test_issue_3692",
"sympy/core/tests/test_numbers.py::test_issue_3423",
"sympy/core/tests/test_numbers.py::test_issue_3449",
"sympy/core/tests/test_numbers.py::test_Integer_factors",
"sympy/core/tests/test_numbers.py::test_Rational_factors",
"sympy/core/tests/test_numbers.py::test_issue_4107",
"sympy/core/tests/test_numbers.py::test_IntegerInteger",
"sympy/core/tests/test_numbers.py::test_Rational_gcd_lcm_cofactors",
"sympy/core/tests/test_numbers.py::test_Float_gcd_lcm_cofactors",
"sympy/core/tests/test_numbers.py::test_issue_4611",
"sympy/core/tests/test_numbers.py::test_conversion_to_mpmath",
"sympy/core/tests/test_numbers.py::test_relational",
"sympy/core/tests/test_numbers.py::test_Integer_as_index",
"sympy/core/tests/test_numbers.py::test_Rational_int",
"sympy/core/tests/test_numbers.py::test_zoo",
"sympy/core/tests/test_numbers.py::test_issue_4122",
"sympy/core/tests/test_numbers.py::test_GoldenRatio_expand",
"sympy/core/tests/test_numbers.py::test_as_content_primitive",
"sympy/core/tests/test_numbers.py::test_hashing_sympy_integers",
"sympy/core/tests/test_numbers.py::test_issue_4172",
"sympy/core/tests/test_numbers.py::test_Catalan_EulerGamma_prec",
"sympy/core/tests/test_numbers.py::test_Float_eq",
"sympy/core/tests/test_numbers.py::test_int_NumberSymbols",
"sympy/core/tests/test_numbers.py::test_issue_6640",
"sympy/core/tests/test_numbers.py::test_issue_6349",
"sympy/core/tests/test_numbers.py::test_mpf_norm",
"sympy/core/tests/test_numbers.py::test_latex",
"sympy/core/tests/test_numbers.py::test_issue_7742",
"sympy/core/tests/test_numbers.py::test_simplify_AlgebraicNumber",
"sympy/core/tests/test_numbers.py::test_Float_idempotence",
"sympy/core/tests/test_numbers.py::test_comp",
"sympy/functions/elementary/tests/test_exponential.py::test_exp_values",
"sympy/functions/elementary/tests/test_exponential.py::test_exp_log",
"sympy/functions/elementary/tests/test_exponential.py::test_exp_expand",
"sympy/functions/elementary/tests/test_exponential.py::test_exp__as_base_exp",
"sympy/functions/elementary/tests/test_exponential.py::test_exp_infinity",
"sympy/functions/elementary/tests/test_exponential.py::test_exp_subs",
"sympy/functions/elementary/tests/test_exponential.py::test_exp_conjugate",
"sympy/functions/elementary/tests/test_exponential.py::test_exp_rewrite",
"sympy/functions/elementary/tests/test_exponential.py::test_exp_leading_term",
"sympy/functions/elementary/tests/test_exponential.py::test_exp_taylor_term",
"sympy/functions/elementary/tests/test_exponential.py::test_log_values",
"sympy/functions/elementary/tests/test_exponential.py::test_log_base",
"sympy/functions/elementary/tests/test_exponential.py::test_log_symbolic",
"sympy/functions/elementary/tests/test_exponential.py::test_exp_assumptions",
"sympy/functions/elementary/tests/test_exponential.py::test_log_assumptions",
"sympy/functions/elementary/tests/test_exponential.py::test_log_hashing",
"sympy/functions/elementary/tests/test_exponential.py::test_log_sign",
"sympy/functions/elementary/tests/test_exponential.py::test_log_expand_complex",
"sympy/functions/elementary/tests/test_exponential.py::test_log_apply_evalf",
"sympy/functions/elementary/tests/test_exponential.py::test_log_expand",
"sympy/functions/elementary/tests/test_exponential.py::test_log_simplify",
"sympy/functions/elementary/tests/test_exponential.py::test_lambertw",
"sympy/functions/elementary/tests/test_exponential.py::test_issue_5673",
"sympy/functions/elementary/tests/test_exponential.py::test_exp_expand_NC",
"sympy/functions/elementary/tests/test_exponential.py::test_as_numer_denom",
"sympy/functions/elementary/tests/test_exponential.py::test_polar",
"sympy/functions/elementary/tests/test_exponential.py::test_log_product",
"sympy/functions/elementary/tests/test_exponential.py::test_issue_8866",
"sympy/functions/elementary/tests/test_exponential.py::test_issue_9116"
] | [] | BSD | 107 |
|
pysmt__pysmt-83 | 18c4ecb85ed6e799ec4947dcb5a072a21fdf7303 | 2015-04-25 15:40:24 | 18c4ecb85ed6e799ec4947dcb5a072a21fdf7303 | diff --git a/pysmt/native_nodes/__init__.py b/pysmt/native_nodes/__init__.py
new file mode 100644
index 0000000..8b13789
--- /dev/null
+++ b/pysmt/native_nodes/__init__.py
@@ -0,0 +1,1 @@
+
diff --git a/pysmt/solvers/eager.py b/pysmt/solvers/eager.py
index da3fbc7..9f43040 100644
--- a/pysmt/solvers/eager.py
+++ b/pysmt/solvers/eager.py
@@ -16,7 +16,7 @@
# limitations under the License.
#
from pysmt.solvers.solver import Model
-from pysmt.shortcuts import get_env, Real, Bool, Int
+from pysmt.shortcuts import get_env
from pysmt.typing import REAL, BOOL, INT
class EagerModel(Model):
@@ -34,37 +34,54 @@ class EagerModel(Model):
Model.__init__(self, environment)
self.environment = environment
self.assignment = assignment
+ # Create a copy of the assignments to memoize completions
+ self.completed_assignment = dict(self.assignment)
+
+ def get_value(self, formula, model_completion=True):
+ if model_completion:
+ syms = formula.get_free_variables()
+ self._complete_model(syms)
+ r = formula.substitute(self.completed_assignment)
+ else:
+ r = formula.substitute(self.assignment)
- def get_value(self, formula):
- r = formula.substitute(self.assignment)
res = r.simplify()
if not res.is_constant():
raise TypeError("Was expecting a constant but got %s" % res)
return res
- def complete_model(self, symbols):
- undefined_symbols = (s for s in symbols if s not in self.assignment)
+
+ def _complete_model(self, symbols):
+ undefined_symbols = (s for s in symbols
+ if s not in self.completed_assignment)
+ mgr = self.environment.formula_manager
for s in undefined_symbols:
if not s.is_symbol():
raise TypeError("Was expecting a symbol but got %s" %s)
- if s.is_symbol(BOOL):
- value = Bool(False)
- elif s.is_symbol(REAL):
- value = Real(0)
- elif s.is_symbol(INT):
- value = Int(0)
+ if s.symbol_type().is_bool_type():
+ value = mgr.Bool(False)
+ elif s.symbol_type().is_real_type():
+ value = mgr.Real(0)
+ elif s.symbol_type().is_int_type():
+ value = mgr.Int(0)
+ elif s.symbol_type().is_bv_type():
+ value = mgr.BVZero(s.bv_width())
else:
raise TypeError("Unhandled type for %s: %s" %
(s, s.symbol_type()))
- self.assignment[s] = value
+ self.completed_assignment[s] = value
+
+
+ def iterator_over(self, language):
+ for x in language:
+ yield x, self.get_value(x, model_completion=True)
def __iter__(self):
"""Overloading of iterator from Model. We iterate only on the
- variables defined in the assignment. Call complete_model to
- include more variables.
+ variables defined in the assignment.
"""
return iter(self.assignment.items())
diff --git a/pysmt/solvers/msat.py b/pysmt/solvers/msat.py
index 5770a86..da38c0a 100644
--- a/pysmt/solvers/msat.py
+++ b/pysmt/solvers/msat.py
@@ -288,10 +288,16 @@ class MathSAT5Solver(IncrementalTrackingSolver, UnsatCoreSolver,
def get_model(self):
assignment = {}
- for s in self.environment.formula_manager.get_all_symbols():
- if s.is_term():
- v = self.get_value(s)
- assignment[s] = v
+ msat_iterator = mathsat.msat_create_model_iterator(self.msat_env)
+ while mathsat.msat_model_iterator_has_next(msat_iterator):
+ term, value = mathsat.msat_model_iterator_next(msat_iterator)
+ pysmt_term = self.converter.back(term)
+ pysmt_value = self.converter.back(value)
+ if self.environment.stc.get_type(pysmt_term).is_real_type() and \
+ pysmt_value.is_int_constant():
+ pysmt_value = self.mgr.Real(pysmt_value.constant_value())
+ assignment[pysmt_term] = pysmt_value
+ mathsat.msat_destroy_model_iterator(msat_iterator)
return EagerModel(assignment=assignment, environment=self.environment)
diff --git a/pysmt/solvers/solver.py b/pysmt/solvers/solver.py
index 3ac613e..f0cf4a0 100644
--- a/pysmt/solvers/solver.py
+++ b/pysmt/solvers/solver.py
@@ -369,43 +369,46 @@ class Model(object):
self.environment = environment
self._converter = None
- def get_value(self, formula):
+ def get_value(self, formula, model_completion=True):
""" Returns the value of formula in the current model (if one exists).
+ If model_completion is True, then variables not appearing in the
+ assignment are given a default value, otherwise an error is generated.
+
This is a simplified version of the SMT-LIB funtion get_values .
"""
raise NotImplementedError
- def get_values(self, formulae):
+ def get_values(self, formulae, model_completion=True):
"""Evaluates the values of the formulae in the current model returning
a dictionary.
"""
res = {}
for f in formulae:
- v = self.get_value(f)
+ v = self.get_value(f, model_completion=model_completion)
res[f] = v
return res
- def get_py_value(self, formula):
+ def get_py_value(self, formula, model_completion=True):
""" Returns the value of formula as a python type.
E.g., Bool(True) is translated into True.
This simplifies writing code that branches on values in the model.
"""
- res = self.get_value(formula)
+ res = self.get_value(formula, model_completion=model_completion)
assert res.is_constant()
return res.constant_value()
- def get_py_values(self, formulae):
+ def get_py_values(self, formulae, model_completion=True):
"""Evaluates the values of the formulae as python types in the current
model returning a dictionary.
"""
res = {}
for f in formulae:
- v = self.get_py_value(f)
+ v = self.get_py_value(f, model_completion=model_completion)
res[f] = v
return res
@@ -419,12 +422,7 @@ class Model(object):
self._converter = value
def __getitem__(self, idx):
- return self.get_value(idx)
-
-
- def __iter__(self):
- for var in self.environment.formula_manager.get_all_symbols():
- yield var, self.get_value(var)
+ return self.get_value(idx, model_completion=True)
def __str__(self):
return "\n".join([ "%s := %s" % (var, value) for (var, value) in self])
diff --git a/pysmt/solvers/z3.py b/pysmt/solvers/z3.py
index ec11e8b..8800911 100644
--- a/pysmt/solvers/z3.py
+++ b/pysmt/solvers/z3.py
@@ -64,11 +64,29 @@ class Z3Model(Model):
self.z3_model = z3_model
self.converter = Z3Converter(environment)
- def get_value(self, formula):
+ def get_value(self, formula, model_completion=True):
titem = self.converter.convert(formula)
- z3_res = self.z3_model.eval(titem, model_completion=True)
+ z3_res = self.z3_model.eval(titem, model_completion=model_completion)
return self.converter.back(z3_res)
+ def iterator_over(self, language):
+ for x in language:
+ yield x, self.get_value(x, model_completion=True)
+
+ def __iter__(self):
+ """Overloading of iterator from Model. We iterate only on the
+ variables defined in the assignment.
+ """
+ for d in self.z3_model.decls():
+ pysmt_d = self.converter.back(d)
+ yield pysmt_d, self.get_value(pysmt_d)
+
+ def __contains__(self, x):
+ """Returns whether the model contains a value for 'x'."""
+ z3_x = self.converter.convert(x)
+ return z3_x in self.z3_model.decls()
+
+
class Z3Solver(IncrementalTrackingSolver, UnsatCoreSolver,
SmtLibBasicSolver, SmtLibIgnoreMixin):
| Solver.get_model should not try to assign a value to each variable in the environment
Implementation of get_model in the solvers using EagerModel, extracts one value for each symbol defined in the environment. This has a few problems:
1. In same cases we are doing much more work than needed
2. We cannot extract "partial models"
3. Symbols of type not supported by the solver (e.g., BV) will cause the solver to fail in the model creation.
Ideally, we should use iteration functions from the native solver API to extract models (if these are available). | pysmt/pysmt | diff --git a/pysmt/test/test_eager_model.py b/pysmt/test/test_eager_model.py
index aed7433..610908a 100644
--- a/pysmt/test/test_eager_model.py
+++ b/pysmt/test/test_eager_model.py
@@ -54,7 +54,7 @@ class TestEagerModel(TestCase):
model = EagerModel(assignment=d)
with self.assertRaises(TypeError):
- model.get_value(And(x,y))
+ model.get_value(And(x,y), model_completion=False)
d2 = {x:TRUE(), y:x}
model = EagerModel(assignment=d2)
@@ -69,13 +69,21 @@ class TestEagerModel(TestCase):
d = {x:TRUE()}
model = EagerModel(assignment=d)
- model.complete_model([x,y,r,p])
self.assertEqual(model.get_value(x), TRUE())
self.assertEqual(model.get_value(Or(x,y)), TRUE())
self.assertTrue(model.get_value(p).is_constant(INT))
self.assertTrue(model.get_value(r).is_constant(REAL))
+ self.assertEqual(model.get_value(x, model_completion=False), TRUE())
+ with self.assertRaises(TypeError):
+ model.get_value(And(x,y), model_completion=False)
+ with self.assertRaises(TypeError):
+ model.get_value(p, model_completion=False)
+ with self.assertRaises(TypeError):
+ model.get_value(r, model_completion=False)
+
+
def test_contains(self):
x, y, z = [FreshSymbol() for _ in xrange(3)]
d = {x: TRUE(), y: FALSE()}
diff --git a/pysmt/test/test_regressions.py b/pysmt/test/test_regressions.py
index 2ce5a75..ce69638 100644
--- a/pysmt/test/test_regressions.py
+++ b/pysmt/test/test_regressions.py
@@ -180,6 +180,19 @@ class TestRegressions(TestCase):
# The modulus operator must be there
self.assertIn("%2", str(ex.expression))
+ @skipIfSolverNotAvailable("msat")
+ def test_msat_partial_model(self):
+ msat = Solver(name="msat")
+ x, y = Symbol("x"), Symbol("y")
+ msat.add_assertion(x)
+ c = msat.solve()
+ self.assertTrue(c)
+
+ model = msat.get_model()
+ self.assertNotIn(y, model)
+ self.assertIn(x, model)
+ msat.exit()
+
if __name__ == "__main__":
import unittest
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_added_files",
"has_many_modified_files",
"has_many_hunks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 2,
"issue_text_score": 0,
"test_score": 0
},
"num_modified_files": 4
} | 0.2 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[dev]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"nose",
"nose-cov",
"pytest"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.9",
"reqs_path": [
"requirements/base.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | cov-core==1.15.0
coverage==7.8.0
exceptiongroup==1.2.2
iniconfig==2.1.0
nose==1.3.7
nose-cov==1.6
packaging==24.2
pluggy==1.5.0
-e git+https://github.com/pysmt/pysmt.git@18c4ecb85ed6e799ec4947dcb5a072a21fdf7303#egg=PySMT
pytest==8.3.5
six==1.17.0
tomli==2.2.1
| name: pysmt
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=3.0.16=h5eee18b_0
- pip=25.0=py39h06a4308_0
- python=3.9.21=he870216_1
- readline=8.2=h5eee18b_0
- setuptools=75.8.0=py39h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- tzdata=2025a=h04d1e81_0
- wheel=0.45.1=py39h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- cov-core==1.15.0
- coverage==7.8.0
- exceptiongroup==1.2.2
- iniconfig==2.1.0
- nose==1.3.7
- nose-cov==1.6
- packaging==24.2
- pluggy==1.5.0
- pytest==8.3.5
- six==1.17.0
- tomli==2.2.1
prefix: /opt/conda/envs/pysmt
| [
"pysmt/test/test_eager_model.py::TestEagerModel::test_complete_model"
] | [] | [
"pysmt/test/test_eager_model.py::TestEagerModel::test_construction",
"pysmt/test/test_eager_model.py::TestEagerModel::test_contains",
"pysmt/test/test_eager_model.py::TestEagerModel::test_env_default_arguments",
"pysmt/test/test_eager_model.py::TestEagerModel::test_result_is_const",
"pysmt/test/test_regressions.py::TestRegressions::test_dependencies_not_includes_toreal",
"pysmt/test/test_regressions.py::TestRegressions::test_infix_notation_wrong_le",
"pysmt/test/test_regressions.py::TestRegressions::test_multiple_declaration_w_same_functiontype",
"pysmt/test/test_regressions.py::TestRegressions::test_multiple_exit",
"pysmt/test/test_regressions.py::TestRegressions::test_simplifying_int_plus_changes_type_of_expression",
"pysmt/test/test_regressions.py::TestRegressions::test_substitute_memoization"
] | [] | Apache License 2.0 | 108 |
|
albertyw__itolapi-11 | 18ab55c5526ef6c8f3285af9363fb8e0e22f2bf1 | 2015-04-26 05:13:26 | 18ab55c5526ef6c8f3285af9363fb8e0e22f2bf1 | diff --git a/examples/example.py b/examples/example.py
index e879042..cac8202 100644
--- a/examples/example.py
+++ b/examples/example.py
@@ -13,9 +13,9 @@ sys.path.append(parent_path)
from itolapi import Itol, ItolExport
-print 'Running example itol and itolexport script'
-print ''
-print 'Creating the upload params'
+print('Running example itol and itolexport script')
+print('')
+print('Creating the upload params')
#Create the Itol class
test = Itol.Itol()
@@ -33,24 +33,24 @@ test.add_variable('dataset1Type','multibar')
# Check parameters
test.print_variables()
#Submit the tree
-print ''
-print 'Uploading the tree. This may take some time depending on how large the tree is and how much load there is on the itol server'
+print('')
+print('Uploading the tree. This may take some time depending on how large the tree is and how much load there is on the itol server')
good_upload = test.upload()
if good_upload == False:
- print 'There was an error:'+test.comm.upload_output
+ print('There was an error:'+test.comm.upload_output)
sys.exit(1)
#Read the tree ID
-print 'Tree ID: '+str(test.comm.tree_id)
+print('Tree ID: '+str(test.comm.tree_id))
#Read the iTOL API return statement
-print 'iTOL output: '+str(test.comm.upload_output)
+print('iTOL output: '+str(test.comm.upload_output))
#Website to be redirected to iTOL tree
-print 'Tree Web Page URL: '+test.get_webpage()
+print('Tree Web Page URL: '+test.get_webpage())
# Warnings associated with the upload
-print 'Warnings: '+str(test.comm.warnings)
+print('Warnings: '+str(test.comm.warnings))
# Export a pre-made tree to pdf
@@ -59,13 +59,13 @@ itol_exporter.set_export_param_value('tree','18793532031912684633930')
itol_exporter.set_export_param_value('format', 'pdf')
itol_exporter.set_export_param_value('datasetList','dataset1')
#itol_exporter.export('example_pdf.pdf')
-#print 'exported tree to ',export_location
+#print('exported tree to ',export_location)
# Export the tree above to pdf
-print 'Exporting to pdf'
+print('Exporting to pdf')
itol_exporter = test.get_itol_export()
export_location = 'example_pdf.pdf'
itol_exporter.set_export_param_value('format', 'pdf')
itol_exporter.set_export_param_value('datasetList','dataset1')
itol_exporter.export('example_pdf.pdf')
-print 'exported tree to ',export_location
+print('exported tree to ',export_location)
diff --git a/examples/failures/fatal.py b/examples/failures/fatal.py
index 59a2ff7..66b3e07 100644
--- a/examples/failures/fatal.py
+++ b/examples/failures/fatal.py
@@ -34,6 +34,6 @@ itol_o.add_variable('dataset1PieRadiusMin','20')
itol_o.add_variable('dataset1BarSizeMax','20')
itol_o.print_variables()
good_upload = itol_o.upload()
-print 'Tree Web Page URL:\n'+itol_o.get_webpage() + '\n'
-print 'Warnings:'
-print itol_o.comm.warnings
+print('Tree Web Page URL:\n'+itol_o.get_webpage() + '\n')
+print('Warnings:')
+print(itol_o.comm.warnings)
diff --git a/examples/failures/warnings.py b/examples/failures/warnings.py
index 66a56f0..c38d816 100644
--- a/examples/failures/warnings.py
+++ b/examples/failures/warnings.py
@@ -34,6 +34,6 @@ itol_o.add_variable('dataset1PieRadiusMin','20')
itol_o.add_variable('dataset1BarSizeMax','20')
itol_o.print_variables()
good_upload = itol_o.upload()
-print 'Tree Web Page URL:\n'+itol_o.get_webpage() + '\n'
-print 'Warnings:'
-print itol_o.comm.warnings
+print('Tree Web Page URL:\n'+itol_o.get_webpage() + '\n')
+print('Warnings:')
+print(itol_o.comm.warnings)
diff --git a/itolapi/Comm.py b/itolapi/Comm.py
index 6afe3c1..ab10513 100644
--- a/itolapi/Comm.py
+++ b/itolapi/Comm.py
@@ -2,6 +2,8 @@
This file is for communication between this API and iTOL servers
This also processes and stores information returned from the server
"""
+from __future__ import unicode_literals
+
import requests
@@ -29,7 +31,7 @@ class Comm:
new_params = {}
files = {}
for k,v in params.items():
- if isinstance(v, file):
+ if hasattr(v, 'read'):
files[k] = v
else:
new_params[k] = v
diff --git a/itolapi/Itol.py b/itolapi/Itol.py
index e771ce8..216c930 100644
--- a/itolapi/Itol.py
+++ b/itolapi/Itol.py
@@ -1,12 +1,20 @@
"""
This is the main file for the iTOL API
"""
+from __future__ import unicode_literals
+
import argparse
import sys
import os
from itolapi import Comm, ItolExport
+
+try:
+ basestring
+except NameError:
+ basestring = str
+
class Itol:
"""
This class handles the main itol functionality
@@ -18,7 +26,6 @@ class Itol:
self.variables = dict()
self.comm = Comm.Comm()
-
def add_variable(self, variable_name, variable_value):
"""
Add a variable and its value to this upload. This function includes
@@ -26,9 +33,9 @@ class Itol:
modifying the variables dictionary
"""
# Variable checking
- if not isinstance(variable_name, str):
+ if not isinstance(variable_name, basestring):
raise TypeError('variable name is not a string')
- if not isinstance(variable_value, str):
+ if not isinstance(variable_value, basestring):
raise TypeError('variable value should be a string')
if self.is_file(variable_name):
if not os.path.isfile(variable_value):
@@ -67,7 +74,7 @@ class Itol:
Get the web page where you can download the Itol tree
"""
webpage = "http://itol.embl.de/external.cgi?tree="+\
- str(self.comm.tree_id)+"&restore_saved=1"
+ bytes(self.comm.tree_id)+"&restore_saved=1"
return webpage
def get_itol_export(self):
@@ -85,15 +92,15 @@ class Itol:
"""
for variable_name, variable_value in self.variables.items():
if isinstance(variable_value, file):
- print variable_name+': '+variable_value.name
+ print(variable_name+': '+variable_value.name)
else:
- print variable_name+': '+variable_value
+ print(variable_name+': '+variable_value)
def delete_variable(self, variable_name):
"""
Remove a variable from the dictionary of set variables
"""
- if self.variables.has_key(variable_name):
+ if variable_name in self.variables:
del self.variables[variable_name]
@@ -107,4 +114,4 @@ if __name__ == "__main__":
itol_upload = Itol()
itol_upload.add_variable('treeFile', tree_file)
itol_upload.upload()
- print itol_upload.get_webpage()
+ print(itol_upload.get_webpage())
diff --git a/itolapi/ItolExport.py b/itolapi/ItolExport.py
index c98c23c..e44422b 100644
--- a/itolapi/ItolExport.py
+++ b/itolapi/ItolExport.py
@@ -1,6 +1,8 @@
"""
This is the main file for exporting of trees created by iTOL
"""
+from __future__ import unicode_literals
+
import argparse
import sys
@@ -72,7 +74,7 @@ if __name__ == "__main__":
itol_exporter.set_export_param_value('datasetList', \
'dataset1,dataset2,dataset3,dataset4,dataset5,\
dataset6,dataset7,dataset8,dataset9,dataset10')
- print 'Exporting tree from server....'
+ print('Exporting tree from server....')
itol_exporter.export(args.file_location)
- print 'Exported to ', args.file_location
+ print('Exported to ', args.file_location)
sys.exit(0)
diff --git a/setup.py b/setup.py
index 6071357..8531d3e 100644
--- a/setup.py
+++ b/setup.py
@@ -21,7 +21,8 @@ setup(name='itolapi',
scripts=['itolapi/Itol.py', 'itolapi/ItolExport.py'],
test_suite="tests",
tests_require=[
- 'mock>=1.0.1'
+ 'mock>=1.0.1',
+ 'tox',
],
classifiers=[
'Development Status :: 5 - Production/Stable',
@@ -30,7 +31,10 @@ setup(name='itolapi',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: MIT License',
'Natural Language :: English',
- 'Programming Language :: Python :: 2 :: Only',
+ 'Programming Language :: Python',
+ 'Programming Language :: Python :: 2.7',
+ 'Programming Language :: Python :: 3',
+ 'Programming Language :: Python :: 3.4',
'Topic :: Scientific/Engineering :: Bio-Informatics',
],
)
diff --git a/tox.ini b/tox.ini
new file mode 100644
index 0000000..99d2280
--- /dev/null
+++ b/tox.ini
@@ -0,0 +1,12 @@
+# Tox (http://tox.testrun.org/) is a tool for running tests
+# in multiple virtualenvs. This configuration file will run the
+# test suite on all supported python versions. To use it, "pip install tox"
+# and then run "tox" from this directory.
+
+[tox]
+envlist = py27, py34
+
+[testenv]
+commands = {envpython} setup.py test
+deps =
+ mock
| Support Python 3 | albertyw/itolapi | diff --git a/tests/comm.py b/tests/comm.py
index 3096f64..b4f5e65 100644
--- a/tests/comm.py
+++ b/tests/comm.py
@@ -1,3 +1,4 @@
+from __future__ import unicode_literals
from mock import MagicMock, patch
import tempfile
import unittest
@@ -6,10 +7,16 @@ from itolapi import Comm
class PullOutFilesTest(unittest.TestCase):
+ def setUp(self):
+ self.tempfile = tempfile.TemporaryFile()
+
+ def tearDown(self):
+ self.tempfile.close()
+
def test_pull_out_files(self):
params = {}
params['asdf'] = 'qwer'
- params['zxcv'] = tempfile.TemporaryFile()
+ params['zxcv'] = self.tempfile
new_params, files = Comm.Comm.pull_out_files(params)
self.assertEqual(new_params, {'asdf': 'qwer'})
self.assertEqual(files, {'zxcv': params['zxcv']})
@@ -17,7 +24,7 @@ class PullOutFilesTest(unittest.TestCase):
def test_doesnt_modify_params(self):
params = {}
params['asdf'] = 'qwer'
- params['zxcv'] = tempfile.TemporaryFile()
+ params['zxcv'] = self.tempfile
Comm.Comm.pull_out_files(params)
self.assertTrue('asdf' in params)
self.assertTrue('zxcv' in params)
@@ -25,12 +32,16 @@ class PullOutFilesTest(unittest.TestCase):
class UploadTreeTest(unittest.TestCase):
def setUp(self):
+ self.tempfile = tempfile.TemporaryFile()
self.comm = Comm.Comm()
self.params = {'asdf': 'qwer'}
- self.files = {'zxcv': tempfile.TemporaryFile()}
+ self.files = {'zxcv': self.tempfile}
self.all_params = self.params.copy()
self.all_params.update(self.files)
+ def tearDown(self):
+ self.tempfile.close()
+
@patch('itolapi.Comm.Comm.pull_out_files')
@patch('itolapi.Comm.requests')
@patch('itolapi.Comm.Comm.parse_upload')
diff --git a/tests/itol.py b/tests/itol.py
index f685ddb..6ec2abd 100644
--- a/tests/itol.py
+++ b/tests/itol.py
@@ -1,3 +1,4 @@
+from __future__ import unicode_literals
from mock import MagicMock, patch
import unittest
diff --git a/tests/itolexport.py b/tests/itolexport.py
index d1af1d9..ee2d5b0 100644
--- a/tests/itolexport.py
+++ b/tests/itolexport.py
@@ -1,3 +1,4 @@
+from __future__ import unicode_literals
from mock import MagicMock, patch
import unittest
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_short_problem_statement",
"has_added_files",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 2,
"issue_text_score": 3,
"test_score": 0
},
"num_modified_files": 7
} | 1.1 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[dev]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest",
"pytest-mock",
"mock"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.9",
"reqs_path": [
"requirements.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | certifi==2025.1.31
charset-normalizer==3.4.1
exceptiongroup==1.2.2
idna==3.10
iniconfig==2.1.0
-e git+https://github.com/albertyw/itolapi.git@18ab55c5526ef6c8f3285af9363fb8e0e22f2bf1#egg=itolapi
mock==5.2.0
packaging==24.2
pluggy==1.5.0
pytest==8.3.5
pytest-mock==3.14.0
requests==2.32.3
tomli==2.2.1
urllib3==2.3.0
| name: itolapi
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=3.0.16=h5eee18b_0
- pip=25.0=py39h06a4308_0
- python=3.9.21=he870216_1
- readline=8.2=h5eee18b_0
- setuptools=75.8.0=py39h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- tzdata=2025a=h04d1e81_0
- wheel=0.45.1=py39h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- certifi==2025.1.31
- charset-normalizer==3.4.1
- exceptiongroup==1.2.2
- idna==3.10
- iniconfig==2.1.0
- mock==5.2.0
- packaging==24.2
- pluggy==1.5.0
- pytest==8.3.5
- pytest-mock==3.14.0
- requests==2.32.3
- tomli==2.2.1
- urllib3==2.3.0
prefix: /opt/conda/envs/itolapi
| [
"tests/comm.py::PullOutFilesTest::test_doesnt_modify_params",
"tests/comm.py::PullOutFilesTest::test_pull_out_files",
"tests/comm.py::UploadTreeTest::test_upload_tree",
"tests/comm.py::ParseUploadTest::test_fatal",
"tests/comm.py::ParseUploadTest::test_successful",
"tests/comm.py::ParseUploadTest::test_successful_warnings",
"tests/comm.py::ExportImageTest::test_export_image",
"tests/itol.py::ItolTest::test_add_variable",
"tests/itol.py::ItolTest::test_bad_upload",
"tests/itol.py::ItolTest::test_checks_file_variable",
"tests/itol.py::ItolTest::test_checks_variable_name",
"tests/itol.py::ItolTest::test_checks_variable_value",
"tests/itol.py::ItolTest::test_delete_variables",
"tests/itol.py::ItolTest::test_get_itol_export",
"tests/itol.py::ItolTest::test_good_upload",
"tests/itol.py::ItolTest::test_initializes",
"tests/itol.py::ItolTest::test_is_file",
"tests/itol.py::ItolTest::test_print_variables",
"tests/itolexport.py::ItolTest::test_add_export_param_dict",
"tests/itolexport.py::ItolTest::test_export",
"tests/itolexport.py::ItolTest::test_get_export_params",
"tests/itolexport.py::ItolTest::test_set_export_param_value"
] | [] | [] | [] | MIT License | 109 |
|
mne-tools__mne-python-2023 | acf8364f01f98233613f7574cac7d533c35183bf | 2015-04-26 17:46:14 | edceb8f38349d6dc0cade1c9f8384cc0707ce3e8 | agramfort: Lgtm
Merge when Travis is happy
Thx for the quick fix | diff --git a/mne/io/brainvision/brainvision.py b/mne/io/brainvision/brainvision.py
index 35fd057a2..81b41fa78 100644
--- a/mne/io/brainvision/brainvision.py
+++ b/mne/io/brainvision/brainvision.py
@@ -396,6 +396,10 @@ def _get_eeg_info(vhdr_fname, eog, misc):
info['filename'] = vhdr_fname
eeg_info = {}
+ ext = os.path.splitext(vhdr_fname)[-1]
+ if ext != '.vhdr':
+ raise IOError("The header file must be given to read the data, "
+ "not the '%s' file." % ext)
with open(vhdr_fname, 'r') as f:
# extract the first section to resemble a cfg
l = f.readline().strip()
| check extension of brainvision file
I mistakenly tried:
raw = mne.io.read_raw_brainvision('test.vmrk')
instead of
raw = mne.io.read_raw_brainvision('test.vhdr')
and got this error, which is not super explicit:
--> 402 assert l == 'Brain Vision Data Exchange Header File Version 1.0'
to help here we should check file extension and use a properly exception (not this assert).
@teonlamont can you take care of that?
thanks heaps.
| mne-tools/mne-python | diff --git a/mne/io/brainvision/tests/test_brainvision.py b/mne/io/brainvision/tests/test_brainvision.py
index 44eb09816..5131d978a 100644
--- a/mne/io/brainvision/tests/test_brainvision.py
+++ b/mne/io/brainvision/tests/test_brainvision.py
@@ -22,6 +22,7 @@ from mne.io import read_raw_brainvision
FILE = inspect.getfile(inspect.currentframe())
data_dir = op.join(op.dirname(op.abspath(FILE)), 'data')
vhdr_path = op.join(data_dir, 'test.vhdr')
+vmrk_path = op.join(data_dir, 'test.vmrk')
vhdr_highpass_path = op.join(data_dir, 'test_highpass.vhdr')
montage = op.join(data_dir, 'test.hpts')
eeg_bin = op.join(data_dir, 'test_bin_raw.fif')
@@ -42,6 +43,7 @@ def test_brainvision_data_filters():
def test_brainvision_data():
"""Test reading raw Brain Vision files
"""
+ assert_raises(IOError, read_raw_brainvision, vmrk_path)
assert_raises(TypeError, read_raw_brainvision, vhdr_path, montage,
preload=True, scale="0")
raw_py = read_raw_brainvision(vhdr_path, montage, eog=eog, preload=True)
| {
"commit_name": "head_commit",
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true,
"llm_score": {
"difficulty_score": 0,
"issue_text_score": 0,
"test_score": 2
},
"num_modified_files": 1
} | 0.8 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[dev]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"numpy>=1.16.0",
"pandas>=1.0.0",
"scikit-learn",
"h5py",
"pysurfer",
"nose",
"nose-timer",
"pytest"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.7",
"reqs_path": [
"requirements/base.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | apptools==5.2.1
certifi @ file:///croot/certifi_1671487769961/work/certifi
configobj==5.0.9
cycler==0.11.0
envisage==7.0.3
exceptiongroup==1.2.2
fonttools==4.38.0
h5py==3.8.0
importlib-metadata==6.7.0
importlib-resources==5.12.0
iniconfig==2.0.0
joblib==1.3.2
kiwisolver==1.4.5
matplotlib==3.5.3
mayavi==4.8.1
-e git+https://github.com/mne-tools/mne-python.git@acf8364f01f98233613f7574cac7d533c35183bf#egg=mne
nibabel==4.0.2
nose==1.3.7
nose-timer==1.0.1
numpy==1.21.6
packaging==24.0
pandas==1.3.5
Pillow==9.5.0
pluggy==1.2.0
pyface==8.0.0
Pygments==2.17.2
pyparsing==3.1.4
pysurfer==0.11.2
pytest==7.4.4
python-dateutil==2.9.0.post0
pytz==2025.2
scikit-learn==1.0.2
scipy==1.7.3
six==1.17.0
threadpoolctl==3.1.0
tomli==2.0.1
traits==6.4.3
traitsui==8.0.0
typing_extensions==4.7.1
vtk==9.3.1
zipp==3.15.0
| name: mne-python
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2022.12.7=py37h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- pip=22.3.1=py37h06a4308_0
- python=3.7.16=h7a1cb2a_0
- readline=8.2=h5eee18b_0
- setuptools=65.6.3=py37h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- wheel=0.38.4=py37h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- apptools==5.2.1
- configobj==5.0.9
- cycler==0.11.0
- envisage==7.0.3
- exceptiongroup==1.2.2
- fonttools==4.38.0
- h5py==3.8.0
- importlib-metadata==6.7.0
- importlib-resources==5.12.0
- iniconfig==2.0.0
- joblib==1.3.2
- kiwisolver==1.4.5
- matplotlib==3.5.3
- mayavi==4.8.1
- nibabel==4.0.2
- nose==1.3.7
- nose-timer==1.0.1
- numpy==1.21.6
- packaging==24.0
- pandas==1.3.5
- pillow==9.5.0
- pluggy==1.2.0
- pyface==8.0.0
- pygments==2.17.2
- pyparsing==3.1.4
- pysurfer==0.11.2
- pytest==7.4.4
- python-dateutil==2.9.0.post0
- pytz==2025.2
- scikit-learn==1.0.2
- scipy==1.7.3
- six==1.17.0
- threadpoolctl==3.1.0
- tomli==2.0.1
- traits==6.4.3
- traitsui==8.0.0
- typing-extensions==4.7.1
- vtk==9.3.1
- zipp==3.15.0
prefix: /opt/conda/envs/mne-python
| [
"mne/io/brainvision/tests/test_brainvision.py::test_brainvision_data"
] | [] | [
"mne/io/brainvision/tests/test_brainvision.py::test_brainvision_data_filters",
"mne/io/brainvision/tests/test_brainvision.py::test_events",
"mne/io/brainvision/tests/test_brainvision.py::test_read_segment"
] | [] | BSD 3-Clause "New" or "Revised" License | 110 |
mkdocs__mkdocs-482 | 1a0dfb5ee3d5dd290da9c8c03b0946e784aa6959 | 2015-04-27 19:05:31 | 463c5b647e9ce5992b519708a0b9c4cba891d65c | ci5er: I never personally had a problem with the old way, but this is pretty dang sweet. Thank you.
waylan: Wow, that is a great improvement. At a glance, the page structure is immediately obvious from the config. I like it.
d0ugal: This is not supported in the MkDocs theme.

d0ugal:  | diff --git a/docs/index.md b/docs/index.md
index 047f6a4e..9f9b1367 100644
--- a/docs/index.md
+++ b/docs/index.md
@@ -105,8 +105,8 @@ We'd like our documentation site to include some navigation headers, so we'll ed
site_name: MkLorum
pages:
- - [index.md, Home]
- - [about.md, About]
+ - Home: index.md
+ - About: about.md
Refresh the browser and you'll now see a navigation bar with `Home` and `About` headers.
@@ -116,9 +116,10 @@ While we're here can also change the configuration file to alter how the documen
site_name: MkLorum
pages:
- - [index.md, Home]
- - [about.md, About]
-```
+ - Home: index.md
+ - About: about.md
+ theme: readthedocs
+
Refresh the browser again, and you'll now see the ReadTheDocs theme being used.
diff --git a/docs/user-guide/configuration.md b/docs/user-guide/configuration.md
index c7dff762..abf7c48f 100644
--- a/docs/user-guide/configuration.md
+++ b/docs/user-guide/configuration.md
@@ -90,22 +90,23 @@ The setting should be a list. Each row in the list represents information about
Here's a simple example that would cause the build stage to create three pages:
-
pages:
- - ['index.md', 'Introduction']
- - ['user-guide.md', 'User Guide']
- - ['about.md', 'About']
+ - 'Introduction': 'index.md'
+ - 'User Guide': 'user-guide.md'
+ - 'Abut': 'about.md'
Assuming the `docs_dir` setting was left with the default value of `docs`, the source files for this site's build process would be `docs/index.md`, `docs/user-guide.md` and `docs/about.md`.
If you have a lot of project documentation you might choose to use headings to break up your site navigation by category. You can do so by including an extra string in the page configuration for any pages that require a navigation heading, like so:
pages:
- - ['index.md', 'Introduction']
- - ['user-guide/creating.md', 'User Guide', 'Creating a new Mashmallow project']
- - ['user-guide/api.md', 'User Guide', 'Mashmallow API guide']
- - ['user-guide/configuration.md', 'User Guide', 'Configuring Mashmallow']
- - ['about/license.md', 'About', 'License']
+ - Introduction: 'index.md'
+ - User Guide:
+ - 'Creating a new Mashmallow project': 'user-guide/creating.md'
+ - 'Mashmallow API guide': 'user-guide/api.md'
+ - 'Configuring Mashmallow': 'user-guide/configuration.md'
+ - About:
+ - License: 'about/license.md'
See also the section on [configuring pages and navigation](/user-guide/writing-your-docs/#configure-pages-and-navigation) for a more detailed breakdown.
diff --git a/docs/user-guide/writing-your-docs.md b/docs/user-guide/writing-your-docs.md
index 57620dd7..8ba930bf 100644
--- a/docs/user-guide/writing-your-docs.md
+++ b/docs/user-guide/writing-your-docs.md
@@ -17,19 +17,21 @@ A simple pages configuration looks like this:
With this example we will build two pages at the top level and they will automatically have their titles inferred from the filename. To provide a custom name for these pages, they can be added after the filename.
pages:
- - ['index.md', 'Home']
- - ['about.md', 'About MkDocs']
+ - Home: 'index.md'
+ - About: 'about.md'
### Multilevel documentation
To create a second level in the navigation and group topics, the category can be provided before the page title. This is best demonstrated in a documentation project with more pages and is slighlt more complicated.
pages:
- - ['index.md', 'Home']
- - ['user-guide/writing-your-docs.md', 'User Guide', 'Writing your docs']
- - ['user-guide/styling-your-docs.md', 'User Guide', 'Styling your docs']
- - ['about/license.md', 'About', 'License']
- - ['about/release-notes.md', 'About', 'Release Notes']
+ - Home: 'index.md'
+ - User Guide:
+ - 'Writing your docs': 'user-guide/writing-your-docs.md'
+ - 'Styling your docs': 'user-guide/styling-your-docs.md'
+ - About:
+ - 'License': 'about/license.md'
+ - 'Release Notes': 'about/release-notes.md'
With the above configuration we have three top level sections Home, User Guide and About. Then under User Guide we have two pages, Writing your docs and Styling your docs. Under the About section we also have two pages, License and Release Notes
diff --git a/mkdocs.yml b/mkdocs.yml
index 48c2a31f..ad7ce968 100644
--- a/mkdocs.yml
+++ b/mkdocs.yml
@@ -5,13 +5,17 @@ site_description: Project documentation with Markdown.
repo_url: https://github.com/mkdocs/mkdocs/
pages:
-- ['index.md', 'Home']
-- ['user-guide/writing-your-docs.md', 'User Guide', 'Writing your docs']
-- ['user-guide/styling-your-docs.md', 'User Guide', 'Styling your docs']
-- ['user-guide/configuration.md', 'User Guide', 'Configuration']
-- ['about/license.md', 'About', 'License']
-- ['about/release-notes.md', 'About', 'Release Notes']
-- ['about/contributing.md', 'About', 'Contributing']
+- Home: index.md
+- User Guide:
+ - Writing Your Docs: user-guide/writing-your-docs.md
+ - Styling Your Docs: user-guide/styling-your-docs.md
+ - Configuration: user-guide/configuration.md
+- About:
+ - License: about/license.md
+ - Release Notes: about/release-notes.md
+ - Contributing: about/contributing.md
+
+use_new_pages_structure: true
markdown_extensions:
toc:
diff --git a/mkdocs/config.py b/mkdocs/config.py
index 65744fa9..408e3393 100644
--- a/mkdocs/config.py
+++ b/mkdocs/config.py
@@ -7,7 +7,7 @@ import os
from six.moves.urllib.parse import urlparse
-from mkdocs import utils
+from mkdocs import utils, legacy
from mkdocs.exceptions import ConfigurationError
log = logging.getLogger(__name__)
@@ -68,7 +68,7 @@ DEFAULT_CONFIG = {
# enabling strict mode causes MkDocs to stop the build when a problem is
# encountered rather than display an error.
- 'strict': False
+ 'strict': False,
}
@@ -153,11 +153,27 @@ def validate_config(user_config):
check for Windows style paths. If they are found, output a warning
and continue.
"""
+
+ # TODO: Remove in 1.0
+ config_types = set(type(l) for l in config['pages'])
+ if list in config_types and dict not in config_types:
+ config['pages'] = legacy.pages_compat_shim(config['pages'])
+ elif list in config_types:
+ raise ConfigurationError("")
+
for page_config in config['pages']:
+
if isinstance(page_config, str):
path = page_config
+ elif isinstance(page_config, dict):
+ if len(page_config) > 1:
+ raise ConfigurationError(
+ "Invalid page config. Should have one key value only")
+ _, path = next(iter(page_config.items()))
elif len(page_config) in (1, 2, 3):
path = page_config[0]
+ else:
+ raise ConfigurationError("Unrecognised page config")
if ntpath.sep in path:
log.warning("The config path contains Windows style paths (\\ "
diff --git a/mkdocs/legacy.py b/mkdocs/legacy.py
new file mode 100644
index 00000000..0ac6d705
--- /dev/null
+++ b/mkdocs/legacy.py
@@ -0,0 +1,120 @@
+import logging
+
+from mkdocs.exceptions import ConfigurationError
+
+log = logging.getLogger(__name__)
+
+
+def pages_compat_shim(original_pages):
+ """
+ Support legacy pages configuration
+
+ Re-write the pages config fron MkDocs <=0.12 to match the
+ new nested structure added in 0.13.
+
+ Given a pages configuration in the old style of:
+
+ pages:
+ - ['index.md', 'Home']
+ - ['user-guide/writing-your-docs.md', 'User Guide']
+ - ['user-guide/styling-your-docs.md', 'User Guide']
+ - ['about/license.md', 'About', 'License']
+ - ['about/release-notes.md', 'About']
+ - ['help/contributing.md', 'Help', 'Contributing']
+ - ['support.md']
+ - ['cli.md', 'CLI Guide']
+
+ Rewrite it to look like:
+
+ pages:
+ - Home: index.md
+ - User Guide:
+ - user-guide/writing-your-docs.md
+ - user-guide/styling-your-docs.md
+ - About:
+ - License: about/license.md
+ - about/release-notes.md
+ - Help:
+ - Contributing: about/contributing.md
+ - support.md
+ - CLI Guide: cli.md
+
+ TODO: Remove in 1.0
+ """
+
+ log.warning("The pages config in the mkdocs.yml uses the deprecated "
+ "structure. This will be removed in the next release of "
+ "MkDocs. See for details on updating: "
+ "http://www.mkdocs.org/about/release-notes/")
+
+ new_pages = []
+
+ for config_line in original_pages:
+
+ if len(config_line) not in (1, 2, 3):
+ msg = (
+ "Line in 'page' config contained {0} items. In Line {1}. "
+ "Expected 1, 2 or 3 strings.".format(
+ config_line, len(config_line))
+ )
+ raise ConfigurationError(msg)
+
+ # First we need to pad out the config line as it could contain
+ # 1-3 items.
+ path, category, title = (list(config_line) + [None, None])[:3]
+
+ if len(new_pages) > 0:
+ # Get the previous top-level page so we can see if the category
+ # matches up with the one we have now.
+ prev_cat, subpages = next(iter(new_pages[-1].items()))
+ else:
+ # We are on the first page
+ prev_cat, subpages = None, []
+
+ # If the category is different, add a new top level category. If the
+ # previous category is None, the it's another top level one too.
+ if prev_cat is None or prev_cat != category:
+ subpages = []
+ new_pages.append({category: subpages})
+
+ # Add the current page to the determined category.
+ subpages.append({title: path})
+
+ # We need to do a bit of cleaning up to match the new structure. In the
+ # above example, pages can either be `- file.md` or `- Title: file.md`.
+ # For pages without a title we currently have `- None: file.md` - so we
+ # need to remove those Nones by changing from a dict to just a string with
+ # the path.
+ for i, category in enumerate(new_pages):
+
+ # Categories are a dictionary with one key as the name and the value
+ # is a list of pages. So, grab that from the dict.
+ category, pages = next(iter(category.items()))
+
+ # If we only have one page, then we can assume it is a top level
+ # category and no further nesting is required unless that single page
+ # has a title itself,
+ if len(pages) == 1:
+ title, path = pages.pop().popitem()
+ # If we have a title, it should be a sub page
+ if title is not None:
+ pages.append({title: path})
+ # if we have a category, but no title it should be a top-level page
+ elif category is not None:
+ new_pages[i] = {category: path}
+ # if we have no category or title, it must be a top level page with
+ # an atomatic title.
+ else:
+ new_pages[i] = path
+ else:
+ # We have more than one page, so the category is valid. We just
+ # need to iterate through and convert any {None: path} dicts to
+ # be just the path string.
+ for j, page in enumerate(pages):
+ title, path = page.popitem()
+ if title:
+ pages[j] = {title: path}
+ else:
+ pages[j] = path
+
+ return new_pages
diff --git a/mkdocs/nav.py b/mkdocs/nav.py
index 85d33513..8323c149 100644
--- a/mkdocs/nav.py
+++ b/mkdocs/nav.py
@@ -28,7 +28,8 @@ def file_to_title(filename):
try:
with open(filename, 'r') as f:
lines = f.read()
- _, table_of_contents, meta = utils.convert_markdown(lines, ['meta', 'toc'])
+ _, table_of_contents, meta = utils.convert_markdown(
+ lines, ['meta', 'toc'])
if "title" in meta:
return meta["title"][0]
if len(table_of_contents.items) > 0:
@@ -53,8 +54,8 @@ class SiteNavigation(object):
def __init__(self, pages_config, use_directory_urls=True):
self.url_context = URLContext()
self.file_context = FileContext()
- self.nav_items, self.pages = \
- _generate_site_navigation(pages_config, self.url_context, use_directory_urls)
+ self.nav_items, self.pages = _generate_site_navigation(
+ pages_config, self.url_context, use_directory_urls)
self.homepage = self.pages[0] if self.pages else None
self.use_directory_urls = use_directory_urls
@@ -122,7 +123,8 @@ class URLContext(object):
return '.'
return url.lstrip('/')
# Under Python 2.6, relative_path adds an extra '/' at the end.
- relative_path = os.path.relpath(url, start=self.base_path).rstrip('/') + suffix
+ relative_path = os.path.relpath(url, start=self.base_path)
+ relative_path = relative_path.rstrip('/') + suffix
return utils.path_to_url(relative_path)
@@ -154,6 +156,7 @@ class FileContext(object):
class Page(object):
def __init__(self, title, url, path, url_context):
+
self.title = title
self.abs_url = url
self.active = False
@@ -177,6 +180,10 @@ class Page(object):
def is_homepage(self):
return utils.is_homepage(self.input_path)
+ @property
+ def is_top_level(self):
+ return len(self.ancestors) == 0
+
def __str__(self):
return self._indent_print()
@@ -196,10 +203,15 @@ class Header(object):
def __init__(self, title, children):
self.title, self.children = title, children
self.active = False
+ self.ancestors = []
def __str__(self):
return self._indent_print()
+ @property
+ def is_top_level(self):
+ return len(self.ancestors) == 0
+
def _indent_print(self, depth=0):
indent = ' ' * depth
active_marker = ' [*]' if self.active else ''
@@ -209,74 +221,102 @@ class Header(object):
return ret
-def _generate_site_navigation(pages_config, url_context, use_directory_urls=True):
+def _path_to_page(path, title, url_context, use_directory_urls):
+ if title is None:
+ title = file_to_title(path.split(os.path.sep)[-1])
+ url = utils.get_url_path(path, use_directory_urls)
+ return Page(title=title, url=url, path=path,
+ url_context=url_context)
+
+
+def _follow(config_line, url_context, use_dir_urls, header=None, title=None):
+
+ if isinstance(config_line, str):
+ path = os.path.normpath(config_line)
+ page = _path_to_page(path, title, url_context, use_dir_urls)
+
+ if header:
+ page.ancestors = [header]
+ header.children.append(page)
+
+ yield page
+ raise StopIteration
+
+ elif not isinstance(config_line, dict):
+ msg = ("Line in 'page' config is of type {0}, dict or string "
+ "expected. Config: {1}").format(type(config_line), config_line)
+ raise exceptions.ConfigurationError(msg)
+
+ if len(config_line) > 1:
+ raise exceptions.ConfigurationError(
+ "Page configs should be in the format 'name: markdown.md'. The "
+ "config contains an invalid entry: {0}".format(config_line))
+ elif len(config_line) == 0:
+ log.warning("Ignoring empty line in the pages config.")
+ raise StopIteration
+
+ next_cat_or_title, subpages_or_path = next(iter(config_line.items()))
+
+ if isinstance(subpages_or_path, str):
+ path = subpages_or_path
+ for sub in _follow(path, url_context, use_dir_urls, header=header, title=next_cat_or_title):
+ yield sub
+ raise StopIteration
+
+ elif not isinstance(subpages_or_path, list):
+ msg = ("Line in 'page' config is of type {0}, list or string "
+ "expected for sub pages. Config: {1}"
+ ).format(type(config_line), config_line)
+ raise exceptions.ConfigurationError(msg)
+
+ next_header = Header(title=next_cat_or_title, children=[])
+ if header:
+ next_header.ancestors = [header]
+ header.children.append(next_header)
+ yield next_header
+
+ subpages = subpages_or_path
+
+ for subpage in subpages:
+ for sub in _follow(subpage, url_context, use_dir_urls, next_header):
+ yield sub
+
+
+def _generate_site_navigation(pages_config, url_context, use_dir_urls=True):
"""
Returns a list of Page and Header instances that represent the
top level site navigation.
"""
nav_items = []
pages = []
+
previous = None
for config_line in pages_config:
- if isinstance(config_line, str):
- path = os.path.normpath(config_line)
- title, child_title = None, None
- elif len(config_line) in (1, 2, 3):
- # Pad any items that don't exist with 'None'
- padded_config = (list(config_line) + [None, None])[:3]
- path, title, child_title = padded_config
- path = os.path.normpath(path)
- else:
- msg = (
- "Line in 'page' config contained %d items. "
- "Expected 1, 2 or 3 strings." % len(config_line)
- )
- raise exceptions.ConfigurationError(msg)
-
- # If both the title and child_title are None, then we
- # have just been given a path. If that path contains a /
- # then lets automatically nest it.
- if title is None and child_title is None and os.path.sep in path:
- filename = path.split(os.path.sep)[-1]
- child_title = file_to_title(filename)
-
- if title is None:
- filename = path.split(os.path.sep)[0]
- title = file_to_title(filename)
-
- # If we don't have a child title but the other title is the same, we
- # should be within a section and the child title needs to be inferred
- # from the filename.
- if len(nav_items) and title == nav_items[-1].title == title and child_title is None:
- filename = path.split(os.path.sep)[-1]
- child_title = file_to_title(filename)
-
- url = utils.get_url_path(path, use_directory_urls)
-
- if not child_title:
- # New top level page.
- page = Page(title=title, url=url, path=path, url_context=url_context)
- nav_items.append(page)
- elif not nav_items or (nav_items[-1].title != title):
- # New second level page.
- page = Page(title=child_title, url=url, path=path, url_context=url_context)
- header = Header(title=title, children=[page])
- nav_items.append(header)
- page.ancestors = [header]
- else:
- # Additional second level page.
- page = Page(title=child_title, url=url, path=path, url_context=url_context)
- header = nav_items[-1]
- header.children.append(page)
- page.ancestors = [header]
- # Add in previous and next information.
- if previous:
- page.previous_page = previous
- previous.next_page = page
- previous = page
+ for page_or_header in _follow(
+ config_line, url_context, use_dir_urls):
+
+ if isinstance(page_or_header, Header):
+
+ if page_or_header.is_top_level:
+ nav_items.append(page_or_header)
+
+ elif isinstance(page_or_header, Page):
+
+ if page_or_header.is_top_level:
+ nav_items.append(page_or_header)
+
+ pages.append(page_or_header)
+
+ if previous:
+ page_or_header.previous_page = previous
+ previous.next_page = page_or_header
+ previous = page_or_header
- pages.append(page)
+ if len(pages) == 0:
+ raise exceptions.ConfigurationError(
+ "No pages found in the pages config. "
+ "Remove it entirely to enable automatic page discovery.")
return (nav_items, pages)
diff --git a/mkdocs/themes/mkdocs/css/base.css b/mkdocs/themes/mkdocs/css/base.css
index 3a31ef73..8bfc7de2 100644
--- a/mkdocs/themes/mkdocs/css/base.css
+++ b/mkdocs/themes/mkdocs/css/base.css
@@ -224,3 +224,52 @@ h1:hover .headerlink, h2:hover .headerlink, h3:hover .headerlink, h4:hover .head
font-weight: bold;
text-align: left;
}
+
+
+.dropdown-submenu {
+ position: relative;
+}
+
+.dropdown-submenu>.dropdown-menu {
+ top: 0;
+ left: 100%;
+ margin-top: -6px;
+ margin-left: -1px;
+ -webkit-border-radius: 0 6px 6px 6px;
+ -moz-border-radius: 0 6px 6px;
+ border-radius: 0 6px 6px 6px;
+}
+
+.dropdown-submenu:hover>.dropdown-menu {
+ display: block;
+}
+
+.dropdown-submenu>a:after {
+ display: block;
+ content: " ";
+ float: right;
+ width: 0;
+ height: 0;
+ border-color: transparent;
+ border-style: solid;
+ border-width: 5px 0 5px 5px;
+ border-left-color: #ccc;
+ margin-top: 5px;
+ margin-right: -10px;
+}
+
+.dropdown-submenu:hover>a:after {
+ border-left-color: #fff;
+}
+
+.dropdown-submenu.pull-left {
+ float: none;
+}
+
+.dropdown-submenu.pull-left>.dropdown-menu {
+ left: -100%;
+ margin-left: 10px;
+ -webkit-border-radius: 6px 0 6px 6px;
+ -moz-border-radius: 6px 0 6px 6px;
+ border-radius: 6px 0 6px 6px;
+}
diff --git a/mkdocs/themes/mkdocs/nav-sub.html b/mkdocs/themes/mkdocs/nav-sub.html
new file mode 100644
index 00000000..76210465
--- /dev/null
+++ b/mkdocs/themes/mkdocs/nav-sub.html
@@ -0,0 +1,14 @@
+{% if not nav_item.children %}
+<li {% if nav_item.active %}class="active"{% endif %}>
+ <a href="{{ nav_item.url }}">{{ nav_item.title }}</a>
+</li>
+{% else %}
+ <li class="dropdown-submenu">
+ <a tabindex="-1" href="">{{ nav_item.title }}</a>
+ <ul class="dropdown-menu">
+ {% for nav_item in nav_item.children %}
+ {% include "nav-sub.html" %}
+ {% endfor %}
+ </ul>
+ </li>
+{% endif %}
diff --git a/mkdocs/themes/mkdocs/nav.html b/mkdocs/themes/mkdocs/nav.html
index 5ab01c90..60cc5ca9 100644
--- a/mkdocs/themes/mkdocs/nav.html
+++ b/mkdocs/themes/mkdocs/nav.html
@@ -28,9 +28,7 @@
<a href="#" class="dropdown-toggle" data-toggle="dropdown">{{ nav_item.title }} <b class="caret"></b></a>
<ul class="dropdown-menu">
{% for nav_item in nav_item.children %}
- <li {% if nav_item.active %}class="active"{% endif %}>
- <a href="{{ nav_item.url }}">{{ nav_item.title }}</a>
- </li>
+ {% include "nav-sub.html" %}
{% endfor %}
</ul>
</li>
diff --git a/mkdocs/themes/readthedocs/base.html b/mkdocs/themes/readthedocs/base.html
index fe4c1474..b6b7ba65 100644
--- a/mkdocs/themes/readthedocs/base.html
+++ b/mkdocs/themes/readthedocs/base.html
@@ -57,7 +57,11 @@
</div>
<div class="wy-menu wy-menu-vertical" data-spy="affix" role="navigation" aria-label="main navigation">
- {% include "toc.html" %}
+ <ul class="current">
+ {% for nav_item in nav %}
+ <li>{% include "toc.html" %}<li>
+ {% endfor %}
+ </ul>
</div>
</nav>
diff --git a/mkdocs/themes/readthedocs/css/theme_extra.css b/mkdocs/themes/readthedocs/css/theme_extra.css
index 675760c9..ccb384e9 100644
--- a/mkdocs/themes/readthedocs/css/theme_extra.css
+++ b/mkdocs/themes/readthedocs/css/theme_extra.css
@@ -25,7 +25,7 @@ h3, h4, h5, h6 {
color: #838383;
}
-.wy-menu-vertical .toctree-l2 a {
+.wy-menu-vertical .subnav a {
padding: 0.4045em 2.427em;
}
@@ -116,3 +116,11 @@ code.cs, code.c {
padding: 6px 12px;
border-color: #D1D4D5;
}
+
+.wy-menu-vertical li ul {
+ display: inherit;
+}
+
+.wy-menu-vertical li ul.subnav ul.subnav{
+ padding-left: 1em;
+}
diff --git a/mkdocs/themes/readthedocs/toc.html b/mkdocs/themes/readthedocs/toc.html
index c7f1d03d..6cd2fc9b 100644
--- a/mkdocs/themes/readthedocs/toc.html
+++ b/mkdocs/themes/readthedocs/toc.html
@@ -1,38 +1,23 @@
-<ul class="current">
- {% for nav_item in nav %}
- {% if nav_item.children %}
- <span>{{ nav_item.title }}</span>
- {% for nav_item in nav_item.children %}
- <li class="toctree-l2 {% if nav_item.active%}current{%endif%}">
- <a class="{% if nav_item.active%}current{%endif%}" href="{{ nav_item.url }}">{{ nav_item.title }}</a>
- {% if nav_item == current_page %}
- <ul>
- {% for toc_item in toc %}
- <li class="toctree-l3"><a href="{{ toc_item.url }}">{{ toc_item.title }}</a></li>
- {% for toc_item in toc_item.children %}
- <li><a class="toctree-l4" href="{{ toc_item.url }}">{{ toc_item.title }}</a></li>
- {% endfor %}
- {% endfor %}
- </ul>
- {% endif %}
- </li>
+{% if nav_item.children %}
+ <ul class="subnav">
+ <li><span>{{ nav_item.title }}</span></li>
+
+ {% for nav_item in nav_item.children %}
+ {% include 'toc.html' %}
+ {% endfor %}
+ </ul>
+{% else %}
+ <li class="toctree-l1 {% if nav_item.active%}current{%endif%}">
+ <a class="{% if nav_item.active%}current{%endif%}" href="{{ nav_item.url }}">{{ nav_item.title }}</a>
+ {% if nav_item == current_page %}
+ <ul>
+ {% for toc_item in toc %}
+ <li class="toctree-l3"><a href="{{ toc_item.url }}">{{ toc_item.title }}</a></li>
+ {% for toc_item in toc_item.children %}
+ <li><a class="toctree-l4" href="{{ toc_item.url }}">{{ toc_item.title }}</a></li>
+ {% endfor %}
{% endfor %}
- {% else %}
- <li class="toctree-l1 {% if nav_item.active%}current{%endif%}">
- <a class="{% if nav_item.active%}current{%endif%}" href="{{ nav_item.url }}">{{ nav_item.title }}</a>
- {% if nav_item == current_page %}
- <ul>
- {% for toc_item in toc %}
- <li class="toctree-l3"><a href="{{ toc_item.url }}">{{ toc_item.title }}</a></li>
- {% for toc_item in toc_item.children %}
- <li><a class="toctree-l4" href="{{ toc_item.url }}">{{ toc_item.title }}</a></li>
- {% endfor %}
- {% endfor %}
- </ul>
- {% endif %}
- </li>
+ </ul>
{% endif %}
-
- {% endfor %}
-</ul>
-
+ </li>
+{% endif %}
| Allow nav links with depth > 2
The default theme doesn't necessarily need to deal with styling them, but they should at least be allowed. | mkdocs/mkdocs | diff --git a/mkdocs/tests/build_tests.py b/mkdocs/tests/build_tests.py
index 784d8925..728b4c7a 100644
--- a/mkdocs/tests/build_tests.py
+++ b/mkdocs/tests/build_tests.py
@@ -84,9 +84,9 @@ class BuildTests(unittest.TestCase):
def test_convert_internal_media(self):
"""Test relative image URL's are the same for different base_urls"""
pages = [
- ('index.md',),
- ('internal.md',),
- ('sub/internal.md')
+ 'index.md',
+ 'internal.md',
+ 'sub/internal.md',
]
site_navigation = nav.SiteNavigation(pages)
@@ -107,9 +107,9 @@ class BuildTests(unittest.TestCase):
def test_convert_internal_asbolute_media(self):
"""Test absolute image URL's are correct for different base_urls"""
pages = [
- ('index.md',),
- ('internal.md',),
- ('sub/internal.md')
+ 'index.md',
+ 'internal.md',
+ 'sub/internal.md',
]
site_navigation = nav.SiteNavigation(pages)
@@ -129,9 +129,9 @@ class BuildTests(unittest.TestCase):
def test_dont_convert_code_block_urls(self):
pages = [
- ('index.md',),
- ('internal.md',),
- ('sub/internal.md')
+ 'index.md',
+ 'internal.md',
+ 'sub/internal.md',
]
site_navigation = nav.SiteNavigation(pages)
@@ -150,9 +150,9 @@ class BuildTests(unittest.TestCase):
def test_anchor_only_link(self):
pages = [
- ('index.md',),
- ('internal.md',),
- ('sub/internal.md')
+ 'index.md',
+ 'internal.md',
+ 'sub/internal.md',
]
site_navigation = nav.SiteNavigation(pages)
@@ -172,7 +172,7 @@ class BuildTests(unittest.TestCase):
md_text = 'An [internal link](internal.md) to another document.'
expected = '<p>An <a href="internal/index.html">internal link</a> to another document.</p>'
pages = [
- ('internal.md',)
+ 'internal.md',
]
site_navigation = nav.SiteNavigation(pages, use_directory_urls=False)
html, toc, meta = build.convert_markdown(md_text, site_navigation=site_navigation)
@@ -297,9 +297,9 @@ class BuildTests(unittest.TestCase):
def test_strict_mode_valid(self):
pages = [
- ('index.md',),
- ('internal.md',),
- ('sub/internal.md')
+ 'index.md',
+ 'internal.md',
+ 'sub/internal.md',
]
site_nav = nav.SiteNavigation(pages)
@@ -309,9 +309,9 @@ class BuildTests(unittest.TestCase):
def test_strict_mode_invalid(self):
pages = [
- ('index.md',),
- ('internal.md',),
- ('sub/internal.md')
+ 'index.md',
+ 'internal.md',
+ 'sub/internal.md',
]
site_nav = nav.SiteNavigation(pages)
diff --git a/mkdocs/tests/config_tests.py b/mkdocs/tests/config_tests.py
index 53d2e915..0687edfe 100644
--- a/mkdocs/tests/config_tests.py
+++ b/mkdocs/tests/config_tests.py
@@ -72,7 +72,7 @@ class ConfigTests(unittest.TestCase):
expected_result = {
'site_name': 'Example',
'pages': [
- ['index.md', 'Introduction']
+ {'Introduction': 'index.md'}
],
}
file_contents = dedent("""
diff --git a/mkdocs/tests/legacy_tests.py b/mkdocs/tests/legacy_tests.py
new file mode 100644
index 00000000..0951fce7
--- /dev/null
+++ b/mkdocs/tests/legacy_tests.py
@@ -0,0 +1,65 @@
+import unittest
+
+import yaml
+
+from mkdocs import legacy
+
+
+class TestCompatabilityShim(unittest.TestCase):
+
+ # TODO: Remove in 1.0
+
+ def test_convert(self):
+
+ self.maxDiff = None
+
+ pages_yaml_old = """
+ pages:
+ - ['index.md', 'Home']
+ - ['user-guide/writing-your-docs.md', 'User Guide']
+ - ['user-guide/styling-your-docs.md', 'User Guide']
+ - ['about/license.md', 'About', 'License']
+ - ['about/release-notes.md', 'About']
+ - ['about/contributing.md', 'About', 'Contributing']
+ - ['help/contributing.md', 'Help', 'Contributing']
+ - ['support.md']
+ - ['cli.md', 'CLI Guide']
+ """
+
+ pages_yaml_new = """
+ pages:
+ - Home: index.md
+ - User Guide:
+ - user-guide/writing-your-docs.md
+ - user-guide/styling-your-docs.md
+ - About:
+ - License: about/license.md
+ - about/release-notes.md
+ - Contributing: about/contributing.md
+ - Help:
+ - Contributing: help/contributing.md
+ - support.md
+ - CLI Guide: cli.md
+ """
+ self.assertEqual(
+ legacy.pages_compat_shim(yaml.load(pages_yaml_old)['pages']),
+ yaml.load(pages_yaml_new)['pages'])
+
+ def test_convert_no_home(self):
+
+ self.maxDiff = None
+
+ pages_yaml_old = """
+ pages:
+ - ['index.md']
+ - ['about.md', 'About']
+ """
+
+ pages_yaml_new = """
+ pages:
+ - index.md
+ - About: about.md
+ """
+ self.assertEqual(
+ legacy.pages_compat_shim(yaml.load(pages_yaml_old)['pages']),
+ yaml.load(pages_yaml_new)['pages'])
diff --git a/mkdocs/tests/nav_tests.py b/mkdocs/tests/nav_tests.py
index 90fc4469..263706a7 100644
--- a/mkdocs/tests/nav_tests.py
+++ b/mkdocs/tests/nav_tests.py
@@ -5,7 +5,7 @@ import mock
import os
import unittest
-from mkdocs import nav
+from mkdocs import nav, legacy
from mkdocs.exceptions import ConfigurationError
from mkdocs.tests.base import dedent
@@ -13,8 +13,8 @@ from mkdocs.tests.base import dedent
class SiteNavigationTests(unittest.TestCase):
def test_simple_toc(self):
pages = [
- ('index.md', 'Home'),
- ('about.md', 'About')
+ {'Home': 'index.md'},
+ {'About': 'about.md'}
]
expected = dedent("""
Home - /
@@ -27,8 +27,8 @@ class SiteNavigationTests(unittest.TestCase):
def test_empty_toc_item(self):
pages = [
- ('index.md',),
- ('about.md', 'About')
+ 'index.md',
+ {'About': 'about.md'}
]
expected = dedent("""
Home - /
@@ -41,36 +41,16 @@ class SiteNavigationTests(unittest.TestCase):
def test_indented_toc(self):
pages = [
- ('index.md', 'Home'),
- ('api-guide/running.md', 'API Guide', 'Running'),
- ('api-guide/testing.md', 'API Guide', 'Testing'),
- ('api-guide/debugging.md', 'API Guide', 'Debugging'),
- ('about/release-notes.md', 'About', 'Release notes'),
- ('about/license.md', 'About', 'License')
- ]
- expected = dedent("""
- Home - /
- API Guide
- Running - /api-guide/running/
- Testing - /api-guide/testing/
- Debugging - /api-guide/debugging/
- About
- Release notes - /about/release-notes/
- License - /about/license/
- """)
- site_navigation = nav.SiteNavigation(pages)
- self.assertEqual(str(site_navigation).strip(), expected)
- self.assertEqual(len(site_navigation.nav_items), 3)
- self.assertEqual(len(site_navigation.pages), 6)
-
- def test_indented_toc_missing_child_title(self):
- pages = [
- ('index.md', 'Home'),
- ('api-guide/running.md', 'API Guide', 'Running'),
- ('api-guide/testing.md', 'API Guide'),
- ('api-guide/debugging.md', 'API Guide', 'Debugging'),
- ('about/release-notes.md', 'About', 'Release notes'),
- ('about/license.md', 'About', 'License')
+ {'Home': 'index.md'},
+ {'API Guide': [
+ {'Running': 'api-guide/running.md'},
+ {'Testing': 'api-guide/testing.md'},
+ {'Debugging': 'api-guide/debugging.md'},
+ ]},
+ {'About': [
+ {'Release notes': 'about/release-notes.md'},
+ {'License': 'about/license.md'}
+ ]}
]
expected = dedent("""
Home - /
@@ -89,9 +69,9 @@ class SiteNavigationTests(unittest.TestCase):
def test_nested_ungrouped(self):
pages = [
- ('index.md', 'Home'),
- ('about/contact.md', 'Contact'),
- ('about/sub/license.md', 'License Title')
+ {'Home': 'index.md'},
+ {'Contact': 'about/contact.md'},
+ {'License Title': 'about/sub/license.md'},
]
expected = dedent("""
Home - /
@@ -105,45 +85,43 @@ class SiteNavigationTests(unittest.TestCase):
def test_nested_ungrouped_no_titles(self):
pages = [
- ('index.md',),
- ('about/contact.md'),
- ('about/sub/license.md')
+ 'index.md',
+ 'about/contact.md',
+ 'about/sub/license.md'
]
expected = dedent("""
Home - /
- About
- Contact - /about/contact/
- License - /about/sub/license/
+ Contact - /about/contact/
+ License - /about/sub/license/
""")
site_navigation = nav.SiteNavigation(pages)
self.assertEqual(str(site_navigation).strip(), expected)
- self.assertEqual(len(site_navigation.nav_items), 2)
+ self.assertEqual(len(site_navigation.nav_items), 3)
self.assertEqual(len(site_navigation.pages), 3)
@mock.patch.object(os.path, 'sep', '\\')
def test_nested_ungrouped_no_titles_windows(self):
pages = [
- ('index.md',),
- ('about\\contact.md'),
- ('about\\sub\\license.md')
+ 'index.md',
+ 'about\\contact.md',
+ 'about\\sub\\license.md',
]
expected = dedent("""
Home - /
- About
- Contact - /about/contact/
- License - /about/sub/license/
+ Contact - /about/contact/
+ License - /about/sub/license/
""")
site_navigation = nav.SiteNavigation(pages)
self.assertEqual(str(site_navigation).strip(), expected)
- self.assertEqual(len(site_navigation.nav_items), 2)
+ self.assertEqual(len(site_navigation.nav_items), 3)
self.assertEqual(len(site_navigation.pages), 3)
def test_walk_simple_toc(self):
pages = [
- ('index.md', 'Home'),
- ('about.md', 'About')
+ {'Home': 'index.md'},
+ {'About': 'about.md'}
]
expected = [
dedent("""
@@ -161,8 +139,8 @@ class SiteNavigationTests(unittest.TestCase):
def test_walk_empty_toc(self):
pages = [
- ('index.md',),
- ('about.md', 'About')
+ 'index.md',
+ {'About': 'about.md'}
]
expected = [
dedent("""
@@ -180,12 +158,16 @@ class SiteNavigationTests(unittest.TestCase):
def test_walk_indented_toc(self):
pages = [
- ('index.md', 'Home'),
- ('api-guide/running.md', 'API Guide', 'Running'),
- ('api-guide/testing.md', 'API Guide', 'Testing'),
- ('api-guide/debugging.md', 'API Guide', 'Debugging'),
- ('about/release-notes.md', 'About', 'Release notes'),
- ('about/license.md', 'About', 'License')
+ {'Home': 'index.md'},
+ {'API Guide': [
+ {'Running': 'api-guide/running.md'},
+ {'Testing': 'api-guide/testing.md'},
+ {'Debugging': 'api-guide/debugging.md'},
+ ]},
+ {'About': [
+ {'Release notes': 'about/release-notes.md'},
+ {'License': 'about/license.md'}
+ ]}
]
expected = [
dedent("""
@@ -255,7 +237,7 @@ class SiteNavigationTests(unittest.TestCase):
def test_base_url(self):
pages = [
- ('index.md',)
+ 'index.md'
]
site_navigation = nav.SiteNavigation(pages, use_directory_urls=False)
base_url = site_navigation.url_context.make_relative('/')
@@ -263,8 +245,8 @@ class SiteNavigationTests(unittest.TestCase):
def test_relative_md_links_have_slash(self):
pages = [
- ('index.md',),
- ('user-guide/styling-your-docs.md',)
+ 'index.md',
+ 'user-guide/styling-your-docs.md'
]
site_navigation = nav.SiteNavigation(pages, use_directory_urls=False)
site_navigation.url_context.base_path = "/user-guide/configuration"
@@ -277,17 +259,17 @@ class SiteNavigationTests(unittest.TestCase):
"""
pages = [
- ('index.md', ),
- ('api-guide/running.md', ),
- ('about/notes.md', ),
- ('about/sub/license.md', ),
+ 'index.md',
+ 'api-guide/running.md',
+ 'about/notes.md',
+ 'about/sub/license.md',
]
url_context = nav.URLContext()
nav_items, pages = nav._generate_site_navigation(pages, url_context)
self.assertEqual([n.title for n in nav_items],
- ['Home', 'Api guide', 'About'])
+ ['Home', 'Running', 'Notes', 'License'])
self.assertEqual([p.title for p in pages],
['Home', 'Running', 'Notes', 'License'])
@@ -297,25 +279,25 @@ class SiteNavigationTests(unittest.TestCase):
Verify inferring page titles based on the filename with a windows path
"""
pages = [
- ('index.md', ),
- ('api-guide\\running.md', ),
- ('about\\notes.md', ),
- ('about\\sub\\license.md', ),
+ 'index.md',
+ 'api-guide\\running.md',
+ 'about\\notes.md',
+ 'about\\sub\\license.md',
]
url_context = nav.URLContext()
nav_items, pages = nav._generate_site_navigation(pages, url_context)
self.assertEqual([n.title for n in nav_items],
- ['Home', 'Api guide', 'About'])
+ ['Home', 'Running', 'Notes', 'License'])
self.assertEqual([p.title for p in pages],
['Home', 'Running', 'Notes', 'License'])
def test_invalid_pages_config(self):
bad_pages = [
- (), # too short
- ('this', 'is', 'too', 'long'),
+ set(), # should be dict or string only
+ {"a": "index.md", "b": "index.md"} # extra key
]
for bad_page in bad_pages:
@@ -325,15 +307,28 @@ class SiteNavigationTests(unittest.TestCase):
self.assertRaises(ConfigurationError, _test)
+ def test_pages_config(self):
+
+ bad_page = {} # empty
+
+ def _test():
+ return nav._generate_site_navigation((bad_page, ), None)
+
+ self.assertRaises(ConfigurationError, _test)
+
def test_ancestors(self):
pages = [
- ('index.md', 'Home'),
- ('api-guide/running.md', 'API Guide', 'Running'),
- ('api-guide/testing.md', 'API Guide', 'Testing'),
- ('api-guide/debugging.md', 'API Guide', 'Debugging'),
- ('about/release-notes.md', 'About', 'Release notes'),
- ('about/license.md', 'About', 'License')
+ {'Home': 'index.md'},
+ {'API Guide': [
+ {'Running': 'api-guide/running.md'},
+ {'Testing': 'api-guide/testing.md'},
+ {'Debugging': 'api-guide/debugging.md'},
+ ]},
+ {'About': [
+ {'Release notes': 'about/release-notes.md'},
+ {'License': 'about/license.md'}
+ ]}
]
site_navigation = nav.SiteNavigation(pages)
@@ -361,3 +356,197 @@ class SiteNavigationTests(unittest.TestCase):
title = nav.file_to_title("mkdocs/tests/resources/no_title_metadata.md")
self.assertEqual(title, "Title")
+
+ def test_nesting(self):
+
+ pages_config = [
+ {'Home': 'index.md'},
+ {'Install': [
+ {'Pre-install': 'install/install-pre.md'},
+ {'The install': 'install/install-actual.md'},
+ {'Post install': 'install/install-post.md'},
+ ]},
+ {'Guide': [
+ {'Tutorial': [
+ {'Getting Started': 'guide/tutorial/running.md'},
+ {'Advanced Features': 'guide/tutorial/testing.md'},
+ {'Further Reading': 'guide/tutorial/debugging.md'},
+ ]},
+ {'API Reference': [
+ {'Feature 1': 'guide/api-ref/running.md'},
+ {'Feature 2': 'guide/api-ref/testing.md'},
+ {'Feature 3': 'guide/api-ref/debugging.md'},
+ ]},
+ {'Testing': 'guide/testing.md'},
+ {'Deploying': 'guide/deploying.md'},
+ ]}
+ ]
+
+ site_navigation = nav.SiteNavigation(pages_config)
+
+ self.assertEqual([n.title for n in site_navigation.nav_items],
+ ['Home', 'Install', 'Guide'])
+ self.assertEqual(len(site_navigation.pages), 12)
+
+ expected = dedent("""
+ Home - /
+ Install
+ Pre-install - /install/install-pre/
+ The install - /install/install-actual/
+ Post install - /install/install-post/
+ Guide
+ Tutorial
+ Getting Started - /guide/tutorial/running/
+ Advanced Features - /guide/tutorial/testing/
+ Further Reading - /guide/tutorial/debugging/
+ API Reference
+ Feature 1 - /guide/api-ref/running/
+ Feature 2 - /guide/api-ref/testing/
+ Feature 3 - /guide/api-ref/debugging/
+ Testing - /guide/testing/
+ Deploying - /guide/deploying/
+ """)
+
+ self.maxDiff = None
+ self.assertEqual(str(site_navigation).strip(), expected)
+
+
+class TestLegacyPagesConfig(unittest.TestCase):
+
+ def test_walk_simple_toc(self):
+ pages = legacy.pages_compat_shim([
+ ('index.md', 'Home'),
+ ('about.md', 'About')
+ ])
+ expected = [
+ dedent("""
+ Home - / [*]
+ About - /about/
+ """),
+ dedent("""
+ Home - /
+ About - /about/ [*]
+ """)
+ ]
+ site_navigation = nav.SiteNavigation(pages)
+ for index, page in enumerate(site_navigation.walk_pages()):
+ self.assertEqual(str(site_navigation).strip(), expected[index])
+
+ def test_walk_empty_toc(self):
+ pages = legacy.pages_compat_shim([
+ ('index.md',),
+ ('about.md', 'About')
+ ])
+
+ expected = [
+ dedent("""
+ Home - / [*]
+ About - /about/
+ """),
+ dedent("""
+ Home - /
+ About - /about/ [*]
+ """)
+ ]
+ site_navigation = nav.SiteNavigation(pages)
+ for index, page in enumerate(site_navigation.walk_pages()):
+ self.assertEqual(str(site_navigation).strip(), expected[index])
+
+ def test_walk_indented_toc(self):
+ pages = legacy.pages_compat_shim([
+ ('index.md', 'Home'),
+ ('api-guide/running.md', 'API Guide', 'Running'),
+ ('api-guide/testing.md', 'API Guide', 'Testing'),
+ ('api-guide/debugging.md', 'API Guide', 'Debugging'),
+ ('about/release-notes.md', 'About', 'Release notes'),
+ ('about/license.md', 'About', 'License')
+ ])
+ expected = [
+ dedent("""
+ Home - / [*]
+ API Guide
+ Running - /api-guide/running/
+ Testing - /api-guide/testing/
+ Debugging - /api-guide/debugging/
+ About
+ Release notes - /about/release-notes/
+ License - /about/license/
+ """),
+ dedent("""
+ Home - /
+ API Guide [*]
+ Running - /api-guide/running/ [*]
+ Testing - /api-guide/testing/
+ Debugging - /api-guide/debugging/
+ About
+ Release notes - /about/release-notes/
+ License - /about/license/
+ """),
+ dedent("""
+ Home - /
+ API Guide [*]
+ Running - /api-guide/running/
+ Testing - /api-guide/testing/ [*]
+ Debugging - /api-guide/debugging/
+ About
+ Release notes - /about/release-notes/
+ License - /about/license/
+ """),
+ dedent("""
+ Home - /
+ API Guide [*]
+ Running - /api-guide/running/
+ Testing - /api-guide/testing/
+ Debugging - /api-guide/debugging/ [*]
+ About
+ Release notes - /about/release-notes/
+ License - /about/license/
+ """),
+ dedent("""
+ Home - /
+ API Guide
+ Running - /api-guide/running/
+ Testing - /api-guide/testing/
+ Debugging - /api-guide/debugging/
+ About [*]
+ Release notes - /about/release-notes/ [*]
+ License - /about/license/
+ """),
+ dedent("""
+ Home - /
+ API Guide
+ Running - /api-guide/running/
+ Testing - /api-guide/testing/
+ Debugging - /api-guide/debugging/
+ About [*]
+ Release notes - /about/release-notes/
+ License - /about/license/ [*]
+ """)
+ ]
+ site_navigation = nav.SiteNavigation(pages)
+ for index, page in enumerate(site_navigation.walk_pages()):
+ self.assertEqual(str(site_navigation).strip(), expected[index])
+
+ def test_indented_toc_missing_child_title(self):
+ pages = legacy.pages_compat_shim([
+ ('index.md', 'Home'),
+ ('api-guide/running.md', 'API Guide', 'Running'),
+ ('api-guide/testing.md', 'API Guide'),
+ ('api-guide/debugging.md', 'API Guide', 'Debugging'),
+ ('about/release-notes.md', 'About', 'Release notes'),
+ ('about/license.md', 'About', 'License')
+ ])
+ expected = dedent("""
+ Home - /
+ API Guide
+ Running - /api-guide/running/
+ Testing - /api-guide/testing/
+ Debugging - /api-guide/debugging/
+ About
+ Release notes - /about/release-notes/
+ License - /about/license/
+ """)
+ site_navigation = nav.SiteNavigation(pages)
+ self.assertEqual(str(site_navigation).strip(), expected)
+ self.assertEqual(len(site_navigation.nav_items), 3)
+ self.assertEqual(len(site_navigation.pages), 6)
diff --git a/mkdocs/tests/search_tests.py b/mkdocs/tests/search_tests.py
index c53f40b6..182f2693 100644
--- a/mkdocs/tests/search_tests.py
+++ b/mkdocs/tests/search_tests.py
@@ -103,8 +103,8 @@ class SearchTests(unittest.TestCase):
"""
pages = [
- ('index.md', 'Home'),
- ('about.md', 'About')
+ {'Home': 'index.md'},
+ {'About': 'about.md'},
]
site_navigation = nav.SiteNavigation(pages)
diff --git a/mkdocs/tests/utils_tests.py b/mkdocs/tests/utils_tests.py
index 23da4e07..e2854187 100644
--- a/mkdocs/tests/utils_tests.py
+++ b/mkdocs/tests/utils_tests.py
@@ -54,8 +54,8 @@ class UtilsTests(unittest.TestCase):
def test_create_media_urls(self):
pages = [
- ('index.md', 'Home'),
- ('about.md', 'About')
+ {'Home': 'index.md'},
+ {'About': 'about.md'}
]
expected_results = {
'https://media.cdn.org/jq.js': 'https://media.cdn.org/jq.js',
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_short_problem_statement",
"has_added_files",
"has_many_modified_files",
"has_many_hunks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 2,
"issue_text_score": 0,
"test_score": 2
},
"num_modified_files": 11
} | 0.12 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[dev]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest",
"pytest-cov",
"pytest-xdist",
"pytest-mock",
"pytest-asyncio",
"mock"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.9",
"reqs_path": [
"requirements/project.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | click==8.1.8
coverage==7.8.0
exceptiongroup==1.2.2
execnet==2.1.1
ghp-import==2.1.0
importlib_metadata==8.6.1
iniconfig==2.1.0
Jinja2==3.1.6
livereload==2.7.1
Markdown==3.7
MarkupSafe==3.0.2
-e git+https://github.com/mkdocs/mkdocs.git@1a0dfb5ee3d5dd290da9c8c03b0946e784aa6959#egg=mkdocs
mock==5.2.0
packaging==24.2
pluggy==1.5.0
pytest==8.3.5
pytest-asyncio==0.26.0
pytest-cov==6.0.0
pytest-mock==3.14.0
pytest-xdist==3.6.1
python-dateutil==2.9.0.post0
PyYAML==6.0.2
six==1.17.0
tomli==2.2.1
tornado==6.4.2
typing_extensions==4.13.0
zipp==3.21.0
| name: mkdocs
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=3.0.16=h5eee18b_0
- pip=25.0=py39h06a4308_0
- python=3.9.21=he870216_1
- readline=8.2=h5eee18b_0
- setuptools=75.8.0=py39h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- tzdata=2025a=h04d1e81_0
- wheel=0.45.1=py39h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- click==8.1.8
- coverage==7.8.0
- exceptiongroup==1.2.2
- execnet==2.1.1
- ghp-import==2.1.0
- importlib-metadata==8.6.1
- iniconfig==2.1.0
- jinja2==3.1.6
- livereload==2.7.1
- markdown==3.7
- markupsafe==3.0.2
- mock==5.2.0
- packaging==24.2
- pluggy==1.5.0
- pytest==8.3.5
- pytest-asyncio==0.26.0
- pytest-cov==6.0.0
- pytest-mock==3.14.0
- pytest-xdist==3.6.1
- python-dateutil==2.9.0.post0
- pyyaml==6.0.2
- six==1.17.0
- tomli==2.2.1
- tornado==6.4.2
- typing-extensions==4.13.0
- zipp==3.21.0
prefix: /opt/conda/envs/mkdocs
| [
"mkdocs/tests/config_tests.py::ConfigTests::test_config_option",
"mkdocs/tests/config_tests.py::ConfigTests::test_default_pages",
"mkdocs/tests/config_tests.py::ConfigTests::test_doc_dir_in_site_dir",
"mkdocs/tests/config_tests.py::ConfigTests::test_empty_config",
"mkdocs/tests/config_tests.py::ConfigTests::test_invalid_config",
"mkdocs/tests/config_tests.py::ConfigTests::test_missing_config_file",
"mkdocs/tests/config_tests.py::ConfigTests::test_missing_site_name",
"mkdocs/tests/config_tests.py::ConfigTests::test_nonexistant_config",
"mkdocs/tests/config_tests.py::ConfigTests::test_theme",
"mkdocs/tests/nav_tests.py::SiteNavigationTests::test_file_to_tile",
"mkdocs/tests/nav_tests.py::SiteNavigationTests::test_invalid_pages_config",
"mkdocs/tests/search_tests.py::SearchTests::test_content_parser",
"mkdocs/tests/search_tests.py::SearchTests::test_content_parser_content_before_header",
"mkdocs/tests/search_tests.py::SearchTests::test_content_parser_no_id",
"mkdocs/tests/search_tests.py::SearchTests::test_content_parser_no_sections",
"mkdocs/tests/search_tests.py::SearchTests::test_find_toc_by_id",
"mkdocs/tests/search_tests.py::SearchTests::test_html_stripper",
"mkdocs/tests/utils_tests.py::UtilsTests::test_get_themes",
"mkdocs/tests/utils_tests.py::UtilsTests::test_html_path",
"mkdocs/tests/utils_tests.py::UtilsTests::test_is_html_file",
"mkdocs/tests/utils_tests.py::UtilsTests::test_is_markdown_file",
"mkdocs/tests/utils_tests.py::UtilsTests::test_reduce_list",
"mkdocs/tests/utils_tests.py::UtilsTests::test_url_path",
"mkdocs/tests/utils_tests.py::UtilsTests::test_yaml_load"
] | [
"mkdocs/tests/build_tests.py::BuildTests::test_anchor_only_link",
"mkdocs/tests/build_tests.py::BuildTests::test_convert_internal_asbolute_media",
"mkdocs/tests/build_tests.py::BuildTests::test_convert_internal_link",
"mkdocs/tests/build_tests.py::BuildTests::test_convert_internal_link_differing_directory",
"mkdocs/tests/build_tests.py::BuildTests::test_convert_internal_link_with_anchor",
"mkdocs/tests/build_tests.py::BuildTests::test_convert_internal_media",
"mkdocs/tests/build_tests.py::BuildTests::test_convert_markdown",
"mkdocs/tests/build_tests.py::BuildTests::test_convert_multiple_internal_links",
"mkdocs/tests/build_tests.py::BuildTests::test_copying_media",
"mkdocs/tests/build_tests.py::BuildTests::test_dont_convert_code_block_urls",
"mkdocs/tests/build_tests.py::BuildTests::test_empty_document",
"mkdocs/tests/build_tests.py::BuildTests::test_extension_config",
"mkdocs/tests/build_tests.py::BuildTests::test_ignore_external_link",
"mkdocs/tests/build_tests.py::BuildTests::test_markdown_custom_extension",
"mkdocs/tests/build_tests.py::BuildTests::test_markdown_duplicate_custom_extension",
"mkdocs/tests/build_tests.py::BuildTests::test_markdown_fenced_code_extension",
"mkdocs/tests/build_tests.py::BuildTests::test_markdown_table_extension",
"mkdocs/tests/build_tests.py::BuildTests::test_not_use_directory_urls",
"mkdocs/tests/build_tests.py::BuildTests::test_strict_mode_invalid",
"mkdocs/tests/build_tests.py::BuildTests::test_strict_mode_valid",
"mkdocs/tests/legacy_tests.py::TestCompatabilityShim::test_convert",
"mkdocs/tests/legacy_tests.py::TestCompatabilityShim::test_convert_no_home",
"mkdocs/tests/nav_tests.py::SiteNavigationTests::test_ancestors",
"mkdocs/tests/nav_tests.py::SiteNavigationTests::test_base_url",
"mkdocs/tests/nav_tests.py::SiteNavigationTests::test_empty_toc_item",
"mkdocs/tests/nav_tests.py::SiteNavigationTests::test_generate_site_navigation",
"mkdocs/tests/nav_tests.py::SiteNavigationTests::test_generate_site_navigation_windows",
"mkdocs/tests/nav_tests.py::SiteNavigationTests::test_indented_toc",
"mkdocs/tests/nav_tests.py::SiteNavigationTests::test_nested_ungrouped",
"mkdocs/tests/nav_tests.py::SiteNavigationTests::test_nested_ungrouped_no_titles",
"mkdocs/tests/nav_tests.py::SiteNavigationTests::test_nested_ungrouped_no_titles_windows",
"mkdocs/tests/nav_tests.py::SiteNavigationTests::test_nesting",
"mkdocs/tests/nav_tests.py::SiteNavigationTests::test_pages_config",
"mkdocs/tests/nav_tests.py::SiteNavigationTests::test_relative_md_links_have_slash",
"mkdocs/tests/nav_tests.py::SiteNavigationTests::test_simple_toc",
"mkdocs/tests/nav_tests.py::SiteNavigationTests::test_walk_empty_toc",
"mkdocs/tests/nav_tests.py::SiteNavigationTests::test_walk_indented_toc",
"mkdocs/tests/nav_tests.py::SiteNavigationTests::test_walk_simple_toc",
"mkdocs/tests/nav_tests.py::TestLegacyPagesConfig::test_indented_toc_missing_child_title",
"mkdocs/tests/nav_tests.py::TestLegacyPagesConfig::test_walk_empty_toc",
"mkdocs/tests/nav_tests.py::TestLegacyPagesConfig::test_walk_indented_toc",
"mkdocs/tests/nav_tests.py::TestLegacyPagesConfig::test_walk_simple_toc",
"mkdocs/tests/search_tests.py::SearchTests::test_create_search_index",
"mkdocs/tests/utils_tests.py::UtilsTests::test_create_media_urls"
] | [] | [] | BSD 2-Clause "Simplified" License | 111 |
google__yapf-131 | 5e7c8aadfe6ed7d892e858b305ef2ca60c65bfcc | 2015-04-27 19:32:21 | 5e7c8aadfe6ed7d892e858b305ef2ca60c65bfcc | coveralls:
[](https://coveralls.io/builds/2434186)
Coverage decreased (-0.2%) to 91.89% when pulling **53c06d00461e35cfd3ae9a27cecc7dcc9d0912f0 on sbc100:handle_errors** into **8c7840c8b835568116219e9d960764198add4927 on google:master**.
| diff --git a/yapf/__init__.py b/yapf/__init__.py
index 7634c5c..7ffdfee 100644
--- a/yapf/__init__.py
+++ b/yapf/__init__.py
@@ -32,6 +32,7 @@ import logging
import os
import sys
+from yapf.yapflib import errors
from yapf.yapflib import file_resources
from yapf.yapflib import py3compat
from yapf.yapflib import style
@@ -40,10 +41,6 @@ from yapf.yapflib import yapf_api
__version__ = '0.1.7'
-class YapfError(Exception):
- pass
-
-
def main(argv):
"""Main program.
@@ -147,7 +144,7 @@ def main(argv):
files = file_resources.GetCommandLineFiles(args.files, args.recursive)
if not files:
- raise YapfError('Input filenames did not match any python files')
+ raise errors.YapfError('Input filenames did not match any python files')
FormatFiles(files, lines,
style_config=args.style,
no_local_style=args.no_local_style,
@@ -213,15 +210,19 @@ def _GetLines(line_strings):
# The 'list' here is needed by Python 3.
line = list(map(int, line_string.split('-', 1)))
if line[0] < 1:
- raise ValueError('invalid start of line range: %r' % line)
+ raise errors.YapfError('invalid start of line range: %r' % line)
if line[0] > line[1]:
- raise ValueError('end comes before start in line range: %r', line)
+ raise errors.YapfError('end comes before start in line range: %r', line)
lines.append(tuple(line))
return lines
def run_main(): # pylint: disable=invalid-name
- sys.exit(main(sys.argv))
+ try:
+ sys.exit(main(sys.argv))
+ except errors.YapfError as e:
+ sys.stderr.write('yapf: ' + str(e) + '\n')
+ sys.exit(1)
if __name__ == '__main__':
diff --git a/yapf/yapflib/__init__.py b/yapf/yapflib/__init__.py
index e7522b2..f526bc3 100644
--- a/yapf/yapflib/__init__.py
+++ b/yapf/yapflib/__init__.py
@@ -11,3 +11,4 @@
# 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.
+
diff --git a/yapf/yapflib/errors.py b/yapf/yapflib/errors.py
new file mode 100644
index 0000000..1bf5bc7
--- /dev/null
+++ b/yapf/yapflib/errors.py
@@ -0,0 +1,22 @@
+# Copyright 2015 Google Inc. 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.
+
+
+class YapfError(Exception):
+ """Parent class for user errors or input errors.
+
+ Exceptions of this type are handled by the command line tool
+ and result in clear error messages, as opposed to backtraces.
+ """
+ pass
diff --git a/yapf/yapflib/style.py b/yapf/yapflib/style.py
index 7d1ecbb..518ace8 100644
--- a/yapf/yapflib/style.py
+++ b/yapf/yapflib/style.py
@@ -18,13 +18,10 @@ import re
import textwrap
from yapf.yapflib import py3compat
+from yapf.yapflib import errors
-class Error(Exception):
- pass
-
-
-class StyleConfigError(Error):
+class StyleConfigError(errors.YapfError):
"""Raised when there's a problem reading the style configuration."""
pass
| yapf crashes with misggin style (e.g. --style=foo)
I've got a fix for this that I will send a PR for.
This is the crash:
```
PYTHONPATH=$PWD/yapf python -m yapf --style=foo -i -r .
Traceback (most recent call last):
File "/usr/lib/python2.7/runpy.py", line 162, in _run_module_as_main
"__main__", fname, loader, pkg_name)
File "/usr/lib/python2.7/runpy.py", line 72, in _run_code
exec code in run_globals
File "/usr/local/google/home/sbc/dev/yapf/yapf/__main__.py", line 16, in <module>
yapf.run_main()
File "yapf/__init__.py", line 209, in run_main
sys.exit(main(sys.argv))
File "yapf/__init__.py", line 146, in main
verify=args.verify)
File "yapf/__init__.py", line 174, in FormatFiles
print_diff=print_diff, verify=verify)
File "yapf/yapflib/yapf_api.py", line 78, in FormatFile
verify=verify), encoding
File "yapf/yapflib/yapf_api.py", line 100, in FormatCode
style.SetGlobalStyle(style.CreateStyleFromConfig(style_config))
File "yapf/yapflib/style.py", line 212, in CreateStyleFromConfig
config = _CreateConfigParserFromConfigFile(style_config)
File "yapf/yapflib/style.py", line 234, in _CreateConfigParserFromConfigFile
'"{0}" is not a valid style or file path'.format(config_filename))
yapf.yapflib.style.StyleConfigError: "foo" is not a valid style or file path
```
| google/yapf | diff --git a/yapftests/main_test.py b/yapftests/main_test.py
index 314dcba..e216d67 100644
--- a/yapftests/main_test.py
+++ b/yapftests/main_test.py
@@ -57,10 +57,23 @@ def patched_input(code):
yapf.py3compat.raw_input = raw_input
+class RunMainTest(unittest.TestCase):
+
+ def testShouldHandleYapfError(self):
+ """run_main should handle YapfError and sys.exit(1)"""
+ expected_message = 'yapf: Input filenames did not match any python files\n'
+ sys.argv = ['yapf', 'foo.c']
+ with captured_output() as (out, err):
+ with self.assertRaises(SystemExit):
+ ret = yapf.run_main()
+ self.assertEqual(out.getvalue(), '')
+ self.assertEqual(err.getvalue(), expected_message)
+
+
class MainTest(unittest.TestCase):
def testNoPythonFilesMatched(self):
- with self.assertRaisesRegexp(yapf.YapfError,
+ with self.assertRaisesRegexp(yapf.errors.YapfError,
'did not match any python files'):
yapf.main(['yapf', 'foo.c'])
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_added_files",
"has_many_modified_files",
"has_many_hunks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 1,
"issue_text_score": 1,
"test_score": 2
},
"num_modified_files": 3
} | 0.1 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[dev]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "pytest",
"pip_packages": [
"pytest"
],
"pre_install": null,
"python": "3.9",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | exceptiongroup @ file:///croot/exceptiongroup_1706031385326/work
iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work
packaging @ file:///croot/packaging_1734472117206/work
pluggy @ file:///croot/pluggy_1733169602837/work
pytest @ file:///croot/pytest_1738938843180/work
tomli @ file:///opt/conda/conda-bld/tomli_1657175507142/work
-e git+https://github.com/google/yapf.git@5e7c8aadfe6ed7d892e858b305ef2ca60c65bfcc#egg=yapf
| name: yapf
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- exceptiongroup=1.2.0=py39h06a4308_0
- iniconfig=1.1.1=pyhd3eb1b0_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=3.0.16=h5eee18b_0
- packaging=24.2=py39h06a4308_0
- pip=25.0=py39h06a4308_0
- pluggy=1.5.0=py39h06a4308_0
- pytest=8.3.4=py39h06a4308_0
- python=3.9.21=he870216_1
- readline=8.2=h5eee18b_0
- setuptools=75.8.0=py39h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- tomli=2.0.1=py39h06a4308_0
- tzdata=2025a=h04d1e81_0
- wheel=0.45.1=py39h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
prefix: /opt/conda/envs/yapf
| [
"yapftests/main_test.py::RunMainTest::testShouldHandleYapfError",
"yapftests/main_test.py::MainTest::testNoPythonFilesMatched"
] | [] | [
"yapftests/main_test.py::MainTest::testEchoBadInput",
"yapftests/main_test.py::MainTest::testEchoInput",
"yapftests/main_test.py::MainTest::testEchoInputWithStyle",
"yapftests/main_test.py::MainTest::testHelp",
"yapftests/main_test.py::MainTest::testVersion"
] | [] | Apache License 2.0 | 112 |
softlayer__softlayer-python-537 | f6722dcb5dc6021cd813280a789fd39e81053da0 | 2015-04-28 02:21:51 | 1195b2020ef6efc40462d59eb079f26e5f39a6d8 | landscape-bot: [](https://landscape.io/diff/140430)
Code quality remained the same when pulling **[4a1754c](https://github.com/sudorandom/softlayer-python/commit/4a1754cc1ec2498205c7a24f66e4a883ab705e70) on sudorandom:issue-536** into **[f6722dc](https://github.com/softlayer/softlayer-python/commit/f6722dcb5dc6021cd813280a789fd39e81053da0) on softlayer:master**. | diff --git a/SoftLayer/CLI/server/list.py b/SoftLayer/CLI/server/list.py
index dec63ee5..03ba456e 100644
--- a/SoftLayer/CLI/server/list.py
+++ b/SoftLayer/CLI/server/list.py
@@ -41,7 +41,7 @@ def cli(env, sortby, cpu, domain, datacenter, hostname, memory, network, tag):
tags=tag)
table = formatting.Table([
- 'guid',
+ 'id',
'hostname',
'primary_ip',
'backend_ip',
@@ -51,10 +51,8 @@ def cli(env, sortby, cpu, domain, datacenter, hostname, memory, network, tag):
table.sortby = sortby or 'hostname'
for server in servers:
- # NOTE(kmcdonald): There are cases where a server might not have a
- # globalIdentifier or hostname.
table.add_row([
- utils.lookup(server, 'globalIdentifier') or server['id'],
+ utils.lookup(server, 'id'),
utils.lookup(server, 'hostname') or formatting.blank(),
utils.lookup(server, 'primaryIpAddress') or formatting.blank(),
utils.lookup(server, 'primaryBackendIpAddress') or
diff --git a/SoftLayer/CLI/virt/list.py b/SoftLayer/CLI/virt/list.py
index 8419f02a..8b92acc1 100644
--- a/SoftLayer/CLI/virt/list.py
+++ b/SoftLayer/CLI/virt/list.py
@@ -50,7 +50,7 @@ def cli(env, sortby, cpu, domain, datacenter, hostname, memory, network,
tags=tag_list)
table = formatting.Table([
- 'guid',
+ 'id',
'hostname',
'primary_ip',
'backend_ip',
@@ -61,7 +61,7 @@ def cli(env, sortby, cpu, domain, datacenter, hostname, memory, network,
for guest in guests:
table.add_row([
- utils.lookup(guest, 'globalIdentifier') or guest['id'],
+ utils.lookup(guest, 'id'),
utils.lookup(guest, 'hostname') or formatting.blank(),
utils.lookup(guest, 'primaryIpAddress') or formatting.blank(),
utils.lookup(guest, 'primaryBackendIpAddress') or
| ID > GUID
Switch the default display to use an object's ID rather than its GUID. Also use the ID rather than the GUID during confirmation text entries. | softlayer/softlayer-python | diff --git a/SoftLayer/tests/CLI/modules/server_tests.py b/SoftLayer/tests/CLI/modules/server_tests.py
index acbab824..a65538cf 100644
--- a/SoftLayer/tests/CLI/modules/server_tests.py
+++ b/SoftLayer/tests/CLI/modules/server_tests.py
@@ -65,7 +65,7 @@ def test_list_servers(self):
'datacenter': 'TEST00',
'primary_ip': '172.16.1.100',
'hostname': 'hardware-test1',
- 'guid': '1a2b3c-1701',
+ 'id': 1000,
'backend_ip': '10.1.0.2',
'action': 'TXN_NAME',
},
@@ -73,7 +73,7 @@ def test_list_servers(self):
'datacenter': 'TEST00',
'primary_ip': '172.16.4.94',
'hostname': 'hardware-test2',
- 'guid': '1a2b3c-1702',
+ 'id': 1001,
'backend_ip': '10.1.0.3',
'action': None,
},
@@ -81,7 +81,7 @@ def test_list_servers(self):
'datacenter': 'TEST00',
'primary_ip': '172.16.4.95',
'hostname': 'hardware-bad-memory',
- 'guid': 1002,
+ 'id': 1002,
'backend_ip': '10.1.0.4',
'action': None,
}
diff --git a/SoftLayer/tests/CLI/modules/vs_tests.py b/SoftLayer/tests/CLI/modules/vs_tests.py
index 75459ff0..9c1064bd 100644
--- a/SoftLayer/tests/CLI/modules/vs_tests.py
+++ b/SoftLayer/tests/CLI/modules/vs_tests.py
@@ -22,13 +22,13 @@ def test_list_vs(self):
'primary_ip': '172.16.240.2',
'hostname': 'vs-test1',
'action': None,
- 'guid': '1a2b3c-1701',
+ 'id': 100,
'backend_ip': '10.45.19.37'},
{'datacenter': 'TEST00',
'primary_ip': '172.16.240.7',
'hostname': 'vs-test2',
'action': None,
- 'guid': '05a8ac-6abf0',
+ 'id': 104,
'backend_ip': '10.45.19.35'}])
def test_detail_vs(self):
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 0,
"issue_text_score": 2,
"test_score": 0
},
"num_modified_files": 2
} | 4.0 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[dev]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.6",
"reqs_path": [
"tools/test-requirements.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | alabaster==0.7.13
attrs==22.2.0
Babel==2.11.0
certifi==2021.5.30
charset-normalizer==2.0.12
click==8.0.4
coverage==6.2
distlib==0.3.9
docutils==0.18.1
filelock==3.4.1
fixtures==4.0.1
idna==3.10
imagesize==1.4.1
importlib-metadata==4.8.3
importlib-resources==5.4.0
iniconfig==1.1.1
Jinja2==3.0.3
MarkupSafe==2.0.1
mock==5.2.0
nose==1.3.7
packaging==21.3
pbr==6.1.1
platformdirs==2.4.0
pluggy==1.0.0
prettytable==2.5.0
py==1.11.0
Pygments==2.14.0
pyparsing==3.1.4
pytest==7.0.1
pytz==2025.2
requests==2.27.1
six==1.17.0
snowballstemmer==2.2.0
-e git+https://github.com/softlayer/softlayer-python.git@f6722dcb5dc6021cd813280a789fd39e81053da0#egg=SoftLayer
Sphinx==5.3.0
sphinxcontrib-applehelp==1.0.2
sphinxcontrib-devhelp==1.0.2
sphinxcontrib-htmlhelp==2.0.0
sphinxcontrib-jsmath==1.0.1
sphinxcontrib-qthelp==1.0.3
sphinxcontrib-serializinghtml==1.1.5
testtools==2.6.0
toml==0.10.2
tomli==1.2.3
tox==3.28.0
typing_extensions==4.1.1
urllib3==1.26.20
virtualenv==20.17.1
wcwidth==0.2.13
zipp==3.6.0
| name: softlayer-python
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- pip=21.2.2=py36h06a4308_0
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_0
- setuptools=58.0.4=py36h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- alabaster==0.7.13
- attrs==22.2.0
- babel==2.11.0
- charset-normalizer==2.0.12
- click==8.0.4
- coverage==6.2
- distlib==0.3.9
- docutils==0.18.1
- filelock==3.4.1
- fixtures==4.0.1
- idna==3.10
- imagesize==1.4.1
- importlib-metadata==4.8.3
- importlib-resources==5.4.0
- iniconfig==1.1.1
- jinja2==3.0.3
- markupsafe==2.0.1
- mock==5.2.0
- nose==1.3.7
- packaging==21.3
- pbr==6.1.1
- platformdirs==2.4.0
- pluggy==1.0.0
- prettytable==2.5.0
- py==1.11.0
- pygments==2.14.0
- pyparsing==3.1.4
- pytest==7.0.1
- pytz==2025.2
- requests==2.27.1
- six==1.17.0
- snowballstemmer==2.2.0
- sphinx==5.3.0
- sphinxcontrib-applehelp==1.0.2
- sphinxcontrib-devhelp==1.0.2
- sphinxcontrib-htmlhelp==2.0.0
- sphinxcontrib-jsmath==1.0.1
- sphinxcontrib-qthelp==1.0.3
- sphinxcontrib-serializinghtml==1.1.5
- testtools==2.6.0
- toml==0.10.2
- tomli==1.2.3
- tox==3.28.0
- typing-extensions==4.1.1
- urllib3==1.26.20
- virtualenv==20.17.1
- wcwidth==0.2.13
- zipp==3.6.0
prefix: /opt/conda/envs/softlayer-python
| [
"SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_list_servers",
"SoftLayer/tests/CLI/modules/vs_tests.py::DnsTests::test_list_vs"
] | [] | [
"SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_cancel_server",
"SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_create_options",
"SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_create_server",
"SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_create_server_missing_required",
"SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_create_server_test_flag",
"SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_create_server_with_export",
"SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_edit_server_failed",
"SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_edit_server_userdata",
"SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_edit_server_userdata_and_file",
"SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_edit_server_userfile",
"SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_nic_edit_server",
"SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_server_cancel_reasons",
"SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_server_details",
"SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_server_power_cycle",
"SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_server_power_cycle_negative",
"SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_server_power_off",
"SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_server_power_on",
"SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_server_reboot_default",
"SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_server_reboot_hard",
"SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_server_reboot_negative",
"SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_server_reboot_soft",
"SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_server_reload",
"SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_update_firmware",
"SoftLayer/tests/CLI/modules/vs_tests.py::DnsTests::test_create",
"SoftLayer/tests/CLI/modules/vs_tests.py::DnsTests::test_create_options",
"SoftLayer/tests/CLI/modules/vs_tests.py::DnsTests::test_detail_vs"
] | [] | MIT License | 113 |
projectmesa__mesa-103 | ca1e91c6ea8b5bc476ae0fdbf708c1f28ae55dc4 | 2015-04-28 14:22:30 | ca1e91c6ea8b5bc476ae0fdbf708c1f28ae55dc4 | diff --git a/examples/ForestFire/.ipynb_checkpoints/Forest Fire Model-checkpoint.ipynb b/examples/ForestFire/.ipynb_checkpoints/Forest Fire Model-checkpoint.ipynb
index 8c8746c5..72b54805 100644
--- a/examples/ForestFire/.ipynb_checkpoints/Forest Fire Model-checkpoint.ipynb
+++ b/examples/ForestFire/.ipynb_checkpoints/Forest Fire Model-checkpoint.ipynb
@@ -1,584 +1,621 @@
{
- "metadata": {
- "name": "",
- "signature": "sha256:7ad05bb257a0bc7d9176a2a5e02312695873a50206c8335653a47975f4e4ee8c"
- },
- "nbformat": 3,
- "nbformat_minor": 0,
- "worksheets": [
+ "cells": [
{
- "cells": [
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "# The Forest Fire Model\n",
- "## A rapid introduction to Mesa\n",
- "\n",
- "The [Forest Fire Model](http://en.wikipedia.org/wiki/Forest-fire_model) is one of the simplest examples of a model that exhibits self-organized criticality.\n",
- "\n",
- "Mesa is a new, Pythonic agent-based modeling framework. A big advantage of using Python is that it a great language for interactive data analysis. Unlike some other ABM frameworks, with Mesa you can write a model, run it, and analyze it all in the same environment. (You don't have to, of course. But you can).\n",
- "\n",
- "In this notebook, we'll go over a rapid-fire (pun intended, sorry) introduction to building and analyzing a model with Mesa."
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "First, some imports. We'll go over what all the Mesa ones mean just below."
- ]
- },
- {
- "cell_type": "code",
- "collapsed": false,
- "input": [
- "import random\n",
- "\n",
- "import numpy as np\n",
- "\n",
- "import matplotlib.pyplot as plt\n",
- "%matplotlib inline\n",
- "\n",
- "from mesa import Model, Agent\n",
- "from mesa.time import RandomActivation\n",
- "from mesa.space import Grid\n",
- "from mesa.datacollection import DataCollector\n",
- "from mesa.batchrunner import BatchRunner "
- ],
- "language": "python",
- "metadata": {},
- "outputs": [],
- "prompt_number": 1
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Building the model\n",
- "\n",
- "Most models consist of basically two things: agents, and an world for the agents to be in. The Forest Fire model has only one kind of agent: a tree. A tree can either be unburned, on fire, or already burned. The environment is a grid, where each cell can either be empty or contain a tree.\n",
- "\n",
- "First, let's define our tree agent. The agent needs to be assigned **x** and **y** coordinates on the grid, and that's about it. We could assign agents a condition to be in, but for now let's have them all start as being 'Fine'. Since the agent doesn't move, and there is only at most one tree per cell, we can use a tuple of its coordinates as a unique identifier.\n",
- "\n",
- "Next, we define the agent's **step** method. This gets called whenever the agent needs to act in the world and takes the *model* object to which it belongs as an input. The tree's behavior is simple: If it is currently on fire, it spreads the fire to any trees above, below, to the left and the right of it that are not themselves burned out or on fire; then it burns itself out. "
- ]
- },
- {
- "cell_type": "code",
- "collapsed": false,
- "input": [
- "class TreeCell(Agent):\n",
- " '''\n",
- " A tree cell.\n",
- " \n",
- " Attributes:\n",
- " x, y: Grid coordinates\n",
- " condition: Can be \"Fine\", \"On Fire\", or \"Burned Out\"\n",
- " unique_id: (x,y) tuple. \n",
- " \n",
- " unique_id isn't strictly necessary here, but it's good practice to give one to each\n",
- " agent anyway.\n",
- " '''\n",
- " def __init__(self, x, y):\n",
- " '''\n",
- " Create a new tree.\n",
- " Args:\n",
- " x, y: The tree's coordinates on the grid.\n",
- " '''\n",
- " self.x = x\n",
- " self.y = y\n",
- " self.unique_id = (x, y)\n",
- " self.condition = \"Fine\"\n",
- " \n",
- " def step(self, model):\n",
- " '''\n",
- " If the tree is on fire, spread it to fine trees nearby.\n",
- " '''\n",
- " if self.condition == \"On Fire\":\n",
- " neighbors = model.grid.get_neighbors(self.x, self.y, moore=False)\n",
- " for neighbor in neighbors:\n",
- " if neighbor.condition == \"Fine\":\n",
- " neighbor.condition = \"On Fire\"\n",
- " self.condition = \"Burned Out\"\n",
- " "
- ],
- "language": "python",
- "metadata": {},
- "outputs": [],
- "prompt_number": 2
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "Now we need to define the model object itself. The main thing the model needs is the grid, which the trees are placed on. But since the model is dynamic, it also needs to include time -- it needs a schedule, to manage the trees activation as they spread the fire from one to the other.\n",
- "\n",
- "The model also needs a few parameters: how large the grid is and what the density of trees on it will be. Density will be the key parameter we'll explore below.\n",
- "\n",
- "Finally, we'll give the model a data collector. This is a Mesa object which collects and stores data on the model as it runs for later analysis.\n",
- "\n",
- "The constructor needs to do a few things. It instantiates all the model-level variables and objects; it randomly places trees on the grid, based on the density parameter; and it starts the fire by setting all the trees on one edge of the grid (x=0) as being On \"Fire\".\n",
- "\n",
- "Next, the model needs a **step** method. Like at the agent level, this method defines what happens every step of the model. We want to activate all the trees, one at a time; then we run the data collector, to count how many trees are currently on fire, burned out, or still fine. If there are no trees left on fire, we stop the model by setting its **running** property to False."
- ]
- },
- {
- "cell_type": "code",
- "collapsed": false,
- "input": [
- "class ForestFire(Model):\n",
- " '''\n",
- " Simple Forest Fire model.\n",
- " '''\n",
- " def __init__(self, height, width, density):\n",
- " '''\n",
- " Create a new forest fire model.\n",
- " \n",
- " Args:\n",
- " height, width: The size of the grid to model\n",
- " density: What fraction of grid cells have a tree in them.\n",
- " '''\n",
- " # Initialize model parameters\n",
- " self.height = height\n",
- " self.width = width\n",
- " self.density = density\n",
- " \n",
- " # Set up model objects\n",
- " self.schedule = RandomActivation(self)\n",
- " self.grid = Grid(height, width, torus=False)\n",
- " self.dc = DataCollector({\"Fine\": lambda m: self.count_type(m, \"Fine\"),\n",
- " \"On Fire\": lambda m: self.count_type(m, \"On Fire\"),\n",
- " \"Burned Out\": lambda m: self.count_type(m, \"Burned Out\")})\n",
- " \n",
- " # Place a tree in each cell with Prob = density\n",
- " for x in range(self.width):\n",
- " for y in range(self.height):\n",
- " if random.random() < self.density:\n",
- " # Create a tree\n",
- " new_tree = TreeCell(x, y)\n",
- " # Set all trees in the first column on fire.\n",
- " if x == 0:\n",
- " new_tree.condition = \"On Fire\"\n",
- " self.grid[y][x] = new_tree\n",
- " self.schedule.add(new_tree)\n",
- " self.running = True\n",
- " \n",
- " def step(self):\n",
- " '''\n",
- " Advance the model by one step.\n",
- " '''\n",
- " self.schedule.step()\n",
- " self.dc.collect(self)\n",
- " # Halt if no more fire\n",
- " if self.count_type(self, \"On Fire\") == 0:\n",
- " self.running = False\n",
- " \n",
- " @staticmethod\n",
- " def count_type(model, tree_condition):\n",
- " '''\n",
- " Helper method to count trees in a given condition in a given model.\n",
- " '''\n",
- " count = 0\n",
- " for tree in model.schedule.agents:\n",
- " if tree.condition == tree_condition:\n",
- " count += 1\n",
- " return count"
- ],
- "language": "python",
- "metadata": {},
- "outputs": [],
- "prompt_number": 3
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Running the model\n",
- "\n",
- "Let's create a model with a 100 x 100 grid, and a tree density of 0.6. Remember, ForestFire takes the arguments *height*, *width*, *density*."
- ]
- },
- {
- "cell_type": "code",
- "collapsed": false,
- "input": [
- "fire = ForestFire(100, 100, 0.6)"
- ],
- "language": "python",
- "metadata": {},
- "outputs": [],
- "prompt_number": 4
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "To run the model until it's done (that is, until it sets its **running** property to False) just use the **run_model()** method. This is implemented in the Model parent object, so we didn't need to implement it above."
- ]
- },
- {
- "cell_type": "code",
- "collapsed": false,
- "input": [
- "fire.run_model()"
- ],
- "language": "python",
- "metadata": {},
- "outputs": [],
- "prompt_number": 5
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "That's all there is to it!\n",
- "\n",
- "But... so what? This code doesn't include a visualization, after all. \n",
- "\n",
- "**TODO: Add a MatPlotLib visualization**\n",
- "\n",
- "Remember the data collector? Now we can put the data it collected into a pandas DataFrame:"
- ]
- },
- {
- "cell_type": "code",
- "collapsed": false,
- "input": [
- "results = fire.dc.get_model_vars_dataframe()"
- ],
- "language": "python",
- "metadata": {},
- "outputs": [],
- "prompt_number": 6
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "And chart it, to see the dynamics."
- ]
- },
- {
- "cell_type": "code",
- "collapsed": false,
- "input": [
- "results.plot()"
- ],
- "language": "python",
- "metadata": {},
- "outputs": [
- {
- "metadata": {},
- "output_type": "pyout",
- "prompt_number": 7,
- "text": [
- "<matplotlib.axes._subplots.AxesSubplot at 0x10988b2e8>"
- ]
- },
- {
- "metadata": {},
- "output_type": "display_data",
- "png": "iVBORw0KGgoAAAANSUhEUgAAAXkAAAEACAYAAABWLgY0AAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAALEgAACxIB0t1+/AAAIABJREFUeJzt3Xl4VOXZ+PHvnYXsGwmEsAZe2UFBlKXCS0Tpixa3umHF\nithWi1KXqgVtxbZuuLVqtfWnCC51wV0REETSug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gT0Tmisi3IvKsiEThgjickuQD9uivsbt418QnItHAW8BNxph9vo+5JRZjTK2x\n5ZquwP+KyJkHPe74OERkIrDHGLMaaHT8sxvi8DjDGDMUOAdbBmxwZiqXxBECnAo8bYw5FSjjoNKM\nU+NwSpLPAbr5zHfD9ubdKldEOgGISAqwx8/taRYRCcUm+JeMMe96FrsyFgBjTDHwITAM98XxE+B8\nEfkeeBUYJyIv4b44MMbs8tzmAe9gz2Hltjh2AjuNMas8829ik/5up8fhlCT/NdBbRFJFpB1wOfC+\nn9t0PN4Hrvbcvxpb33Y0ERFgDpBpjPm7z0OuikVEkrwjHEQkAhgPrMZlcRhj7jTGdDPG9AQmAZ8Y\nY67CZXGISKSIxHjuRwE/BdbhsjiMMbuBHSLSx7PobGA98AFOj8PfBwV8DmCcg/01bBYw09/tOYp2\nv4r99W4l9rjCNUB77AGzzcASIN7f7WxGHKOxtd8MbFJcjR015KpYgMHAt5441gK3e5a7Ko6DYhoL\nvO/GOLC17AzP9J33f9ttcXjafAr2QP4a4G3swVjHx6E/hlJKqQDmlHKNUkqpVqBJXimlApgmeaWU\nCmCa5JVSKoBpkldKqQCmSV4ppQKYJnmllApgmuSVUiqA/X9Qq9l5Pb7B1AAAAABJRU5ErkJggg==\n",
- "text": [
- "<matplotlib.figure.Figure at 0x10987db70>"
- ]
- }
- ],
- "prompt_number": 7
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "In this case, the fire burned itself out after about 90 steps, with many trees left unburned. \n",
- "\n",
- "You can try changing the density parameter and rerunning the code above, to see how different densities yield different dynamics. For example:"
- ]
- },
- {
- "cell_type": "code",
- "collapsed": false,
- "input": [
- "fire = ForestFire(100, 100, 0.8)\n",
- "fire.run_model()\n",
- "results = fire.dc.get_model_vars_dataframe()\n",
- "results.plot()"
- ],
- "language": "python",
- "metadata": {},
- "outputs": [
- {
- "metadata": {},
- "output_type": "pyout",
- "prompt_number": 8,
- "text": [
- "<matplotlib.axes._subplots.AxesSubplot at 0x109c54208>"
- ]
- },
- {
- "metadata": {},
- "output_type": "display_data",
- "png": "iVBORw0KGgoAAAANSUhEUgAAAXkAAAEACAYAAABWLgY0AAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAALEgAACxIB0t1+/AAAIABJREFUeJzsnXd4FNX3h9+ThN5CkYC0oPTeq0CooqI06SUBRBFpigX0\nq6A/BURQiiBVpElHmnQkAlJCC8VIJ/TeAoQSkvv7YzZkCYGEsLuz5b7Pc5+duXNn5nMyO2cn5945\nV5RSaDQajcY98TJbgEaj0Wjsh3byGo1G48ZoJ6/RaDRujHbyGo1G48ZoJ6/RaDRujHbyGo1G48Yk\n6uRFpL+I/Csi+0TkdxFJJSJZRGSNiBwSkdUi4huv/WEROSAiDazqy1uOcVhERtrLII1Go9HE8VQn\nLyL+QFegnFKqJOANtAb6AWuUUoWAdZZ1RKQY0AooBjQExoqIWA73C9BFKVUQKCgiDW1ujUaj0Wge\nIbEn+QggCkgrIj5AWuAs8BYw1dJmKtDEstwYmKWUilJKhQNHgMoikhPIoJQKsbSbZrWPRqPRaOzE\nU528UuoqMBw4ieHcryul1gB+SqkLlmYXAD/L8ovAaatDnAZyJVB/xlKv0Wg0GjuSWLjmZaAP4I/h\nqNOLSHvrNsrIi6BzI2g0Go0T4pPI9grAZqXUFQARWQhUBc6LSA6l1HlLKOaipf0ZII/V/rkxnuDP\nWJat688kdEIR0T8YGo1G84wopSSh+sSc/AHgSxFJA9wF6gEhwG0gEPje8rnI0n4J8LuI/IgRjikI\nhCillIhEiEhly/4dgFFPEZtUu9yKgQMHMnDgQLNlmIK2faDZMkzBk20fMGAgffoM5PJluHQJLl+O\nKzduQEQE3LxpfMYuR0ZCVBTcv2+U2OXr1xP070AiTl4ptUdEpgE7gBhgFzAByADMFZEuQDjQ0tI+\nTETmAmHAA6C7ivPY3YHfgDTAcqXUyuT/edyT8PBwsyWYhrbdM3F325WC8+fh4EE4dOjRzyNHwhkx\nAl54AbJlM8oLL0DWrODrC35+kCEDZ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ZXdJzwAXbc5L2rPWZpmYveMz2oqQ7gBlJ54oHy8pflzP5\nX4Dhwv4w6Wy+TZYk3Qkg6S7gQo/7UxpJg6QCP2X7SG5uTX4A238A08DDtCP7o8CYpJ+Bw8ATkqZo\nR3YAbC/m378Dn5OGqUvPX5cifwq4V9I2SZuAceBoj/tUtaPAvry9Dzhyjc9uWEqn7JPAgu0PCoca\nn1/Slu7sCUk3Ak8Bc7Qgu+23bQ/b3g68CMzafokWZAeQdJOkW/P2zcDTwBkqyF+befKSnmHlOfOT\ntid63KXSSDoM7Aa2kMbh3gG+AD4F7gE6wAu2N+abg68hzyb5FjjNyjDdAdLq50bnl/Qg6eZaX/6Z\nsv2epM00PHuRpN3AG7bH2pJd0nbS2TukYfJPbE9Ukb82RT6EEML6q8twTQghhBJEkQ8hhAaLIh9C\nCA0WRT6EEBosinwIITRYFPkQQmiwKPIhhNBgUeRDCKHB/gXedjkAMUGImgAAAABJRU5ErkJggg==\n",
- "text": [
- "<matplotlib.figure.Figure at 0x109c517b8>"
- ]
- }
- ],
- "prompt_number": 8
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "... But to really understand how the final outcome varies with density, we can't just tweak the parameter by hand over and over again. We need to do a batch run. \n",
- "\n",
- "## Batch runs\n",
- "\n",
- "Batch runs, also called parameter sweeps, allow use to systemically vary the density parameter, run the model, and check the output. Mesa provides a BatchRunner object which takes a model class, a dictionary of parameters and the range of values they can take and runs the model at each combination of these values. We can also give it reporters, which collect some data on the model at the end of each run and store it, associated with the parameters that produced it.\n",
- "\n",
- "For ease of typing and reading, we'll first create the parameters to vary and the reporter, and then assign them to a new BatchRunner."
- ]
- },
- {
- "cell_type": "code",
- "collapsed": false,
- "input": [
- "param_set = dict(height=50, # Height and width are constant\n",
- " width=50,\n",
- " # Vary density from 0.01 to 1, in 0.01 increments:\n",
- " density=np.linspace(0,1,101)[1:]) "
- ],
- "language": "python",
- "metadata": {},
- "outputs": [],
- "prompt_number": 9
- },
- {
- "cell_type": "code",
- "collapsed": false,
- "input": [
- "# At the end of each model run, calculate the fraction of trees which are Burned Out\n",
- "model_reporter = {\"BurnedOut\": lambda m: (ForestFire.count_type(m, \"Burned Out\") / \n",
- " m.schedule.get_agent_count()) }"
- ],
- "language": "python",
- "metadata": {},
- "outputs": [],
- "prompt_number": 10
- },
- {
- "cell_type": "code",
- "collapsed": false,
- "input": [
- "# Create the batch runner\n",
- "param_run = BatchRunner(ForestFire, param_set, model_reporters=model_reporter)"
- ],
- "language": "python",
- "metadata": {},
- "outputs": [],
- "prompt_number": 11
- },
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "# The Forest Fire Model\n",
+ "## A rapid introduction to Mesa\n",
+ "\n",
+ "The [Forest Fire Model](http://en.wikipedia.org/wiki/Forest-fire_model) is one of the simplest examples of a model that exhibits self-organized criticality.\n",
+ "\n",
+ "Mesa is a new, Pythonic agent-based modeling framework. A big advantage of using Python is that it a great language for interactive data analysis. Unlike some other ABM frameworks, with Mesa you can write a model, run it, and analyze it all in the same environment. (You don't have to, of course. But you can).\n",
+ "\n",
+ "In this notebook, we'll go over a rapid-fire (pun intended, sorry) introduction to building and analyzing a model with Mesa."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "First, some imports. We'll go over what all the Mesa ones mean just below."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 1,
+ "metadata": {
+ "collapsed": false
+ },
+ "outputs": [],
+ "source": [
+ "import random\n",
+ "\n",
+ "import numpy as np\n",
+ "\n",
+ "import matplotlib.pyplot as plt\n",
+ "%matplotlib inline\n",
+ "\n",
+ "from mesa import Model, Agent\n",
+ "from mesa.time import RandomActivation\n",
+ "from mesa.space import Grid\n",
+ "from mesa.datacollection import DataCollector\n",
+ "from mesa.batchrunner import BatchRunner "
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Building the model\n",
+ "\n",
+ "Most models consist of basically two things: agents, and an world for the agents to be in. The Forest Fire model has only one kind of agent: a tree. A tree can either be unburned, on fire, or already burned. The environment is a grid, where each cell can either be empty or contain a tree.\n",
+ "\n",
+ "First, let's define our tree agent. The agent needs to be assigned **x** and **y** coordinates on the grid, and that's about it. We could assign agents a condition to be in, but for now let's have them all start as being 'Fine'. Since the agent doesn't move, and there is only at most one tree per cell, we can use a tuple of its coordinates as a unique identifier.\n",
+ "\n",
+ "Next, we define the agent's **step** method. This gets called whenever the agent needs to act in the world and takes the *model* object to which it belongs as an input. The tree's behavior is simple: If it is currently on fire, it spreads the fire to any trees above, below, to the left and the right of it that are not themselves burned out or on fire; then it burns itself out. "
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 2,
+ "metadata": {
+ "collapsed": false
+ },
+ "outputs": [],
+ "source": [
+ "class TreeCell(Agent):\n",
+ " '''\n",
+ " A tree cell.\n",
+ " \n",
+ " Attributes:\n",
+ " x, y: Grid coordinates\n",
+ " condition: Can be \"Fine\", \"On Fire\", or \"Burned Out\"\n",
+ " unique_id: (x,y) tuple. \n",
+ " \n",
+ " unique_id isn't strictly necessary here, but it's good practice to give one to each\n",
+ " agent anyway.\n",
+ " '''\n",
+ " def __init__(self, x, y):\n",
+ " '''\n",
+ " Create a new tree.\n",
+ " Args:\n",
+ " x, y: The tree's coordinates on the grid.\n",
+ " '''\n",
+ " self.x = x\n",
+ " self.y = y\n",
+ " self.unique_id = (x, y)\n",
+ " self.condition = \"Fine\"\n",
+ " \n",
+ " def step(self, model):\n",
+ " '''\n",
+ " If the tree is on fire, spread it to fine trees nearby.\n",
+ " '''\n",
+ " if self.condition == \"On Fire\":\n",
+ " neighbors = model.grid.get_neighbors(self.x, self.y, moore=False)\n",
+ " for neighbor in neighbors:\n",
+ " if neighbor.condition == \"Fine\":\n",
+ " neighbor.condition = \"On Fire\"\n",
+ " self.condition = \"Burned Out\"\n",
+ " "
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Now we need to define the model object itself. The main thing the model needs is the grid, which the trees are placed on. But since the model is dynamic, it also needs to include time -- it needs a schedule, to manage the trees activation as they spread the fire from one to the other.\n",
+ "\n",
+ "The model also needs a few parameters: how large the grid is and what the density of trees on it will be. Density will be the key parameter we'll explore below.\n",
+ "\n",
+ "Finally, we'll give the model a data collector. This is a Mesa object which collects and stores data on the model as it runs for later analysis.\n",
+ "\n",
+ "The constructor needs to do a few things. It instantiates all the model-level variables and objects; it randomly places trees on the grid, based on the density parameter; and it starts the fire by setting all the trees on one edge of the grid (x=0) as being On \"Fire\".\n",
+ "\n",
+ "Next, the model needs a **step** method. Like at the agent level, this method defines what happens every step of the model. We want to activate all the trees, one at a time; then we run the data collector, to count how many trees are currently on fire, burned out, or still fine. If there are no trees left on fire, we stop the model by setting its **running** property to False."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 3,
+ "metadata": {
+ "collapsed": false
+ },
+ "outputs": [],
+ "source": [
+ "class ForestFire(Model):\n",
+ " '''\n",
+ " Simple Forest Fire model.\n",
+ " '''\n",
+ " def __init__(self, height, width, density):\n",
+ " '''\n",
+ " Create a new forest fire model.\n",
+ " \n",
+ " Args:\n",
+ " height, width: The size of the grid to model\n",
+ " density: What fraction of grid cells have a tree in them.\n",
+ " '''\n",
+ " # Initialize model parameters\n",
+ " self.height = height\n",
+ " self.width = width\n",
+ " self.density = density\n",
+ " \n",
+ " # Set up model objects\n",
+ " self.schedule = RandomActivation(self)\n",
+ " self.grid = Grid(height, width, torus=False)\n",
+ " self.dc = DataCollector({\"Fine\": lambda m: self.count_type(m, \"Fine\"),\n",
+ " \"On Fire\": lambda m: self.count_type(m, \"On Fire\"),\n",
+ " \"Burned Out\": lambda m: self.count_type(m, \"Burned Out\")})\n",
+ " \n",
+ " # Place a tree in each cell with Prob = density\n",
+ " for x in range(self.width):\n",
+ " for y in range(self.height):\n",
+ " if random.random() < self.density:\n",
+ " # Create a tree\n",
+ " new_tree = TreeCell(x, y)\n",
+ " # Set all trees in the first column on fire.\n",
+ " if x == 0:\n",
+ " new_tree.condition = \"On Fire\"\n",
+ " self.grid[y][x] = new_tree\n",
+ " self.schedule.add(new_tree)\n",
+ " self.running = True\n",
+ " \n",
+ " def step(self):\n",
+ " '''\n",
+ " Advance the model by one step.\n",
+ " '''\n",
+ " self.schedule.step()\n",
+ " self.dc.collect(self)\n",
+ " # Halt if no more fire\n",
+ " if self.count_type(self, \"On Fire\") == 0:\n",
+ " self.running = False\n",
+ " \n",
+ " @staticmethod\n",
+ " def count_type(model, tree_condition):\n",
+ " '''\n",
+ " Helper method to count trees in a given condition in a given model.\n",
+ " '''\n",
+ " count = 0\n",
+ " for tree in model.schedule.agents:\n",
+ " if tree.condition == tree_condition:\n",
+ " count += 1\n",
+ " return count"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Running the model\n",
+ "\n",
+ "Let's create a model with a 100 x 100 grid, and a tree density of 0.6. Remember, ForestFire takes the arguments *height*, *width*, *density*."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 4,
+ "metadata": {
+ "collapsed": false
+ },
+ "outputs": [],
+ "source": [
+ "fire = ForestFire(100, 100, 0.6)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "To run the model until it's done (that is, until it sets its **running** property to False) just use the **run_model()** method. This is implemented in the Model parent object, so we didn't need to implement it above."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 5,
+ "metadata": {
+ "collapsed": false
+ },
+ "outputs": [],
+ "source": [
+ "fire.run_model()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "That's all there is to it!\n",
+ "\n",
+ "But... so what? This code doesn't include a visualization, after all. \n",
+ "\n",
+ "**TODO: Add a MatPlotLib visualization**\n",
+ "\n",
+ "Remember the data collector? Now we can put the data it collected into a pandas DataFrame:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 6,
+ "metadata": {
+ "collapsed": false
+ },
+ "outputs": [],
+ "source": [
+ "results = fire.dc.get_model_vars_dataframe()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "And chart it, to see the dynamics."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 7,
+ "metadata": {
+ "collapsed": false
+ },
+ "outputs": [
{
- "cell_type": "markdown",
+ "data": {
+ "text/plain": [
+ "<matplotlib.axes._subplots.AxesSubplot at 0x109a3eda0>"
+ ]
+ },
+ "execution_count": 7,
"metadata": {},
- "source": [
- "Now the BatchRunner, which we've named param_run, is ready to go. To run the model at every combination of parameters (in this case, every density value), just use the **run_all()** method."
- ]
+ "output_type": "execute_result"
},
{
- "cell_type": "code",
- "collapsed": false,
- "input": [
- "param_run.run_all()"
- ],
- "language": "python",
+ "data": {
+ "image/png": "iVBORw0KGgoAAAANSUhEUgAAAXsAAAEACAYAAABS29YJAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAALEgAACxIB0t1+/AAAIABJREFUeJztnXncVFX9x98fFlEWWUQBWTU3MM0lFUsDFwzLvYRMVNQy\nw1SyVCjzOtXPrSyztFJJXErFJc0lFFHTMsVMlERFVExIEBQEVBTk+/vjnHkYludhnoeZuXfm+b5f\nr/uauedun3vn3u898z3f8z0yMxzHcZzapkXaAhzHcZzy48becRynGeDG3nEcpxngxt5xHKcZ4Mbe\ncRynGeDG3nEcpxlQlLGX1EnS7ZJelDRd0l6SukiaJGmGpAcldSpYf6ykVyS9JOmggvLdJU2Ly35V\njhNyHMdx1qbYmv2vgPvNrD+wM/ASMAaYZGbbAZPjPJIGAMOBAcBQ4CpJivv5LXCymW0LbCtpaMnO\nxHEcx6mX9Rp7SR2Bfc3sDwBmtsLM3gMOA66Pq10PHBG/Hw7cbGbLzWwWMBPYS1IPoIOZTYnr3VCw\njeM4jlNGiqnZbwXMl3SdpH9LukZSO6Cbmc2L68wDusXvWwKzC7afDfRcR/mcWO44juOUmWKMfStg\nN+A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X7\nZ7ka7sesabTEPrbEnrTEfmmJfRHYjgFcDLwEdCWM9HcecH5xOzTL1BQkpa+jcZrtZLAZYF3S1pKB\n3y6T9OvXzyZPnlw3f99999l2221XNz9o0CC79tpr6+avu+4622effermJdmVV15p22yzjW299db2\n6KOPWs+ePe2yyy6zLbbYwnr06GHXXXdd3frLli2z733ve9anTx/r1q2bnXrqqfbhhx/WLb/00kut\nR48e1rNnTxs3bpxJsldffXUt3StXrrQ+ffrYz372s7XKP/3pT9v5559vZmZJktiIESPqlr/++usm\nyVasWGE/+MEPrGXLlrbxxhtb+/bt7fTTT1/nNarGZ8+n1Z69Btfxmn0TKMwpLTEYuJAQYvluWprW\npBpyc1ea+FDwwQcfcOutt7L33nvXLZO03trv3XffzdNPP8306dMxM+bNm8fixYv53//+x7hx4zjt\ntNN4772QQmXMmDHMnDmT5557jpkzZzJnzhx+/OMfAzBx4kQuu+wyHnroIWbMmMFDDz1U7zFffvll\n3nzzTY4++ujVyiXxla98hUmTJjWoWRL/93//x7777suVV17JkiVLuOKKdWYOKCvVcD/WukY39huA\nRHfgZuBYM2akrSfrSKWZmoKZccQRR9C5c2c6derE5MmT+f73v9+ofYwdO5ZOnTrRpk0bAFq3bs35\n559Py5YtOfjgg2nfvj0vv/wyZsY111zDL37xCzp16kT79u0ZO3Yst9xyCwATJkzgpJNOYsCAAbRt\n25ZcLlfvMRcsWABAjx491lrWvXv3uuXFkH/ZOc0T71TVBMzs0Th04HWEPPT1V81SwjLmfwRI09ZI\n4u6772b//ffHzLjrrrsYNGgQL774IltssUVR++jdu/dq85ttthktWqyqL7Vt25alS5cyf/58Pvjg\nA3bfffe6ZWbGypWhx/xbb73FHnvsUbesT58+9R6za9euddv07dt3tWVvvfUWm2++eVHaIV2/fRbv\nxzWpdY1es286pwGbAfVXy5xMIokjjzySli1b8ve//x2Adu3a8f7779etM3fu3HVuVwxdu3Zlk002\nYfr06SxcuJCFCxeyaNEiFi8Ogyj16NGD//73v3XrF35fk+23355evXoxY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vZVsDXgIfN7LiM\naZwLvClpu1h0IKHb+z1kRCMhB9JASZvE3/1AYDrZ0pinvt/2L8DXJG0kaSvC3/8pKehD0lBCLfRw\nMyvszp8JjWY2zcy6mdlW8dmZDewW3WOZ0FjAXYQUK8RnaCMzW0BjdVaihbnIVuiDCdEuM4GxaeuJ\nmvYh+MGnEpKjPUvIj9IFeIiQDfNBoFPaWqPeQayKxsmURkISq6cJ+U3uJETjZE3jOYSX0DRCw2fr\ntDUS/q39j5Aj503gxIY0EVwTMwkvry+mpPEkQtK4Nwqem6syovGj/HVcY/lrxGictDTWpzPehzfG\n+/IZYHBTdHqnKsdxnGZAVtw4juM4ThlxY+84jtMMcGPvOI7TDHBj7ziO0wxwY+84jtMMcGPvOI7T\nDHBj7ziO0wxwY+84jtMM+H8bqxBDsJagjAAAAABJRU5ErkJggg==\n",
+ "text/plain": [
+ "<matplotlib.figure.Figure at 0x109a3e5f8>"
+ ]
+ },
"metadata": {},
- "outputs": [],
- "prompt_number": 12
- },
+ "output_type": "display_data"
+ }
+ ],
+ "source": [
+ "results.plot()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "In this case, the fire burned itself out after about 90 steps, with many trees left unburned. \n",
+ "\n",
+ "You can try changing the density parameter and rerunning the code above, to see how different densities yield different dynamics. For example:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 8,
+ "metadata": {
+ "collapsed": false
+ },
+ "outputs": [
{
- "cell_type": "markdown",
+ "data": {
+ "text/plain": [
+ "<matplotlib.axes._subplots.AxesSubplot at 0x109e2b470>"
+ ]
+ },
+ "execution_count": 8,
"metadata": {},
- "source": [
- "Like with the data collector, we can extract the data the batch runner collected into a dataframe:"
- ]
+ "output_type": "execute_result"
},
{
- "cell_type": "code",
- "collapsed": false,
- "input": [
- "df = param_run.get_model_vars_dataframe()"
- ],
- "language": "python",
+ "data": {
+ "image/png": "iVBORw0KGgoAAAANSUhEUgAAAXkAAAEACAYAAABWL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YBVxgZjsD+wJDoueWGBvN\nbCVwiJn1wGUqPETSgSTIxjTOB6ayrhdc0mw0oLeZ7WFm+0RlSbNxA/LCyZM2SMpc//TUIKmCxsxe\nw3XHSudoXN5qotdjcyoqg5jZXDObHK0vww1q60CCbAQw160PXN/9UtwzTZSNkrbGDYK7G9dfHBJm\nY0TFHihJtHE98sXJdwC+StueFZUlkbZmNi9an4cbvFXwSOoM7IFLC50oGyWVSJqMs2WimX1EwmwE\n/ozLupg+0CZpNhrwkqR3JJ0ZlSXNxg3I9WCojVGUrb9RTuWCt11SU+Bx4HwzW+oGUzqSYKO5wTM9\nJLUAXpR0SIX9BW2jXHqGb8zs/Y1NFlLoNkYcYGZzJG0BTJA0LX1nQmzcgHypyc8GOqZtd8TV5pPI\nPMmlLJXUHjccumCRtCnOwT9oZk9GxYmyMYWZLcZlIOxJsmzcHzha0ufAaOCnkh4kWTZiZnOi1/nA\nP3Bh4kTZWBn54uTfAbpI6iyX2+NE4OmYNf1/O3eM0kAUBnH8P5aKjdha5ACeIZWCjWWwkRzCSi+Q\nwsYLpBIRrNQDpPACgoK1rZ03GIu3kjSxiSHLx/xgYWG32GmG5e3bb12egXF3PgYe/7i319Re2afA\nh+2bhUuVMu7/7rhQm+NzBLxSKKPtK9sHtgfAGTCzfU6hjJK2Je125zvAMfBOoYzL9GafvKQT5nPm\np7YnG36klUm6B4a0WRdftJnUT8ADbUjRJzCy/b2pZ1xFt8vkBXhjvuR2SfuTuUrGQ9oHua3uuLV9\nLWmPIhkXSRoCF7ZPK2WUNKC9vUNbpr6zPamUcZnelHxERPy/vizXRETEGqTkIyIKS8lHRBSWko+I\nKCwlHxFRWEo+IqKwlHxERGEp+YiIwn4A7VrCBdJQ0o4AAAAASUVORK5CYII=\n",
+ "text/plain": [
+ "<matplotlib.figure.Figure at 0x109a3e5c0>"
+ ]
+ },
"metadata": {},
- "outputs": [],
- "prompt_number": 13
- },
+ "output_type": "display_data"
+ }
+ ],
+ "source": [
+ "fire = ForestFire(100, 100, 0.8)\n",
+ "fire.run_model()\n",
+ "results = fire.dc.get_model_vars_dataframe()\n",
+ "results.plot()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "... But to really understand how the final outcome varies with density, we can't just tweak the parameter by hand over and over again. We need to do a batch run. \n",
+ "\n",
+ "## Batch runs\n",
+ "\n",
+ "Batch runs, also called parameter sweeps, allow use to systemically vary the density parameter, run the model, and check the output. Mesa provides a BatchRunner object which takes a model class, a dictionary of parameters and the range of values they can take and runs the model at each combination of these values. We can also give it reporters, which collect some data on the model at the end of each run and store it, associated with the parameters that produced it.\n",
+ "\n",
+ "For ease of typing and reading, we'll first create the parameters to vary and the reporter, and then assign them to a new BatchRunner."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 9,
+ "metadata": {
+ "collapsed": false
+ },
+ "outputs": [],
+ "source": [
+ "param_set = dict(height=50, # Height and width are constant\n",
+ " width=50,\n",
+ " # Vary density from 0.01 to 1, in 0.01 increments:\n",
+ " density=np.linspace(0,1,101)[1:]) "
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 10,
+ "metadata": {
+ "collapsed": false
+ },
+ "outputs": [],
+ "source": [
+ "# At the end of each model run, calculate the fraction of trees which are Burned Out\n",
+ "model_reporter = {\"BurnedOut\": lambda m: (ForestFire.count_type(m, \"Burned Out\") / \n",
+ " m.schedule.get_agent_count()) }"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 11,
+ "metadata": {
+ "collapsed": false
+ },
+ "outputs": [],
+ "source": [
+ "# Create the batch runner\n",
+ "param_run = BatchRunner(ForestFire, param_set, model_reporters=model_reporter)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Now the BatchRunner, which we've named param_run, is ready to go. To run the model at every combination of parameters (in this case, every density value), just use the **run_all()** method."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 12,
+ "metadata": {
+ "collapsed": false
+ },
+ "outputs": [],
+ "source": [
+ "param_run.run_all()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Like with the data collector, we can extract the data the batch runner collected into a dataframe:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 13,
+ "metadata": {
+ "collapsed": false
+ },
+ "outputs": [],
+ "source": [
+ "df = param_run.get_model_vars_dataframe()"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 14,
+ "metadata": {
+ "collapsed": false
+ },
+ "outputs": [
{
- "cell_type": "code",
- "collapsed": false,
- "input": [
- "df.head()"
- ],
- "language": "python",
+ "data": {
+ "text/html": [
+ "<div style=\"max-height:1000px;max-width:1500px;overflow:auto;\">\n",
+ "<table border=\"1\" class=\"dataframe\">\n",
+ " <thead>\n",
+ " <tr style=\"text-align: right;\">\n",
+ " <th></th>\n",
+ " <th>BurnedOut</th>\n",
+ " <th>Run</th>\n",
+ " <th>density</th>\n",
+ " <th>height</th>\n",
+ " <th>width</th>\n",
+ " </tr>\n",
+ " </thead>\n",
+ " <tbody>\n",
+ " <tr>\n",
+ " <th>0</th>\n",
+ " <td> 0.009288</td>\n",
+ " <td> 11</td>\n",
+ " <td> 0.12</td>\n",
+ " <td> 50</td>\n",
+ " <td> 50</td>\n",
+ " </tr>\n",
+ " <tr>\n",
+ " <th>1</th>\n",
+ " <td> 1.000000</td>\n",
+ " <td> 98</td>\n",
+ " <td> 0.99</td>\n",
+ " <td> 50</td>\n",
+ " <td> 50</td>\n",
+ " </tr>\n",
+ " <tr>\n",
+ " <th>2</th>\n",
+ " <td> 0.092608</td>\n",
+ " <td> 48</td>\n",
+ " <td> 0.49</td>\n",
+ " <td> 50</td>\n",
+ " <td> 50</td>\n",
+ " </tr>\n",
+ " <tr>\n",
+ " <th>3</th>\n",
+ " <td> 0.024691</td>\n",
+ " <td> 3</td>\n",
+ " <td> 0.04</td>\n",
+ " <td> 50</td>\n",
+ " <td> 50</td>\n",
+ " </tr>\n",
+ " <tr>\n",
+ " <th>4</th>\n",
+ " <td> 0.060748</td>\n",
+ " <td> 42</td>\n",
+ " <td> 0.43</td>\n",
+ " <td> 50</td>\n",
+ " <td> 50</td>\n",
+ " </tr>\n",
+ " </tbody>\n",
+ "</table>\n",
+ "</div>"
+ ],
+ "text/plain": [
+ " BurnedOut Run density height width\n",
+ "0 0.009288 11 0.12 50 50\n",
+ "1 1.000000 98 0.99 50 50\n",
+ "2 0.092608 48 0.49 50 50\n",
+ "3 0.024691 3 0.04 50 50\n",
+ "4 0.060748 42 0.43 50 50"
+ ]
+ },
+ "execution_count": 14,
"metadata": {},
- "outputs": [
- {
- "html": [
- "<div style=\"max-height:1000px;max-width:1500px;overflow:auto;\">\n",
- "<table border=\"1\" class=\"dataframe\">\n",
- " <thead>\n",
- " <tr style=\"text-align: right;\">\n",
- " <th></th>\n",
- " <th>BurnedOut</th>\n",
- " <th>Run</th>\n",
- " <th>density</th>\n",
- " <th>height</th>\n",
- " <th>width</th>\n",
- " </tr>\n",
- " </thead>\n",
- " <tbody>\n",
- " <tr>\n",
- " <th>0</th>\n",
- " <td> 0.142256</td>\n",
- " <td> 45</td>\n",
- " <td> 0.46</td>\n",
- " <td> 50</td>\n",
- " <td> 50</td>\n",
- " </tr>\n",
- " <tr>\n",
- " <th>1</th>\n",
- " <td> 0.946026</td>\n",
- " <td> 68</td>\n",
- " <td> 0.69</td>\n",
- " <td> 50</td>\n",
- " <td> 50</td>\n",
- " </tr>\n",
- " <tr>\n",
- " <th>2</th>\n",
- " <td> 0.978022</td>\n",
- " <td> 71</td>\n",
- " <td> 0.72</td>\n",
- " <td> 50</td>\n",
- " <td> 50</td>\n",
- " </tr>\n",
- " <tr>\n",
- " <th>3</th>\n",
- " <td> 0.027190</td>\n",
- " <td> 12</td>\n",
- " <td> 0.13</td>\n",
- " <td> 50</td>\n",
- " <td> 50</td>\n",
- " </tr>\n",
- " <tr>\n",
- " <th>4</th>\n",
- " <td> 0.082645</td>\n",
- " <td> 43</td>\n",
- " <td> 0.44</td>\n",
- " <td> 50</td>\n",
- " <td> 50</td>\n",
- " </tr>\n",
- " </tbody>\n",
- "</table>\n",
- "</div>"
- ],
- "metadata": {},
- "output_type": "pyout",
- "prompt_number": 14,
- "text": [
- " BurnedOut Run density height width\n",
- "0 0.142256 45 0.46 50 50\n",
- "1 0.946026 68 0.69 50 50\n",
- "2 0.978022 71 0.72 50 50\n",
- "3 0.027190 12 0.13 50 50\n",
- "4 0.082645 43 0.44 50 50"
- ]
- }
- ],
- "prompt_number": 14
- },
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "df.head()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "As you can see, each row here is a run of the model, identified by its parameter values (and given a unique index by the Run column). To view how the BurnedOut fraction varies with density, we can easily just plot them:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 15,
+ "metadata": {
+ "collapsed": false
+ },
+ "outputs": [
{
- "cell_type": "markdown",
+ "data": {
+ "text/plain": [
+ "(0, 1)"
+ ]
+ },
+ "execution_count": 15,
"metadata": {},
- "source": [
- "As you can see, each row here is a run of the model, identified by its parameter values (and given a unique index by the Run column). To view how the BurnedOut fraction varies with density, we can easily just plot them:"
- ]
+ "output_type": "execute_result"
},
{
- "cell_type": "code",
- "collapsed": false,
- "input": [
- "plt.scatter(df.density, df.BurnedOut)\n",
- "plt.xlim(0,1)"
- ],
- "language": "python",
+ "data": {
+ "image/png": "iVBORw0KGgoAAAANSUhEUgAAAX4AAAEACAYAAAC08h1NAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAALEgAACxIB0t1+/AAAGXpJREFUeJzt3X+sJeV93/H3l+WHWLdbvLsSbgAL4lLHRdjyWoG1vTXX\nsmE3VCoFV0HEpAQ7iMYlG7prBUwts1ITR0iwQhvHgLcYiBKZVolp1hVlIY2vHCFMDYQfwbuEjU3F\njwSZxTapWbb749s/Zi537rnnnDv3zL3n3Hvm/ZJGe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u6KiKcoGrG/nZmvj6zSiyQivgGcB6yNiBeBGym6/AbOTb/AJUkt\n46MXJallDH5JahmDX5JaxuCXpJYx+CWpZQx+SWoZg1+SWsbgl6SW+f9ehOb1bB9nvQAAAABJRU5E\nrkJggg==\n",
+ "text/plain": [
+ "<matplotlib.figure.Figure at 0x10a095748>"
+ ]
+ },
"metadata": {},
- "outputs": [
- {
- "metadata": {},
- "output_type": "pyout",
- "prompt_number": 15,
- "text": [
- "(0, 1)"
- ]
- },
- {
- "metadata": {},
- "output_type": "display_data",
- "png": "iVBORw0KGgoAAAANSUhEUgAAAX4AAAEACAYAAAC08h1NAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAALEgAACxIB0t1+/AAAGS9JREFUeJzt3X+M3PV95/Hn24Y9bXTHgePKuQAJKUdyORqQQQGnzp03\nl+yuw0lQ7FM5GnJukhbudKRttE0MtS5slKQVulpBNBIBQsASStAphNY5cbv2tRkaI8IFCoYzNsVJ\nkfjRoDikUa9nyfb5fX/MrHd2PDs7M9/dmd35Ph/Sivnu9zPf72e/eF/z2ffnM9+JzESSVB6r+t0B\nSVJvGfySVDIGvySVjMEvSSVj8EtSyRj8klQyhYM/Ir4REW9ExPPz7P9YROyPiOci4vGIuKToOSVJ\n3VuMEf/9wOYW+38M/OvMvAT4InDPIpxTktSlwsGfmd8Hft5i/xOZ+Yva5pPAeUXPKUnqXq9r/J8C\nHu3xOSVJdc7o1Yki4kPAJ4GNvTqnJOl0PQn+2oTuvcDmzDytLBQR3jBIkrqQmdHpc5a81BMR7wC+\nA9yQmYfna5eZfmVy22239b0Py+XLa+G18Fq0/upW4RF/RHwL2ASsjYhXgNuAM2thfjfweeAc4K6I\nADiemVcUPa8kqTuFgz8zr19g/28Bv1X0PJKkxeE7d5eZkZGRfndh2fBazPJazPJaFBdF6kSL1omI\nXA79kKSVJCLI5Ti5K0laXgx+SSoZg1+SSsbgl6SSMfglqWQMfkkqGYNfkkrG4JekkjH4JalkDH5J\nKhmDX5J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gM\n+DDwFuCJiPhBZr60pD3rvXauxR8Az2bmSERcCOyNiEsz8++XuG/LUUe52cvgfw04v277fKqvTK3a\nnFf73qBp51pQm9C9F9icma3+1FvJ2rkWlwMPVTOftcBHI+J4Zu7uTRd7pp1r8QpwJDOPAkcj4i+B\nS4FBC/52rsWvAl8GyMwfRcTfAO8BnupJD5ePjnOzl6Wep4CLIuKCiBgCrqP6JrB6u4H/ABARG4C/\ny9n7AQ2SBa9FRLwD+A5wQ2Ye7kMfe2XBa5GZv5yZ78rMd1Gt8/+nAQx9aO935M+AD0bE6oh4C9XJ\nvBd63M9eaOdaHAI+AlCrab8H+HFPe7k8dJybPRvxZ+aJiLgZmKY6Y39fZh6MiJtq++/OzEcj4qqI\nOAz8A/CJXvWvl9q5FsDngXOAu2oj3eOZeUW/+rxU2rwWpdDm78ihiJii+qbIk1TfLDlwwd/mv4s/\nBO6PiP1UB7Gfy8w3+9bpJRIR3wI2AWsj4hXgNqolv65z0zdwSVLJ+NGLklQyBr8klYzBL0klY/BL\nUskY/JJUMga/JJWMwS9JJWPwS1LJ/H90HnxhfKFFXgAAAABJRU5ErkJggg==\n",
- "text": [
- "<matplotlib.figure.Figure at 0x10a339828>"
- ]
- }
- ],
- "prompt_number": 15
- },
+ "output_type": "display_data"
+ }
+ ],
+ "source": [
+ "plt.scatter(df.density, df.BurnedOut)\n",
+ "plt.xlim(0,1)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "And we see the very clear emergence of a critical value around 0.5, where the model quickly shifts from almost no trees being burned, to almost all of them.\n",
+ "\n",
+ "In this case we ran the model only once at each value. However, it's easy to have the BatchRunner execute multiple runs at each parameter combination, in order to generate more statistically reliable results. We do this using the *iteration* argument.\n",
+ "\n",
+ "Let's run the model 5 times at each parameter point, and export and plot the results as above."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 16,
+ "metadata": {
+ "collapsed": false
+ },
+ "outputs": [
{
- "cell_type": "markdown",
+ "data": {
+ "text/plain": [
+ "(0, 1)"
+ ]
+ },
+ "execution_count": 16,
"metadata": {},
- "source": [
- "And we see the very clear emergence of a critical value around 0.5, where the model quickly shifts from almost no trees being burned, to almost all of them.\n",
- "\n",
- "In this case we ran the model only once at each value. However, it's easy to have the BatchRunner execute multiple runs at each parameter combination, in order to generate more statistically reliable results. We do this using the *iteration* argument.\n",
- "\n",
- "Let's run the model 5 times at each parameter point, and export and plot the results as above."
- ]
+ "output_type": "execute_result"
},
{
- "cell_type": "code",
- "collapsed": false,
- "input": [
- "param_run = BatchRunner(ForestFire, param_set, iterations=5, model_reporters=model_reporter)\n",
- "param_run.run_all()\n",
- "df = param_run.get_model_vars_dataframe()\n",
- "plt.scatter(df.density, df.BurnedOut)\n",
- "plt.xlim(0,1)"
- ],
- "language": "python",
+ "data": {
+ "image/png": "iVBORw0KGgoAAAANSUhEUgAAAX4AAAEACAYAAAC08h1NAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAALEgAACxIB0t1+/AAAIABJREFUeJzt3X+QHOV95/H3V9J6rQWvpF0lOCAwBLBxbGF+XEBnOFif\nLaSQijnDVSgCOYwdgo3JGrQ67MiU0ZUxse+QTHQuDFawUF185nIhPkRCQOTMVlIum7PELwULkGzI\ngYi5SALWoB/sar/3x/O0pmemZ3Z2e3dmdvvzqupS9/TT3c+2dr/9zLefftrcHRERKY5Zra6AiIg0\nlwK/iEjBKPCLiBSMAr+ISMEo8IuIFIwCv4hIweQO/Gb2HTN71cy21Vh/uZk9ZWZPm9kPzezUvMcU\nEZGJm4wW/wZgeZ31PwfOc/dTga8A356EY4qIyATlDvzu/g/Aa3XW/8jd34iLjwGL8h5TREQmrtk5\n/k8DDzb5mCIikjKnWQcys48AnwLOadYxRUSkWlMCf7yhux5Y7u5VaSEz04BBIiIT4O423m2mPPCb\n2XHAXwFXuPvOWuUmUvmZyMxWu/vqVtejHehclOhclOhclEy00Zw78JvZ94DzgYVm9hJwM9AB4O53\nAV8GFgDfMj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m4H\nvujuHrsIz9Tuv42ciw7gDOCjQBfwIzP7sbvvmNKaNV8j52IV8KS795nZicAjZvYhd//lFNetHY0r\nbjYz8O8Cjk0tH0u4MtUrsyh+NtM0ci6IN3TXA8vdvd5XvemskXNxJnBviPksBH7LzIbdfVNzqtg0\njZyLl4Dd7r4f2G9mfw98CJhpgb+Rc/Fh4KsA7v4zM3sBeB+wpSk1bB/jjpvNTPVsAU42s+PN7B3A\npYSHwNI2Af8BwMyWAK97aTygmWTMc2FmxwF/BVzh7jtbUMdmGfNcuPuvu/sJ7n4CIc//2RkY9KGx\nv5H7gXPNbLaZdRFu5v20yfVshkbOxbPAxwBiTvt9wM+bWsv2MO642bQWv7uPmNl1wMOEO/Z3u/t2\nM7smrr/L3R80swvNbCfwFnBVs+rXTI2cC+DLwALgW7GlO+zuZ7WqzlOlwXNRCA3+jTxrZg8RHooc\nJTwsOeMCf4O/F7cCG8zsKUIj9kZ339uySk8RM/secD6w0MxeAm4mpPwmHDf1AJeISMHo1YsiIgWj\nwC8iUjAK/CIiBaPALyJSMAr8IiIFo8AvIlIwCvwiIgWjwC8iUjD/H15+d1SmsbWuAAAAAElFTkSu\nQmCC\n",
+ "text/plain": [
+ "<matplotlib.figure.Figure at 0x10a417710>"
+ ]
+ },
"metadata": {},
- "outputs": [
- {
- "metadata": {},
- "output_type": "pyout",
- "prompt_number": 16,
- "text": [
- "(0, 1)"
- ]
- },
- {
- "metadata": {},
- "output_type": "display_data",
- "png": "iVBORw0KGgoAAAANSUhEUgAAAX4AAAEACAYAAAC08h1NAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAALEgAACxIB0t1+/AAAIABJREFUeJzt3X90HOV97/H3V1rW2LGNvRI/DMYmKAQIMSCTELfkxsoF\nIYcGp9g9SSikuqQxpC1xUsmBEJvEt5bCyQ84XJrc8KMpdpO03HtK6BX3gIWTRk7hQFL/iHEJTrFN\ncqEmnNjKD2icCOHv/WNmpNnZH1pppV1J+3mds4eZnWdnnh2s7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DPAPOBr4Yt3dfc/eJq\n1XmilHguakKJfyP7zGwrwU2Rxwhulpx2gb/EfxefA+43sz0Ejdib3L2/apWeIGb2D8ByoNHMXgA+\nS5DyG3Pc1A1cIiI1Ro9eFBGpMQr8IiI1RoFfRKTGKPCLiNQYBX4RkRqjwC8iUmMU+EVEaowCv4hI\njfn/vIVXkfM6S7gAAAAASUVORK5CYII=\n",
- "text": [
- "<matplotlib.figure.Figure at 0x109eb1be0>"
- ]
- }
- ],
- "prompt_number": 16
+ "output_type": "display_data"
}
],
- "metadata": {}
+ "source": [
+ "param_run = BatchRunner(ForestFire, param_set, iterations=5, model_reporters=model_reporter)\n",
+ "param_run.run_all()\n",
+ "df = param_run.get_model_vars_dataframe()\n",
+ "plt.scatter(df.density, df.BurnedOut)\n",
+ "plt.xlim(0,1)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": true
+ },
+ "outputs": [],
+ "source": []
}
- ]
-}
\ No newline at end of file
+ ],
+ "metadata": {
+ "kernelspec": {
+ "display_name": "Python 3",
+ "language": "python",
+ "name": "python3"
+ },
+ "language_info": {
+ "codemirror_mode": {
+ "name": "ipython",
+ "version": 3
+ },
+ "file_extension": ".py",
+ "mimetype": "text/x-python",
+ "name": "python",
+ "nbconvert_exporter": "python",
+ "pygments_lexer": "ipython3",
+ "version": "3.4.2"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 0
+}
diff --git a/examples/ForestFire/Forest Fire Model.ipynb b/examples/ForestFire/Forest Fire Model.ipynb
index 8c8746c5..72b54805 100644
--- a/examples/ForestFire/Forest Fire Model.ipynb
+++ b/examples/ForestFire/Forest Fire Model.ipynb
@@ -1,584 +1,621 @@
{
- "metadata": {
- "name": "",
- "signature": "sha256:7ad05bb257a0bc7d9176a2a5e02312695873a50206c8335653a47975f4e4ee8c"
- },
- "nbformat": 3,
- "nbformat_minor": 0,
- "worksheets": [
+ "cells": [
{
- "cells": [
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "# The Forest Fire Model\n",
- "## A rapid introduction to Mesa\n",
- "\n",
- "The [Forest Fire Model](http://en.wikipedia.org/wiki/Forest-fire_model) is one of the simplest examples of a model that exhibits self-organized criticality.\n",
- "\n",
- "Mesa is a new, Pythonic agent-based modeling framework. A big advantage of using Python is that it a great language for interactive data analysis. Unlike some other ABM frameworks, with Mesa you can write a model, run it, and analyze it all in the same environment. (You don't have to, of course. But you can).\n",
- "\n",
- "In this notebook, we'll go over a rapid-fire (pun intended, sorry) introduction to building and analyzing a model with Mesa."
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "First, some imports. We'll go over what all the Mesa ones mean just below."
- ]
- },
- {
- "cell_type": "code",
- "collapsed": false,
- "input": [
- "import random\n",
- "\n",
- "import numpy as np\n",
- "\n",
- "import matplotlib.pyplot as plt\n",
- "%matplotlib inline\n",
- "\n",
- "from mesa import Model, Agent\n",
- "from mesa.time import RandomActivation\n",
- "from mesa.space import Grid\n",
- "from mesa.datacollection import DataCollector\n",
- "from mesa.batchrunner import BatchRunner "
- ],
- "language": "python",
- "metadata": {},
- "outputs": [],
- "prompt_number": 1
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Building the model\n",
- "\n",
- "Most models consist of basically two things: agents, and an world for the agents to be in. The Forest Fire model has only one kind of agent: a tree. A tree can either be unburned, on fire, or already burned. The environment is a grid, where each cell can either be empty or contain a tree.\n",
- "\n",
- "First, let's define our tree agent. The agent needs to be assigned **x** and **y** coordinates on the grid, and that's about it. We could assign agents a condition to be in, but for now let's have them all start as being 'Fine'. Since the agent doesn't move, and there is only at most one tree per cell, we can use a tuple of its coordinates as a unique identifier.\n",
- "\n",
- "Next, we define the agent's **step** method. This gets called whenever the agent needs to act in the world and takes the *model* object to which it belongs as an input. The tree's behavior is simple: If it is currently on fire, it spreads the fire to any trees above, below, to the left and the right of it that are not themselves burned out or on fire; then it burns itself out. "
- ]
- },
- {
- "cell_type": "code",
- "collapsed": false,
- "input": [
- "class TreeCell(Agent):\n",
- " '''\n",
- " A tree cell.\n",
- " \n",
- " Attributes:\n",
- " x, y: Grid coordinates\n",
- " condition: Can be \"Fine\", \"On Fire\", or \"Burned Out\"\n",
- " unique_id: (x,y) tuple. \n",
- " \n",
- " unique_id isn't strictly necessary here, but it's good practice to give one to each\n",
- " agent anyway.\n",
- " '''\n",
- " def __init__(self, x, y):\n",
- " '''\n",
- " Create a new tree.\n",
- " Args:\n",
- " x, y: The tree's coordinates on the grid.\n",
- " '''\n",
- " self.x = x\n",
- " self.y = y\n",
- " self.unique_id = (x, y)\n",
- " self.condition = \"Fine\"\n",
- " \n",
- " def step(self, model):\n",
- " '''\n",
- " If the tree is on fire, spread it to fine trees nearby.\n",
- " '''\n",
- " if self.condition == \"On Fire\":\n",
- " neighbors = model.grid.get_neighbors(self.x, self.y, moore=False)\n",
- " for neighbor in neighbors:\n",
- " if neighbor.condition == \"Fine\":\n",
- " neighbor.condition = \"On Fire\"\n",
- " self.condition = \"Burned Out\"\n",
- " "
- ],
- "language": "python",
- "metadata": {},
- "outputs": [],
- "prompt_number": 2
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "Now we need to define the model object itself. The main thing the model needs is the grid, which the trees are placed on. But since the model is dynamic, it also needs to include time -- it needs a schedule, to manage the trees activation as they spread the fire from one to the other.\n",
- "\n",
- "The model also needs a few parameters: how large the grid is and what the density of trees on it will be. Density will be the key parameter we'll explore below.\n",
- "\n",
- "Finally, we'll give the model a data collector. This is a Mesa object which collects and stores data on the model as it runs for later analysis.\n",
- "\n",
- "The constructor needs to do a few things. It instantiates all the model-level variables and objects; it randomly places trees on the grid, based on the density parameter; and it starts the fire by setting all the trees on one edge of the grid (x=0) as being On \"Fire\".\n",
- "\n",
- "Next, the model needs a **step** method. Like at the agent level, this method defines what happens every step of the model. We want to activate all the trees, one at a time; then we run the data collector, to count how many trees are currently on fire, burned out, or still fine. If there are no trees left on fire, we stop the model by setting its **running** property to False."
- ]
- },
- {
- "cell_type": "code",
- "collapsed": false,
- "input": [
- "class ForestFire(Model):\n",
- " '''\n",
- " Simple Forest Fire model.\n",
- " '''\n",
- " def __init__(self, height, width, density):\n",
- " '''\n",
- " Create a new forest fire model.\n",
- " \n",
- " Args:\n",
- " height, width: The size of the grid to model\n",
- " density: What fraction of grid cells have a tree in them.\n",
- " '''\n",
- " # Initialize model parameters\n",
- " self.height = height\n",
- " self.width = width\n",
- " self.density = density\n",
- " \n",
- " # Set up model objects\n",
- " self.schedule = RandomActivation(self)\n",
- " self.grid = Grid(height, width, torus=False)\n",
- " self.dc = DataCollector({\"Fine\": lambda m: self.count_type(m, \"Fine\"),\n",
- " \"On Fire\": lambda m: self.count_type(m, \"On Fire\"),\n",
- " \"Burned Out\": lambda m: self.count_type(m, \"Burned Out\")})\n",
- " \n",
- " # Place a tree in each cell with Prob = density\n",
- " for x in range(self.width):\n",
- " for y in range(self.height):\n",
- " if random.random() < self.density:\n",
- " # Create a tree\n",
- " new_tree = TreeCell(x, y)\n",
- " # Set all trees in the first column on fire.\n",
- " if x == 0:\n",
- " new_tree.condition = \"On Fire\"\n",
- " self.grid[y][x] = new_tree\n",
- " self.schedule.add(new_tree)\n",
- " self.running = True\n",
- " \n",
- " def step(self):\n",
- " '''\n",
- " Advance the model by one step.\n",
- " '''\n",
- " self.schedule.step()\n",
- " self.dc.collect(self)\n",
- " # Halt if no more fire\n",
- " if self.count_type(self, \"On Fire\") == 0:\n",
- " self.running = False\n",
- " \n",
- " @staticmethod\n",
- " def count_type(model, tree_condition):\n",
- " '''\n",
- " Helper method to count trees in a given condition in a given model.\n",
- " '''\n",
- " count = 0\n",
- " for tree in model.schedule.agents:\n",
- " if tree.condition == tree_condition:\n",
- " count += 1\n",
- " return count"
- ],
- "language": "python",
- "metadata": {},
- "outputs": [],
- "prompt_number": 3
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Running the model\n",
- "\n",
- "Let's create a model with a 100 x 100 grid, and a tree density of 0.6. Remember, ForestFire takes the arguments *height*, *width*, *density*."
- ]
- },
- {
- "cell_type": "code",
- "collapsed": false,
- "input": [
- "fire = ForestFire(100, 100, 0.6)"
- ],
- "language": "python",
- "metadata": {},
- "outputs": [],
- "prompt_number": 4
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "To run the model until it's done (that is, until it sets its **running** property to False) just use the **run_model()** method. This is implemented in the Model parent object, so we didn't need to implement it above."
- ]
- },
- {
- "cell_type": "code",
- "collapsed": false,
- "input": [
- "fire.run_model()"
- ],
- "language": "python",
- "metadata": {},
- "outputs": [],
- "prompt_number": 5
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "That's all there is to it!\n",
- "\n",
- "But... so what? This code doesn't include a visualization, after all. \n",
- "\n",
- "**TODO: Add a MatPlotLib visualization**\n",
- "\n",
- "Remember the data collector? Now we can put the data it collected into a pandas DataFrame:"
- ]
- },
- {
- "cell_type": "code",
- "collapsed": false,
- "input": [
- "results = fire.dc.get_model_vars_dataframe()"
- ],
- "language": "python",
- "metadata": {},
- "outputs": [],
- "prompt_number": 6
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "And chart it, to see the dynamics."
- ]
- },
- {
- "cell_type": "code",
- "collapsed": false,
- "input": [
- "results.plot()"
- ],
- "language": "python",
- "metadata": {},
- "outputs": [
- {
- "metadata": {},
- "output_type": "pyout",
- "prompt_number": 7,
- "text": [
- "<matplotlib.axes._subplots.AxesSubplot at 0x10988b2e8>"
- ]
- },
- {
- "metadata": {},
- "output_type": "display_data",
- "png": "iVBORw0KGgoAAAANSUhEUgAAAXkAAAEACAYAAABWLgY0AAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAALEgAACxIB0t1+/AAAIABJREFUeJzt3Xl4VOXZ+PHvnYXsGwmEsAZe2UFBlKXCS0Tpixa3umHF\nithWi1KXqgVtxbZuuLVqtfWnCC51wV0REETSugIqASRsAYMQISQhC0kI2Z7fH89M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ivsbt418QnItHAW8BNxph9vo+5JRZjTK2x\n5ZquwP+KyJkHPe74OERkIrDHGLMaaHT8sxvi8DjDGDMUOAdbBmxwZiqXxBECnAo8bYw5FSjjoNKM\nU+NwSpLPAbr5zHfD9ubdKldEOgGISAqwx8/taRYRCcUm+JeMMe96FrsyFgBjTDHwITAM98XxE+B8\nEfkeeBUYJyIv4b44MMbs8tzmAe9gz2Hltjh2AjuNMas8829ik/5up8fhlCT/NdBbRFJFpB1wOfC+\nn9t0PN4Hrvbcvxpb33Y0ERFgDpBpjPm7z0OuikVEkrwjHEQkAhgPrMZlcRhj7jTGdDPG9AQmAZ8Y\nY67CZXGISKSIxHjuRwE/BdbhsjiMMbuBHSLSx7PobGA98AFOj8PfBwV8DmCcg/01bBYw09/tOYp2\nv4r99W4l9rjCNUB77AGzzcASIN7f7WxGHKOxtd8MbFJcjR015KpYgMHAt5441gK3e5a7Ko6DYhoL\nvO/GOLC17AzP9J33f9ttcXjafAr2QP4a4G3swVjHx6E/hlJKqQDmlHKNUkqpVqBJXimlApgmeaWU\nCmCa5JVSKoBpkldKqQCmSV4ppQKYJnmllApgmuSVUiqA/X9Qq9l5Pb7B1AAAAABJRU5ErkJggg==\n",
- "text": [
- "<matplotlib.figure.Figure at 0x10987db70>"
- ]
- }
- ],
- "prompt_number": 7
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "In this case, the fire burned itself out after about 90 steps, with many trees left unburned. \n",
- "\n",
- "You can try changing the density parameter and rerunning the code above, to see how different densities yield different dynamics. For example:"
- ]
- },
- {
- "cell_type": "code",
- "collapsed": false,
- "input": [
- "fire = ForestFire(100, 100, 0.8)\n",
- "fire.run_model()\n",
- "results = fire.dc.get_model_vars_dataframe()\n",
- "results.plot()"
- ],
- "language": "python",
- "metadata": {},
- "outputs": [
- {
- "metadata": {},
- "output_type": "pyout",
- "prompt_number": 8,
- "text": [
- "<matplotlib.axes._subplots.AxesSubplot at 0x109c54208>"
- ]
- },
- {
- "metadata": {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oqQ7gBlJ54oHy8pflzP5\nX4Dhwv4w6Wy+TZYk3Qkg6S7gQo/7UxpJg6QCP2X7SG5uTX4A238A08DDtCP7o8CYpJ+Bw8ATkqZo\nR3YAbC/m378Dn5OGqUvPX5cifwq4V9I2SZuAceBoj/tUtaPAvry9Dzhyjc9uWEqn7JPAgu0PCoca\nn1/Slu7sCUk3Ak8Bc7Qgu+23bQ/b3g68CMzafokWZAeQdJOkW/P2zcDTwBkqyF+befKSnmHlOfOT\ntid63KXSSDoM7Aa2kMbh3gG+AD4F7gE6wAu2N+abg68hzyb5FjjNyjDdAdLq50bnl/Qg6eZaX/6Z\nsv2epM00PHuRpN3AG7bH2pJd0nbS2TukYfJPbE9Ukb82RT6EEML6q8twTQghhBJEkQ8hhAaLIh9C\nCA0WRT6EEBosinwIITRYFPkQQmiwKPIhhNBgUeRDCKHB/gXedjkAMUGImgAAAABJRU5ErkJggg==\n",
- "text": [
- "<matplotlib.figure.Figure at 0x109c517b8>"
- ]
- }
- ],
- "prompt_number": 8
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "... But to really understand how the final outcome varies with density, we can't just tweak the parameter by hand over and over again. We need to do a batch run. \n",
- "\n",
- "## Batch runs\n",
- "\n",
- "Batch runs, also called parameter sweeps, allow use to systemically vary the density parameter, run the model, and check the output. Mesa provides a BatchRunner object which takes a model class, a dictionary of parameters and the range of values they can take and runs the model at each combination of these values. We can also give it reporters, which collect some data on the model at the end of each run and store it, associated with the parameters that produced it.\n",
- "\n",
- "For ease of typing and reading, we'll first create the parameters to vary and the reporter, and then assign them to a new BatchRunner."
- ]
- },
- {
- "cell_type": "code",
- "collapsed": false,
- "input": [
- "param_set = dict(height=50, # Height and width are constant\n",
- " width=50,\n",
- " # Vary density from 0.01 to 1, in 0.01 increments:\n",
- " density=np.linspace(0,1,101)[1:]) "
- ],
- "language": "python",
- "metadata": {},
- "outputs": [],
- "prompt_number": 9
- },
- {
- "cell_type": "code",
- "collapsed": false,
- "input": [
- "# At the end of each model run, calculate the fraction of trees which are Burned Out\n",
- "model_reporter = {\"BurnedOut\": lambda m: (ForestFire.count_type(m, \"Burned Out\") / \n",
- " m.schedule.get_agent_count()) }"
- ],
- "language": "python",
- "metadata": {},
- "outputs": [],
- "prompt_number": 10
- },
- {
- "cell_type": "code",
- "collapsed": false,
- "input": [
- "# Create the batch runner\n",
- "param_run = BatchRunner(ForestFire, param_set, model_reporters=model_reporter)"
- ],
- "language": "python",
- "metadata": {},
- "outputs": [],
- "prompt_number": 11
- },
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "# The Forest Fire Model\n",
+ "## A rapid introduction to Mesa\n",
+ "\n",
+ "The [Forest Fire Model](http://en.wikipedia.org/wiki/Forest-fire_model) is one of the simplest examples of a model that exhibits self-organized criticality.\n",
+ "\n",
+ "Mesa is a new, Pythonic agent-based modeling framework. A big advantage of using Python is that it a great language for interactive data analysis. Unlike some other ABM frameworks, with Mesa you can write a model, run it, and analyze it all in the same environment. (You don't have to, of course. But you can).\n",
+ "\n",
+ "In this notebook, we'll go over a rapid-fire (pun intended, sorry) introduction to building and analyzing a model with Mesa."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "First, some imports. We'll go over what all the Mesa ones mean just below."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 1,
+ "metadata": {
+ "collapsed": false
+ },
+ "outputs": [],
+ "source": [
+ "import random\n",
+ "\n",
+ "import numpy as np\n",
+ "\n",
+ "import matplotlib.pyplot as plt\n",
+ "%matplotlib inline\n",
+ "\n",
+ "from mesa import Model, Agent\n",
+ "from mesa.time import RandomActivation\n",
+ "from mesa.space import Grid\n",
+ "from mesa.datacollection import DataCollector\n",
+ "from mesa.batchrunner import BatchRunner "
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Building the model\n",
+ "\n",
+ "Most models consist of basically two things: agents, and an world for the agents to be in. The Forest Fire model has only one kind of agent: a tree. A tree can either be unburned, on fire, or already burned. The environment is a grid, where each cell can either be empty or contain a tree.\n",
+ "\n",
+ "First, let's define our tree agent. The agent needs to be assigned **x** and **y** coordinates on the grid, and that's about it. We could assign agents a condition to be in, but for now let's have them all start as being 'Fine'. Since the agent doesn't move, and there is only at most one tree per cell, we can use a tuple of its coordinates as a unique identifier.\n",
+ "\n",
+ "Next, we define the agent's **step** method. This gets called whenever the agent needs to act in the world and takes the *model* object to which it belongs as an input. The tree's behavior is simple: If it is currently on fire, it spreads the fire to any trees above, below, to the left and the right of it that are not themselves burned out or on fire; then it burns itself out. "
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 2,
+ "metadata": {
+ "collapsed": false
+ },
+ "outputs": [],
+ "source": [
+ "class TreeCell(Agent):\n",
+ " '''\n",
+ " A tree cell.\n",
+ " \n",
+ " Attributes:\n",
+ " x, y: Grid coordinates\n",
+ " condition: Can be \"Fine\", \"On Fire\", or \"Burned Out\"\n",
+ " unique_id: (x,y) tuple. \n",
+ " \n",
+ " unique_id isn't strictly necessary here, but it's good practice to give one to each\n",
+ " agent anyway.\n",
+ " '''\n",
+ " def __init__(self, x, y):\n",
+ " '''\n",
+ " Create a new tree.\n",
+ " Args:\n",
+ " x, y: The tree's coordinates on the grid.\n",
+ " '''\n",
+ " self.x = x\n",
+ " self.y = y\n",
+ " self.unique_id = (x, y)\n",
+ " self.condition = \"Fine\"\n",
+ " \n",
+ " def step(self, model):\n",
+ " '''\n",
+ " If the tree is on fire, spread it to fine trees nearby.\n",
+ " '''\n",
+ " if self.condition == \"On Fire\":\n",
+ " neighbors = model.grid.get_neighbors(self.x, self.y, moore=False)\n",
+ " for neighbor in neighbors:\n",
+ " if neighbor.condition == \"Fine\":\n",
+ " neighbor.condition = \"On Fire\"\n",
+ " self.condition = \"Burned Out\"\n",
+ " "
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Now we need to define the model object itself. The main thing the model needs is the grid, which the trees are placed on. But since the model is dynamic, it also needs to include time -- it needs a schedule, to manage the trees activation as they spread the fire from one to the other.\n",
+ "\n",
+ "The model also needs a few parameters: how large the grid is and what the density of trees on it will be. Density will be the key parameter we'll explore below.\n",
+ "\n",
+ "Finally, we'll give the model a data collector. This is a Mesa object which collects and stores data on the model as it runs for later analysis.\n",
+ "\n",
+ "The constructor needs to do a few things. It instantiates all the model-level variables and objects; it randomly places trees on the grid, based on the density parameter; and it starts the fire by setting all the trees on one edge of the grid (x=0) as being On \"Fire\".\n",
+ "\n",
+ "Next, the model needs a **step** method. Like at the agent level, this method defines what happens every step of the model. We want to activate all the trees, one at a time; then we run the data collector, to count how many trees are currently on fire, burned out, or still fine. If there are no trees left on fire, we stop the model by setting its **running** property to False."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 3,
+ "metadata": {
+ "collapsed": false
+ },
+ "outputs": [],
+ "source": [
+ "class ForestFire(Model):\n",
+ " '''\n",
+ " Simple Forest Fire model.\n",
+ " '''\n",
+ " def __init__(self, height, width, density):\n",
+ " '''\n",
+ " Create a new forest fire model.\n",
+ " \n",
+ " Args:\n",
+ " height, width: The size of the grid to model\n",
+ " density: What fraction of grid cells have a tree in them.\n",
+ " '''\n",
+ " # Initialize model parameters\n",
+ " self.height = height\n",
+ " self.width = width\n",
+ " self.density = density\n",
+ " \n",
+ " # Set up model objects\n",
+ " self.schedule = RandomActivation(self)\n",
+ " self.grid = Grid(height, width, torus=False)\n",
+ " self.dc = DataCollector({\"Fine\": lambda m: self.count_type(m, \"Fine\"),\n",
+ " \"On Fire\": lambda m: self.count_type(m, \"On Fire\"),\n",
+ " \"Burned Out\": lambda m: self.count_type(m, \"Burned Out\")})\n",
+ " \n",
+ " # Place a tree in each cell with Prob = density\n",
+ " for x in range(self.width):\n",
+ " for y in range(self.height):\n",
+ " if random.random() < self.density:\n",
+ " # Create a tree\n",
+ " new_tree = TreeCell(x, y)\n",
+ " # Set all trees in the first column on fire.\n",
+ " if x == 0:\n",
+ " new_tree.condition = \"On Fire\"\n",
+ " self.grid[y][x] = new_tree\n",
+ " self.schedule.add(new_tree)\n",
+ " self.running = True\n",
+ " \n",
+ " def step(self):\n",
+ " '''\n",
+ " Advance the model by one step.\n",
+ " '''\n",
+ " self.schedule.step()\n",
+ " self.dc.collect(self)\n",
+ " # Halt if no more fire\n",
+ " if self.count_type(self, \"On Fire\") == 0:\n",
+ " self.running = False\n",
+ " \n",
+ " @staticmethod\n",
+ " def count_type(model, tree_condition):\n",
+ " '''\n",
+ " Helper method to count trees in a given condition in a given model.\n",
+ " '''\n",
+ " count = 0\n",
+ " for tree in model.schedule.agents:\n",
+ " if tree.condition == tree_condition:\n",
+ " count += 1\n",
+ " return count"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Running the model\n",
+ "\n",
+ "Let's create a model with a 100 x 100 grid, and a tree density of 0.6. Remember, ForestFire takes the arguments *height*, *width*, *density*."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 4,
+ "metadata": {
+ "collapsed": false
+ },
+ "outputs": [],
+ "source": [
+ "fire = ForestFire(100, 100, 0.6)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "To run the model until it's done (that is, until it sets its **running** property to False) just use the **run_model()** method. This is implemented in the Model parent object, so we didn't need to implement it above."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 5,
+ "metadata": {
+ "collapsed": false
+ },
+ "outputs": [],
+ "source": [
+ "fire.run_model()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "That's all there is to it!\n",
+ "\n",
+ "But... so what? This code doesn't include a visualization, after all. \n",
+ "\n",
+ "**TODO: Add a MatPlotLib visualization**\n",
+ "\n",
+ "Remember the data collector? Now we can put the data it collected into a pandas DataFrame:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 6,
+ "metadata": {
+ "collapsed": false
+ },
+ "outputs": [],
+ "source": [
+ "results = fire.dc.get_model_vars_dataframe()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "And chart it, to see the dynamics."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 7,
+ "metadata": {
+ "collapsed": false
+ },
+ "outputs": [
{
- "cell_type": "markdown",
+ "data": {
+ "text/plain": [
+ "<matplotlib.axes._subplots.AxesSubplot at 0x109a3eda0>"
+ ]
+ },
+ "execution_count": 7,
"metadata": {},
- "source": [
- "Now the BatchRunner, which we've named param_run, is ready to go. To run the model at every combination of parameters (in this case, every density value), just use the **run_all()** method."
- ]
+ "output_type": "execute_result"
},
{
- "cell_type": "code",
- "collapsed": false,
- "input": [
- "param_run.run_all()"
- ],
- "language": "python",
+ "data": {
+ "image/png": "iVBORw0KGgoAAAANSUhEUgAAAXsAAAEACAYAAABS29YJAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAALEgAACxIB0t1+/AAAIABJREFUeJztnXncVFX9x98fFlEWWUQBWTU3MM0lFUsDFwzLvYRMVNQy\nw1SyVCjzOtXPrSyztFJJXErFJc0lFFHTMsVMlERFVExIEBQEVBTk+/vjnHkYludhnoeZuXfm+b5f\nr/uauedun3vn3u898z3f8z0yMxzHcZzapkXaAhzHcZzy48becRynGeDG3nEcpxngxt5xHKcZ4Mbe\ncRynGeDG3nEcpxlQlLGX1EnS7ZJelDRd0l6SukiaJGmGpAcldSpYf6ykVyS9JOmggvLdJU2Ly35V\njhNyHMdx1qbYmv2vgPvNrD+wM/ASMAaYZGbbAZPjPJIGAMOBAcBQ4CpJivv5LXCymW0LbCtpaMnO\nxHEcx6mX9Rp7SR2Bfc3sDwBmtsLM3gMOA66Pq10PHBG/Hw7cbGbLzWwWMBPYS1IPoIOZTYnr3VCw\njeM4jlNGiqnZbwXMl3SdpH9LukZSO6Cbmc2L68wDusXvWwKzC7afDfRcR/mcWO44juOUmWKMfStg\nN+AqM9sNeJ/ossljIeeC511wHMfJKK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mmJfRHYjgFcDLwEdCWM9HcecH5xOzTL1BQkpa+jcZrtZLAZYF3S1pKB\n3y6T9OvXzyZPnlw3f99999l2221XNz9o0CC79tpr6+avu+4622effermJdmVV15p22yzjW299db2\n6KOPWs+ePe2yyy6zLbbYwnr06GHXXXdd3frLli2z733ve9anTx/r1q2bnXrqqfbhhx/WLb/00kut\nR48e1rNnTxs3bpxJsldffXUt3StXrrQ+ffrYz372s7XKP/3pT9v5559vZmZJktiIESPqlr/++usm\nyVasWGE/+MEPrGXLlrbxxhtb+/bt7fTTT1/nNarGZ8+n1Z69Btfxmn0TKMwpLTEYuJAQYvluWprW\npBpyc1ea+FDwwQcfcOutt7L33nvXLZO03trv3XffzdNPP8306dMxM+bNm8fixYv53//+x7hx4zjt\ntNN4772QQmXMmDHMnDmT5557jpkzZzJnzhx+/OMfAzBx4kQuu+wyHnroIWbMmMFDDz1U7zFffvll\n3nzzTY4++ujVyiXxla98hUmTJjWoWRL/93//x7777suVV17JkiVLuOKKdWYOKCvVcD/WukY39huA\nRHfgZuBYM2akrSfrSKWZmoKZccQRR9C5c2c6derE5MmT+f73v9+ofYwdO5ZOnTrRpk0bAFq3bs35\n559Py5YtOfjgg2nfvj0vv/wyZsY111zDL37xCzp16kT79u0ZO3Yst9xyCwATJkzgpJNOYsCAAbRt\n25ZcLlfvMRcsWABAjx491lrWvXv3uuXFkH/ZOc0T71TVBMzs0Th04HWEPPT1V81SwjLmfwRI09ZI\n4u6772b//ffHzLjrrrsYNGgQL774IltssUVR++jdu/dq85ttthktWqyqL7Vt25alS5cyf/58Pvjg\nA3bfffe6ZWbGypWhx/xbb73FHnvsUbesT58+9R6za9euddv07dt3tWVvvfUWm2++eVHaIV2/fRbv\nxzWpdY1es286pwGbAfVXy5xMIokjjzySli1b8ve//x2Adu3a8f7779etM3fu3HVuVwxdu3Zlk002\nYfr06SxcuJCFCxeyaNEiFi8Ogyj16NGD//73v3XrF35fk+23355evXoxYcKE1cpXrlzJHXfcwQEH\nHFC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h0IKHb+z1kRCMhB9JASZvE3/1AYDrZ0pinvt/2L8DXJG0kaSvC3/8pKehD0lBCLfRw\nMyvszp8JjWY2zcy6mdlW8dmZDewW3WOZ0FjAXYQUK8RnaCMzW0BjdVaihbnIVuiDCdEuM4GxaeuJ\nmvYh+MGnEpKjPUvIj9IFeIiQDfNBoFPaWqPeQayKxsmURkISq6cJ+U3uJETjZE3jOYSX0DRCw2fr\ntDUS/q39j5Aj503gxIY0EVwTMwkvry+mpPEkQtK4Nwqem6syovGj/HVcY/lrxGictDTWpzPehzfG\n+/IZYHBTdHqnKsdxnGZAVtw4juM4ThlxY+84jtMMcGPvOI7TDHBj7ziO0wxwY+84jtMMcGPvOI7T\nDHBj7ziO0wxwY+84jtMM+H8bqxBDsJagjAAAAABJRU5ErkJggg==\n",
+ "text/plain": [
+ "<matplotlib.figure.Figure at 0x109a3e5f8>"
+ ]
+ },
"metadata": {},
- "outputs": [],
- "prompt_number": 12
- },
+ "output_type": "display_data"
+ }
+ ],
+ "source": [
+ "results.plot()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "In this case, the fire burned itself out after about 90 steps, with many trees left unburned. \n",
+ "\n",
+ "You can try changing the density parameter and rerunning the code above, to see how different densities yield different dynamics. For example:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 8,
+ "metadata": {
+ "collapsed": false
+ },
+ "outputs": [
{
- "cell_type": "markdown",
+ "data": {
+ "text/plain": [
+ "<matplotlib.axes._subplots.AxesSubplot at 0x109e2b470>"
+ ]
+ },
+ "execution_count": 8,
"metadata": {},
- "source": [
- "Like with the data collector, we can extract the data the batch runner collected into a dataframe:"
- ]
+ "output_type": "execute_result"
},
{
- "cell_type": "code",
- "collapsed": false,
- "input": [
- "df = param_run.get_model_vars_dataframe()"
- ],
- "language": "python",
+ "data": {
+ "image/png": "iVBORw0KGgoAAAANSUhEUgAAAXkAAAEACAYAAABWLgY0AAAABHNCSVQICAgIfAhkiAA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VwiJn1wGUqPETSgSTIxjTOB6ayrhdc0mw0oLeZ7WFm+0RlSbNxA/LCyZM2SMpc//TUIKmCxsxe\nw3XHSudoXN5qotdjcyoqg5jZXDObHK0vww1q60CCbAQw160PXN/9UtwzTZSNkrbGDYK7G9dfHBJm\nY0TFHihJtHE98sXJdwC+StueFZUlkbZmNi9an4cbvFXwSOoM7IFLC50oGyWVSJqMs2WimX1EwmwE\n/ozLupg+0CZpNhrwkqR3JJ0ZlSXNxg3I9WCojVGUrb9RTuWCt11SU+Bx4HwzW+oGUzqSYKO5wTM9\nJLUAXpR0SIX9BW2jXHqGb8zs/Y1NFlLoNkYcYGZzJG0BTJA0LX1nQmzcgHypyc8GOqZtd8TV5pPI\nPMmlLJXUHjccumCRtCnOwT9oZk9GxYmyMYWZLcZlIOxJsmzcHzha0ufAaOCnkh4kWTZiZnOi1/nA\nP3Bh4kTZWBn54uTfAbpI6iyX2+NE4OmYNf1/O3eM0kAUBnH8P5aKjdha5ACeIZWCjWWwkRzCSi+Q\nwsYLpBIRrNQDpPACgoK1rZ03GIu3kjSxiSHLx/xgYWG32GmG5e3bb12egXF3PgYe/7i319Re2afA\nh+2bhUuVMu7/7rhQm+NzBLxSKKPtK9sHtgfAGTCzfU6hjJK2Je125zvAMfBOoYzL9GafvKQT5nPm\np7YnG36klUm6B4a0WRdftJnUT8ADbUjRJzCy/b2pZ1xFt8vkBXhjvuR2SfuTuUrGQ9oHua3uuLV9\nLWmPIhkXSRoCF7ZPK2WUNKC9vUNbpr6zPamUcZnelHxERPy/vizXRETEGqTkIyIKS8lHRBSWko+I\nKCwlHxFRWEo+IqKwlHxERGEp+YiIwn4A7VrCBdJQ0o4AAAAASUVORK5CYII=\n",
+ "text/plain": [
+ "<matplotlib.figure.Figure at 0x109a3e5c0>"
+ ]
+ },
"metadata": {},
- "outputs": [],
- "prompt_number": 13
- },
+ "output_type": "display_data"
+ }
+ ],
+ "source": [
+ "fire = ForestFire(100, 100, 0.8)\n",
+ "fire.run_model()\n",
+ "results = fire.dc.get_model_vars_dataframe()\n",
+ "results.plot()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "... But to really understand how the final outcome varies with density, we can't just tweak the parameter by hand over and over again. We need to do a batch run. \n",
+ "\n",
+ "## Batch runs\n",
+ "\n",
+ "Batch runs, also called parameter sweeps, allow use to systemically vary the density parameter, run the model, and check the output. Mesa provides a BatchRunner object which takes a model class, a dictionary of parameters and the range of values they can take and runs the model at each combination of these values. We can also give it reporters, which collect some data on the model at the end of each run and store it, associated with the parameters that produced it.\n",
+ "\n",
+ "For ease of typing and reading, we'll first create the parameters to vary and the reporter, and then assign them to a new BatchRunner."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 9,
+ "metadata": {
+ "collapsed": false
+ },
+ "outputs": [],
+ "source": [
+ "param_set = dict(height=50, # Height and width are constant\n",
+ " width=50,\n",
+ " # Vary density from 0.01 to 1, in 0.01 increments:\n",
+ " density=np.linspace(0,1,101)[1:]) "
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 10,
+ "metadata": {
+ "collapsed": false
+ },
+ "outputs": [],
+ "source": [
+ "# At the end of each model run, calculate the fraction of trees which are Burned Out\n",
+ "model_reporter = {\"BurnedOut\": lambda m: (ForestFire.count_type(m, \"Burned Out\") / \n",
+ " m.schedule.get_agent_count()) }"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 11,
+ "metadata": {
+ "collapsed": false
+ },
+ "outputs": [],
+ "source": [
+ "# Create the batch runner\n",
+ "param_run = BatchRunner(ForestFire, param_set, model_reporters=model_reporter)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Now the BatchRunner, which we've named param_run, is ready to go. To run the model at every combination of parameters (in this case, every density value), just use the **run_all()** method."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 12,
+ "metadata": {
+ "collapsed": false
+ },
+ "outputs": [],
+ "source": [
+ "param_run.run_all()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Like with the data collector, we can extract the data the batch runner collected into a dataframe:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 13,
+ "metadata": {
+ "collapsed": false
+ },
+ "outputs": [],
+ "source": [
+ "df = param_run.get_model_vars_dataframe()"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 14,
+ "metadata": {
+ "collapsed": false
+ },
+ "outputs": [
{
- "cell_type": "code",
- "collapsed": false,
- "input": [
- "df.head()"
- ],
- "language": "python",
+ "data": {
+ "text/html": [
+ "<div style=\"max-height:1000px;max-width:1500px;overflow:auto;\">\n",
+ "<table border=\"1\" class=\"dataframe\">\n",
+ " <thead>\n",
+ " <tr style=\"text-align: right;\">\n",
+ " <th></th>\n",
+ " <th>BurnedOut</th>\n",
+ " <th>Run</th>\n",
+ " <th>density</th>\n",
+ " <th>height</th>\n",
+ " <th>width</th>\n",
+ " </tr>\n",
+ " </thead>\n",
+ " <tbody>\n",
+ " <tr>\n",
+ " <th>0</th>\n",
+ " <td> 0.009288</td>\n",
+ " <td> 11</td>\n",
+ " <td> 0.12</td>\n",
+ " <td> 50</td>\n",
+ " <td> 50</td>\n",
+ " </tr>\n",
+ " <tr>\n",
+ " <th>1</th>\n",
+ " <td> 1.000000</td>\n",
+ " <td> 98</td>\n",
+ " <td> 0.99</td>\n",
+ " <td> 50</td>\n",
+ " <td> 50</td>\n",
+ " </tr>\n",
+ " <tr>\n",
+ " <th>2</th>\n",
+ " <td> 0.092608</td>\n",
+ " <td> 48</td>\n",
+ " <td> 0.49</td>\n",
+ " <td> 50</td>\n",
+ " <td> 50</td>\n",
+ " </tr>\n",
+ " <tr>\n",
+ " <th>3</th>\n",
+ " <td> 0.024691</td>\n",
+ " <td> 3</td>\n",
+ " <td> 0.04</td>\n",
+ " <td> 50</td>\n",
+ " <td> 50</td>\n",
+ " </tr>\n",
+ " <tr>\n",
+ " <th>4</th>\n",
+ " <td> 0.060748</td>\n",
+ " <td> 42</td>\n",
+ " <td> 0.43</td>\n",
+ " <td> 50</td>\n",
+ " <td> 50</td>\n",
+ " </tr>\n",
+ " </tbody>\n",
+ "</table>\n",
+ "</div>"
+ ],
+ "text/plain": [
+ " BurnedOut Run density height width\n",
+ "0 0.009288 11 0.12 50 50\n",
+ "1 1.000000 98 0.99 50 50\n",
+ "2 0.092608 48 0.49 50 50\n",
+ "3 0.024691 3 0.04 50 50\n",
+ "4 0.060748 42 0.43 50 50"
+ ]
+ },
+ "execution_count": 14,
"metadata": {},
- "outputs": [
- {
- "html": [
- "<div style=\"max-height:1000px;max-width:1500px;overflow:auto;\">\n",
- "<table border=\"1\" class=\"dataframe\">\n",
- " <thead>\n",
- " <tr style=\"text-align: right;\">\n",
- " <th></th>\n",
- " <th>BurnedOut</th>\n",
- " <th>Run</th>\n",
- " <th>density</th>\n",
- " <th>height</th>\n",
- " <th>width</th>\n",
- " </tr>\n",
- " </thead>\n",
- " <tbody>\n",
- " <tr>\n",
- " <th>0</th>\n",
- " <td> 0.142256</td>\n",
- " <td> 45</td>\n",
- " <td> 0.46</td>\n",
- " <td> 50</td>\n",
- " <td> 50</td>\n",
- " </tr>\n",
- " <tr>\n",
- " <th>1</th>\n",
- " <td> 0.946026</td>\n",
- " <td> 68</td>\n",
- " <td> 0.69</td>\n",
- " <td> 50</td>\n",
- " <td> 50</td>\n",
- " </tr>\n",
- " <tr>\n",
- " <th>2</th>\n",
- " <td> 0.978022</td>\n",
- " <td> 71</td>\n",
- " <td> 0.72</td>\n",
- " <td> 50</td>\n",
- " <td> 50</td>\n",
- " </tr>\n",
- " <tr>\n",
- " <th>3</th>\n",
- " <td> 0.027190</td>\n",
- " <td> 12</td>\n",
- " <td> 0.13</td>\n",
- " <td> 50</td>\n",
- " <td> 50</td>\n",
- " </tr>\n",
- " <tr>\n",
- " <th>4</th>\n",
- " <td> 0.082645</td>\n",
- " <td> 43</td>\n",
- " <td> 0.44</td>\n",
- " <td> 50</td>\n",
- " <td> 50</td>\n",
- " </tr>\n",
- " </tbody>\n",
- "</table>\n",
- "</div>"
- ],
- "metadata": {},
- "output_type": "pyout",
- "prompt_number": 14,
- "text": [
- " BurnedOut Run density height width\n",
- "0 0.142256 45 0.46 50 50\n",
- "1 0.946026 68 0.69 50 50\n",
- "2 0.978022 71 0.72 50 50\n",
- "3 0.027190 12 0.13 50 50\n",
- "4 0.082645 43 0.44 50 50"
- ]
- }
- ],
- "prompt_number": 14
- },
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "df.head()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "As you can see, each row here is a run of the model, identified by its parameter values (and given a unique index by the Run column). To view how the BurnedOut fraction varies with density, we can easily just plot them:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 15,
+ "metadata": {
+ "collapsed": false
+ },
+ "outputs": [
{
- "cell_type": "markdown",
+ "data": {
+ "text/plain": [
+ "(0, 1)"
+ ]
+ },
+ "execution_count": 15,
"metadata": {},
- "source": [
- "As you can see, each row here is a run of the model, identified by its parameter values (and given a unique index by the Run column). To view how the BurnedOut fraction varies with density, we can easily just plot them:"
- ]
+ "output_type": "execute_result"
},
{
- "cell_type": "code",
- "collapsed": false,
- "input": [
- "plt.scatter(df.density, df.BurnedOut)\n",
- "plt.xlim(0,1)"
- ],
- "language": "python",
+ "data": {
+ "image/png": "iVBORw0KGgoAAAANSUhEUgAAAX4AAAEACAYAAAC08h1NAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAALEgAACxIB0t1+/AAAGXpJREFUeJzt3X+sJeV93/H3l+WHWLdbvLsSbgAL4lLHRdjyWoG1vTXX\nsmE3VCoFV0HEpAQ7iMYlG7prBUwts1ITR0iwQhvHgLcYiBKZVolp1hVlIY2vHCFMDYQfwbuEjU3F\njwSZxTapWbb749s/Zi537rnnnDv3zL3n3Hvm/ZJGe+fMMzPPmbv3M895njkzkZlIktrjm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GcB6yNiBeBGym6/AbOTb/AJUkt\n46MXJallDH5JahmDX5JaxuCXpJYx+CWpZQx+SWoZg1+SWsbgl6SW+f9ehOb1bB9nvQAAAABJRU5E\nrkJggg==\n",
+ "text/plain": [
+ "<matplotlib.figure.Figure at 0x10a095748>"
+ ]
+ },
"metadata": {},
- "outputs": [
- {
- "metadata": {},
- "output_type": "pyout",
- "prompt_number": 15,
- "text": [
- "(0, 1)"
- ]
- },
- {
- "metadata": {},
- "output_type": "display_data",
- "png": "iVBORw0KGgoAAAANSUhEUgAAAX4AAAEACAYAAAC08h1NAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAALEgAACxIB0t1+/AAAGS9JREFUeJzt3X+M3PV95/Hn24Y9bXTHgePKuQAJKUdyORqQQQGnzp03\nl+yuw0lQ7FM5GnJukhbudKRttE0MtS5slKQVulpBNBIBQsASStAphNY5cbv2tRkaI8IFCoYzNsVJ\nkfjRoDikUa9nyfb5fX/MrHd2PDs7M9/dmd35Ph/Sivnu9zPf72e/eF/z2ffnM9+JzESSVB6r+t0B\nSVJvGfySVDIGvySVjMEvSSVj8EtSyRj8klQyhYM/Ir4REW9ExPPz7P9YROyPiOci4vGIuKToOSVJ\n3VuMEf/9wOYW+38M/OvMvAT4InDPIpxTktSlwsGfmd8Hft5i/xOZ+Yva5pPAeUXPKUnqXq9r/J8C\nHu3xOSVJdc7o1Yki4kPAJ4GNvTqnJOl0PQn+2oTuvcDmzDytLBQR3jBIkrqQmdHpc5a81BMR7wC+\nA9yQmYfna5eZfmVy22239b0Py+XLa+G18Fq0/upW4RF/RHwL2ASsjYhXgNuAM2thfjfweeAc4K6I\nADiemVcUPa8kqTuFgz8zr19g/28Bv1X0PJKkxeE7d5eZkZGRfndh2fBazPJazPJaFBdF6kSL1omI\nXA79kKSVJCLI5Ti5K0laXgx+SSoZg1+SSsbgl6SSMfglqWQMfkkqGYNfkkrG4JekkjH4JalkDH5J\nKhmDX5JKxuCXpJIx+CWpZAx+SSoZg1+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XauxR8Az2bmSERcCOyNiEsz8++XuG/LUUe52cvgfw04v277fKqvTK3a\nnFf73qBp51pQm9C9F9icma3+1FvJ2rkWlwMPVTOftcBHI+J4Zu7uTRd7pp1r8QpwJDOPAkcj4i+B\nS4FBC/52rsWvAl8GyMwfRcTfAO8BnupJD5ePjnOzl6Wep4CLIuKCiBgCrqP6JrB6u4H/ABARG4C/\ny9n7AQ2SBa9FRLwD+A5wQ2Ye7kMfe2XBa5GZv5yZ78rMd1Gt8/+nAQx9aO935M+AD0bE6oh4C9XJ\nvBd63M9eaOdaHAI+AlCrab8H+HFPe7k8dJybPRvxZ+aJiLgZmKY6Y39fZh6MiJtq++/OzEcj4qqI\nOAz8A/CJXvWvl9q5FsDngXOAu2oj3eOZeUW/+rxU2rwWpdDm78ihiJii+qbIk1TfLDlwwd/mv4s/\nBO6PiP1UB7Gfy8w3+9bpJRIR3wI2AWsj4hXgNqolv65z0zdwSVLJ+NGLklQyBr8klYzBL0klY/BL\nUskY/JJUMga/JJWMwS9JJWPwS1LJ/H90HnxhfKFFXgAAAABJRU5ErkJggg==\n",
- "text": [
- "<matplotlib.figure.Figure at 0x10a339828>"
- ]
- }
- ],
- "prompt_number": 15
- },
+ "output_type": "display_data"
+ }
+ ],
+ "source": [
+ "plt.scatter(df.density, df.BurnedOut)\n",
+ "plt.xlim(0,1)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "And we see the very clear emergence of a critical value around 0.5, where the model quickly shifts from almost no trees being burned, to almost all of them.\n",
+ "\n",
+ "In this case we ran the model only once at each value. However, it's easy to have the BatchRunner execute multiple runs at each parameter combination, in order to generate more statistically reliable results. We do this using the *iteration* argument.\n",
+ "\n",
+ "Let's run the model 5 times at each parameter point, and export and plot the results as above."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 16,
+ "metadata": {
+ "collapsed": false
+ },
+ "outputs": [
{
- "cell_type": "markdown",
+ "data": {
+ "text/plain": [
+ "(0, 1)"
+ ]
+ },
+ "execution_count": 16,
"metadata": {},
- "source": [
- "And we see the very clear emergence of a critical value around 0.5, where the model quickly shifts from almost no trees being burned, to almost all of them.\n",
- "\n",
- "In this case we ran the model only once at each value. However, it's easy to have the BatchRunner execute multiple runs at each parameter combination, in order to generate more statistically reliable results. We do this using the *iteration* argument.\n",
- "\n",
- "Let's run the model 5 times at each parameter point, and export and plot the results as above."
- ]
+ "output_type": "execute_result"
},
{
- "cell_type": "code",
- "collapsed": false,
- "input": [
- "param_run = BatchRunner(ForestFire, param_set, iterations=5, model_reporters=model_reporter)\n",
- "param_run.run_all()\n",
- "df = param_run.get_model_vars_dataframe()\n",
- "plt.scatter(df.density, df.BurnedOut)\n",
- "plt.xlim(0,1)"
- ],
- "language": "python",
+ "data": {
+ "image/png": "iVBORw0KGgoAAAANSUhEUgAAAX4AAAEACAYAAAC08h1NAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAALEgAACxIB0t1+/AAAIABJREFUeJzt3X+QHOV95/H3V9J6rQWvpF0lOCAwBLBxbGF+XEBnOFif\nLaSQijnDVSgCOYwdgo3JGrQ67MiU0ZUxse+QTHQuDFawUF185nIhPkRCQOTMVlIum7PELwULkGzI\ngYi5SALWoB/sar/3x/O0pmemZ3Z2e3dmdvvzqupS9/TT3c+2dr/9zLefftrcHRERKY5Zra6AiIg0\nlwK/iEjBKPCLiBSMAr+ISMEo8IuIFIwCv4hIweQO/Gb2HTN71cy21Vh/uZk9ZWZPm9kPzezUvMcU\nEZGJm4wW/wZgeZ31PwfOc/dTga8A356EY4qIyATlDvzu/g/Aa3XW/8jd34iLjwGL8h5TREQmrtk5\n/k8DDzb5mCIikjKnWQcys48AnwLOadYxRUSkWlMCf7yhux5Y7u5VaSEz04BBIiIT4O423m2mPPCb\n2XHAXwFXuPvOWuUmUvmZyMxWu/vqVtejHehclOhclOhclEy00Zw78JvZ94DzgYVm9hJwM9AB4O53\nAV8GFgDfMjOAYXc/K+9xRURkYnIHfne/bIz1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DOCjQBfwIzP7sbvvmNKaNV8j52IV8KS795nZicAjZvYhd//lFNetHY0r\nbjYz8O8Cjk0tH0u4MtUrsyh+NtM0ci6IN3TXA8vdvd5XvemskXNxJnBviPksBH7LzIbdfVNzqtg0\njZyLl4Dd7r4f2G9mfw98CJhpgb+Rc/Fh4KsA7v4zM3sBeB+wpSk1bB/jjpvNTPVsAU42s+PN7B3A\npYSHwNI2Af8BwMyWAK97aTygmWTMc2FmxwF/BVzh7jtbUMdmGfNcuPuvu/sJ7n4CIc//2RkY9KGx\nv5H7gXPNbLaZdRFu5v20yfVshkbOxbPAxwBiTvt9wM+bWsv2MO642bQWv7uPmNl1wMOEO/Z3u/t2\nM7smrr/L3R80swvNbCfwFnBVs+rXTI2cC+DLwALgW7GlO+zuZ7WqzlOlwXNRCA3+jTxrZg8RHooc\nJTwsOeMCf4O/F7cCG8zsKUIj9kZ339uySk8RM/secD6w0MxeAm4mpPwmHDf1AJeISMHo1YsiIgWj\nwC8iUjAK/CIiBaPALyJSMAr8IiIFo8AvIlIwCvwiIgWjwC8iUjD/H15+d1SmsbWuAAAAAElFTkSu\nQmCC\n",
+ "text/plain": [
+ "<matplotlib.figure.Figure at 0x10a417710>"
+ ]
+ },
"metadata": {},
- "outputs": [
- {
- "metadata": {},
- "output_type": "pyout",
- "prompt_number": 16,
- "text": [
- "(0, 1)"
- ]
- },
- {
- "metadata": {},
- "output_type": "display_data",
- "png": "iVBORw0KGgoAAAANSUhEUgAAAX4AAAEACAYAAAC08h1NAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAALEgAACxIB0t1+/AAAIABJREFUeJzt3X90HOV97/H3V1rW2LGNvRI/DMYmKAQIMSCTELfkxsoF\nIYcGp9g9SSikuqQxpC1xUsmBEJvEt5bCyQ84XJrc8KMpdpO03HtK6BX3gIWTRk7hQFL/iHEJTrFN\ncqEmnNjKD2icCOHv/WNmpNnZH1pppV1J+3mds4eZnWdnnh2s7zz7fZ55xtwdERGpHXXVroCIiFS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ilHguakKJfyP7zGwrwU2Rxwhulpx2gb/EfxefA+43sz0Ejdib3L2/apWeIGb2D8ByoNHMXgA+\nS5DyG3Pc1A1cIiI1Ro9eFBGpMQr8IiI1RoFfRKTGKPCLiNQYBX4RkRqjwC8iUmMU+EVEaowCv4hI\njfn/vIVXkfM6S7gAAAAASUVORK5CYII=\n",
- "text": [
- "<matplotlib.figure.Figure at 0x109eb1be0>"
- ]
- }
- ],
- "prompt_number": 16
+ "output_type": "display_data"
}
],
- "metadata": {}
+ "source": [
+ "param_run = BatchRunner(ForestFire, param_set, iterations=5, model_reporters=model_reporter)\n",
+ "param_run.run_all()\n",
+ "df = param_run.get_model_vars_dataframe()\n",
+ "plt.scatter(df.density, df.BurnedOut)\n",
+ "plt.xlim(0,1)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": true
+ },
+ "outputs": [],
+ "source": []
}
- ]
-}
\ No newline at end of file
+ ],
+ "metadata": {
+ "kernelspec": {
+ "display_name": "Python 3",
+ "language": "python",
+ "name": "python3"
+ },
+ "language_info": {
+ "codemirror_mode": {
+ "name": "ipython",
+ "version": 3
+ },
+ "file_extension": ".py",
+ "mimetype": "text/x-python",
+ "name": "python",
+ "nbconvert_exporter": "python",
+ "pygments_lexer": "ipython3",
+ "version": "3.4.2"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 0
+}
diff --git a/mesa/datacollection.py b/mesa/datacollection.py
index 4836d16c..0a4a9290 100644
--- a/mesa/datacollection.py
+++ b/mesa/datacollection.py
@@ -3,20 +3,27 @@ Mesa Data Collection Module
=====================================================
DataCollector is meant to provide a simple, standard way to collect data
-generated by a Mesa model. It collects two types of data: model-level and
-agent-level data.
+generated by a Mesa model. It collects three types of data: model-level data,
+agent-level data, and tables.
A DataCollector is instantiated with two dictionaries of reporter names and
associated functions for each, one for model-level data and one for
-agent-level data. When the collect() method is called, each model-level
-function is called, with the model as the argument, and the results associated
-with the relevant variable. Then the agent-level functions are called on each
+agent-level data; a third dictionary provides table names and columns.
+
+When the collect() method is called, each model-level function is called, with
+the model as the argument, and the results associated with the relevant
+variable. Then the agent-level functions are called on each
agent in the model scheduler.
-The DataCollector then stores the data it collects in two dictionaries:
+Additionally, other objects can write directly to tables by passing in an
+appropriate dictionary object for a table row.
+
+The DataCollector then stores the data it collects in dictionaries:
* model_vars maps each reporter to a list of its values
* agent_vars maps each reporter to a list of lists, where each nested list
stores (agent_id, value) pairs.
+ * tables maps each table to a dictionary, with each column as a key with a
+ list as its value.
Finally, DataCollector can create a pandas DataFrame from each collection.
@@ -43,10 +50,11 @@ class DataCollector(object):
model_vars = {}
agent_vars = {}
+ tables = {}
model = None
- def __init__(self, model_reporters=None, agent_reporters=None):
+ def __init__(self, model_reporters={}, agent_reporters={}, tables={}):
'''
Instantiate a DataCollector with lists of model and agent reporters.
@@ -59,21 +67,62 @@ class DataCollector(object):
it might look like this:
{"energy": lambda a: a.energy}
+ The tables arg accepts a dictionary mapping names of tables to lists of
+ columns. For example, if we want to allow agents to write their age
+ when they are destroyed (to keep track of lifespans), it might look
+ like:
+ {"Lifespan": ["unique_id", "age"]}
+
Args:
model_reporters: Dictionary of reporter names and functions.
agent_reporters: Dictionary of reporter names and functions.
'''
- self.model_reporters = model_reporters
- self.agent_reporters = agent_reporters
+ self.model_reporters = {}
+ self.agent_reporters = {}
+ self.tables = {}
- if self.model_reporters:
- for var in self.model_reporters:
- self.model_vars[var] = []
+ for name, func in model_reporters.items():
+ self._new_model_reporter(name, func)
- if self.agent_reporters:
- for var in self.agent_reporters:
- self.agent_vars[var] = []
+ for name, func in agent_reporters.items():
+ self._new_agent_reporter(name, func)
+
+ for name, columns in tables.items():
+ self._new_table(name, columns)
+
+ def _new_model_reporter(self, reporter_name, reporter_function):
+ '''
+ Add a new model-level reporter to collect.
+ Args:
+ reporter_name: Name of the model-level variable to collect.
+ reporter_function: Function object that returns the variable when
+ given a model instance.
+ '''
+
+ self.model_reporters[reporter_name] = reporter_function
+ self.model_vars[reporter_name] = []
+
+ def _new_agent_reporter(self, reporter_name, reporter_function):
+ '''
+ Add a new agent-level reporter to collect.
+ Args:
+ reporter_name: Name of the agent-level variable to collect.
+ reporter_function: Function object that returns the variable when
+ given an agent object.
+ '''
+ self.agent_reporters[reporter_name] = reporter_function
+ self.agent_vars[reporter_name] = []
+
+ def _new_table(self, table_name, table_columns):
+ '''
+ Add a new table that objects can write to.
+ Args:
+ table_name: Name of the new table.
+ table_columns: List of columns to add to the table.
+ '''
+ new_table = {column: [] for column in table_columns}
+ self.tables[table_name] = new_table
def collect(self, model):
'''
@@ -90,6 +139,27 @@ class DataCollector(object):
agent_records.append((agent.unique_id, reporter(agent)))
self.agent_vars[var].append(agent_records)
+ def add_table_row(self, table_name, row, ignore_missing=False):
+ '''
+ Add a row dictionary to a specific table.
+
+ Args:
+ table_name: Name of the table to append a row to.
+ row: A dictionary of the form {column_name: value...}
+ ignore_missing: If True, fill any missing columns with Nones;
+ if False, throw an error if any columns are missing
+ '''
+ if table_name not in self.tables:
+ raise Exception("Table does not exist.")
+
+ for column in self.tables[table_name]:
+ if column in row:
+ self.tables[table_name][column].append(row[column])
+ elif ignore_missing:
+ self.tables[table_name][column].append(None)
+ else:
+ raise Exception("Could not insert row with missing column")
+
def get_model_vars_dataframe(self):
'''
Create a pandas DataFrame from the model variables.
@@ -115,3 +185,14 @@ class DataCollector(object):
df = pd.DataFrame.from_dict(data, orient="index")
df.index.names = ["Step", "AgentID"]
return df
+
+ def get_table_dataframe(self, table_name):
+ '''
+ Create a pandas DataFrame from a particular table.
+
+ Args:
+ table_name: The name of the table to convert.
+ '''
+ if table_name not in self.tables:
+ raise Exception("No such table.")
+ return pd.DataFrame(self.tables[table_name])
| Add data collection features
Discovered a need for these two features while using Mesa "in production":
- Break apart the constructor to allow variables to be added later
- Create tables that the model and/or agents can write to directly as needed, rather than data collected automatically every step.
| projectmesa/mesa | diff --git a/tests/test_datacollector.py b/tests/test_datacollector.py
new file mode 100644
index 00000000..e1115978
--- /dev/null
+++ b/tests/test_datacollector.py
@@ -0,0 +1,119 @@
+'''
+Test the DataCollector
+'''
+import unittest
+
+from mesa import Model, Agent
+from mesa.time import BaseScheduler
+from mesa.datacollection import DataCollector
+
+
+class MockAgent(Agent):
+ '''
+ Minimalistic agent for testing purposes.
+ '''
+ def __init__(self, unique_id, val):
+ self.unique_id = unique_id
+ self.val = val
+
+ def step(self, model):
+ '''
+ Increment val by 1.
+ '''
+ self.val += 1
+
+ def write_final_values(self, model):
+ '''
+ Write the final value to the appropriate table.
+ '''
+ row = {"agent_id": self.unique_id, "final_value": self.val}
+ model.datacollector.add_table_row("Final_Values", row)
+
+
+class MockModel(Model):
+ '''
+ Minimalistic model for testing purposes.
+ '''
+
+ schedule = BaseScheduler(None)
+
+ def __init__(self):
+ self.schedule = BaseScheduler(self)
+ for i in range(10):
+ a = MockAgent(i, i)
+ self.schedule.add(a)
+ self.datacollector = DataCollector(
+ {"total_agents": lambda m: m.schedule.get_agent_count()},
+ {"value": lambda a: a.val},
+ {"Final_Values": ["agent_id", "final_value"]})
+
+ def step(self):
+ self.schedule.step()
+ self.datacollector.collect(self)
+
+
+class TestDataCollector(unittest.TestCase):
+ def setUp(self):
+ '''
+ Create the model and run it a set number of steps.
+ '''
+ self.model = MockModel()
+ for i in range(7):
+ self.model.step()
+ # Write to table:
+ for agent in self.model.schedule.agents:
+ agent.write_final_values(self.model)
+
+ def test_model_vars(self):
+ '''
+ Test model-level variable collection.
+ '''
+ data_collector = self.model.datacollector
+ assert "total_agents" in data_collector.model_vars
+ assert len(data_collector.model_vars["total_agents"]) == 7
+ for element in data_collector.model_vars["total_agents"]:
+ assert element == 10
+
+ def test_agent_vars(self):
+ '''
+ Test agent-level variable collection.
+ '''
+ data_collector = self.model.datacollector
+ assert len(data_collector.agent_vars["value"]) == 7
+ for step in data_collector.agent_vars["value"]:
+ assert len(step) == 10
+ for record in step:
+ assert len(record) == 2
+
+ def test_table_rows(self):
+ '''
+ Test table collection
+ '''
+ data_collector = self.model.datacollector
+ assert len(data_collector.tables["Final_Values"]) == 2
+ assert "agent_id" in data_collector.tables["Final_Values"]
+ assert "final_value" in data_collector.tables["Final_Values"]
+ for key, data in data_collector.tables["Final_Values"].items():
+ assert len(data) == 10
+
+ with self.assertRaises(Exception):
+ data_collector.add_table_row("error_table", {})
+
+ with self.assertRaises(Exception):
+ data_collector.add_table_row("Final_Values", {"final_value": 10})
+
+ def test_exports(self):
+ '''
+ Test DataFrame exports
+ '''
+ data_collector = self.model.datacollector
+ model_vars = data_collector.get_model_vars_dataframe()
+ agent_vars = data_collector.get_agent_vars_dataframe()
+ table_df = data_collector.get_table_dataframe("Final_Values")
+
+ assert model_vars.shape == (7, 1)
+ assert agent_vars.shape == (70, 1)
+ assert table_df.shape == (10, 2)
+
+ with self.assertRaises(Exception):
+ table_df = data_collector.get_table_dataframe("not a real table")
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": -1,
"issue_text_score": 2,
"test_score": -1
},
"num_modified_files": 3
} | unknown | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[dev]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest",
"pytest-cov",
"flake8"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.9",
"reqs_path": [
"requirements/base.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | coverage==7.8.0
exceptiongroup==1.2.2
flake8==7.2.0
iniconfig==2.1.0
mccabe==0.7.0
-e git+https://github.com/projectmesa/mesa.git@ca1e91c6ea8b5bc476ae0fdbf708c1f28ae55dc4#egg=Mesa
numpy==2.0.2
packaging==24.2
pandas==2.2.3
pluggy==1.5.0
pycodestyle==2.13.0
pyflakes==3.3.1
pytest==8.3.5
pytest-cov==6.0.0
python-dateutil==2.9.0.post0
pytz==2025.2
six==1.17.0
tomli==2.2.1
tornado==6.4.2
tzdata==2025.2
| name: mesa
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=3.0.16=h5eee18b_0
- pip=25.0=py39h06a4308_0
- python=3.9.21=he870216_1
- readline=8.2=h5eee18b_0
- setuptools=75.8.0=py39h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- wheel=0.45.1=py39h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- coverage==7.8.0
- exceptiongroup==1.2.2
- flake8==7.2.0
- iniconfig==2.1.0
- mccabe==0.7.0
- numpy==2.0.2
- packaging==24.2
- pandas==2.2.3
- pluggy==1.5.0
- pycodestyle==2.13.0
- pyflakes==3.3.1
- pytest==8.3.5
- pytest-cov==6.0.0
- python-dateutil==2.9.0.post0
- pytz==2025.2
- six==1.17.0
- tomli==2.2.1
- tornado==6.4.2
- tzdata==2025.2
prefix: /opt/conda/envs/mesa
| [
"tests/test_datacollector.py::TestDataCollector::test_agent_vars",
"tests/test_datacollector.py::TestDataCollector::test_exports",
"tests/test_datacollector.py::TestDataCollector::test_model_vars",
"tests/test_datacollector.py::TestDataCollector::test_table_rows"
] | [] | [] | [] | Apache License 2.0 | 114 |
|
sjagoe__usagi-49 | 66dccaaca17941c7cd587d7c8828f68cc87f41f0 | 2015-04-28 17:51:59 | 66dccaaca17941c7cd587d7c8828f68cc87f41f0 | diff --git a/CHANGELOG.rst b/CHANGELOG.rst
index ef6028e..27fa8ce 100644
--- a/CHANGELOG.rst
+++ b/CHANGELOG.rst
@@ -10,6 +10,8 @@ Enhancements
* Added an option to the body assertion to filter json responses with a
``jq`` (https://pypi.python.org/pypi/jq) filter (#44).
+* Added an option to cases and tests to allow setting the
+ unittest.TestCase.maxDiff parameter (#47).
Version 0.2.0
diff --git a/usagi/schema.py b/usagi/schema.py
index 20915a9..5b0f11a 100644
--- a/usagi/schema.py
+++ b/usagi/schema.py
@@ -118,12 +118,18 @@ SCHEMA = {
},
'minItems': 1,
},
+ 'max-diff': {
+ '$ref': '#/definitions/max-diff',
+ },
},
'required': ['name', 'tests'],
},
'test': {
'type': 'object',
'properties': {
+ 'max-diff': {
+ '$ref': '#/definitions/max-diff',
+ },
'parameters': {'type': 'object'},
'url': {
'oneOf': [
@@ -155,5 +161,9 @@ SCHEMA = {
},
'required': ['url', 'name'],
},
+ 'max-diff': {
+ 'type': ['number', 'null'],
+ 'description': 'Set the case maxDiff option to control error output', # noqa
+ },
},
}
| Allow setting maxDiff at the testCase level and test level
Currently if a body assertion fails there is no way to see the whole diff to resolve the issue.
We need a mechanism to set the underlying TestCase `maxDiff` attribute on a test-case level and an individual test level. | sjagoe/usagi | diff --git a/usagi/tests/test_schema.py b/usagi/tests/test_schema.py
index 21fac64..f270e32 100644
--- a/usagi/tests/test_schema.py
+++ b/usagi/tests/test_schema.py
@@ -337,3 +337,137 @@ class TestSchema(unittest.TestCase):
# Validation fails
with self.assertRaises(ValidationError):
jsonschema.validate(test_data, SCHEMA)
+
+ def test_schema_case_max_diff_null(self):
+ # Given
+ test_yaml = textwrap.dedent("""
+ version: '1.0'
+
+ config:
+ host: test.domain
+
+ cases:
+ - name: "Basic"
+ max-diff: null
+ tests:
+ - name: "Another URL"
+ url: "/another"
+
+ """)
+
+ test_data = yaml.safe_load(test_yaml)
+
+ # Validation succeeds
+ jsonschema.validate(test_data, SCHEMA)
+
+ def test_schema_case_max_diff_number(self):
+ # Given
+ test_yaml = textwrap.dedent("""
+ version: '1.0'
+
+ config:
+ host: test.domain
+
+ cases:
+ - name: "Basic"
+ max-diff: 12345
+ tests:
+ - name: "Another URL"
+ url: "/another"
+
+ """)
+
+ test_data = yaml.safe_load(test_yaml)
+
+ # Validation succeeds
+ jsonschema.validate(test_data, SCHEMA)
+
+ def test_schema_case_max_diff_string(self):
+ # Given
+ test_yaml = textwrap.dedent("""
+ version: '1.0'
+
+ config:
+ host: test.domain
+
+ cases:
+ - name: "Basic"
+ max-diff: '12345'
+ tests:
+ - name: "Another URL"
+ url: "/another"
+
+ """)
+
+ test_data = yaml.safe_load(test_yaml)
+
+ # Validation fails
+ with self.assertRaises(ValidationError):
+ jsonschema.validate(test_data, SCHEMA)
+
+ def test_schema_test_max_diff_null(self):
+ # Given
+ test_yaml = textwrap.dedent("""
+ version: '1.0'
+
+ config:
+ host: test.domain
+
+ cases:
+ - name: "Basic"
+ tests:
+ - name: "Another URL"
+ url: "/another"
+ max-diff: null
+
+ """)
+
+ test_data = yaml.safe_load(test_yaml)
+
+ # Validation succeeds
+ jsonschema.validate(test_data, SCHEMA)
+
+ def test_schema_test_max_diff_number(self):
+ # Given
+ test_yaml = textwrap.dedent("""
+ version: '1.0'
+
+ config:
+ host: test.domain
+
+ cases:
+ - name: "Basic"
+ tests:
+ - name: "Another URL"
+ url: "/another"
+ max-diff: 12345
+
+ """)
+
+ test_data = yaml.safe_load(test_yaml)
+
+ # Validation succeeds
+ jsonschema.validate(test_data, SCHEMA)
+
+ def test_schema_test_max_diff_string(self):
+ # Given
+ test_yaml = textwrap.dedent("""
+ version: '1.0'
+
+ config:
+ host: test.domain
+
+ cases:
+ - name: "Basic"
+ tests:
+ - name: "Another URL"
+ url: "/another"
+ max-diff: '12345'
+
+ """)
+
+ test_data = yaml.safe_load(test_yaml)
+
+ # Validation fails
+ with self.assertRaises(ValidationError):
+ jsonschema.validate(test_data, SCHEMA)
diff --git a/usagi/tests/test_web_test.py b/usagi/tests/test_web_test.py
index 266f86c..4a72983 100644
--- a/usagi/tests/test_web_test.py
+++ b/usagi/tests/test_web_test.py
@@ -25,7 +25,7 @@ from ..plugins.test_parameters import (
)
from ..config import Config
from ..utils import create_session
-from ..web_test import WebPoll, WebTest
+from ..web_test import WebPoll, WebTest, _Default
class TestWebTest(unittest.TestCase):
@@ -72,6 +72,77 @@ class TestWebTest(unittest.TestCase):
# Then
self.assertIs(test.session, session)
self.assertIs(test.config, config)
+ self.assertIs(test.max_diff, _Default)
+ self.assertEqual(test.name, name)
+ self.assertEqual(test.url, expected_url)
+ self.assertEqual(self._get_web_test_method(test), 'GET')
+ self.assertEqual(len(test.assertions), 0)
+
+ def test_from_dict_null_max_diff(self):
+ # Given
+ config = Config.from_dict({'host': 'test.invalid'}, __file__)
+ session = create_session()
+ name = 'A test'
+ url = '/api/test'
+ test_spec = {
+ 'name': name,
+ 'url': url,
+ 'max-diff': None,
+ }
+ expected_url = urllib.parse.urlunparse(
+ urllib.parse.ParseResult(
+ config.scheme,
+ config.host,
+ url,
+ None,
+ None,
+ None,
+ ),
+ )
+
+ # When
+ test = WebTest.from_dict(
+ session, test_spec, config, {}, self.test_parameter_plugins)
+
+ # Then
+ self.assertIs(test.session, session)
+ self.assertIs(test.config, config)
+ self.assertIsNone(test.max_diff)
+ self.assertEqual(test.name, name)
+ self.assertEqual(test.url, expected_url)
+ self.assertEqual(self._get_web_test_method(test), 'GET')
+ self.assertEqual(len(test.assertions), 0)
+
+ def test_from_dict_integer_max_diff(self):
+ # Given
+ config = Config.from_dict({'host': 'test.invalid'}, __file__)
+ session = create_session()
+ name = 'A test'
+ url = '/api/test'
+ test_spec = {
+ 'name': name,
+ 'url': url,
+ 'max-diff': 5001,
+ }
+ expected_url = urllib.parse.urlunparse(
+ urllib.parse.ParseResult(
+ config.scheme,
+ config.host,
+ url,
+ None,
+ None,
+ None,
+ ),
+ )
+
+ # When
+ test = WebTest.from_dict(
+ session, test_spec, config, {}, self.test_parameter_plugins)
+
+ # Then
+ self.assertIs(test.session, session)
+ self.assertIs(test.config, config)
+ self.assertEqual(test.max_diff, 5001)
self.assertEqual(test.name, name)
self.assertEqual(test.url, expected_url)
self.assertEqual(self._get_web_test_method(test), 'GET')
@@ -106,6 +177,7 @@ class TestWebTest(unittest.TestCase):
# Then
self.assertIs(test.session, session)
self.assertIs(test.config, config)
+ self.assertIs(test.max_diff, _Default)
self.assertEqual(test.name, name)
self.assertEqual(test.url, expected_url)
self.assertEqual(self._get_web_test_method(test), 'POST')
@@ -208,6 +280,73 @@ class TestWebTest(unittest.TestCase):
self.assertEqual(args, (204, 200))
self.assertIn('msg', kwargs)
+ # No maxDiff has been set
+ self.assertIsInstance(case.maxDiff, Mock)
+
+ @responses.activate
+ def test_run_null_max_diff(self):
+ # Given
+ config = Config.from_dict({'host': 'test.invalid'}, __file__)
+ session = create_session()
+ name = 'A test'
+ url = '/api/test'
+ test_spec = {
+ 'name': name,
+ 'url': url,
+ 'max-diff': None,
+ }
+ assertions = {}
+
+ test = WebTest.from_dict(
+ session, test_spec, config, assertions,
+ self.test_parameter_plugins)
+
+ responses.add(
+ self._get_web_test_method(test),
+ test.url,
+ status=204,
+ )
+
+ # When
+ case = Mock()
+ test.run(case)
+
+ # Then
+ # maxDiff set to None
+ self.assertIs(case.maxDiff, None)
+
+ @responses.activate
+ def test_run_int_max_diff(self):
+ # Given
+ config = Config.from_dict({'host': 'test.invalid'}, __file__)
+ session = create_session()
+ name = 'A test'
+ url = '/api/test'
+ test_spec = {
+ 'name': name,
+ 'url': url,
+ 'max-diff': 2121,
+ }
+ assertions = {}
+
+ test = WebTest.from_dict(
+ session, test_spec, config, assertions,
+ self.test_parameter_plugins)
+
+ responses.add(
+ self._get_web_test_method(test),
+ test.url,
+ status=204,
+ )
+
+ # When
+ case = Mock()
+ test.run(case)
+
+ # Then
+ # maxDiff set to value
+ self.assertEqual(case.maxDiff, 2121)
+
def test_connection_error(self):
# Given
config = Config.from_dict({'host': 'test.invalid'}, __file__)
diff --git a/usagi/tests/test_yaml_test_loader.py b/usagi/tests/test_yaml_test_loader.py
index 1527b0e..0dcd22d 100644
--- a/usagi/tests/test_yaml_test_loader.py
+++ b/usagi/tests/test_yaml_test_loader.py
@@ -316,3 +316,69 @@ class TestYamlTestLoader(unittest.TestCase):
self.assertEqual(test.request.url, 'http://test.domain/another')
self.assertEqual(post_1.request.url, 'http://test.domain/one')
self.assertEqual(post_2.request.url, 'http://test.domain/two')
+
+ def test_load_yaml_tests_case_max_diff_null(self):
+ # Given
+ test_yaml = textwrap.dedent("""
+ ---
+ version: '1.0'
+
+ config:
+ host: test.domain
+
+ cases:
+ - name: "Basic"
+ max-diff: null
+ tests:
+ - name: "Test root URL"
+ url: "/"
+ - name: "Test sub URL"
+ url: "/sub/"
+
+ """)
+
+ test_data = yaml.safe_load(test_yaml)
+
+ # When
+ suite = self.loader.load_tests_from_yaml(
+ test_data, '/path/to/foo.yaml')
+
+ # Then
+ self.assertIsInstance(suite, TestSuite)
+ self.assertEqual(suite.countTestCases(), 2)
+ cls1, cls2 = [type(case) for case in find_test_cases(suite)]
+ self.assertIs(cls1, cls2)
+ self.assertIsNone(cls1.maxDiff)
+
+ def test_load_yaml_tests_case_max_diff_number(self):
+ # Given
+ test_yaml = textwrap.dedent("""
+ ---
+ version: '1.0'
+
+ config:
+ host: test.domain
+
+ cases:
+ - name: "Basic"
+ max-diff: 1234
+ tests:
+ - name: "Test root URL"
+ url: "/"
+ - name: "Test sub URL"
+ url: "/sub/"
+
+ """)
+
+ test_data = yaml.safe_load(test_yaml)
+
+ # When
+ suite = self.loader.load_tests_from_yaml(
+ test_data, '/path/to/foo.yaml')
+
+ # Then
+ self.assertIsInstance(suite, TestSuite)
+ self.assertEqual(suite.countTestCases(), 2)
+ cls1, cls2 = [type(case) for case in find_test_cases(suite)]
+ self.assertIs(cls1, cls2)
+ self.assertEqual(cls1.maxDiff, 1234)
diff --git a/usagi/web_test.py b/usagi/web_test.py
index db205c6..b410e84 100644
--- a/usagi/web_test.py
+++ b/usagi/web_test.py
@@ -33,6 +33,9 @@ def initialize_test_parameter_loaders(test_parameter_plugins, parameter_specs):
yield cls.from_dict({name: value})
+_Default = object()
+
+
class WebTest(object):
"""The main entry-point into a single web test case.
@@ -42,7 +45,7 @@ class WebTest(object):
"""
def __init__(self, session, config, name, path, assertions,
- parameter_loaders):
+ parameter_loaders, max_diff):
super(WebTest, self).__init__()
self.session = session
self.name = name
@@ -50,6 +53,7 @@ class WebTest(object):
self.path = path
self.assertions = assertions
self.parameter_loaders = parameter_loaders
+ self.max_diff = max_diff
@property
def url(self):
@@ -80,6 +84,8 @@ class WebTest(object):
spec = spec.copy()
name = spec.pop('name')
+ max_diff = spec.pop('max-diff', _Default)
+
assertion_specs = spec.pop('assertions', [])
assertions = initialize_assertions(
assertions_map, assertion_specs)
@@ -100,6 +106,7 @@ class WebTest(object):
path=spec['url'],
assertions=list(assertions),
parameter_loaders=list(parameter_loaders),
+ max_diff=max_diff,
)
def run(self, case):
@@ -111,6 +118,9 @@ class WebTest(object):
The ``TestCase`` instance used to record test results.
"""
+ if self.max_diff is not _Default:
+ case.maxDiff = self.max_diff
+
try:
url = self.url
except InvalidVariableType as exc:
diff --git a/usagi/yaml_test_loader.py b/usagi/yaml_test_loader.py
index 373a7ca..5a2457f 100644
--- a/usagi/yaml_test_loader.py
+++ b/usagi/yaml_test_loader.py
@@ -98,6 +98,9 @@ def create_test_case_for_case(filename, config, case, assertions_map,
)
class_dict[TEST_NAME_ATTRIBUTE] = case['name']
+ if 'max-diff' in case:
+ class_dict['maxDiff'] = case['max-diff']
+
def __str__(self):
method = getattr(self, self._testMethodName)
template = '{0!r} ({1})'
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_many_modified_files",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 2,
"issue_text_score": 1,
"test_score": 3
},
"num_modified_files": 2
} | 0.2 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[dev]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"coverage",
"mock",
"responses",
"pytest"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.4",
"reqs_path": [
"test_requirements.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | attrs==22.2.0
certifi==2021.5.30
charset-normalizer==2.0.12
coverage==6.2
docutils==0.18.1
enum34==1.1.10
haas==0.9.0
idna==3.10
importlib-metadata==4.8.3
iniconfig==1.1.1
jq==0.1.8
jsonschema==3.2.0
mock==5.2.0
packaging==21.3
pbr==6.1.1
pluggy==1.0.0
py==1.11.0
pyparsing==3.1.4
pyrsistent==0.18.0
pytest==7.0.1
PyYAML==6.0.1
requests==2.27.1
responses==0.17.0
six==1.17.0
statistics==1.0.3.5
stevedore==3.5.2
tomli==1.2.3
typing_extensions==4.1.1
urllib3==1.26.20
-e git+https://github.com/sjagoe/usagi.git@66dccaaca17941c7cd587d7c8828f68cc87f41f0#egg=usagi
zipp==3.6.0
| name: usagi
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- pip=21.2.2=py36h06a4308_0
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_0
- setuptools=58.0.4=py36h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- attrs==22.2.0
- charset-normalizer==2.0.12
- coverage==6.2
- docutils==0.18.1
- enum34==1.1.10
- haas==0.9.0
- idna==3.10
- importlib-metadata==4.8.3
- iniconfig==1.1.1
- jq==0.1.8
- jsonschema==3.2.0
- mock==5.2.0
- packaging==21.3
- pbr==6.1.1
- pluggy==1.0.0
- py==1.11.0
- pyparsing==3.1.4
- pyrsistent==0.18.0
- pytest==7.0.1
- pyyaml==6.0.1
- requests==2.27.1
- responses==0.17.0
- six==1.17.0
- statistics==1.0.3.5
- stevedore==3.5.2
- tomli==1.2.3
- typing-extensions==4.1.1
- urllib3==1.26.20
- zipp==3.6.0
prefix: /opt/conda/envs/usagi
| [
"usagi/tests/test_schema.py::TestSchema::test_schema_case_max_diff_string",
"usagi/tests/test_schema.py::TestSchema::test_schema_test_max_diff_string"
] | [
"usagi/tests/test_web_test.py::TestWebTest::test_poll_fail",
"usagi/tests/test_web_test.py::TestWebTest::test_poll_success",
"usagi/tests/test_web_test.py::TestWebTest::test_run"
] | [
"usagi/tests/test_schema.py::TestSchema::test_schema",
"usagi/tests/test_schema.py::TestSchema::test_schema_assertions",
"usagi/tests/test_schema.py::TestSchema::test_schema_bad_host",
"usagi/tests/test_schema.py::TestSchema::test_schema_bad_pre_definition",
"usagi/tests/test_schema.py::TestSchema::test_schema_case_max_diff_null",
"usagi/tests/test_schema.py::TestSchema::test_schema_case_max_diff_number",
"usagi/tests/test_schema.py::TestSchema::test_schema_empty_assertions",
"usagi/tests/test_schema.py::TestSchema::test_schema_invalid_assertions",
"usagi/tests/test_schema.py::TestSchema::test_schema_missing_config",
"usagi/tests/test_schema.py::TestSchema::test_schema_missing_host",
"usagi/tests/test_schema.py::TestSchema::test_schema_no_cases",
"usagi/tests/test_schema.py::TestSchema::test_schema_pre_definitions_case_setup",
"usagi/tests/test_schema.py::TestSchema::test_schema_test_max_diff_null",
"usagi/tests/test_schema.py::TestSchema::test_schema_test_max_diff_number",
"usagi/tests/test_schema.py::TestSchema::test_schema_top_level_single_test",
"usagi/tests/test_schema.py::TestSchema::test_schema_top_level_tests",
"usagi/tests/test_web_test.py::TestWebTest::test_connection_error",
"usagi/tests/test_web_test.py::TestWebTest::test_create_invlalid_assertions",
"usagi/tests/test_web_test.py::TestWebTest::test_create_with_assertions",
"usagi/tests/test_web_test.py::TestWebTest::test_create_with_body",
"usagi/tests/test_web_test.py::TestWebTest::test_create_with_headers",
"usagi/tests/test_web_test.py::TestWebTest::test_create_with_invalid_parameter",
"usagi/tests/test_web_test.py::TestWebTest::test_from_dict",
"usagi/tests/test_web_test.py::TestWebTest::test_from_dict_integer_max_diff",
"usagi/tests/test_web_test.py::TestWebTest::test_from_dict_null_max_diff",
"usagi/tests/test_web_test.py::TestWebTest::test_from_different_method",
"usagi/tests/test_web_test.py::TestWebTest::test_invalid_url",
"usagi/tests/test_web_test.py::TestWebTest::test_run_int_max_diff",
"usagi/tests/test_web_test.py::TestWebTest::test_run_null_max_diff",
"usagi/tests/test_web_test.py::TestWebTest::test_templating_url",
"usagi/tests/test_yaml_test_loader.py::TestYamlTestLoader::test_case_dunder_str",
"usagi/tests/test_yaml_test_loader.py::TestYamlTestLoader::test_case_setup",
"usagi/tests/test_yaml_test_loader.py::TestYamlTestLoader::test_execute_single_case",
"usagi/tests/test_yaml_test_loader.py::TestYamlTestLoader::test_execute_single_case_failure",
"usagi/tests/test_yaml_test_loader.py::TestYamlTestLoader::test_load_invalid_yaml_tests",
"usagi/tests/test_yaml_test_loader.py::TestYamlTestLoader::test_load_yaml_tests",
"usagi/tests/test_yaml_test_loader.py::TestYamlTestLoader::test_load_yaml_tests_case_max_diff_null",
"usagi/tests/test_yaml_test_loader.py::TestYamlTestLoader::test_load_yaml_tests_case_max_diff_number",
"usagi/tests/test_yaml_test_loader.py::TestYamlTestLoader::test_plugins_loaded"
] | [] | BSD 3-Clause "New" or "Revised" License | 115 |
|
WikiWatershed__tr-55-21 | 9f2680961841099dcbebaabdb460b11f8789a4ae | 2015-04-30 20:03:55 | 9f2680961841099dcbebaabdb460b11f8789a4ae | diff --git a/README.md b/README.md
index 72023c1..0bda9ed 100644
--- a/README.md
+++ b/README.md
@@ -4,73 +4,174 @@ A Python implementation of TR-55.
## Functions
-`simulate_all_tiles` and `simulate_year` are the two functions intended for consumers of this module.
+`simulate_day`, `simulate_year`, `simulate_modifications` are the three functions most likely to be of direct interest for users of this module.
-### `simulate_all_tiles`
+### `simulate_day`
-The `simulate_all_tiles` function simulates the events of a single day. It takes three arguments:
+The `simulate_day` function simulates the events of a single day. It takes four arguments:
- 1. `parameters` which is either a `date` object (which is mapped to *precipitation* and *evapotranspiration* using sample year data) or that argument is a single day's *precipitation* and *evapotranspiration* as a tuple of two floats (in units of inches).
+ 1. `day` has one of two types. If it is an integer, it representing the day of the year (where `day == 0` represents October 15th) and is used to retrieve the precipitation and evapotranspiration for that day from the sample year table. Alternatively, `day` can be a tuple of precipitation and evapotranspiration.
If the sample year data are to be considered typical, *precipitation* should generally be between 0 and 3 inches daily, and *evapotranspiration* should be between 0 and 0.2 inches daily.
- 2. `tile_census` is a dictionary containing the number of appearances of each type of tile in the query area, e.g.
+ 2. `tile_census` is a dictionary containing the number of appearances of each type of tile in the query area, as well as modifications, e.g.
```Python
- {
- "result": {
- "cell_count": 147,
- "distribution": {
- "d:hi_residential": 33,
- "c:commercial": 42,
- "a:deciduous_forest": 72
- }
- }
- }
+ {
+ "cell_count": 147,
+ "distribution": {
+ "d:hi_residential": {"cell_count": 33},
+ "c:commercial": {"cell_count": 42},
+ "a:deciduous_forest": {"cell_count": 72}
+ },
+ "modifications": {
+ ":no_till": {
+ "cell_count": 30,
+ "distribution": {
+ "d:hi_residential": {"cell_count": 10},
+ "c:commercial": {"cell_count": 20}
+ }
+ },
+ "d:rock": {
+ "cell_count": 5,
+ "distribution": {
+ "a:deciduous_forest": {"cell_count": 5}
+ }
+ }
+ }
+ }
```
- Here, `"d:hi_residential"` indicates *High-Intensity Residential* land use on top of *Type D* soil.
+ Here, `"d:hi_residential"` indicates *High-Intensity Residential* land use on top of *Type D* soil, `"c:commerical"` indicates *Commercial* land use on top of *Type C* soil, and so on.
- 3. `pre_columbian` is a boolean argument which controls whether or not to simulate the given area under pre-Columbian conditions. When this is set to true, all land-uses other than *water* and *wetland* are treated as *mixed forest*.
+ The `":no_till"` key and its value say that 10 units of `"d:hi_residential"` should be turned into `"d:no_till"` and 20 units of `"c:commercial"` should be turned into `"c:no_till"`. The `"d:rock"` key and its value say that 5 units of `"a:deciduous_forest"` should be reclassified as `"d:rock"`.
-The algorithm used is close to TR-55 (the algorithm found in [the USDA's Technical Release 55, revised 1986](http://www.cpesc.org/reference/tr55.pdf)), but with a few differences. The main differences are:
+ 3. `subst` is a substitution that should be performed on the census. It is used to implement the BMPs/reclassifications mentioned above. When `subst` is a colon followed by a BMP, then the BMP is superimposed on all of the tiles in the census. When `subst` is a soil type and a land use, then all tiles in the census are treated as if they have that soil type and land use.
+
+ 4. `pre_columbian` is a boolean argument which controls whether or not to simulate the given area under pre-Columbian conditions. When it set to true, all land-uses other than *water* and *wetland* are treated as *mixed forest*.
+
+The algorithm implemented by this code is close to TR-55, the algorithm found in [the USDA's Technical Release 55, revised 1986](http://www.cpesc.org/reference/tr55.pdf), but with a few differences. The main differences are:
* it applies the TR-55 algorithm on a tile-by-tile basis and aggregates the results rather than running the TR-55 algorithm once over the entire area
* it uses the *Pitt Small Storm Hydrology Model* on tiles which are of a "built-type" when precipitation is two inches or less
-and there are numerous other small differences, as well.
+and there are numerous other small differences.
-`simulate_all_tiles` returns a triple of *runoff*, *evapotranspiration*, and *infiltration* (all in units of inches).
+`simulate_day` returns a dictionary with `runoff`, `et`, and `inf` keys. All three of these numbers are in units of inches.
### `simulate_year`
-The `simulate_year` function takes two parameters, `tile_census` and `pre_columbian` as described above, and simulates an entire year using a year's worth of sample precipitation and evapotranspiration data. It returns a triple of *runoff*, *evapotranspiration*, and *infiltration* for the given area over the entire sample year.
+The `simulate_year` and simulates an entire year using one year of sample precipitation and evapotranspiration data. It returns a dictionary of with `runoff`, `et`, and `inf` keys, and also keys which map associated with various pollutant loads.
+
+The function takes four parameters. `tile_census`, `subst`, and `pre_columbian` as described above. The `cell_res` argument gives the resolution in meters of the data.
+
+### `simulate_modifications`
+
+This function takes three parameters, `tile_census`, `cell_res`, and `pre_columbian`, all as described above. The output of this function is similar to that of `simulate_year`, except it shows the results both with and without modifications.
## Usage Example
The following program:
```Python
-from tr55.model import simulate_year
+# -*- coding: utf-8 -*-
+from __future__ import print_function
+from __future__ import unicode_literals
+from __future__ import division
+
+import pprint
+
+from tr55.model import simulate_modifications
tiles = {
- "result": {
- "cell_count": 147,
- "distribution": {
- "d:hi_residential": 33,
- "c:commercial": 42,
- "a:deciduous_forest": 72
+ "cell_count": 147,
+ "distribution": {
+ "d:hi_residential": {"cell_count": 33},
+ "c:commercial": {"cell_count": 42},
+ "a:deciduous_forest": {"cell_count": 72}
+ },
+ "modifications": {
+ ":no_till": {
+ "cell_count": 30,
+ "distribution": {
+ "d:hi_residential": {"cell_count": 10},
+ "c:commercial": {"cell_count": 20}
+ }
+ },
+ "d:rock": {
+ "cell_count": 5,
+ "distribution": {
+ "a:deciduous_forest": {"cell_count": 5}
+ }
}
}
}
-(q, et, inf) = simulate_year(tiles)
-print("%f inches of runoff" % q)
-print("%f inches of et" % et)
-print("%f inches of infiltration" % inf)
+pprint.pprint(simulate_modifications(tiles))
```
should produce the following output:
-```
-17.614212 inches of runoff
-15.167862 inches of et
-20.245580 inches of infiltration
+```Python
+{u'modified': {u'bod': 1155.5832690023512,
+ u'cell_count': 147,
+ u'distribution': {u'a:deciduous_forest': {u'bod': 1.9676947491691286,
+ u'cell_count': 72,
+ u'et': 24.675262500000017,
+ u'inf': 34.53218880673186,
+ u'runoff': 0.7999320266014792,
+ u'tn': 0.006128885284297285,
+ u'tp': 0.00019354374581991428,
+ u'tss': 1.258034347829443},
+ u'c:commercial': {u'bod': 619.3321622220828,
+ u'cell_count': 42,
+ u'et': 17.42526,
+ u'inf': 16.198443763932524,
+ u'runoff': 21.23295052178176,
+ u'tn': 4.545098932436254,
+ u'tp': 0.7192244464514511,
+ u'tss': 126.3137934080361},
+ u'd:hi_residential': {u'bod': 534.2834120310993,
+ u'cell_count': 33,
+ u'et': 15.08352545454543,
+ u'inf': 13.967458770273502,
+ u'runoff': 24.498158107332266,
+ u'tn': 3.101560485095788,
+ u'tp': 0.5206999354540374,
+ u'tss': 63.842339912190674}},
+ u'et': 20.450586122448982,
+ u'inf': 24.67740388835977,
+ u'runoff': 11.957947247429287,
+ u'tn': 7.652788302816338,
+ u'tp': 1.2401179256513084,
+ u'tss': 191.41416766805622},
+ u'unmodified': {u'bod': 1762.555509187117,
+ u'cell_count': 147,
+ u'distribution': {u'a:deciduous_forest': {u'bod': 0.0,
+ u'cell_count': 72,
+ u'et': 26.51670000000007,
+ u'inf': 34.91810000000001,
+ u'runoff': 0.0,
+ u'tn': 0.0,
+ u'tp': 0.0,
+ u'tss': 0.0},
+ u'c:commercial': {u'bod': 1061.0138827829708,
+ u'cell_count': 42,
+ u'et': 2.272860000000005,
+ u'inf': 4.430079770137537,
+ u'runoff': 36.375400229862464,
+ u'tn': 7.786472849455671,
+ u'tp': 1.2321451541995787,
+ u'tss': 216.39549270630107},
+ u'd:hi_residential': {u'bod': 701.5416264041463,
+ u'cell_count': 33,
+ u'et': 6.818579999999993,
+ u'inf': 8.361629213022574,
+ u'runoff': 32.167342828759615,
+ u'tn': 4.072508593956273,
+ u'tp': 0.6837058223430238,
+ u'tss': 83.8282790872751}},
+ u'et': 15.167861632653095,
+ u'inf': 20.24558036990151,
+ u'runoff': 17.614211721110824,
+ u'tn': 11.858981443411944,
+ u'tp': 1.9158509765426026,
+ u'tss': 300.2237717935762}}
```
## Testing
diff --git a/tr55/model.py b/tr55/model.py
index 4e4cfc9..3ec4b0e 100644
--- a/tr55/model.py
+++ b/tr55/model.py
@@ -1,3 +1,8 @@
+# -*- coding: utf-8 -*-
+from __future__ import print_function
+from __future__ import unicode_literals
+from __future__ import division
+
"""
TR-55 Model Implementation
@@ -10,32 +15,34 @@ and variables used in this program are as follows:
* `init_abs` is Ia, the initial abstraction, another form of infiltration
"""
-from datetime import date, timedelta
-from tr55.tablelookup import days_in_sample_year
-from tr55.tablelookup import lookup_et, lookup_p, lookup_cn
-from tr55.tablelookup import lookup_bmp_infiltration, is_bmp, is_built_type
+import sys
+
+from tr55.tablelookup import lookup_pet, lookup_cn, lookup_bmp_infiltration, \
+ is_bmp, is_built_type, precolumbian, get_pollutants
+from tr55.water_quality import get_volume_of_runoff, get_pollutant_load
+from tr55.operations import dict_minus, dict_plus
def runoff_pitt(precip, land_use):
"""
- The Pitt Small Storm Hydrology method. This comes from Table D in
- the 2010/12/27 document. The output is a runoff value in inches.
+ The Pitt Small Storm Hydrology method. The output is a runoff
+ value in inches.
"""
- co1 = +3.638858398e-2
- co2 = -1.243464039e-1
- co3 = +1.295682223e-1
- co4 = +9.375868043e-1
- co5 = -2.235170859e-2
- co6 = +0.170228067e0
- co7 = -3.971810782e-1
- co8 = +3.887275538e-1
- co9 = -2.289321859e-2
- pr4 = pow(precip, 4)
- pr3 = pow(precip, 3)
- pr2 = pow(precip, 2)
-
- impervious = (co1 * pr3) + (co2 * pr2) + (co3 * precip) + co4
- urb_grass = (co5 * pr4) + (co6 * pr3) + (co7 * pr2) + (co8 * precip) + co9
+ c1 = +3.638858398e-2
+ c2 = -1.243464039e-1
+ c3 = +1.295682223e-1
+ c4 = +9.375868043e-1
+ c5 = -2.235170859e-2
+ c6 = +0.170228067e0
+ c7 = -3.971810782e-1
+ c8 = +3.887275538e-1
+ c9 = -2.289321859e-2
+ p4 = pow(precip, 4)
+ p3 = pow(precip, 3)
+ p2 = pow(precip, 2)
+
+ impervious = (c1 * p3) + (c2 * p2) + (c3 * precip) + c4
+ urb_grass = (c5 * p4) + (c6 * p3) + (c7 * p2) + (c8 * precip) + c9
runoff_vals = {
'water': impervious,
@@ -47,8 +54,9 @@ def runoff_pitt(precip, land_use):
'transportation': impervious,
'urban_grass': urb_grass
}
+
if land_use not in runoff_vals:
- raise Exception('Land use %s not a built-type' % land_use)
+ raise Exception('Land use %s not a built-type.' % land_use)
else:
return min(runoff_vals[land_use], precip)
@@ -71,7 +79,7 @@ def runoff_nrcs(precip, evaptrans, soil_type, land_use):
"""
curve_number = lookup_cn(soil_type, land_use)
if nrcs_cutoff(precip, curve_number):
- return 0
+ return 0.0
potential_retention = (1000.0 / curve_number) - 10
initial_abs = 0.2 * potential_retention
precip_minus_initial_abs = precip - initial_abs
@@ -81,55 +89,43 @@ def runoff_nrcs(precip, evaptrans, soil_type, land_use):
return min(runoff, precip - evaptrans)
-def simulate_tile(parameters, tile_string, pre_columbian=False):
+def simulate_tile(parameters, tile_string):
"""
- Simulate a tile on a given day using the method given in the
- flowchart 2011_06_16_Stroud_model_diagram_revised.PNG and as
- revised by various emails.
+ Simulate a single tile with some particular precipitation and
+ evapotranspiration.
- The first argument can be one of two types. It can either be a
- date object, in which case the precipitation and
- evapotranspiration are looked up from the sample year table.
- Alternatively, those two values can be supplied directly via this
- argument as a tuple.
+ The first argument contains the precipitation and
+ evapotranspiration as a tuple.
The second argument is a string which contains a soil type and
- land use separted by a colon.
-
- The third argument is a boolean which is true if pre-Columbian
- circumstances are to be simulated and false otherwise.
+ land use separated by a colon.
- The return value is a triple of runoff, evapotranspiration, and
+ The return value is a dictionary of runoff, evapotranspiration, and
infiltration.
"""
- tile_string = tile_string.lower();
- soil_type, land_use = tile_string.split(':')
-
- pre_columbian_land_uses = set([
- 'water',
- 'woody_wetland',
- 'herbaceous_wetland'
- ])
-
- if pre_columbian:
- if land_use not in pre_columbian_land_uses:
- land_use = 'mixed_forest'
-
- if type(parameters) is date:
- precip = lookup_p(parameters) # precipitation
- evaptrans = lookup_et(parameters, land_use) # evapotranspiration
- elif type(parameters) is tuple:
+ if type(parameters) is tuple:
precip, evaptrans = parameters
else:
- raise Exception('First argument must be a date or a (P,ET) pair')
+ raise Exception('First argument must be a (P,ET) pair')
+
+ tile_string = tile_string.lower()
+ soil_type, land_use = tile_string.split(':')
if precip == 0.0:
- return (0.0, evaptrans, 0.0)
+ return {
+ 'runoff': 0.0,
+ 'et': evaptrans,
+ 'inf': 0.0,
+ }
if is_bmp(land_use) and land_use != 'rain_garden':
inf = lookup_bmp_infiltration(soil_type, land_use) # infiltration
runoff = precip - (evaptrans + inf) # runoff
- return (runoff, evaptrans, inf) # Q, ET, Inf.
+ return {
+ 'runoff': runoff,
+ 'et': evaptrans,
+ 'inf': inf,
+ }
elif land_use == 'rain_garden':
# Here, return a mixture of 20% ideal rain garden and 80% high
# intensity residential.
@@ -137,9 +133,11 @@ def simulate_tile(parameters, tile_string, pre_columbian=False):
runoff = precip - (evaptrans + inf)
hi_res_tile = soil_type + ':hi_residential'
hi_res = simulate_tile((precip, evaptrans), hi_res_tile)
- return (0.2 * runoff + 0.8 * hi_res[0],
- 0.2 * evaptrans + 0.8 * hi_res[1],
- 0.2 * inf + 0.8 * hi_res[2])
+ return {
+ 'runoff': 0.2 * runoff + 0.8 * hi_res[0],
+ 'et': 0.2 * evaptrans + 0.8 * hi_res[1],
+ 'inf': 0.2 * inf + 0.8 * hi_res[2],
+ }
if is_built_type(land_use) and precip <= 2.0:
runoff = runoff_pitt(precip, land_use)
@@ -150,75 +148,176 @@ def simulate_tile(parameters, tile_string, pre_columbian=False):
else:
runoff = runoff_nrcs(precip, evaptrans, soil_type, land_use)
inf = precip - (evaptrans + runoff)
- return (runoff, evaptrans, max(inf, 0.0))
+ return {
+ 'runoff': runoff,
+ 'et': evaptrans,
+ 'inf': max(inf, 0.0),
+ }
-def simulate_all_tiles(parameters, tile_census, pre_columbian=False):
+
+def simulate_day(day, tile_census, subst=None, pre_columbian=False):
"""
Simulate each tile for one day and return the overall results.
- The first argument is either a day or a P,ET double (as in simulate_tile).
+ The first argument is an integer representing the day of the year
+ (day == 0 represents October 15th) or a precip, et pair.
- The second argument is a dictionary (presumably converted from
- JSON) that gives the number of each type of tile in the query
- polygon.
+ The second argument is a dictionary that gives a census of all of the
+ tiles in the query area.
- The output is a runoff, evapotranspiration, infiltration triple
- which is an average of those produced by all of the tiles.
- """
- if 'result' not in tile_census:
- raise Exception('No "result" key')
- elif 'cell_count' not in tile_census['result']:
- raise Exception('No "result.cell_count" key')
- elif 'distribution' not in tile_census['result']:
- raise Exception('No "result.distribution" key')
+ The third argument is the tile string substitution to be applied
+ to each tile. This is used for simulating BMPs and
+ reclassifications.
- global_count = tile_census['result']['cell_count']
+ The fourth argument is a boolean which is true if pre-Columbian
+ circumstances are to be simulated and false otherwise. When this
+ argument is true, all land uses except for water and wetland are
+ transformed to mixed forest.
- def simulate(tile_string, local_count):
- """
- A local helper function which captures various values.
- """
- return [(x * local_count) / global_count
- for x in simulate_tile(parameters, tile_string, pre_columbian)]
+ The output is a runoff, evapotranspiration, infiltration dictionary.
+ """
+ if 'cell_count' not in tile_census:
+ raise Exception('No "cell_count" key.')
+ elif 'distribution' not in tile_census:
+ raise Exception('No "distribution" key.')
- def simulate_plus(left, right):
+ def simulate(tile, n):
"""
- Add two simulations.
+ Return the three values in units of inch-tiles instead of inches.
+ Inches are an inconvenient unit to work with.
"""
- (a, b, c) = left
- (x, y, z) = right
- return (a+x, b+y, c+z)
+ (soil_type, land_use) = tile.split(':')
+
+ # If a substitution has been supplied, apply it.
+ if sys.version_info.major == 3:
+ types = (str)
+ else:
+ types = (str, unicode)
+ if isinstance(subst, types) and subst.find(':') >= 0:
+ (subst_soil_type, subst_land_use) = subst.split(':')
+ if len(subst_soil_type) > 0:
+ soil_type = subst_soil_type
+ land_use = subst_land_use
+
+ # If a Pre-Columbian simulation has been requested, change the
+ # land use type.
+ if pre_columbian:
+ land_use = precolumbian(land_use)
+
+ # Retrieve the precipitation and evapotranspiration, then run
+ # the simulation.
+ if isinstance(day, int):
+ parameters = lookup_pet(day, land_use)
+ else:
+ parameters = day
+
+ retval = simulate_tile(parameters, soil_type + ':' + land_use)
+ for key in retval.keys():
+ retval[key] *= n
+ return retval
+
+ results = {tile: simulate(tile, d['cell_count'])
+ for tile, d in tile_census['distribution'].items()}
+
+ return {
+ 'distribution': results
+ }
- results = [simulate(tile, n)
- for tile, n in tile_census['result']['distribution'].items()]
- area_sum = (0.0, 0.0, 0.0)
- for result in results:
- area_sum = simulate_plus(area_sum, result)
+def simulate_year(tile_census, cell_res=10, subst=None, pre_columbian=False):
+ """
+ Simulate an entire year, including water quality.
- return area_sum
+ The first argument is a tile census as described in `simulate_day`.
+ The second argument is the tile resolution in meters.
-def simulate_year(tile_census, pre_columbian=False):
- """
- Simulate an entire year.
- """
- year = [date(1, 1, 1) + timedelta(days=i)
- for i in range(days_in_sample_year())]
- simulated_year = [simulate_all_tiles(day, tile_census, pre_columbian)
- for day in year]
+ The third parameter is the tile string substitution to be performed.
- def day_plus(one, two):
- """
- Add two simulated days.
- """
- (runoff1, et1, inf1) = one
- (runoff2, et2, inf2) = two
- return (runoff1 + runoff2, et1 + et2, inf1 + inf2)
+ The fourth parameter is as in `simulate_day`.
+ """
+ # perform a daily simulation for each day of the year
+ simulated_year = [simulate_day(day, tile_census, subst, pre_columbian)
+ for day in range(365)]
- year_sum = (0.0, 0.0, 0.0)
+ # add those simulations together
+ year_sum = {}
for day in simulated_year:
- year_sum = day_plus(year_sum, day)
+ year_sum = dict_plus(year_sum, day)
- return year_sum
+ # add the results into the census
+ retval = dict_plus(year_sum, tile_census)
+
+ # get the land use after the modification.
+ if isinstance(subst, str):
+ use_after = subst.split(':')[1]
+ else:
+ user_after = None # noqa
+
+ # perform water quality computations
+ for (pair, result) in retval['distribution'].items():
+ use_before = pair.split(':')[1]
+ runoff = result['runoff']
+ n = result['cell_count']
+ liters = get_volume_of_runoff(runoff / n, n, cell_res)
+ for pol in get_pollutants():
+ # Try to compute the pollutant load with the land use
+ # after the modifications. If that is impossible (there
+ # is no modification, the use is modified to a BMP, et
+ # cetera) then use the previous land use.
+ try:
+ load = get_pollutant_load(use_after, pol, liters)
+ except:
+ load = get_pollutant_load(use_before, pol, liters)
+ result[pol] = load
+
+ return retval
+
+
+def simulate_modifications(tile_census, cell_res=10, pre_columbian=False):
+ """
+ Simulate an entire year, including effects of modifications.
+ """
+ def rescale(result):
+ if isinstance(result, dict):
+ if 'cell_count' in result:
+ n = float(result['cell_count'])
+ result['runoff'] /= n
+ result['et'] /= n
+ result['inf'] /= n
+ for (key, val) in result.items():
+ rescale(val)
+
+ def tally_subresults(result):
+ retval = result.copy()
+ total = {}
+ for (pair, subresult) in result['distribution'].items():
+ total = dict_plus(total, subresult)
+ retval.update(total)
+ retval.pop('modifications', None)
+ rescale(retval)
+ return retval
+
+ # compute unmodified results
+ orig_result = simulate_year(tile_census, cell_res, None, pre_columbian)
+
+ # Compute the census ex-modifications and the subresults for each
+ # of the modifications.
+ mod_census = tile_census.copy()
+ subresults = []
+ if 'modifications' in tile_census:
+ for (subst, census) in tile_census['modifications'].items():
+ mod_census = dict_minus(mod_census, census)
+ subresult = simulate_year(census, cell_res, subst, pre_columbian)
+ subresults.append(subresult)
+
+ # Compute the result with modifications taken into account.
+ mod_result = simulate_year(mod_census, cell_res, None, pre_columbian)
+ for subresult in subresults:
+ mod_result = dict_plus(mod_result, subresult)
+
+ return {
+ 'unmodified': tally_subresults(orig_result),
+ 'modified': tally_subresults(mod_result)
+ }
diff --git a/tr55/operations.py b/tr55/operations.py
new file mode 100644
index 0000000..ae66328
--- /dev/null
+++ b/tr55/operations.py
@@ -0,0 +1,66 @@
+# -*- coding: utf-8 -*-
+from __future__ import print_function
+from __future__ import unicode_literals
+from __future__ import division
+
+import sys
+
+
+def tandem_walk(op, pred, left, right):
+ """
+ Walk two similarly-structured dictionaries in tandem, performing
+ the given operation when both halves satisfy the given predicate.
+ Otherwise, if both haves are dictionaries, recurse.
+ """
+ if pred(left) and pred(right):
+ return op(left, right)
+ elif isinstance(left, dict) and isinstance(right, dict):
+ retval = left.copy()
+ left_set = set(left.keys())
+ right_set = set(right.keys())
+ intersection = left_set & right_set
+ difference = right_set - left_set
+ for key in intersection:
+ retval[key] = tandem_walk(op, pred, left[key], right[key])
+ for key in difference:
+ retval[key] = right[key]
+ return retval
+
+
+def isnumber(obj):
+ """
+ Is obj a number?
+ """
+ if sys.version_info.major == 3:
+ types = (int, float)
+ else:
+ types = (int, long, float)
+ return isinstance(obj, types)
+
+
+def plus(x, y):
+ """
+ Sum of two numbers.
+ """
+ return x + y
+
+
+def minus(x, y):
+ """
+ Difference of two numbers.
+ """
+ return x - y
+
+
+def dict_plus(left, right):
+ """
+ Sum of two similarly-structured dictionaries.
+ """
+ return tandem_walk(plus, isnumber, left, right)
+
+
+def dict_minus(left, right):
+ """
+ Difference of two similarly-structured dictionaries.
+ """
+ return tandem_walk(minus, isnumber, left, right)
diff --git a/tr55/tablelookup.py b/tr55/tablelookup.py
index 562b55c..eb5115e 100644
--- a/tr55/tablelookup.py
+++ b/tr55/tablelookup.py
@@ -1,80 +1,42 @@
+# -*- coding: utf-8 -*-
+from __future__ import print_function
+from __future__ import unicode_literals
+from __future__ import division
+
"""
Various routines to do table lookups.
"""
-from datetime import date
-from tr55.tables import SAMPLE_YEAR, BMPS, BUILT_TYPES, LAND_USE_VALUES
+from tr55.tables import SAMPLE_YEAR, BMPS, BUILT_TYPES, LAND_USE_VALUES, \
+ PRE_COLUMBIAN_LAND_USES, POLLUTANTS, POLLUTION_LOADS
def lookup_ki(land_use):
"""
Lookup the landuse coefficient.
"""
- if land_use not in LAND_USE_VALUES or 'ki' not in LAND_USE_VALUES[land_use]:
+ if land_use not in LAND_USE_VALUES \
+ or 'ki' not in LAND_USE_VALUES[land_use]:
raise Exception('Unknown land use: %s' % land_use)
else:
return LAND_USE_VALUES[land_use]['ki']
-def lookup_et(simulation_day, land_use):
+def lookup_pet(day, land_use):
"""
Lookup/compute evapotranspiration from the tables.
"""
- fixed_year = SAMPLE_YEAR['year_start'].year
- simulation_day = date(fixed_year, simulation_day.month, simulation_day.day)
-
- # Compute $ET_{\max}$ based on the time of year
- grow_start = SAMPLE_YEAR['growing_start']
- grow_end = SAMPLE_YEAR['growing_end']
- grow_et = SAMPLE_YEAR['growing_etmax']
- nongrow_et = SAMPLE_YEAR['nongrowing_etmax']
- if grow_start <= simulation_day and simulation_day <= grow_end:
- et_max = grow_et
- else:
- et_max = nongrow_et
-
- # Compute the landuse coefficient
- landuse_coefficient = LAND_USE_VALUES[land_use]['ki']
-
- # Report $ET$, the evapotranspiration
- return et_max * landuse_coefficient
-
-
-def days_in_sample_year():
- """
- Return the number of days in the sample year.
- """
- return SAMPLE_YEAR['days_per_year']
-
-
-def lookup_p(simulation_day):
- """
- Lookup percipitation from the SAMPLE_YEAR table.
- """
- fixed_year = SAMPLE_YEAR['year_start'].year
- simulation_day = date(fixed_year, simulation_day.month, simulation_day.day)
- seconds_per_day = 60 * 60 * 24
- days_per_year = SAMPLE_YEAR['days_per_year']
- day_delta = simulation_day - SAMPLE_YEAR['year_start']
- seconds_from_start = day_delta.total_seconds()
- days_from_start = int(seconds_from_start / seconds_per_day)
-
- days = (days_from_start + days_per_year) % days_per_year
- # This is a bit unattractive. If it turns out to be a performance
- # problem (which is unlikely), an interval tree can be used or the
- # SAMPLE_YEAR table itself can be reorganized.
- for consecutive_days, precipitation in SAMPLE_YEAR['precipitation']:
- if 0 <= days and days < consecutive_days:
- return precipitation
- days -= consecutive_days
- raise Exception('No percipitation data for %s' % simulation_day)
+ (precip, et_max) = SAMPLE_YEAR[day]
+ ki = LAND_USE_VALUES[land_use]['ki']
+ return (precip, et_max * ki)
def lookup_bmp_infiltration(soil_type, bmp):
"""
Lookup the amount of infiltration causes by a particular BMP.
"""
- if bmp not in LAND_USE_VALUES or 'infiltration' not in LAND_USE_VALUES[bmp]:
+ if bmp not in LAND_USE_VALUES \
+ or 'infiltration' not in LAND_USE_VALUES[bmp]:
raise Exception('%s not a BMP' % bmp)
elif soil_type not in LAND_USE_VALUES[bmp]['infiltration']:
raise Exception('BMP %s incompatible with soil %s' % (bmp, soil_type))
@@ -88,7 +50,8 @@ def lookup_cn(soil_type, land_use):
"""
if land_use not in LAND_USE_VALUES:
raise Exception('Unknown land use %s' % land_use)
- elif 'cn' not in LAND_USE_VALUES[land_use] or soil_type not in LAND_USE_VALUES[land_use]['cn']:
+ elif 'cn' not in LAND_USE_VALUES[land_use] \
+ or soil_type not in LAND_USE_VALUES[land_use]['cn']:
raise Exception('Unknown soil type %s' % soil_type)
else:
return LAND_USE_VALUES[land_use]['cn'][soil_type]
@@ -106,3 +69,48 @@ def is_built_type(land_use):
Test to see if the land use is a "built type".
"""
return land_use in BUILT_TYPES
+
+
+def precolumbian(land_use):
+ """
+ Project the given land use to a Pre-Columbian one.
+ """
+ if not land_use in PRE_COLUMBIAN_LAND_USES:
+ return 'mixed_forest'
+ else:
+ return land_use
+
+
+def lookup_load(nlcd_class, pollutant):
+ """
+ Get the Event Mean Concentration of `pollutant` for land use
+ class `nlcd_class`
+ """
+ if pollutant not in ['tn', 'tp', 'bod', 'tss']:
+ raise Exception('Unknown pollutant type: %s' % pollutant)
+
+ if nlcd_class not in POLLUTION_LOADS:
+ raise Exception('Unknown NLCD class: %s' % nlcd_class)
+
+ return POLLUTION_LOADS[nlcd_class][pollutant]
+
+
+def lookup_nlcd(land_use):
+ """
+ Get the NLCD number for a particular human-readable land use.
+ """
+ if land_use not in LAND_USE_VALUES:
+ raise Exception('Unknown land use type: %s' % land_use)
+
+ if 'nlcd' not in LAND_USE_VALUES[land_use]:
+ raise Exception('Land use type %s does not have an NLCD class defined',
+ land_use)
+
+ return LAND_USE_VALUES[land_use]['nlcd']
+
+
+def get_pollutants():
+ """
+ Return the list of pollutants.
+ """
+ return POLLUTANTS
diff --git a/tr55/tables.py b/tr55/tables.py
index f94909a..a3ef230 100644
--- a/tr55/tables.py
+++ b/tr55/tables.py
@@ -1,146 +1,416 @@
+# -*- coding: utf-8 -*-
+from __future__ import print_function
+from __future__ import unicode_literals
+from __future__ import division
+
"""
TR-55 tables
"""
-from datetime import date
-
-# The 'year_start' key points to the date on which this year-long
-# dataset starts. The 'growing_start' and 'growing_end' keys point to
-# dates giving the respective start and end of growing season. The
-# values in the array associated with the 'precipitation' key are
-# tuples of a number of consecutive days, and the amount of
-# precipitation during that run of days.
-SAMPLE_YEAR = {
- 'year_start': date(1, 10, 15), # Sample year starts on 10/15
- 'days_per_year': 365, # The number of days in the sample year
-
- 'growing_start': date(1, 4, 15), # Growing season starts on 4/15
- 'growing_end': date(1, 10, 14), # The last day of growing season is 10/14
- 'growing_etmax': 0.207, # Max. e/t during growing season
- 'nongrowing_etmax': 0.0, # ditto non-growing season
+# The values in the array are tuples of inches of precipitation and
+# evapotranspiration. October 15th is at index 0.
+SAMPLE_YEAR = [
+ (0.0, 0.00),
+ (0.0, 0.00),
+ (0.0, 0.00),
+ (0.0, 0.00),
+ (0.0, 0.00),
+ (0.0, 0.00),
+ (0.0, 0.00),
+ (0.0, 0.00),
+ (0.0, 0.00),
+ (0.0, 0.00),
+ (0.0, 0.00),
+ (0.0, 0.00),
+ (0.0, 0.00),
+ (0.0, 0.00),
+ (0.0, 0.00),
+ (0.0, 0.00),
+ (0.0, 0.00),
+ (0.0, 0.00),
+ (0.0, 0.00),
+ (0.0, 0.00),
+ (0.0, 0.00),
+ (0.0, 0.00),
+ (0.0, 0.00),
+ (0.0, 0.00),
+ (0.0, 0.00),
+ (0.0, 0.00),
+ (0.0, 0.00),
+ (0.0, 0.00),
+ (0.0, 0.00),
+ (0.0, 0.00),
+ (0.0, 0.00),
+ (0.0, 0.00),
+ (0.0, 0.00),
+ (0.0, 0.00),
+ (0.0, 0.00),
+ (0.0, 0.00),
+ (0.0, 0.00),
+ (0.0, 0.00),
+ (0.0, 0.00),
+ (0.0, 0.00),
+ (0.0, 0.00),
+ (0.0, 0.00),
+ (0.0, 0.00),
+ (0.0, 0.00),
+ (0.0, 0.00),
+ (0.0, 0.00),
+ (0.0, 0.00),
+ (0.0, 0.00),
+ (0.0, 0.00),
+ (0.0, 0.00),
+ (0.0, 0.00),
+ (0.0, 0.00),
+ (0.0, 0.00),
+ (0.0, 0.00),
+ (0.0, 0.00),
+ (0.0, 0.00),
+ (0.0, 0.00),
+ (0.0, 0.00),
+ (0.0, 0.00),
+ (0.0, 0.00),
+ (0.0, 0.00),
+ (0.0, 0.00),
+ (0.0, 0.00),
+ (0.0, 0.00),
+ (0.0, 0.00),
+ (0.0, 0.00),
+ (0.0, 0.00),
+ (0.0, 0.00),
+ (0.0, 0.00),
+ (0.0, 0.00),
+ (0.0, 0.00),
+ (0.0, 0.00),
+ (0.0, 0.00),
+ (0.0, 0.00),
+ (0.0, 0.00),
+ (0.0, 0.00),
+ (0.0, 0.00),
+ (0.0, 0.00),
+ (0.0, 0.00),
+ (0.0, 0.00),
+ (0.0, 0.00),
+ (0.0, 0.00),
+ (0.0, 0.00),
+ (0.0, 0.00),
+ (0.0, 0.00),
+ (0.0, 0.00),
+ (0.0, 0.00),
+ (0.0, 0.00),
+ (0.0, 0.00),
+ (0.0, 0.00),
+ (0.0, 0.00),
+ (0.0, 0.00),
+ (0.0, 0.00),
+ (0.0, 0.00),
+ (0.0, 0.00),
+ (0.0, 0.00),
+ (0.0, 0.00),
+ (0.0, 0.00),
+ (0.0, 0.00),
+ (0.0, 0.00),
+ (0.0, 0.00),
+ (0.0, 0.00),
+ (0.0, 0.00),
+ (0.0, 0.00),
+ (0.0, 0.00),
+ (0.0, 0.00),
+ (0.0, 0.00),
+ (0.0, 0.00),
+ (0.0, 0.00),
+ (0.0, 0.00),
+ (0.0, 0.00),
+ (0.0, 0.00),
+ (0.0, 0.00),
+ (0.0, 0.00),
+ (0.0, 0.00),
+ (0.0, 0.00),
+ (0.0, 0.00),
+ (0.0, 0.00),
+ (0.0, 0.00),
+ (0.0, 0.00),
+ (0.01, 0.0),
+ (0.01, 0.0),
+ (0.01, 0.0),
+ (0.01, 0.0),
+ (0.01, 0.0),
+ (0.01, 0.0),
+ (0.01, 0.0),
+ (0.02, 0.0),
+ (0.02, 0.0),
+ (0.02, 0.0),
+ (0.02, 0.0),
+ (0.03, 0.0),
+ (0.03, 0.0),
+ (0.03, 0.0),
+ (0.04, 0.0),
+ (0.04, 0.0),
+ (0.05, 0.0),
+ (0.05, 0.0),
+ (0.06, 0.0),
+ (0.06, 0.0),
+ (0.07, 0.0),
+ (0.07, 0.0),
+ (0.08, 0.0),
+ (0.09, 0.0),
+ (0.09, 0.0),
+ (0.10, 0.0),
+ (0.11, 0.0),
+ (0.11, 0.0),
+ (0.12, 0.0),
+ (0.14, 0.0),
+ (0.15, 0.0),
+ (0.16, 0.0),
+ (0.17, 0.0),
+ (0.18, 0.0),
+ (0.20, 0.0),
+ (0.21, 0.0),
+ (0.23, 0.0),
+ (0.25, 0.0),
+ (0.26, 0.0),
+ (0.28, 0.0),
+ (0.30, 0.0),
+ (0.33, 0.0),
+ (0.34, 0.0),
+ (0.37, 0.0),
+ (0.38, 0.0),
+ (0.41, 0.0),
+ (0.44, 0.0),
+ (0.48, 0.0),
+ (0.52, 0.0),
+ (0.55, 0.0),
+ (0.59, 0.0),
+ (0.63, 0.0),
+ (0.67, 0.0),
+ (0.72, 0.0),
+ (0.77, 0.0),
+ (0.82, 0.0),
+ (0.89, 0.0),
+ (0.98, 0.0),
+ (1.09, 0.0),
+ (1.22, 0.0),
+ (1.42, 0.0),
+ (1.92, 0.0),
+ (2.71, 0.207),
+ (1.88, 0.207),
+ (1.57, 0.207),
+ (1.33, 0.207),
+ (1.18, 0.207),
+ (1.06, 0.207),
+ (0.95, 0.207),
+ (0.86, 0.207),
+ (0.76, 0.207),
+ (0.69, 0.207),
+ (0.63, 0.207),
+ (0.57, 0.207),
+ (0.54, 0.207),
+ (0.50, 0.207),
+ (0.46, 0.207),
+ (0.43, 0.207),
+ (0.40, 0.207),
+ (0.37, 0.207),
+ (0.34, 0.207),
+ (0.33, 0.207),
+ (0.30, 0.207),
+ (0.28, 0.207),
+ (0.26, 0.207),
+ (0.25, 0.207),
+ (0.23, 0.207),
+ (0.22, 0.207),
+ (0.20, 0.207),
+ (0.18, 0.207),
+ (0.17, 0.207),
+ (0.16, 0.207),
+ (0.15, 0.207),
+ (0.13, 0.207),
+ (0.12, 0.207),
+ (0.11, 0.207),
+ (0.10, 0.207),
+ (0.10, 0.207),
+ (0.09, 0.207),
+ (0.08, 0.207),
+ (0.08, 0.207),
+ (0.07, 0.207),
+ (0.07, 0.207),
+ (0.06, 0.207),
+ (0.05, 0.207),
+ (0.05, 0.207),
+ (0.04, 0.207),
+ (0.04, 0.207),
+ (0.04, 0.207),
+ (0.03, 0.207),
+ (0.03, 0.207),
+ (0.03, 0.207),
+ (0.02, 0.207),
+ (0.02, 0.207),
+ (0.02, 0.207),
+ (0.02, 0.207),
+ (0.01, 0.207),
+ (0.01, 0.207),
+ (0.01, 0.207),
+ (0.01, 0.207),
+ (0.01, 0.207),
+ (0.01, 0.207),
+ (0.01, 0.207),
+ (0.00, 0.207),
+ (0.00, 0.207),
+ (0.00, 0.207),
+ (0.00, 0.207),
+ (0.00, 0.207),
+ (0.00, 0.207),
+ (0.00, 0.207),
+ (0.00, 0.207),
+ (0.00, 0.207),
+ (0.00, 0.207),
+ (0.00, 0.207),
+ (0.00, 0.207),
+ (0.00, 0.207),
+ (0.00, 0.207),
+ (0.00, 0.207),
+ (0.00, 0.207),
+ (0.00, 0.207),
+ (0.00, 0.207),
+ (0.00, 0.207),
+ (0.00, 0.207),
+ (0.00, 0.207),
+ (0.00, 0.207),
+ (0.00, 0.207),
+ (0.00, 0.207),
+ (0.00, 0.207),
+ (0.00, 0.207),
+ (0.00, 0.207),
+ (0.00, 0.207),
+ (0.00, 0.207),
+ (0.00, 0.207),
+ (0.00, 0.207),
+ (0.00, 0.207),
+ (0.00, 0.207),
+ (0.00, 0.207),
+ (0.00, 0.207),
+ (0.00, 0.207),
+ (0.00, 0.207),
+ (0.00, 0.207),
+ (0.00, 0.207),
+ (0.00, 0.207),
+ (0.00, 0.207),
+ (0.00, 0.207),
+ (0.00, 0.207),
+ (0.00, 0.207),
+ (0.00, 0.207),
+ (0.00, 0.207),
+ (0.00, 0.207),
+ (0.00, 0.207),
+ (0.00, 0.207),
+ (0.00, 0.207),
+ (0.00, 0.207),
+ (0.00, 0.207),
+ (0.00, 0.207),
+ (0.00, 0.207),
+ (0.00, 0.207),
+ (0.00, 0.207),
+ (0.00, 0.207),
+ (0.00, 0.207),
+ (0.00, 0.207),
+ (0.00, 0.207),
+ (0.00, 0.207),
+ (0.00, 0.207),
+ (0.00, 0.207),
+ (0.00, 0.207),
+ (0.00, 0.207),
+ (0.00, 0.207),
+ (0.00, 0.207),
+ (0.00, 0.207),
+ (0.00, 0.207),
+ (0.00, 0.207),
+ (0.00, 0.207),
+ (0.00, 0.207),
+ (0.00, 0.207),
+ (0.00, 0.207),
+ (0.00, 0.207),
+ (0.00, 0.207),
+ (0.00, 0.207),
+ (0.00, 0.207),
+ (0.00, 0.207),
+ (0.00, 0.207),
+ (0.00, 0.207),
+ (0.00, 0.207),
+ (0.00, 0.207),
+ (0.00, 0.207),
+ (0.00, 0.207),
+ (0.00, 0.207),
+ (0.00, 0.207),
+ (0.00, 0.207),
+ (0.00, 0.207),
+ (0.00, 0.207),
+ (0.00, 0.207),
+ (0.00, 0.207),
+ (0.00, 0.207),
+ (0.00, 0.207),
+ (0.00, 0.207),
+ (0.00, 0.207),
+ (0.00, 0.207),
+ (0.00, 0.207),
+ (0.00, 0.207),
+ (0.00, 0.207),
+ (0.00, 0.207),
+ (0.00, 0.207),
+ (0.00, 0.207),
+ (0.00, 0.207),
+ (0.00, 0.207),
+ (0.00, 0.207),
+ (0.00, 0.207),
+ (0.00, 0.207),
+ (0.00, 0.207),
+ (0.00, 0.207),
+ (0.00, 0.207),
+ (0.00, 0.207),
+ (0.00, 0.207),
+ (0.00, 0.207),
+ (0.00, 0.207),
+ (0.00, 0.207),
+ (0.00, 0.207),
+ (0.00, 0.207),
+ (0.00, 0.207),
+ (0.00, 0.207),
+ (0.00, 0.207),
+ (0.00, 0.207)
+]
- 'precipitation': [
- (120, 0.00),
- (7, 0.01),
- (4, 0.02),
- (3, 0.03),
- (2, 0.04),
- (2, 0.05),
- (2, 0.06),
- (2, 0.07),
- (1, 0.08),
- (2, 0.09),
- (1, 0.10),
- (2, 0.11),
- (1, 0.12),
- (1, 0.14),
- (1, 0.15),
- (1, 0.16),
- (1, 0.17),
- (1, 0.18),
- (1, 0.20),
- (1, 0.21),
- (1, 0.23),
- (1, 0.25),
- (1, 0.26),
- (1, 0.28),
- (1, 0.30),
- (1, 0.33),
- (1, 0.34),
- (1, 0.37),
- (1, 0.38),
- (1, 0.41),
- (1, 0.44),
- (1, 0.48),
- (1, 0.52),
- (1, 0.55),
- (1, 0.59),
- (1, 0.63),
- (1, 0.67),
- (1, 0.72),
- (1, 0.77),
- (1, 0.82),
- (1, 0.89),
- (1, 0.98),
- (1, 1.09),
- (1, 1.22),
- (1, 1.42),
- (1, 1.92),
-
- (1, 2.71),
- (1, 1.88),
- (1, 1.57),
- (1, 1.33),
- (1, 1.18),
- (1, 1.06),
- (1, 0.95),
- (1, 0.86),
- (1, 0.76),
- (1, 0.69),
- (1, 0.63),
- (1, 0.57),
- (1, 0.54),
- (1, 0.50),
- (1, 0.46),
- (1, 0.43),
- (1, 0.40),
- (1, 0.37),
- (1, 0.34),
- (1, 0.33),
- (1, 0.30),
- (1, 0.28),
- (1, 0.26),
- (1, 0.25),
- (1, 0.23),
- (1, 0.22),
- (1, 0.20),
- (1, 0.18),
- (1, 0.17),
- (1, 0.16),
- (1, 0.15),
- (1, 0.13),
- (1, 0.12),
- (1, 0.11),
- (2, 0.10),
- (1, 0.09),
- (2, 0.08),
- (2, 0.07),
- (1, 0.06),
- (2, 0.05),
- (3, 0.04),
- (3, 0.03),
- (4, 0.02),
- (7, 0.01),
- (122, 0.00)
- ]
-}
+# Land use descriptions may map to the same nlcd code and have the same values
+# but could be handled differently in the model execution (ex, commercial,
+# industrial, transportation). Describes the NLCD class value, the landscape
+# factor (ki) and the Curve Numbers for each hydrologic soil group for that use
+# type.
+# NOTE: Missing NLCD types 12 & 52 (plus all Alaska only types (51, 72-74)
LAND_USE_VALUES = {
- 'water': {'ki': 0.0, 'cn': {'a': 100, 'b': 100, 'c': 100, 'd': 100}},
- 'li_residential': {'ki': 0.42, 'cn': {'a': 51, 'b': 68, 'c': 79, 'd': 84}},
- 'hi_residential': {'ki': 0.18, 'cn': {'a': 77, 'b': 85, 'c': 90, 'd': 92}},
- 'commercial': {'ki': 0.06, 'cn': {'a': 89, 'b': 92, 'c': 94, 'd': 95}},
- 'industrial': {'ki': 0.06, 'cn': {'a': 89, 'b': 92, 'c': 94, 'd': 95}},
- 'transportation': {'ki': 0.06, 'cn': {'a': 89, 'b': 92, 'c': 94, 'd': 95}},
- 'rock': {'ki': 0.0, 'cn': {'a': 77, 'b': 86, 'c': 86, 'd': 91}},
- 'sand': {'ki': 0.0, 'cn': {'a': 77, 'b': 86, 'c': 86, 'd': 91}},
- 'clay': {'ki': 0.0, 'cn': {'a': 77, 'b': 86, 'c': 86, 'd': 91}},
- 'deciduous_forest': {'ki': 0.7, 'cn': {'a': 30, 'b': 55, 'c': 70, 'd': 77}},
- 'evergreen_forest': {'ki': 0.7, 'cn': {'a': 30, 'b': 55, 'c': 70, 'd': 77}},
- 'mixed_forest': {'ki': 0.7, 'cn': {'a': 30, 'b': 55, 'c': 70, 'd': 77}},
- 'grassland': {'ki': 0.6, 'cn': {'a': 30, 'b': 58, 'c': 71, 'd': 78}},
- 'pasture': {'ki': 0.6, 'cn': {'a': 39, 'b': 61, 'c': 74, 'd': 80}},
- 'hay': {'ki': 0.6, 'cn': {'a': 39, 'b': 61, 'c': 74, 'd': 80}},
- 'row_crop': {'ki': 0.9, 'cn': {'a': 67, 'b': 78, 'c': 85, 'd': 89}},
- 'urban_grass': {'ki': 0.7, 'cn': {'a': 68, 'b': 79, 'c': 86, 'd': 89}},
- 'woody_wetland': {'ki': 1, 'cn': {'a': 98, 'b': 98, 'c': 98, 'd': 98}},
- 'herbaceous_wetland': {'ki': 1, 'cn': {'a': 98, 'b': 98, 'c': 98, 'd': 98}},
- 'green_roof': {'ki': 0.4, 'infiltration': {'a': 1.6, 'b': 1.6, 'c': 1.6, 'd': 1.6}},
- 'porous_paving': {'ki': 0.0, 'infiltration': {'a': 7.73, 'b': 4.13, 'c': 1.73}},
- 'rain_garden': {'ki': 0.08, 'infiltration': {'a': 1.2, 'b': 0.6, 'c': 0.2}},
- 'infiltration_trench': {'ki': 0.0, 'infiltration': {'a': 2.4, 'b': 1.8, 'c': 1.4}},
- 'cluster_housing': {'ki': 0.42},
- 'no_till': {'ki': 0.9, 'cn': {'a': 57, 'b': 73, 'c': 82, 'd': 86}}
+ 'water': {'nlcd': 11, 'ki': 0.0, 'cn': {'a': 100, 'b': 100, 'c': 100, 'd': 100}}, # noqa
+ 'li_residential': {'nlcd': 22, 'ki': 0.42, 'cn': {'a': 51, 'b': 68, 'c': 79, 'd': 84}}, # noqa
+ 'hi_residential': {'nlcd': 23, 'ki': 0.18, 'cn': {'a': 77, 'b': 85, 'c': 90, 'd': 92}}, # noqa
+ 'commercial': {'nlcd': 24, 'ki': 0.06, 'cn': {'a': 89, 'b': 92, 'c': 94, 'd': 95}}, # noqa
+ 'industrial': {'nlcd': 24, 'ki': 0.06, 'cn': {'a': 89, 'b': 92, 'c': 94, 'd': 95}}, # noqa
+ 'transportation': {'nlcd': 24, 'ki': 0.06, 'cn': {'a': 89, 'b': 92, 'c': 94, 'd': 95}}, # noqa
+ 'rock': {'nlcd': 31, 'ki': 0.0, 'cn': {'a': 77, 'b': 86, 'c': 86, 'd': 91}}, # noqa
+ 'sand': {'nlcd': 31, 'ki': 0.0, 'cn': {'a': 77, 'b': 86, 'c': 86, 'd': 91}}, # noqa
+ 'clay': {'nlcd': 31, 'ki': 0.0, 'cn': {'a': 77, 'b': 86, 'c': 86, 'd': 91}}, # noqa
+ 'deciduous_forest': {'nlcd': 41, 'ki': 0.7, 'cn': {'a': 30, 'b': 55, 'c': 70, 'd': 77}}, # noqa
+ 'evergreen_forest': {'nlcd': 42, 'ki': 0.7, 'cn': {'a': 30, 'b': 55, 'c': 70, 'd': 77}}, # noqa
+ 'mixed_forest': {'nlcd': 43, 'ki': 0.7, 'cn': {'a': 30, 'b': 55, 'c': 70, 'd': 77}}, # noqa
+ 'grassland': {'nlcd': 71, 'ki': 0.6, 'cn': {'a': 30, 'b': 58, 'c': 71, 'd': 78}}, # noqa
+ 'pasture': {'nlcd': 81, 'ki': 0.6, 'cn': {'a': 39, 'b': 61, 'c': 74, 'd': 80}}, # noqa
+ 'hay': {'nlcd': 81, 'ki': 0.6, 'cn': {'a': 39, 'b': 61, 'c': 74, 'd': 80}}, # noqa
+ 'row_crop': {'nlcd': 82, 'ki': 0.9, 'cn': {'a': 67, 'b': 78, 'c': 85, 'd': 89}}, # noqa
+ 'urban_grass': {'nlcd': 21, 'ki': 0.7, 'cn': {'a': 68, 'b': 79, 'c': 86, 'd': 89}}, # noqa
+ 'woody_wetland': {'nlcd': 90, 'ki': 1, 'cn': {'a': 98, 'b': 98, 'c': 98, 'd': 98}}, # noqa
+ 'herbaceous_wetland': {'nlcd': 95, 'ki': 1, 'cn': {'a': 98, 'b': 98, 'c': 98, 'd': 98}}, # noqa
+
+ 'green_roof': {'ki': 0.4, 'infiltration': {'a': 1.6, 'b': 1.6, 'c': 1.6, 'd': 1.6}}, # noqa
+ 'porous_paving': {'ki': 0.0, 'infiltration': {'a': 7.73, 'b': 4.13, 'c': 1.73}}, # noqa
+ 'rain_garden': {'ki': 0.08, 'infiltration': {'a': 1.2, 'b': 0.6, 'c': 0.2}}, # noqa
+ 'infiltration_trench': {'ki': 0.0, 'infiltration': {'a': 2.4, 'b': 1.8, 'c': 1.4}}, # noqa
+ 'cluster_housing': {'ki': 0.42},
+ 'no_till': {'ki': 0.9, 'cn': {'a': 57, 'b': 73, 'c': 82, 'd': 86}} # noqa
}
# The set of best management practices that we know about. The
@@ -151,4 +421,49 @@ BMPS = set(['green_roof', 'porous_paving',
# The set of "built" land uses
BUILT_TYPES = set(['li_residential', 'hi_residential', 'cluster_housing',
- 'commercial', 'industrial', 'transportation', 'urban_grass'])
+ 'commercial', 'industrial', 'transportation',
+ 'urban_grass'])
+
+PRE_COLUMBIAN_LAND_USES = set([
+ 'water',
+ 'woody_wetland',
+ 'herbaceous_wetland'
+])
+
+# The set of pollutants that we are concerned with.
+POLLUTANTS = set(['tn', 'tp', 'bod', 'tss'])
+
+# Event mean concentrations (mg/l) by pollutant and NLCD type
+# tn: Total Nitrogen, tp: Total Phosphorus,
+# bod: Biochemical Oxygen Demand, tss: Total Suspended Solids
+POLLUTION_LOADS = {
+ 11: {'tn': 0, 'tp': 0, 'bod': 0, 'tss': 0},
+ 12: {'tn': 0, 'tp': 0, 'bod': 0, 'tss': 0},
+ 21: {'tn': 2.8, 'tp': 0.62, 'bod': 61, 'tss': 155.6},
+ 22: {'tn': 4.15, 'tp': 0.8, 'bod': 309, 'tss': 147.1},
+ 23: {'tn': 6.85, 'tp': 1.15, 'bod': 1180, 'tss': 141.0},
+ 24: {'tn': 9.1, 'tp': 1.44, 'bod': 1240, 'tss': 252.9},
+ 31: {'tn': 0.1, 'tp': 0.01, 'bod': 1320, 'tss': 10},
+ 32: {'tn': 0.1, 'tp': 0.01, 'bod': 30, 'tss': 10},
+ 41: {'tn': 0.19, 'tp': 0.006, 'bod': 61, 'tss': 39},
+ 42: {'tn': 0.19, 'tp': 0.006, 'bod': 61, 'tss': 39},
+ 43: {'tn': 0.19, 'tp': 0.006, 'bod': 61, 'tss': 39},
+ 51: {'tn': 0, 'tp': 0, 'bod': 0, 'tss': 0},
+ 52: {'tn': 0.19, 'tp': 0.006, 'bod': 61, 'tss': 39},
+ 71: {'tn': 0.19, 'tp': 0.006, 'bod': 61, 'tss': 47},
+ 72: {'tn': 0, 'tp': 0, 'bod': 0, 'tss': 0},
+ 73: {'tn': 0, 'tp': 0, 'bod': 0, 'tss': 0},
+ 74: {'tn': 0, 'tp': 0, 'bod': 0, 'tss': 0},
+ 81: {'tn': 23.0, 'tp': 3.0, 'bod': 1000, 'tss': 500},
+ 82: {'tn': 23.0, 'tp': 3.0, 'bod': 1000, 'tss': 1000},
+ 90: {'tn': 0.19, 'tp': 0.006, 'bod': 61, 'tss': 0},
+ 91: {'tn': 0.19, 'tp': 0.006, 'bod': 61, 'tss': 0},
+ 92: {'tn': 0.19, 'tp': 0.006, 'bod': 61, 'tss': 0},
+ 93: {'tn': 0.19, 'tp': 0.006, 'bod': 61, 'tss': 0},
+ 94: {'tn': 0.19, 'tp': 0.006, 'bod': 61, 'tss': 0},
+ 95: {'tn': 0.19, 'tp': 0.006, 'bod': 61, 'tss': 0},
+ 96: {'tn': 0.19, 'tp': 0.006, 'bod': 61, 'tss': 0},
+ 97: {'tn': 0.19, 'tp': 0.006, 'bod': 61, 'tss': 0},
+ 98: {'tn': 0.19, 'tp': 0.006, 'bod': 61, 'tss': 0},
+ 99: {'tn': 0.19, 'tp': 0.006, 'bod': 61, 'tss': 0}
+}
diff --git a/tr55/water_quality.py b/tr55/water_quality.py
new file mode 100644
index 0000000..1abae85
--- /dev/null
+++ b/tr55/water_quality.py
@@ -0,0 +1,53 @@
+# -*- coding: utf-8 -*-
+from __future__ import print_function
+from __future__ import unicode_literals
+from __future__ import division
+
+from tr55.tablelookup import lookup_load, lookup_nlcd
+
+
+def get_volume_of_runoff(runoff, cell_count, cell_resolution):
+ """
+ Calculate the volume of runoff over the entire modeled area
+
+ Args:
+ runoff (number): Q from TR55, averaged amount of runoff over a number
+ of cells.
+
+ cell_count (integer): The number of cells included in the area
+
+ tile_resolution (integer): The size in meters that a cell represents
+
+ Returns:
+ The volume of runoff liters in of the total area of interest
+ """
+
+ # Runoff is in inches, so convert to meters which is the units for the cell
+ # area and compute the meter-cells in the group. Multiply the resolution
+ # of the cell to get the runoff volume in cubic meters.
+ inch_to_meter = 0.0254
+
+ runoff_m = runoff * inch_to_meter
+ meter_cells = runoff_m * cell_count
+ volume_cubic_meters = meter_cells * cell_resolution # XXX
+
+ liters = volume_cubic_meters * 1000
+
+ return liters
+
+
+def get_pollutant_load(use_type, pollutant, runoff_liters):
+ """
+ Calculate the pollutant load over a particular land use type given an
+ amount of runoff generated on that area and an event mean concentration
+ of the pollutant. Returns the pollutant load in lbs.
+ """
+ mg_per_kg = 1000000
+ lbs_per_kg = 2.205
+
+ nlcd = lookup_nlcd(use_type)
+ emc = lookup_load(nlcd, pollutant)
+
+ load_mg_l = emc * runoff_liters
+
+ return (load_mg_l / mg_per_kg) * lbs_per_kg
| Add simple water quality routine.
Barry Evans has provided an algorithm to extend TR-55 results with simple water quality predictions based on the same workflow of the existing model. | WikiWatershed/tr-55 | diff --git a/test/test_model.py b/test/test_model.py
index ac66ae5..201b339 100644
--- a/test/test_model.py
+++ b/test/test_model.py
@@ -1,25 +1,28 @@
+# -*- coding: utf-8 -*-
+from __future__ import print_function
+from __future__ import unicode_literals
+from __future__ import division
+
"""
Model test set
"""
import unittest
-from datetime import date
from math import sqrt
-from tr55.tablelookup import lookup_ki, is_built_type
-from tr55.model import runoff_nrcs, simulate_tile, simulate_all_tiles
-from tr55.model import simulate_year
+
+from tr55.tablelookup import lookup_ki
+from tr55.model import runoff_nrcs, simulate_tile, simulate_day
# These data are taken directly from Table 2-1 of the revised (1986)
# TR-55 report. The data in the PS array are various precipitation
# levels, and each respective CNx array is the calculated runoff for
# that particular curve number with the given level of precipitation
# corresponding to that in PS.
-PS = [1.0, 1.2, 1.4, 1.6, 1.8, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0]
-CN55 = [0.000, 0.000, 0.000, 0.000, 0.000, 0.020, 0.080, 0.190, 0.350, 0.530, 0.740, 0.980, 1.520, 2.120, 2.780, 3.490, 4.230, 5.000, 5.790, 6.610, 7.440, 8.290]
-CN70 = [0.000, 0.030, 0.060, 0.110, 0.170, 0.240, 0.460, 0.710, 1.010, 1.330, 1.670, 2.040, 2.810, 3.620, 4.460, 5.330, 6.220, 7.130, 8.050, 8.980, 9.910, 10.85]
-CN80 = [0.080, 0.150, 0.240, 0.340, 0.440, 0.560, 0.890, 1.250, 1.640, 2.040, 2.460, 2.890, 3.780, 4.690, 5.630, 6.570, 7.520, 8.480, 9.450, 10.42, 11.39, 12.37]
-CN90 = [0.320, 0.460, 0.610, 0.760, 0.930, 1.090, 1.530, 1.980, 2.450, 2.920, 3.400, 3.880, 4.850, 5.820, 6.810, 7.790, 8.780, 9.770, 10.76, 11.76, 12.75, 13.74]
-
+PS = [1.0, 1.2, 1.4, 1.6, 1.8, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0] # noqa
+CN55 = [0.000, 0.000, 0.000, 0.000, 0.000, 0.020, 0.080, 0.190, 0.350, 0.530, 0.740, 0.980, 1.520, 2.120, 2.780, 3.490, 4.230, 5.000, 5.790, 6.610, 7.440, 8.290] # noqa
+CN70 = [0.000, 0.030, 0.060, 0.110, 0.170, 0.240, 0.460, 0.710, 1.010, 1.330, 1.670, 2.040, 2.810, 3.620, 4.460, 5.330, 6.220, 7.130, 8.050, 8.980, 9.910, 10.85] # noqa
+CN80 = [0.080, 0.150, 0.240, 0.340, 0.440, 0.560, 0.890, 1.250, 1.640, 2.040, 2.460, 2.890, 3.780, 4.690, 5.630, 6.570, 7.520, 8.480, 9.450, 10.42, 11.39, 12.37] # noqa
+CN90 = [0.320, 0.460, 0.610, 0.760, 0.930, 1.090, 1.530, 1.980, 2.450, 2.920, 3.400, 3.880, 4.850, 5.820, 6.810, 7.790, 8.780, 9.770, 10.76, 11.76, 12.75, 13.74] # noqa
# INPUT and OUTPUT are data that were emailed to Azavea in a
# spreadsheet for testing the TR-55 model implementation.
INPUT = [
@@ -592,23 +595,26 @@ OUTPUT = [
def simulate(precip, tile_string):
soil_type, land_use = tile_string.split(':')
ki = lookup_ki(land_use)
- return simulate_tile((precip, 0.209 * ki), tile_string)
+ return simulate_tile((precip, 0.207 * ki), tile_string)
+
def average(l):
return reduce(lambda x, y: x + y, l) / len(l)
+
class TestModel(unittest.TestCase):
"""
- Model test set
+ Model test set.
"""
def test_nrcs(self):
"""
Test the implementation of the runoff equation.
"""
- # This pair has CN=55 in Table C of the 2010/12/27 memo
+ # This pair has CN=55
runoffs = [round(runoff_nrcs(precip, 0.0, 'b', 'deciduous_forest'), 2)
for precip in PS]
- self.assertEqual(runoffs[4:], CN55[4:]) # Low curve number and low P cause too-high runoff
+ # Low curve number and low P cause too-high runoff
+ self.assertEqual(runoffs[4:], CN55[4:])
# This pair has CN=70
runoffs = [round(runoff_nrcs(precip, 0.0, 'c', 'deciduous_forest'), 2)
@@ -625,104 +631,174 @@ class TestModel(unittest.TestCase):
for precip in PS]
self.assertEqual(runoffs, CN90)
- def test_simulate_tile_horizontal(self):
+ def test_simulate_tile_1(self):
"""
- Test the one-day simulation using sample input/output. The number
- 0.04 is not very meaningful, this test just attempts to give
- you some idea about the mean error of the three quantities
- relative to precipitation.
+ Test the tile simulation using sample input/output.
+
+ The number 0.04 is not very meaningful, this test just
+ attempts to give some idea about the mean error of the three
+ quantities relative to precipitation.
"""
def similar(incoming, expected):
precip, tile_string = incoming
results = simulate(precip, tile_string)
- me = average(map(lambda x, y: abs(x - y) / precip, results, expected))
+ results = (results['runoff'], results['et'], results['inf'])
+ lam = lambda x, y: abs(x - y) / precip
+ me = average(map(lam, results, expected))
# Precipitation levels <= 2 inches are known to be
# problematic. It is unclear why the 'rock' type is
# giving trouble on soil types C and D.
- if precip > 2 and tile_string != 'c:rock' and tile_string != 'd:rock':
+ if precip > 2 and tile_string != 'c:rock' \
+ and tile_string != 'd:rock':
self.assertTrue(me < 0.04, tile_string + ' ' + str(me))
map(similar, INPUT, OUTPUT)
- def test_simulate_tiles_vertical(self):
+ def test_simulate_tile_2(self):
"""
- Test the RMSE of the runoff levels produced by the one-day
- simulation against values sample input/output. The number
- 0.13 is not very meaningful, this test just attempts to show
- to deviation.
+ Test the RMSE of the runoff levels produced by the tile simulation
+ against values sample input/output. The number 0.13 is not
+ very meaningful, this test just attempts to put a bound on the
+ deviation.
"""
- results = [simulate(precip, tile_string)[0] / precip
+ results = [simulate(precip, tile_string)['runoff'] / precip
for precip, tile_string in INPUT
- if precip > 2 and tile_string != 'c:rock' and tile_string != 'd:rock']
+ if precip > 2 and tile_string != 'c:rock' and
+ tile_string != 'd:rock']
expected = [OUTPUT[i][0] / INPUT[i][0]
for i in range(len(INPUT))
- if INPUT[i][0] > 2 and INPUT[i][1] != 'c:rock' and INPUT[i][1] != 'd:rock']
- rmse = sqrt(average(map(lambda x, y: pow((x - y), 2), results, expected)))
+ if INPUT[i][0] > 2 and INPUT[i][1] != 'c:rock' and
+ INPUT[i][1] != 'd:rock']
+ lam = lambda x, y: pow((x - y), 2)
+ rmse = sqrt(average(map(lam, results, expected)))
self.assertTrue(rmse < 0.13)
- def test_simulate_all_tiles(self):
+ def test_simulate_day_invalid(self):
"""
- Test the tile-by-tile simulation.
+ Test the daily simulation with bad responses.
"""
- # Test invalid responses
+ non_response1 = {
+ "cell_count": 1
+ }
+
non_response2 = {
- "result": { # No "distribution" key
- "cell_count": 1
+ "distribution": {}
+ }
+
+ self.assertRaises(Exception, simulate_day, (0, non_response1))
+ self.assertRaises(Exception, simulate_day, (0, non_response2))
+
+ def test_simulate_day_valid(self):
+ """
+ Test the daily simulation with valid responses.
+ """
+ response1 = {
+ "cell_count": 2,
+ "distribution": {
+ "a:pasture": 1,
+ "c:rock": 1
}
}
- non_response3 = {
- "result": { # No "cell_count" key
- "distribution": {}
+
+ response2 = {
+ "cell_count": 20,
+ "distribution": {
+ "a:pasture": 10,
+ "c:rock": 10
}
}
- self.assertRaises(Exception, simulate_all_tiles, (date.today(), non_response2))
- self.assertRaises(Exception, simulate_all_tiles, (date.today(), non_response3))
- # Test valid responses
+ self.assertEqual(
+ simulate_day(0, response1),
+ simulate_day(0, response2))
+
+ def test_simulate_day_precolumbian(self):
+ """
+ Test the daily simulation in Pre-Columbian times.
+ """
response1 = {
- "result": {
- "cell_count": 2,
- "distribution": {
- "a:pasture": 1,
- "c:rock": 1
- }
+ "cell_count": 1,
+ "distribution": {
+ "d:hi_residential": 1
}
}
+
response2 = {
- "result": {
- "cell_count": 20,
- "distribution": {
- "a:pasture": 10,
- "c:rock": 10
- }
+ "cell_count": 10,
+ "distribution": {
+ "d:pasture": 10
}
}
- map(self.assertAlmostEqual,
- simulate_all_tiles(date.today(), response1),
- simulate_all_tiles(date.today(), response2))
-
- # Test Pre-Columbian calculation
- response3 = {
- "result": {
- "cell_count": 1,
- "distribution": {
- "d:hi_residential": 1
- }
+
+ result1 = simulate_day(182, response1)
+ result2 = simulate_day(182, response2)
+ self.assertNotEqual(
+ result1['distribution']['d:hi_residential'],
+ result2['distribution']['d:pasture'])
+
+ result3 = simulate_day(182, response1, pre_columbian=True)
+ result4 = simulate_day(182, response2, pre_columbian=True)
+ self.assertEqual(
+ result3['distribution']['d:hi_residential'],
+ result4['distribution']['d:pasture'])
+
+ def test_simulate_day_subst_1(self):
+ """
+ Test the daily simulation with BMP substitution.
+ """
+ response1 = {
+ "cell_count": 1,
+ "distribution": {
+ "d:hi_residential": 1
}
}
- response4 = {
- "result": {
- "cell_count": 10,
- "distribution": {
- "d:pasture": 10
- }
+
+ response2 = {
+ "cell_count": 1,
+ "distribution": {
+ "d:no_till": 1
}
}
- map(self.assertNotEqual,
- simulate_all_tiles(date(1, 4, 15), response3),
- simulate_all_tiles(date(1, 4, 15), response4))
- map(self.assertEqual,
- simulate_all_tiles(date(1, 4, 15), response3, True),
- simulate_all_tiles(date(1, 4, 15), response4, True))
+
+ result1 = simulate_day(182, response1)
+ result2 = simulate_day(182, response2)
+ self.assertNotEqual(
+ result1['distribution']['d:hi_residential'],
+ result2['distribution']['d:no_till'])
+
+ result1 = simulate_day(182, response1, subst=':no_till')
+ self.assertEqual(
+ result1['distribution']['d:hi_residential'],
+ result2['distribution']['d:no_till'])
+
+ def test_simulate_day_subst_2(self):
+ """
+ Test the daily simulation with reclassification.
+ """
+ response1 = {
+ "cell_count": 1,
+ "distribution": {
+ "d:mixed_forest": 1
+ }
+ }
+
+ response2 = {
+ "cell_count": 1,
+ "distribution": {
+ "a:rock": 1
+ }
+ }
+
+ result1 = simulate_day(182, response1)
+ result2 = simulate_day(182, response2)
+ self.assertNotEqual(
+ result1['distribution']['d:mixed_forest'],
+ result2['distribution']['a:rock'])
+
+ result1 = simulate_day(182, response1, subst='a:rock')
+ self.assertEqual(
+ result1['distribution']['d:mixed_forest'],
+ result2['distribution']['a:rock'])
+
if __name__ == "__main__":
unittest.main()
diff --git a/test/test_operations.py b/test/test_operations.py
new file mode 100644
index 0000000..5c5a77e
--- /dev/null
+++ b/test/test_operations.py
@@ -0,0 +1,38 @@
+# -*- coding: utf-8 -*-
+from __future__ import print_function
+from __future__ import unicode_literals
+from __future__ import division
+
+"""
+Operation tests.
+"""
+
+import unittest
+
+from tr55.operations import dict_plus, dict_minus
+
+
+class TestOperations(unittest.TestCase):
+ """
+ Dictionary operation test set.
+ """
+ def test_plus(self):
+ """
+ Test dictionary addition.
+ """
+ a = {'x': {'y': {'z': {'a': 1, 'b': 3, 'c': 13}}}}
+ b = {'x': {'y': {'z': {'a': 1, 'b': 5, 'c': 21}}}}
+ c = {'x': {'y': {'z': {'a': 2, 'b': 8, 'c': 34}}}}
+ self.assertEqual(dict_plus(a, b), c)
+
+ def test_minus(self):
+ """
+ Test dictionary subtraction.
+ """
+ a = {'x': {'y': {'z': {'a': 34, 'b': 144, 'c': 610}}}}
+ b = {'x': {'y': {'z': {'a': 21, 'b': 89, 'c': 377}}}}
+ c = {'x': {'y': {'z': {'a': 13, 'b': 55, 'c': 233}}}}
+ self.assertEqual(dict_minus(a, b), c)
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/test/test_tablelookup.py b/test/test_tablelookup.py
index f1b1e83..b9398b6 100644
--- a/test/test_tablelookup.py
+++ b/test/test_tablelookup.py
@@ -1,36 +1,32 @@
+# -*- coding: utf-8 -*-
+from __future__ import print_function
+from __future__ import unicode_literals
+from __future__ import division
+
"""
-Table Lookup test set
+Table Lookup test set.
"""
import unittest
-from datetime import date
-from tr55.tables import LAND_USE_VALUES
-from tr55.tablelookup import lookup_et, lookup_p, lookup_bmp_infiltration, lookup_cn
+
+from tr55.tablelookup import lookup_pet, lookup_bmp_infiltration, lookup_cn
class TestTablelookups(unittest.TestCase):
"""
Table Lookup test set
"""
- def test_lookup_p(self):
+ def test_lookup_pet(self):
"""
Do some spot-checks on the SampleYear data.
"""
- self.assertEqual(lookup_p(date(1, 10, 15)), 0.0)
- self.assertEqual(lookup_p(date(1, 2, 12)), 0.01)
- self.assertEqual(lookup_p(date(1, 2, 15)), 0.01)
- self.assertEqual(lookup_p(date(1, 2, 19)), 0.02)
- self.assertEqual(lookup_p(date(1, 10, 14)), 0.0)
-
- def test_lookup_et(self):
- """
- Do some spot-checks on the data from Table A.
- """
- self.assertEqual(lookup_et(date(1, 4, 15), 'woody_wetland'), 0.207)
- self.assertEqual(lookup_et(date(1, 10, 14), 'woody_wetland'), 0.207)
- self.assertTrue(lookup_et(date(1, 6, 15), 'commercial') > 0.0)
- self.assertEqual(lookup_et(date(1, 4, 14), 'woody_wetland'), 0.0)
- self.assertEqual(lookup_et(date(1, 10, 15), 'woody_wetland'), 0.0)
+ self.assertEqual(lookup_pet(0, 'water')[0], 0.0)
+ self.assertEqual(lookup_pet(52, 'hi_residential')[1], 0.0)
+ self.assertEqual(lookup_pet(104, 'green_roof')[1], 0.0)
+ self.assertEqual(lookup_pet(156, 'cluster_housing')[0], 0.23)
+ self.assertEqual(lookup_pet(208, 'grassland')[0], 0.2)
+ self.assertEqual(lookup_pet(260, 'woody_wetland')[1], 0.207)
+ self.assertEqual(lookup_pet(352, 'hay')[1], 0.207 * 0.6)
def test_lookup_bmp_infiltration(self):
"""
@@ -39,7 +35,7 @@ class TestTablelookups(unittest.TestCase):
self.assertEqual(lookup_bmp_infiltration('d', 'green_roof'), 1.6)
self.assertEqual(lookup_bmp_infiltration('c', 'porous_paving'), 1.73)
self.assertEqual(lookup_bmp_infiltration('b', 'rain_garden'), 0.6)
- self.assertEqual(lookup_bmp_infiltration('a', 'infiltration_trench'), 2.4)
+ self.assertEqual(lookup_bmp_infiltration('a', 'infiltration_trench'), 2.4) # noqa
def test_lookup_cn(self):
"""
diff --git a/test/test_water_quality.py b/test/test_water_quality.py
new file mode 100644
index 0000000..f3cf6b7
--- /dev/null
+++ b/test/test_water_quality.py
@@ -0,0 +1,44 @@
+# -*- coding: utf-8 -*-
+from __future__ import print_function
+from __future__ import unicode_literals
+from __future__ import division
+
+import unittest
+from tr55.water_quality import get_volume_of_runoff, get_pollutant_load
+from tr55.tables import POLLUTION_LOADS
+
+
+class TestWaterQuality(unittest.TestCase):
+
+ def test_volume(self):
+ """
+ Test the water volume computation.
+ """
+ cell_res = 30 # meters
+ cell_count = 100
+ runoff = 0.4 # inches
+ liters = get_volume_of_runoff(runoff, cell_count, cell_res)
+
+ self.assertEquals(30480, liters,
+ "Did not calculate the correct runoff volume")
+
+ def test_load(self):
+ """
+ Test the pollutant load computation.
+ """
+ nlcd = 24
+ pollutant = 'tn'
+ emc = POLLUTION_LOADS[nlcd][pollutant]
+ runoff_liters = 1000
+
+ expected = ((runoff_liters * emc) / 1000000) * 2.205
+ load = get_pollutant_load('commercial', pollutant, runoff_liters)
+
+ self.assertEquals(expected, load)
+
+ def test_load_bad_nlcd(self):
+ self.assertRaises(Exception, get_pollutant_load, 'asdf', 'tn', 1000)
+
+ def test_load_bad_pollutant(self):
+ self.assertRaises(Exception, get_pollutant_load, 'commercial',
+ 'asdf', 1000)
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_short_problem_statement",
"has_added_files",
"has_many_modified_files",
"has_many_hunks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 3,
"issue_text_score": 3,
"test_score": 3
},
"num_modified_files": 4
} | unknown | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[test]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest"
],
"pre_install": null,
"python": "3.9",
"reqs_path": [
"requirements.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | exceptiongroup==1.2.2
iniconfig==2.1.0
nose==1.3.4
packaging==24.2
pluggy==1.5.0
pytest==8.3.5
tomli==2.2.1
-e git+https://github.com/WikiWatershed/tr-55.git@9f2680961841099dcbebaabdb460b11f8789a4ae#egg=tr55
| name: tr-55
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=3.0.16=h5eee18b_0
- pip=25.0=py39h06a4308_0
- python=3.9.21=he870216_1
- readline=8.2=h5eee18b_0
- setuptools=75.8.0=py39h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- tzdata=2025a=h04d1e81_0
- wheel=0.45.1=py39h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- exceptiongroup==1.2.2
- iniconfig==2.1.0
- nose==1.3.4
- packaging==24.2
- pluggy==1.5.0
- pytest==8.3.5
- tomli==2.2.1
prefix: /opt/conda/envs/tr-55
| [
"test/test_model.py::TestModel::test_simulate_day_invalid",
"test/test_model.py::TestModel::test_simulate_tile_1",
"test/test_operations.py::TestOperations::test_minus",
"test/test_operations.py::TestOperations::test_plus",
"test/test_tablelookup.py::TestTablelookups::test_lookup_bmp_infiltration",
"test/test_tablelookup.py::TestTablelookups::test_lookup_cn",
"test/test_tablelookup.py::TestTablelookups::test_lookup_pet",
"test/test_water_quality.py::TestWaterQuality::test_load",
"test/test_water_quality.py::TestWaterQuality::test_load_bad_nlcd",
"test/test_water_quality.py::TestWaterQuality::test_load_bad_pollutant",
"test/test_water_quality.py::TestWaterQuality::test_volume"
] | [
"test/test_model.py::TestModel::test_nrcs",
"test/test_model.py::TestModel::test_simulate_day_precolumbian",
"test/test_model.py::TestModel::test_simulate_day_subst_1",
"test/test_model.py::TestModel::test_simulate_day_subst_2",
"test/test_model.py::TestModel::test_simulate_day_valid",
"test/test_model.py::TestModel::test_simulate_tile_2"
] | [] | [] | Apache License 2.0 | 116 |
|
typesafehub__conductr-cli-50 | 171c9dc9c17827b586d3002ba49186e5653f37bf | 2015-05-01 08:35:41 | e5561a7e43d92a0c19e7b6e31a36448455a17fba | diff --git a/conductr_cli/bundle_utils.py b/conductr_cli/bundle_utils.py
index cf11423..c7b72e2 100644
--- a/conductr_cli/bundle_utils.py
+++ b/conductr_cli/bundle_utils.py
@@ -7,5 +7,5 @@ def short_id(bundle_id):
def conf(bundle_path):
bundle_zip = ZipFile(bundle_path)
- bundleConf = [bundle_zip.read(name) for name in bundle_zip.namelist() if name.endswith('bundle.conf')]
- return bundleConf[0].decode('utf-8') if len(bundleConf) == 1 else ''
+ bundle_configuration = [bundle_zip.read(name) for name in bundle_zip.namelist() if name.endswith('bundle.conf')]
+ return bundle_configuration[0].decode('utf-8') if len(bundle_configuration) == 1 else ''
diff --git a/conductr_cli/conduct.py b/conductr_cli/conduct.py
index 3f62279..0aafe51 100755
--- a/conductr_cli/conduct.py
+++ b/conductr_cli/conduct.py
@@ -3,7 +3,8 @@
import argcomplete
import argparse
-from conductr_cli import conduct_info, conduct_load, conduct_run, conduct_services, conduct_stop, conduct_unload, conduct_version
+from conductr_cli \
+ import conduct_info, conduct_load, conduct_run, conduct_services, conduct_stop, conduct_unload, conduct_version
import os
diff --git a/conductr_cli/conduct_info.py b/conductr_cli/conduct_info.py
index 82dbb02..0c35ad9 100644
--- a/conductr_cli/conduct_info.py
+++ b/conductr_cli/conduct_info.py
@@ -12,7 +12,7 @@ def info(args):
response = requests.get(url)
conduct_logging.raise_for_status_inc_3xx(response)
- if (args.verbose):
+ if args.verbose:
conduct_logging.pretty_json(response.text)
data = [
@@ -38,6 +38,6 @@ def calc_column_widths(data):
for column, value in row.items():
column_len = len(str(value))
width_key = column + '_width'
- if (column_len > column_widths.get(width_key, 0)):
+ if column_len > column_widths.get(width_key, 0):
column_widths[width_key] = column_len
return column_widths
diff --git a/conductr_cli/conduct_load.py b/conductr_cli/conduct_load.py
index 5de7897..3da8ef7 100644
--- a/conductr_cli/conduct_load.py
+++ b/conductr_cli/conduct_load.py
@@ -2,59 +2,64 @@ from pyhocon import ConfigFactory, ConfigTree
from pyhocon.exceptions import ConfigMissingException
from conductr_cli import bundle_utils, conduct_url, conduct_logging
from functools import partial
+from urllib.parse import ParseResult, urlparse, urlunparse
+from urllib.request import urlretrieve
+from pathlib import Path
+
import json
-import os
-import re
import requests
-
@conduct_logging.handle_connection_error
@conduct_logging.handle_http_error
@conduct_logging.handle_invalid_config
@conduct_logging.handle_no_file
+@conduct_logging.handle_bad_zip
def load(args):
"""`conduct load` command"""
- if not os.path.isfile(args.bundle):
- raise FileNotFoundError(args.bundle)
-
- if args.configuration is not None and not os.path.isfile(args.configuration):
- raise FileNotFoundError(args.configuration)
+ print('Retrieving bundle...')
+ bundle_file, bundle_headers = urlretrieve(get_url(args.bundle))
+ if args.configuration is not None:
+ print('Retrieving configuration...')
+ configuration_file, configuration_headers = urlretrieve(get_url(args.configuration)) \
+ if args.configuration is not None else (None, None)
- bundle_conf = ConfigFactory.parse_string(bundle_utils.conf(args.bundle))
- overlay_bundle_conf = None if args.configuration is None else \
- ConfigFactory.parse_string(bundle_utils.conf(args.configuration))
+ bundle_conf = ConfigFactory.parse_string(bundle_utils.conf(bundle_file))
+ overlay_bundle_conf = None if configuration_file is None else \
+ ConfigFactory.parse_string(bundle_utils.conf(configuration_file))
- withBundleConfs = partial(applyToConfs, bundle_conf, overlay_bundle_conf)
+ with_bundle_configurations = partial(apply_to_configurations, bundle_conf, overlay_bundle_conf)
url = conduct_url.url('bundles', args)
files = [
- ('nrOfCpus', withBundleConfs(ConfigTree.get_string, 'nrOfCpus')),
- ('memory', withBundleConfs(ConfigTree.get_string, 'memory')),
- ('diskSpace', withBundleConfs(ConfigTree.get_string, 'diskSpace')),
- ('roles', ' '.join(withBundleConfs(ConfigTree.get_list, 'roles'))),
- ('bundleName', withBundleConfs(ConfigTree.get_string, 'name')),
- ('system', withBundleConfs(ConfigTree.get_string, 'system')),
- ('bundle', open(args.bundle, 'rb'))
+ ('nrOfCpus', with_bundle_configurations(ConfigTree.get_string, 'nrOfCpus')),
+ ('memory', with_bundle_configurations(ConfigTree.get_string, 'memory')),
+ ('diskSpace', with_bundle_configurations(ConfigTree.get_string, 'diskSpace')),
+ ('roles', ' '.join(with_bundle_configurations(ConfigTree.get_list, 'roles'))),
+ ('bundleName', with_bundle_configurations(ConfigTree.get_string, 'name')),
+ ('system', with_bundle_configurations(ConfigTree.get_string, 'system')),
+ ('bundle', open(bundle_file, 'rb'))
]
- if args.configuration is not None:
- files.append(('configuration', open(args.configuration, 'rb')))
+ if configuration_file is not None:
+ files.append(('configuration', open(configuration_file, 'rb')))
+ print('Loading bundle to ConductR...')
response = requests.post(url, files=files)
conduct_logging.raise_for_status_inc_3xx(response)
- if (args.verbose):
+ if args.verbose:
conduct_logging.pretty_json(response.text)
response_json = json.loads(response.text)
- bundleId = response_json['bundleId'] if args.long_ids else bundle_utils.short_id(response_json['bundleId'])
+ bundle_id = response_json['bundleId'] if args.long_ids else bundle_utils.short_id(response_json['bundleId'])
print('Bundle loaded.')
- print('Start bundle with: conduct run{} {}'.format(args.cli_parameters, bundleId))
- print('Unload bundle with: conduct unload{} {}'.format(args.cli_parameters, bundleId))
+ print('Start bundle with: conduct run{} {}'.format(args.cli_parameters, bundle_id))
+ print('Unload bundle with: conduct unload{} {}'.format(args.cli_parameters, bundle_id))
print('Print ConductR info with: conduct info{}'.format(args.cli_parameters))
-def applyToConfs(base_conf, overlay_conf, method, key):
+
+def apply_to_configurations(base_conf, overlay_conf, method, key):
if overlay_conf is None:
return method(base_conf, key)
else:
@@ -62,3 +67,10 @@ def applyToConfs(base_conf, overlay_conf, method, key):
return method(overlay_conf, key)
except ConfigMissingException:
return method(base_conf, key)
+
+
+def get_url(uri):
+ parsed = urlparse(uri, scheme='file')
+ op = Path(uri)
+ np = str(op.cwd() / op if parsed.scheme == 'file' and op.root == '' else parsed.path)
+ return urlunparse(ParseResult(parsed.scheme, parsed.netloc, np, parsed.params, parsed.query, parsed.fragment))
diff --git a/conductr_cli/conduct_logging.py b/conductr_cli/conduct_logging.py
index a4c94d0..c6d13a4 100644
--- a/conductr_cli/conduct_logging.py
+++ b/conductr_cli/conduct_logging.py
@@ -1,9 +1,12 @@
import json
import sys
+import urllib
+
from pyhocon.exceptions import ConfigException
from requests import status_codes
from requests.exceptions import ConnectionError, HTTPError
-
+from urllib.error import URLError
+from zipfile import BadZipFile
# print to stderr
def error(message, *objs):
@@ -15,7 +18,7 @@ def warning(message, *objs):
def connection_error(err, args):
- error('Unable to contact Typesafe ConductR.')
+ error('Unable to contact ConductR.')
error('Reason: {}'.format(err.args[0]))
error('Make sure it can be accessed at {}:{}.'.format(args[0].ip, args[0].port))
@@ -74,7 +77,9 @@ def handle_no_file(func):
def handler(*args, **kwargs):
try:
return func(*args, **kwargs)
- except FileNotFoundError as err:
+ except urllib.error.HTTPError as err:
+ error('Resource not found: {}', err.url)
+ except URLError as err:
error('File not found: {}', err.args[0])
# Do not change the wrapped function name,
@@ -84,6 +89,20 @@ def handle_no_file(func):
return handler
+def handle_bad_zip(func):
+ def handler(*args, **kwargs):
+ try:
+ return func(*args, **kwargs)
+ except BadZipFile as err:
+ error('Problem with the bundle: {}', err.args[0])
+
+ # Do not change the wrapped function name,
+ # so argparse configuration can be tested.
+ handler.__name__ = func.__name__
+
+ return handler
+
+
def raise_for_status_inc_3xx(response):
"""
raise status when status code is 3xx
diff --git a/conductr_cli/conduct_run.py b/conductr_cli/conduct_run.py
index e45ead1..779603c 100644
--- a/conductr_cli/conduct_run.py
+++ b/conductr_cli/conduct_run.py
@@ -13,12 +13,12 @@ def run(args):
response = requests.put(url)
conduct_logging.raise_for_status_inc_3xx(response)
- if (args.verbose):
+ if args.verbose:
conduct_logging.pretty_json(response.text)
response_json = json.loads(response.text)
- bundleId = response_json['bundleId'] if args.long_ids else bundle_utils.short_id(response_json['bundleId'])
+ bundle_id = response_json['bundleId'] if args.long_ids else bundle_utils.short_id(response_json['bundleId'])
print('Bundle run request sent.')
- print('Stop bundle with: conduct stop{} {}'.format(args.cli_parameters, bundleId))
+ print('Stop bundle with: conduct stop{} {}'.format(args.cli_parameters, bundle_id))
print('Print ConductR info with: conduct info{}'.format(args.cli_parameters))
diff --git a/conductr_cli/conduct_services.py b/conductr_cli/conduct_services.py
index 2b07544..236033b 100644
--- a/conductr_cli/conduct_services.py
+++ b/conductr_cli/conduct_services.py
@@ -13,7 +13,7 @@ def services(args):
response = requests.get(url)
conduct_logging.raise_for_status_inc_3xx(response)
- if (args.verbose):
+ if args.verbose:
conduct_logging.pretty_json(response.text)
data = sorted([
@@ -39,7 +39,8 @@ def services(args):
service_endpoints[url.path] |= {service['service']}
except KeyError:
service_endpoints[url.path] = {service['service']}
- duplicate_endpoints = [service for (service, endpoint) in service_endpoints.items() if len(endpoint) > 1] if len(service_endpoints) > 0 else []
+ duplicate_endpoints = [service for (service, endpoint) in service_endpoints.items() if len(endpoint) > 1] \
+ if len(service_endpoints) > 0 else []
data.insert(0, {'service': 'SERVICE', 'bundle_id': 'BUNDLE ID', 'bundle_name': 'BUNDLE NAME', 'status': 'STATUS'})
diff --git a/conductr_cli/conduct_stop.py b/conductr_cli/conduct_stop.py
index b15457d..fdfae85 100644
--- a/conductr_cli/conduct_stop.py
+++ b/conductr_cli/conduct_stop.py
@@ -13,12 +13,12 @@ def stop(args):
response = requests.put(url)
conduct_logging.raise_for_status_inc_3xx(response)
- if (args.verbose):
+ if args.verbose:
conduct_logging.pretty_json(response.text)
response_json = json.loads(response.text)
- bundleId = response_json['bundleId'] if args.long_ids else bundle_utils.short_id(response_json['bundleId'])
+ bundle_id = response_json['bundleId'] if args.long_ids else bundle_utils.short_id(response_json['bundleId'])
print('Bundle stop request sent.')
- print('Unload bundle with: conduct unload{} {}'.format(args.cli_parameters, bundleId))
+ print('Unload bundle with: conduct unload{} {}'.format(args.cli_parameters, bundle_id))
print('Print ConductR info with: conduct info{}'.format(args.cli_parameters))
diff --git a/conductr_cli/conduct_unload.py b/conductr_cli/conduct_unload.py
index b6bc47b..49d9990 100644
--- a/conductr_cli/conduct_unload.py
+++ b/conductr_cli/conduct_unload.py
@@ -12,7 +12,7 @@ def unload(args):
response = requests.delete(url)
conduct_logging.raise_for_status_inc_3xx(response)
- if (args.verbose):
+ if args.verbose:
conduct_logging.pretty_json(response.text)
print('Bundle unload request sent.')
diff --git a/conductr_cli/conduct_version.py b/conductr_cli/conduct_version.py
index 206d209..0e23b33 100644
--- a/conductr_cli/conduct_version.py
+++ b/conductr_cli/conduct_version.py
@@ -2,5 +2,5 @@ from conductr_cli import __version__
# `conduct version` command
-def version(args):
+def version():
print(__version__)
| conduct load should support urls
We should extend the `load` sub command so that it can download a remote resource for the purposes of then uploading it to ConductR. Accepting a URL therefore allows us to pull down bundles and their respective configurations from remote locations. | typesafehub/conductr-cli | diff --git a/conductr_cli/test/cli_test_case.py b/conductr_cli/test/cli_test_case.py
index f57eaad..5f44a83 100644
--- a/conductr_cli/test/cli_test_case.py
+++ b/conductr_cli/test/cli_test_case.py
@@ -10,7 +10,7 @@ class CliTestCase():
@property
def default_connection_error(self):
- return strip_margin("""|ERROR: Unable to contact Typesafe ConductR.
+ return strip_margin("""|ERROR: Unable to contact ConductR.
|ERROR: Reason: test reason
|ERROR: Make sure it can be accessed at {}:{}.
|""")
@@ -47,7 +47,7 @@ class CliTestCase():
def strip_margin(string, marginChar='|'):
- return '\n'.join([line[line.index(marginChar) + 1:] for line in string.split('\n')])
+ return '\n'.join([line[line.find(marginChar) + 1:] for line in string.split('\n')])
def create_temp_bundle_with_contents(contents):
diff --git a/conductr_cli/test/test_conduct_load.py b/conductr_cli/test/test_conduct_load.py
index 8ec2e54..220b4c3 100644
--- a/conductr_cli/test/test_conduct_load.py
+++ b/conductr_cli/test/test_conduct_load.py
@@ -2,6 +2,7 @@ from unittest import TestCase
from unittest.mock import call, patch, MagicMock
from conductr_cli.test.cli_test_case import CliTestCase, create_temp_bundle, create_temp_bundle_with_contents, strip_margin
from conductr_cli import conduct_load
+from urllib.error import URLError
import shutil
@@ -52,7 +53,9 @@ class TestConductLoadCommand(TestCase, CliTestCase):
('bundle', 1)
]
- output_template = """|Bundle loaded.
+ output_template = """|Retrieving bundle...
+ |{downloading_configuration}Loading bundle to ConductR...
+ |{verbose}Bundle loaded.
|Start bundle with: conduct run{params} {bundle_id}
|Unload bundle with: conduct unload{params} {bundle_id}
|Print ConductR info with: conduct info{params}
@@ -62,64 +65,84 @@ class TestConductLoadCommand(TestCase, CliTestCase):
def tearDownClass(cls):
shutil.rmtree(cls.tmpdir)
- def default_output(self, params='', bundle_id='45e0c47'):
- return strip_margin(self.output_template.format(**{'params': params, 'bundle_id': bundle_id}))
+ def default_output(self, params='', bundle_id='45e0c47', downloading_configuration='', verbose=''):
+ return strip_margin(self.output_template.format(**{
+ 'params': params,
+ 'bundle_id': bundle_id,
+ 'downloading_configuration': downloading_configuration,
+ 'verbose': verbose}))
def test_success(self):
+ urlretrieve_mock = MagicMock(return_value=(self.bundle_file, ()))
http_method = self.respond_with(200, self.default_response)
stdout = MagicMock()
- openMock = MagicMock(return_value=1)
+ open_mock = MagicMock(return_value=1)
- with patch('requests.post', http_method), patch('sys.stdout', stdout), patch('builtins.open', openMock):
+ with patch('conductr_cli.conduct_load.urlretrieve', urlretrieve_mock), \
+ patch('requests.post', http_method), \
+ patch('sys.stdout', stdout), \
+ patch('builtins.open', open_mock):
conduct_load.load(MagicMock(**self.default_args))
- openMock.assert_called_with(self.bundle_file, 'rb')
+ open_mock.assert_called_with(self.bundle_file, 'rb')
http_method.assert_called_with(self.default_url, files=self.default_files)
self.assertEqual(self.default_output(), self.output(stdout))
def test_success_verbose(self):
+ urlretrieve_mock = MagicMock(return_value=(self.bundle_file, ()))
http_method = self.respond_with(200, self.default_response)
stdout = MagicMock()
- openMock = MagicMock(return_value=1)
+ open_mock = MagicMock(return_value=1)
- with patch('requests.post', http_method), patch('sys.stdout', stdout), patch('builtins.open', openMock):
+ with patch('conductr_cli.conduct_load.urlretrieve', urlretrieve_mock), \
+ patch('requests.post', http_method), \
+ patch('sys.stdout', stdout), \
+ patch('builtins.open', open_mock):
args = self.default_args.copy()
args.update({'verbose': True})
conduct_load.load(MagicMock(**args))
- openMock.assert_called_with(self.bundle_file, 'rb')
+ open_mock.assert_called_with(self.bundle_file, 'rb')
http_method.assert_called_with(self.default_url, files=self.default_files)
- self.assertEqual(self.default_response + self.default_output(), self.output(stdout))
+ self.assertEqual(self.default_output(verbose=self.default_response), self.output(stdout))
def test_success_long_ids(self):
+ urlretrieve_mock = MagicMock(return_value=(self.bundle_file, ()))
http_method = self.respond_with(200, self.default_response)
stdout = MagicMock()
- openMock = MagicMock(return_value=1)
+ open_mock = MagicMock(return_value=1)
- with patch('requests.post', http_method), patch('sys.stdout', stdout), patch('builtins.open', openMock):
+ with patch('conductr_cli.conduct_load.urlretrieve', urlretrieve_mock), \
+ patch('requests.post', http_method), \
+ patch('sys.stdout', stdout), \
+ patch('builtins.open', open_mock):
args = self.default_args.copy()
args.update({'long_ids': True})
conduct_load.load(MagicMock(**args))
- openMock.assert_called_with(self.bundle_file, 'rb')
+ open_mock.assert_called_with(self.bundle_file, 'rb')
http_method.assert_called_with(self.default_url, files=self.default_files)
self.assertEqual(self.default_output(bundle_id='45e0c477d3e5ea92aa8d85c0d8f3e25c'), self.output(stdout))
def test_success_custom_ip_port(self):
+ urlretrieve_mock = MagicMock(return_value=(self.bundle_file, ()))
http_method = self.respond_with(200, self.default_response)
stdout = MagicMock()
- openMock = MagicMock(return_value=1)
+ open_mock = MagicMock(return_value=1)
cli_parameters = ' --ip 127.0.1.1 --port 9006'
- with patch('requests.post', http_method), patch('sys.stdout', stdout), patch('builtins.open', openMock):
+ with patch('conductr_cli.conduct_load.urlretrieve', urlretrieve_mock),\
+ patch('requests.post', http_method), \
+ patch('sys.stdout', stdout), \
+ patch('builtins.open', open_mock):
args = self.default_args.copy()
args.update({'cli_parameters': cli_parameters})
conduct_load.load(MagicMock(**args))
- openMock.assert_called_with(self.bundle_file, 'rb')
+ open_mock.assert_called_with(self.bundle_file, 'rb')
http_method.assert_called_with(self.default_url, files=self.default_files)
self.assertEqual(
@@ -127,22 +150,26 @@ class TestConductLoadCommand(TestCase, CliTestCase):
self.output(stdout))
def test_success_with_configuration(self):
- http_method = self.respond_with(200, self.default_response)
- stdout = MagicMock()
- openMock = MagicMock(return_value=1)
-
tmpdir, config_file = create_temp_bundle_with_contents({
'bundle.conf': '{name="overlaid-name"}',
'config.sh': 'echo configuring'
})
- with patch('requests.post', http_method), patch('sys.stdout', stdout), patch('builtins.open', openMock):
+ urlretrieve_mock = MagicMock(side_effect=[(self.bundle_file, ()), (config_file, ())])
+ http_method = self.respond_with(200, self.default_response)
+ stdout = MagicMock()
+ open_mock = MagicMock(return_value=1)
+
+ with patch('conductr_cli.conduct_load.urlretrieve', urlretrieve_mock), \
+ patch('requests.post', http_method), \
+ patch('sys.stdout', stdout), \
+ patch('builtins.open', open_mock):
args = self.default_args.copy()
args.update({'configuration': config_file})
conduct_load.load(MagicMock(**args))
self.assertEqual(
- openMock.call_args_list,
+ open_mock.call_args_list,
[call(self.bundle_file, 'rb'), call(config_file, 'rb')]
)
@@ -150,17 +177,21 @@ class TestConductLoadCommand(TestCase, CliTestCase):
expected_files[4] = ('bundleName', 'overlaid-name')
http_method.assert_called_with(self.default_url, files=expected_files)
- self.assertEqual(self.default_output(), self.output(stdout))
+ self.assertEqual(self.default_output(downloading_configuration='Retrieving configuration...\n'), self.output(stdout))
def test_failure(self):
+ urlretrieve_mock = MagicMock(return_value=(self.bundle_file, ()))
http_method = self.respond_with(404)
stderr = MagicMock()
- openMock = MagicMock(return_value=1)
+ open_mock = MagicMock(return_value=1)
- with patch('requests.post', http_method), patch('sys.stderr', stderr), patch('builtins.open', openMock):
+ with patch('conductr_cli.conduct_load.urlretrieve', urlretrieve_mock), \
+ patch('requests.post', http_method), \
+ patch('sys.stderr', stderr), \
+ patch('builtins.open', open_mock):
conduct_load.load(MagicMock(**self.default_args))
- openMock.assert_called_with(self.bundle_file, 'rb')
+ open_mock.assert_called_with(self.bundle_file, 'rb')
http_method.assert_called_with(self.default_url, files=self.default_files)
self.assertEqual(
@@ -169,14 +200,18 @@ class TestConductLoadCommand(TestCase, CliTestCase):
self.output(stderr))
def test_failure_invalid_address(self):
+ urlretrieve_mock = MagicMock(return_value=(self.bundle_file, ()))
http_method = self.raise_connection_error('test reason')
stderr = MagicMock()
- openMock = MagicMock(return_value=1)
+ open_mock = MagicMock(return_value=1)
- with patch('requests.post', http_method), patch('sys.stderr', stderr), patch('builtins.open', openMock):
+ with patch('conductr_cli.conduct_load.urlretrieve', urlretrieve_mock), \
+ patch('requests.post', http_method), \
+ patch('sys.stderr', stderr), \
+ patch('builtins.open', open_mock):
conduct_load.load(MagicMock(**self.default_args))
- openMock.assert_called_with(self.bundle_file, 'rb')
+ open_mock.assert_called_with(self.bundle_file, 'rb')
http_method.assert_called_with(self.default_url, files=self.default_files)
self.assertEqual(
@@ -295,9 +330,10 @@ class TestConductLoadCommand(TestCase, CliTestCase):
shutil.rmtree(tmpdir)
def test_failure_no_bundle(self):
+ urlretrieve_mock = MagicMock(side_effect=URLError('no_such.bundle'))
stderr = MagicMock()
- with patch('sys.stderr', stderr):
+ with patch('conductr_cli.conduct_load.urlretrieve', urlretrieve_mock), patch('sys.stderr', stderr):
args = self.default_args.copy()
args.update({'bundle': 'no_such.bundle'})
conduct_load.load(MagicMock(**args))
@@ -308,9 +344,11 @@ class TestConductLoadCommand(TestCase, CliTestCase):
self.output(stderr))
def test_failure_no_configuration(self):
+ urlretrieve_mock = MagicMock(side_effect=[(self.bundle_file, ()), URLError('no_such.conf')])
+
stderr = MagicMock()
- with patch('sys.stderr', stderr):
+ with patch('conductr_cli.conduct_load.urlretrieve', urlretrieve_mock), patch('sys.stderr', stderr):
args = self.default_args.copy()
args.update({'configuration': 'no_such.conf'})
conduct_load.load(MagicMock(**args))
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 1,
"issue_text_score": 1,
"test_score": 2
},
"num_modified_files": 10
} | 0.13 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "pytest",
"pip_packages": [
"pytest"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.9",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | argcomplete==3.6.1
certifi==2025.1.31
charset-normalizer==3.4.1
-e git+https://github.com/typesafehub/conductr-cli.git@171c9dc9c17827b586d3002ba49186e5653f37bf#egg=conductr_cli
exceptiongroup @ file:///croot/exceptiongroup_1706031385326/work
idna==3.10
iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work
packaging @ file:///croot/packaging_1734472117206/work
pluggy @ file:///croot/pluggy_1733169602837/work
pyhocon==0.2.1
pyparsing==2.0.3
pytest @ file:///croot/pytest_1738938843180/work
requests==2.32.3
tomli @ file:///opt/conda/conda-bld/tomli_1657175507142/work
urllib3==2.3.0
| name: conductr-cli
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- exceptiongroup=1.2.0=py39h06a4308_0
- iniconfig=1.1.1=pyhd3eb1b0_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=3.0.16=h5eee18b_0
- packaging=24.2=py39h06a4308_0
- pip=25.0=py39h06a4308_0
- pluggy=1.5.0=py39h06a4308_0
- pytest=8.3.4=py39h06a4308_0
- python=3.9.21=he870216_1
- readline=8.2=h5eee18b_0
- setuptools=75.8.0=py39h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- tomli=2.0.1=py39h06a4308_0
- tzdata=2025a=h04d1e81_0
- wheel=0.45.1=py39h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- argcomplete==3.6.1
- certifi==2025.1.31
- charset-normalizer==3.4.1
- idna==3.10
- pyhocon==0.2.1
- pyparsing==2.0.3
- requests==2.32.3
- urllib3==2.3.0
prefix: /opt/conda/envs/conductr-cli
| [
"conductr_cli/test/test_conduct_load.py::TestConductLoadCommand::test_failure",
"conductr_cli/test/test_conduct_load.py::TestConductLoadCommand::test_failure_invalid_address",
"conductr_cli/test/test_conduct_load.py::TestConductLoadCommand::test_failure_no_bundle",
"conductr_cli/test/test_conduct_load.py::TestConductLoadCommand::test_failure_no_configuration",
"conductr_cli/test/test_conduct_load.py::TestConductLoadCommand::test_success",
"conductr_cli/test/test_conduct_load.py::TestConductLoadCommand::test_success_custom_ip_port",
"conductr_cli/test/test_conduct_load.py::TestConductLoadCommand::test_success_long_ids",
"conductr_cli/test/test_conduct_load.py::TestConductLoadCommand::test_success_verbose",
"conductr_cli/test/test_conduct_load.py::TestConductLoadCommand::test_success_with_configuration"
] | [] | [
"conductr_cli/test/test_conduct_load.py::TestConductLoadCommand::test_failure_no_disk_space",
"conductr_cli/test/test_conduct_load.py::TestConductLoadCommand::test_failure_no_memory",
"conductr_cli/test/test_conduct_load.py::TestConductLoadCommand::test_failure_no_nr_of_cpus",
"conductr_cli/test/test_conduct_load.py::TestConductLoadCommand::test_failure_no_roles",
"conductr_cli/test/test_conduct_load.py::TestConductLoadCommand::test_failure_roles_not_a_list"
] | [] | Apache License 2.0 | 117 |
|
falconry__falcon-538 | 0af00afd67d92dbf9c6a721d0a1d1218408c1eb7 | 2015-05-01 23:38:20 | b78ffaac7c412d3b3d6cd3c70dd05024d79d2cce | diff --git a/falcon/routing/compiled.py b/falcon/routing/compiled.py
index 1a2f903..79a7bac 100644
--- a/falcon/routing/compiled.py
+++ b/falcon/routing/compiled.py
@@ -29,74 +29,6 @@ class CompiledRouter(object):
tree for each look-up, it generates inlined, bespoke Python code to
perform the search, then compiles that code. This makes the route
processing quite fast.
-
- The generated code looks something like this::
-
- def find(path, return_values, expressions, params):
- path_len = len(path)
- if path_len > 0:
- if path[0] == "repos":
- if path_len > 1:
- params["org"] = path[1]
- if path_len > 2:
- params["repo"] = path[2]
- if path_len > 3:
- if path[3] == "commits":
- return return_values[3]
- if path[3] == "compare":
- if path_len > 4:
- match = expressions[0].match(path[4])
- if match is not None:
- params.update(match.groupdict())
- if path_len > 5:
- if path[5] == "full":
- return return_values[5]
- if path[5] == "part":
- return return_values[6]
- return None
- return return_values[4]
- if path[4] == "all":
- return return_values[7]
- match = expressions[1].match(path[4])
- if match is not None:
- params.update(match.groupdict())
- if path_len > 5:
- if path[5] == "full":
- return return_values[9]
- return None
- return return_values[8]
- return None
- return None
- return None
- return return_values[2]
- return return_values[1]
- return return_values[0]
- if path[0] == "teams":
- if path_len > 1:
- params["id"] = path[1]
- if path_len > 2:
- if path[2] == "members":
- return return_values[11]
- return None
- return return_values[10]
- return None
- if path[0] == "user":
- if path_len > 1:
- if path[1] == "memberships":
- return return_values[12]
- return None
- return None
- if path[0] == "emojis":
- if path_len > 1:
- if path[1] == "signs":
- if path_len > 2:
- params["id"] = path[2]
- return return_values[14]
- return None
- return None
- return return_values[13]
- return None
- return None
"""
def __init__(self):
@@ -125,6 +57,7 @@ class CompiledRouter(object):
if node.matches(segment):
path_index += 1
if path_index == len(path):
+ # NOTE(kgriffs): Override previous node
node.method_map = method_map
node.resource = resource
else:
@@ -179,6 +112,10 @@ class CompiledRouter(object):
level_indent = indent
found_simple = False
+ # NOTE(kgriffs): Sort static nodes before var nodes so that
+ # none of them get masked. False sorts before True.
+ nodes = sorted(nodes, key=lambda node: node.is_var)
+
for node in nodes:
if node.is_var:
if node.is_complex:
@@ -225,7 +162,13 @@ class CompiledRouter(object):
if node.resource is None:
line('return None')
else:
- line('return return_values[%d]' % resource_idx)
+ # NOTE(kgriffs): Make sure that we have consumed all of
+ # the segments for the requested route; otherwise we could
+ # mistakenly match "/foo/23/bar" against "/foo/{id}".
+ line('if path_len == %d:' % (level + 1))
+ line('return return_values[%d]' % resource_idx, 1)
+
+ line('return None')
indent = level_indent
@@ -326,7 +269,7 @@ class CompiledRouterNode(object):
#
# simple, simple ==> True
# simple, complex ==> True
- # simple, string ==> True
+ # simple, string ==> False
# complex, simple ==> True
# complex, complex ==> False
# complex, string ==> False
@@ -334,7 +277,6 @@ class CompiledRouterNode(object):
# string, complex ==> False
# string, string ==> False
#
-
other = CompiledRouterNode(segment)
if self.is_var:
@@ -352,10 +294,13 @@ class CompiledRouterNode(object):
# /foo/{thing1}
# /foo/{thing2}
#
- # or
+ # On the other hand, this is OK:
#
# /foo/{thing1}
# /foo/all
- return True
+ #
+ return other.is_var
+ # NOTE(kgriffs): If self is a static string match, then all the cases
+ # for other are False, so no need to check.
return False
| URI template conflicts after router update
I have been abusing the route order a bit, and would like to know if there is a way to do this with the new router, or if this is actually a bug.
```python
application = falcon.API()
application.add_route('/action1', Action1Handler())
application.add_route('/action2', Action2Handler())
application.add_route('/action3', Action3Handler())
application.add_route('/{action}', ActionFallbackHandler())
```
I realize this is probably a strange use case, and I could move the top 3 handlers into the bottom one and just relay the requests to the various other handlers, but this way seems cleaner. | falconry/falcon | diff --git a/tests/test_default_router.py b/tests/test_default_router.py
index cb14489..8e3b518 100644
--- a/tests/test_default_router.py
+++ b/tests/test_default_router.py
@@ -7,6 +7,9 @@ class ResourceWithId(object):
def __init__(self, resource_id):
self.resource_id = resource_id
+ def __repr__(self):
+ return 'ResourceWithId({0})'.format(self.resource_id)
+
def on_get(self, req, resp):
resp.body = self.resource_id
@@ -36,19 +39,33 @@ def setup_routes(router_interface):
{}, ResourceWithId(10))
router_interface.add_route(
'/repos/{org}/{repo}/compare/all', {}, ResourceWithId(11))
+
+ # NOTE(kgriffs): The ordering of these calls is significant; we
+ # need to test that the {id} field does not match the other routes,
+ # regardless of the order they are added.
router_interface.add_route(
'/emojis/signs/0', {}, ResourceWithId(12))
router_interface.add_route(
'/emojis/signs/{id}', {}, ResourceWithId(13))
+ router_interface.add_route(
+ '/emojis/signs/42', {}, ResourceWithId(14))
+ router_interface.add_route(
+ '/emojis/signs/42/small', {}, ResourceWithId(14.1))
+ router_interface.add_route(
+ '/emojis/signs/78/small', {}, ResourceWithId(14.1))
+
router_interface.add_route(
'/repos/{org}/{repo}/compare/{usr0}:{branch0}...{usr1}:{branch1}/part',
- {}, ResourceWithId(14))
+ {}, ResourceWithId(15))
router_interface.add_route(
'/repos/{org}/{repo}/compare/{usr0}:{branch0}',
- {}, ResourceWithId(15))
+ {}, ResourceWithId(16))
router_interface.add_route(
'/repos/{org}/{repo}/compare/{usr0}:{branch0}/full',
- {}, ResourceWithId(16))
+ {}, ResourceWithId(17))
+
+ router_interface.add_route(
+ '/gists/{id}/raw', {}, ResourceWithId(18))
@ddt.ddt
@@ -61,14 +78,23 @@ class TestStandaloneRouter(testing.TestBase):
@ddt.data(
'/teams/{collision}',
'/repos/{org}/{repo}/compare/{simple-collision}',
- '/emojis/signs/1',
+ '/emojis/signs/{id_too}',
)
def test_collision(self, template):
self.assertRaises(
ValueError,
- self.router.add_route, template, {}, ResourceWithId(6)
+ self.router.add_route, template, {}, ResourceWithId(-1)
)
+ def test_dump(self):
+ print(self.router._src)
+
+ def test_override(self):
+ self.router.add_route('/emojis/signs/0', {}, ResourceWithId(-1))
+
+ resource, method_map, params = self.router.find('/emojis/signs/0')
+ self.assertEqual(resource.resource_id, -1)
+
def test_missing(self):
resource, method_map, params = self.router.find('/this/does/not/exist')
self.assertIs(resource, None)
@@ -90,17 +116,24 @@ class TestStandaloneRouter(testing.TestBase):
resource, method_map, params = self.router.find('/emojis/signs/1')
self.assertEqual(resource.resource_id, 13)
- def test_dead_segment(self):
- resource, method_map, params = self.router.find('/teams')
- self.assertIs(resource, None)
+ resource, method_map, params = self.router.find('/emojis/signs/42')
+ self.assertEqual(resource.resource_id, 14)
- resource, method_map, params = self.router.find('/emojis/signs')
- self.assertIs(resource, None)
+ resource, method_map, params = self.router.find('/emojis/signs/42/small')
+ self.assertEqual(resource.resource_id, 14.1)
- resource, method_map, params = self.router.find('/emojis/signs/stop')
- self.assertEqual(params, {
- 'id': 'stop',
- })
+ resource, method_map, params = self.router.find('/emojis/signs/1/small')
+ self.assertEqual(resource, None)
+
+ @ddt.data(
+ '/teams',
+ '/emojis/signs',
+ '/gists',
+ '/gists/42',
+ )
+ def test_dead_segment(self, template):
+ resource, method_map, params = self.router.find(template)
+ self.assertIs(resource, None)
def test_malformed_pattern(self):
resource, method_map, params = self.router.find(
@@ -120,6 +153,16 @@ class TestStandaloneRouter(testing.TestBase):
self.assertEqual(resource.resource_id, 6)
self.assertEqual(params, {'id': '42'})
+ resource, method_map, params = self.router.find('/emojis/signs/stop')
+ self.assertEqual(params, {'id': 'stop'})
+
+ resource, method_map, params = self.router.find('/gists/42/raw')
+ self.assertEqual(params, {'id': '42'})
+
+ def test_subsegment_not_found(self):
+ resource, method_map, params = self.router.find('/emojis/signs/0/x')
+ self.assertIs(resource, None)
+
def test_multivar(self):
resource, method_map, params = self.router.find(
'/repos/racker/falcon/commits')
@@ -131,7 +174,7 @@ class TestStandaloneRouter(testing.TestBase):
self.assertEqual(resource.resource_id, 11)
self.assertEqual(params, {'org': 'racker', 'repo': 'falcon'})
- @ddt.data(('', 5), ('/full', 10), ('/part', 14))
+ @ddt.data(('', 5), ('/full', 10), ('/part', 15))
@ddt.unpack
def test_complex(self, url_postfix, resource_id):
uri = '/repos/racker/falcon/compare/johndoe:master...janedoe:dev'
@@ -147,7 +190,7 @@ class TestStandaloneRouter(testing.TestBase):
'branch1': 'dev'
})
- @ddt.data(('', 15), ('/full', 16))
+ @ddt.data(('', 16), ('/full', 17))
@ddt.unpack
def test_complex_alt(self, url_postfix, resource_id):
uri = '/repos/falconry/falcon/compare/johndoe:master'
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_many_hunks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 1,
"issue_text_score": 1,
"test_score": 2
},
"num_modified_files": 1
} | 0.3 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "pytest",
"pip_packages": [
"nose",
"coverage",
"ddt",
"pyyaml",
"requests",
"testtools",
"pytest"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.7",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | attrs @ file:///croot/attrs_1668696182826/work
certifi @ file:///croot/certifi_1671487769961/work/certifi
charset-normalizer==3.4.1
coverage==7.2.7
ddt==1.7.2
-e git+https://github.com/falconry/falcon.git@0af00afd67d92dbf9c6a721d0a1d1218408c1eb7#egg=falcon
flit_core @ file:///opt/conda/conda-bld/flit-core_1644941570762/work/source/flit_core
idna==3.10
importlib-metadata @ file:///tmp/build/80754af9/importlib-metadata_1648562407465/work
iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work
nose==1.3.7
packaging @ file:///croot/packaging_1671697413597/work
pluggy @ file:///tmp/build/80754af9/pluggy_1648042572264/work
py @ file:///opt/conda/conda-bld/py_1644396412707/work
pytest==7.1.2
python-mimeparse==1.6.0
PyYAML==6.0.1
requests==2.31.0
six==1.17.0
testtools==2.7.1
tomli @ file:///opt/conda/conda-bld/tomli_1657175507142/work
typing_extensions @ file:///croot/typing_extensions_1669924550328/work
urllib3==2.0.7
zipp @ file:///croot/zipp_1672387121353/work
| name: falcon
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- attrs=22.1.0=py37h06a4308_0
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2022.12.7=py37h06a4308_0
- flit-core=3.6.0=pyhd3eb1b0_0
- importlib-metadata=4.11.3=py37h06a4308_0
- importlib_metadata=4.11.3=hd3eb1b0_0
- iniconfig=1.1.1=pyhd3eb1b0_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- packaging=22.0=py37h06a4308_0
- pip=22.3.1=py37h06a4308_0
- pluggy=1.0.0=py37h06a4308_1
- py=1.11.0=pyhd3eb1b0_0
- pytest=7.1.2=py37h06a4308_0
- python=3.7.16=h7a1cb2a_0
- readline=8.2=h5eee18b_0
- setuptools=65.6.3=py37h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- tomli=2.0.1=py37h06a4308_0
- typing_extensions=4.4.0=py37h06a4308_0
- wheel=0.38.4=py37h06a4308_0
- xz=5.6.4=h5eee18b_1
- zipp=3.11.0=py37h06a4308_0
- zlib=1.2.13=h5eee18b_1
- pip:
- charset-normalizer==3.4.1
- coverage==7.2.7
- ddt==1.7.2
- idna==3.10
- nose==1.3.7
- python-mimeparse==1.6.0
- pyyaml==6.0.1
- requests==2.31.0
- six==1.17.0
- testtools==2.7.1
- urllib3==2.0.7
prefix: /opt/conda/envs/falcon
| [
"tests/test_default_router.py::TestStandaloneRouter::test_collision_1__teams__collision_",
"tests/test_default_router.py::TestStandaloneRouter::test_collision_2__repos__org___repo__compare__simple_collision_",
"tests/test_default_router.py::TestStandaloneRouter::test_collision_3__emojis_signs__id_too_",
"tests/test_default_router.py::TestStandaloneRouter::test_complex_1______5_",
"tests/test_default_router.py::TestStandaloneRouter::test_complex_2____full___10_",
"tests/test_default_router.py::TestStandaloneRouter::test_complex_3____part___15_",
"tests/test_default_router.py::TestStandaloneRouter::test_complex_alt_1______16_",
"tests/test_default_router.py::TestStandaloneRouter::test_complex_alt_2____full___17_",
"tests/test_default_router.py::TestStandaloneRouter::test_dead_segment_1__teams",
"tests/test_default_router.py::TestStandaloneRouter::test_dead_segment_2__emojis_signs",
"tests/test_default_router.py::TestStandaloneRouter::test_dead_segment_3__gists",
"tests/test_default_router.py::TestStandaloneRouter::test_dead_segment_4__gists_42",
"tests/test_default_router.py::TestStandaloneRouter::test_dump",
"tests/test_default_router.py::TestStandaloneRouter::test_literal",
"tests/test_default_router.py::TestStandaloneRouter::test_literal_segment",
"tests/test_default_router.py::TestStandaloneRouter::test_malformed_pattern",
"tests/test_default_router.py::TestStandaloneRouter::test_missing",
"tests/test_default_router.py::TestStandaloneRouter::test_multivar",
"tests/test_default_router.py::TestStandaloneRouter::test_override",
"tests/test_default_router.py::TestStandaloneRouter::test_subsegment_not_found",
"tests/test_default_router.py::TestStandaloneRouter::test_variable"
] | [] | [] | [] | Apache License 2.0 | 118 |
|
mne-tools__mne-python-2053 | 1164d58d954f4dae9266b551d9d3efb979c3f597 | 2015-05-02 21:12:47 | edceb8f38349d6dc0cade1c9f8384cc0707ce3e8 | diff --git a/mne/io/meas_info.py b/mne/io/meas_info.py
index 6e850b71a..b55a983b6 100644
--- a/mne/io/meas_info.py
+++ b/mne/io/meas_info.py
@@ -31,7 +31,7 @@ from ..externals.six import b, BytesIO, string_types, text_type
_kind_dict = dict(
- eeg=(FIFF.FIFFV_EEG_CH, FIFF.FIFFV_COIL_NONE, FIFF.FIFF_UNIT_V),
+ eeg=(FIFF.FIFFV_EEG_CH, FIFF.FIFFV_COIL_EEG, FIFF.FIFF_UNIT_V),
mag=(FIFF.FIFFV_MEG_CH, FIFF.FIFFV_COIL_VV_MAG_T3, FIFF.FIFF_UNIT_T),
grad=(FIFF.FIFFV_MEG_CH, FIFF.FIFFV_COIL_VV_PLANAR_T1, FIFF.FIFF_UNIT_T_M),
misc=(FIFF.FIFFV_MISC_CH, FIFF.FIFFV_COIL_NONE, FIFF.FIFF_UNIT_NONE),
| Initialise coil types
How to initialize coil types in info object?
```
chans = mne.channels.read_montage('BrainAmpMRIPlus_32sfp', ch_names=None, path= datapath, unit='mm', transform=False)
chanNames = chans.ch_names
info = mne.create_info(chanNames, 250.0, ch_types='eeg')
layout = mne.channels.find_layout(info, ch_type='eeg', exclude=None)
eventOnset = np.array(range(1,41))*2
eventZero = np.ones(40)
eventId = np.ones(40)
events = np.transpose(np.vstack((eventOnset, eventZero, eventId)))
epochs = mne.EpochsArray(cueLtemp, info, events, tmin=0, event_id=None, reject=None, flat=None, reject_tmin=None, reject_tmax=None, verbose=None)
epochs.set_montage(chans)
epochs.plot_projs_topomap(ch_type='eeg', layout=layout)
```
I get RuntimeError: No EEG channels present. Cannot find EEG layout. when I run mne.channels.find_layout()
If I use create_info with ch_types = 'eeg' shouldn't the coil type be eeg also? what exactly is the coil type and coil trans anyway? Should they be initialised?
Since I am learning mne is all this stuff explained somewhere or is this the only place I can ask questions? I went through the examples and they all use standard data sets. I am coming from matlab and my data is preprocessed in matlab.
Thanks for helping me out guys | mne-tools/mne-python | diff --git a/mne/io/tests/test_meas_info.py b/mne/io/tests/test_meas_info.py
index 7668f36dd..588ac65a1 100644
--- a/mne/io/tests/test_meas_info.py
+++ b/mne/io/tests/test_meas_info.py
@@ -24,6 +24,15 @@ hsp_fname = op.join(data_dir, 'test_hsp.txt')
elp_fname = op.join(data_dir, 'test_elp.txt')
+def test_make_info():
+ """Test some create_info properties
+ """
+ n_ch = 1
+ info = create_info(n_ch, 1000., 'eeg')
+ coil_types = set([ch['coil_type'] for ch in info['chs']])
+ assert_true(FIFF.FIFFV_COIL_EEG in coil_types)
+
+
def test_fiducials_io():
"""Test fiducials i/o"""
tempdir = _TempDir()
| {
"commit_name": "head_commit",
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true,
"llm_score": {
"difficulty_score": 0,
"issue_text_score": 1,
"test_score": 0
},
"num_modified_files": 1
} | 0.8 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[dev]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"numpy>=1.16.0",
"pandas>=1.0.0",
"scikit-learn",
"h5py",
"pysurfer",
"nose",
"nose-timer",
"pytest"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.7",
"reqs_path": [
"requirements/base.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | apptools==5.2.1
certifi @ file:///croot/certifi_1671487769961/work/certifi
configobj==5.0.9
cycler==0.11.0
envisage==7.0.3
exceptiongroup==1.2.2
fonttools==4.38.0
h5py==3.8.0
importlib-metadata==6.7.0
importlib-resources==5.12.0
iniconfig==2.0.0
joblib==1.3.2
kiwisolver==1.4.5
matplotlib==3.5.3
mayavi==4.8.1
-e git+https://github.com/mne-tools/mne-python.git@1164d58d954f4dae9266b551d9d3efb979c3f597#egg=mne
nibabel==4.0.2
nose==1.3.7
nose-timer==1.0.1
numpy==1.21.6
packaging==24.0
pandas==1.3.5
Pillow==9.5.0
pluggy==1.2.0
pyface==8.0.0
Pygments==2.17.2
pyparsing==3.1.4
pysurfer==0.11.2
pytest==7.4.4
python-dateutil==2.9.0.post0
pytz==2025.2
scikit-learn==1.0.2
scipy==1.7.3
six==1.17.0
threadpoolctl==3.1.0
tomli==2.0.1
traits==6.4.3
traitsui==8.0.0
typing_extensions==4.7.1
vtk==9.3.1
zipp==3.15.0
| name: mne-python
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2022.12.7=py37h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- pip=22.3.1=py37h06a4308_0
- python=3.7.16=h7a1cb2a_0
- readline=8.2=h5eee18b_0
- setuptools=65.6.3=py37h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- wheel=0.38.4=py37h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- apptools==5.2.1
- configobj==5.0.9
- cycler==0.11.0
- envisage==7.0.3
- exceptiongroup==1.2.2
- fonttools==4.38.0
- h5py==3.8.0
- importlib-metadata==6.7.0
- importlib-resources==5.12.0
- iniconfig==2.0.0
- joblib==1.3.2
- kiwisolver==1.4.5
- matplotlib==3.5.3
- mayavi==4.8.1
- nibabel==4.0.2
- nose==1.3.7
- nose-timer==1.0.1
- numpy==1.21.6
- packaging==24.0
- pandas==1.3.5
- pillow==9.5.0
- pluggy==1.2.0
- pyface==8.0.0
- pygments==2.17.2
- pyparsing==3.1.4
- pysurfer==0.11.2
- pytest==7.4.4
- python-dateutil==2.9.0.post0
- pytz==2025.2
- scikit-learn==1.0.2
- scipy==1.7.3
- six==1.17.0
- threadpoolctl==3.1.0
- tomli==2.0.1
- traits==6.4.3
- traitsui==8.0.0
- typing-extensions==4.7.1
- vtk==9.3.1
- zipp==3.15.0
prefix: /opt/conda/envs/mne-python
| [
"mne/io/tests/test_meas_info.py::test_make_info"
] | [] | [
"mne/io/tests/test_meas_info.py::test_fiducials_io",
"mne/io/tests/test_meas_info.py::test_info",
"mne/io/tests/test_meas_info.py::test_read_write_info",
"mne/io/tests/test_meas_info.py::test_io_dig_points",
"mne/io/tests/test_meas_info.py::test_make_dig_points"
] | [] | BSD 3-Clause "New" or "Revised" License | 119 |
|
softlayer__softlayer-python-542 | 6ece88935972d6165adba9f2ea19e56020967c55 | 2015-05-03 21:31:29 | 1195b2020ef6efc40462d59eb079f26e5f39a6d8 | diff --git a/SoftLayer/CLI/formatting.py b/SoftLayer/CLI/formatting.py
index 138e5318..b7f25a5c 100644
--- a/SoftLayer/CLI/formatting.py
+++ b/SoftLayer/CLI/formatting.py
@@ -192,8 +192,8 @@ def no_going_back(confirmation):
prompt = ('This action cannot be undone! Type "%s" or press Enter '
'to abort' % confirmation)
- ans = click.confirm(prompt, default='', show_default=False).lower()
- if ans == str(confirmation):
+ ans = click.prompt(prompt, default='', show_default=False)
+ if ans.lower() == str(confirmation):
return True
return False
diff --git a/SoftLayer/managers/messaging.py b/SoftLayer/managers/messaging.py
index 6c7e0237..8c273b6b 100644
--- a/SoftLayer/managers/messaging.py
+++ b/SoftLayer/managers/messaging.py
@@ -168,7 +168,12 @@ def _make_request(self, method, path, **kwargs):
url = '/'.join((self.endpoint, 'v1', self.account_id, path))
resp = requests.request(method, url, **kwargs)
- resp.raise_for_status()
+ try:
+ resp.raise_for_status()
+ except requests.HTTPError as ex:
+ content = json.loads(ex.response.content)
+ raise exceptions.SoftLayerAPIError(ex.response.status_code,
+ content['message'])
return resp
def authenticate(self, username, api_key, auth_token=None):
| dns record-remove AttributeError
I think the transcript speaks for itself. :)
```
$ slcli --version
slcli (SoftLayer Command-line), version 4.0.1
$ slcli dns record-remove 56530852
This action cannot be undone! Type "yes" or press Enter to abort: yes
An unexpected error has occured:
Traceback (most recent call last):
File "/usr/local/lib/python2.7/site-packages/SoftLayer/CLI/core.py", line 180, in main
cli.main()
File "/usr/local/lib/python2.7/site-packages/click/core.py", line 644, in main
rv = self.invoke(ctx)
File "/usr/local/lib/python2.7/site-packages/click/core.py", line 991, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "/usr/local/lib/python2.7/site-packages/click/core.py", line 991, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "/usr/local/lib/python2.7/site-packages/click/core.py", line 837, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "/usr/local/lib/python2.7/site-packages/click/core.py", line 464, in invoke
return callback(*args, **kwargs)
File "/usr/local/lib/python2.7/site-packages/click/decorators.py", line 64, in new_func
return ctx.invoke(f, obj, *args[1:], **kwargs)
File "/usr/local/lib/python2.7/site-packages/click/core.py", line 464, in invoke
return callback(*args, **kwargs)
File "/usr/local/lib/python2.7/site-packages/SoftLayer/CLI/dns/record_remove.py", line 20, in cli
if not (env.skip_confirmations or formatting.no_going_back('yes')):
File "/usr/local/lib/python2.7/site-packages/SoftLayer/CLI/formatting.py", line 195, in no_going_back
ans = click.confirm(prompt, default='', show_default=False).lower()
AttributeError: 'bool' object has no attribute 'lower'
Feel free to report this error as it is likely a bug:
https://github.com/softlayer/softlayer-python/issues
```
| softlayer/softlayer-python | diff --git a/SoftLayer/tests/CLI/helper_tests.py b/SoftLayer/tests/CLI/helper_tests.py
index 1dea9ab4..d6017355 100644
--- a/SoftLayer/tests/CLI/helper_tests.py
+++ b/SoftLayer/tests/CLI/helper_tests.py
@@ -41,21 +41,21 @@ def test_fail(self):
class PromptTests(testing.TestCase):
- @mock.patch('click.confirm')
- def test_do_or_die(self, confirm_mock):
+ @mock.patch('click.prompt')
+ def test_do_or_die(self, prompt_mock):
confirmed = '37347373737'
- confirm_mock.return_value = confirmed
+ prompt_mock.return_value = confirmed
result = formatting.no_going_back(confirmed)
self.assertTrue(result)
# no_going_back should cast int's to str()
confirmed = '4712309182309'
- confirm_mock.return_value = confirmed
+ prompt_mock.return_value = confirmed
result = formatting.no_going_back(int(confirmed))
self.assertTrue(result)
confirmed = None
- confirm_mock.return_value = ''
+ prompt_mock.return_value = ''
result = formatting.no_going_back(confirmed)
self.assertFalse(result)
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 0,
"issue_text_score": 1,
"test_score": 0
},
"num_modified_files": 2
} | 4.0 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[dev]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.6",
"reqs_path": [
"tools/test-requirements.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | alabaster==0.7.13
attrs==22.2.0
Babel==2.11.0
certifi==2021.5.30
charset-normalizer==2.0.12
click==8.0.4
coverage==6.2
distlib==0.3.9
docutils==0.18.1
filelock==3.4.1
fixtures==4.0.1
idna==3.10
imagesize==1.4.1
importlib-metadata==4.8.3
importlib-resources==5.4.0
iniconfig==1.1.1
Jinja2==3.0.3
MarkupSafe==2.0.1
mock==5.2.0
nose==1.3.7
packaging==21.3
pbr==6.1.1
platformdirs==2.4.0
pluggy==1.0.0
prettytable==2.5.0
py==1.11.0
Pygments==2.14.0
pyparsing==3.1.4
pytest==7.0.1
pytz==2025.2
requests==2.27.1
six==1.17.0
snowballstemmer==2.2.0
-e git+https://github.com/softlayer/softlayer-python.git@6ece88935972d6165adba9f2ea19e56020967c55#egg=SoftLayer
Sphinx==5.3.0
sphinxcontrib-applehelp==1.0.2
sphinxcontrib-devhelp==1.0.2
sphinxcontrib-htmlhelp==2.0.0
sphinxcontrib-jsmath==1.0.1
sphinxcontrib-qthelp==1.0.3
sphinxcontrib-serializinghtml==1.1.5
testtools==2.6.0
toml==0.10.2
tomli==1.2.3
tox==3.28.0
typing_extensions==4.1.1
urllib3==1.26.20
virtualenv==20.17.1
wcwidth==0.2.13
zipp==3.6.0
| name: softlayer-python
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- pip=21.2.2=py36h06a4308_0
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_0
- setuptools=58.0.4=py36h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- alabaster==0.7.13
- attrs==22.2.0
- babel==2.11.0
- charset-normalizer==2.0.12
- click==8.0.4
- coverage==6.2
- distlib==0.3.9
- docutils==0.18.1
- filelock==3.4.1
- fixtures==4.0.1
- idna==3.10
- imagesize==1.4.1
- importlib-metadata==4.8.3
- importlib-resources==5.4.0
- iniconfig==1.1.1
- jinja2==3.0.3
- markupsafe==2.0.1
- mock==5.2.0
- nose==1.3.7
- packaging==21.3
- pbr==6.1.1
- platformdirs==2.4.0
- pluggy==1.0.0
- prettytable==2.5.0
- py==1.11.0
- pygments==2.14.0
- pyparsing==3.1.4
- pytest==7.0.1
- pytz==2025.2
- requests==2.27.1
- six==1.17.0
- snowballstemmer==2.2.0
- sphinx==5.3.0
- sphinxcontrib-applehelp==1.0.2
- sphinxcontrib-devhelp==1.0.2
- sphinxcontrib-htmlhelp==2.0.0
- sphinxcontrib-jsmath==1.0.1
- sphinxcontrib-qthelp==1.0.3
- sphinxcontrib-serializinghtml==1.1.5
- testtools==2.6.0
- toml==0.10.2
- tomli==1.2.3
- tox==3.28.0
- typing-extensions==4.1.1
- urllib3==1.26.20
- virtualenv==20.17.1
- wcwidth==0.2.13
- zipp==3.6.0
prefix: /opt/conda/envs/softlayer-python
| [
"SoftLayer/tests/CLI/helper_tests.py::PromptTests::test_do_or_die"
] | [] | [
"SoftLayer/tests/CLI/helper_tests.py::CLIJSONEncoderTest::test_default",
"SoftLayer/tests/CLI/helper_tests.py::CLIJSONEncoderTest::test_fail",
"SoftLayer/tests/CLI/helper_tests.py::PromptTests::test_confirmation",
"SoftLayer/tests/CLI/helper_tests.py::FormattedItemTests::test_blank",
"SoftLayer/tests/CLI/helper_tests.py::FormattedItemTests::test_gb",
"SoftLayer/tests/CLI/helper_tests.py::FormattedItemTests::test_init",
"SoftLayer/tests/CLI/helper_tests.py::FormattedItemTests::test_mb_to_gb",
"SoftLayer/tests/CLI/helper_tests.py::FormattedListTests::test_init",
"SoftLayer/tests/CLI/helper_tests.py::FormattedListTests::test_str",
"SoftLayer/tests/CLI/helper_tests.py::FormattedListTests::test_to_python",
"SoftLayer/tests/CLI/helper_tests.py::FormattedTxnTests::test_active_txn",
"SoftLayer/tests/CLI/helper_tests.py::FormattedTxnTests::test_active_txn_empty",
"SoftLayer/tests/CLI/helper_tests.py::FormattedTxnTests::test_active_txn_missing",
"SoftLayer/tests/CLI/helper_tests.py::FormattedTxnTests::test_transaction_status",
"SoftLayer/tests/CLI/helper_tests.py::FormattedTxnTests::test_transaction_status_missing",
"SoftLayer/tests/CLI/helper_tests.py::CLIAbortTests::test_init",
"SoftLayer/tests/CLI/helper_tests.py::ResolveIdTests::test_resolve_id_multiple",
"SoftLayer/tests/CLI/helper_tests.py::ResolveIdTests::test_resolve_id_none",
"SoftLayer/tests/CLI/helper_tests.py::ResolveIdTests::test_resolve_id_one",
"SoftLayer/tests/CLI/helper_tests.py::TestFormatOutput::test_format_output_formatted_item",
"SoftLayer/tests/CLI/helper_tests.py::TestFormatOutput::test_format_output_json",
"SoftLayer/tests/CLI/helper_tests.py::TestFormatOutput::test_format_output_json_keyvaluetable",
"SoftLayer/tests/CLI/helper_tests.py::TestFormatOutput::test_format_output_list",
"SoftLayer/tests/CLI/helper_tests.py::TestFormatOutput::test_format_output_python",
"SoftLayer/tests/CLI/helper_tests.py::TestFormatOutput::test_format_output_python_keyvaluetable",
"SoftLayer/tests/CLI/helper_tests.py::TestFormatOutput::test_format_output_raw",
"SoftLayer/tests/CLI/helper_tests.py::TestFormatOutput::test_format_output_string",
"SoftLayer/tests/CLI/helper_tests.py::TestFormatOutput::test_format_output_table",
"SoftLayer/tests/CLI/helper_tests.py::TestFormatOutput::test_sequentialoutput",
"SoftLayer/tests/CLI/helper_tests.py::TestFormatOutput::test_unknown",
"SoftLayer/tests/CLI/helper_tests.py::TestTemplateArgs::test_no_template_option",
"SoftLayer/tests/CLI/helper_tests.py::TestTemplateArgs::test_template_options",
"SoftLayer/tests/CLI/helper_tests.py::TestExportToTemplate::test_export_to_template"
] | [] | MIT License | 120 |
|
softlayer__softlayer-python-543 | 6ece88935972d6165adba9f2ea19e56020967c55 | 2015-05-03 23:26:15 | 1195b2020ef6efc40462d59eb079f26e5f39a6d8 | diff --git a/SoftLayer/CLI/formatting.py b/SoftLayer/CLI/formatting.py
index 138e5318..41556a9a 100644
--- a/SoftLayer/CLI/formatting.py
+++ b/SoftLayer/CLI/formatting.py
@@ -73,6 +73,7 @@ def format_prettytable(table):
for i, row in enumerate(table.rows):
for j, item in enumerate(row):
table.rows[i][j] = format_output(item)
+
ptable = table.prettytable()
ptable.hrules = prettytable.FRAME
ptable.horizontal_char = '.'
@@ -83,12 +84,15 @@ def format_prettytable(table):
def format_no_tty(table):
"""Converts SoftLayer.CLI.formatting.Table instance to a prettytable."""
+
for i, row in enumerate(table.rows):
for j, item in enumerate(row):
table.rows[i][j] = format_output(item, fmt='raw')
ptable = table.prettytable()
+
for col in table.columns:
ptable.align[col] = 'l'
+
ptable.hrules = prettytable.NONE
ptable.border = False
ptable.header = False
@@ -304,6 +308,30 @@ def __str__(self):
__repr__ = __str__
+ # Implement sorting methods.
+ # NOTE(kmcdonald): functools.total_ordering could be used once support for
+ # Python 2.6 is dropped
+ def __eq__(self, other):
+ return self.original == getattr(other, 'original', other)
+
+ def __lt__(self, other):
+ if self.original is None:
+ return True
+
+ other_val = getattr(other, 'original', other)
+ if other_val is None:
+ return False
+ return self.original < other_val
+
+ def __gt__(self, other):
+ return not (self < other or self == other)
+
+ def __le__(self, other):
+ return self < other or self == other
+
+ def __ge__(self, other):
+ return not self < other
+
def _format_python_value(value):
"""If the value has to_python() defined then return that."""
diff --git a/SoftLayer/CLI/server/list.py b/SoftLayer/CLI/server/list.py
index 03ba456e..d6f45622 100644
--- a/SoftLayer/CLI/server/list.py
+++ b/SoftLayer/CLI/server/list.py
@@ -14,7 +14,7 @@
@click.command()
@click.option('--sortby',
help='Column to sort by',
- type=click.Choice(['guid',
+ type=click.Choice(['id',
'hostname',
'primary_ip',
'backend_ip',
| unable to pipe out the `slcli server list commands`
Running `slcli server list` works fine, but it throws an error when piping to another file (or grep)
`slcli vs list` can pipe to another unix commands fine.
`slcli server list | tee /tmp/a`
An unexpected error has occured:
Traceback (most recent call last):
File "/usr/local/lib/python3.4/site-packages/SoftLayer-4.0.1-py3.4.egg/SoftLayer/CLI/core.py", line 180, in main
cli.main()
File "/usr/local/lib/python3.4/site-packages/click/core.py", line 644, in main
rv = self.invoke(ctx)
File "/usr/local/lib/python3.4/site-packages/click/core.py", line 991, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "/usr/local/lib/python3.4/site-packages/click/core.py", line 959, in _process_result
**ctx.params)
File "/usr/local/lib/python3.4/site-packages/click/core.py", line 464, in invoke
return callback(*args, **kwargs)
File "/usr/local/lib/python3.4/site-packages/SoftLayer-4.0.1-py3.4.egg/SoftLayer/CLI/core.py", line 162, in output_result
output = env.fmt(result)
File "/usr/local/lib/python3.4/site-packages/SoftLayer-4.0.1-py3.4.egg/SoftLayer/CLI/environment.py", line 45, in fmt
return formatting.format_output(output, fmt=self.format)
File "/usr/local/lib/python3.4/site-packages/SoftLayer-4.0.1-py3.4.egg/SoftLayer/CLI/formatting.py", line 38, in format_output
return str(format_no_tty(data))
File "/usr/local/lib/python3.4/site-packages/prettytable.py", line 237, in __str__
return self.__unicode__()
File "/usr/local/lib/python3.4/site-packages/prettytable.py", line 243, in __unicode__
return self.get_string()
File "/usr/local/lib/python3.4/site-packages/prettytable.py", line 984, in get_string
rows = self._get_rows(options)
File "/usr/local/lib/python3.4/site-packages/prettytable.py", line 933, in _get_rows
rows.sort(reverse=options["reversesort"], key=options["sort_key"])
TypeError: unorderable types: FormattedItem() < str()
Feel free to report this error as it is likely a bug:
https://github.com/softlayer/softlayer-python/issues
| softlayer/softlayer-python | diff --git a/SoftLayer/testing/fixtures/SoftLayer_Account.py b/SoftLayer/testing/fixtures/SoftLayer_Account.py
index 994d5fb6..9e1a43da 100644
--- a/SoftLayer/testing/fixtures/SoftLayer_Account.py
+++ b/SoftLayer/testing/fixtures/SoftLayer_Account.py
@@ -136,7 +136,7 @@
'friendlyName': 'Friendly Transaction Name',
'id': 6660
}
- }
+ },
}, {
'id': 1001,
'globalIdentifier': '1a2b3c-1702',
@@ -224,6 +224,8 @@
'id': 19082
},
]
+}, {
+ 'id': 1003,
}]
getDomains = [{'name': 'example.com',
'id': 12345,
diff --git a/SoftLayer/tests/CLI/helper_tests.py b/SoftLayer/tests/CLI/helper_tests.py
index 1dea9ab4..e693535a 100644
--- a/SoftLayer/tests/CLI/helper_tests.py
+++ b/SoftLayer/tests/CLI/helper_tests.py
@@ -131,6 +131,27 @@ def test_blank(self):
self.assertEqual('-', item.formatted)
self.assertEqual('NULL', str(item))
+ def test_sort_mixed(self):
+ blank = formatting.blank()
+ items = [10, blank]
+ sorted_items = sorted(items)
+ self.assertEqual(sorted_items, [blank, 10])
+
+ items = [blank, 10]
+ sorted_items = sorted(items)
+ self.assertEqual(sorted_items, [blank, 10])
+
+ items = [blank, "10"]
+ sorted_items = sorted(items)
+ self.assertEqual(sorted_items, [blank, "10"])
+
+ def test_sort(self):
+ items = [10, formatting.FormattedItem(20), formatting.FormattedItem(5)]
+ sorted_items = sorted(items)
+ self.assertEqual(sorted_items, [formatting.FormattedItem(5),
+ 10,
+ formatting.FormattedItem(20)])
+
class FormattedListTests(testing.TestCase):
def test_init(self):
diff --git a/SoftLayer/tests/CLI/modules/server_tests.py b/SoftLayer/tests/CLI/modules/server_tests.py
index a65538cf..85df2f42 100644
--- a/SoftLayer/tests/CLI/modules/server_tests.py
+++ b/SoftLayer/tests/CLI/modules/server_tests.py
@@ -84,11 +84,19 @@ def test_list_servers(self):
'id': 1002,
'backend_ip': '10.1.0.4',
'action': None,
- }
+ },
+ {
+ 'action': None,
+ 'backend_ip': None,
+ 'datacenter': None,
+ 'hostname': None,
+ 'id': 1003,
+ 'primary_ip': None,
+ },
]
self.assertEqual(result.exit_code, 0)
- self.assertEqual(json.loads(result.output), expected)
+ self.assertEqual(expected, json.loads(result.output))
@mock.patch('SoftLayer.CLI.formatting.no_going_back')
@mock.patch('SoftLayer.HardwareManager.reload')
diff --git a/SoftLayer/tests/managers/hardware_tests.py b/SoftLayer/tests/managers/hardware_tests.py
index 79aa5025..efec2591 100644
--- a/SoftLayer/tests/managers/hardware_tests.py
+++ b/SoftLayer/tests/managers/hardware_tests.py
@@ -78,7 +78,7 @@ def test_list_hardware_with_filters(self):
def test_resolve_ids_ip(self):
_id = self.hardware._get_ids_from_ip('172.16.1.100')
- self.assertEqual(_id, [1000, 1001, 1002])
+ self.assertEqual(_id, [1000, 1001, 1002, 1003])
_id = self.hardware._get_ids_from_ip('nope')
self.assertEqual(_id, [])
@@ -93,7 +93,7 @@ def test_resolve_ids_ip(self):
def test_resolve_ids_hostname(self):
_id = self.hardware._get_ids_from_hostname('hardware-test1')
- self.assertEqual(_id, [1000, 1001, 1002])
+ self.assertEqual(_id, [1000, 1001, 1002, 1003])
def test_get_hardware(self):
result = self.hardware.get_hardware(1000)
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 2,
"issue_text_score": 0,
"test_score": 0
},
"num_modified_files": 2
} | 4.0 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[dev]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.6",
"reqs_path": [
"tools/test-requirements.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | alabaster==0.7.13
attrs==22.2.0
Babel==2.11.0
certifi==2021.5.30
charset-normalizer==2.0.12
click==8.0.4
coverage==6.2
distlib==0.3.9
docutils==0.18.1
filelock==3.4.1
fixtures==4.0.1
idna==3.10
imagesize==1.4.1
importlib-metadata==4.8.3
importlib-resources==5.4.0
iniconfig==1.1.1
Jinja2==3.0.3
MarkupSafe==2.0.1
mock==5.2.0
nose==1.3.7
packaging==21.3
pbr==6.1.1
platformdirs==2.4.0
pluggy==1.0.0
prettytable==2.5.0
py==1.11.0
Pygments==2.14.0
pyparsing==3.1.4
pytest==7.0.1
pytz==2025.2
requests==2.27.1
six==1.17.0
snowballstemmer==2.2.0
-e git+https://github.com/softlayer/softlayer-python.git@6ece88935972d6165adba9f2ea19e56020967c55#egg=SoftLayer
Sphinx==5.3.0
sphinxcontrib-applehelp==1.0.2
sphinxcontrib-devhelp==1.0.2
sphinxcontrib-htmlhelp==2.0.0
sphinxcontrib-jsmath==1.0.1
sphinxcontrib-qthelp==1.0.3
sphinxcontrib-serializinghtml==1.1.5
testtools==2.6.0
toml==0.10.2
tomli==1.2.3
tox==3.28.0
typing_extensions==4.1.1
urllib3==1.26.20
virtualenv==20.17.1
wcwidth==0.2.13
zipp==3.6.0
| name: softlayer-python
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- pip=21.2.2=py36h06a4308_0
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_0
- setuptools=58.0.4=py36h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- alabaster==0.7.13
- attrs==22.2.0
- babel==2.11.0
- charset-normalizer==2.0.12
- click==8.0.4
- coverage==6.2
- distlib==0.3.9
- docutils==0.18.1
- filelock==3.4.1
- fixtures==4.0.1
- idna==3.10
- imagesize==1.4.1
- importlib-metadata==4.8.3
- importlib-resources==5.4.0
- iniconfig==1.1.1
- jinja2==3.0.3
- markupsafe==2.0.1
- mock==5.2.0
- nose==1.3.7
- packaging==21.3
- pbr==6.1.1
- platformdirs==2.4.0
- pluggy==1.0.0
- prettytable==2.5.0
- py==1.11.0
- pygments==2.14.0
- pyparsing==3.1.4
- pytest==7.0.1
- pytz==2025.2
- requests==2.27.1
- six==1.17.0
- snowballstemmer==2.2.0
- sphinx==5.3.0
- sphinxcontrib-applehelp==1.0.2
- sphinxcontrib-devhelp==1.0.2
- sphinxcontrib-htmlhelp==2.0.0
- sphinxcontrib-jsmath==1.0.1
- sphinxcontrib-qthelp==1.0.3
- sphinxcontrib-serializinghtml==1.1.5
- testtools==2.6.0
- toml==0.10.2
- tomli==1.2.3
- tox==3.28.0
- typing-extensions==4.1.1
- urllib3==1.26.20
- virtualenv==20.17.1
- wcwidth==0.2.13
- zipp==3.6.0
prefix: /opt/conda/envs/softlayer-python
| [
"SoftLayer/tests/CLI/helper_tests.py::FormattedItemTests::test_sort",
"SoftLayer/tests/CLI/helper_tests.py::FormattedItemTests::test_sort_mixed"
] | [] | [
"SoftLayer/tests/CLI/helper_tests.py::CLIJSONEncoderTest::test_default",
"SoftLayer/tests/CLI/helper_tests.py::CLIJSONEncoderTest::test_fail",
"SoftLayer/tests/CLI/helper_tests.py::PromptTests::test_confirmation",
"SoftLayer/tests/CLI/helper_tests.py::PromptTests::test_do_or_die",
"SoftLayer/tests/CLI/helper_tests.py::FormattedItemTests::test_blank",
"SoftLayer/tests/CLI/helper_tests.py::FormattedItemTests::test_gb",
"SoftLayer/tests/CLI/helper_tests.py::FormattedItemTests::test_init",
"SoftLayer/tests/CLI/helper_tests.py::FormattedItemTests::test_mb_to_gb",
"SoftLayer/tests/CLI/helper_tests.py::FormattedListTests::test_init",
"SoftLayer/tests/CLI/helper_tests.py::FormattedListTests::test_str",
"SoftLayer/tests/CLI/helper_tests.py::FormattedListTests::test_to_python",
"SoftLayer/tests/CLI/helper_tests.py::FormattedTxnTests::test_active_txn",
"SoftLayer/tests/CLI/helper_tests.py::FormattedTxnTests::test_active_txn_empty",
"SoftLayer/tests/CLI/helper_tests.py::FormattedTxnTests::test_active_txn_missing",
"SoftLayer/tests/CLI/helper_tests.py::FormattedTxnTests::test_transaction_status",
"SoftLayer/tests/CLI/helper_tests.py::FormattedTxnTests::test_transaction_status_missing",
"SoftLayer/tests/CLI/helper_tests.py::CLIAbortTests::test_init",
"SoftLayer/tests/CLI/helper_tests.py::ResolveIdTests::test_resolve_id_multiple",
"SoftLayer/tests/CLI/helper_tests.py::ResolveIdTests::test_resolve_id_none",
"SoftLayer/tests/CLI/helper_tests.py::ResolveIdTests::test_resolve_id_one",
"SoftLayer/tests/CLI/helper_tests.py::TestFormatOutput::test_format_output_formatted_item",
"SoftLayer/tests/CLI/helper_tests.py::TestFormatOutput::test_format_output_json",
"SoftLayer/tests/CLI/helper_tests.py::TestFormatOutput::test_format_output_json_keyvaluetable",
"SoftLayer/tests/CLI/helper_tests.py::TestFormatOutput::test_format_output_list",
"SoftLayer/tests/CLI/helper_tests.py::TestFormatOutput::test_format_output_python",
"SoftLayer/tests/CLI/helper_tests.py::TestFormatOutput::test_format_output_python_keyvaluetable",
"SoftLayer/tests/CLI/helper_tests.py::TestFormatOutput::test_format_output_raw",
"SoftLayer/tests/CLI/helper_tests.py::TestFormatOutput::test_format_output_string",
"SoftLayer/tests/CLI/helper_tests.py::TestFormatOutput::test_format_output_table",
"SoftLayer/tests/CLI/helper_tests.py::TestFormatOutput::test_sequentialoutput",
"SoftLayer/tests/CLI/helper_tests.py::TestFormatOutput::test_unknown",
"SoftLayer/tests/CLI/helper_tests.py::TestTemplateArgs::test_no_template_option",
"SoftLayer/tests/CLI/helper_tests.py::TestTemplateArgs::test_template_options",
"SoftLayer/tests/CLI/helper_tests.py::TestExportToTemplate::test_export_to_template",
"SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_cancel_server",
"SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_create_options",
"SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_create_server",
"SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_create_server_missing_required",
"SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_create_server_test_flag",
"SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_create_server_with_export",
"SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_edit_server_failed",
"SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_edit_server_userdata",
"SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_edit_server_userdata_and_file",
"SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_edit_server_userfile",
"SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_list_servers",
"SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_nic_edit_server",
"SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_server_cancel_reasons",
"SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_server_details",
"SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_server_power_cycle",
"SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_server_power_cycle_negative",
"SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_server_power_off",
"SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_server_power_on",
"SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_server_reboot_default",
"SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_server_reboot_hard",
"SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_server_reboot_negative",
"SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_server_reboot_soft",
"SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_server_reload",
"SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_update_firmware",
"SoftLayer/tests/managers/hardware_tests.py::HardwareTests::test_cancel_hardware",
"SoftLayer/tests/managers/hardware_tests.py::HardwareTests::test_cancel_hardware_no_billing_item",
"SoftLayer/tests/managers/hardware_tests.py::HardwareTests::test_cancel_hardware_with_reason_and_comment",
"SoftLayer/tests/managers/hardware_tests.py::HardwareTests::test_cancel_hardware_without_reason",
"SoftLayer/tests/managers/hardware_tests.py::HardwareTests::test_change_port_speed_private",
"SoftLayer/tests/managers/hardware_tests.py::HardwareTests::test_change_port_speed_public",
"SoftLayer/tests/managers/hardware_tests.py::HardwareTests::test_edit",
"SoftLayer/tests/managers/hardware_tests.py::HardwareTests::test_edit_blank",
"SoftLayer/tests/managers/hardware_tests.py::HardwareTests::test_edit_meta",
"SoftLayer/tests/managers/hardware_tests.py::HardwareTests::test_generate_create_dict",
"SoftLayer/tests/managers/hardware_tests.py::HardwareTests::test_generate_create_dict_invalid_size",
"SoftLayer/tests/managers/hardware_tests.py::HardwareTests::test_generate_create_dict_no_items",
"SoftLayer/tests/managers/hardware_tests.py::HardwareTests::test_generate_create_dict_no_regions",
"SoftLayer/tests/managers/hardware_tests.py::HardwareTests::test_get_create_options",
"SoftLayer/tests/managers/hardware_tests.py::HardwareTests::test_get_create_options_package_missing",
"SoftLayer/tests/managers/hardware_tests.py::HardwareTests::test_get_hardware",
"SoftLayer/tests/managers/hardware_tests.py::HardwareTests::test_init_with_ordering_manager",
"SoftLayer/tests/managers/hardware_tests.py::HardwareTests::test_list_hardware",
"SoftLayer/tests/managers/hardware_tests.py::HardwareTests::test_list_hardware_with_filters",
"SoftLayer/tests/managers/hardware_tests.py::HardwareTests::test_place_order",
"SoftLayer/tests/managers/hardware_tests.py::HardwareTests::test_reload",
"SoftLayer/tests/managers/hardware_tests.py::HardwareTests::test_rescue",
"SoftLayer/tests/managers/hardware_tests.py::HardwareTests::test_resolve_ids_hostname",
"SoftLayer/tests/managers/hardware_tests.py::HardwareTests::test_resolve_ids_ip",
"SoftLayer/tests/managers/hardware_tests.py::HardwareTests::test_update_firmware",
"SoftLayer/tests/managers/hardware_tests.py::HardwareTests::test_update_firmware_selective",
"SoftLayer/tests/managers/hardware_tests.py::HardwareTests::test_verify_order",
"SoftLayer/tests/managers/hardware_tests.py::HardwareHelperTests::test_get_bandwidth_price_id_no_items",
"SoftLayer/tests/managers/hardware_tests.py::HardwareHelperTests::test_get_default_price_id_item_not_first",
"SoftLayer/tests/managers/hardware_tests.py::HardwareHelperTests::test_get_default_price_id_no_items",
"SoftLayer/tests/managers/hardware_tests.py::HardwareHelperTests::test_get_extra_price_id_no_items",
"SoftLayer/tests/managers/hardware_tests.py::HardwareHelperTests::test_get_os_price_id_no_items",
"SoftLayer/tests/managers/hardware_tests.py::HardwareHelperTests::test_get_port_speed_price_id_no_items"
] | [] | MIT License | 121 |
|
falconry__falcon-540 | 3791b3a1c9e210e2e04a8a57f64561101685ef0e | 2015-05-04 22:59:32 | b78ffaac7c412d3b3d6cd3c70dd05024d79d2cce | diff --git a/falcon/request.py b/falcon/request.py
index b16e154..74915a0 100644
--- a/falcon/request.py
+++ b/falcon/request.py
@@ -599,7 +599,7 @@ class Request(object):
if not required:
return None
- raise HTTPMissingParam(name)
+ raise HTTPMissingHeader(name)
def get_header_as_datetime(self, header, required=False):
"""Return an HTTP header with HTTP-Date values as a datetime.
| Request.get_header raises the wrong exception
Found an issue that is making exception-handling not very intuitive when dealing with required headers...
```
try:
my_header = req.get_header('My-Header', required=True)
except falcon.HTTPMissingHeader:
print 'Missing header'
except falcon.HTTPMissingParam:
print 'Missing param'
# Prints "Missing param"
```
Basically, calling ``get_header()`` with ``required=True`` should raise a ``HTTPMissingHeader`` exception, when actually what gets raised is ``HTTPMissingParam``.
This also leads to confusing error response messages, since the response title and header refer to a missing, required "query parameter" instead of a "header". | falconry/falcon | diff --git a/tests/test_headers.py b/tests/test_headers.py
index f2a689a..654eee9 100644
--- a/tests/test_headers.py
+++ b/tests/test_headers.py
@@ -183,9 +183,14 @@ class TestHeaders(testing.TestBase):
def test_required_header(self):
self.simulate_request(self.test_route)
- self.assertRaises(falcon.HTTPBadRequest,
- self.resource.req.get_header, 'X-Not-Found',
- required=True)
+ try:
+ self.resource.req.get_header('X-Not-Found', required=True)
+ self.fail('falcon.HTTPMissingHeader not raised')
+ except falcon.HTTPMissingHeader as ex:
+ self.assertIsInstance(ex, falcon.HTTPBadRequest)
+ self.assertEqual(ex.title, 'Missing header value')
+ expected_desc = 'The X-Not-Found header is required.'
+ self.assertEqual(ex.description, expected_desc)
def test_no_body_on_100(self):
self.resource = StatusTestResource(falcon.HTTP_100)
diff --git a/tests/test_query_params.py b/tests/test_query_params.py
index 893afda..d6adbf8 100644
--- a/tests/test_query_params.py
+++ b/tests/test_query_params.py
@@ -94,6 +94,7 @@ class _TestQueryParams(testing.TestBase):
getattr(req, method_name)('marker', required=True)
self.fail('falcon.HTTPMissingParam not raised')
except falcon.HTTPMissingParam as ex:
+ self.assertIsInstance(ex, falcon.HTTPBadRequest)
self.assertEqual(ex.title, 'Missing query parameter')
expected_desc = 'The "marker" query parameter is required.'
self.assertEqual(ex.description, expected_desc)
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 0,
"issue_text_score": 0,
"test_score": 3
},
"num_modified_files": 1
} | 0.3 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"nose",
"nose-cov",
"pytest"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.9",
"reqs_path": [
"tools/test-requires"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | certifi==2025.1.31
charset-normalizer==3.4.1
cov-core==1.15.0
coverage==7.8.0
ddt==1.7.2
exceptiongroup==1.2.2
-e git+https://github.com/falconry/falcon.git@3791b3a1c9e210e2e04a8a57f64561101685ef0e#egg=falcon
idna==3.10
iniconfig==2.1.0
nose==1.3.7
nose-cov==1.6
packaging==24.2
pluggy==1.5.0
pytest==8.3.5
python-mimeparse==2.0.0
PyYAML==6.0.2
requests==2.32.3
six==1.17.0
testtools==2.7.2
tomli==2.2.1
urllib3==2.3.0
| name: falcon
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=3.0.16=h5eee18b_0
- pip=25.0=py39h06a4308_0
- python=3.9.21=he870216_1
- readline=8.2=h5eee18b_0
- setuptools=75.8.0=py39h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- tzdata=2025a=h04d1e81_0
- wheel=0.45.1=py39h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- certifi==2025.1.31
- charset-normalizer==3.4.1
- cov-core==1.15.0
- coverage==7.8.0
- ddt==1.7.2
- exceptiongroup==1.2.2
- idna==3.10
- iniconfig==2.1.0
- nose==1.3.7
- nose-cov==1.6
- packaging==24.2
- pluggy==1.5.0
- pytest==8.3.5
- python-mimeparse==2.0.0
- pyyaml==6.0.2
- requests==2.32.3
- six==1.17.0
- testtools==2.7.2
- tomli==2.2.1
- urllib3==2.3.0
prefix: /opt/conda/envs/falcon
| [
"tests/test_headers.py::TestHeaders::test_required_header"
] | [] | [
"tests/test_headers.py::TestHeaders::test_add_link_complex",
"tests/test_headers.py::TestHeaders::test_add_link_multiple",
"tests/test_headers.py::TestHeaders::test_add_link_single",
"tests/test_headers.py::TestHeaders::test_add_link_with_anchor",
"tests/test_headers.py::TestHeaders::test_add_link_with_hreflang",
"tests/test_headers.py::TestHeaders::test_add_link_with_hreflang_multi",
"tests/test_headers.py::TestHeaders::test_add_link_with_title",
"tests/test_headers.py::TestHeaders::test_add_link_with_title_star",
"tests/test_headers.py::TestHeaders::test_add_link_with_type_hint",
"tests/test_headers.py::TestHeaders::test_content_header_missing",
"tests/test_headers.py::TestHeaders::test_content_length",
"tests/test_headers.py::TestHeaders::test_custom_content_type",
"tests/test_headers.py::TestHeaders::test_custom_media_type",
"tests/test_headers.py::TestHeaders::test_default_media_type",
"tests/test_headers.py::TestHeaders::test_default_value",
"tests/test_headers.py::TestHeaders::test_get_raw_headers",
"tests/test_headers.py::TestHeaders::test_no_body_on_100",
"tests/test_headers.py::TestHeaders::test_no_body_on_101",
"tests/test_headers.py::TestHeaders::test_no_body_on_204",
"tests/test_headers.py::TestHeaders::test_no_body_on_304",
"tests/test_headers.py::TestHeaders::test_no_content_type",
"tests/test_headers.py::TestHeaders::test_passthrough_req_headers",
"tests/test_headers.py::TestHeaders::test_passthrough_resp_headers",
"tests/test_headers.py::TestHeaders::test_response_append_header",
"tests/test_headers.py::TestHeaders::test_response_header_helpers_on_get",
"tests/test_headers.py::TestHeaders::test_response_set_header",
"tests/test_headers.py::TestHeaders::test_unicode_location_headers",
"tests/test_headers.py::TestHeaders::test_vary_header",
"tests/test_headers.py::TestHeaders::test_vary_headers",
"tests/test_headers.py::TestHeaders::test_vary_headers_tuple",
"tests/test_headers.py::TestHeaders::test_vary_star",
"tests/test_query_params.py::_TestQueryParams::test_allowed_names",
"tests/test_query_params.py::_TestQueryParams::test_blank",
"tests/test_query_params.py::_TestQueryParams::test_boolean",
"tests/test_query_params.py::_TestQueryParams::test_boolean_blank",
"tests/test_query_params.py::_TestQueryParams::test_get_date_invalid",
"tests/test_query_params.py::_TestQueryParams::test_get_date_missing_param",
"tests/test_query_params.py::_TestQueryParams::test_get_date_store",
"tests/test_query_params.py::_TestQueryParams::test_get_date_valid",
"tests/test_query_params.py::_TestQueryParams::test_get_date_valid_with_format",
"tests/test_query_params.py::_TestQueryParams::test_int",
"tests/test_query_params.py::_TestQueryParams::test_int_neg",
"tests/test_query_params.py::_TestQueryParams::test_list_transformer",
"tests/test_query_params.py::_TestQueryParams::test_list_type",
"tests/test_query_params.py::_TestQueryParams::test_list_type_blank",
"tests/test_query_params.py::_TestQueryParams::test_multiple_form_keys",
"tests/test_query_params.py::_TestQueryParams::test_multiple_form_keys_as_list",
"tests/test_query_params.py::_TestQueryParams::test_multiple_keys_as_bool",
"tests/test_query_params.py::_TestQueryParams::test_multiple_keys_as_int",
"tests/test_query_params.py::_TestQueryParams::test_none",
"tests/test_query_params.py::_TestQueryParams::test_param_property",
"tests/test_query_params.py::_TestQueryParams::test_percent_encoded",
"tests/test_query_params.py::_TestQueryParams::test_required_1_get_param",
"tests/test_query_params.py::_TestQueryParams::test_required_2_get_param_as_int",
"tests/test_query_params.py::_TestQueryParams::test_required_3_get_param_as_bool",
"tests/test_query_params.py::_TestQueryParams::test_required_4_get_param_as_list",
"tests/test_query_params.py::_TestQueryParams::test_simple",
"tests/test_query_params.py::PostQueryParams::test_allowed_names",
"tests/test_query_params.py::PostQueryParams::test_blank",
"tests/test_query_params.py::PostQueryParams::test_boolean",
"tests/test_query_params.py::PostQueryParams::test_boolean_blank",
"tests/test_query_params.py::PostQueryParams::test_get_date_invalid",
"tests/test_query_params.py::PostQueryParams::test_get_date_missing_param",
"tests/test_query_params.py::PostQueryParams::test_get_date_store",
"tests/test_query_params.py::PostQueryParams::test_get_date_valid",
"tests/test_query_params.py::PostQueryParams::test_get_date_valid_with_format",
"tests/test_query_params.py::PostQueryParams::test_int",
"tests/test_query_params.py::PostQueryParams::test_int_neg",
"tests/test_query_params.py::PostQueryParams::test_list_transformer",
"tests/test_query_params.py::PostQueryParams::test_list_type",
"tests/test_query_params.py::PostQueryParams::test_list_type_blank",
"tests/test_query_params.py::PostQueryParams::test_multiple_form_keys",
"tests/test_query_params.py::PostQueryParams::test_multiple_form_keys_as_list",
"tests/test_query_params.py::PostQueryParams::test_multiple_keys_as_bool",
"tests/test_query_params.py::PostQueryParams::test_multiple_keys_as_int",
"tests/test_query_params.py::PostQueryParams::test_non_ascii",
"tests/test_query_params.py::PostQueryParams::test_none",
"tests/test_query_params.py::PostQueryParams::test_param_property",
"tests/test_query_params.py::PostQueryParams::test_percent_encoded",
"tests/test_query_params.py::PostQueryParams::test_required_1_get_param",
"tests/test_query_params.py::PostQueryParams::test_required_2_get_param_as_int",
"tests/test_query_params.py::PostQueryParams::test_required_3_get_param_as_bool",
"tests/test_query_params.py::PostQueryParams::test_required_4_get_param_as_list",
"tests/test_query_params.py::PostQueryParams::test_simple",
"tests/test_query_params.py::GetQueryParams::test_allowed_names",
"tests/test_query_params.py::GetQueryParams::test_blank",
"tests/test_query_params.py::GetQueryParams::test_boolean",
"tests/test_query_params.py::GetQueryParams::test_boolean_blank",
"tests/test_query_params.py::GetQueryParams::test_get_date_invalid",
"tests/test_query_params.py::GetQueryParams::test_get_date_missing_param",
"tests/test_query_params.py::GetQueryParams::test_get_date_store",
"tests/test_query_params.py::GetQueryParams::test_get_date_valid",
"tests/test_query_params.py::GetQueryParams::test_get_date_valid_with_format",
"tests/test_query_params.py::GetQueryParams::test_int",
"tests/test_query_params.py::GetQueryParams::test_int_neg",
"tests/test_query_params.py::GetQueryParams::test_list_transformer",
"tests/test_query_params.py::GetQueryParams::test_list_type",
"tests/test_query_params.py::GetQueryParams::test_list_type_blank",
"tests/test_query_params.py::GetQueryParams::test_multiple_form_keys",
"tests/test_query_params.py::GetQueryParams::test_multiple_form_keys_as_list",
"tests/test_query_params.py::GetQueryParams::test_multiple_keys_as_bool",
"tests/test_query_params.py::GetQueryParams::test_multiple_keys_as_int",
"tests/test_query_params.py::GetQueryParams::test_none",
"tests/test_query_params.py::GetQueryParams::test_param_property",
"tests/test_query_params.py::GetQueryParams::test_percent_encoded",
"tests/test_query_params.py::GetQueryParams::test_required_1_get_param",
"tests/test_query_params.py::GetQueryParams::test_required_2_get_param_as_int",
"tests/test_query_params.py::GetQueryParams::test_required_3_get_param_as_bool",
"tests/test_query_params.py::GetQueryParams::test_required_4_get_param_as_list",
"tests/test_query_params.py::GetQueryParams::test_simple"
] | [] | Apache License 2.0 | 122 |
|
falconry__falcon-541 | 6912cdc1232754f8e8be4bd25ce150f9485012c2 | 2015-05-05 00:11:45 | b78ffaac7c412d3b3d6cd3c70dd05024d79d2cce | diff --git a/doc/api/routing.rst b/doc/api/routing.rst
index b76ba4f..c0ce2d2 100644
--- a/doc/api/routing.rst
+++ b/doc/api/routing.rst
@@ -43,4 +43,4 @@ A custom routing engine may be specified when instantiating
api = API(router=fancy)
.. automodule:: falcon.routing
- :members: create_http_method_map, CompiledRouter
+ :members: create_http_method_map, compile_uri_template, CompiledRouter
diff --git a/falcon/request.py b/falcon/request.py
index 74915a0..b16e154 100644
--- a/falcon/request.py
+++ b/falcon/request.py
@@ -599,7 +599,7 @@ class Request(object):
if not required:
return None
- raise HTTPMissingHeader(name)
+ raise HTTPMissingParam(name)
def get_header_as_datetime(self, header, required=False):
"""Return an HTTP header with HTTP-Date values as a datetime.
diff --git a/falcon/routing/__init__.py b/falcon/routing/__init__.py
index 6498a47..9ced8d6 100644
--- a/falcon/routing/__init__.py
+++ b/falcon/routing/__init__.py
@@ -14,6 +14,7 @@
from falcon.routing.compiled import CompiledRouter
from falcon.routing.util import create_http_method_map # NOQA
+from falcon.routing.util import compile_uri_template # NOQA
DefaultRouter = CompiledRouter
diff --git a/falcon/routing/util.py b/falcon/routing/util.py
index 40625af..e4f258e 100644
--- a/falcon/routing/util.py
+++ b/falcon/routing/util.py
@@ -12,10 +12,72 @@
# See the License for the specific language governing permissions and
# limitations under the License.
+import re
+
+import six
+
from falcon import HTTP_METHODS, responders
from falcon.hooks import _wrap_with_hooks
+# NOTE(kgriffs): Published method; take care to avoid breaking changes.
+def compile_uri_template(template):
+ """Compile the given URI template string into a pattern matcher.
+
+ This function can be used to construct custom routing engines that
+ iterate through a list of possible routes, attempting to match
+ an incoming request against each route's compiled regular expression.
+
+ Each field is converted to a named group, so that when a match
+ is found, the fields can be easily extracted using
+ :py:meth:`re.MatchObject.groupdict`.
+
+ This function does not support the more flexible templating
+ syntax used in the default router. Only simple paths with bracketed
+ field expressions are recognized. For example::
+
+ /
+ /books
+ /books/{isbn}
+ /books/{isbn}/characters
+ /books/{isbn}/characters/{name}
+
+ Also, note that if the template contains a trailing slash character,
+ it will be stripped in order to normalize the routing logic.
+
+ Args:
+ template(str): The template to compile. Note that field names are
+ restricted to ASCII a-z, A-Z, and the underscore character.
+
+ Returns:
+ tuple: (template_field_names, template_regex)
+ """
+
+ if not isinstance(template, six.string_types):
+ raise TypeError('uri_template is not a string')
+
+ if not template.startswith('/'):
+ raise ValueError("uri_template must start with '/'")
+
+ if '//' in template:
+ raise ValueError("uri_template may not contain '//'")
+
+ if template != '/' and template.endswith('/'):
+ template = template[:-1]
+
+ expression_pattern = r'{([a-zA-Z][a-zA-Z_]*)}'
+
+ # Get a list of field names
+ fields = set(re.findall(expression_pattern, template))
+
+ # Convert Level 1 var patterns to equivalent named regex groups
+ escaped = re.sub(r'[\.\(\)\[\]\?\*\+\^\|]', r'\\\g<0>', template)
+ pattern = re.sub(expression_pattern, r'(?P<\1>[^/]+)', escaped)
+ pattern = r'\A' + pattern + r'\Z'
+
+ return fields, re.compile(pattern, re.IGNORECASE)
+
+
def create_http_method_map(resource, before, after):
"""Maps HTTP methods (e.g., 'GET', 'POST') to methods of a resource object.
| Has compile_uri_template been removed?
I can't see it in the code any more. | falconry/falcon | diff --git a/tests/test_headers.py b/tests/test_headers.py
index 654eee9..f2a689a 100644
--- a/tests/test_headers.py
+++ b/tests/test_headers.py
@@ -183,14 +183,9 @@ class TestHeaders(testing.TestBase):
def test_required_header(self):
self.simulate_request(self.test_route)
- try:
- self.resource.req.get_header('X-Not-Found', required=True)
- self.fail('falcon.HTTPMissingHeader not raised')
- except falcon.HTTPMissingHeader as ex:
- self.assertIsInstance(ex, falcon.HTTPBadRequest)
- self.assertEqual(ex.title, 'Missing header value')
- expected_desc = 'The X-Not-Found header is required.'
- self.assertEqual(ex.description, expected_desc)
+ self.assertRaises(falcon.HTTPBadRequest,
+ self.resource.req.get_header, 'X-Not-Found',
+ required=True)
def test_no_body_on_100(self):
self.resource = StatusTestResource(falcon.HTTP_100)
diff --git a/tests/test_query_params.py b/tests/test_query_params.py
index d6adbf8..893afda 100644
--- a/tests/test_query_params.py
+++ b/tests/test_query_params.py
@@ -94,7 +94,6 @@ class _TestQueryParams(testing.TestBase):
getattr(req, method_name)('marker', required=True)
self.fail('falcon.HTTPMissingParam not raised')
except falcon.HTTPMissingParam as ex:
- self.assertIsInstance(ex, falcon.HTTPBadRequest)
self.assertEqual(ex.title, 'Missing query parameter')
expected_desc = 'The "marker" query parameter is required.'
self.assertEqual(ex.description, expected_desc)
diff --git a/tests/test_uri_templates_legacy.py b/tests/test_uri_templates_legacy.py
new file mode 100644
index 0000000..538f4be
--- /dev/null
+++ b/tests/test_uri_templates_legacy.py
@@ -0,0 +1,96 @@
+import ddt
+
+import falcon
+from falcon import routing
+import falcon.testing as testing
+
+
[email protected]
+class TestUriTemplates(testing.TestBase):
+
+ def test_string_type_required(self):
+ self.assertRaises(TypeError, routing.compile_uri_template, 42)
+ self.assertRaises(TypeError, routing.compile_uri_template, falcon.API)
+
+ def test_template_must_start_with_slash(self):
+ self.assertRaises(ValueError, routing.compile_uri_template, 'this')
+ self.assertRaises(ValueError, routing.compile_uri_template, 'this/that')
+
+ def test_template_may_not_contain_double_slash(self):
+ self.assertRaises(ValueError, routing.compile_uri_template, '//')
+ self.assertRaises(ValueError, routing.compile_uri_template, 'a//')
+ self.assertRaises(ValueError, routing.compile_uri_template, '//b')
+ self.assertRaises(ValueError, routing.compile_uri_template, 'a//b')
+ self.assertRaises(ValueError, routing.compile_uri_template, 'a/b//')
+ self.assertRaises(ValueError, routing.compile_uri_template, 'a/b//c')
+
+ def test_root(self):
+ fields, pattern = routing.compile_uri_template('/')
+ self.assertFalse(fields)
+ self.assertFalse(pattern.match('/x'))
+
+ result = pattern.match('/')
+ self.assertTrue(result)
+ self.assertFalse(result.groupdict())
+
+ @ddt.data('/hello', '/hello/world', '/hi/there/how/are/you')
+ def test_no_fields(self, path):
+ fields, pattern = routing.compile_uri_template(path)
+ self.assertFalse(fields)
+ self.assertFalse(pattern.match(path[:-1]))
+
+ result = pattern.match(path)
+ self.assertTrue(result)
+ self.assertFalse(result.groupdict())
+
+ def test_one_field(self):
+ fields, pattern = routing.compile_uri_template('/{name}')
+ self.assertEqual(fields, set(['name']))
+
+ result = pattern.match('/Kelsier')
+ self.assertTrue(result)
+ self.assertEqual(result.groupdict(), {'name': 'Kelsier'})
+
+ fields, pattern = routing.compile_uri_template('/character/{name}')
+ self.assertEqual(fields, set(['name']))
+
+ result = pattern.match('/character/Kelsier')
+ self.assertTrue(result)
+ self.assertEqual(result.groupdict(), {'name': 'Kelsier'})
+
+ fields, pattern = routing.compile_uri_template('/character/{name}/profile')
+ self.assertEqual(fields, set(['name']))
+
+ self.assertFalse(pattern.match('/character'))
+ self.assertFalse(pattern.match('/character/Kelsier'))
+ self.assertFalse(pattern.match('/character/Kelsier/'))
+
+ result = pattern.match('/character/Kelsier/profile')
+ self.assertTrue(result)
+ self.assertEqual(result.groupdict(), {'name': 'Kelsier'})
+
+ @ddt.data('', '/')
+ def test_two_fields(self, postfix):
+ path = '/book/{id}/characters/{name}' + postfix
+ fields, pattern = routing.compile_uri_template(path)
+ self.assertEqual(fields, set(['name', 'id']))
+
+ result = pattern.match('/book/0765350386/characters/Vin')
+ self.assertTrue(result)
+ self.assertEqual(result.groupdict(), {'name': 'Vin', 'id': '0765350386'})
+
+ def test_three_fields(self):
+ fields, pattern = routing.compile_uri_template('/{a}/{b}/x/{c}')
+ self.assertEqual(fields, set('abc'))
+
+ result = pattern.match('/one/2/x/3')
+ self.assertTrue(result)
+ self.assertEqual(result.groupdict(), {'a': 'one', 'b': '2', 'c': '3'})
+
+ def test_malformed_field(self):
+ fields, pattern = routing.compile_uri_template('/{a}/{1b}/x/{c}')
+ self.assertEqual(fields, set('ac'))
+
+ result = pattern.match('/one/{1b}/x/3')
+ self.assertTrue(result)
+ self.assertEqual(result.groupdict(), {'a': 'one', 'c': '3'})
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files",
"has_many_hunks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 2,
"issue_text_score": 2,
"test_score": 2
},
"num_modified_files": 4
} | 0.3 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "pytest",
"pip_packages": [
"nose",
"coverage",
"ddt",
"pyyaml",
"requests",
"testtools",
"pytest"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.7",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | attrs @ file:///croot/attrs_1668696182826/work
certifi @ file:///croot/certifi_1671487769961/work/certifi
charset-normalizer==3.4.1
coverage==7.2.7
ddt==1.7.2
-e git+https://github.com/falconry/falcon.git@6912cdc1232754f8e8be4bd25ce150f9485012c2#egg=falcon
flit_core @ file:///opt/conda/conda-bld/flit-core_1644941570762/work/source/flit_core
idna==3.10
importlib-metadata @ file:///tmp/build/80754af9/importlib-metadata_1648562407465/work
iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work
nose==1.3.7
packaging @ file:///croot/packaging_1671697413597/work
pluggy @ file:///tmp/build/80754af9/pluggy_1648042572264/work
py @ file:///opt/conda/conda-bld/py_1644396412707/work
pytest==7.1.2
python-mimeparse==1.6.0
PyYAML==6.0.1
requests==2.31.0
six==1.17.0
testtools==2.7.1
tomli @ file:///opt/conda/conda-bld/tomli_1657175507142/work
typing_extensions @ file:///croot/typing_extensions_1669924550328/work
urllib3==2.0.7
zipp @ file:///croot/zipp_1672387121353/work
| name: falcon
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- attrs=22.1.0=py37h06a4308_0
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2022.12.7=py37h06a4308_0
- flit-core=3.6.0=pyhd3eb1b0_0
- importlib-metadata=4.11.3=py37h06a4308_0
- importlib_metadata=4.11.3=hd3eb1b0_0
- iniconfig=1.1.1=pyhd3eb1b0_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- packaging=22.0=py37h06a4308_0
- pip=22.3.1=py37h06a4308_0
- pluggy=1.0.0=py37h06a4308_1
- py=1.11.0=pyhd3eb1b0_0
- pytest=7.1.2=py37h06a4308_0
- python=3.7.16=h7a1cb2a_0
- readline=8.2=h5eee18b_0
- setuptools=65.6.3=py37h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- tomli=2.0.1=py37h06a4308_0
- typing_extensions=4.4.0=py37h06a4308_0
- wheel=0.38.4=py37h06a4308_0
- xz=5.6.4=h5eee18b_1
- zipp=3.11.0=py37h06a4308_0
- zlib=1.2.13=h5eee18b_1
- pip:
- charset-normalizer==3.4.1
- coverage==7.2.7
- ddt==1.7.2
- idna==3.10
- nose==1.3.7
- python-mimeparse==1.6.0
- pyyaml==6.0.1
- requests==2.31.0
- six==1.17.0
- testtools==2.7.1
- urllib3==2.0.7
prefix: /opt/conda/envs/falcon
| [
"tests/test_uri_templates_legacy.py::TestUriTemplates::test_malformed_field",
"tests/test_uri_templates_legacy.py::TestUriTemplates::test_no_fields_1__hello",
"tests/test_uri_templates_legacy.py::TestUriTemplates::test_no_fields_2__hello_world",
"tests/test_uri_templates_legacy.py::TestUriTemplates::test_no_fields_3__hi_there_how_are_you",
"tests/test_uri_templates_legacy.py::TestUriTemplates::test_one_field",
"tests/test_uri_templates_legacy.py::TestUriTemplates::test_root",
"tests/test_uri_templates_legacy.py::TestUriTemplates::test_string_type_required",
"tests/test_uri_templates_legacy.py::TestUriTemplates::test_template_may_not_contain_double_slash",
"tests/test_uri_templates_legacy.py::TestUriTemplates::test_template_must_start_with_slash",
"tests/test_uri_templates_legacy.py::TestUriTemplates::test_three_fields",
"tests/test_uri_templates_legacy.py::TestUriTemplates::test_two_fields_1_",
"tests/test_uri_templates_legacy.py::TestUriTemplates::test_two_fields_2__"
] | [] | [
"tests/test_headers.py::TestHeaders::test_add_link_complex",
"tests/test_headers.py::TestHeaders::test_add_link_multiple",
"tests/test_headers.py::TestHeaders::test_add_link_single",
"tests/test_headers.py::TestHeaders::test_add_link_with_anchor",
"tests/test_headers.py::TestHeaders::test_add_link_with_hreflang",
"tests/test_headers.py::TestHeaders::test_add_link_with_hreflang_multi",
"tests/test_headers.py::TestHeaders::test_add_link_with_title",
"tests/test_headers.py::TestHeaders::test_add_link_with_title_star",
"tests/test_headers.py::TestHeaders::test_add_link_with_type_hint",
"tests/test_headers.py::TestHeaders::test_content_header_missing",
"tests/test_headers.py::TestHeaders::test_content_length",
"tests/test_headers.py::TestHeaders::test_custom_content_type",
"tests/test_headers.py::TestHeaders::test_custom_media_type",
"tests/test_headers.py::TestHeaders::test_default_media_type",
"tests/test_headers.py::TestHeaders::test_default_value",
"tests/test_headers.py::TestHeaders::test_get_raw_headers",
"tests/test_headers.py::TestHeaders::test_no_body_on_100",
"tests/test_headers.py::TestHeaders::test_no_body_on_101",
"tests/test_headers.py::TestHeaders::test_no_body_on_204",
"tests/test_headers.py::TestHeaders::test_no_body_on_304",
"tests/test_headers.py::TestHeaders::test_no_content_type",
"tests/test_headers.py::TestHeaders::test_passthrough_req_headers",
"tests/test_headers.py::TestHeaders::test_passthrough_resp_headers",
"tests/test_headers.py::TestHeaders::test_required_header",
"tests/test_headers.py::TestHeaders::test_response_append_header",
"tests/test_headers.py::TestHeaders::test_response_header_helpers_on_get",
"tests/test_headers.py::TestHeaders::test_response_set_header",
"tests/test_headers.py::TestHeaders::test_unicode_location_headers",
"tests/test_headers.py::TestHeaders::test_vary_header",
"tests/test_headers.py::TestHeaders::test_vary_headers",
"tests/test_headers.py::TestHeaders::test_vary_headers_tuple",
"tests/test_headers.py::TestHeaders::test_vary_star",
"tests/test_query_params.py::_TestQueryParams::test_allowed_names",
"tests/test_query_params.py::_TestQueryParams::test_blank",
"tests/test_query_params.py::_TestQueryParams::test_boolean",
"tests/test_query_params.py::_TestQueryParams::test_boolean_blank",
"tests/test_query_params.py::_TestQueryParams::test_get_date_invalid",
"tests/test_query_params.py::_TestQueryParams::test_get_date_missing_param",
"tests/test_query_params.py::_TestQueryParams::test_get_date_store",
"tests/test_query_params.py::_TestQueryParams::test_get_date_valid",
"tests/test_query_params.py::_TestQueryParams::test_get_date_valid_with_format",
"tests/test_query_params.py::_TestQueryParams::test_int",
"tests/test_query_params.py::_TestQueryParams::test_int_neg",
"tests/test_query_params.py::_TestQueryParams::test_list_transformer",
"tests/test_query_params.py::_TestQueryParams::test_list_type",
"tests/test_query_params.py::_TestQueryParams::test_list_type_blank",
"tests/test_query_params.py::_TestQueryParams::test_multiple_form_keys",
"tests/test_query_params.py::_TestQueryParams::test_multiple_form_keys_as_list",
"tests/test_query_params.py::_TestQueryParams::test_multiple_keys_as_bool",
"tests/test_query_params.py::_TestQueryParams::test_multiple_keys_as_int",
"tests/test_query_params.py::_TestQueryParams::test_none",
"tests/test_query_params.py::_TestQueryParams::test_param_property",
"tests/test_query_params.py::_TestQueryParams::test_percent_encoded",
"tests/test_query_params.py::_TestQueryParams::test_required_1_get_param",
"tests/test_query_params.py::_TestQueryParams::test_required_2_get_param_as_int",
"tests/test_query_params.py::_TestQueryParams::test_required_3_get_param_as_bool",
"tests/test_query_params.py::_TestQueryParams::test_required_4_get_param_as_list",
"tests/test_query_params.py::_TestQueryParams::test_simple",
"tests/test_query_params.py::PostQueryParams::test_allowed_names",
"tests/test_query_params.py::PostQueryParams::test_blank",
"tests/test_query_params.py::PostQueryParams::test_boolean",
"tests/test_query_params.py::PostQueryParams::test_boolean_blank",
"tests/test_query_params.py::PostQueryParams::test_get_date_invalid",
"tests/test_query_params.py::PostQueryParams::test_get_date_missing_param",
"tests/test_query_params.py::PostQueryParams::test_get_date_store",
"tests/test_query_params.py::PostQueryParams::test_get_date_valid",
"tests/test_query_params.py::PostQueryParams::test_get_date_valid_with_format",
"tests/test_query_params.py::PostQueryParams::test_int",
"tests/test_query_params.py::PostQueryParams::test_int_neg",
"tests/test_query_params.py::PostQueryParams::test_list_transformer",
"tests/test_query_params.py::PostQueryParams::test_list_type",
"tests/test_query_params.py::PostQueryParams::test_list_type_blank",
"tests/test_query_params.py::PostQueryParams::test_multiple_form_keys",
"tests/test_query_params.py::PostQueryParams::test_multiple_form_keys_as_list",
"tests/test_query_params.py::PostQueryParams::test_multiple_keys_as_bool",
"tests/test_query_params.py::PostQueryParams::test_multiple_keys_as_int",
"tests/test_query_params.py::PostQueryParams::test_non_ascii",
"tests/test_query_params.py::PostQueryParams::test_none",
"tests/test_query_params.py::PostQueryParams::test_param_property",
"tests/test_query_params.py::PostQueryParams::test_percent_encoded",
"tests/test_query_params.py::PostQueryParams::test_required_1_get_param",
"tests/test_query_params.py::PostQueryParams::test_required_2_get_param_as_int",
"tests/test_query_params.py::PostQueryParams::test_required_3_get_param_as_bool",
"tests/test_query_params.py::PostQueryParams::test_required_4_get_param_as_list",
"tests/test_query_params.py::PostQueryParams::test_simple",
"tests/test_query_params.py::GetQueryParams::test_allowed_names",
"tests/test_query_params.py::GetQueryParams::test_blank",
"tests/test_query_params.py::GetQueryParams::test_boolean",
"tests/test_query_params.py::GetQueryParams::test_boolean_blank",
"tests/test_query_params.py::GetQueryParams::test_get_date_invalid",
"tests/test_query_params.py::GetQueryParams::test_get_date_missing_param",
"tests/test_query_params.py::GetQueryParams::test_get_date_store",
"tests/test_query_params.py::GetQueryParams::test_get_date_valid",
"tests/test_query_params.py::GetQueryParams::test_get_date_valid_with_format",
"tests/test_query_params.py::GetQueryParams::test_int",
"tests/test_query_params.py::GetQueryParams::test_int_neg",
"tests/test_query_params.py::GetQueryParams::test_list_transformer",
"tests/test_query_params.py::GetQueryParams::test_list_type",
"tests/test_query_params.py::GetQueryParams::test_list_type_blank",
"tests/test_query_params.py::GetQueryParams::test_multiple_form_keys",
"tests/test_query_params.py::GetQueryParams::test_multiple_form_keys_as_list",
"tests/test_query_params.py::GetQueryParams::test_multiple_keys_as_bool",
"tests/test_query_params.py::GetQueryParams::test_multiple_keys_as_int",
"tests/test_query_params.py::GetQueryParams::test_none",
"tests/test_query_params.py::GetQueryParams::test_param_property",
"tests/test_query_params.py::GetQueryParams::test_percent_encoded",
"tests/test_query_params.py::GetQueryParams::test_required_1_get_param",
"tests/test_query_params.py::GetQueryParams::test_required_2_get_param_as_int",
"tests/test_query_params.py::GetQueryParams::test_required_3_get_param_as_bool",
"tests/test_query_params.py::GetQueryParams::test_required_4_get_param_as_list",
"tests/test_query_params.py::GetQueryParams::test_simple"
] | [] | Apache License 2.0 | 123 |
|
mkdocs__mkdocs-497 | aa7dd95813f49ad187111af387fa3f427720184b | 2015-05-05 05:36:38 | 463c5b647e9ce5992b519708a0b9c4cba891d65c | diff --git a/mkdocs/build.py b/mkdocs/build.py
index 86617977..1bc2c318 100644
--- a/mkdocs/build.py
+++ b/mkdocs/build.py
@@ -10,9 +10,8 @@ from jinja2.exceptions import TemplateNotFound
from six.moves.urllib.parse import urljoin
import jinja2
import json
-import markdown
-from mkdocs import nav, search, toc, utils
+from mkdocs import nav, search, utils
from mkdocs.relative_path_ext import RelativePathExtension
import mkdocs
@@ -39,19 +38,8 @@ def convert_markdown(markdown_source, site_navigation=None, extensions=(), stric
builtin_extensions = ['meta', 'toc', 'tables', 'fenced_code']
mkdocs_extensions = [RelativePathExtension(site_navigation, strict), ]
extensions = utils.reduce_list(builtin_extensions + mkdocs_extensions + user_extensions)
- md = markdown.Markdown(
- extensions=extensions,
- extension_configs=extension_configs
- )
- html_content = md.convert(markdown_source)
-
- # On completely blank markdown files, no Meta or tox properties are added
- # to the generated document.
- meta = getattr(md, 'Meta', {})
- toc_html = getattr(md, 'toc', '')
- # Post process the generated table of contents into a data structure
- table_of_contents = toc.TableOfContents(toc_html)
+ html_content, table_of_contents, meta = utils.convert_markdown(markdown_source, extensions, extension_configs)
return (html_content, table_of_contents, meta)
diff --git a/mkdocs/nav.py b/mkdocs/nav.py
index 1b8c6c48..85d33513 100644
--- a/mkdocs/nav.py
+++ b/mkdocs/nav.py
@@ -15,18 +15,37 @@ from mkdocs import utils, exceptions
log = logging.getLogger(__name__)
-def filename_to_title(filename):
+def file_to_title(filename):
"""
Automatically generate a default title, given a filename.
+
+ The method parses the file to check for a title, uses the filename
+ as a title otherwise.
"""
if utils.is_homepage(filename):
return 'Home'
+ try:
+ with open(filename, 'r') as f:
+ lines = f.read()
+ _, table_of_contents, meta = utils.convert_markdown(lines, ['meta', 'toc'])
+ if "title" in meta:
+ return meta["title"][0]
+ if len(table_of_contents.items) > 0:
+ return table_of_contents.items[0].title
+ except IOError:
+ # File couldn't be found - use filename as the title
+ # this is used in tests. We use the filename as the title
+ # in that case
+ pass
+
+ # No title found in the document, using the filename
title = os.path.splitext(filename)[0]
title = title.replace('-', ' ').replace('_', ' ')
- # Captialize if the filename was all lowercase, otherwise leave it as-is.
+ # Capitalize if the filename was all lowercase, otherwise leave it as-is.
if title.lower() == title:
title = title.capitalize()
+
return title
@@ -220,18 +239,18 @@ def _generate_site_navigation(pages_config, url_context, use_directory_urls=True
# then lets automatically nest it.
if title is None and child_title is None and os.path.sep in path:
filename = path.split(os.path.sep)[-1]
- child_title = filename_to_title(filename)
+ child_title = file_to_title(filename)
if title is None:
filename = path.split(os.path.sep)[0]
- title = filename_to_title(filename)
+ title = file_to_title(filename)
# If we don't have a child title but the other title is the same, we
# should be within a section and the child title needs to be inferred
# from the filename.
if len(nav_items) and title == nav_items[-1].title == title and child_title is None:
filename = path.split(os.path.sep)[-1]
- child_title = filename_to_title(filename)
+ child_title = file_to_title(filename)
url = utils.get_url_path(path, use_directory_urls)
diff --git a/mkdocs/utils.py b/mkdocs/utils.py
index 67e4356d..9149ec09 100644
--- a/mkdocs/utils.py
+++ b/mkdocs/utils.py
@@ -9,9 +9,15 @@ and structure of the site and pages in the site.
import os
import shutil
+import markdown
+import logging
+from mkdocs import toc
from six.moves.urllib.parse import urlparse
from six.moves.urllib.request import pathname2url
+
+log = logging.getLogger(__name__)
+
try:
from collections import OrderedDict
import yaml
@@ -272,6 +278,34 @@ def path_to_url(path):
return pathname2url(path)
+def convert_markdown(markdown_source, extensions=None, extension_configs=None):
+ """
+ Convert the Markdown source file to HTML content, and additionally
+ return the parsed table of contents, and a dictionary of any metadata
+ that was specified in the Markdown file.
+ `extensions` is an optional sequence of Python Markdown extensions to add
+ to the default set.
+ """
+ extensions = extensions or []
+ extension_configs = extension_configs or {}
+
+ md = markdown.Markdown(
+ extensions=extensions,
+ extension_configs=extension_configs
+ )
+ html_content = md.convert(markdown_source)
+
+ # On completely blank markdown files, no Meta or tox properties are added
+ # to the generated document.
+ meta = getattr(md, 'Meta', {})
+ toc_html = getattr(md, 'toc', '')
+
+ # Post process the generated table of contents into a data structure
+ table_of_contents = toc.TableOfContents(toc_html)
+
+ return (html_content, table_of_contents, meta)
+
+
def get_theme_names():
"""Return a list containing all the names of all the builtin themes."""
| If no title is provided in the mkdocs.yml use the title in the markdown file
As per the title, this came up in #308 but it's something I've wanted for a while.
| mkdocs/mkdocs | diff --git a/mkdocs/tests/nav_tests.py b/mkdocs/tests/nav_tests.py
index cdd2bf9f..90fc4469 100644
--- a/mkdocs/tests/nav_tests.py
+++ b/mkdocs/tests/nav_tests.py
@@ -348,3 +348,16 @@ class SiteNavigationTests(unittest.TestCase):
for page, expected_ancestor in zip(site_navigation.pages, ancestors):
self.assertEqual(page.ancestors, expected_ancestor)
+
+ def test_file_to_tile(self):
+ title = nav.file_to_title("mkdocs/tests/resources/empty.md")
+ self.assertEqual(title, "Mkdocs/tests/resources/empty")
+
+ title = nav.file_to_title("mkdocs/tests/resources/with_title.md")
+ self.assertEqual(title, "Title")
+
+ title = nav.file_to_title("mkdocs/tests/resources/title_metadata.md")
+ self.assertEqual(title, "Metadata Title")
+
+ title = nav.file_to_title("mkdocs/tests/resources/no_title_metadata.md")
+ self.assertEqual(title, "Title")
diff --git a/mkdocs/tests/resources/empty.md b/mkdocs/tests/resources/empty.md
new file mode 100644
index 00000000..f208f991
--- /dev/null
+++ b/mkdocs/tests/resources/empty.md
@@ -0,0 +1,1 @@
+There's no title in this file.
diff --git a/mkdocs/tests/resources/no_title_metadata.md b/mkdocs/tests/resources/no_title_metadata.md
new file mode 100644
index 00000000..af50b648
--- /dev/null
+++ b/mkdocs/tests/resources/no_title_metadata.md
@@ -0,0 +1,4 @@
+author: I have no title in metadata
+
+# Title
+
diff --git a/mkdocs/tests/resources/title_metadata.md b/mkdocs/tests/resources/title_metadata.md
new file mode 100644
index 00000000..dd4c6f02
--- /dev/null
+++ b/mkdocs/tests/resources/title_metadata.md
@@ -0,0 +1,4 @@
+title: Metadata Title
+
+# Title
+
diff --git a/mkdocs/tests/resources/with_title.md b/mkdocs/tests/resources/with_title.md
new file mode 100644
index 00000000..e7f1dc2f
--- /dev/null
+++ b/mkdocs/tests/resources/with_title.md
@@ -0,0 +1,2 @@
+# Title
+
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 1,
"issue_text_score": 1,
"test_score": 0
},
"num_modified_files": 3
} | 0.12 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[dev]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest",
"mock"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.9",
"reqs_path": [
"requirements/project.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | click==8.1.8
exceptiongroup==1.2.2
ghp-import==2.1.0
importlib_metadata==8.6.1
iniconfig==2.1.0
Jinja2==3.1.6
livereload==2.7.1
Markdown==3.7
MarkupSafe==3.0.2
-e git+https://github.com/mkdocs/mkdocs.git@aa7dd95813f49ad187111af387fa3f427720184b#egg=mkdocs
mock==5.2.0
packaging==24.2
pluggy==1.5.0
pytest==8.3.5
python-dateutil==2.9.0.post0
PyYAML==6.0.2
six==1.17.0
tomli==2.2.1
tornado==6.4.2
zipp==3.21.0
| name: mkdocs
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=3.0.16=h5eee18b_0
- pip=25.0=py39h06a4308_0
- python=3.9.21=he870216_1
- readline=8.2=h5eee18b_0
- setuptools=75.8.0=py39h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- tzdata=2025a=h04d1e81_0
- wheel=0.45.1=py39h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- click==8.1.8
- exceptiongroup==1.2.2
- ghp-import==2.1.0
- importlib-metadata==8.6.1
- iniconfig==2.1.0
- jinja2==3.1.6
- livereload==2.7.1
- markdown==3.7
- markupsafe==3.0.2
- mock==5.2.0
- packaging==24.2
- pluggy==1.5.0
- pytest==8.3.5
- python-dateutil==2.9.0.post0
- pyyaml==6.0.2
- six==1.17.0
- tomli==2.2.1
- tornado==6.4.2
- zipp==3.21.0
prefix: /opt/conda/envs/mkdocs
| [
"mkdocs/tests/nav_tests.py::SiteNavigationTests::test_file_to_tile"
] | [] | [
"mkdocs/tests/nav_tests.py::SiteNavigationTests::test_ancestors",
"mkdocs/tests/nav_tests.py::SiteNavigationTests::test_base_url",
"mkdocs/tests/nav_tests.py::SiteNavigationTests::test_empty_toc_item",
"mkdocs/tests/nav_tests.py::SiteNavigationTests::test_generate_site_navigation",
"mkdocs/tests/nav_tests.py::SiteNavigationTests::test_generate_site_navigation_windows",
"mkdocs/tests/nav_tests.py::SiteNavigationTests::test_indented_toc",
"mkdocs/tests/nav_tests.py::SiteNavigationTests::test_indented_toc_missing_child_title",
"mkdocs/tests/nav_tests.py::SiteNavigationTests::test_invalid_pages_config",
"mkdocs/tests/nav_tests.py::SiteNavigationTests::test_nested_ungrouped",
"mkdocs/tests/nav_tests.py::SiteNavigationTests::test_nested_ungrouped_no_titles",
"mkdocs/tests/nav_tests.py::SiteNavigationTests::test_nested_ungrouped_no_titles_windows",
"mkdocs/tests/nav_tests.py::SiteNavigationTests::test_relative_md_links_have_slash",
"mkdocs/tests/nav_tests.py::SiteNavigationTests::test_simple_toc",
"mkdocs/tests/nav_tests.py::SiteNavigationTests::test_walk_empty_toc",
"mkdocs/tests/nav_tests.py::SiteNavigationTests::test_walk_indented_toc",
"mkdocs/tests/nav_tests.py::SiteNavigationTests::test_walk_simple_toc"
] | [] | BSD 2-Clause "Simplified" License | 124 |
|
sensiblecodeio__xypath-76 | 2de90e58b881b271a743ae5c60c5e03904d2ef7f | 2015-05-05 12:42:50 | 2de90e58b881b271a743ae5c60c5e03904d2ef7f | diff --git a/.travis.yml b/.travis.yml
index 1e8f611..ea3c474 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -1,6 +1,8 @@
language: python
python:
- "2.7"
+ - "3.4"
+ - "3.5"
# command to install dependencies, e.g. pip install -r requirements.txt --use-mirrors
install:
- pip install setuptools --upgrade # fix for html5lib
diff --git a/Dockerfile b/Dockerfile
new file mode 100644
index 0000000..201d0c7
--- /dev/null
+++ b/Dockerfile
@@ -0,0 +1,24 @@
+FROM ubuntu:16.04
+
+RUN apt-get update && \
+ apt-get install -y \
+ python-pip \
+ python3-pip
+
+RUN locale-gen en_GB.UTF-8
+
+RUN mkdir /home/nobody && \
+ chown nobody /home/nobody
+
+USER nobody
+ENV HOME=/home/nobody \
+ PATH=/home/nobody/.local/bin:$PATH \
+ LANG=en_GB.UTF-8
+# LANG needed for httpretty install on Py3
+
+WORKDIR /home/nobody
+
+RUN pip install --user nose messytables pyhamcrest
+RUN pip3 install --user nose messytables pyhamcrest
+
+COPY . /home/nobody/
diff --git a/Makefile b/Makefile
new file mode 100644
index 0000000..688d376
--- /dev/null
+++ b/Makefile
@@ -0,0 +1,7 @@
+run: build
+ @docker run --rm --tty --interactive xypath
+
+build:
+ @docker build --tag xypath .
+
+.PHONY: run build
diff --git a/requirements.txt b/requirements.txt
index 21c6ad0..f0559e8 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -1,3 +1,3 @@
-messytables==0.15.0
+messytables==0.15.1
nose
coverage
diff --git a/setup.py b/setup.py
index 9d40510..14947e8 100644
--- a/setup.py
+++ b/setup.py
@@ -8,7 +8,7 @@ navigating around and extracting values from tabular data.
setup(
name='xypath',
- version='1.0.12',
+ version='1.1.0',
description="Extract fields from tabular data with complex expressions.",
long_description=long_desc,
classifiers=[
@@ -16,7 +16,10 @@ setup(
"Intended Audience :: Developers",
"License :: OSI Approved :: BSD License",
"Operating System :: POSIX :: Linux",
- "Programming Language :: Python",
+ "Operating System :: Microsoft :: Windows",
+ "Programming Language :: Python 2.7",
+ "Programming Language :: Python 3.4",
+ "Programming Language :: Python 3.5",
],
keywords='',
author='The Sensible Code Company Ltd',
@@ -28,7 +31,7 @@ setup(
include_package_data=False,
zip_safe=False,
install_requires=[
- 'messytables==0.15',
+ 'messytables==0.15.1',
],
tests_require=[],
entry_points=\
diff --git a/xypath/__init__.py b/xypath/__init__.py
index a5b930b..0b1a2c3 100644
--- a/xypath/__init__.py
+++ b/xypath/__init__.py
@@ -1,2 +1,3 @@
-from xypath import *
-import xyzzy
+from __future__ import absolute_import
+from .xypath import *
+from . import xyzzy
diff --git a/xypath/contrib/excel.py b/xypath/contrib/excel.py
index 64399ce..622a989 100644
--- a/xypath/contrib/excel.py
+++ b/xypath/contrib/excel.py
@@ -1,8 +1,12 @@
+from __future__ import absolute_import
+from __future__ import print_function
import sys
from itertools import product
-from ..extern.tabulate import tabulate
+from xypath.extern.tabulate import tabulate
import xypath
import re
+from six.moves import range
+from six.moves import zip
class InvalidExcelReference(Exception):
pass
@@ -96,7 +100,7 @@ def filter_one(self, filter_by):
elif filter_length > 1:
foundmsg = "{}: {}".format(
filter_length,
- filtered.excel_locations(filtered)
+ filtered.excel_locations()
)
return filtered.assert_one(
@@ -126,9 +130,9 @@ def as_list(self, collapse_empty=False, excel_labels=False):
width, height = xmax-xmin+1, ymax-ymin+1
- result = [[None]*width for i in xrange(height)]
+ result = [[None]*width for i in range(height)]
- for x, y in product(xrange(xmin, xmax+1), xrange(ymin, ymax+1)):
+ for x, y in product(range(xmin, xmax+1), range(ymin, ymax+1)):
cell = self.table.get_at(x, y)
result[y-ymin][x-xmin] = cell.value if cell in self else None
@@ -186,6 +190,6 @@ def pprint(self, collapse_empty=False,
row[i] = cell
if excel_labels:
- print >>stream, tabulate(result[1:], headers=result[0])
+ print(tabulate(result[1:], headers=result[0]), file=stream)
else:
- print >>stream, tabulate(result)
+ print(tabulate(result), file=stream)
diff --git a/xypath/extern/tabulate.py b/xypath/extern/tabulate.py
index 6735275..e4cadff 100644
--- a/xypath/extern/tabulate.py
+++ b/xypath/extern/tabulate.py
@@ -31,9 +31,14 @@
from __future__ import print_function
from __future__ import unicode_literals
+from __future__ import absolute_import
from collections import namedtuple
from platform import python_version_tuple
import re
+from six.moves import map
+import six
+from six.moves import range
+from six.moves import zip
if python_version_tuple()[0] < "3":
@@ -41,7 +46,7 @@ if python_version_tuple()[0] < "3":
_none_type = type(None)
_int_type = int
_float_type = float
- _text_type = unicode
+ _text_type = six.text_type
_binary_type = str
else:
from itertools import zip_longest as izip_longest
@@ -345,7 +350,7 @@ def _align_column(strings, alignment, minwidth=0, has_invisible=True):
else:
width_fn = len
- maxwidth = max(max(map(width_fn, strings)), minwidth)
+ maxwidth = max(max(list(map(width_fn, strings))), minwidth)
padded_strings = [padfn(maxwidth, s, has_invisible) for s in strings]
return padded_strings
@@ -432,11 +437,11 @@ def _normalize_tabular_data(tabular_data, headers):
# dict-like and pandas.DataFrame?
if hasattr(tabular_data.values, "__call__"):
# likely a conventional dict
- keys = tabular_data.keys()
- rows = list(izip_longest(*tabular_data.values())) # columns have to be transposed
+ keys = list(tabular_data.keys())
+ rows = list(izip_longest(*list(tabular_data.values()))) # columns have to be transposed
elif hasattr(tabular_data, "index"):
# values is a property, has .index => it's likely a pandas.DataFrame (pandas 0.11.0)
- keys = tabular_data.keys()
+ keys = list(tabular_data.keys())
vals = tabular_data.values # values matrix doesn't need to be transposed
names = tabular_data.index
rows = [[v]+list(row) for v,row in zip(names, vals)]
@@ -450,7 +455,7 @@ def _normalize_tabular_data(tabular_data, headers):
rows = list(tabular_data)
if headers == "keys" and len(rows) > 0: # keys are column indices
- headers = list(map(_text_type, range(len(rows[0]))))
+ headers = list(map(_text_type, list(range(len(rows[0])))))
# take headers from the first row if necessary
if headers == "firstrow" and len(rows) > 0:
diff --git a/xypath/loader.py b/xypath/loader.py
index 6cbc179..ac8a4e2 100644
--- a/xypath/loader.py
+++ b/xypath/loader.py
@@ -1,5 +1,7 @@
+from __future__ import absolute_import
import messytables
-import xypath
+from . import xypath
+import six
def table_set(filename, *args, **kwargs):
"""get all the tables for a single spreadsheet"""
@@ -27,7 +29,7 @@ def get_sheets(mt_tableset, ids):
xy_table.index = table_index
return xy_table
- if isinstance(ids, (int, basestring)) or callable(ids):
+ if isinstance(ids, (int, six.string_types)) or callable(ids):
# it's a single thing, listify it
ids = (ids, )
@@ -38,7 +40,7 @@ def get_sheets(mt_tableset, ids):
elif isinstance(identifier, int):
if identifier == table_index:
yield xy()
- elif isinstance(identifier, basestring):
+ elif isinstance(identifier, six.string_types):
if identifier.strip() == mt_table.name.strip():
yield xy()
elif callable(identifier):
diff --git a/xypath/xypath.py b/xypath/xypath.py
index eb7ffdb..e5ebd76 100755
--- a/xypath/xypath.py
+++ b/xypath/xypath.py
@@ -5,10 +5,14 @@ Everyone agrees that col 2, row 1 is (2,1) which is xy ordered.
This works well with the name.
Remember that the usual iterators (over a list-of-lists)
is outer loop y first."""
+from __future__ import absolute_import
import re
import messytables
import os
+import six
+from six.moves import range
+from six.moves import zip
try:
import hamcrest
have_ham = True
@@ -19,7 +23,7 @@ from collections import defaultdict
from copy import copy
from itertools import product, takewhile
-import contrib.excel
+from xypath.contrib import excel as contrib_excel
UP = (0, -1)
RIGHT = (1, 0)
@@ -30,6 +34,12 @@ DOWN_RIGHT = (1, 1)
UP_LEFT = (-1, -1)
DOWN_LEFT = (-1, 1)
+def cmp(x, y):
+ if x<y:
+ return -1
+ if x>y:
+ return 1
+ return 0
class XYPathError(Exception):
"""Problems with spreadsheet layouts should raise this or a descendant."""
@@ -62,7 +72,7 @@ class NoLookupError(AssertionError, XYPathError):
def describe_filter_method(filter_by):
if callable(filter_by):
return "matching a function called {}".format(filter_by.__name__)
- if isinstance(filter_by, basestring):
+ if isinstance(filter_by, six.string_types):
return "containing the string {!r}".format(filter_by)
if have_ham and isinstance(filter_by, hamcrest.matcher.Matcher):
return "containing "+str(filter_by)
@@ -113,7 +123,7 @@ class _XYCell(object):
(self.value, self.x, self.y)
def __unicode__(self):
- return unicode(self.value)
+ return six.text_type(self.value)
def lookup(self, header_bag, direction, strict=False):
"""
@@ -242,16 +252,16 @@ class _XYCell(object):
class CoreBag(object):
"""Has a collection of _XYCells"""
def pprint(self, *args, **kwargs):
- return contrib.excel.pprint(self, *args, **kwargs)
+ return contrib_excel.pprint(self, *args, **kwargs)
def as_list(self, *args, **kwargs):
- return contrib.excel.as_list(self, *args, **kwargs)
+ return contrib_excel.as_list(self, *args, **kwargs)
def filter_one(self, filter_by):
- return contrib.excel.filter_one(self, filter_by)
+ return contrib_excel.filter_one(self, filter_by)
def excel_locations(self, *args, **kwargs):
- return contrib.excel.excel_locations(self, *args, **kwargs)
+ return contrib_excel.excel_locations(self, *args, **kwargs)
def __init__(self, table):
self.__store = set()
@@ -389,13 +399,13 @@ class CoreBag(object):
"""
if callable(filter_by):
return self._filter_internal(filter_by)
- elif isinstance(filter_by, basestring):
- return self._filter_internal(lambda cell: unicode(cell.value).strip() == filter_by)
+ elif isinstance(filter_by, six.string_types):
+ return self._filter_internal(lambda cell: six.text_type(cell.value).strip() == filter_by)
elif have_ham and isinstance(filter_by, hamcrest.matcher.Matcher):
return self._filter_internal(lambda cell: filter_by.matches(cell.value))
elif isinstance(filter_by, re._pattern_type):
return self._filter_internal(
- lambda cell: re.match(filter_by, unicode(cell.value)))
+ lambda cell: re.match(filter_by, six.text_type(cell.value)))
else:
raise ValueError("filter_by must be function, hamcrest filter, compiled regex or string.")
@@ -646,14 +656,14 @@ class Bag(CoreBag):
"""
if dx < 0:
- dxs = range(0, dx - 1, -1)
+ dxs = list(range(0, dx - 1, -1))
else:
- dxs = range(0, dx + 1, +1)
+ dxs = list(range(0, dx + 1, +1))
if dy < 0:
- dys = range(0, dy - 1, -1)
+ dys = list(range(0, dy - 1, -1))
else:
- dys = range(0, dy + 1, +1)
+ dys = list(range(0, dy + 1, +1))
bag = Bag(table=self.table)
for cell in self.unordered_cells:
@@ -693,7 +703,7 @@ class Bag(CoreBag):
return lambda value: self.filter(lambda cell: not cell.properties[name[:-7]] == value)
if name.endswith("_is"):
return lambda value: self.filter(lambda cell: cell.properties[name[:-3]] == value)
- raise AttributeError, "Bag has no attribute {!r}".format(name)
+ raise AttributeError("Bag has no attribute {!r}".format(name))
class Table(Bag):
@@ -709,6 +719,9 @@ class Table(Bag):
self.sheet = None
self.name = name
+ def __hash__(self):
+ return id(self)
+
def rows(self):
"""Get bags containing each row's cells, in order"""
for row_num in range(0, self._max_y + 1): # inclusive
@@ -720,8 +733,8 @@ class Table(Bag):
yield self._x_index[col_num]
def col(self, column):
- if isinstance(column, basestring):
- c_num = contrib.excel.excel_column_number(column, index=0)
+ if isinstance(column, six.string_types):
+ c_num = contrib_excel.excel_column_number(column, index=0)
return self.col(c_num)
else:
assert isinstance(column, int)
diff --git a/xypath/xyzzy.py b/xypath/xyzzy.py
index 7cbb9d8..4e2b9c6 100755
--- a/xypath/xyzzy.py
+++ b/xypath/xyzzy.py
@@ -1,8 +1,9 @@
+from __future__ import absolute_import
#!/usr/bin/env python
from collections import OrderedDict
from itertools import groupby
-from xypath import Bag
+from .xypath import Bag
class LookupFailureError(Exception):
@@ -36,15 +37,16 @@ def are_distinct(fields):
allbags = set()
bagcount = 0
for field in fields:
- for bag in field.values():
- allbags = allbags.union(bag)
+ for bag in list(field.values()):
+ allbags = allbags.union([cell._cell for cell in bag])
bagcount = bagcount + len(bag)
return len(allbags) == bagcount
def xyzzy(self, fields, valuename='_value'): # XYZZY
- assert are_distinct(fields.values())
- fieldkeys = fields.keys()
+ # assert are_distinct(list(fields.values()))
+ # function fixed: wasn't distinct in first place
+ fieldkeys = list(fields.keys())
assert valuename not in fieldkeys
def fieldlookup(cell):
| Python 3 support
I get this error installing with pip3:
```
Running setup.py install for xypath
File "/usr/local/lib/python3.5/dist-packages/xypath/xypath.py", line 696
raise AttributeError, "Bag has no attribute {!r}".format(name)
^
SyntaxError: invalid syntax
``` | sensiblecodeio/xypath | diff --git a/test/tcore.py b/test/tcore.py
index 7c3b5da..fed0cab 100755
--- a/test/tcore.py
+++ b/test/tcore.py
@@ -1,3 +1,4 @@
+from __future__ import absolute_import
#!/usr/bin/env python
import sys
import unittest
@@ -50,7 +51,7 @@ class TCore(unittest.TestCase):
self.fail('No exception was raised')
except Exception as inst:
self.assertIsInstance(inst, exception_type)
- self.assertEqual(inst.message, msg)
+ self.assertEqual(str(inst), msg)
class TMissing(unittest.TestCase):
@classmethod
diff --git a/test/test_bag.py b/test/test_bag.py
index 8b3c24c..3248ac6 100644
--- a/test/test_bag.py
+++ b/test/test_bag.py
@@ -1,3 +1,4 @@
+from __future__ import absolute_import
#!/usr/bin/env python
import sys
sys.path.append('xypath')
@@ -8,7 +9,7 @@ import unittest
class Test_Bag(tcore.TCore):
def test_bag_from_list(self):
"That Bag.from_list works and table is preserved"
- true_bag = self.table.filter(lambda b: b.value > "F")
+ true_bag = self.table.filter(lambda b: b.x % 2 and b.y % 2)
fake_bag = list(true_bag.table)
self.assertEqual(type(fake_bag), list)
remade_bag = xypath.Bag.from_list(fake_bag)
diff --git a/test/test_contrib.py b/test/test_contrib.py
index aebe68c..5f042ae 100644
--- a/test/test_contrib.py
+++ b/test/test_contrib.py
@@ -1,3 +1,4 @@
+from __future__ import absolute_import
#!/usr/bin/env python
import unittest
import xypath.contrib.excel
diff --git a/test/test_excel.py b/test/test_excel.py
index 5fdbc7d..cbb8870 100644
--- a/test/test_excel.py
+++ b/test/test_excel.py
@@ -1,3 +1,4 @@
+from __future__ import absolute_import
import unittest
from nose.tools import assert_raises, assert_equal
import xypath.contrib.excel as exceltool
diff --git a/test/test_fill.py b/test/test_fill.py
index 0f15fa6..0ef4f20 100644
--- a/test/test_fill.py
+++ b/test/test_fill.py
@@ -1,3 +1,4 @@
+from __future__ import absolute_import
#!/usr/bin/env python
import sys
sys.path.append('xypath')
diff --git a/test/test_filter.py b/test/test_filter.py
index af90609..8b846ed 100644
--- a/test/test_filter.py
+++ b/test/test_filter.py
@@ -1,3 +1,4 @@
+from __future__ import absolute_import
#!/usr/bin/env python
import sys
diff --git a/test/test_filter_one.py b/test/test_filter_one.py
index f3b4445..0d26af1 100644
--- a/test/test_filter_one.py
+++ b/test/test_filter_one.py
@@ -1,3 +1,5 @@
+from __future__ import absolute_import
+from __future__ import print_function
#!/usr/bin/env python
import sys
@@ -26,11 +28,10 @@ class TestFilterOne(tcore.TCore):
try:
self.table.filter_one(re.compile(r'.*Europe.*'))
except xypath.MultipleCellsAssertionError as e:
- pass
+ assert "We expected to find one cell matching the regex '.*Europe.*', but we found 4: " in str(e)
+
+ cells = "C158, C147, C172, C189".split(', ')
+ assert len([cell for cell in cells if cell in str(e)]) >= 3
else:
assert False, "Didn't get a MultipleCellsAssertionError"
- assert "We expected to find one cell matching the regex '.*Europe.*', but we found 4: " in str(e)
- print e
- for cell in "C158, C147, C172, C189".split(', '):
- assert cell in str(e)
diff --git a/test/test_import.py b/test/test_import.py
index 124ffdd..c24208a 100644
--- a/test/test_import.py
+++ b/test/test_import.py
@@ -1,3 +1,4 @@
+from __future__ import absolute_import
#!/usr/bin/env python
import sys
import unittest
diff --git a/test/test_junction.py b/test/test_junction.py
index 6f97ebc..1c5d1f6 100644
--- a/test/test_junction.py
+++ b/test/test_junction.py
@@ -1,3 +1,4 @@
+from __future__ import absolute_import
#!/usr/bin/env python
import sys
sys.path.append('xypath')
diff --git a/test/test_loader.py b/test/test_loader.py
index 0649356..29a8263 100644
--- a/test/test_loader.py
+++ b/test/test_loader.py
@@ -1,3 +1,4 @@
+from __future__ import absolute_import
import unittest
import xypath.loader
from nose.tools import assert_equal
diff --git a/test/test_pprint.py b/test/test_pprint.py
index 8f8190e..22980b8 100644
--- a/test/test_pprint.py
+++ b/test/test_pprint.py
@@ -1,7 +1,8 @@
+from __future__ import absolute_import
import tcore
import xypath
from textwrap import dedent
-from cStringIO import StringIO
+from io import StringIO
class TestPPrint(tcore.TCore):
diff --git a/test/test_table.py b/test/test_table.py
index ec21e5d..82d2549 100644
--- a/test/test_table.py
+++ b/test/test_table.py
@@ -1,3 +1,4 @@
+from __future__ import absolute_import
#!/usr/bin/env python
import sys
sys.path.append('xypath')
diff --git a/test/test_xycell.py b/test/test_xycell.py
index 31386b0..923806e 100644
--- a/test/test_xycell.py
+++ b/test/test_xycell.py
@@ -1,3 +1,5 @@
+from __future__ import absolute_import
+from __future__ import print_function
import tcore
import xypath.xypath as xypath # no privacy
@@ -12,7 +14,7 @@ class Test_Lookup(unittest.TestCase):
cls.messy, cls.table = tcore.get_messytables_fixture(cls.wpp_filename)
def test_cell_lookup(self):
- print self.table
+ print(self.table)
v = self.table.filter("V")._cell
a = self.table.filter("A")
b = self.table.filter("B")
diff --git a/test/test_xyzzy.py b/test/test_xyzzy.py
index f7f3bbb..9909bf5 100644
--- a/test/test_xyzzy.py
+++ b/test/test_xyzzy.py
@@ -1,3 +1,4 @@
+from __future__ import absolute_import
import xypath
import xypath.xyzzy
from collections import OrderedDict
@@ -46,5 +47,7 @@ def xtract_by_numbers(table, rows, columns):
def test_xyzzy_kinda_works():
things = xtract_by_numbers(xy, dimensions_horizontal, dimensions_vertical)
- sorted_things = [thing.values() for thing in sorted(things)]
- assert sorted_things == output
+
+ unsorted_things = [list(thing.values()) for thing in things]
+ sorted_things = sorted(unsorted_things)
+ assert sorted_things == output, sorted_things
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_short_problem_statement",
"has_added_files",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 3,
"issue_text_score": 2,
"test_score": 0
},
"num_modified_files": 9
} | 1.0 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest"
],
"pre_install": null,
"python": "3.9",
"reqs_path": [
"requirements.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | certifi==2025.1.31
chardet==5.2.0
charset-normalizer==3.4.1
coverage==7.8.0
exceptiongroup==1.2.2
html5lib==1.1
idna==3.10
iniconfig==2.1.0
json-table-schema==0.2.1
lxml==5.3.1
messytables==0.15.0
nose==1.3.7
packaging==24.2
pluggy==1.5.0
pytest==8.3.5
python-dateutil==2.9.0.post0
python-magic==0.4.27
requests==2.32.3
six==1.17.0
tomli==2.2.1
urllib3==2.3.0
webencodings==0.5.1
xlrd==2.0.1
-e git+https://github.com/sensiblecodeio/xypath.git@2de90e58b881b271a743ae5c60c5e03904d2ef7f#egg=xypath
| name: xypath
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=3.0.16=h5eee18b_0
- pip=25.0=py39h06a4308_0
- python=3.9.21=he870216_1
- readline=8.2=h5eee18b_0
- setuptools=75.8.0=py39h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- tzdata=2025a=h04d1e81_0
- wheel=0.45.1=py39h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- certifi==2025.1.31
- chardet==5.2.0
- charset-normalizer==3.4.1
- coverage==7.8.0
- exceptiongroup==1.2.2
- html5lib==1.1
- idna==3.10
- iniconfig==2.1.0
- json-table-schema==0.2.1
- lxml==5.3.1
- messytables==0.15.0
- nose==1.3.7
- packaging==24.2
- pluggy==1.5.0
- pytest==8.3.5
- python-dateutil==2.9.0.post0
- python-magic==0.4.27
- requests==2.32.3
- six==1.17.0
- tomli==2.2.1
- urllib3==2.3.0
- webencodings==0.5.1
- xlrd==2.0.1
prefix: /opt/conda/envs/xypath
| [
"test/test_contrib.py::Test_Contrib::test_excel_address_coordinate",
"test/test_contrib.py::Test_Contrib::test_excel_nums",
"test/test_excel.py::Test_Loader::test_col_label",
"test/test_excel.py::Test_Loader::test_excel_address",
"test/test_excel.py::Test_Loader::test_excel_col",
"test/test_excel.py::Test_Loader::test_invalid_excel_address",
"test/test_xycell.py::XYCellTests::test_cell_copy",
"test/test_xycell.py::XYCellTests::test_cell_equality",
"test/test_xycell.py::XYCellTests::test_cell_identity",
"test/test_xycell.py::XYCellTests::test_cell_identity_not_equal_different_tables",
"test/test_xycell.py::XYCellTests::test_cell_identity_not_equal_different_x",
"test/test_xycell.py::XYCellTests::test_cell_identity_not_equal_different_y",
"test/test_xycell.py::XYCellTests::test_cell_shift_takes_tuples",
"test/test_xyzzy.py::test_xyzzy_kinda_works"
] | [
"test/test_loader.py::Test_Loader::test_foo"
] | [] | [] | BSD 2-Clause "Simplified" License | 125 |
|
box__box-python-sdk-46 | 221ef994e215b78b4049847db9656fcc83d10d79 | 2015-05-05 20:17:27 | 221ef994e215b78b4049847db9656fcc83d10d79 | diff --git a/HISTORY.rst b/HISTORY.rst
index b38b2b1..c2dfaf0 100644
--- a/HISTORY.rst
+++ b/HISTORY.rst
@@ -3,6 +3,13 @@
Release History
---------------
+Upcoming
+++++++++
+
+- Added support for setting shared link expiration dates.
+- Added support for setting shared link permissions.
+
+
1.1.6 (2015-04-17)
++++++++++++++++++
@@ -19,13 +26,6 @@ Release History
- Added support to the search endpoint for metadata filters.
- Added support to the search endpoint for filtering based on result type and content types.
-1.1.3 (2015-03-26)
-++++++++++++++++++
-
-- Added support for the /shared_items endpoint. `client.get_shared_item` can be used to get information about
- a shared link. See https://developers.box.com/docs/#shared-items
-
-
1.1.3 (2015-03-26)
++++++++++++++++++
diff --git a/boxsdk/object/item.py b/boxsdk/object/item.py
index e507e86..26fb391 100644
--- a/boxsdk/object/item.py
+++ b/boxsdk/object/item.py
@@ -159,7 +159,7 @@ def move(self, parent_folder):
}
return self.update_info(data)
- def get_shared_link(self, access=None, etag=None):
+ def get_shared_link(self, access=None, etag=None, unshared_at=None, allow_download=None, allow_preview=None):
"""Get a shared link for the item with the given access permissions.
:param access:
@@ -171,6 +171,21 @@ def get_shared_link(self, access=None, etag=None):
If specified, instruct the Box API to create the link only if the current version's etag matches.
:type etag:
`unicode` or None
+ :param unshared_at:
+ The date on which this link should be disabled. May only be set if the current user is not a free user
+ and has permission to set expiration dates.
+ :type unshared_at:
+ :class:`datetime.date` or None
+ :param allow_download:
+ Whether or not the item being shared can be downloaded when accessed via the shared link.
+ If this parameter is None, the default setting will be used.
+ :type allow_download:
+ `bool` or None
+ :param allow_preview:
+ Whether or not the item being shared can be previewed when accessed via the shared link.
+ If this parameter is None, the default setting will be used.
+ :type allow_preview:
+ `bool` or None
:returns:
The URL of the shared link.
:rtype:
@@ -182,6 +197,17 @@ def get_shared_link(self, access=None, etag=None):
'access': access
}
}
+
+ if unshared_at is not None:
+ data['shared_link']['unshared_at'] = unshared_at.isoformat()
+
+ if allow_download is not None or allow_preview is not None:
+ data['shared_link']['permissions'] = permissions = {}
+ if allow_download is not None:
+ permissions['can_download'] = allow_download
+ if allow_preview is not None:
+ permissions['can_preview'] = allow_preview
+
item = self.update_info(data, etag=etag)
return item.shared_link['url']
diff --git a/tox.ini b/tox.ini
index 211ff3d..8eb5920 100644
--- a/tox.ini
+++ b/tox.ini
@@ -28,6 +28,7 @@ deps =
commands =
rst2html.py --strict README.rst
rst2html.py --strict HISTORY.rst
+ rst2html.py --strict CONTRIBUTING.rst
[testenv:pep8]
commands =
| Add ability to set expiration date on shared links
`get_shared_link()` only takes access and etag as parameters. The create shared link API supports many other parameters, including unshared_at, permissions, can_download, can_preview.
https://box-content.readme.io/#page-create-a-shared-link-for-a-file | box/box-python-sdk | diff --git a/test/unit/object/test_item.py b/test/unit/object/test_item.py
index 1bfa2f1..32721fc 100644
--- a/test/unit/object/test_item.py
+++ b/test/unit/object/test_item.py
@@ -1,6 +1,7 @@
# coding: utf-8
from __future__ import unicode_literals
+from datetime import date
import json
import pytest
@@ -55,12 +56,33 @@ def test_move_item(test_item_and_response, mock_box_session, test_folder, mock_o
assert isinstance(move_response, test_item.__class__)
[email protected]('access,expected_access_data', [(None, {}), ('open', {'access': 'open'})])
[email protected](params=(True, False, None))
+def shared_link_can_download(request):
+ return request.param
+
+
[email protected](params=(True, False, None))
+def shared_link_can_preview(request):
+ return request.param
+
+
[email protected](params=('open', None))
+def shared_link_access(request):
+ return request.param
+
+
[email protected](params=(date(2015, 5, 5), None))
+def shared_link_unshared_at(request):
+ return request.param
+
+
def test_get_shared_link(
test_item_and_response,
mock_box_session,
- access,
- expected_access_data,
+ shared_link_access,
+ shared_link_unshared_at,
+ shared_link_can_download,
+ shared_link_can_preview,
test_url,
etag,
if_match_header,
@@ -69,10 +91,27 @@ def test_get_shared_link(
test_item, _ = test_item_and_response
expected_url = test_item.get_url()
mock_box_session.put.return_value.json.return_value = {'shared_link': {'url': test_url}}
- url = test_item.get_shared_link(access, etag=etag)
+ expected_data = {'shared_link': {}}
+ if shared_link_access is not None:
+ expected_data['shared_link']['access'] = shared_link_access
+ if shared_link_unshared_at is not None:
+ expected_data['shared_link']['unshared_at'] = shared_link_unshared_at.isoformat()
+ if shared_link_can_download is not None or shared_link_can_preview is not None:
+ expected_data['shared_link']['permissions'] = permissions = {}
+ if shared_link_can_download is not None:
+ permissions['can_download'] = shared_link_can_download
+ if shared_link_can_preview is not None:
+ permissions['can_preview'] = shared_link_can_preview
+ url = test_item.get_shared_link(
+ etag=etag,
+ access=shared_link_access,
+ unshared_at=shared_link_unshared_at,
+ allow_download=shared_link_can_download,
+ allow_preview=shared_link_can_preview,
+ )
mock_box_session.put.assert_called_once_with(
expected_url,
- data=json.dumps({'shared_link': expected_access_data}),
+ data=json.dumps(expected_data),
headers=if_match_header,
params=None,
)
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_short_problem_statement",
"has_hyperlinks",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 1,
"issue_text_score": 1,
"test_score": 2
},
"num_modified_files": 3
} | 1.1 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[dev]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest",
"pytest-xdist",
"mock",
"sqlalchemy",
"bottle"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.9",
"reqs_path": [
"requirements.txt",
"requirements-dev.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | alabaster==0.7.16
astroid==3.3.9
babel==2.17.0
bottle==0.13.2
-e git+https://github.com/box/box-python-sdk.git@221ef994e215b78b4049847db9656fcc83d10d79#egg=boxsdk
cachetools==5.5.2
certifi==2025.1.31
chardet==5.2.0
charset-normalizer==3.4.1
colorama==0.4.6
coverage==7.8.0
dill==0.3.9
distlib==0.3.9
docutils==0.21.2
enum34==1.1.10
exceptiongroup==1.2.2
execnet==2.1.1
filelock==3.18.0
greenlet==3.1.1
idna==3.10
imagesize==1.4.1
importlib_metadata==8.6.1
iniconfig==2.1.0
isort==6.0.1
Jinja2==3.1.6
jsonpatch==1.33
jsonpointer==3.0.0
MarkupSafe==3.0.2
mccabe==0.7.0
mock==5.2.0
ordereddict==1.1
packaging==24.2
pep8==1.7.1
platformdirs==4.3.7
pluggy==1.5.0
Pygments==2.19.1
pylint==3.3.6
pyproject-api==1.9.0
pytest==8.3.5
pytest-cov==6.0.0
pytest-xdist==3.6.1
requests==2.32.3
six==1.17.0
snowballstemmer==2.2.0
Sphinx==7.4.7
sphinxcontrib-applehelp==2.0.0
sphinxcontrib-devhelp==2.0.0
sphinxcontrib-htmlhelp==2.1.0
sphinxcontrib-jsmath==1.0.1
sphinxcontrib-qthelp==2.0.0
sphinxcontrib-serializinghtml==2.0.0
SQLAlchemy==2.0.40
tomli==2.2.1
tomlkit==0.13.2
tox==4.25.0
typing_extensions==4.13.0
urllib3==2.3.0
virtualenv==20.29.3
zipp==3.21.0
| name: box-python-sdk
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=3.0.16=h5eee18b_0
- pip=25.0=py39h06a4308_0
- python=3.9.21=he870216_1
- readline=8.2=h5eee18b_0
- setuptools=75.8.0=py39h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- tzdata=2025a=h04d1e81_0
- wheel=0.45.1=py39h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- alabaster==0.7.16
- astroid==3.3.9
- babel==2.17.0
- bottle==0.13.2
- cachetools==5.5.2
- certifi==2025.1.31
- chardet==5.2.0
- charset-normalizer==3.4.1
- colorama==0.4.6
- coverage==7.8.0
- dill==0.3.9
- distlib==0.3.9
- docutils==0.21.2
- enum34==1.1.10
- exceptiongroup==1.2.2
- execnet==2.1.1
- filelock==3.18.0
- greenlet==3.1.1
- idna==3.10
- imagesize==1.4.1
- importlib-metadata==8.6.1
- iniconfig==2.1.0
- isort==6.0.1
- jinja2==3.1.6
- jsonpatch==1.33
- jsonpointer==3.0.0
- markupsafe==3.0.2
- mccabe==0.7.0
- mock==5.2.0
- ordereddict==1.1
- packaging==24.2
- pep8==1.7.1
- platformdirs==4.3.7
- pluggy==1.5.0
- pygments==2.19.1
- pylint==3.3.6
- pyproject-api==1.9.0
- pytest==8.3.5
- pytest-cov==6.0.0
- pytest-xdist==3.6.1
- requests==2.32.3
- six==1.17.0
- snowballstemmer==2.2.0
- sphinx==7.4.7
- sphinxcontrib-applehelp==2.0.0
- sphinxcontrib-devhelp==2.0.0
- sphinxcontrib-htmlhelp==2.1.0
- sphinxcontrib-jsmath==1.0.1
- sphinxcontrib-qthelp==2.0.0
- sphinxcontrib-serializinghtml==2.0.0
- sqlalchemy==2.0.40
- tomli==2.2.1
- tomlkit==0.13.2
- tox==4.25.0
- typing-extensions==4.13.0
- urllib3==2.3.0
- virtualenv==20.29.3
- zipp==3.21.0
prefix: /opt/conda/envs/box-python-sdk
| [
"test/unit/object/test_item.py::test_get_shared_link[file-open-shared_link_unshared_at0-True-True-None]",
"test/unit/object/test_item.py::test_get_shared_link[file-open-shared_link_unshared_at0-True-True-etag]",
"test/unit/object/test_item.py::test_get_shared_link[file-open-shared_link_unshared_at0-True-False-None]",
"test/unit/object/test_item.py::test_get_shared_link[file-open-shared_link_unshared_at0-True-False-etag]",
"test/unit/object/test_item.py::test_get_shared_link[file-open-shared_link_unshared_at0-True-None-None]",
"test/unit/object/test_item.py::test_get_shared_link[file-open-shared_link_unshared_at0-True-None-etag]",
"test/unit/object/test_item.py::test_get_shared_link[file-open-shared_link_unshared_at0-False-True-None]",
"test/unit/object/test_item.py::test_get_shared_link[file-open-shared_link_unshared_at0-False-True-etag]",
"test/unit/object/test_item.py::test_get_shared_link[file-open-shared_link_unshared_at0-False-False-None]",
"test/unit/object/test_item.py::test_get_shared_link[file-open-shared_link_unshared_at0-False-False-etag]",
"test/unit/object/test_item.py::test_get_shared_link[file-open-shared_link_unshared_at0-False-None-None]",
"test/unit/object/test_item.py::test_get_shared_link[file-open-shared_link_unshared_at0-False-None-etag]",
"test/unit/object/test_item.py::test_get_shared_link[file-open-shared_link_unshared_at0-None-True-None]",
"test/unit/object/test_item.py::test_get_shared_link[file-open-shared_link_unshared_at0-None-True-etag]",
"test/unit/object/test_item.py::test_get_shared_link[file-open-shared_link_unshared_at0-None-False-None]",
"test/unit/object/test_item.py::test_get_shared_link[file-open-shared_link_unshared_at0-None-False-etag]",
"test/unit/object/test_item.py::test_get_shared_link[file-open-shared_link_unshared_at0-None-None-None]",
"test/unit/object/test_item.py::test_get_shared_link[file-open-shared_link_unshared_at0-None-None-etag]",
"test/unit/object/test_item.py::test_get_shared_link[file-open-None-True-True-None]",
"test/unit/object/test_item.py::test_get_shared_link[file-open-None-True-True-etag]",
"test/unit/object/test_item.py::test_get_shared_link[file-open-None-True-False-None]",
"test/unit/object/test_item.py::test_get_shared_link[file-open-None-True-False-etag]",
"test/unit/object/test_item.py::test_get_shared_link[file-open-None-True-None-None]",
"test/unit/object/test_item.py::test_get_shared_link[file-open-None-True-None-etag]",
"test/unit/object/test_item.py::test_get_shared_link[file-open-None-False-True-None]",
"test/unit/object/test_item.py::test_get_shared_link[file-open-None-False-True-etag]",
"test/unit/object/test_item.py::test_get_shared_link[file-open-None-False-False-None]",
"test/unit/object/test_item.py::test_get_shared_link[file-open-None-False-False-etag]",
"test/unit/object/test_item.py::test_get_shared_link[file-open-None-False-None-None]",
"test/unit/object/test_item.py::test_get_shared_link[file-open-None-False-None-etag]",
"test/unit/object/test_item.py::test_get_shared_link[file-open-None-None-True-None]",
"test/unit/object/test_item.py::test_get_shared_link[file-open-None-None-True-etag]",
"test/unit/object/test_item.py::test_get_shared_link[file-open-None-None-False-None]",
"test/unit/object/test_item.py::test_get_shared_link[file-open-None-None-False-etag]",
"test/unit/object/test_item.py::test_get_shared_link[file-open-None-None-None-None]",
"test/unit/object/test_item.py::test_get_shared_link[file-open-None-None-None-etag]",
"test/unit/object/test_item.py::test_get_shared_link[file-None-shared_link_unshared_at0-True-True-None]",
"test/unit/object/test_item.py::test_get_shared_link[file-None-shared_link_unshared_at0-True-True-etag]",
"test/unit/object/test_item.py::test_get_shared_link[file-None-shared_link_unshared_at0-True-False-None]",
"test/unit/object/test_item.py::test_get_shared_link[file-None-shared_link_unshared_at0-True-False-etag]",
"test/unit/object/test_item.py::test_get_shared_link[file-None-shared_link_unshared_at0-True-None-None]",
"test/unit/object/test_item.py::test_get_shared_link[file-None-shared_link_unshared_at0-True-None-etag]",
"test/unit/object/test_item.py::test_get_shared_link[file-None-shared_link_unshared_at0-False-True-None]",
"test/unit/object/test_item.py::test_get_shared_link[file-None-shared_link_unshared_at0-False-True-etag]",
"test/unit/object/test_item.py::test_get_shared_link[file-None-shared_link_unshared_at0-False-False-None]",
"test/unit/object/test_item.py::test_get_shared_link[file-None-shared_link_unshared_at0-False-False-etag]",
"test/unit/object/test_item.py::test_get_shared_link[file-None-shared_link_unshared_at0-False-None-None]",
"test/unit/object/test_item.py::test_get_shared_link[file-None-shared_link_unshared_at0-False-None-etag]",
"test/unit/object/test_item.py::test_get_shared_link[file-None-shared_link_unshared_at0-None-True-None]",
"test/unit/object/test_item.py::test_get_shared_link[file-None-shared_link_unshared_at0-None-True-etag]",
"test/unit/object/test_item.py::test_get_shared_link[file-None-shared_link_unshared_at0-None-False-None]",
"test/unit/object/test_item.py::test_get_shared_link[file-None-shared_link_unshared_at0-None-False-etag]",
"test/unit/object/test_item.py::test_get_shared_link[file-None-shared_link_unshared_at0-None-None-None]",
"test/unit/object/test_item.py::test_get_shared_link[file-None-shared_link_unshared_at0-None-None-etag]",
"test/unit/object/test_item.py::test_get_shared_link[file-None-None-True-True-None]",
"test/unit/object/test_item.py::test_get_shared_link[file-None-None-True-True-etag]",
"test/unit/object/test_item.py::test_get_shared_link[file-None-None-True-False-None]",
"test/unit/object/test_item.py::test_get_shared_link[file-None-None-True-False-etag]",
"test/unit/object/test_item.py::test_get_shared_link[file-None-None-True-None-None]",
"test/unit/object/test_item.py::test_get_shared_link[file-None-None-True-None-etag]",
"test/unit/object/test_item.py::test_get_shared_link[file-None-None-False-True-None]",
"test/unit/object/test_item.py::test_get_shared_link[file-None-None-False-True-etag]",
"test/unit/object/test_item.py::test_get_shared_link[file-None-None-False-False-None]",
"test/unit/object/test_item.py::test_get_shared_link[file-None-None-False-False-etag]",
"test/unit/object/test_item.py::test_get_shared_link[file-None-None-False-None-None]",
"test/unit/object/test_item.py::test_get_shared_link[file-None-None-False-None-etag]",
"test/unit/object/test_item.py::test_get_shared_link[file-None-None-None-True-None]",
"test/unit/object/test_item.py::test_get_shared_link[file-None-None-None-True-etag]",
"test/unit/object/test_item.py::test_get_shared_link[file-None-None-None-False-None]",
"test/unit/object/test_item.py::test_get_shared_link[file-None-None-None-False-etag]",
"test/unit/object/test_item.py::test_get_shared_link[file-None-None-None-None-None]",
"test/unit/object/test_item.py::test_get_shared_link[file-None-None-None-None-etag]",
"test/unit/object/test_item.py::test_get_shared_link[folder-open-shared_link_unshared_at0-True-True-None]",
"test/unit/object/test_item.py::test_get_shared_link[folder-open-shared_link_unshared_at0-True-True-etag]",
"test/unit/object/test_item.py::test_get_shared_link[folder-open-shared_link_unshared_at0-True-False-None]",
"test/unit/object/test_item.py::test_get_shared_link[folder-open-shared_link_unshared_at0-True-False-etag]",
"test/unit/object/test_item.py::test_get_shared_link[folder-open-shared_link_unshared_at0-True-None-None]",
"test/unit/object/test_item.py::test_get_shared_link[folder-open-shared_link_unshared_at0-True-None-etag]",
"test/unit/object/test_item.py::test_get_shared_link[folder-open-shared_link_unshared_at0-False-True-None]",
"test/unit/object/test_item.py::test_get_shared_link[folder-open-shared_link_unshared_at0-False-True-etag]",
"test/unit/object/test_item.py::test_get_shared_link[folder-open-shared_link_unshared_at0-False-False-None]",
"test/unit/object/test_item.py::test_get_shared_link[folder-open-shared_link_unshared_at0-False-False-etag]",
"test/unit/object/test_item.py::test_get_shared_link[folder-open-shared_link_unshared_at0-False-None-None]",
"test/unit/object/test_item.py::test_get_shared_link[folder-open-shared_link_unshared_at0-False-None-etag]",
"test/unit/object/test_item.py::test_get_shared_link[folder-open-shared_link_unshared_at0-None-True-None]",
"test/unit/object/test_item.py::test_get_shared_link[folder-open-shared_link_unshared_at0-None-True-etag]",
"test/unit/object/test_item.py::test_get_shared_link[folder-open-shared_link_unshared_at0-None-False-None]",
"test/unit/object/test_item.py::test_get_shared_link[folder-open-shared_link_unshared_at0-None-False-etag]",
"test/unit/object/test_item.py::test_get_shared_link[folder-open-shared_link_unshared_at0-None-None-None]",
"test/unit/object/test_item.py::test_get_shared_link[folder-open-shared_link_unshared_at0-None-None-etag]",
"test/unit/object/test_item.py::test_get_shared_link[folder-open-None-True-True-None]",
"test/unit/object/test_item.py::test_get_shared_link[folder-open-None-True-True-etag]",
"test/unit/object/test_item.py::test_get_shared_link[folder-open-None-True-False-None]",
"test/unit/object/test_item.py::test_get_shared_link[folder-open-None-True-False-etag]",
"test/unit/object/test_item.py::test_get_shared_link[folder-open-None-True-None-None]",
"test/unit/object/test_item.py::test_get_shared_link[folder-open-None-True-None-etag]",
"test/unit/object/test_item.py::test_get_shared_link[folder-open-None-False-True-None]",
"test/unit/object/test_item.py::test_get_shared_link[folder-open-None-False-True-etag]",
"test/unit/object/test_item.py::test_get_shared_link[folder-open-None-False-False-None]",
"test/unit/object/test_item.py::test_get_shared_link[folder-open-None-False-False-etag]",
"test/unit/object/test_item.py::test_get_shared_link[folder-open-None-False-None-None]",
"test/unit/object/test_item.py::test_get_shared_link[folder-open-None-False-None-etag]",
"test/unit/object/test_item.py::test_get_shared_link[folder-open-None-None-True-None]",
"test/unit/object/test_item.py::test_get_shared_link[folder-open-None-None-True-etag]",
"test/unit/object/test_item.py::test_get_shared_link[folder-open-None-None-False-None]",
"test/unit/object/test_item.py::test_get_shared_link[folder-open-None-None-False-etag]",
"test/unit/object/test_item.py::test_get_shared_link[folder-open-None-None-None-None]",
"test/unit/object/test_item.py::test_get_shared_link[folder-open-None-None-None-etag]",
"test/unit/object/test_item.py::test_get_shared_link[folder-None-shared_link_unshared_at0-True-True-None]",
"test/unit/object/test_item.py::test_get_shared_link[folder-None-shared_link_unshared_at0-True-True-etag]",
"test/unit/object/test_item.py::test_get_shared_link[folder-None-shared_link_unshared_at0-True-False-None]",
"test/unit/object/test_item.py::test_get_shared_link[folder-None-shared_link_unshared_at0-True-False-etag]",
"test/unit/object/test_item.py::test_get_shared_link[folder-None-shared_link_unshared_at0-True-None-None]",
"test/unit/object/test_item.py::test_get_shared_link[folder-None-shared_link_unshared_at0-True-None-etag]",
"test/unit/object/test_item.py::test_get_shared_link[folder-None-shared_link_unshared_at0-False-True-None]",
"test/unit/object/test_item.py::test_get_shared_link[folder-None-shared_link_unshared_at0-False-True-etag]",
"test/unit/object/test_item.py::test_get_shared_link[folder-None-shared_link_unshared_at0-False-False-None]",
"test/unit/object/test_item.py::test_get_shared_link[folder-None-shared_link_unshared_at0-False-False-etag]",
"test/unit/object/test_item.py::test_get_shared_link[folder-None-shared_link_unshared_at0-False-None-None]",
"test/unit/object/test_item.py::test_get_shared_link[folder-None-shared_link_unshared_at0-False-None-etag]",
"test/unit/object/test_item.py::test_get_shared_link[folder-None-shared_link_unshared_at0-None-True-None]",
"test/unit/object/test_item.py::test_get_shared_link[folder-None-shared_link_unshared_at0-None-True-etag]",
"test/unit/object/test_item.py::test_get_shared_link[folder-None-shared_link_unshared_at0-None-False-None]",
"test/unit/object/test_item.py::test_get_shared_link[folder-None-shared_link_unshared_at0-None-False-etag]",
"test/unit/object/test_item.py::test_get_shared_link[folder-None-shared_link_unshared_at0-None-None-None]",
"test/unit/object/test_item.py::test_get_shared_link[folder-None-shared_link_unshared_at0-None-None-etag]",
"test/unit/object/test_item.py::test_get_shared_link[folder-None-None-True-True-None]",
"test/unit/object/test_item.py::test_get_shared_link[folder-None-None-True-True-etag]",
"test/unit/object/test_item.py::test_get_shared_link[folder-None-None-True-False-None]",
"test/unit/object/test_item.py::test_get_shared_link[folder-None-None-True-False-etag]",
"test/unit/object/test_item.py::test_get_shared_link[folder-None-None-True-None-None]",
"test/unit/object/test_item.py::test_get_shared_link[folder-None-None-True-None-etag]",
"test/unit/object/test_item.py::test_get_shared_link[folder-None-None-False-True-None]",
"test/unit/object/test_item.py::test_get_shared_link[folder-None-None-False-True-etag]",
"test/unit/object/test_item.py::test_get_shared_link[folder-None-None-False-False-None]",
"test/unit/object/test_item.py::test_get_shared_link[folder-None-None-False-False-etag]",
"test/unit/object/test_item.py::test_get_shared_link[folder-None-None-False-None-None]",
"test/unit/object/test_item.py::test_get_shared_link[folder-None-None-False-None-etag]",
"test/unit/object/test_item.py::test_get_shared_link[folder-None-None-None-True-None]",
"test/unit/object/test_item.py::test_get_shared_link[folder-None-None-None-True-etag]",
"test/unit/object/test_item.py::test_get_shared_link[folder-None-None-None-False-None]",
"test/unit/object/test_item.py::test_get_shared_link[folder-None-None-None-False-etag]",
"test/unit/object/test_item.py::test_get_shared_link[folder-None-None-None-None-None]",
"test/unit/object/test_item.py::test_get_shared_link[folder-None-None-None-None-etag]"
] | [] | [
"test/unit/object/test_item.py::test_update_info[file-None]",
"test/unit/object/test_item.py::test_update_info[file-etag]",
"test/unit/object/test_item.py::test_update_info[folder-None]",
"test/unit/object/test_item.py::test_update_info[folder-etag]",
"test/unit/object/test_item.py::test_rename_item[file]",
"test/unit/object/test_item.py::test_rename_item[folder]",
"test/unit/object/test_item.py::test_copy_item[file]",
"test/unit/object/test_item.py::test_copy_item[folder]",
"test/unit/object/test_item.py::test_move_item[file]",
"test/unit/object/test_item.py::test_move_item[folder]",
"test/unit/object/test_item.py::test_remove_shared_link[file-None]",
"test/unit/object/test_item.py::test_remove_shared_link[file-etag]",
"test/unit/object/test_item.py::test_remove_shared_link[folder-None]",
"test/unit/object/test_item.py::test_remove_shared_link[folder-etag]",
"test/unit/object/test_item.py::test_get[file-None-None]",
"test/unit/object/test_item.py::test_get[file-None-fields1]",
"test/unit/object/test_item.py::test_get[file-etag-None]",
"test/unit/object/test_item.py::test_get[file-etag-fields1]",
"test/unit/object/test_item.py::test_get[folder-None-None]",
"test/unit/object/test_item.py::test_get[folder-None-fields1]",
"test/unit/object/test_item.py::test_get[folder-etag-None]",
"test/unit/object/test_item.py::test_get[folder-etag-fields1]"
] | [] | Apache License 2.0 | 126 |
|
mkdocs__mkdocs-501 | 7cc47645d357fa96bf7197e30b519f331e77a3d5 | 2015-05-06 12:18:45 | 463c5b647e9ce5992b519708a0b9c4cba891d65c | landscape-bot: [](https://landscape.io/diff/146595)
Repository health decreased by 0.24% when pulling **[f42c054](https://github.com/d0ugal/mkdocs/commit/f42c054a9b0fc86f7ed40de43fec8ebb53ab4191) on d0ugal:auto-pages** into **[7cc4764](https://github.com/mkdocs/mkdocs/commit/7cc47645d357fa96bf7197e30b519f331e77a3d5) on mkdocs:master**.
* [1 new problem was found](https://landscape.io/diff/146595) (including 0 errors and 1 code smell).
* No problems were fixed.
landscape-bot: [](https://landscape.io/diff/146599)
Code quality remained the same when pulling **[7fc3de2](https://github.com/d0ugal/mkdocs/commit/7fc3de2959a6c94556be4f0e9c5a0cf27d451318) on d0ugal:auto-pages** into **[7cc4764](https://github.com/mkdocs/mkdocs/commit/7cc47645d357fa96bf7197e30b519f331e77a3d5) on mkdocs:master**.
landscape-bot: [](https://landscape.io/diff/146599)
Code quality remained the same when pulling **[7fc3de2](https://github.com/d0ugal/mkdocs/commit/7fc3de2959a6c94556be4f0e9c5a0cf27d451318) on d0ugal:auto-pages** into **[7cc4764](https://github.com/mkdocs/mkdocs/commit/7cc47645d357fa96bf7197e30b519f331e77a3d5) on mkdocs:master**.
landscape-bot: [](https://landscape.io/diff/146619)
Code quality remained the same when pulling **[d49f3a0](https://github.com/d0ugal/mkdocs/commit/d49f3a09fb5431351d5bd975e71f40a3cd69cdd4) on d0ugal:auto-pages** into **[7cc4764](https://github.com/mkdocs/mkdocs/commit/7cc47645d357fa96bf7197e30b519f331e77a3d5) on mkdocs:master**. | diff --git a/mkdocs.yml b/mkdocs.yml
index ad7ce968..930ccd95 100644
--- a/mkdocs.yml
+++ b/mkdocs.yml
@@ -4,19 +4,6 @@ site_description: Project documentation with Markdown.
repo_url: https://github.com/mkdocs/mkdocs/
-pages:
-- Home: index.md
-- User Guide:
- - Writing Your Docs: user-guide/writing-your-docs.md
- - Styling Your Docs: user-guide/styling-your-docs.md
- - Configuration: user-guide/configuration.md
-- About:
- - License: about/license.md
- - Release Notes: about/release-notes.md
- - Contributing: about/contributing.md
-
-use_new_pages_structure: true
-
markdown_extensions:
toc:
permalink: ""
diff --git a/mkdocs/config.py b/mkdocs/config.py
index 408e3393..71451244 100644
--- a/mkdocs/config.py
+++ b/mkdocs/config.py
@@ -145,6 +145,8 @@ def validate_config(user_config):
elif utils.is_template_file(filename):
extra_templates.append(filename)
+ pages = utils.nest_paths(pages)
+
if config['pages'] is None:
config['pages'] = pages
else:
diff --git a/mkdocs/nav.py b/mkdocs/nav.py
index 58b5bc14..d70628d3 100644
--- a/mkdocs/nav.py
+++ b/mkdocs/nav.py
@@ -22,13 +22,7 @@ def filename_to_title(filename):
if utils.is_homepage(filename):
return 'Home'
- title = os.path.splitext(filename)[0]
- title = title.replace('-', ' ').replace('_', ' ')
- # Capitalize if the filename was all lowercase, otherwise leave it as-is.
- if title.lower() == title:
- title = title.capitalize()
-
- return title
+ return utils.filename_to_title(filename)
class SiteNavigation(object):
diff --git a/mkdocs/utils.py b/mkdocs/utils.py
index 971ce480..685e90aa 100644
--- a/mkdocs/utils.py
+++ b/mkdocs/utils.py
@@ -307,3 +307,60 @@ def get_theme_names():
"""Return a list containing all the names of all the builtin themes."""
return os.listdir(os.path.join(os.path.dirname(__file__), 'themes'))
+
+
+def filename_to_title(filename):
+
+ title = os.path.splitext(filename)[0]
+ title = title.replace('-', ' ').replace('_', ' ')
+ # Capitalize if the filename was all lowercase, otherwise leave it as-is.
+ if title.lower() == title:
+ title = title.capitalize()
+
+ return title
+
+
+def find_or_create_node(branch, key):
+ """
+ Given a list, look for dictionary with a key matching key and return it's
+ value. If it doesn't exist, create it with the value of an empty list and
+ return that.
+ """
+
+ for node in branch:
+ if not isinstance(node, dict):
+ continue
+
+ if key in node:
+ return node[key]
+
+ new_branch = []
+ node = {key: new_branch}
+ branch.append(node)
+ return new_branch
+
+
+def nest_paths(paths):
+ """
+ Given a list of paths, convert them into a nested structure that will match
+ the pages config.
+ """
+ nested = []
+
+ for path in paths:
+
+ if os.path.sep not in path:
+ nested.append(path)
+ continue
+
+ directory, _ = os.path.split(path)
+ parts = directory.split(os.path.sep)
+
+ branch = nested
+ for part in parts:
+ part = filename_to_title(part)
+ branch = find_or_create_node(branch, part)
+
+ branch.append(path)
+
+ return nested
| Regression with automatic pages config
Caused by: 7849e71b8401608f86e81b48e7b29d18e8408663 | mkdocs/mkdocs | diff --git a/mkdocs/tests/utils_tests.py b/mkdocs/tests/utils_tests.py
index e2854187..41d066e6 100644
--- a/mkdocs/tests/utils_tests.py
+++ b/mkdocs/tests/utils_tests.py
@@ -1,6 +1,7 @@
#!/usr/bin/env python
# coding: utf-8
+import os
import unittest
from mkdocs import nav, utils
@@ -108,3 +109,32 @@ class UtilsTests(unittest.TestCase):
sorted(['flatly', 'cerulean', 'slate', 'bootstrap', 'yeti',
'spacelab', 'united', 'readable', 'simplex', 'mkdocs',
'cosmo', 'journal', 'cyborg', 'readthedocs', 'amelia']))
+
+ def test_nest_paths(self):
+
+ j = os.path.join
+
+ result = utils.nest_paths([
+ 'index.md',
+ j('user-guide', 'configuration.md'),
+ j('user-guide', 'styling-your-docs.md'),
+ j('user-guide', 'writing-your-docs.md'),
+ j('about', 'contributing.md'),
+ j('about', 'license.md'),
+ j('about', 'release-notes.md'),
+ ])
+
+ self.assertEqual(
+ result,
+ [
+ 'index.md',
+ {'User guide': [
+ j('user-guide', 'configuration.md'),
+ j('user-guide', 'styling-your-docs.md'),
+ j('user-guide', 'writing-your-docs.md')]},
+ {'About': [
+ j('about', 'contributing.md'),
+ j('about', 'license.md'),
+ j('about', 'release-notes.md')]}
+ ]
+ )
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_short_problem_statement",
"has_git_commit_hash",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 1,
"issue_text_score": 2,
"test_score": 0
},
"num_modified_files": 4
} | 0.12 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest"
],
"pre_install": null,
"python": "3.7",
"reqs_path": [
"requirements/project.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | certifi @ file:///croot/certifi_1671487769961/work/certifi
click==8.1.8
exceptiongroup==1.2.2
ghp-import==2.1.0
importlib-metadata==6.7.0
iniconfig==2.0.0
Jinja2==3.1.6
livereload==2.7.1
Markdown==3.4.4
MarkupSafe==2.1.5
-e git+https://github.com/mkdocs/mkdocs.git@7cc47645d357fa96bf7197e30b519f331e77a3d5#egg=mkdocs
packaging==24.0
pluggy==1.2.0
pytest==7.4.4
python-dateutil==2.9.0.post0
PyYAML==6.0.1
six==1.17.0
tomli==2.0.1
tornado==6.2
typing_extensions==4.7.1
zipp==3.15.0
| name: mkdocs
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2022.12.7=py37h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- pip=22.3.1=py37h06a4308_0
- python=3.7.16=h7a1cb2a_0
- readline=8.2=h5eee18b_0
- setuptools=65.6.3=py37h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- wheel=0.38.4=py37h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- click==8.1.8
- exceptiongroup==1.2.2
- ghp-import==2.1.0
- importlib-metadata==6.7.0
- iniconfig==2.0.0
- jinja2==3.1.6
- livereload==2.7.1
- markdown==3.4.4
- markupsafe==2.1.5
- packaging==24.0
- pluggy==1.2.0
- pytest==7.4.4
- python-dateutil==2.9.0.post0
- pyyaml==6.0.1
- six==1.17.0
- tomli==2.0.1
- tornado==6.2
- typing-extensions==4.7.1
- zipp==3.15.0
prefix: /opt/conda/envs/mkdocs
| [
"mkdocs/tests/utils_tests.py::UtilsTests::test_nest_paths"
] | [
"mkdocs/tests/utils_tests.py::UtilsTests::test_create_media_urls"
] | [
"mkdocs/tests/utils_tests.py::UtilsTests::test_get_themes",
"mkdocs/tests/utils_tests.py::UtilsTests::test_html_path",
"mkdocs/tests/utils_tests.py::UtilsTests::test_is_html_file",
"mkdocs/tests/utils_tests.py::UtilsTests::test_is_markdown_file",
"mkdocs/tests/utils_tests.py::UtilsTests::test_reduce_list",
"mkdocs/tests/utils_tests.py::UtilsTests::test_url_path",
"mkdocs/tests/utils_tests.py::UtilsTests::test_yaml_load"
] | [] | BSD 2-Clause "Simplified" License | 127 |
typesafehub__conductr-cli-52 | e5561a7e43d92a0c19e7b6e31a36448455a17fba | 2015-05-06 15:35:08 | e5561a7e43d92a0c19e7b6e31a36448455a17fba | diff --git a/.gitignore b/.gitignore
index b8b187e..896a06a 100644
--- a/.gitignore
+++ b/.gitignore
@@ -6,3 +6,4 @@ deb_dist/*
.idea
*.iml
*.pyc
+.tox
diff --git a/.travis.yml b/.travis.yml
index 4374097..817f35a 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -1,7 +1,8 @@
language: python
-python:
-- '3.4'
-script: python3 setup.py test
+install:
+ - pip3 install --user virtualenv
+script:
+ - python3 setup.py test
deploy:
provider: pypi
user: typesafehub
diff --git a/conductr_cli/conduct_logging.py b/conductr_cli/conduct_logging.py
index 159999f..3d9feb8 100644
--- a/conductr_cli/conduct_logging.py
+++ b/conductr_cli/conduct_logging.py
@@ -26,7 +26,7 @@ def connection_error(err, args):
def pretty_json(s):
s_json = json.loads(s)
- print(json.dumps(s_json, sort_keys=True, indent=2))
+ print(json.dumps(s_json, sort_keys=True, indent=2, separators=(',', ': ')))
def handle_connection_error(func):
diff --git a/conductr_cli/shazar.py b/conductr_cli/shazar.py
index 5c97b3d..cac7342 100755
--- a/conductr_cli/shazar.py
+++ b/conductr_cli/shazar.py
@@ -11,10 +11,10 @@ import tempfile
import zipfile
-def run():
+def run(argv=None):
parser = build_parser()
argcomplete.autocomplete(parser)
- args = parser.parse_args()
+ args = parser.parse_args(argv)
args.func(args)
@@ -45,10 +45,8 @@ def shazar(args):
else:
zip_file.write(args.source, source_base_name)
- dest = shutil.move(
- temp_file,
- os.path.join(args.output_dir, '{}-{}.zip'.format(source_base_name, create_digest(temp_file)))
- )
+ dest = os.path.join(args.output_dir, '{}-{}.zip'.format(source_base_name, create_digest(temp_file)))
+ shutil.move(temp_file, dest)
print('Created digested ZIP archive at {}'.format(dest))
diff --git a/setup.py b/setup.py
index 535fada..03f23f9 100644
--- a/setup.py
+++ b/setup.py
@@ -1,10 +1,46 @@
import os
+import sys
from setuptools import setup, find_packages
from conductr_cli import __version__
+from setuptools.command.test import test
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
+install_requires = [
+ 'requests>=2.3.0',
+ 'argcomplete>=0.8.1',
+ 'pyhocon==0.2.1'
+]
+if sys.version_info[:2] == (3, 2):
+ install_requires.extend([
+ 'pathlib==1.0.1',
+ 'mock==1.0.1'
+ ])
+
+
+class Tox(test):
+ user_options = [('tox-args=', 'a', 'Arguments to pass to tox')]
+
+ def initialize_options(self):
+ test.initialize_options(self)
+ self.tox_args = None
+
+ def finalize_options(self):
+ test.finalize_options(self)
+ self.test_args = []
+ self.test_suite = True
+
+ def run_tests(self):
+ # import here, cause outside the eggs aren't loaded
+ import tox
+ import shlex
+ args = self.tox_args
+ if args:
+ args = shlex.split(self.tox_args)
+ errno = tox.cmdline(args=args)
+ sys.exit(errno)
+
setup(
name='conductr-cli',
version=__version__,
@@ -17,13 +53,12 @@ setup(
],
},
- install_requires=[
- 'requests>=2.3.0',
- 'argcomplete>=0.8.1',
- 'pyhocon==0.2.1'
- ],
+ install_requires=install_requires,
+ tests_require=['tox'],
test_suite='conductr_cli.test',
+ cmdclass={'test': Tox},
+
license='Apache 2',
description='A CLI client for Typesafe ConductR',
url='https://github.com/typesafehub/conductr-cli',
diff --git a/tox.ini b/tox.ini
new file mode 100644
index 0000000..5b12aef
--- /dev/null
+++ b/tox.ini
@@ -0,0 +1,6 @@
+[tox]
+envlist = py32, py34
+
+[testenv]
+deps = nose
+commands = nosetests
| Improve CLI message
From @rpokrywka
shazar: “Created digested ZIP archive at None” - the message should be giving more information.
@rpokrywka Can you provide a reproducible test case? | typesafehub/conductr-cli | diff --git a/conductr_cli/test/cli_test_case.py b/conductr_cli/test/cli_test_case.py
index cbad63c..7467a38 100644
--- a/conductr_cli/test/cli_test_case.py
+++ b/conductr_cli/test/cli_test_case.py
@@ -1,9 +1,13 @@
import os
import shutil
import tempfile
-from unittest.mock import MagicMock
from requests.exceptions import ConnectionError, HTTPError
+try:
+ from unittest.mock import MagicMock # 3.3 and beyond
+except ImportError:
+ from mock import MagicMock
+
class CliTestCase():
"""Provides test case common functionality"""
diff --git a/conductr_cli/test/test_conduct_info.py b/conductr_cli/test/test_conduct_info.py
index 6188067..234f94d 100644
--- a/conductr_cli/test/test_conduct_info.py
+++ b/conductr_cli/test/test_conduct_info.py
@@ -1,8 +1,12 @@
from unittest import TestCase
-from unittest.mock import patch, MagicMock
from conductr_cli.test.cli_test_case import CliTestCase, strip_margin
from conductr_cli import conduct_info
+try:
+ from unittest.mock import patch, MagicMock # 3.3 and beyond
+except ImportError:
+ from mock import patch, MagicMock
+
class TestConductInfoCommand(TestCase, CliTestCase):
diff --git a/conductr_cli/test/test_conduct_load.py b/conductr_cli/test/test_conduct_load.py
index 378215f..eb3b983 100644
--- a/conductr_cli/test/test_conduct_load.py
+++ b/conductr_cli/test/test_conduct_load.py
@@ -1,10 +1,14 @@
from unittest import TestCase
-from unittest.mock import call, patch, MagicMock
from conductr_cli.test.cli_test_case import CliTestCase, create_temp_bundle, create_temp_bundle_with_contents, strip_margin
from conductr_cli import conduct_load
from urllib.error import URLError
import shutil
+try:
+ from unittest.mock import call, patch, MagicMock # 3.3 and beyond
+except ImportError:
+ from mock import call, patch, MagicMock
+
class TestConductLoadCommand(TestCase, CliTestCase):
diff --git a/conductr_cli/test/test_conduct_run.py b/conductr_cli/test/test_conduct_run.py
index 9f18628..2bdc26b 100644
--- a/conductr_cli/test/test_conduct_run.py
+++ b/conductr_cli/test/test_conduct_run.py
@@ -1,8 +1,12 @@
from unittest import TestCase
-from unittest.mock import patch, MagicMock
from conductr_cli.test.cli_test_case import CliTestCase, strip_margin
from conductr_cli import conduct_run
+try:
+ from unittest.mock import patch, MagicMock # 3.3 and beyond
+except ImportError:
+ from mock import patch, MagicMock
+
class TestConductRunCommand(TestCase, CliTestCase):
diff --git a/conductr_cli/test/test_conduct_services.py b/conductr_cli/test/test_conduct_services.py
index 590794e..431afef 100644
--- a/conductr_cli/test/test_conduct_services.py
+++ b/conductr_cli/test/test_conduct_services.py
@@ -1,8 +1,12 @@
from unittest import TestCase
-from unittest.mock import patch, MagicMock
from conductr_cli.test.cli_test_case import CliTestCase, strip_margin
from conductr_cli import conduct_services
+try:
+ from unittest.mock import patch, MagicMock # 3.3 and beyond
+except ImportError:
+ from mock import patch, MagicMock
+
class TestConductServicesCommand(TestCase, CliTestCase):
diff --git a/conductr_cli/test/test_conduct_stop.py b/conductr_cli/test/test_conduct_stop.py
index 2c3ab19..39a4e00 100644
--- a/conductr_cli/test/test_conduct_stop.py
+++ b/conductr_cli/test/test_conduct_stop.py
@@ -1,8 +1,12 @@
from unittest import TestCase
-from unittest.mock import patch, MagicMock
from conductr_cli.test.cli_test_case import CliTestCase, strip_margin
from conductr_cli import conduct_stop
+try:
+ from unittest.mock import patch, MagicMock # 3.3 and beyond
+except ImportError:
+ from mock import patch, MagicMock
+
class TestConductStopCommand(TestCase, CliTestCase):
diff --git a/conductr_cli/test/test_conduct_unload.py b/conductr_cli/test/test_conduct_unload.py
index 1cbf7c2..bcff6ac 100644
--- a/conductr_cli/test/test_conduct_unload.py
+++ b/conductr_cli/test/test_conduct_unload.py
@@ -1,8 +1,12 @@
from unittest import TestCase
-from unittest.mock import patch, MagicMock
from conductr_cli.test.cli_test_case import CliTestCase, strip_margin
from conductr_cli import conduct_unload
+try:
+ from unittest.mock import patch, MagicMock # 3.3 and beyond
+except ImportError:
+ from mock import patch, MagicMock
+
class TestConductUnloadCommand(TestCase, CliTestCase):
diff --git a/conductr_cli/test/test_shazar.py b/conductr_cli/test/test_shazar.py
index c8d0407..adfd475 100644
--- a/conductr_cli/test/test_shazar.py
+++ b/conductr_cli/test/test_shazar.py
@@ -1,7 +1,14 @@
from unittest import TestCase
+import shutil
import tempfile
from os import remove
-from conductr_cli.shazar import create_digest, build_parser
+from conductr_cli.shazar import create_digest, build_parser, run
+from conductr_cli.test.cli_test_case import CliTestCase
+
+try:
+ from unittest.mock import patch, MagicMock # 3.3 and beyond
+except ImportError:
+ from mock import patch, MagicMock
class TestShazar(TestCase):
@@ -23,3 +30,25 @@ class TestShazar(TestCase):
self.assertEqual(args.output_dir, 'output-dir')
self.assertEqual(args.source, 'source')
+
+
+class TestIntegration(TestCase, CliTestCase):
+
+ def setUp(self): # noqa
+ self.tmpdir = tempfile.mkdtemp()
+ self.tmpfile = tempfile.NamedTemporaryFile(mode='w+b', delete=False)
+ self.tmpfile.write(b'test file data')
+
+ def test(self):
+ stdout = MagicMock()
+ with patch('sys.stdout', stdout):
+ run('--output-dir {} {}'.format(self.tmpdir, self.tmpfile.name).split())
+
+ self.assertRegex(
+ self.output(stdout),
+ 'Created digested ZIP archive at /tmp/tmp[a-z0-9_]{6,8}/tmp[a-z0-9_]{6,8}-[a-f0-9]{64}\.zip'
+ )
+
+ def tearDown(self): # noqa
+ shutil.rmtree(self.tmpdir)
+ remove(self.tmpfile.name)
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_short_problem_statement",
"has_added_files",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 1,
"issue_text_score": 2,
"test_score": 2
},
"num_modified_files": 5
} | 0.13 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "pytest",
"pip_packages": [
"pytest"
],
"pre_install": null,
"python": "3.9",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | argcomplete==3.6.1
certifi==2025.1.31
charset-normalizer==3.4.1
-e git+https://github.com/typesafehub/conductr-cli.git@e5561a7e43d92a0c19e7b6e31a36448455a17fba#egg=conductr_cli
exceptiongroup @ file:///croot/exceptiongroup_1706031385326/work
idna==3.10
iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work
packaging @ file:///croot/packaging_1734472117206/work
pluggy @ file:///croot/pluggy_1733169602837/work
pyhocon==0.2.1
pyparsing==2.0.3
pytest @ file:///croot/pytest_1738938843180/work
requests==2.32.3
tomli @ file:///opt/conda/conda-bld/tomli_1657175507142/work
urllib3==2.3.0
| name: conductr-cli
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- exceptiongroup=1.2.0=py39h06a4308_0
- iniconfig=1.1.1=pyhd3eb1b0_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=3.0.16=h5eee18b_0
- packaging=24.2=py39h06a4308_0
- pip=25.0=py39h06a4308_0
- pluggy=1.5.0=py39h06a4308_0
- pytest=8.3.4=py39h06a4308_0
- python=3.9.21=he870216_1
- readline=8.2=h5eee18b_0
- setuptools=75.8.0=py39h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- tomli=2.0.1=py39h06a4308_0
- tzdata=2025a=h04d1e81_0
- wheel=0.45.1=py39h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- argcomplete==3.6.1
- certifi==2025.1.31
- charset-normalizer==3.4.1
- idna==3.10
- pyhocon==0.2.1
- pyparsing==2.0.3
- requests==2.32.3
- urllib3==2.3.0
prefix: /opt/conda/envs/conductr-cli
| [
"conductr_cli/test/test_shazar.py::TestIntegration::test"
] | [] | [
"conductr_cli/test/test_conduct_info.py::TestConductInfoCommand::test_double_digits",
"conductr_cli/test/test_conduct_info.py::TestConductInfoCommand::test_failure_invalid_address",
"conductr_cli/test/test_conduct_info.py::TestConductInfoCommand::test_has_error",
"conductr_cli/test/test_conduct_info.py::TestConductInfoCommand::test_long_ids",
"conductr_cli/test/test_conduct_info.py::TestConductInfoCommand::test_no_bundles",
"conductr_cli/test/test_conduct_info.py::TestConductInfoCommand::test_one_running_one_starting_one_stopped",
"conductr_cli/test/test_conduct_info.py::TestConductInfoCommand::test_one_running_one_stopped_verbose",
"conductr_cli/test/test_conduct_info.py::TestConductInfoCommand::test_stopped_bundle",
"conductr_cli/test/test_conduct_load.py::TestConductLoadCommand::test_failure",
"conductr_cli/test/test_conduct_load.py::TestConductLoadCommand::test_failure_invalid_address",
"conductr_cli/test/test_conduct_load.py::TestConductLoadCommand::test_failure_no_bundle",
"conductr_cli/test/test_conduct_load.py::TestConductLoadCommand::test_failure_no_configuration",
"conductr_cli/test/test_conduct_load.py::TestConductLoadCommand::test_failure_no_disk_space",
"conductr_cli/test/test_conduct_load.py::TestConductLoadCommand::test_failure_no_memory",
"conductr_cli/test/test_conduct_load.py::TestConductLoadCommand::test_failure_no_nr_of_cpus",
"conductr_cli/test/test_conduct_load.py::TestConductLoadCommand::test_failure_no_roles",
"conductr_cli/test/test_conduct_load.py::TestConductLoadCommand::test_failure_roles_not_a_list",
"conductr_cli/test/test_conduct_load.py::TestConductLoadCommand::test_success",
"conductr_cli/test/test_conduct_load.py::TestConductLoadCommand::test_success_custom_ip_port",
"conductr_cli/test/test_conduct_load.py::TestConductLoadCommand::test_success_long_ids",
"conductr_cli/test/test_conduct_load.py::TestConductLoadCommand::test_success_verbose",
"conductr_cli/test/test_conduct_load.py::TestConductLoadCommand::test_success_with_configuration",
"conductr_cli/test/test_conduct_run.py::TestConductRunCommand::test_failure",
"conductr_cli/test/test_conduct_run.py::TestConductRunCommand::test_failure_invalid_address",
"conductr_cli/test/test_conduct_run.py::TestConductRunCommand::test_success",
"conductr_cli/test/test_conduct_run.py::TestConductRunCommand::test_success_long_ids",
"conductr_cli/test/test_conduct_run.py::TestConductRunCommand::test_success_verbose",
"conductr_cli/test/test_conduct_run.py::TestConductRunCommand::test_success_with_configuration",
"conductr_cli/test/test_conduct_services.py::TestConductServicesCommand::test_no_bundles",
"conductr_cli/test/test_conduct_services.py::TestConductServicesCommand::test_one_bundle_starting",
"conductr_cli/test/test_conduct_services.py::TestConductServicesCommand::test_one_bundle_starting_long_ids",
"conductr_cli/test/test_conduct_services.py::TestConductServicesCommand::test_two_bundles_mult_components_endpoints",
"conductr_cli/test/test_conduct_services.py::TestConductServicesCommand::test_two_bundles_mult_components_endpoints_no_path",
"conductr_cli/test/test_conduct_stop.py::TestConductStopCommand::test_failure",
"conductr_cli/test/test_conduct_stop.py::TestConductStopCommand::test_failure_invalid_address",
"conductr_cli/test/test_conduct_stop.py::TestConductStopCommand::test_success",
"conductr_cli/test/test_conduct_stop.py::TestConductStopCommand::test_success_long_ids",
"conductr_cli/test/test_conduct_stop.py::TestConductStopCommand::test_success_verbose",
"conductr_cli/test/test_conduct_stop.py::TestConductStopCommand::test_success_with_configuration",
"conductr_cli/test/test_conduct_unload.py::TestConductUnloadCommand::test_failure",
"conductr_cli/test/test_conduct_unload.py::TestConductUnloadCommand::test_failure_invalid_address",
"conductr_cli/test/test_conduct_unload.py::TestConductUnloadCommand::test_success",
"conductr_cli/test/test_conduct_unload.py::TestConductUnloadCommand::test_success_verbose",
"conductr_cli/test/test_conduct_unload.py::TestConductUnloadCommand::test_success_with_configuration",
"conductr_cli/test/test_shazar.py::TestShazar::test_create_digest",
"conductr_cli/test/test_shazar.py::TestShazar::test_parser_success"
] | [] | Apache License 2.0 | 128 |
|
peterbe__premailer-124 | f211f3f1bcfc87dc0318f056d319bb5575f62a72 | 2015-05-08 16:42:16 | f211f3f1bcfc87dc0318f056d319bb5575f62a72 | graingert: Use
`if urlparse.urlparse(base_url).scheme:`
peterbe: @graingert done.
peterbe: @graingert I force-pushed a new commit message. Just for you :)
graingert: Bling
peterbe: So, @graingert you approve?
What do you think @ewjoachim ?
ewjoachim: Nothing to add, I'm ok. | diff --git a/premailer/premailer.py b/premailer/premailer.py
index b53fc23..2d3a221 100644
--- a/premailer/premailer.py
+++ b/premailer/premailer.py
@@ -17,7 +17,7 @@ if sys.version_info >= (3,): # pragma: no cover
# As in, Python 3
from io import StringIO
from urllib.request import urlopen
- from urllib.parse import urljoin
+ from urllib.parse import urljoin, urlparse
STR_TYPE = str
else: # Python 2
try:
@@ -26,7 +26,7 @@ else: # Python 2
from StringIO import StringIO
StringIO = StringIO # shut up pyflakes
from urllib2 import urlopen
- from urlparse import urljoin
+ from urlparse import urljoin, urlparse
STR_TYPE = basestring
import cssutils
@@ -402,25 +402,23 @@ class Premailer(object):
# URLs
#
if self.base_url:
- if not self.base_url.endswith('/'):
- self.base_url += '/'
+ if not urlparse(self.base_url).scheme:
+ raise ValueError('Base URL must start have a scheme')
for attr in ('href', 'src'):
for item in page.xpath("//@%s" % attr):
parent = item.getparent()
+ url = parent.attrib[attr]
if (
attr == 'href' and self.preserve_internal_links and
- parent.attrib[attr].startswith('#')
+ url.startswith('#')
):
continue
if (
attr == 'src' and self.preserve_inline_attachments and
- parent.attrib[attr].startswith('cid:')
+ url.startswith('cid:')
):
continue
- parent.attrib[attr] = urljoin(
- self.base_url,
- parent.attrib[attr].lstrip('/')
- )
+ parent.attrib[attr] = urljoin(self.base_url, url)
if hasattr(self.html, "getroottree"):
return root
| Replacement of urls beginning with //
When using a link whose href starts with "//", Premailer should just add http or https depending on the base url it uses. Currently, it replaces it with the full host, so ``//another.host/`` becomes ``http://my.base.host/another.host/`` | peterbe/premailer | diff --git a/premailer/tests/test_premailer.py b/premailer/tests/test_premailer.py
index ba63f85..4390a4e 100644
--- a/premailer/tests/test_premailer.py
+++ b/premailer/tests/test_premailer.py
@@ -478,7 +478,6 @@ class Tests(unittest.TestCase):
</head>
<body>
<img src="/images/foo.jpg">
- <img src="/images/bar.gif">
<img src="http://www.googe.com/photos/foo.jpg">
<a href="/home">Home</a>
<a href="http://www.peterbe.com">External</a>
@@ -494,10 +493,9 @@ class Tests(unittest.TestCase):
<title>Title</title>
</head>
<body>
- <img src="http://kungfupeople.com/base/images/foo.jpg">
- <img src="http://kungfupeople.com/base/images/bar.gif">
+ <img src="http://kungfupeople.com/images/foo.jpg">
<img src="http://www.googe.com/photos/foo.jpg">
- <a href="http://kungfupeople.com/base/home">Home</a>
+ <a href="http://kungfupeople.com/home">Home</a>
<a href="http://www.peterbe.com">External</a>
<a href="http://www.peterbe.com/base/">External 2</a>
<a href="http://kungfupeople.com/base/subpage">Subpage</a>
@@ -505,7 +503,7 @@ class Tests(unittest.TestCase):
</body>
</html>'''
- p = Premailer(html, base_url='http://kungfupeople.com/base',
+ p = Premailer(html, base_url='http://kungfupeople.com/base/',
preserve_internal_links=True)
result_html = p.transform()
@@ -2302,3 +2300,36 @@ sheet" type="text/css">
result_html = p.transform()
compare_html(expect_html, result_html)
+
+ def test_links_without_protocol(self):
+ """If you the base URL is set to https://example.com and your html
+ contains <img src="//otherdomain.com/">... then the URL to point to
+ is "https://otherdomain.com/" not "https://example.com/file.css"
+ """
+ html = """<html>
+ <head>
+ </head>
+ <body>
+ <img src="//example.com">
+ </body>
+ </html>"""
+
+ expect_html = """<html>
+ <head>
+ </head>
+ <body>
+ <img src="{protocol}://example.com">
+ </body>
+ </html>"""
+
+ p = Premailer(html, base_url='https://www.peterbe.com')
+ result_html = p.transform()
+ compare_html(expect_html.format(protocol="https"), result_html)
+
+ p = Premailer(html, base_url='http://www.peterbe.com')
+ result_html = p.transform()
+ compare_html(expect_html.format(protocol="http"), result_html)
+
+ # Because you can't set a base_url without a full protocol
+ p = Premailer(html, base_url='www.peterbe.com')
+ assert_raises(ValueError, p.transform)
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_hyperlinks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 1,
"issue_text_score": 1,
"test_score": 2
},
"num_modified_files": 1
} | unknown | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "lxml cssselect cssutils nose mock",
"pip_packages": [
"nose",
"mock",
"pytest"
],
"pre_install": null,
"python": "3.9",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | cssselect @ file:///croot/cssselect_1707339882883/work
cssutils @ file:///home/conda/feedstock_root/build_artifacts/cssutils_1734884840740/work
exceptiongroup==1.2.2
iniconfig==2.1.0
lxml @ file:///croot/lxml_1737039601731/work
mock @ file:///tmp/build/80754af9/mock_1607622725907/work
nose @ file:///opt/conda/conda-bld/nose_1642704612149/work
packaging==24.2
pluggy==1.5.0
-e git+https://github.com/peterbe/premailer.git@f211f3f1bcfc87dc0318f056d319bb5575f62a72#egg=premailer
pytest==8.3.5
tomli==2.2.1
| name: premailer
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- cssselect=1.2.0=py39h06a4308_0
- cssutils=2.11.0=pyhd8ed1ab_1
- icu=73.1=h6a678d5_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- libxml2=2.13.5=hfdd30dd_0
- libxslt=1.1.41=h097e994_0
- lxml=5.3.0=py39h57af460_1
- mock=4.0.3=pyhd3eb1b0_0
- ncurses=6.4=h6a678d5_0
- nose=1.3.7=pyhd3eb1b0_1008
- openssl=3.0.16=h5eee18b_0
- pip=25.0=py39h06a4308_0
- python=3.9.21=he870216_1
- readline=8.2=h5eee18b_0
- setuptools=75.8.0=py39h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- tzdata=2025a=h04d1e81_0
- wheel=0.45.1=py39h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- exceptiongroup==1.2.2
- iniconfig==2.1.0
- packaging==24.2
- pluggy==1.5.0
- pytest==8.3.5
- tomli==2.2.1
prefix: /opt/conda/envs/premailer
| [
"premailer/tests/test_premailer.py::Tests::test_base_url_with_path",
"premailer/tests/test_premailer.py::Tests::test_links_without_protocol"
] | [] | [
"premailer/tests/test_premailer.py::Tests::test_apple_newsletter_example",
"premailer/tests/test_premailer.py::Tests::test_base_url_fixer",
"premailer/tests/test_premailer.py::Tests::test_basic_html",
"premailer/tests/test_premailer.py::Tests::test_basic_html_shortcut_function",
"premailer/tests/test_premailer.py::Tests::test_basic_html_with_pseudo_selector",
"premailer/tests/test_premailer.py::Tests::test_basic_xml",
"premailer/tests/test_premailer.py::Tests::test_broken_xml",
"premailer/tests/test_premailer.py::Tests::test_child_selector",
"premailer/tests/test_premailer.py::Tests::test_command_line_fileinput_from_argument",
"premailer/tests/test_premailer.py::Tests::test_command_line_fileinput_from_stdin",
"premailer/tests/test_premailer.py::Tests::test_command_line_preserve_style_tags",
"premailer/tests/test_premailer.py::Tests::test_comments_in_media_queries",
"premailer/tests/test_premailer.py::Tests::test_css_disable_basic_html_attributes",
"premailer/tests/test_premailer.py::Tests::test_css_text",
"premailer/tests/test_premailer.py::Tests::test_css_text_with_only_body_present",
"premailer/tests/test_premailer.py::Tests::test_css_with_html_attributes",
"premailer/tests/test_premailer.py::Tests::test_css_with_pseudoclasses_excluded",
"premailer/tests/test_premailer.py::Tests::test_css_with_pseudoclasses_included",
"premailer/tests/test_premailer.py::Tests::test_disabled_validator",
"premailer/tests/test_premailer.py::Tests::test_doctype",
"premailer/tests/test_premailer.py::Tests::test_empty_style_tag",
"premailer/tests/test_premailer.py::Tests::test_external_links",
"premailer/tests/test_premailer.py::Tests::test_external_links_unfindable",
"premailer/tests/test_premailer.py::Tests::test_external_styles_and_links",
"premailer/tests/test_premailer.py::Tests::test_external_styles_on_http",
"premailer/tests/test_premailer.py::Tests::test_external_styles_on_https",
"premailer/tests/test_premailer.py::Tests::test_external_styles_with_base_url",
"premailer/tests/test_premailer.py::Tests::test_favour_rule_with_class_over_generic",
"premailer/tests/test_premailer.py::Tests::test_favour_rule_with_element_over_generic",
"premailer/tests/test_premailer.py::Tests::test_favour_rule_with_id_over_others",
"premailer/tests/test_premailer.py::Tests::test_favour_rule_with_important_over_others",
"premailer/tests/test_premailer.py::Tests::test_fontface_selectors_with_no_selectortext",
"premailer/tests/test_premailer.py::Tests::test_ignore_some_external_stylesheets",
"premailer/tests/test_premailer.py::Tests::test_ignore_some_incorrectly",
"premailer/tests/test_premailer.py::Tests::test_ignore_some_inline_stylesheets",
"premailer/tests/test_premailer.py::Tests::test_ignore_style_elements_with_media_attribute",
"premailer/tests/test_premailer.py::Tests::test_include_star_selector",
"premailer/tests/test_premailer.py::Tests::test_inline_wins_over_external",
"premailer/tests/test_premailer.py::Tests::test_keyframe_selectors",
"premailer/tests/test_premailer.py::Tests::test_last_child",
"premailer/tests/test_premailer.py::Tests::test_last_child_exclude_pseudo",
"premailer/tests/test_premailer.py::Tests::test_leftover_important",
"premailer/tests/test_premailer.py::Tests::test_load_external_url",
"premailer/tests/test_premailer.py::Tests::test_load_external_url_gzip",
"premailer/tests/test_premailer.py::Tests::test_mailto_url",
"premailer/tests/test_premailer.py::Tests::test_mediaquery",
"premailer/tests/test_premailer.py::Tests::test_merge_styles_basic",
"premailer/tests/test_premailer.py::Tests::test_merge_styles_non_trivial",
"premailer/tests/test_premailer.py::Tests::test_merge_styles_with_class",
"premailer/tests/test_premailer.py::Tests::test_mixed_pseudo_selectors",
"premailer/tests/test_premailer.py::Tests::test_multiple_style_elements",
"premailer/tests/test_premailer.py::Tests::test_multithreading",
"premailer/tests/test_premailer.py::Tests::test_parse_style_rules",
"premailer/tests/test_premailer.py::Tests::test_precedence_comparison",
"premailer/tests/test_premailer.py::Tests::test_prefer_inline_to_class",
"premailer/tests/test_premailer.py::Tests::test_shortcut_function",
"premailer/tests/test_premailer.py::Tests::test_strip_important",
"premailer/tests/test_premailer.py::Tests::test_style_attribute_specificity",
"premailer/tests/test_premailer.py::Tests::test_style_block_with_external_urls",
"premailer/tests/test_premailer.py::Tests::test_turnoff_cache_works_as_expected",
"premailer/tests/test_premailer.py::Tests::test_type_test",
"premailer/tests/test_premailer.py::Tests::test_xml_cdata"
] | [] | BSD 3-Clause "New" or "Revised" License | 129 |
DinoTools__python-overpy-18 | ac7df97ef4302d7eda46a6bb34a887e9b275748c | 2015-05-09 07:36:00 | 7b0e0d999acb0549b57a271f31830fc020471731 | diff --git a/overpy/__init__.py b/overpy/__init__.py
index 454e1f5..cf48898 100644
--- a/overpy/__init__.py
+++ b/overpy/__init__.py
@@ -1,5 +1,6 @@
from collections import OrderedDict
from decimal import Decimal
+from xml.sax import handler, make_parser
import json
import re
import sys
@@ -14,6 +15,9 @@ from overpy.__about__ import (
PY2 = sys.version_info[0] == 2
PY3 = sys.version_info[0] == 3
+XML_PARSER_DOM = 1
+XML_PARSER_SAX = 2
+
if PY2:
from urllib2 import urlopen
from urllib2 import HTTPError
@@ -41,10 +45,12 @@ class Overpass(object):
"""
default_read_chunk_size = 4096
- def __init__(self, read_chunk_size=None):
+ def __init__(self, read_chunk_size=None, xml_parser=XML_PARSER_SAX):
"""
:param read_chunk_size: Max size of each chunk read from the server response
:type read_chunk_size: Integer
+ :param xml_parser: The xml parser to use
+ :type xml_parser: Integer
"""
self.url = "http://overpass-api.de/api/interpreter"
self._regex_extract_error_msg = re.compile(b"\<p\>(?P<msg>\<strong\s.*?)\</p\>")
@@ -52,6 +58,7 @@ class Overpass(object):
if read_chunk_size is None:
read_chunk_size = self.default_read_chunk_size
self.read_chunk_size = read_chunk_size
+ self.xml_parser = xml_parser
def query(self, query):
"""
@@ -131,7 +138,7 @@ class Overpass(object):
data = json.loads(data, parse_float=Decimal)
return Result.from_json(data, api=self)
- def parse_xml(self, data, encoding="utf-8"):
+ def parse_xml(self, data, encoding="utf-8", parser=None):
"""
:param data: Raw XML Data
@@ -141,14 +148,16 @@ class Overpass(object):
:return: Result object
:rtype: overpy.Result
"""
+ if parser is None:
+ parser = self.xml_parser
+
if isinstance(data, bytes):
data = data.decode(encoding)
if PY2 and not isinstance(data, str):
# Python 2.x: Convert unicode strings
data = data.encode(encoding)
- import xml.etree.ElementTree as ET
- root = ET.fromstring(data)
- return Result.from_xml(root, api=self)
+
+ return Result.from_xml(data, api=self, parser=parser)
class Result(object):
@@ -262,7 +271,7 @@ class Result(object):
return result
@classmethod
- def from_xml(cls, root, api=None):
+ def from_xml(cls, data, api=None, parser=XML_PARSER_SAX):
"""
Create a new instance and load data from xml object.
@@ -270,15 +279,34 @@ class Result(object):
:type data: xml.etree.ElementTree.Element
:param api:
:type api: Overpass
+ :param parser: Specify the parser to use(DOM or SAX)
+ :type parser: Integer
:return: New instance of Result object
:rtype: Result
"""
result = cls(api=api)
- for elem_cls in [Node, Way, Relation]:
- for child in root:
- if child.tag.lower() == elem_cls._type_value:
- result.append(elem_cls.from_xml(child, result=result))
+ if parser == XML_PARSER_DOM:
+ import xml.etree.ElementTree as ET
+ root = ET.fromstring(data)
+ for elem_cls in [Node, Way, Relation]:
+ for child in root:
+ if child.tag.lower() == elem_cls._type_value:
+ result.append(elem_cls.from_xml(child, result=result))
+
+ elif parser == XML_PARSER_SAX:
+ if PY2:
+ from StringIO import StringIO
+ else:
+ from io import StringIO
+ source = StringIO(data)
+ sax_handler = OSMSAXHandler(result)
+ parser = make_parser()
+ parser.setContentHandler(sax_handler)
+ parser.parse(source)
+ else:
+ # ToDo: better exception
+ raise Exception("Unknown XML parser")
return result
def get_node(self, node_id, resolve_missing=False):
@@ -952,3 +980,185 @@ class RelationRelation(RelationMember):
def __repr__(self):
return "<overpy.RelationRelation ref={} role={}>".format(self.ref, self.role)
+
+
+class OSMSAXHandler(handler.ContentHandler):
+ """
+ SAX parser for Overpass XML response.
+ """
+ #: Tuple of opening elements to ignore
+ ignore_start = ('osm', 'meta', 'note')
+ #: Tuple of closing elements to ignore
+ ignore_end = ('osm', 'meta', 'note', 'tag', 'nd', 'member')
+
+ def __init__(self, result):
+ """
+ :param result: Append results to this result set.
+ :type result: overpy.Result
+ """
+ handler.ContentHandler.__init__(self)
+ self._result = result
+ self._curr = {}
+
+ def startElement(self, name, attrs):
+ """
+ Handle opening elements.
+
+ :param name: Name of the element
+ :type name: String
+ :param attrs: Attributes of the element
+ :type attrs: Dict
+ """
+ if name in self.ignore_start:
+ return
+ try:
+ handler = getattr(self, '_handle_start_%s' % name)
+ except AttributeError:
+ raise KeyError("Unknown element start '%s'" % name)
+ handler(attrs)
+
+ def endElement(self, name):
+ """
+ Handle closing elements
+
+ :param name: Name of the element
+ :type name: String
+ """
+ if name in self.ignore_end:
+ return
+ try:
+ handler = getattr(self, '_handle_end_%s' % name)
+ except AttributeError:
+ raise KeyError("Unknown element start '%s'" % name)
+ handler()
+
+ def _handle_start_tag(self, attrs):
+ """
+ Handle opening tag element
+
+ :param attrs: Attributes of the element
+ :type attrs: Dict
+ """
+ try:
+ tag_key = attrs['k']
+ except KeyError:
+ raise ValueError("Tag without name/key.")
+ self._curr['tags'][tag_key] = attrs.get('v')
+
+ def _handle_start_node(self, attrs):
+ """
+ Handle opening node element
+
+ :param attrs: Attributes of the element
+ :type attrs: Dict
+ """
+ self._curr = {
+ 'attributes': dict(attrs),
+ 'lat': None,
+ 'lon': None,
+ 'node_id': None,
+ 'tags': {}
+ }
+ if attrs.get('id', None) is not None:
+ self._curr['node_id'] = int(attrs['id'])
+ del self._curr['attributes']['id']
+ if attrs.get('lat', None) is not None:
+ self._curr['lat'] = Decimal(attrs['lat'])
+ del self._curr['attributes']['lat']
+ if attrs.get('lon', None) is not None:
+ self._curr['lon'] = Decimal(attrs['lon'])
+ del self._curr['attributes']['lon']
+
+ def _handle_end_node(self):
+ """
+ Handle closing node element
+ """
+ self._result.append(Node(result=self._result, **self._curr))
+ self._curr = {}
+
+ def _handle_start_way(self, attrs):
+ """
+ Handle opening way element
+
+ :param attrs: Attributes of the element
+ :type attrs: Dict
+ """
+ self._curr = {
+ 'attributes': dict(attrs),
+ 'node_ids': [],
+ 'tags': {},
+ 'way_id': None
+ }
+ if attrs.get('id', None) is not None:
+ self._curr['way_id'] = int(attrs['id'])
+ del self._curr['attributes']['id']
+
+ def _handle_end_way(self):
+ """
+ Handle closing way element
+ """
+ self._result.append(Way(result=self._result, **self._curr))
+ self._curr = {}
+
+ def _handle_start_nd(self, attrs):
+ """
+ Handle opening nd element
+
+ :param attrs: Attributes of the element
+ :type attrs: Dict
+ """
+ try:
+ node_ref = attrs['ref']
+ except KeyError:
+ raise ValueError("Unable to find required ref value.")
+ self._curr['node_ids'].append(int(node_ref))
+
+ def _handle_start_relation(self, attrs):
+ """
+ Handle opening relation element
+
+ :param attrs: Attributes of the element
+ :type attrs: Dict
+ """
+ self._curr = {
+ 'attributes': dict(attrs),
+ 'members': [],
+ 'rel_id': None,
+ 'tags': {}
+ }
+ if attrs.get('id', None) is not None:
+ self._curr['rel_id'] = int(attrs['id'])
+ del self._curr['attributes']['id']
+
+ def _handle_end_relation(self):
+ """
+ Handle closing relation element
+ """
+ self._result.append(Relation(result=self._result, **self._curr))
+ self._curr = {}
+
+ def _handle_start_member(self, attrs):
+ """
+ Handle opening member element
+
+ :param attrs: Attributes of the element
+ :type attrs: Dict
+ """
+ params = {
+ 'ref': None,
+ 'result': self._result,
+ 'role': None
+ }
+ if attrs.get('ref', None):
+ params['ref'] = int(attrs['ref'])
+ if attrs.get('role', None):
+ params['role'] = attrs['role']
+
+ if attrs['type'] == 'node':
+ self._curr['members'].append(RelationNode(**params))
+ elif attrs['type'] == 'way':
+ self._curr['members'].append(RelationWay(**params))
+ elif attrs['type'] == 'relation':
+ self._curr['members'].append(RelationRelation(**params))
+ else:
+ raise ValueError("Undefined type for member: '%s'" % attrs['type'])
| Less memory-consuming xml parsing
Currently the whole xml-result is first parsed into a xml.etree.ElementTree and than processed to create overpy structures. While this is perfectly fine for small amounts of data, larger files or requests consume a lot of memory that is not freed after the overpy result is constructed.
A SAX-style parser could reduce the memory footprint and both overpy's architecture and osm_xml's structure would easily support such a parser. | DinoTools/python-overpy | diff --git a/tests/test_xml.py b/tests/test_xml.py
index 2f6d02a..e0c7397 100644
--- a/tests/test_xml.py
+++ b/tests/test_xml.py
@@ -9,31 +9,51 @@ from tests.base_class import read_file
class TestNodes(BaseTestNodes):
def test_node01(self):
api = overpy.Overpass()
- result = api.parse_xml(read_file("xml/node-01.xml"))
+ # DOM
+ result = api.parse_xml(read_file("xml/node-01.xml"), parser=overpy.XML_PARSER_DOM)
+ self._test_node01(result)
+ # SAX
+ result = api.parse_xml(read_file("xml/node-01.xml"), parser=overpy.XML_PARSER_SAX)
self._test_node01(result)
class TestRelation(BaseTestRelation):
def test_relation01(self):
api = overpy.Overpass()
- result = api.parse_xml(read_file("xml/relation-01.xml"))
+ # DOM
+ result = api.parse_xml(read_file("xml/relation-01.xml"), parser=overpy.XML_PARSER_DOM)
+ self._test_relation01(result)
+ # SAX
+ result = api.parse_xml(read_file("xml/relation-01.xml"), parser=overpy.XML_PARSER_SAX)
self._test_relation01(result)
def test_relation02(self):
api = overpy.Overpass()
- result = api.parse_xml(read_file("xml/relation-02.xml"))
+ # DOM
+ result = api.parse_xml(read_file("xml/relation-02.xml"), parser=overpy.XML_PARSER_DOM)
+ self._test_relation02(result)
+ # SAX
+ result = api.parse_xml(read_file("xml/relation-02.xml"), parser=overpy.XML_PARSER_SAX)
self._test_relation02(result)
class TestWay(BaseTestWay):
def test_way01(self):
api = overpy.Overpass()
- result = api.parse_xml(read_file("xml/way-01.xml"))
+ # DOM
+ result = api.parse_xml(read_file("xml/way-01.xml"), parser=overpy.XML_PARSER_DOM)
+ self._test_way01(result)
+ # SAX
+ result = api.parse_xml(read_file("xml/way-01.xml"), parser=overpy.XML_PARSER_SAX)
self._test_way01(result)
def test_way02(self):
api = overpy.Overpass()
- result = api.parse_xml(read_file("xml/way-02.xml"))
+ # DOM
+ result = api.parse_xml(read_file("xml/way-02.xml"), parser=overpy.XML_PARSER_DOM)
+ self._test_way02(result)
+ # SAX
+ result = api.parse_xml(read_file("xml/way-02.xml"), parser=overpy.XML_PARSER_SAX)
self._test_way02(result)
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 2,
"issue_text_score": 1,
"test_score": 0
},
"num_modified_files": 1
} | 0.3 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "pytest",
"pip_packages": [
"pytest"
],
"pre_install": null,
"python": "3.9",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | exceptiongroup @ file:///croot/exceptiongroup_1706031385326/work
iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work
-e git+https://github.com/DinoTools/python-overpy.git@ac7df97ef4302d7eda46a6bb34a887e9b275748c#egg=overpy
packaging @ file:///croot/packaging_1734472117206/work
pluggy @ file:///croot/pluggy_1733169602837/work
pytest @ file:///croot/pytest_1738938843180/work
tomli @ file:///opt/conda/conda-bld/tomli_1657175507142/work
| name: python-overpy
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- exceptiongroup=1.2.0=py39h06a4308_0
- iniconfig=1.1.1=pyhd3eb1b0_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=3.0.16=h5eee18b_0
- packaging=24.2=py39h06a4308_0
- pip=25.0=py39h06a4308_0
- pluggy=1.5.0=py39h06a4308_0
- pytest=8.3.4=py39h06a4308_0
- python=3.9.21=he870216_1
- readline=8.2=h5eee18b_0
- setuptools=75.8.0=py39h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- tomli=2.0.1=py39h06a4308_0
- tzdata=2025a=h04d1e81_0
- wheel=0.45.1=py39h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
prefix: /opt/conda/envs/python-overpy
| [
"tests/test_xml.py::TestNodes::test_node01",
"tests/test_xml.py::TestRelation::test_relation01",
"tests/test_xml.py::TestRelation::test_relation02",
"tests/test_xml.py::TestWay::test_way01",
"tests/test_xml.py::TestWay::test_way02"
] | [] | [
"tests/test_xml.py::TestDataError::test_element_wrong_type",
"tests/test_xml.py::TestDataError::test_node_missing_data",
"tests/test_xml.py::TestDataError::test_relation_missing_data",
"tests/test_xml.py::TestDataError::test_way_missing_data"
] | [] | MIT License | 130 |
|
mkdocs__mkdocs-510 | 5b8bae094b2cfbc3cb9ef2f77cee4c1271abd3e2 | 2015-05-09 20:09:55 | 463c5b647e9ce5992b519708a0b9c4cba891d65c | diff --git a/docs/user-guide/configuration.md b/docs/user-guide/configuration.md
index a619e5ea..97824ff0 100644
--- a/docs/user-guide/configuration.md
+++ b/docs/user-guide/configuration.md
@@ -163,6 +163,13 @@ Set a list of JavaScript files to be included by the theme.
**default**: By default `extra_javascript` will contain a list of all the JavaScript files found within the `docs_dir`, if none are found it will be `[]` (an empty list).
+
+### extra
+
+A set of key value pairs, where the values can be any valid YAML construct, that will be passed to the template. This allows for great flexibility when creating custom themes.
+
+**default**: By default `extra` will be an empty key value mapping.
+
## Preview controls
### use_directory_urls
diff --git a/docs/user-guide/styling-your-docs.md b/docs/user-guide/styling-your-docs.md
index af7d6ef7..78d510b3 100644
--- a/docs/user-guide/styling-your-docs.md
+++ b/docs/user-guide/styling-your-docs.md
@@ -119,15 +119,11 @@ Article content from each page specified in `mkdocs.yml` is inserted using the `
### Template Variables
-Each template in a theme is built with a template context. These are the variables that are available to theme. The context varies depending on the template that is being built. At the moment templates are either built with
-the global context or with a page specific context. The global context is used
-for HTML pages that don't represent an individual Markdown document, for
-example a 404.html page or search.html.
-
+Each template in a theme is built with a template context. These are the variables that are available to themes. The context varies depending on the template that is being built. At the moment templates are either built with the global context or with a page specific context. The global context is used for HTML pages that don't represent an individual Markdown document, for example a 404.html page or search.html.
#### Global Context
-The following variables in the context map directly the the configuration file.
+The following variables in the context map directly the the [configuration options](/user-guide/configuration/).
Variable Name | Configuration name
----------------- | ------------------- |
@@ -140,6 +136,7 @@ repo_name | repo_name |
site_url | site_url |
extra_css | extra_css |
extra_javascript | extra_javascript |
+extra | extra |
include_nav | include_nav |
include_next_prev | include_next_prev |
copyright | copyright |
@@ -237,6 +234,34 @@ The page object for the previous page. The isage is the same as for
##### next_page
The page object for the next page.The isage is the same as for `current_page`.
+#### Extra Context
+
+Additional variables can be passed to the template with the [`extra`](/user-guide/configuration/#extra) configuration option. This is a set of key value pairs that can make custom templates far more flexible.
+
+For example, this could be used to include the project version of all pages and a list of links related to the project. This can be achieved with the following `extra` configuration:
+
+```yaml
+extra:
+ version: 0.13.0
+ links:
+ - https://github.com/mkdocs
+ - https://docs.readthedocs.org/en/latest/builds.html#mkdocs
+ - http://www.mkdocs.org/
+```
+
+And then displayed with this HTML in the custom theme.
+
+```html
+{{ extra.version }}
+
+{% if extra.links %}
+ <ul>
+ {% for link in extra.links %}
+ <li>{{ link }}</li>
+ {% endfor %}
+ </ul>
+{% endif %}
+```
### Search and themes
diff --git a/mkdocs/build.py b/mkdocs/build.py
index 1bd28e88..55dd4d47 100644
--- a/mkdocs/build.py
+++ b/mkdocs/build.py
@@ -1,4 +1,5 @@
# coding: utf-8
+from __future__ import print_function
from datetime import datetime
from io import open
@@ -90,7 +91,9 @@ def get_global_context(nav, config):
'google_analytics': config['google_analytics'],
'mkdocs_version': mkdocs.__version__,
- 'build_date_utc': datetime.utcnow()
+ 'build_date_utc': datetime.utcnow(),
+
+ 'extra': config['extra']
}
@@ -149,7 +152,7 @@ def build_sitemap(config, env, site_navigation):
def build_template(template_name, env, config, site_navigation=None):
- log.debug("Building template: %s", template_name)
+ log.debug("Building %s page", template_name)
try:
template = env.get_template(template_name)
@@ -279,12 +282,12 @@ def build(config, live_server=False, dump_json=False, clean_site_dir=False):
Perform a full site build.
"""
if clean_site_dir:
- log.info("Cleaning site directory")
+ print("Cleaning site directory")
utils.clean_directory(config['site_dir'])
if not live_server:
- log.info("Building documentation to directory: %s", config['site_dir'])
+ print("Building documentation to directory: %s" % config['site_dir'])
if not clean_site_dir and site_directory_contains_stale_files(config['site_dir']):
- log.info("The directory contains stale files. Use --clean to remove them.")
+ print("Directory %s contains stale files. Use --clean to remove them." % config['site_dir'])
if dump_json:
build_pages(config, dump_json=True)
diff --git a/mkdocs/cli.py b/mkdocs/cli.py
index 91ad8d34..06aa8a86 100644
--- a/mkdocs/cli.py
+++ b/mkdocs/cli.py
@@ -19,16 +19,11 @@ def configure_logging(is_verbose=False):
'''When a --verbose flag is passed, increase the verbosity of mkdocs'''
logger = logging.getLogger('mkdocs')
- logger.propagate = False
- stream = logging.StreamHandler()
- formatter = logging.Formatter("%(levelname)-7s - %(message)s ")
- stream.setFormatter(formatter)
- logger.addHandler(stream)
if is_verbose:
logger.setLevel(logging.DEBUG)
else:
- logger.setLevel(logging.INFO)
+ logger.setLevel(logging.WARNING)
clean_help = "Remove old files from the site_dir before building"
diff --git a/mkdocs/config/defaults.py b/mkdocs/config/defaults.py
index b3b14146..6ce0922e 100644
--- a/mkdocs/config/defaults.py
+++ b/mkdocs/config/defaults.py
@@ -96,4 +96,11 @@ DEFAULT_SCHEMA = (
# enabling strict mode causes MkDocs to stop the build when a problem is
# encountered rather than display an error.
('strict', config_options.Type(bool, default=False)),
+
+ # extra is a mapping/dictionary of data that is passed to the template.
+ # This allows template authors to require extra configuration that not
+ # relevant to all themes and doesn't need to be explicitly supported by
+ # MkDocs itself. A good example here would be including the current
+ # project version.
+ ('extra', config_options.Type(dict, default={})),
)
diff --git a/mkdocs/gh_deploy.py b/mkdocs/gh_deploy.py
index 4e07a0a5..f5692d2d 100644
--- a/mkdocs/gh_deploy.py
+++ b/mkdocs/gh_deploy.py
@@ -1,19 +1,15 @@
-import logging
+from __future__ import print_function
import subprocess
import os
-log = logging.getLogger(__name__)
-
def gh_deploy(config):
if not os.path.exists('.git'):
- log.info('Cannot deploy - this directory does not appear to be a git '
- 'repository')
+ print('Cannot deploy - this directory does not appear to be a git repository')
return
- log.info("Copying '%s' to `gh-pages` branch and pushing to GitHub.",
- config['site_dir'])
+ print("Copying '%s' to `gh-pages` branch and pushing to GitHub." % config['site_dir'])
try:
command = ['ghp-import', '-p', config['site_dir']]
if 'remote_branch' in config:
@@ -27,16 +23,13 @@ def gh_deploy(config):
# This GitHub pages repository has a CNAME configured.
with(open('CNAME', 'r')) as f:
cname_host = f.read().strip()
- log.info('Based on your CNAME file, your documentation should be '
- 'available shortly at: http://%s', cname_host)
- log.info('NOTE: Your DNS records must be configured appropriately for '
- 'your CNAME URL to work.')
+ print('Based on your CNAME file, your documentation should be available shortly at: http://%s' % cname_host)
+ print('NOTE: Your DNS records must be configured appropriately for your CNAME URL to work.')
return
# No CNAME found. We will use the origin URL to determine the GitHub
# pages location.
- url = subprocess.check_output(["git", "config", "--get",
- "remote.origin.url"])
+ url = subprocess.check_output(["git", "config", "--get", "remote.origin.url"])
url = url.decode('utf-8').strip()
host = None
@@ -48,10 +41,10 @@ def gh_deploy(config):
if host is None:
# This could be a GitHub Enterprise deployment.
- log.info('Your documentation should be available shortly.')
+ print('Your documentation should be available shortly.')
else:
username, repo = path.split('/', 1)
if repo.endswith('.git'):
repo = repo[:-len('.git')]
url = 'http://%s.github.io/%s' % (username, repo)
- log.info('Your documentation should shortly be available at: ' + url)
+ print('Your documentation should shortly be available at: ' + url)
diff --git a/mkdocs/new.py b/mkdocs/new.py
index 165d124d..4f3420f9 100644
--- a/mkdocs/new.py
+++ b/mkdocs/new.py
@@ -1,8 +1,7 @@
# coding: utf-8
-from __future__ import unicode_literals
+from __future__ import print_function, unicode_literals
import os
-import logging
from io import open
config_text = 'site_name: My Docs\n'
@@ -25,8 +24,6 @@ For full documentation visit [mkdocs.org](http://mkdocs.org).
... # Other markdown pages, images and other files.
"""
-log = logging.getLogger(__name__)
-
def new(output_dir):
@@ -35,20 +32,20 @@ def new(output_dir):
index_path = os.path.join(docs_dir, 'index.md')
if os.path.exists(config_path):
- log.info('Project already exists.')
+ print('Project already exists.')
return
if not os.path.exists(output_dir):
- log.info('Creating project directory: %s', output_dir)
+ print('Creating project directory: %s' % output_dir)
os.mkdir(output_dir)
- log.info('Writing config file: %s', config_path)
+ print('Writing config file: %s' % config_path)
open(config_path, 'w', encoding='utf-8').write(config_text)
if os.path.exists(index_path):
return
- log.info('Writing initial docs: %s', index_path)
+ print('Writing initial docs: %s' % index_path)
if not os.path.exists(docs_dir):
os.mkdir(docs_dir)
open(index_path, 'w', encoding='utf-8').write(index_text)
| Global template variables?
This is more of a question (and potentially a feature request if this isn't supported) than an issue – is there some way to declare global variables?
For example, in my config.yml, I'd like to define some global variable, `version-num` that, of course, represents the current version of the library that I'm documenting. I'd naturally like to use this all over in my documentation and have only one place to update the version number when releasing a new version – in config.yml.
Though I've tried to do this and beyond the pre-defined variables in the mkdocs documentation, nothing that I declare seems to be picked up.
Is there some way to do this that I don't see?
PS, Jekyll allows for this, so I'm basically assuming the same semantics as Jekyll, i.e., that user-defined variables in config.yml are globally accessible | mkdocs/mkdocs | diff --git a/mkdocs/tests/build_tests.py b/mkdocs/tests/build_tests.py
index 7f2a04a7..96f3b5b0 100644
--- a/mkdocs/tests/build_tests.py
+++ b/mkdocs/tests/build_tests.py
@@ -7,6 +7,7 @@ import tempfile
import unittest
from six.moves import zip
+import mock
from mkdocs import build, nav
from mkdocs.config import base as config_base, defaults as config_defaults
@@ -343,3 +344,22 @@ class BuildTests(unittest.TestCase):
""")
self.assertEqual(html.strip(), expected_html)
+
+ def test_extra_context(self):
+
+ # Same as the default schema, but don't verify the docs_dir exists.
+ config = config_base.Config(schema=config_defaults.DEFAULT_SCHEMA)
+ config.load_dict({
+ 'site_name': "Site",
+ 'extra': {
+ 'a': 1
+ }
+ })
+
+ self.assertEqual(config.validate(), ([], []))
+
+ context = build.get_global_context(mock.Mock(), config)
+
+ self.assertEqual(context['extra'], {
+ 'a': 1
+ })
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 1,
"issue_text_score": 1,
"test_score": 1
},
"num_modified_files": 7
} | 0.12 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"coverage",
"flake8",
"nose",
"mock",
"pytest"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.9",
"reqs_path": [
"requirements/project.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | click==8.1.8
coverage==7.8.0
exceptiongroup==1.2.2
flake8==7.2.0
ghp-import==2.1.0
importlib_metadata==8.6.1
iniconfig==2.1.0
Jinja2==3.1.6
livereload==2.7.1
Markdown==3.7
MarkupSafe==3.0.2
mccabe==0.7.0
-e git+https://github.com/mkdocs/mkdocs.git@5b8bae094b2cfbc3cb9ef2f77cee4c1271abd3e2#egg=mkdocs
mock==5.2.0
nose==1.3.7
packaging==24.2
pluggy==1.5.0
pycodestyle==2.13.0
pyflakes==3.3.1
pytest==8.3.5
python-dateutil==2.9.0.post0
PyYAML==6.0.2
six==1.17.0
tomli==2.2.1
tornado==6.4.2
zipp==3.21.0
| name: mkdocs
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=3.0.16=h5eee18b_0
- pip=25.0=py39h06a4308_0
- python=3.9.21=he870216_1
- readline=8.2=h5eee18b_0
- setuptools=75.8.0=py39h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- tzdata=2025a=h04d1e81_0
- wheel=0.45.1=py39h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- click==8.1.8
- coverage==7.8.0
- exceptiongroup==1.2.2
- flake8==7.2.0
- ghp-import==2.1.0
- importlib-metadata==8.6.1
- iniconfig==2.1.0
- jinja2==3.1.6
- livereload==2.7.1
- markdown==3.7
- markupsafe==3.0.2
- mccabe==0.7.0
- mock==5.2.0
- nose==1.3.7
- packaging==24.2
- pluggy==1.5.0
- pycodestyle==2.13.0
- pyflakes==3.3.1
- pytest==8.3.5
- python-dateutil==2.9.0.post0
- pyyaml==6.0.2
- six==1.17.0
- tomli==2.2.1
- tornado==6.4.2
- zipp==3.21.0
prefix: /opt/conda/envs/mkdocs
| [
"mkdocs/tests/build_tests.py::BuildTests::test_extra_context"
] | [
"mkdocs/tests/build_tests.py::BuildTests::test_anchor_only_link",
"mkdocs/tests/build_tests.py::BuildTests::test_convert_internal_asbolute_media",
"mkdocs/tests/build_tests.py::BuildTests::test_convert_internal_link",
"mkdocs/tests/build_tests.py::BuildTests::test_convert_internal_link_differing_directory",
"mkdocs/tests/build_tests.py::BuildTests::test_convert_internal_link_with_anchor",
"mkdocs/tests/build_tests.py::BuildTests::test_convert_internal_media",
"mkdocs/tests/build_tests.py::BuildTests::test_convert_markdown",
"mkdocs/tests/build_tests.py::BuildTests::test_convert_multiple_internal_links",
"mkdocs/tests/build_tests.py::BuildTests::test_copying_media",
"mkdocs/tests/build_tests.py::BuildTests::test_dont_convert_code_block_urls",
"mkdocs/tests/build_tests.py::BuildTests::test_empty_document",
"mkdocs/tests/build_tests.py::BuildTests::test_extension_config",
"mkdocs/tests/build_tests.py::BuildTests::test_ignore_external_link",
"mkdocs/tests/build_tests.py::BuildTests::test_markdown_custom_extension",
"mkdocs/tests/build_tests.py::BuildTests::test_markdown_duplicate_custom_extension",
"mkdocs/tests/build_tests.py::BuildTests::test_markdown_fenced_code_extension",
"mkdocs/tests/build_tests.py::BuildTests::test_markdown_table_extension",
"mkdocs/tests/build_tests.py::BuildTests::test_not_use_directory_urls",
"mkdocs/tests/build_tests.py::BuildTests::test_strict_mode_invalid",
"mkdocs/tests/build_tests.py::BuildTests::test_strict_mode_valid"
] | [] | [] | BSD 2-Clause "Simplified" License | 131 |
|
mne-tools__mne-python-2076 | 7f8071891d7a8c2fdaa61ea3a8819394fcd86de2 | 2015-05-09 22:40:37 | edceb8f38349d6dc0cade1c9f8384cc0707ce3e8 | diff --git a/mne/datasets/sample/__init__.py b/mne/datasets/sample/__init__.py
index 1a278cfcc..3e4de83f4 100644
--- a/mne/datasets/sample/__init__.py
+++ b/mne/datasets/sample/__init__.py
@@ -1,4 +1,4 @@
"""MNE sample dataset
"""
-from .sample import data_path, has_sample_data
+from .sample import data_path, has_sample_data, get_version
diff --git a/mne/datasets/sample/sample.py b/mne/datasets/sample/sample.py
index 87ed46446..15d4b1281 100644
--- a/mne/datasets/sample/sample.py
+++ b/mne/datasets/sample/sample.py
@@ -5,7 +5,8 @@
from ...utils import verbose
from ...fixes import partial
-from ..utils import has_dataset, _data_path, _doc
+from ..utils import (has_dataset, _data_path, _data_path_doc,
+ _get_version, _version_doc)
has_sample_data = partial(has_dataset, name='sample')
@@ -18,5 +19,11 @@ def data_path(path=None, force_update=False, update_path=True, download=True,
update_path=update_path, name='sample',
download=download)
-data_path.__doc__ = _doc.format(name='sample',
- conf='MNE_DATASETS_SAMPLE_PATH')
+data_path.__doc__ = _data_path_doc.format(name='sample',
+ conf='MNE_DATASETS_SAMPLE_PATH')
+
+
+def get_version():
+ return _get_version('sample')
+
+get_version.__doc__ = _version_doc.format(name='sample')
diff --git a/mne/datasets/somato/__init__.py b/mne/datasets/somato/__init__.py
index ab144bc9d..aa3f82d8d 100644
--- a/mne/datasets/somato/__init__.py
+++ b/mne/datasets/somato/__init__.py
@@ -1,4 +1,4 @@
"""Somatosensory dataset
"""
-from .somato import data_path, has_somato_data
+from .somato import data_path, has_somato_data, get_version
diff --git a/mne/datasets/somato/somato.py b/mne/datasets/somato/somato.py
index 525f2af3d..d0daf987b 100644
--- a/mne/datasets/somato/somato.py
+++ b/mne/datasets/somato/somato.py
@@ -1,11 +1,12 @@
-# Authors: Alexandre Gramfort <[email protected]>
+# Authors: Alexandre Gramfort <[email protected]>
# Martin Luessi <[email protected]>
# Eric Larson <[email protected]>
# License: BSD Style.
from ...utils import verbose
from ...fixes import partial
-from ..utils import has_dataset, _data_path, _doc
+from ..utils import (has_dataset, _data_path, _data_path_doc,
+ _get_version, _version_doc)
has_somato_data = partial(has_dataset, name='somato')
@@ -18,5 +19,11 @@ def data_path(path=None, force_update=False, update_path=True, download=True,
update_path=update_path, name='somato',
download=download)
-data_path.__doc__ = _doc.format(name='somato',
- conf='MNE_DATASETS_SOMATO_PATH')
+data_path.__doc__ = _data_path_doc.format(name='somato',
+ conf='MNE_DATASETS_SOMATO_PATH')
+
+
+def get_version():
+ return _get_version('somato')
+
+get_version.__doc__ = _version_doc.format(name='somato')
diff --git a/mne/datasets/spm_face/__init__.py b/mne/datasets/spm_face/__init__.py
index 43b513e9f..90f01c728 100644
--- a/mne/datasets/spm_face/__init__.py
+++ b/mne/datasets/spm_face/__init__.py
@@ -1,4 +1,4 @@
"""SPM face dataset
"""
-from .spm_data import data_path, has_spm_data
+from .spm_data import data_path, has_spm_data, get_version
diff --git a/mne/datasets/spm_face/spm_data.py b/mne/datasets/spm_face/spm_data.py
index ca681de16..19c6461ee 100644
--- a/mne/datasets/spm_face/spm_data.py
+++ b/mne/datasets/spm_face/spm_data.py
@@ -4,7 +4,8 @@
from ...utils import verbose
from ...fixes import partial
-from ..utils import has_dataset, _data_path, _doc
+from ..utils import (has_dataset, _data_path, _data_path_doc,
+ _get_version, _version_doc)
has_spm_data = partial(has_dataset, name='spm')
@@ -17,5 +18,11 @@ def data_path(path=None, force_update=False, update_path=True, download=True,
update_path=update_path, name='spm',
download=download)
-data_path.__doc__ = _doc.format(name='spm',
- conf='MNE_DATASETS_SPM_DATA_PATH')
+data_path.__doc__ = _data_path_doc.format(name='spm',
+ conf='MNE_DATASETS_SPM_DATA_PATH')
+
+
+def get_version():
+ return _get_version('spm')
+
+get_version.__doc__ = _version_doc.format(name='spm')
diff --git a/mne/datasets/utils.py b/mne/datasets/utils.py
index 3ede4d718..be6f5fb0d 100644
--- a/mne/datasets/utils.py
+++ b/mne/datasets/utils.py
@@ -17,7 +17,7 @@ from ..externals.six import string_types
from ..externals.six.moves import input
-_doc = """Get path to local copy of {name} dataset
+_data_path_doc = """Get path to local copy of {name} dataset
Parameters
----------
@@ -49,6 +49,16 @@ _doc = """Get path to local copy of {name} dataset
"""
+_version_doc = """Get version of the local {name} dataset
+
+ Returns
+ -------
+ version : str | None
+ Version of the {name} local dataset, or None if the dataset
+ does not exist locally.
+"""
+
+
def _dataset_version(path, name):
"""Get the version of the dataset"""
ver_fname = op.join(path, 'version.txt')
@@ -64,7 +74,7 @@ def _dataset_version(path, name):
def _data_path(path=None, force_update=False, update_path=True, download=True,
- name=None, check_version=True):
+ name=None, check_version=False, return_version=False):
"""Aux function
"""
key = {'sample': 'MNE_DATASETS_SAMPLE_PATH',
@@ -229,8 +239,14 @@ def _data_path(path=None, force_update=False, update_path=True, download=True,
'you may need to update the {name} dataset by using '
'mne.datasets.{name}.data_path(force_update=True)'.format(
name=name, current=data_version, newest=mne_version))
+ return (path, data_version) if return_version else path
+
- return path
+def _get_version(name):
+ """Helper to get a dataset version"""
+ if not has_dataset(name):
+ return None
+ return _data_path(name=name, return_version=True)[1]
def has_dataset(name):
diff --git a/mne/io/base.py b/mne/io/base.py
index 501e8a7f1..cb3623324 100644
--- a/mne/io/base.py
+++ b/mne/io/base.py
@@ -1054,6 +1054,7 @@ class _BaseRaw(ProjMixin, ContainsMixin, PickDropChannelsMixin,
block : bool
Whether to halt program execution until the figure is closed.
Useful for setting bad channels on the fly (click on line).
+ May not work on all systems / platforms.
highpass : float | None
Highpass to apply when displaying data.
lowpass : float | None
diff --git a/mne/viz/raw.py b/mne/viz/raw.py
index 518280032..1bea5a1f4 100644
--- a/mne/viz/raw.py
+++ b/mne/viz/raw.py
@@ -373,6 +373,7 @@ def plot_raw(raw, events=None, duration=10.0, start=0.0, n_channels=None,
block : bool
Whether to halt program execution until the figure is closed.
Useful for setting bad channels on the fly by clicking on a line.
+ May not work on all systems / platforms.
highpass : float | None
Highpass to apply when displaying data.
lowpass : float | None
@@ -623,7 +624,10 @@ def plot_raw(raw, events=None, duration=10.0, start=0.0, n_channels=None,
_toggle_options(None, params)
if show:
- plt.show(block=block)
+ try:
+ plt.show(block=block)
+ except TypeError: # not all versions have this
+ plt.show()
return fig
diff --git a/setup.py b/setup.py
index 9cbd8af53..353d7c37d 100755
--- a/setup.py
+++ b/setup.py
@@ -71,6 +71,7 @@ if __name__ == "__main__":
'mne.datasets.somato',
'mne.datasets.spm_face',
'mne.datasets.testing',
+ 'mne.datasets.tests',
'mne.externals',
'mne.io', 'mne.io.tests',
'mne.io.array', 'mne.io.array.tests',
| Q: Dataset versions
Have we gotten any useful information from embedding dataset versions in our tarballs? As far as I can tell it has just led to a bunch of warnings when doing imports (see e.g. Mainak's recent notebook examples). I propose we get rid of them for now, and replace them with a new system in the future if need be. But for now I think it's beyond YAGNI and into the adding-annoyance category... | mne-tools/mne-python | diff --git a/mne/datasets/testing/__init__.py b/mne/datasets/testing/__init__.py
index 816bbf18a..7fa74ee41 100644
--- a/mne/datasets/testing/__init__.py
+++ b/mne/datasets/testing/__init__.py
@@ -1,4 +1,4 @@
"""MNE sample dataset
"""
-from ._testing import data_path, requires_testing_data
+from ._testing import data_path, requires_testing_data, get_version
diff --git a/mne/datasets/testing/_testing.py b/mne/datasets/testing/_testing.py
index fe23cf4fb..932bd2e20 100644
--- a/mne/datasets/testing/_testing.py
+++ b/mne/datasets/testing/_testing.py
@@ -7,7 +7,8 @@ import numpy as np
from ...utils import verbose, get_config
from ...fixes import partial
-from ..utils import has_dataset, _data_path, _doc
+from ..utils import (has_dataset, _data_path, _data_path_doc,
+ _get_version, _version_doc)
has_testing_data = partial(has_dataset, name='testing')
@@ -24,8 +25,14 @@ def data_path(path=None, force_update=False, update_path=True,
update_path=update_path, name='testing',
download=download)
-data_path.__doc__ = _doc.format(name='testing',
- conf='MNE_DATASETS_TESTING_PATH')
+data_path.__doc__ = _data_path_doc.format(name='testing',
+ conf='MNE_DATASETS_TESTING_PATH')
+
+
+def get_version():
+ return _get_version('testing')
+
+get_version.__doc__ = _version_doc.format(name='testing')
# Allow forcing of testing dataset skip (for Debian tests) using:
diff --git a/mne/datasets/tests/__init__.py b/mne/datasets/tests/__init__.py
new file mode 100644
index 000000000..e69de29bb
diff --git a/mne/datasets/tests/test_datasets.py b/mne/datasets/tests/test_datasets.py
new file mode 100644
index 000000000..76bacaa14
--- /dev/null
+++ b/mne/datasets/tests/test_datasets.py
@@ -0,0 +1,15 @@
+from nose.tools import assert_true
+
+from mne import datasets
+from mne.externals.six import string_types
+
+
+def test_datasets():
+ """Test simple dataset functions
+ """
+ for dname in ('sample', 'somato', 'spm_face', 'testing'):
+ dataset = getattr(datasets, dname)
+ if dataset.data_path(download=False) != '':
+ assert_true(isinstance(dataset.get_version(), string_types))
+ else:
+ assert_true(dataset.get_version() is None)
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 2,
"issue_text_score": 2,
"test_score": 3
},
"num_modified_files": 10
} | 0.8 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[dev]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"numpy>=1.16.0",
"pandas>=1.0.0",
"scikit-learn",
"h5py",
"pysurfer",
"nose",
"nose-timer",
"pytest"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.7",
"reqs_path": [
"requirements/base.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | apptools==5.2.1
certifi @ file:///croot/certifi_1671487769961/work/certifi
configobj==5.0.9
cycler==0.11.0
envisage==7.0.3
exceptiongroup==1.2.2
fonttools==4.38.0
h5py==3.8.0
importlib-metadata==6.7.0
importlib-resources==5.12.0
iniconfig==2.0.0
joblib==1.3.2
kiwisolver==1.4.5
matplotlib==3.5.3
mayavi==4.8.1
-e git+https://github.com/mne-tools/mne-python.git@7f8071891d7a8c2fdaa61ea3a8819394fcd86de2#egg=mne
nibabel==4.0.2
nose==1.3.7
nose-timer==1.0.1
numpy==1.21.6
packaging==24.0
pandas==1.3.5
Pillow==9.5.0
pluggy==1.2.0
pyface==8.0.0
Pygments==2.17.2
pyparsing==3.1.4
pysurfer==0.11.2
pytest==7.4.4
python-dateutil==2.9.0.post0
pytz==2025.2
scikit-learn==1.0.2
scipy==1.7.3
six==1.17.0
threadpoolctl==3.1.0
tomli==2.0.1
traits==6.4.3
traitsui==8.0.0
typing_extensions==4.7.1
vtk==9.3.1
zipp==3.15.0
| name: mne-python
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2022.12.7=py37h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- pip=22.3.1=py37h06a4308_0
- python=3.7.16=h7a1cb2a_0
- readline=8.2=h5eee18b_0
- setuptools=65.6.3=py37h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- wheel=0.38.4=py37h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- apptools==5.2.1
- configobj==5.0.9
- cycler==0.11.0
- envisage==7.0.3
- exceptiongroup==1.2.2
- fonttools==4.38.0
- h5py==3.8.0
- importlib-metadata==6.7.0
- importlib-resources==5.12.0
- iniconfig==2.0.0
- joblib==1.3.2
- kiwisolver==1.4.5
- matplotlib==3.5.3
- mayavi==4.8.1
- nibabel==4.0.2
- nose==1.3.7
- nose-timer==1.0.1
- numpy==1.21.6
- packaging==24.0
- pandas==1.3.5
- pillow==9.5.0
- pluggy==1.2.0
- pyface==8.0.0
- pygments==2.17.2
- pyparsing==3.1.4
- pysurfer==0.11.2
- pytest==7.4.4
- python-dateutil==2.9.0.post0
- pytz==2025.2
- scikit-learn==1.0.2
- scipy==1.7.3
- six==1.17.0
- threadpoolctl==3.1.0
- tomli==2.0.1
- traits==6.4.3
- traitsui==8.0.0
- typing-extensions==4.7.1
- vtk==9.3.1
- zipp==3.15.0
prefix: /opt/conda/envs/mne-python
| [
"mne/datasets/tests/test_datasets.py::test_datasets"
] | [] | [] | [] | BSD 3-Clause "New" or "Revised" License | 132 |
|
pre-commit__pre-commit-226 | d97ea30c4bb309a2877fed95323ac8c793c0679f | 2015-05-10 16:40:06 | 9515ca06378d74f1e4f8013db2b5230c1f15edaa | coveralls:
[](https://coveralls.io/builds/2530482)
Coverage decreased (-0.07%) to 99.93% when pulling **8aa931ef823fbeda568db1d3c50c55b04d83fa2e on Lucas-C:master** into **d97ea30c4bb309a2877fed95323ac8c793c0679f on pre-commit:master**.
coveralls:
[](https://coveralls.io/builds/2530482)
Coverage decreased (-0.07%) to 99.93% when pulling **8aa931ef823fbeda568db1d3c50c55b04d83fa2e on Lucas-C:master** into **d97ea30c4bb309a2877fed95323ac8c793c0679f on pre-commit:master**.
coveralls:
[](https://coveralls.io/builds/2530482)
Coverage decreased (-0.07%) to 99.93% when pulling **8aa931ef823fbeda568db1d3c50c55b04d83fa2e on Lucas-C:master** into **d97ea30c4bb309a2877fed95323ac8c793c0679f on pre-commit:master**.
asottile: :+1: Looks great, address my last couple comments and I'll merge it
coveralls:
[](https://coveralls.io/builds/2530626)
Coverage remained the same at 100.0% when pulling **e1098d96177b1558c586b369b6d6729d8fa1c19c on Lucas-C:master** into **d97ea30c4bb309a2877fed95323ac8c793c0679f on pre-commit:master**.
Lucas-C: Thanks for all your comments !
Everything should be fixed now :)
coveralls:
[](https://coveralls.io/builds/2530648)
Coverage remained the same at 100.0% when pulling **f5504c1f257e8041bc977de64cfb89139d88d676 on Lucas-C:master** into **d97ea30c4bb309a2877fed95323ac8c793c0679f on pre-commit:master**.
Lucas-C: I guess one last to do will be to update the docs :smile: | diff --git a/pre_commit/clientlib/validate_config.py b/pre_commit/clientlib/validate_config.py
index 44c7cd8..bdd0e2c 100644
--- a/pre_commit/clientlib/validate_config.py
+++ b/pre_commit/clientlib/validate_config.py
@@ -6,6 +6,13 @@ from pre_commit.clientlib.validate_base import is_regex_valid
from pre_commit.errors import FatalError
+_LOCAL_HOOKS_MAGIC_REPO_STRING = 'local'
+
+
+def is_local_hooks(repo_entry):
+ return repo_entry['repo'] == _LOCAL_HOOKS_MAGIC_REPO_STRING
+
+
class InvalidConfigError(FatalError):
pass
@@ -53,7 +60,12 @@ def try_regex(repo, hook, value, field_name):
def validate_config_extra(config):
for repo in config:
- if 'sha' not in repo:
+ if is_local_hooks(repo):
+ if 'sha' in repo:
+ raise InvalidConfigError(
+ '"sha" property provided for local hooks'
+ )
+ elif 'sha' not in repo:
raise InvalidConfigError(
'Missing "sha" field for repository {0}'.format(repo['repo'])
)
diff --git a/pre_commit/commands/run.py b/pre_commit/commands/run.py
index 4e3fb18..5e8745b 100644
--- a/pre_commit/commands/run.py
+++ b/pre_commit/commands/run.py
@@ -18,15 +18,6 @@ from pre_commit.util import noop_context
logger = logging.getLogger('pre_commit')
-class HookExecutor(object):
- def __init__(self, hook, invoker):
- self.hook = hook
- self._invoker = invoker
-
- def invoke(self, filenames):
- return self._invoker(self.hook, filenames)
-
-
def _get_skips(environ):
skips = environ.get('SKIP', '')
return set(skip.strip() for skip in skips.split(',') if skip.strip())
@@ -80,8 +71,7 @@ def get_filenames(args, include_expr, exclude_expr):
return getter(include_expr, exclude_expr)
-def _run_single_hook(hook_executor, args, write, skips=frozenset()):
- hook = hook_executor.hook
+def _run_single_hook(hook, repo, args, write, skips=frozenset()):
filenames = get_filenames(args, hook['files'], hook['exclude'])
if hook['id'] in skips:
_print_user_skipped(hook, write, args)
@@ -95,7 +85,7 @@ def _run_single_hook(hook_executor, args, write, skips=frozenset()):
write(get_hook_message(_hook_msg_start(hook, args.verbose), end_len=6))
sys.stdout.flush()
- retcode, stdout, stderr = hook_executor.invoke(filenames)
+ retcode, stdout, stderr = repo.run_hook(hook, filenames)
if retcode != hook['expected_return_value']:
retcode = 1
@@ -119,19 +109,19 @@ def _run_single_hook(hook_executor, args, write, skips=frozenset()):
return retcode
-def _run_hooks(hook_executors, args, write, environ):
+def _run_hooks(repo_hooks, args, write, environ):
"""Actually run the hooks."""
skips = _get_skips(environ)
retval = 0
- for hook_executor in hook_executors:
- retval |= _run_single_hook(hook_executor, args, write, skips)
+ for repo, hook in repo_hooks:
+ retval |= _run_single_hook(hook, repo, args, write, skips)
return retval
-def get_hook_executors(runner):
+def get_repo_hooks(runner):
for repo in runner.repositories:
- for _, repo_hook in repo.hooks:
- yield HookExecutor(repo_hook, repo.run_hook)
+ for _, hook in repo.hooks:
+ yield (repo, hook)
def _has_unmerged_paths(runner):
@@ -159,13 +149,13 @@ def run(runner, args, write=sys_stdout_write_wrapper, environ=os.environ):
ctx = staged_files_only(runner.cmd_runner)
with ctx:
- hook_executors = list(get_hook_executors(runner))
+ repo_hooks = list(get_repo_hooks(runner))
if args.hook:
- hook_executors = [
- he for he in hook_executors
- if he.hook['id'] == args.hook
+ repo_hooks = [
+ (repo, hook) for repo, hook in repo_hooks
+ if hook['id'] == args.hook
]
- if not hook_executors:
+ if not repo_hooks:
write('No hook with id `{0}`\n'.format(args.hook))
return 1
- return _run_hooks(hook_executors, args, write, environ)
+ return _run_hooks(repo_hooks, args, write, environ)
diff --git a/pre_commit/repository.py b/pre_commit/repository.py
index cbe0535..7ca6a44 100644
--- a/pre_commit/repository.py
+++ b/pre_commit/repository.py
@@ -5,6 +5,10 @@ import shutil
from cached_property import cached_property
+from pre_commit import git
+from pre_commit.clientlib.validate_config import is_local_hooks
+from pre_commit.clientlib.validate_manifest import MANIFEST_JSON_SCHEMA
+from pre_commit.jsonschema_extensions import apply_defaults
from pre_commit.languages.all import languages
from pre_commit.manifest import Manifest
from pre_commit.prefixed_command_runner import PrefixedCommandRunner
@@ -21,10 +25,13 @@ class Repository(object):
@classmethod
def create(cls, config, store):
- repo_path_getter = store.get_repo_path_getter(
- config['repo'], config['sha']
- )
- return cls(config, repo_path_getter)
+ if is_local_hooks(config):
+ return LocalRepository(config)
+ else:
+ repo_path_getter = store.get_repo_path_getter(
+ config['repo'], config['sha']
+ )
+ return cls(config, repo_path_getter)
@cached_property
def repo_url(self):
@@ -111,3 +118,28 @@ class Repository(object):
return languages[hook['language']].run_hook(
self.cmd_runner, hook, file_args,
)
+
+
+class LocalRepository(Repository):
+ def __init__(self, repo_config, repo_path_getter=None):
+ repo_path_getter = None
+ super(LocalRepository, self).__init__(repo_config, repo_path_getter)
+
+ @cached_property
+ def hooks(self):
+ return tuple(
+ (hook['id'], apply_defaults(hook, MANIFEST_JSON_SCHEMA['items']))
+ for hook in self.repo_config['hooks']
+ )
+
+ @cached_property
+ def cmd_runner(self):
+ return PrefixedCommandRunner(git.get_root())
+
+ @cached_property
+ def sha(self):
+ raise NotImplementedError
+
+ @cached_property
+ def manifest(self):
+ raise NotImplementedError
| Add support for pcre / scripts / system hooks definition in .pre-commit-config.yaml
Everything is in the title :)
_Rationale:_ a `pre-commit` user shouldn't have to setup a git repository to configure a pre-commit check that can be defined in 5 lines or less.
_Example:_ taken the from [do_not_commit](https://github.com/pricematch/pricematch-pre-commit-hooks/blob/master/hooks.yaml) hook:
- id: do_not_commit
name: Block if "DO NOT COMMIT" is found
entry: DO NOT COMMIT
language: pcre
files: ^(.*)$
_Suggested solutions:_
1. Allow for pcre / scripts / system hooks definition in _.pre-commit-config.yaml_
2. Allow for the `repo` field in _.pre-commit-config.yaml_ to point to a subfolder (of the git repo configured with `pre-commit`) that contains a _hooks.yaml_ .
This currently crashes because `pre-commit` expect to find git repository in the folder point by `repo`. | pre-commit/pre-commit | diff --git a/testing/fixtures.py b/testing/fixtures.py
index 1b1b802..1c0184a 100644
--- a/testing/fixtures.py
+++ b/testing/fixtures.py
@@ -60,12 +60,16 @@ def write_config(directory, config):
config_file.write(ordered_dump([config], **C.YAML_DUMP_KWARGS))
-def make_consuming_repo(tmpdir_factory, repo_source):
- path = make_repo(tmpdir_factory, repo_source)
- config = make_config_from_repo(path)
- git_path = git_dir(tmpdir_factory)
+def add_config_to_repo(git_path, config):
write_config(git_path, config)
with cwd(git_path):
cmd_output('git', 'add', C.CONFIG_FILE)
cmd_output('git', 'commit', '-m', 'Add hooks config')
return git_path
+
+
+def make_consuming_repo(tmpdir_factory, repo_source):
+ path = make_repo(tmpdir_factory, repo_source)
+ config = make_config_from_repo(path)
+ git_path = git_dir(tmpdir_factory)
+ return add_config_to_repo(git_path, config)
diff --git a/tests/clientlib/validate_config_test.py b/tests/clientlib/validate_config_test.py
index 51eb7e4..c507f28 100644
--- a/tests/clientlib/validate_config_test.py
+++ b/tests/clientlib/validate_config_test.py
@@ -1,5 +1,6 @@
from __future__ import unicode_literals
+import jsonschema
import pytest
from pre_commit.clientlib.validate_config import CONFIG_JSON_SCHEMA
@@ -25,7 +26,7 @@ def test_run(input, expected_output):
assert run(input) == expected_output
[email protected](('manifest_obj', 'expected'), (
[email protected](('config_obj', 'expected'), (
([], False),
(
[{
@@ -66,8 +67,8 @@ def test_run(input, expected_output):
False,
),
))
-def test_is_valid_according_to_schema(manifest_obj, expected):
- ret = is_valid_according_to_schema(manifest_obj, CONFIG_JSON_SCHEMA)
+def test_is_valid_according_to_schema(config_obj, expected):
+ ret = is_valid_according_to_schema(config_obj, CONFIG_JSON_SCHEMA)
assert ret is expected
@@ -121,3 +122,55 @@ def test_config_with_ok_exclude_regex_passes():
CONFIG_JSON_SCHEMA,
)
validate_config_extra(config)
+
+
[email protected]('config_obj', (
+ [{
+ 'repo': 'local',
+ 'sha': 'foo',
+ 'hooks': [{
+ 'id': 'do_not_commit',
+ 'name': 'Block if "DO NOT COMMIT" is found',
+ 'entry': 'DO NOT COMMIT',
+ 'language': 'pcre',
+ 'files': '^(.*)$',
+ }],
+ }],
+))
+def test_config_with_local_hooks_definition_fails(config_obj):
+ with pytest.raises((
+ jsonschema.exceptions.ValidationError, InvalidConfigError
+ )):
+ jsonschema.validate(config_obj, CONFIG_JSON_SCHEMA)
+ config = apply_defaults(config_obj, CONFIG_JSON_SCHEMA)
+ validate_config_extra(config)
+
+
[email protected]('config_obj', (
+ [{
+ 'repo': 'local',
+ 'hooks': [{
+ 'id': 'arg-per-line',
+ 'name': 'Args per line hook',
+ 'entry': 'bin/hook.sh',
+ 'language': 'script',
+ 'files': '',
+ 'args': ['hello', 'world'],
+ }],
+ }],
+ [{
+ 'repo': 'local',
+ 'hooks': [{
+ 'id': 'arg-per-line',
+ 'name': 'Args per line hook',
+ 'entry': 'bin/hook.sh',
+ 'language': 'script',
+ 'files': '',
+ 'args': ['hello', 'world'],
+ }]
+ }],
+))
+def test_config_with_local_hooks_definition_passes(config_obj):
+ jsonschema.validate(config_obj, CONFIG_JSON_SCHEMA)
+ config = apply_defaults(config_obj, CONFIG_JSON_SCHEMA)
+ validate_config_extra(config)
diff --git a/tests/commands/run_test.py b/tests/commands/run_test.py
index 9cca610..aad0611 100644
--- a/tests/commands/run_test.py
+++ b/tests/commands/run_test.py
@@ -14,10 +14,12 @@ from pre_commit.commands.run import _get_skips
from pre_commit.commands.run import _has_unmerged_paths
from pre_commit.commands.run import get_changed_files
from pre_commit.commands.run import run
+from pre_commit.ordereddict import OrderedDict
from pre_commit.runner import Runner
from pre_commit.util import cmd_output
from pre_commit.util import cwd
from testing.auto_namedtuple import auto_namedtuple
+from testing.fixtures import add_config_to_repo
from testing.fixtures import make_consuming_repo
@@ -81,7 +83,7 @@ def _test_run(repo, options, expected_outputs, expected_ret, stage):
stage_a_file()
args = _get_opts(**options)
ret, printed = _do_run(repo, args)
- assert ret == expected_ret
+ assert ret == expected_ret, (ret, expected_ret, printed)
for expected_output_part in expected_outputs:
assert expected_output_part in printed
@@ -313,9 +315,7 @@ def test_lots_of_files(mock_out_store_directory, tmpdir_factory):
git_path = make_consuming_repo(tmpdir_factory, 'python_hooks_repo')
with cwd(git_path):
# Override files so we run against them
- with io.open(
- '.pre-commit-config.yaml', 'a+',
- ) as config_file:
+ with io.open('.pre-commit-config.yaml', 'a+') as config_file:
config_file.write(' files: ""\n')
# Write a crap ton of files
@@ -334,3 +334,66 @@ def test_lots_of_files(mock_out_store_directory, tmpdir_factory):
stderr=subprocess.STDOUT,
env=env,
)
+
+
+def test_local_hook_passes(
+ repo_with_passing_hook, mock_out_store_directory,
+):
+ config = OrderedDict((
+ ('repo', 'local'),
+ ('hooks', (OrderedDict((
+ ('id', 'pylint'),
+ ('name', 'PyLint'),
+ ('entry', 'python -m pylint.__main__'),
+ ('language', 'system'),
+ ('files', r'\.py$'),
+ )), OrderedDict((
+ ('id', 'do_not_commit'),
+ ('name', 'Block if "DO NOT COMMIT" is found'),
+ ('entry', 'DO NOT COMMIT'),
+ ('language', 'pcre'),
+ ('files', '^(.*)$'),
+ ))))
+ ))
+ add_config_to_repo(repo_with_passing_hook, config)
+
+ with io.open('dummy.py', 'w') as staged_file:
+ staged_file.write('"""TODO: something"""\n')
+ cmd_output('git', 'add', 'dummy.py')
+
+ _test_run(
+ repo_with_passing_hook,
+ options={},
+ expected_outputs=[''],
+ expected_ret=0,
+ stage=False
+ )
+
+
+def test_local_hook_fails(
+ repo_with_passing_hook, mock_out_store_directory,
+):
+ config = OrderedDict((
+ ('repo', 'local'),
+ ('hooks', [OrderedDict((
+ ('id', 'no-todo'),
+ ('name', 'No TODO'),
+ ('entry', 'grep -iI todo'),
+ ('expected_return_value', 1),
+ ('language', 'system'),
+ ('files', ''),
+ ))])
+ ))
+ add_config_to_repo(repo_with_passing_hook, config)
+
+ with io.open('dummy.py', 'w') as staged_file:
+ staged_file.write('"""TODO: something"""\n')
+ cmd_output('git', 'add', 'dummy.py')
+
+ _test_run(
+ repo_with_passing_hook,
+ options={},
+ expected_outputs=[''],
+ expected_ret=1,
+ stage=False
+ )
diff --git a/tests/repository_test.py b/tests/repository_test.py
index cde6a76..c0bd079 100644
--- a/tests/repository_test.py
+++ b/tests/repository_test.py
@@ -12,6 +12,7 @@ from pre_commit.clientlib.validate_config import CONFIG_JSON_SCHEMA
from pre_commit.clientlib.validate_config import validate_config_extra
from pre_commit.jsonschema_extensions import apply_defaults
from pre_commit.languages.python import PythonEnv
+from pre_commit.ordereddict import OrderedDict
from pre_commit.repository import Repository
from pre_commit.util import cmd_output
from pre_commit.util import cwd
@@ -377,3 +378,22 @@ def test_tags_on_repositories(in_tmpdir, tmpdir_factory, store):
ret = repo_2.run_hook(repo_2.hooks[0][1], ['bar'])
assert ret[0] == 0
assert ret[1] == 'bar\nHello World\n'
+
+
+def test_local_repository():
+ config = OrderedDict((
+ ('repo', 'local'),
+ ('hooks', [OrderedDict((
+ ('id', 'do_not_commit'),
+ ('name', 'Block if "DO NOT COMMIT" is found'),
+ ('entry', 'DO NOT COMMIT'),
+ ('language', 'pcre'),
+ ('files', '^(.*)$'),
+ ))])
+ ))
+ local_repo = Repository.create(config, 'dummy')
+ with pytest.raises(NotImplementedError):
+ local_repo.sha
+ with pytest.raises(NotImplementedError):
+ local_repo.manifest
+ assert len(local_repo.hooks) == 1
diff --git a/tests/runner_test.py b/tests/runner_test.py
index b1a5d5d..7399c4d 100644
--- a/tests/runner_test.py
+++ b/tests/runner_test.py
@@ -5,8 +5,10 @@ import os
import os.path
import pre_commit.constants as C
+from pre_commit.ordereddict import OrderedDict
from pre_commit.runner import Runner
from pre_commit.util import cwd
+from testing.fixtures import add_config_to_repo
from testing.fixtures import git_dir
from testing.fixtures import make_consuming_repo
@@ -52,6 +54,31 @@ def test_repositories(tmpdir_factory, mock_out_store_directory):
assert len(runner.repositories) == 1
+def test_local_hooks(tmpdir_factory, mock_out_store_directory):
+ config = OrderedDict((
+ ('repo', 'local'),
+ ('hooks', (OrderedDict((
+ ('id', 'arg-per-line'),
+ ('name', 'Args per line hook'),
+ ('entry', 'bin/hook.sh'),
+ ('language', 'script'),
+ ('files', ''),
+ ('args', ['hello', 'world']),
+ )), OrderedDict((
+ ('id', 'do_not_commit'),
+ ('name', 'Block if "DO NOT COMMIT" is found'),
+ ('entry', 'DO NOT COMMIT'),
+ ('language', 'pcre'),
+ ('files', '^(.*)$'),
+ ))))
+ ))
+ git_path = git_dir(tmpdir_factory)
+ add_config_to_repo(git_path, config)
+ runner = Runner(git_path)
+ assert len(runner.repositories) == 1
+ assert len(runner.repositories[0].hooks) == 2
+
+
def test_pre_commit_path():
runner = Runner(os.path.join('foo', 'bar'))
expected_path = os.path.join('foo', 'bar', '.git', 'hooks', 'pre-commit')
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_hyperlinks",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 2,
"issue_text_score": 1,
"test_score": 0
},
"num_modified_files": 3
} | 0.4 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[dev]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.5",
"reqs_path": [
"requirements-dev.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | aspy.yaml==1.3.0
astroid==1.3.2
attrs==22.2.0
cached-property==1.5.2
certifi==2021.5.30
coverage==6.2
distlib==0.3.9
filelock==3.4.1
flake8==5.0.4
importlib-metadata==4.8.3
importlib-resources==5.4.0
iniconfig==1.1.1
jsonschema==3.2.0
logilab-common==1.9.7
mccabe==0.7.0
mock==5.2.0
mypy-extensions==1.0.0
nodeenv==1.6.0
ordereddict==1.1
packaging==21.3
platformdirs==2.4.0
pluggy==1.0.0
-e git+https://github.com/pre-commit/pre-commit.git@d97ea30c4bb309a2877fed95323ac8c793c0679f#egg=pre_commit
py==1.11.0
pycodestyle==2.9.1
pyflakes==2.5.0
pylint==1.3.1
pyparsing==3.1.4
pyrsistent==0.18.0
pytest==7.0.1
PyYAML==6.0.1
simplejson==3.20.1
six==1.17.0
tomli==1.2.3
typing_extensions==4.1.1
virtualenv==20.17.1
zipp==3.6.0
| name: pre-commit
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- pip=21.2.2=py36h06a4308_0
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_0
- setuptools=58.0.4=py36h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- argparse==1.4.0
- aspy-yaml==1.3.0
- astroid==1.3.2
- attrs==22.2.0
- cached-property==1.5.2
- coverage==6.2
- distlib==0.3.9
- filelock==3.4.1
- flake8==5.0.4
- importlib-metadata==4.8.3
- importlib-resources==5.4.0
- iniconfig==1.1.1
- jsonschema==3.2.0
- logilab-common==1.9.7
- mccabe==0.7.0
- mock==5.2.0
- mypy-extensions==1.0.0
- nodeenv==1.6.0
- ordereddict==1.1
- packaging==21.3
- platformdirs==2.4.0
- pluggy==1.0.0
- py==1.11.0
- pycodestyle==2.9.1
- pyflakes==2.5.0
- pylint==1.3.1
- pyparsing==3.1.4
- pyrsistent==0.18.0
- pytest==7.0.1
- pyyaml==6.0.1
- simplejson==3.20.1
- six==1.17.0
- tomli==1.2.3
- typing-extensions==4.1.1
- virtualenv==20.17.1
- zipp==3.6.0
prefix: /opt/conda/envs/pre-commit
| [
"tests/clientlib/validate_config_test.py::test_config_with_local_hooks_definition_fails[config_obj0]",
"tests/clientlib/validate_config_test.py::test_config_with_local_hooks_definition_passes[config_obj0]",
"tests/clientlib/validate_config_test.py::test_config_with_local_hooks_definition_passes[config_obj1]",
"tests/repository_test.py::test_local_repository"
] | [
"tests/clientlib/validate_config_test.py::test_run[input0-0]",
"tests/clientlib/validate_config_test.py::test_run[input1-0]",
"tests/commands/run_test.py::test_lots_of_files",
"tests/repository_test.py::test_python_hook",
"tests/repository_test.py::test_python_hook_args_with_spaces",
"tests/repository_test.py::test_versioned_python_hook",
"tests/repository_test.py::test_run_a_node_hook",
"tests/repository_test.py::test_run_versioned_node_hook",
"tests/repository_test.py::test_run_a_ruby_hook",
"tests/repository_test.py::test_run_versioned_ruby_hook",
"tests/repository_test.py::test_system_hook_with_spaces",
"tests/repository_test.py::test_run_a_script_hook",
"tests/repository_test.py::test_run_hook_with_spaced_args",
"tests/repository_test.py::test_pcre_hook_no_match",
"tests/repository_test.py::test_pcre_hook_matching",
"tests/repository_test.py::test_pcre_many_files",
"tests/repository_test.py::test_cwd_of_hook",
"tests/repository_test.py::test_lots_of_files",
"tests/repository_test.py::test_languages",
"tests/repository_test.py::test_reinstall",
"tests/repository_test.py::test_control_c_control_c_on_install",
"tests/repository_test.py::test_really_long_file_paths",
"tests/repository_test.py::test_config_overrides_repo_specifics",
"tests/repository_test.py::test_tags_on_repositories",
"tests/runner_test.py::test_repositories",
"tests/runner_test.py::test_local_hooks"
] | [
"tests/clientlib/validate_config_test.py::test_run[input2-1]",
"tests/clientlib/validate_config_test.py::test_run[input3-1]",
"tests/clientlib/validate_config_test.py::test_run[input4-1]",
"tests/clientlib/validate_config_test.py::test_is_valid_according_to_schema[config_obj0-False]",
"tests/clientlib/validate_config_test.py::test_is_valid_according_to_schema[config_obj1-True]",
"tests/clientlib/validate_config_test.py::test_is_valid_according_to_schema[config_obj2-True]",
"tests/clientlib/validate_config_test.py::test_is_valid_according_to_schema[config_obj3-False]",
"tests/clientlib/validate_config_test.py::test_config_with_failing_regexes_fails",
"tests/clientlib/validate_config_test.py::test_config_with_ok_regexes_passes",
"tests/clientlib/validate_config_test.py::test_config_with_invalid_exclude_regex_fails",
"tests/clientlib/validate_config_test.py::test_config_with_ok_exclude_regex_passes",
"tests/commands/run_test.py::test_has_unmerged_paths[some-True]",
"tests/commands/run_test.py::test_has_unmerged_paths[-False]",
"tests/commands/run_test.py::test_get_skips[environ0-expected_output0]",
"tests/commands/run_test.py::test_get_skips[environ1-expected_output1]",
"tests/commands/run_test.py::test_get_skips[environ2-expected_output2]",
"tests/commands/run_test.py::test_get_skips[environ3-expected_output3]",
"tests/commands/run_test.py::test_get_skips[environ4-expected_output4]",
"tests/commands/run_test.py::test_get_skips[environ5-expected_output5]",
"tests/commands/run_test.py::test_get_skips[environ6-expected_output6]",
"tests/commands/run_test.py::test_get_changed_files",
"tests/repository_test.py::test_repo_url",
"tests/repository_test.py::test_sha",
"tests/runner_test.py::test_init_has_no_side_effects",
"tests/runner_test.py::test_create_sets_correct_directory",
"tests/runner_test.py::test_create_changes_to_git_root",
"tests/runner_test.py::test_config_file_path",
"tests/runner_test.py::test_pre_commit_path",
"tests/runner_test.py::test_pre_push_path",
"tests/runner_test.py::test_cmd_runner"
] | [] | MIT License | 133 |
mne-tools__mne-python-2080 | f2ab0641f087c63beab715ff5fdaa9399c0807fe | 2015-05-10 19:50:29 | edceb8f38349d6dc0cade1c9f8384cc0707ce3e8 | Eric89GXL: Okay, this has some potentially nice (up to 2x) memory-saving changes for EDF, but I don't think we can get the same benefit for KIT (at least not easily). This unifies `preload_data` and how `preload` is handled across raw types, and allows `data_buffer` to be used for EDF and KIT as well as FIF.
Ready for review from my end. @teonlamont please look closely to make sure it makes sense. Tests still pass, and I've been relying on those being correct to make sure things all worked properly.
agramfort: @teonlamont please take a close look | diff --git a/mne/io/base.py b/mne/io/base.py
index 9a3c83be2..578109de7 100644
--- a/mne/io/base.py
+++ b/mne/io/base.py
@@ -215,22 +215,39 @@ class _BaseRaw(ProjMixin, ContainsMixin, PickDropChannelsMixin,
Subclasses must provide the following methods:
- * _read_segment(start, stop, sel, projector, verbose)
+ * _read_segment(start, stop, sel, data_buffer, projector, verbose)
(only needed for types that support on-demand disk reads)
"""
@verbose
- def __init__(self, info, data=None,
+ def __init__(self, info, preload=False,
first_samps=(0,), last_samps=None,
filenames=(), rawdirs=(),
comp=None, orig_comp_grade=None,
- orig_format='double', verbose=None):
- # some functions (e.g., filtering) only work w/64-bit data
- if data is not None:
- if data.dtype not in (np.float64, np.complex128):
+ orig_format='double',
+ verbose=None):
+ # wait until the end to preload data, but triage here
+ if isinstance(preload, np.ndarray):
+ # some functions (e.g., filtering) only work w/64-bit data
+ if preload.dtype not in (np.float64, np.complex128):
raise RuntimeError('datatype must be float64 or complex128, '
- 'not %s' % data.dtype)
+ 'not %s' % preload.dtype)
+ self._data = preload
+ self.preload = True
+ self._last_samps = np.array([self._data.shape[1] - 1])
+ load_from_disk = False
+ else:
+ if last_samps is None:
+ raise ValueError('last_samps must be given unless preload is '
+ 'an ndarray')
+ if preload is False:
+ self.preload = False
+ load_from_disk = False
+ elif preload is not True and not isinstance(preload, string_types):
+ raise ValueError('bad preload: %s' % preload)
+ else:
+ load_from_disk = True
+ self._last_samps = np.array(last_samps)
self.info = info
- self._data = data
cals = np.empty(info['nchan'])
for k in range(info['nchan']):
cals[k] = info['chs'][k]['range'] * info['chs'][k]['cal']
@@ -240,19 +257,70 @@ class _BaseRaw(ProjMixin, ContainsMixin, PickDropChannelsMixin,
self.comp = comp
self._orig_comp_grade = orig_comp_grade
self._filenames = list(filenames)
- self.preload = True if data is not None else False
self._first_samps = np.array(first_samps)
self.orig_format = orig_format
- if data is not None:
- self._last_samps = np.array([self._data.shape[1] - 1])
- else:
- self._last_samps = np.array(last_samps)
self._projectors = list()
self._projector = None
+ # If we have True or a string, actually do the preloading
+ if load_from_disk:
+ self._preload_data(preload)
- def _read_segment(start, stop, sel, projector, verbose):
+ def _read_segment(start, stop, sel, data_buffer, projector, verbose):
+ """Read a chunk of raw data
+
+ Parameters
+ ----------
+ start : int, (optional)
+ first sample to include (first is 0). If omitted, defaults to the
+ first sample in data.
+ stop : int, (optional)
+ First sample to not include.
+ If omitted, data is included to the end.
+ sel : array, optional
+ Indices of channels to select.
+ data_buffer : array or str, optional
+ numpy array to fill with data read, must have the correct shape.
+ If str, a np.memmap with the correct data type will be used
+ to store the data.
+ projector : array
+ SSP operator to apply to the data.
+ verbose : bool, str, int, or None
+ If not None, override default verbose level (see mne.verbose).
+
+ Returns
+ -------
+ data : array, [channels x samples]
+ the data matrix (channels x samples).
+ times : array, [samples]
+ returns the time values corresponding to the samples.
+ """
raise NotImplementedError
+ @verbose
+ def preload_data(self, verbose=None):
+ """Preload raw data
+
+ Parameters
+ ----------
+ verbose : bool, str, int, or None
+ If not None, override default verbose level (see mne.verbose).
+
+ Notes
+ -----
+ This function will preload raw data if it was not already preloaded.
+ If data were already preloaded, it will do nothing.
+ """
+ if not self.preload:
+ self._preload_data(True)
+
+ def _preload_data(self, preload):
+ """This function actually preloads the data"""
+ data_buffer = preload if isinstance(preload, string_types) else None
+ self._data = self._read_segment(data_buffer=data_buffer)[0]
+ assert len(self._data) == self.info['nchan']
+ self.preload = True
+ self.close()
+
@property
def first_samp(self):
return self._first_samps[0]
@@ -1344,7 +1412,6 @@ class _BaseRaw(ProjMixin, ContainsMixin, PickDropChannelsMixin,
raws : list, or Raw instance
list of Raw instances to concatenate to the current instance
(in order), or a single raw instance to concatenate.
-
preload : bool, str, or None (default None)
Preload data into memory for data manipulation and faster indexing.
If True, the data will be preloaded into memory (fast, requires
@@ -1414,7 +1481,8 @@ class _BaseRaw(ProjMixin, ContainsMixin, PickDropChannelsMixin,
def close(self):
"""Clean up the object.
- Does nothing for now.
+ Does nothing for objects that close their file descriptors.
+ Things like RawFIF will override this method.
"""
pass
diff --git a/mne/io/edf/edf.py b/mne/io/edf/edf.py
index 5a8eb8e5f..700849294 100644
--- a/mne/io/edf/edf.py
+++ b/mne/io/edf/edf.py
@@ -60,9 +60,12 @@ class RawEDF(_BaseRaw):
-1 corresponds to the last channel.
If None, the annotation channel is not used.
Note: this is overruled by the annotation file if specified.
- preload : bool
- If True, all data are loaded at initialization.
- If False, data are not read until save.
+ preload : bool or str (default False)
+ Preload data into memory for data manipulation and faster indexing.
+ If True, the data will be preloaded into memory (fast, requires
+ large amount of memory). If preload is a string, preload is the
+ file name of a memory-mapped file which is used to store the data
+ on the hard drive (slower, requires less memory).
verbose : bool, str, int, or None
If not None, override default verbose level (see mne.verbose).
@@ -89,18 +92,9 @@ class RawEDF(_BaseRaw):
# Raw attributes
last_samps = [self._edf_info['nsamples'] - 1]
super(RawEDF, self).__init__(
- info, last_samps=last_samps, orig_format='int', verbose=verbose)
-
- if preload:
- self.preload = preload
- logger.info('Reading raw data from %s...' % input_fname)
- self._data, _ = self._read_segment()
- assert len(self._data) == self.info['nchan']
- self._last_samps = np.array([self._data.shape[1] - 1])
- logger.info(' Range : %d ... %d = %9.3f ... %9.3f secs'
- % (self.first_samp, self.last_samp,
- float(self.first_samp) / self.info['sfreq'],
- float(self.last_samp) / self.info['sfreq']))
+ info, preload, last_samps=last_samps, orig_format='int',
+ verbose=verbose)
+
logger.info('Ready.')
def __repr__(self):
@@ -110,50 +104,27 @@ class RawEDF(_BaseRaw):
"n_channels x n_times : %s x %s" % (n_chan, data_range))
return "<RawEDF | %s>" % ', '.join(s)
- def _read_segment(self, start=0, stop=None, sel=None, verbose=None,
- projector=None):
- """Read a chunk of raw data
-
- Parameters
- ----------
- start : int, (optional)
- first sample to include (first is 0). If omitted, defaults to the
- first sample in data.
- stop : int, (optional)
- First sample to not include.
- If omitted, data is included to the end.
- sel : array, optional
- Indices of channels to select.
- projector : array
- SSP operator to apply to the data.
- verbose : bool, str, int, or None
- If not None, override default verbose level (see mne.verbose).
-
- Returns
- -------
- data : array, [channels x samples]
- the data matrix (channels x samples).
- times : array, [samples]
- returns the time values corresponding to the samples.
- """
+ @verbose
+ def _read_segment(self, start=0, stop=None, sel=None, data_buffer=None,
+ projector=None, verbose=None):
+ """Read a chunk of raw data"""
from scipy.interpolate import interp1d
if sel is None:
- sel = list(range(self.info['nchan']))
- elif len(sel) == 1 and sel[0] == 0 and start == 0 and stop == 1:
- return (666, 666)
+ sel = np.arange(self.info['nchan'])
if projector is not None:
raise NotImplementedError('Currently does not handle projections.')
if stop is None:
stop = self.last_samp + 1
elif stop > self.last_samp + 1:
stop = self.last_samp + 1
+ sel = np.array(sel)
# Initial checks
start = int(start)
stop = int(stop)
n_samps = self._edf_info['n_samps']
- max_samp = self._edf_info['max_samp']
+ buf_len = self._edf_info['max_samp']
sfreq = self.info['sfreq']
n_chan = self.info['nchan']
data_size = self._edf_info['data_size']
@@ -165,8 +136,8 @@ class RawEDF(_BaseRaw):
subtype = self._edf_info['subtype']
# this is used to deal with indexing in the middle of a sampling period
- blockstart = int(floor(float(start) / max_samp) * max_samp)
- blockstop = int(ceil(float(stop) / max_samp) * max_samp)
+ blockstart = int(floor(float(start) / buf_len) * buf_len)
+ blockstop = int(ceil(float(stop) / buf_len) * buf_len)
if blockstop > self.last_samp:
blockstop = self.last_samp + 1
@@ -188,100 +159,179 @@ class RawEDF(_BaseRaw):
picks = [stim_channel, tal_channel]
offsets[picks] = 0
- with open(self.info['filename'], 'rb') as fid:
+ # set up output array
+ data_shape = (len(sel), stop - start)
+ if isinstance(data_buffer, np.ndarray):
+ if data_buffer.shape != data_shape:
+ raise ValueError('data_buffer has incorrect shape')
+ data = data_buffer
+ else:
+ data = np.empty(data_shape, dtype=float)
+
+ read_size = blockstop - blockstart
+ this_data = np.empty((len(sel), buf_len))
+ """
+ Consider this example:
+
+ tmin, tmax = (2, 27)
+ read_size = 30
+ buf_len = 10
+ sfreq = 1.
+
+ +---------+---------+---------+
+ File structure: | buf0 | buf1 | buf2 |
+ +---------+---------+---------+
+ File time: 0 10 20 30
+ +---------+---------+---------+
+ Requested time: 2 27
+
+ | |
+ blockstart blockstop
+ | |
+ start stop
+
+ We need 27 - 2 = 25 samples (per channel) to store our data, and
+ we need to read from 3 buffers (30 samples) to get all of our data.
+
+ On all reads but the first, the data we read starts at
+ the first sample of the buffer. On all reads but the last,
+ the data we read ends on the last sample of the buffer.
+
+ We call this_data the variable that stores the current buffer's data,
+ and data the variable that stores the total output.
+
+ On the first read, we need to do this::
+
+ >>> data[0:buf_len-2] = this_data[2:buf_len]
+
+ On the second read, we need to do::
+
+ >>> data[1*buf_len-2:2*buf_len-2] = this_data[0:buf_len]
+
+ On the final read, we need to do::
+
+ >>> data[2*buf_len-2:3*buf_len-2-3] = this_data[0:buf_len-3]
+
+ """
+ with open(self.info['filename'], 'rb', buffering=0) as fid:
# extract data
- fid.seek(data_offset)
- buffer_size = blockstop - blockstart
- pointer = blockstart * n_chan * data_size
- fid.seek(data_offset + pointer)
- datas = np.empty((n_chan, buffer_size), dtype=float)
- blocks = int(ceil(float(buffer_size) / max_samp))
- for i in range(blocks):
- data = np.empty((n_chan, max_samp), dtype=np.int32)
+ fid.seek(data_offset + blockstart * n_chan * data_size)
+ n_blk = int(ceil(float(read_size) / buf_len))
+ start_offset = start - blockstart
+ end_offset = blockstop - stop
+ for bi in range(n_blk):
+ # Triage start (sidx) and end (eidx) indices for
+ # data (d) and read (r)
+ if bi == 0:
+ d_sidx = 0
+ r_sidx = start_offset
+ else:
+ d_sidx = bi * buf_len - start_offset
+ r_sidx = 0
+ if bi == n_blk - 1:
+ d_eidx = data_shape[1]
+ r_eidx = buf_len - end_offset
+ else:
+ d_eidx = (bi + 1) * buf_len - start_offset
+ r_eidx = buf_len
+ n_buf_samp = r_eidx - r_sidx
+ count = 0
for j, samp in enumerate(n_samps):
# bdf data: 24bit data
- if subtype in ('24BIT', 'bdf'):
- ch_data = np.fromfile(fid, dtype=np.uint8,
- count=samp * data_size)
- ch_data = ch_data.reshape(-1, 3).astype(np.int32)
- ch_data = ((ch_data[:, 0]) +
- (ch_data[:, 1] << 8) +
- (ch_data[:, 2] << 16))
- # 24th bit determines the sign
- ch_data[ch_data >= (1 << 23)] -= (1 << 24)
- # edf data: 16bit data
+ if j not in sel:
+ fid.seek(samp * data_size, 1)
+ continue
+ if samp == buf_len:
+ # use faster version with skips built in
+ if r_sidx > 0:
+ fid.seek(r_sidx * data_size, 1)
+ ch_data = _read_ch(fid, subtype, n_buf_samp, data_size)
+ if r_eidx < buf_len:
+ fid.seek((buf_len - r_eidx) * data_size, 1)
else:
- ch_data = np.fromfile(fid, dtype='<i2', count=samp)
- if j == tal_channel:
- # don't resample tal_channel,
- # pad with zeros instead.
- n_missing = int(max_samp - samp)
- ch_data = np.hstack([ch_data,
- [0] * n_missing])
- elif j == stim_channel and samp < max_samp:
- if annot and annotmap or \
- tal_channel is not None:
- # don't bother with resampling the stim ch
- # because it gets overwritten later on.
- ch_data = np.zeros(max_samp)
+ # read in all the data and triage appropriately
+ ch_data = _read_ch(fid, subtype, samp, data_size)
+ if j == tal_channel:
+ # don't resample tal_channel,
+ # pad with zeros instead.
+ n_missing = int(buf_len - samp)
+ ch_data = np.hstack([ch_data, [0] * n_missing])
+ ch_data = ch_data[r_sidx:r_eidx]
+ elif j == stim_channel:
+ if annot and annotmap or \
+ tal_channel is not None:
+ # don't bother with resampling the stim ch
+ # because it gets overwritten later on.
+ ch_data = np.zeros(n_buf_samp)
+ else:
+ warnings.warn('Interpolating stim channel.'
+ ' Events may jitter.')
+ oldrange = np.linspace(0, 1, samp + 1, True)
+ newrange = np.linspace(0, 1, buf_len, False)
+ newrange = newrange[r_sidx:r_eidx]
+ ch_data = interp1d(
+ oldrange, np.append(ch_data, 0),
+ kind='zero')(newrange)
else:
- warnings.warn('Interpolating stim channel.'
- ' Events may jitter.')
- oldrange = np.linspace(0, 1, samp + 1,
- True)
- newrange = np.linspace(0, 1, max_samp,
- False)
- ch_data = interp1d(
- oldrange, np.append(ch_data, 0),
- kind='zero')(newrange)
- elif samp != max_samp:
- ch_data = resample(x=ch_data, up=max_samp, down=samp,
- npad=0)
- data[j] = ch_data
- start_pt = int(max_samp * i)
- stop_pt = int(start_pt + max_samp)
- datas[:, start_pt:stop_pt] = data
- datas *= gains.T
- datas += offsets
+ ch_data = resample(ch_data, buf_len, samp,
+ npad=0)[r_sidx:r_eidx]
+ this_data[count, :n_buf_samp] = ch_data
+ count += 1
+ data[:, d_sidx:d_eidx] = this_data[:, :n_buf_samp]
+ data *= gains.T[sel]
+ data += offsets[sel]
if stim_channel is not None:
+ stim_channel_idx = np.where(sel == stim_channel)[0][0]
if annot and annotmap:
- datas[stim_channel] = 0
evts = _read_annot(annot, annotmap, sfreq, self.last_samp)
- datas[stim_channel, :evts.size] = evts[start:stop]
+ stim = evts[start:stop]
elif tal_channel is not None:
- evts = _parse_tal_channel(datas[tal_channel])
+ tal_channel_idx = np.where(sel == tal_channel)[0][0]
+ evts = _parse_tal_channel(data[tal_channel_idx])
self._edf_info['events'] = evts
unique_annots = sorted(set([e[2] for e in evts]))
mapping = dict((a, n + 1) for n, a in enumerate(unique_annots))
- datas[stim_channel] = 0
+ stim = np.zeros(read_size)
for t_start, t_duration, annotation in evts:
evid = mapping[annotation]
n_start = int(t_start * sfreq)
n_stop = int(t_duration * sfreq) + n_start - 1
# make sure events without duration get one sample
n_stop = n_stop if n_stop > n_start else n_start + 1
- if any(datas[stim_channel][n_start:n_stop]):
+ if any(stim[n_start:n_stop]):
raise NotImplementedError('EDF+ with overlapping '
'events not supported.')
- datas[stim_channel][n_start:n_stop] = evid
+ stim[n_start:n_stop] = evid
else:
- # Allows support for up to 16-bit trigger values
- mask = 2 ** 16 - 1
- stim = np.array(datas[stim_channel], int)
- mask = mask * np.ones(stim.shape, int)
- stim = np.bitwise_and(stim, mask)
- datas[stim_channel] = stim
- datastart = start - blockstart
- datastop = stop - blockstart
- datas = datas[sel, datastart:datastop]
+ # Allows support for up to 16-bit trigger values (2 ** 16 - 1)
+ stim = np.bitwise_and(data[stim_channel_idx].astype(int),
+ 65535)
+ data[stim_channel_idx, :] = \
+ stim[start - blockstart:stop - blockstart]
logger.info('[done]')
times = np.arange(start, stop, dtype=float) / self.info['sfreq']
-
- return datas, times
+ return data, times
+
+
+def _read_ch(fid, subtype, samp, data_size):
+ """Helper to read a number of samples for a single channel"""
+ if subtype in ('24BIT', 'bdf'):
+ ch_data = np.fromfile(fid, dtype=np.uint8,
+ count=samp * data_size)
+ ch_data = ch_data.reshape(-1, 3).astype(np.int32)
+ ch_data = ((ch_data[:, 0]) +
+ (ch_data[:, 1] << 8) +
+ (ch_data[:, 2] << 16))
+ # 24th bit determines the sign
+ ch_data[ch_data >= (1 << 23)] -= (1 << 24)
+ # edf data: 16bit data
+ else:
+ ch_data = np.fromfile(fid, dtype='<i2', count=samp)
+ return ch_data
def _parse_tal_channel(tal_channel_data):
@@ -324,46 +374,7 @@ def _parse_tal_channel(tal_channel_data):
def _get_edf_info(fname, stim_channel, annot, annotmap, tal_channel,
eog, misc, preload):
- """Extracts all the information from the EDF+,BDF file.
-
- Parameters
- ----------
- fname : str
- Raw EDF+,BDF file to be read.
- stim_channel : str | int | None
- The channel name or channel index (starting at 0).
- -1 corresponds to the last channel.
- If None, there will be no stim channel added.
- annot : str | None
- Path to annotation file.
- If None, no derived stim channel will be added (for files requiring
- annotation file to interpret stim channel).
- annotmap : str | None
- Path to annotation map file containing mapping from label to trigger.
- Must be specified if annot is not None.
- tal_channel : int | None
- The channel index (starting at 0).
- Index of the channel containing EDF+ annotations.
- -1 corresponds to the last channel.
- If None, the annotation channel is not used.
- Note: this is overruled by the annotation file if specified.
- eog : list of str | None
- Names of channels that should be designated EOG channels. Names should
- correspond to the electrodes in the edf file. Default is None.
- misc : list of str | None
- Names of channels that should be designated MISC channels. Names
- should correspond to the electrodes in the edf file. Default is None.
- preload : bool
- If True, all data are loaded at initialization.
- If False, data are not read until save.
-
- Returns
- -------
- info : instance of Info
- The measurement info.
- edf_info : dict
- A dict containing all the EDF+,BDF specific parameters.
- """
+ """Extracts all the information from the EDF+,BDF file"""
if eog is None:
eog = []
@@ -632,9 +643,12 @@ def read_raw_edf(input_fname, montage=None, eog=None, misc=None,
-1 corresponds to the last channel.
If None, the annotation channel is not used.
Note: this is overruled by the annotation file if specified.
- preload : bool
- If True, all data are loaded at initialization.
- If False, data are not read until save.
+ preload : bool or str (default False)
+ Preload data into memory for data manipulation and faster indexing.
+ If True, the data will be preloaded into memory (fast, requires
+ large amount of memory). If preload is a string, preload is the
+ file name of a memory-mapped file which is used to store the data
+ on the hard drive (slower, requires less memory).
verbose : bool, str, int, or None
If not None, override default verbose level (see mne.verbose).
diff --git a/mne/io/fiff/raw.py b/mne/io/fiff/raw.py
index 6d3027fcd..9894f8513 100644
--- a/mne/io/fiff/raw.py
+++ b/mne/io/fiff/raw.py
@@ -114,7 +114,7 @@ class RawFIF(_BaseRaw):
_check_raw_compatibility(raws)
super(RawFIF, self).__init__(
- copy.deepcopy(raws[0].info), None,
+ copy.deepcopy(raws[0].info), False,
[r.first_samp for r in raws], [r.last_samp for r in raws],
[r.filename for r in raws], [r._rawdir for r in raws],
copy.deepcopy(raws[0].comp), raws[0]._orig_comp_grade,
@@ -135,36 +135,6 @@ class RawFIF(_BaseRaw):
if proj:
self.apply_proj()
- def _preload_data(self, preload):
- """This function actually preloads the data"""
- if isinstance(preload, string_types):
- # we will use a memmap: preload is a filename
- data_buffer = preload
- else:
- data_buffer = None
-
- self._data = self._read_segment(data_buffer=data_buffer)[0]
- self.preload = True
- # close files once data are preloaded
- self.close()
-
- @verbose
- def preload_data(self, verbose=None):
- """Preload raw data
-
- Parameters
- ----------
- verbose : bool, str, int, or None
- If not None, override default verbose level (see mne.verbose).
-
- Notes
- -----
- This function will preload raw data if it was not already preloaded.
- If data were already preloaded, it will do nothing.
- """
- if not self.preload:
- self._preload_data(True)
-
@verbose
def _read_raw_file(self, fname, allow_maxshield, preload, compensation,
do_check_fname=True, verbose=None):
@@ -376,36 +346,10 @@ class RawFIF(_BaseRaw):
return raw, next_fname
+ @verbose
def _read_segment(self, start=0, stop=None, sel=None, data_buffer=None,
- verbose=None, projector=None):
- """Read a chunk of raw data
-
- Parameters
- ----------
- start : int, (optional)
- first sample to include (first is 0). If omitted, defaults to the
- first sample in data.
- stop : int, (optional)
- First sample to not include.
- If omitted, data is included to the end.
- sel : array, optional
- Indices of channels to select.
- data_buffer : array or str, optional
- numpy array to fill with data read, must have the correct shape.
- If str, a np.memmap with the correct data type will be used
- to store the data.
- verbose : bool, str, int, or None
- If not None, override default verbose level (see mne.verbose).
- projector : array
- SSP operator to apply to the data.
-
- Returns
- -------
- data : array, [channels x samples]
- the data matrix (channels x samples).
- times : array, [samples]
- returns the time values corresponding to the samples.
- """
+ projector=None, verbose=None):
+ """Read a chunk of raw data"""
# Initial checks
start = int(start)
stop = self.n_times if stop is None else min([int(stop), self.n_times])
diff --git a/mne/io/kit/kit.py b/mne/io/kit/kit.py
index 9ccb87ccb..8de71ac9a 100644
--- a/mne/io/kit/kit.py
+++ b/mne/io/kit/kit.py
@@ -63,9 +63,12 @@ class RawKIT(_BaseRaw):
stimthresh : float
The threshold level for accepting voltage changes in KIT trigger
channels as a trigger event. If None, stim must also be set to None.
- preload : bool
- If True, all data are loaded at initialization.
- If False, data are not read until save.
+ preload : bool or str (default False)
+ Preload data into memory for data manipulation and faster indexing.
+ If True, the data will be preloaded into memory (fast, requires
+ large amount of memory). If preload is a string, preload is the
+ file name of a memory-mapped file which is used to store the data
+ on the hard drive (slower, requires less memory).
verbose : bool, str, int, or None
If not None, override default verbose level (see mne.verbose).
@@ -90,9 +93,9 @@ class RawKIT(_BaseRaw):
logger.info('Creating Info structure...')
last_samps = [self._kit_info['n_samples'] - 1]
+ self._set_stimchannels(info, stim)
super(RawKIT, self).__init__(
- info, last_samps=last_samps, verbose=verbose)
- self._set_stimchannels(stim)
+ info, preload, last_samps=last_samps, verbose=verbose)
if isinstance(mrk, list):
mrk = [read_mrk(marker) if isinstance(marker, string_types)
@@ -103,19 +106,9 @@ class RawKIT(_BaseRaw):
self.info['dig'] = dig_points
self.info['dev_head_t'] = dev_head_t
elif (mrk is not None or elp is not None or hsp is not None):
- err = ("mrk, elp and hsp need to be provided as a group (all or "
- "none)")
- raise ValueError(err)
+ raise ValueError('mrk, elp and hsp need to be provided as a group '
+ '(all or none)')
- if preload:
- self.preload = preload
- logger.info('Reading raw data from %s...' % input_fname)
- self._data, _ = self._read_segment()
- assert self._data.shape == (self.info['nchan'], self.last_samp + 1)
-
- logger.info(' Range : %d ... %d = %9.3f ... %9.3f secs'
- % (self.first_samp, self.last_samp,
- self.times[0], self.times[-1]))
logger.info('Ready.')
def __repr__(self):
@@ -151,7 +144,7 @@ class RawKIT(_BaseRaw):
return stim_ch
- def _set_stimchannels(self, stim='<'):
+ def _set_stimchannels(self, info, stim='<'):
"""Specify how the trigger channel is synthesized from analog channels.
Has to be done before loading data. For a RawKIT instance that has been
@@ -160,6 +153,8 @@ class RawKIT(_BaseRaw):
Parameters
----------
+ info : instance of MeasInfo
+ The measurement info.
stim : list of int | '<' | '>'
Can be submitted as list of trigger channels.
If a list is not specified, the default triggers extracted from
@@ -171,7 +166,7 @@ class RawKIT(_BaseRaw):
"""
if stim is not None:
if isinstance(stim, str):
- picks = pick_types(self.info, meg=False, ref_meg=False,
+ picks = pick_types(info, meg=False, ref_meg=False,
misc=True, exclude=[])[:8]
if stim == '<':
stim = picks[::-1]
@@ -181,16 +176,16 @@ class RawKIT(_BaseRaw):
raise ValueError("stim needs to be list of int, '>' or "
"'<', not %r" % str(stim))
elif np.max(stim) >= self._kit_info['nchan']:
- msg = ("Tried to set stim channel %i, but sqd file only has %i"
- " channels" % (np.max(stim), self._kit_info['nchan']))
- raise ValueError(msg)
+ raise ValueError('Tried to set stim channel %i, but sqd file '
+ 'only has %i channels'
+ % (np.max(stim), self._kit_info['nchan']))
# modify info
- self.info['nchan'] = self._kit_info['nchan'] + 1
+ info['nchan'] = self._kit_info['nchan'] + 1
ch_name = 'STI 014'
chan_info = {}
chan_info['cal'] = KIT.CALIB_FACTOR
- chan_info['logno'] = self.info['nchan']
- chan_info['scanno'] = self.info['nchan']
+ chan_info['logno'] = info['nchan']
+ chan_info['scanno'] = info['nchan']
chan_info['range'] = 1.0
chan_info['unit'] = FIFF.FIFF_UNIT_NONE
chan_info['unit_mul'] = 0
@@ -198,50 +193,27 @@ class RawKIT(_BaseRaw):
chan_info['coil_type'] = FIFF.FIFFV_COIL_NONE
chan_info['loc'] = np.zeros(12)
chan_info['kind'] = FIFF.FIFFV_STIM_CH
- self.info['chs'].append(chan_info)
- self.info['ch_names'].append(ch_name)
+ info['chs'].append(chan_info)
+ info['ch_names'].append(ch_name)
if self.preload:
err = "Can't change stim channel after preloading data"
raise NotImplementedError(err)
self._kit_info['stim'] = stim
- def _read_segment(self, start=0, stop=None, sel=None, verbose=None,
- projector=None):
- """Read a chunk of raw data
-
- Parameters
- ----------
- start : int, (optional)
- first sample to include (first is 0). If omitted, defaults to the
- first sample in data.
- stop : int, (optional)
- First sample to not include.
- If omitted, data is included to the end.
- sel : array, optional
- Indices of channels to select.
- projector : array
- SSP operator to apply to the data.
- verbose : bool, str, int, or None
- If not None, override default verbose level (see mne.verbose).
-
- Returns
- -------
- data : array, [channels x samples]
- the data matrix (channels x samples).
- times : array, [samples]
- returns the time values corresponding to the samples.
- """
+ @verbose
+ def _read_segment(self, start=0, stop=None, sel=None, data_buffer=None,
+ projector=None, verbose=None):
+ """Read a chunk of raw data"""
if sel is None:
- sel = list(range(self.info['nchan']))
- elif len(sel) == 1 and sel[0] == 0 and start == 0 and stop == 1:
- return (666, 666)
+ sel = np.arange(self.info['nchan'])
if projector is not None:
raise NotImplementedError('Currently does not handle projections.')
if stop is None:
stop = self.last_samp + 1
elif stop > self.last_samp + 1:
stop = self.last_samp + 1
+ sel = np.array(sel)
# Initial checks
start = int(start)
@@ -294,6 +266,14 @@ class RawKIT(_BaseRaw):
data = np.vstack((data, stim_ch))
data = data[sel]
+ # This maybe should be refactored to actually save memory...
+ data_shape = data.shape
+ if isinstance(data_buffer, np.ndarray):
+ if data_buffer.shape != data_shape:
+ raise ValueError('data_buffer has incorrect shape')
+ data_buffer[...] = data
+ data = data_buffer
+
logger.info('[done]')
times = np.arange(start, stop, dtype=float) / self.info['sfreq']
@@ -413,9 +393,8 @@ class EpochsKIT(EpochsArray):
for key, val in event_id.items():
if val not in events[:, 2]:
- msg = ('No matching events found for %s '
- '(event id %i)' % (key, val))
- raise ValueError(msg)
+ raise ValueError('No matching events found for %s '
+ '(event id %i)' % (key, val))
data = self._read_data()
assert data.shape == (self._kit_info['n_epochs'], self.info['nchan'],
@@ -520,8 +499,8 @@ def _set_dig_kit(mrk, elp, hsp, auto_decimate=True):
msg = ("The selected head shape contained {n_in} points, which is "
"more than recommended ({n_rec}), and was automatically "
"downsampled to {n_new} points. The preferred way to "
- "downsample is using FastScan.")
- msg = msg.format(n_in=n_pts, n_rec=KIT.DIG_POINTS, n_new=n_new)
+ "downsample is using FastScan."
+ ).format(n_in=n_pts, n_rec=KIT.DIG_POINTS, n_new=n_new)
logger.warning(msg)
if isinstance(elp, string_types):
| preload_data is only for RawFIF
I was just working with a RawEDF and I went to call `raw.preload_data`, but I noticed that this method didn't exist for this Raw class. It's currently only implemented for RawFIF. I also saw that there is a new (to me at least) parameter in `_read_segment` called `data_buffer` that is being used whereas the other modules don't have this. should we use this method's use? | mne-tools/mne-python | diff --git a/mne/io/brainvision/tests/test_brainvision.py b/mne/io/brainvision/tests/test_brainvision.py
index 5131d978a..13762077d 100644
--- a/mne/io/brainvision/tests/test_brainvision.py
+++ b/mne/io/brainvision/tests/test_brainvision.py
@@ -47,6 +47,7 @@ def test_brainvision_data():
assert_raises(TypeError, read_raw_brainvision, vhdr_path, montage,
preload=True, scale="0")
raw_py = read_raw_brainvision(vhdr_path, montage, eog=eog, preload=True)
+ raw_py.preload_data() # currently does nothing
assert_equal(raw_py.info['highpass'], 0.)
assert_equal(raw_py.info['lowpass'], 250.)
diff --git a/mne/io/bti/tests/test_bti.py b/mne/io/bti/tests/test_bti.py
index 914233034..f6dc30465 100644
--- a/mne/io/bti/tests/test_bti.py
+++ b/mne/io/bti/tests/test_bti.py
@@ -53,6 +53,7 @@ def test_read_pdf():
def test_crop():
""" Test crop raw """
raw = read_raw_bti(pdf_fnames[0], config_fnames[0], hs_fnames[0])
+ raw.preload_data() # currently does nothing
y, t = raw[:]
t0, t1 = 0.25 * t[-1], 0.75 * t[-1]
mask = (t0 <= t) * (t <= t1)
diff --git a/mne/io/edf/tests/test_edf.py b/mne/io/edf/tests/test_edf.py
index 326a8ea51..f2959c3e2 100644
--- a/mne/io/edf/tests/test_edf.py
+++ b/mne/io/edf/tests/test_edf.py
@@ -47,9 +47,6 @@ def test_bdf_data():
picks = pick_types(raw_py.info, meg=False, eeg=True, exclude='bads')
data_py, _ = raw_py[picks]
- print(raw_py) # to test repr
- print(raw_py.info) # to test Info repr
-
# this .mat was generated using the EEG Lab Biosemi Reader
raw_eeglab = io.loadmat(bdf_eeglab_path)
raw_eeglab = raw_eeglab['data'] * 1e-6 # data are stored in microvolts
@@ -118,13 +115,20 @@ def test_read_segment():
assert_allclose(data1, data11, rtol=1e-6)
assert_array_almost_equal(times1, times11)
assert_equal(sorted(raw1.info.keys()), sorted(raw11.info.keys()))
-
- raw2 = read_raw_edf(edf_path, stim_channel=None, preload=True)
- raw2_file = op.join(tempdir, 'test2-raw.fif')
- raw2.save(raw2_file, overwrite=True)
- data2, times2 = raw2[:139, :]
- assert_allclose(data1, data2, rtol=1e-6)
- assert_array_equal(times1, times2)
+ data2, times2 = raw1[0, 0:1]
+ assert_array_equal(data2[0], data1[0, 0:1])
+ assert_array_equal(times2, times1[0:1])
+
+ buffer_fname = op.join(tempdir, 'buffer')
+ for preload in (buffer_fname, True, False): # false here means "delayed"
+ raw2 = read_raw_edf(edf_path, stim_channel=None, preload=preload)
+ if preload is False:
+ raw2.preload_data()
+ raw2_file = op.join(tempdir, 'test2-raw.fif')
+ raw2.save(raw2_file, overwrite=True)
+ data2, times2 = raw2[:139, :]
+ assert_allclose(data1, data2, rtol=1e-6)
+ assert_array_equal(times1, times2)
raw1 = Raw(raw1_file, preload=True)
raw2 = Raw(raw2_file, preload=True)
diff --git a/mne/io/egi/tests/test_egi.py b/mne/io/egi/tests/test_egi.py
index b12e59c38..4faf0535b 100644
--- a/mne/io/egi/tests/test_egi.py
+++ b/mne/io/egi/tests/test_egi.py
@@ -26,7 +26,8 @@ def test_io_egi():
tempdir = _TempDir()
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter('always', category=RuntimeWarning)
- read_raw_egi(egi_fname, include=None)
+ raw = read_raw_egi(egi_fname, include=None)
+ raw.preload_data() # currently does nothing
assert_equal(len(w), 1)
assert_true(w[0].category == RuntimeWarning)
msg = 'Did not find any event code with more than one event.'
diff --git a/mne/io/kit/tests/test_kit.py b/mne/io/kit/tests/test_kit.py
index b3fe8a434..43f711f2c 100644
--- a/mne/io/kit/tests/test_kit.py
+++ b/mne/io/kit/tests/test_kit.py
@@ -96,12 +96,25 @@ def test_read_segment():
preload=True)
raw2_file = op.join(tempdir, 'test2-raw.fif')
raw2.save(raw2_file, buffer_size_sec=.1, overwrite=True)
+ data1, times1 = raw1[0, 0:1]
+
raw1 = Raw(raw1_file, preload=True)
raw2 = Raw(raw2_file, preload=True)
assert_array_equal(raw1._data, raw2._data)
+ data2, times2 = raw2[0, 0:1]
+ assert_array_almost_equal(data1, data2)
+ assert_array_almost_equal(times1, times2)
raw3 = read_raw_kit(sqd_path, mrk_path, elp_path, hsp_path, stim='<',
preload=True)
assert_array_almost_equal(raw1._data, raw3._data)
+ raw4 = read_raw_kit(sqd_path, mrk_path, elp_path, hsp_path, stim='<',
+ preload=False)
+ raw4.preload_data()
+ buffer_fname = op.join(tempdir, 'buffer')
+ assert_array_almost_equal(raw1._data, raw4._data)
+ raw5 = read_raw_kit(sqd_path, mrk_path, elp_path, hsp_path, stim='<',
+ preload=buffer_fname)
+ assert_array_almost_equal(raw1._data, raw5._data)
def test_ch_loc():
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 2,
"issue_text_score": 1,
"test_score": 3
},
"num_modified_files": 4
} | 0.8 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[dev]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"numpy>=1.16.0",
"pandas>=1.0.0",
"scikit-learn",
"h5py",
"pysurfer",
"nose",
"nose-timer",
"pytest"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.7",
"reqs_path": [
"requirements/base.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | apptools==5.2.1
certifi @ file:///croot/certifi_1671487769961/work/certifi
configobj==5.0.9
cycler==0.11.0
envisage==7.0.3
exceptiongroup==1.2.2
fonttools==4.38.0
h5py==3.8.0
importlib-metadata==6.7.0
importlib-resources==5.12.0
iniconfig==2.0.0
joblib==1.3.2
kiwisolver==1.4.5
matplotlib==3.5.3
mayavi==4.8.1
-e git+https://github.com/mne-tools/mne-python.git@f2ab0641f087c63beab715ff5fdaa9399c0807fe#egg=mne
nibabel==4.0.2
nose==1.3.7
nose-timer==1.0.1
numpy==1.21.6
packaging==24.0
pandas==1.3.5
Pillow==9.5.0
pluggy==1.2.0
pyface==8.0.0
Pygments==2.17.2
pyparsing==3.1.4
pysurfer==0.11.2
pytest==7.4.4
python-dateutil==2.9.0.post0
pytz==2025.2
scikit-learn==1.0.2
scipy==1.7.3
six==1.17.0
threadpoolctl==3.1.0
tomli==2.0.1
traits==6.4.3
traitsui==8.0.0
typing_extensions==4.7.1
vtk==9.3.1
zipp==3.15.0
| name: mne-python
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2022.12.7=py37h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- pip=22.3.1=py37h06a4308_0
- python=3.7.16=h7a1cb2a_0
- readline=8.2=h5eee18b_0
- setuptools=65.6.3=py37h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- wheel=0.38.4=py37h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- apptools==5.2.1
- configobj==5.0.9
- cycler==0.11.0
- envisage==7.0.3
- exceptiongroup==1.2.2
- fonttools==4.38.0
- h5py==3.8.0
- importlib-metadata==6.7.0
- importlib-resources==5.12.0
- iniconfig==2.0.0
- joblib==1.3.2
- kiwisolver==1.4.5
- matplotlib==3.5.3
- mayavi==4.8.1
- nibabel==4.0.2
- nose==1.3.7
- nose-timer==1.0.1
- numpy==1.21.6
- packaging==24.0
- pandas==1.3.5
- pillow==9.5.0
- pluggy==1.2.0
- pyface==8.0.0
- pygments==2.17.2
- pyparsing==3.1.4
- pysurfer==0.11.2
- pytest==7.4.4
- python-dateutil==2.9.0.post0
- pytz==2025.2
- scikit-learn==1.0.2
- scipy==1.7.3
- six==1.17.0
- threadpoolctl==3.1.0
- tomli==2.0.1
- traits==6.4.3
- traitsui==8.0.0
- typing-extensions==4.7.1
- vtk==9.3.1
- zipp==3.15.0
prefix: /opt/conda/envs/mne-python
| [
"mne/io/brainvision/tests/test_brainvision.py::test_brainvision_data",
"mne/io/bti/tests/test_bti.py::test_crop",
"mne/io/edf/tests/test_edf.py::test_read_segment",
"mne/io/egi/tests/test_egi.py::test_io_egi",
"mne/io/kit/tests/test_kit.py::test_read_segment"
] | [] | [
"mne/io/brainvision/tests/test_brainvision.py::test_brainvision_data_filters",
"mne/io/brainvision/tests/test_brainvision.py::test_events",
"mne/io/brainvision/tests/test_brainvision.py::test_read_segment",
"mne/io/bti/tests/test_bti.py::test_read_config",
"mne/io/bti/tests/test_bti.py::test_read_pdf",
"mne/io/bti/tests/test_bti.py::test_raw",
"mne/io/bti/tests/test_bti.py::test_setup_headshape",
"mne/io/edf/tests/test_edf.py::test_bdf_data",
"mne/io/edf/tests/test_edf.py::test_edf_data",
"mne/io/edf/tests/test_edf.py::test_append",
"mne/io/edf/tests/test_edf.py::test_parse_annotation",
"mne/io/edf/tests/test_edf.py::test_edf_annotations",
"mne/io/edf/tests/test_edf.py::test_write_annotations",
"mne/io/kit/tests/test_kit.py::test_data",
"mne/io/kit/tests/test_kit.py::test_epochs",
"mne/io/kit/tests/test_kit.py::test_ch_loc",
"mne/io/kit/tests/test_kit.py::test_stim_ch"
] | [] | BSD 3-Clause "New" or "Revised" License | 134 |
typesafehub__conductr-cli-57 | 357be15356b14f09069cf542e8a4765edd6a0d0a | 2015-05-13 17:22:23 | 357be15356b14f09069cf542e8a4765edd6a0d0a | diff --git a/conductr_cli/conduct_load.py b/conductr_cli/conduct_load.py
index 38bc3d8..982965d 100644
--- a/conductr_cli/conduct_load.py
+++ b/conductr_cli/conduct_load.py
@@ -19,11 +19,14 @@ def load(args):
"""`conduct load` command"""
print('Retrieving bundle...')
- bundle_file, bundle_headers = urlretrieve(get_url(args.bundle))
+ bundle_name, bundle_url = get_url(args.bundle)
+ bundle_file, bundle_headers = urlretrieve(bundle_url)
+
+ configuration_file, configuration_headers, configuration_name = (None, None, None)
if args.configuration is not None:
print('Retrieving configuration...')
- configuration_file, configuration_headers = urlretrieve(get_url(args.configuration)) \
- if args.configuration is not None else (None, None)
+ configuration_name, configuration_url = get_url(args.configuration)
+ configuration_file, configuration_headers = urlretrieve(configuration_url)
bundle_conf = ConfigFactory.parse_string(bundle_utils.conf(bundle_file))
overlay_bundle_conf = None if configuration_file is None else \
@@ -39,10 +42,10 @@ def load(args):
('roles', ' '.join(with_bundle_configurations(ConfigTree.get_list, 'roles'))),
('bundleName', with_bundle_configurations(ConfigTree.get_string, 'name')),
('system', with_bundle_configurations(ConfigTree.get_string, 'system')),
- ('bundle', open(bundle_file, 'rb'))
+ ('bundle', (bundle_name, open(bundle_file, 'rb')))
]
if configuration_file is not None:
- files.append(('configuration', open(configuration_file, 'rb')))
+ files.append(('configuration', (configuration_name, open(configuration_file, 'rb'))))
print('Loading bundle to ConductR...')
response = requests.post(url, files=files)
@@ -74,4 +77,5 @@ def get_url(uri):
parsed = urlparse(uri, scheme='file')
op = Path(uri)
np = str(op.cwd() / op if parsed.scheme == 'file' and op.root == '' else parsed.path)
- return urlunparse(ParseResult(parsed.scheme, parsed.netloc, np, parsed.params, parsed.query, parsed.fragment))
+ url = urlunparse(ParseResult(parsed.scheme, parsed.netloc, np, parsed.params, parsed.query, parsed.fragment))
+ return (url.split('/')[-1], url)
| Unable to load bundle from https
ConductR RC1, CLI 0.15
Loading a bundle via https hangs. The cli must be terminated.
```bash
> conduct load https://github.com/typesafehub/project-doc/releases/download/1.0/project-doc-1.0-SNAPSHOT-e78ed07d4a895e14595a21aef1bf616b1b0e4d886f3265bc7b152acf93d259b5.zip
Retrieving bundle...
Retrieving configuration...
Loading bundle to ConductR...
```
If I wget the bundle to the local file system, the bundle loads successfully. | typesafehub/conductr-cli | diff --git a/conductr_cli/test/test_conduct_load.py b/conductr_cli/test/test_conduct_load.py
index b5503cb..93ee6f7 100644
--- a/conductr_cli/test/test_conduct_load.py
+++ b/conductr_cli/test/test_conduct_load.py
@@ -2,6 +2,7 @@ from unittest import TestCase
from conductr_cli.test.cli_test_case import CliTestCase, create_temp_bundle, create_temp_bundle_with_contents, strip_margin
from conductr_cli import conduct_load
from urllib.error import URLError
+import os
import shutil
try:
@@ -54,7 +55,7 @@ class TestConductLoadCommand(TestCase, CliTestCase):
('roles', ' '.join(roles)),
('bundleName', bundleName),
('system', system),
- ('bundle', 1)
+ ('bundle', ('bundle.zip', 1))
]
output_template = """|Retrieving bundle...
@@ -177,7 +178,7 @@ class TestConductLoadCommand(TestCase, CliTestCase):
[call(self.bundle_file, 'rb'), call(config_file, 'rb')]
)
- expected_files = self.default_files + [('configuration', 1)]
+ expected_files = self.default_files + [('configuration', ('bundle.zip', 1))]
expected_files[4] = ('bundleName', 'overlaid-name')
http_method.assert_called_with(self.default_url, files=expected_files)
@@ -361,3 +362,16 @@ class TestConductLoadCommand(TestCase, CliTestCase):
strip_margin("""|ERROR: File not found: no_such.conf
|"""),
self.output(stderr))
+
+
+class TestGetUrl(TestCase):
+
+ def test_url(self):
+ filename, url = conduct_load.get_url('https://site.com/bundle-1.0-e78ed07d4a895e14595a21aef1bf616b1b0e4d886f3265bc7b152acf93d259b5.zip')
+ self.assertEqual('bundle-1.0-e78ed07d4a895e14595a21aef1bf616b1b0e4d886f3265bc7b152acf93d259b5.zip', filename)
+ self.assertEqual('https://site.com/bundle-1.0-e78ed07d4a895e14595a21aef1bf616b1b0e4d886f3265bc7b152acf93d259b5.zip', url)
+
+ def test_file(self):
+ filename, url = conduct_load.get_url('bundle-1.0-e78ed07d4a895e14595a21aef1bf616b1b0e4d886f3265bc7b152acf93d259b5.zip')
+ self.assertEqual('bundle-1.0-e78ed07d4a895e14595a21aef1bf616b1b0e4d886f3265bc7b152acf93d259b5.zip', filename)
+ self.assertEqual('file://' + os.getcwd() + '/bundle-1.0-e78ed07d4a895e14595a21aef1bf616b1b0e4d886f3265bc7b152acf93d259b5.zip', url)
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_hyperlinks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 1,
"issue_text_score": 1,
"test_score": 3
},
"num_modified_files": 1
} | 0.15 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "pytest",
"pip_packages": [
"nose",
"flake8",
"pep8-naming",
"git+https://github.com/zheller/flake8-quotes#aef86c4f8388e790332757e5921047ad53160a75",
"pytest"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.9",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | argcomplete==3.6.1
certifi==2025.1.31
charset-normalizer==3.4.1
-e git+https://github.com/typesafehub/conductr-cli.git@357be15356b14f09069cf542e8a4765edd6a0d0a#egg=conductr_cli
exceptiongroup @ file:///croot/exceptiongroup_1706031385326/work
flake8==7.2.0
flake8-quotes @ git+https://github.com/zheller/flake8-quotes@e75accbd40f0e1fa1e8f0e746b93c9766db8f106
idna==3.10
iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work
mccabe==0.7.0
nose==1.3.7
packaging @ file:///croot/packaging_1734472117206/work
pep8-naming==0.14.1
pluggy @ file:///croot/pluggy_1733169602837/work
pycodestyle==2.13.0
pyflakes==3.3.1
pyhocon==0.2.1
pyparsing==2.0.3
pytest @ file:///croot/pytest_1738938843180/work
requests==2.32.3
tomli @ file:///opt/conda/conda-bld/tomli_1657175507142/work
urllib3==2.3.0
| name: conductr-cli
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- exceptiongroup=1.2.0=py39h06a4308_0
- iniconfig=1.1.1=pyhd3eb1b0_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=3.0.16=h5eee18b_0
- packaging=24.2=py39h06a4308_0
- pip=25.0=py39h06a4308_0
- pluggy=1.5.0=py39h06a4308_0
- pytest=8.3.4=py39h06a4308_0
- python=3.9.21=he870216_1
- readline=8.2=h5eee18b_0
- setuptools=75.8.0=py39h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- tomli=2.0.1=py39h06a4308_0
- tzdata=2025a=h04d1e81_0
- wheel=0.45.1=py39h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- argcomplete==3.6.1
- certifi==2025.1.31
- charset-normalizer==3.4.1
- flake8==7.2.0
- flake8-quotes==3.4.0
- idna==3.10
- mccabe==0.7.0
- nose==1.3.7
- pep8-naming==0.14.1
- pycodestyle==2.13.0
- pyflakes==3.3.1
- pyhocon==0.2.1
- pyparsing==2.0.3
- requests==2.32.3
- urllib3==2.3.0
prefix: /opt/conda/envs/conductr-cli
| [
"conductr_cli/test/test_conduct_load.py::TestConductLoadCommand::test_failure",
"conductr_cli/test/test_conduct_load.py::TestConductLoadCommand::test_failure_invalid_address",
"conductr_cli/test/test_conduct_load.py::TestConductLoadCommand::test_success",
"conductr_cli/test/test_conduct_load.py::TestConductLoadCommand::test_success_custom_ip_port",
"conductr_cli/test/test_conduct_load.py::TestConductLoadCommand::test_success_long_ids",
"conductr_cli/test/test_conduct_load.py::TestConductLoadCommand::test_success_verbose",
"conductr_cli/test/test_conduct_load.py::TestConductLoadCommand::test_success_with_configuration",
"conductr_cli/test/test_conduct_load.py::TestGetUrl::test_file",
"conductr_cli/test/test_conduct_load.py::TestGetUrl::test_url"
] | [] | [
"conductr_cli/test/test_conduct_load.py::TestConductLoadCommand::test_failure_no_bundle",
"conductr_cli/test/test_conduct_load.py::TestConductLoadCommand::test_failure_no_configuration",
"conductr_cli/test/test_conduct_load.py::TestConductLoadCommand::test_failure_no_disk_space",
"conductr_cli/test/test_conduct_load.py::TestConductLoadCommand::test_failure_no_memory",
"conductr_cli/test/test_conduct_load.py::TestConductLoadCommand::test_failure_no_nr_of_cpus",
"conductr_cli/test/test_conduct_load.py::TestConductLoadCommand::test_failure_no_roles",
"conductr_cli/test/test_conduct_load.py::TestConductLoadCommand::test_failure_roles_not_a_list"
] | [] | Apache License 2.0 | 135 |
|
zopefoundation__Acquisition-10 | 6f20ea96fff40814882da580844949ea97f6c4ba | 2015-05-13 21:46:49 | 6f20ea96fff40814882da580844949ea97f6c4ba | diff --git a/CHANGES.rst b/CHANGES.rst
index 3e617c3..0b44a8b 100644
--- a/CHANGES.rst
+++ b/CHANGES.rst
@@ -4,7 +4,15 @@ Changelog
4.2.2 (unreleased)
------------------
-- TBD
+- Make the pure-Python Acquirer objects cooperatively use the
+ superclass ``__getattribute__`` method, like the C implementation.
+ See https://github.com/zopefoundation/Acquisition/issues/7.
+
+- The pure-Python implicit acquisition wrapper allows wrapped objects
+ to use ``object.__getattribute__(self, name)``. This differs from
+ the C implementation, but is important for compatibility with the
+ pure-Python versions of libraries like ``persistent``. See
+ https://github.com/zopefoundation/Acquisition/issues/9.
4.2.1 (2015-04-23)
------------------
diff --git a/src/Acquisition/__init__.py b/src/Acquisition/__init__.py
index eae7d7c..c44bbba 100644
--- a/src/Acquisition/__init__.py
+++ b/src/Acquisition/__init__.py
@@ -2,10 +2,12 @@ from __future__ import absolute_import, print_function
# pylint:disable=W0212,R0911,R0912
+
import os
import operator
import sys
import types
+import weakref
import ExtensionClass
@@ -39,17 +41,30 @@ def _apply_filter(predicate, inst, name, result, extra, orig):
return predicate(orig, inst, name, result, extra)
if sys.version_info < (3,):
+ import copy_reg
+
def _rebound_method(method, wrapper):
"""Returns a version of the method with self bound to `wrapper`"""
if isinstance(method, types.MethodType):
method = types.MethodType(method.im_func, wrapper, method.im_class)
return method
+ exec("""def _reraise(tp, value, tb=None):
+ raise tp, value, tb
+""")
else: # pragma: no cover (python 2 is currently our reference)
+ import copyreg as copy_reg
+
def _rebound_method(method, wrapper):
"""Returns a version of the method with self bound to `wrapper`"""
if isinstance(method, types.MethodType):
method = types.MethodType(method.__func__, wrapper)
return method
+ def _reraise(tp, value, tb=None):
+ if value is None:
+ value = tp()
+ if value.__traceback__ is not tb:
+ raise value.with_traceback(tb)
+ raise value
###
# Wrapper object protocol, mostly ported from C directly
@@ -283,16 +298,58 @@ def _Wrapper_findattr(wrapper, name,
_NOT_GIVEN = object() # marker
+_OGA = object.__getattribute__
+
+# Map from object types with slots to their generated, derived
+# types (or None if no derived type is needed)
+_wrapper_subclass_cache = weakref.WeakKeyDictionary()
+
+def _make_wrapper_subclass_if_needed(cls, obj, container):
+ # If the type of an object to be wrapped has __slots__, then we
+ # must create a wrapper subclass that has descriptors for those
+ # same slots. In this way, its methods that use object.__getattribute__
+ # directly will continue to work, even when given an instance of _Wrapper
+ if getattr(cls, '_Wrapper__DERIVED', False):
+ return None
+ type_obj = type(obj)
+ wrapper_subclass = _wrapper_subclass_cache.get(type_obj, _NOT_GIVEN)
+ if wrapper_subclass is _NOT_GIVEN:
+ slotnames = copy_reg._slotnames(type_obj)
+ if slotnames and not isinstance(obj, _Wrapper):
+ new_type_dict = {'_Wrapper__DERIVED': True}
+ def _make_property(slotname):
+ return property(lambda s: getattr(s._obj, slotname),
+ lambda s, v: setattr(s._obj, slotname, v),
+ lambda s: delattr(s._obj, slotname))
+ for slotname in slotnames:
+ new_type_dict[slotname] = _make_property(slotname)
+ new_type = type(cls.__name__ + '_' + type_obj.__name__,
+ (cls,),
+ new_type_dict)
+ else:
+ new_type = None
+ wrapper_subclass = _wrapper_subclass_cache[type_obj] = new_type
+ return wrapper_subclass
class _Wrapper(ExtensionClass.Base):
- __slots__ = ('_obj','_container',)
+ __slots__ = ('_obj','_container', '__dict__')
_IS_IMPLICIT = None
def __new__(cls, obj, container):
- inst = super(_Wrapper,cls).__new__(cls)
+ wrapper_subclass = _make_wrapper_subclass_if_needed(cls, obj, container)
+ if wrapper_subclass:
+ inst = wrapper_subclass(obj, container)
+ else:
+ inst = super(_Wrapper,cls).__new__(cls)
inst._obj = obj
inst._container = container
+ if hasattr(obj, '__dict__') and not isinstance(obj, _Wrapper):
+ # Make our __dict__ refer to the same dict
+ # as the other object, so that if it has methods that
+ # use `object.__getattribute__` they still work. Note that because we have
+ # slots, we won't interfere with the contents of that dict
+ object.__setattr__(inst, '__dict__', obj.__dict__)
return inst
def __init__(self, obj, container):
@@ -325,11 +382,11 @@ class _Wrapper(ExtensionClass.Base):
def __getattribute__(self, name):
if name in ('_obj', '_container'):
- return object.__getattribute__(self, name)
- if self._obj is not None or self._container is not None:
+ return _OGA(self, name)
+ if _OGA(self, '_obj') is not None or _OGA(self, '_container') is not None:
return _Wrapper_findattr(self, name, None, None, None,
True, type(self)._IS_IMPLICIT, False, False)
- return object.__getattribute__(self, name)
+ return _OGA(self, name)
def __of__(self, parent):
# Based on __of__ in the C code;
@@ -684,11 +741,15 @@ class _Acquirer(ExtensionClass.Base):
def __getattribute__(self, name):
try:
- return ExtensionClass.Base.__getattribute__(self, name)
+ return super(_Acquirer, self).__getattribute__(name)
except AttributeError:
# the doctests have very specific error message
- # requirements
- raise AttributeError(name)
+ # requirements (but at least we can preserve the traceback)
+ _, _, tb = sys.exc_info()
+ try:
+ _reraise(AttributeError, AttributeError(name), tb)
+ finally:
+ del tb
def __of__(self, context):
return type(self)._Wrapper(self, context)
| Pure-Python Wrapper objects break `object.__getattribute__` in methods of the wrapped object
Certain "base" classes make direct use of `object.__getattribute__` in their method implementations. (i.e., *outside* of their own `__getattribute__` implementation). They may do this for performance reasons, or to simplify their implementation of `__getattribute__`. One prominent example is `persistent.Persistent`, but there are undoubtedly others.
If classes like this are wrapped with a pure-Python acquisition wrapper, those methods fail, because the `self` they have is not the `self` they expect (it's the wrapper), and directly calling `object.__getattribute__` bypasses the wrapper's `__getattribute__` implementation.
Here's an example test that fails with pure-Python, but works under the C implementation:
```python
def test_object_getattribute_in_rebound_method(self):
class Persistent(object):
__slots__ = ('__flags')
def __init__(self):
self.__flags = 42
def get_flags(self):
return object.__getattribute__(self, '_Persistent__flags')
wrapped = Persistent()
wrapper = Acquisition.ImplicitAcquisitionWrapper(wrapped, None)
self.assertEqual(wrapped.get_flags(), wrapper.get_flags())
```
It fails like so:
```
File "/Acquisition/tests.py", line 3171, in test_object_getattribute_in_rebound_method
self.assertEqual(wrapped.get_flags(), wrapper.get_flags())
File "/Acquisition/tests.py", line 3166, in get_flags
return object.__getattribute__(self, '_Persistent__flags')
AttributeError: 'ImplicitAcquisitionWrapper' object has no attribute '_Persistent__flags'
```
I'm trying to figure out how to fix this. | zopefoundation/Acquisition | diff --git a/src/Acquisition/tests.py b/src/Acquisition/tests.py
index 4bc523f..277d0fe 100644
--- a/src/Acquisition/tests.py
+++ b/src/Acquisition/tests.py
@@ -3124,6 +3124,125 @@ class TestAcquire(unittest.TestCase):
found = self.acquire(self.a.b.c, AQ_PARENT)
self.assertTrue(found.aq_self is self.a.b.aq_self)
+class TestCooperativeBase(unittest.TestCase):
+
+ def _make_acquirer(self, kind):
+ from ExtensionClass import Base
+
+ class ExtendsBase(Base):
+ def __getattribute__(self, name):
+ if name == 'magic':
+ return 42
+ return super(ExtendsBase,self).__getattribute__(name)
+
+ class Acquirer(kind, ExtendsBase):
+ pass
+
+ return Acquirer()
+
+ def _check___getattribute___is_cooperative(self, acquirer):
+ self.assertEqual(getattr(acquirer, 'magic'), 42)
+
+ def test_implicit___getattribute__is_cooperative(self):
+ self._check___getattribute___is_cooperative(self._make_acquirer(Acquisition.Implicit))
+
+ def test_explicit___getattribute__is_cooperative(self):
+ self._check___getattribute___is_cooperative(self._make_acquirer(Acquisition.Explicit))
+
+if 'Acquisition._Acquisition' not in sys.modules:
+ # Implicitly wrapping an object that uses object.__getattribute__
+ # in its implementation of __getattribute__ doesn't break.
+ # This can arise with the `persistent` library or other
+ # "base" classes.
+
+ # The C implementation doesn't directly support this; however,
+ # it is used heavily in the Python implementation of Persistent.
+
+ class TestImplicitWrappingGetattribute(unittest.TestCase):
+
+ def test_object_getattribute_in_rebound_method_with_slots(self):
+
+ class Persistent(object):
+ __slots__ = ('__flags',)
+ def __init__(self):
+ self.__flags = 42
+
+ def get_flags(self):
+ return object.__getattribute__(self, '_Persistent__flags')
+
+ wrapped = Persistent()
+ wrapper = Acquisition.ImplicitAcquisitionWrapper(wrapped, None)
+
+ self.assertEqual(wrapped.get_flags(), wrapper.get_flags())
+
+ # Changing it is not reflected in the wrapper's dict (this is an
+ # implementation detail)
+ wrapper._Persistent__flags = -1
+ self.assertEqual(wrapped.get_flags(), -1)
+ self.assertEqual(wrapped.get_flags(), wrapper.get_flags())
+
+ wrapper_dict = object.__getattribute__(wrapper, '__dict__')
+ self.assertFalse('_Persistent__flags' in wrapper_dict)
+
+ def test_type_with_slots_reused(self):
+
+ class Persistent(object):
+ __slots__ = ('__flags',)
+ def __init__(self):
+ self.__flags = 42
+
+ def get_flags(self):
+ return object.__getattribute__(self, '_Persistent__flags')
+
+ wrapped = Persistent()
+ wrapper = Acquisition.ImplicitAcquisitionWrapper(wrapped, None)
+ wrapper2 = Acquisition.ImplicitAcquisitionWrapper(wrapped, None)
+
+ self.assertTrue( type(wrapper) is type(wrapper2))
+
+ def test_object_getattribute_in_rebound_method_with_dict(self):
+
+ class Persistent(object):
+ def __init__(self):
+ self.__flags = 42
+
+ def get_flags(self):
+ return object.__getattribute__(self, '_Persistent__flags')
+
+ wrapped = Persistent()
+ wrapper = Acquisition.ImplicitAcquisitionWrapper(wrapped, None)
+
+ self.assertEqual(wrapped.get_flags(), wrapper.get_flags())
+
+ # Changing it is also reflected in both dicts (this is an
+ # implementation detail)
+ wrapper._Persistent__flags = -1
+ self.assertEqual(wrapped.get_flags(), -1)
+ self.assertEqual(wrapped.get_flags(), wrapper.get_flags())
+
+ wrapper_dict = object.__getattribute__(wrapper, '__dict__')
+ self.assertTrue('_Persistent__flags' in wrapper_dict)
+
+
+ def test_object_getattribute_in_rebound_method_with_slots_and_dict(self):
+
+ class Persistent(object):
+ __slots__ = ('__flags', '__dict__')
+ def __init__(self):
+ self.__flags = 42
+ self.__oid = 'oid'
+
+ def get_flags(self):
+ return object.__getattribute__(self, '_Persistent__flags')
+
+ def get_oid(self):
+ return object.__getattribute__(self, '_Persistent__oid')
+
+ wrapped = Persistent()
+ wrapper = Acquisition.ImplicitAcquisitionWrapper(wrapped, None)
+
+ self.assertEqual(wrapped.get_flags(), wrapper.get_flags())
+ self.assertEqual(wrapped.get_oid(), wrapper.get_oid())
class TestUnicode(unittest.TestCase):
@@ -3537,6 +3656,7 @@ def test_suite():
unittest.makeSuite(TestAcquire),
unittest.makeSuite(TestUnicode),
unittest.makeSuite(TestProxying),
+ unittest.makeSuite(TestCooperativeBase),
]
# This file is only available in a source checkout, skip it
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 2,
"issue_text_score": 1,
"test_score": 2
},
"num_modified_files": 2
} | 4.2 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"nose",
"pytest"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.7",
"reqs_path": [
"requirements/base.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | -e git+https://github.com/zopefoundation/Acquisition.git@6f20ea96fff40814882da580844949ea97f6c4ba#egg=Acquisition
certifi @ file:///croot/certifi_1671487769961/work/certifi
exceptiongroup==1.2.2
ExtensionClass==5.1
importlib-metadata==6.7.0
iniconfig==2.0.0
nose==1.3.7
packaging==24.0
pluggy==1.2.0
pytest==7.4.4
tomli==2.0.1
typing_extensions==4.7.1
zipp==3.15.0
zope.interface==6.4.post2
| name: Acquisition
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2022.12.7=py37h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- pip=22.3.1=py37h06a4308_0
- python=3.7.16=h7a1cb2a_0
- readline=8.2=h5eee18b_0
- setuptools=65.6.3=py37h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- wheel=0.38.4=py37h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- exceptiongroup==1.2.2
- extensionclass==5.1
- importlib-metadata==6.7.0
- iniconfig==2.0.0
- nose==1.3.7
- packaging==24.0
- pluggy==1.2.0
- pytest==7.4.4
- tomli==2.0.1
- typing-extensions==4.7.1
- zipp==3.15.0
- zope-interface==6.4.post2
prefix: /opt/conda/envs/Acquisition
| [
"src/Acquisition/tests.py::TestCooperativeBase::test_explicit___getattribute__is_cooperative",
"src/Acquisition/tests.py::TestCooperativeBase::test_implicit___getattribute__is_cooperative",
"src/Acquisition/tests.py::TestImplicitWrappingGetattribute::test_object_getattribute_in_rebound_method_with_dict",
"src/Acquisition/tests.py::TestImplicitWrappingGetattribute::test_object_getattribute_in_rebound_method_with_slots",
"src/Acquisition/tests.py::TestImplicitWrappingGetattribute::test_object_getattribute_in_rebound_method_with_slots_and_dict"
] | [
"src/Acquisition/tests.py::test_suite"
] | [
"src/Acquisition/tests.py::test_unwrapped",
"src/Acquisition/tests.py::test_simple",
"src/Acquisition/tests.py::test__of__exception",
"src/Acquisition/tests.py::test_muliple",
"src/Acquisition/tests.py::test_pinball",
"src/Acquisition/tests.py::test_explicit",
"src/Acquisition/tests.py::test_mixed_explicit_and_explicit",
"src/Acquisition/tests.py::test_aq_inContextOf",
"src/Acquisition/tests.py::test_AqAlg",
"src/Acquisition/tests.py::test_explicit_acquisition",
"src/Acquisition/tests.py::test_creating_wrappers_directly",
"src/Acquisition/tests.py::test_cant_pickle_acquisition_wrappers_classic",
"src/Acquisition/tests.py::test_cant_pickle_acquisition_wrappers_newstyle",
"src/Acquisition/tests.py::test_cant_persist_acquisition_wrappers_classic",
"src/Acquisition/tests.py::test_cant_persist_acquisition_wrappers_newstyle",
"src/Acquisition/tests.py::test_interfaces",
"src/Acquisition/tests.py::test_mixin_post_class_definition",
"src/Acquisition/tests.py::test_mixin_base",
"src/Acquisition/tests.py::test_Basic_gc",
"src/Acquisition/tests.py::test_Wrapper_gc",
"src/Acquisition/tests.py::test_container_proxying",
"src/Acquisition/tests.py::test___parent__no_wrappers",
"src/Acquisition/tests.py::test_implicit_wrapper_as___parent__",
"src/Acquisition/tests.py::test_explicit_wrapper_as___parent__",
"src/Acquisition/tests.py::test_implicit_wrapper_has_nonwrapper_as_aq_parent",
"src/Acquisition/tests.py::test_explicit_wrapper_has_nonwrapper_as_aq_parent",
"src/Acquisition/tests.py::test___parent__aq_parent_circles",
"src/Acquisition/tests.py::test_python_impl_cycle",
"src/Acquisition/tests.py::test_unwrapped_implicit_acquirer_unwraps__parent__",
"src/Acquisition/tests.py::test__iter__after_AttributeError",
"src/Acquisition/tests.py::test_special_names",
"src/Acquisition/tests.py::test_deleting_parent_attrs",
"src/Acquisition/tests.py::test__cmp__is_called_on_wrapped_object",
"src/Acquisition/tests.py::test_wrapped_methods_have_correct_self",
"src/Acquisition/tests.py::test_cannot_set_attributes_on_empty_wrappers",
"src/Acquisition/tests.py::test_getitem_setitem_not_implemented",
"src/Acquisition/tests.py::test_getitem_setitem_implemented",
"src/Acquisition/tests.py::test_wrapped_objects_are_unwrapped_on_set",
"src/Acquisition/tests.py::test_wrapper_calls_of_on_non_wrapper",
"src/Acquisition/tests.py::test_aq_inContextOf_odd_cases",
"src/Acquisition/tests.py::test_search_repeated_objects",
"src/Acquisition/tests.py::TestParent::test_parent_parent_circles",
"src/Acquisition/tests.py::TestParent::test_parent_parent_parent_circles",
"src/Acquisition/tests.py::TestAcquire::test_explicit_module_default",
"src/Acquisition/tests.py::TestAcquire::test_explicit_module_false",
"src/Acquisition/tests.py::TestAcquire::test_explicit_module_true",
"src/Acquisition/tests.py::TestAcquire::test_explicit_wrapper_default",
"src/Acquisition/tests.py::TestAcquire::test_explicit_wrapper_false",
"src/Acquisition/tests.py::TestAcquire::test_explicit_wrapper_true",
"src/Acquisition/tests.py::TestAcquire::test_no_wrapper_but___parent___falls_back_to_default",
"src/Acquisition/tests.py::TestAcquire::test_unwrapped_falls_back_to_default",
"src/Acquisition/tests.py::TestAcquire::test_w_unicode_attr_name",
"src/Acquisition/tests.py::TestAcquire::test_wrapper_falls_back_to_default",
"src/Acquisition/tests.py::TestImplicitWrappingGetattribute::test_type_with_slots_reused",
"src/Acquisition/tests.py::TestUnicode::test_explicit_aq_unicode_should_be_called",
"src/Acquisition/tests.py::TestUnicode::test_explicit_should_fall_back_to_str",
"src/Acquisition/tests.py::TestUnicode::test_implicit_aq_unicode_should_be_called",
"src/Acquisition/tests.py::TestUnicode::test_implicit_should_fall_back_to_str",
"src/Acquisition/tests.py::TestUnicode::test_str_fallback_should_be_called_with_wrapped_self",
"src/Acquisition/tests.py::TestUnicode::test_unicode_should_be_called_with_wrapped_self",
"src/Acquisition/tests.py::TestProxying::test_explicit_proxy_bool",
"src/Acquisition/tests.py::TestProxying::test_explicit_proxy_call",
"src/Acquisition/tests.py::TestProxying::test_explicit_proxy_comporison",
"src/Acquisition/tests.py::TestProxying::test_explicit_proxy_contains",
"src/Acquisition/tests.py::TestProxying::test_explicit_proxy_hash",
"src/Acquisition/tests.py::TestProxying::test_explicit_proxy_special_meths",
"src/Acquisition/tests.py::TestProxying::test_implicit_proxy_bool",
"src/Acquisition/tests.py::TestProxying::test_implicit_proxy_call",
"src/Acquisition/tests.py::TestProxying::test_implicit_proxy_comporison",
"src/Acquisition/tests.py::TestProxying::test_implicit_proxy_contains",
"src/Acquisition/tests.py::TestProxying::test_implicit_proxy_hash",
"src/Acquisition/tests.py::TestProxying::test_implicit_proxy_special_meths"
] | [] | Zope Public License 2.1 | 136 |
|
chimpler__pyhocon-28 | 1dfded0867d7de333d2ee9bc90ee25b2d690f819 | 2015-05-14 03:44:54 | 4683937b1d195ce2f53ca78987571e41bfe273e7 | diff --git a/pyhocon/config_tree.py b/pyhocon/config_tree.py
index 60b2d88..d045c7b 100644
--- a/pyhocon/config_tree.py
+++ b/pyhocon/config_tree.py
@@ -70,6 +70,9 @@ class ConfigTree(OrderedDict):
type=l.__class__.__name__)
)
else:
+ # if there was an override keep overide value
+ if isinstance(value, ConfigValues):
+ value.overriden_value = self.get(key_elt, None)
super(ConfigTree, self).__setitem__(key_elt, value)
else:
next_config_tree = super(ConfigTree, self).get(key_elt)
| ${?foo} unsets previous value if new is undefined
pyhocon==0.3.2
Apparently `${?VAR_NAME}` no longer complains about undefined variables but is seems to be unsetting the key. My expectation is that `${?foo}` would leave the key referencing the last value unless it had something to replace it with.
```
...
File "/Users/bkuberek/Development/people-service/.venv/lib/python2.7/site-packages/pyhocon/__init__.py", line 203, in parse
ConfigParser._resolve_substitutions(config, substitutions)
File "/Users/bkuberek/Development/people-service/.venv/lib/python2.7/site-packages/pyhocon/__init__.py", line 246, in _resolve_substitutions
is_optional_resolved, resolved_value = ConfigParser._resolve_variable(config, substitution)
File "/Users/bkuberek/Development/people-service/.venv/lib/python2.7/site-packages/pyhocon/__init__.py", line 228, in _resolve_variable
col=col(substitution.loc, substitution.instring)))
pyhocon.exceptions.ConfigSubstitutionException: Cannot resolve variable ${database.name} (line: 20, col: 102)
```
Here is my configuration:
```
{
database {
host = "localhost"
port = "5432"
user = "people"
name = "peopledb"
pass = "dev"
url = "postgresql://"${database.user}":"${database.pass}"@"${database.host}":"${database.port}"/"${database.name}
# Override from environment variables if they exist
host = ${?DB_HOST}
port = ${?DB_PORT}
user = ${?DB_USER}
name = ${?DB_NAME}
pass = ${?DB_PASS}
}
}
```
| chimpler/pyhocon | diff --git a/tests/test_config_parser.py b/tests/test_config_parser.py
index b343d35..c0dbb15 100644
--- a/tests/test_config_parser.py
+++ b/tests/test_config_parser.py
@@ -797,7 +797,21 @@ class TestConfigParser(object):
assert config['database.user'] == 'test_user'
assert config['database.pass'] == 'test_pass'
- def test_substitution_override(self):
+ def test_substitution_flat_override(self):
+ config = ConfigFactory.parse_string(
+ """
+ database {
+ name = peopledb
+ pass = peoplepass
+ name = ${?NOT_EXISTS}
+ pass = ${?NOT_EXISTS}
+ }
+ """)
+
+ assert config['database.name'] == 'peopledb'
+ assert config['database.pass'] == 'peoplepass'
+
+ def test_substitution_nested_override(self):
config = ConfigFactory.parse_string(
"""
database {
| {
"commit_name": "head_commit",
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true,
"llm_score": {
"difficulty_score": 0,
"issue_text_score": 0,
"test_score": 0
},
"num_modified_files": 1
} | 0.3 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.9",
"reqs_path": [
"requirements/base.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | exceptiongroup==1.2.2
iniconfig==2.1.0
packaging==24.2
pluggy==1.5.0
-e git+https://github.com/chimpler/pyhocon.git@1dfded0867d7de333d2ee9bc90ee25b2d690f819#egg=pyhocon
pyparsing==2.0.3
pytest==8.3.5
tomli==2.2.1
| name: pyhocon
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=3.0.16=h5eee18b_0
- pip=25.0=py39h06a4308_0
- python=3.9.21=he870216_1
- readline=8.2=h5eee18b_0
- setuptools=75.8.0=py39h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- tzdata=2025a=h04d1e81_0
- wheel=0.45.1=py39h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- exceptiongroup==1.2.2
- iniconfig==2.1.0
- packaging==24.2
- pluggy==1.5.0
- pyparsing==2.0.3
- pytest==8.3.5
- tomli==2.2.1
prefix: /opt/conda/envs/pyhocon
| [
"tests/test_config_parser.py::TestConfigParser::test_substitution_flat_override"
] | [] | [
"tests/test_config_parser.py::TestConfigParser::test_parse_simple_value",
"tests/test_config_parser.py::TestConfigParser::test_parse_with_enclosing_brace",
"tests/test_config_parser.py::TestConfigParser::test_parse_with_enclosing_square_bracket",
"tests/test_config_parser.py::TestConfigParser::test_quoted_key_with_dots",
"tests/test_config_parser.py::TestConfigParser::test_comma_to_separate_expr",
"tests/test_config_parser.py::TestConfigParser::test_dict_merge",
"tests/test_config_parser.py::TestConfigParser::test_parse_with_comments",
"tests/test_config_parser.py::TestConfigParser::test_missing_config",
"tests/test_config_parser.py::TestConfigParser::test_parse_null",
"tests/test_config_parser.py::TestConfigParser::test_parse_empty",
"tests/test_config_parser.py::TestConfigParser::test_parse_override",
"tests/test_config_parser.py::TestConfigParser::test_concat_dict",
"tests/test_config_parser.py::TestConfigParser::test_concat_string",
"tests/test_config_parser.py::TestConfigParser::test_concat_list",
"tests/test_config_parser.py::TestConfigParser::test_bad_concat",
"tests/test_config_parser.py::TestConfigParser::test_string_substitutions",
"tests/test_config_parser.py::TestConfigParser::test_int_substitutions",
"tests/test_config_parser.py::TestConfigParser::test_cascade_string_substitutions",
"tests/test_config_parser.py::TestConfigParser::test_dict_substitutions",
"tests/test_config_parser.py::TestConfigParser::test_list_substitutions",
"tests/test_config_parser.py::TestConfigParser::test_non_existent_substitution",
"tests/test_config_parser.py::TestConfigParser::test_non_compatible_substitution",
"tests/test_config_parser.py::TestConfigParser::test_concat_multi_line_string",
"tests/test_config_parser.py::TestConfigParser::test_concat_multi_line_list",
"tests/test_config_parser.py::TestConfigParser::test_concat_multi_line_dict",
"tests/test_config_parser.py::TestConfigParser::test_parse_URL_from_samples",
"tests/test_config_parser.py::TestConfigParser::test_include_dict_from_samples",
"tests/test_config_parser.py::TestConfigParser::test_list_of_dicts",
"tests/test_config_parser.py::TestConfigParser::test_list_of_lists",
"tests/test_config_parser.py::TestConfigParser::test_list_of_dicts_with_merge",
"tests/test_config_parser.py::TestConfigParser::test_list_of_lists_with_merge",
"tests/test_config_parser.py::TestConfigParser::test_invalid_assignment",
"tests/test_config_parser.py::TestConfigParser::test_invalid_dict",
"tests/test_config_parser.py::TestConfigParser::test_include_list",
"tests/test_config_parser.py::TestConfigParser::test_include_dict",
"tests/test_config_parser.py::TestConfigParser::test_substitution_override",
"tests/test_config_parser.py::TestConfigParser::test_substitution_nested_override",
"tests/test_config_parser.py::TestConfigParser::test_optional_substitution",
"tests/test_config_parser.py::TestConfigParser::test_substitution_cycle",
"tests/test_config_parser.py::TestConfigParser::test_assign_number_with_eol",
"tests/test_config_parser.py::TestConfigParser::test_assign_strings_with_eol",
"tests/test_config_parser.py::TestConfigParser::test_assign_list_numbers_with_eol",
"tests/test_config_parser.py::TestConfigParser::test_assign_list_strings_with_eol",
"tests/test_config_parser.py::TestConfigParser::test_assign_dict_strings_with_equal_sign_with_eol",
"tests/test_config_parser.py::TestConfigParser::test_assign_dict_strings_no_equal_sign_with_eol"
] | [] | Apache License 2.0 | 137 |
|
mkdocs__mkdocs-528 | 93a181a208af0440f44e7f51081b9df9d9f30568 | 2015-05-15 04:38:15 | 463c5b647e9ce5992b519708a0b9c4cba891d65c | landscape-bot: [](https://landscape.io/diff/153156)
Code quality remained the same when pulling **[d3fa1bd](https://github.com/waylan/mkdocs/commit/d3fa1bd74f3d126c31e03d9330922b265354fa15) on waylan:519** into **[667fc66](https://github.com/mkdocs/mkdocs/commit/667fc663a2d9f6b3c7fb5c26777161a4ad42368f) on mkdocs:master**.
d0ugal: This looks great! I should be able to review it today.
landscape-bot: [](https://landscape.io/diff/154259)
Code quality remained the same when pulling **[06a74af](https://github.com/waylan/mkdocs/commit/06a74afdc8bfe120398344b021738e305ca246d3) on waylan:519** into **[93a181a](https://github.com/mkdocs/mkdocs/commit/93a181a208af0440f44e7f51081b9df9d9f30568) on mkdocs:master**.
d0ugal: This is lovely, do you plan to do any more updates? I'm happy to merge as it is. Tested it and it works great.
waylan: The only other thing I would consider doing at this point is removing the OrderedDict stuff for the config as this removes the need for it. I don't think it would hurt to leave it in, but removing it removes one more thing to maintain long-term. @facelessuser have any thoughts?
Regardless, that could happen latter. Feel free to merge any time.
facelessuser: Remove it, unless ordered dicts will be desired somewhere in the future. It hurts nothing, but I only added it because, at the time, it was decided not to do the extension config this way. But now we are, so the original need is gone. | diff --git a/docs/user-guide/configuration.md b/docs/user-guide/configuration.md
index 924e6207..4b9c5b8d 100644
--- a/docs/user-guide/configuration.md
+++ b/docs/user-guide/configuration.md
@@ -8,7 +8,7 @@ Guide to all available configuration settings.
Project settings are always configured by using a YAML configuration file in the project directory named `mkdocs.yml`.
-As a miniumum this configuration file must contain the `site_name` setting. All other settings are optional.
+As a minimum this configuration file must contain the `site_name` setting. All other settings are optional.
## Project information
@@ -16,7 +16,7 @@ As a miniumum this configuration file must contain the `site_name` setting. All
This is a **required setting**, and should be a string that is used as the main title for the project documentation. For example:
- site_name: Mashmallow Generator
+ site_name: Marshmallow Generator
When rendering the theme this setting will be passed as the `site_name` context variable.
@@ -109,9 +109,9 @@ If you have a lot of project documentation you might choose to use headings to b
pages:
- Introduction: 'index.md'
- User Guide:
- - 'Creating a new Mashmallow project': 'user-guide/creating.md'
- - 'Mashmallow API guide': 'user-guide/api.md'
- - 'Configuring Mashmallow': 'user-guide/configuration.md'
+ - 'Creating a new Marshmallow project': 'user-guide/creating.md'
+ - 'Marshmallow API guide': 'user-guide/api.md'
+ - 'Configuring Marshmallow': 'user-guide/configuration.md'
- About:
- License: 'about/license.md'
@@ -150,16 +150,21 @@ Lets you set the directory where the output HTML and other files are created. T
**default**: `'site'`
-**Note**: If you are using source code control you will normally want to ensure that your *build output* files are not commited into the repository, and only keep the *source* files under version control. For example, if using `git` you might add the following line to your `.gitignore` file:
+!!! note "Note:"
+ If you are using source code control you will normally want to ensure
+ that your *build output* files are not committed into the repository, and only
+ keep the *source* files under version control. For example, if using `git` you
+ might add the following line to your `.gitignore` file:
- site/
+ site/
-If you're using another source code control you'll want to check its documentation on how to ignore specific directories.
+ If you're using another source code control you'll want to check its
+ documentation on how to ignore specific directories.
### extra_css
-Set a list of css files to be included by the theme.
+Set a list of CSS files to be included by the theme.
**default**: By default `extra_css` will contain a list of all the CSS files found within the `docs_dir`, if none are found it will be `[]` (an empty list).
@@ -207,7 +212,7 @@ Determines if a broken link to a page within the documentation is considered a w
Determines the address used when running `mkdocs serve`. Setting this allows you to use another port, or allows you to make the service accessible over your local network by using the `0.0.0.0` address.
-As with all settings, you can set this from the command line, which can be usful, for example:
+As with all settings, you can set this from the command line, which can be useful, for example:
mkdocs serve --dev-addr=0.0.0.0:80 # Run on port 80, accessible over the local network.
@@ -217,30 +222,62 @@ As with all settings, you can set this from the command line, which can be usful
### markdown_extensions
-MkDocs uses the [Python Markdown][pymkd] library to translate Markdown files into HTML. Python Markdown supports a variety of [extensions][pymdk-extensions] that customize how pages are formatted. This setting lets you enable a list of extensions beyond the ones that MkDocs uses by default (`meta`, `toc`, `tables`, and `fenced_code`).
+MkDocs uses the [Python Markdown][pymkd] library to translate Markdown files
+into HTML. Python Markdown supports a variety of [extensions][pymdk-extensions]
+that customize how pages are formatted. This setting lets you enable a list of
+extensions beyond the ones that MkDocs uses by default (`meta`, `toc`, `tables`,
+and `fenced_code`).
For example, to enable the [SmartyPants typography extension][smarty], use:
- markdown_extensions: [smartypants]
+ markdown_extensions:
+ - smarty
-Some extensions provide configuration options of their own. If you would like to set any configuration options, then you can define `markdown_extensions` as a key/value mapping rather than a list. The key must be the name of the extension and the value must be a key/value pair (option name/option value) for the configuration option.
+Some extensions provide configuration options of their own. If you would like to
+set any configuration options, then you can nest a key/value mapping
+(`option_name: option value`) of any options that a given extension supports.
+See the documentation for the extension you are using to determine what options
+they support.
For example, to enable permalinks in the (included) `toc` extension, use:
markdown_extensions:
- toc:
+ - toc:
+ permalink: True
+
+Note that a colon (`:`) must follow the extension name (`toc`) and then on a new line
+the option name and value must be indented and seperated by a colon. If you would like
+to define multipe options for a single extension, each option must be defined on
+a seperate line:
+
+ markdown_extensions:
+ - toc:
permalink: True
+ separator: "_"
-Add additonal items for each extension. If you have no configuration options to set for a specific extension, then you may leave that extensions options blank:
+Add an additional item to the list for each extension. If you have no
+configuration options to set for a specific extension, then simply omit options
+for that extension:
markdown_extensions:
- smartypants:
- toc:
+ - smarty
+ - toc:
permalink: True
+ - sane_lists
+!!! note "See Also:"
+ The Python-Markdown documentation provides a [list of extensions][exts]
+ which are available out-of-the-box. For a list of configuration options
+ available for a given extension, see the documentation for that extension.
+
+ You may also install and use various [third party extensions][3rd]. Consult the
+ documentation provided by those extensions for installation instructions and
+ available configuration options.
**default**: `[]`
[pymdk-extensions]: http://pythonhosted.org/Markdown/extensions/index.html
[pymkd]: http://pythonhosted.org/Markdown/
-[smarty]: https://pypi.python.org/pypi/mdx_smartypants
+[smarty]: https://pythonhosted.org/Markdown/extensions/smarty.html
+[exts]:https://pythonhosted.org/Markdown/extensions/index.html
+[3rd]: https://github.com/waylan/Python-Markdown/wiki/Third-Party-Extensions
\ No newline at end of file
diff --git a/mkdocs.yml b/mkdocs.yml
index 930ccd95..e092f9ec 100644
--- a/mkdocs.yml
+++ b/mkdocs.yml
@@ -5,9 +5,9 @@ site_description: Project documentation with Markdown.
repo_url: https://github.com/mkdocs/mkdocs/
markdown_extensions:
- toc:
+ - toc:
permalink: ""
- admonition:
+ - admonition:
copyright: Copyright © 2014, <a href="https://twitter.com/_tomchristie">Tom Christie</a>.
google_analytics: ['UA-27795084-5', 'mkdocs.org']
diff --git a/mkdocs/build.py b/mkdocs/build.py
index 73d9a309..70f60e7a 100644
--- a/mkdocs/build.py
+++ b/mkdocs/build.py
@@ -17,30 +17,17 @@ import mkdocs
log = logging.getLogger(__name__)
-def convert_markdown(markdown_source, site_navigation=None, extensions=(), strict=False):
+def convert_markdown(markdown_source, config, site_navigation=None):
"""
- Convert the Markdown source file to HTML content, and additionally
- return the parsed table of contents, and a dictionary of any metadata
- that was specified in the Markdown file.
-
- `extensions` is an optional sequence of Python Markdown extensions to add
- to the default set.
+ Convert the Markdown source file to HTML as per the config and site_navigation.
+ Return a tuple of the HTML as a string, the parsed table of contents,
+ and a dictionary of any metadata that was specified in the Markdown file.
"""
-
- # Generate the HTML from the markdown source
- if isinstance(extensions, dict):
- user_extensions = list(extensions.keys())
- extension_configs = dict([(k, v) for k, v in extensions.items() if isinstance(v, dict)])
- else:
- user_extensions = list(extensions)
- extension_configs = {}
- builtin_extensions = ['meta', 'toc', 'tables', 'fenced_code']
- mkdocs_extensions = [RelativePathExtension(site_navigation, strict), ]
- extensions = utils.reduce_list(builtin_extensions + mkdocs_extensions + user_extensions)
-
- html_content, table_of_contents, meta = utils.convert_markdown(markdown_source, extensions, extension_configs)
-
- return (html_content, table_of_contents, meta)
+ return utils.convert_markdown(
+ markdown_source=markdown_source,
+ extensions=[RelativePathExtension(site_navigation, config['strict'])] + config['markdown_extensions'],
+ extension_configs=config['mdx_configs']
+ )
def get_global_context(nav, config):
@@ -182,8 +169,9 @@ def _build_page(page, config, site_navigation, env, dump_json):
# Process the markdown text
html_content, table_of_contents, meta = convert_markdown(
- input_content, site_navigation,
- extensions=config['markdown_extensions'], strict=config['strict']
+ markdown_source=input_content,
+ config=config,
+ site_navigation=site_navigation
)
context = get_global_context(site_navigation, config)
diff --git a/mkdocs/config/base.py b/mkdocs/config/base.py
index 870d00b7..53ffbad1 100644
--- a/mkdocs/config/base.py
+++ b/mkdocs/config/base.py
@@ -1,9 +1,9 @@
import six
import logging
import os
+import yaml
from mkdocs import exceptions
-from mkdocs import utils
from mkdocs.config import config_options, defaults
log = logging.getLogger('mkdocs.config')
@@ -82,7 +82,7 @@ class Config(six.moves.UserDict):
self.data.update(patch)
def load_file(self, config_file):
- return self.load_dict(utils.yaml_load(config_file))
+ return self.load_dict(yaml.load(config_file))
def _open_config_file(config_file):
diff --git a/mkdocs/config/config_options.py b/mkdocs/config/config_options.py
index c6ac2910..6c47197b 100644
--- a/mkdocs/config/config_options.py
+++ b/mkdocs/config/config_options.py
@@ -343,3 +343,56 @@ class NumPages(BaseConfigOption):
config[key_name] = len(config['pages']) > self.at_lest
except TypeError:
config[key_name] = False
+
+
+class Private(BaseConfigOption):
+ """
+ Private Config Option
+
+ A config option only for internal use. Raises an error if set by the user.
+ """
+
+ def run_validation(self, value):
+ raise ValidationError('For internal use only.')
+
+
+class MarkdownExtensions(BaseConfigOption):
+ """
+ Markdown Extensions Config Option
+
+ A list of extensions. If a list item contains extension configs,
+ those are set on the private setting passed to `configkey`. The
+ `builtins` keyword accepts a list of extensions which cannot be
+ overriden by the user. However, builtins can be duplicated to define
+ config options for them if desired.
+ """
+ def __init__(self, builtins=None, configkey='mdx_configs', **kwargs):
+ super(MarkdownExtensions, self).__init__(**kwargs)
+ self.builtins = builtins or []
+ self.configkey = configkey
+ self.configdata = {}
+
+ def run_validation(self, value):
+ if not isinstance(value, (list, tuple)):
+ raise ValidationError('Invalid Markdown Extensions configuration')
+ extensions = []
+ for item in value:
+ if isinstance(item, dict):
+ if len(item) > 1:
+ raise ValidationError('Invalid Markdown Extensions configuration')
+ ext, cfg = item.popitem()
+ extensions.append(ext)
+ if cfg is None:
+ continue
+ if not isinstance(cfg, dict):
+ raise ValidationError('Invalid config options for Markdown '
+ "Extension '{0}'.".format(ext))
+ self.configdata[ext] = cfg
+ elif isinstance(item, six.string_types):
+ extensions.append(item)
+ else:
+ raise ValidationError('Invalid Markdown Extensions configuration')
+ return utils.reduce_list(self.builtins + extensions)
+
+ def post_validation(self, config, key_name):
+ config[self.configkey] = self.configdata
diff --git a/mkdocs/config/defaults.py b/mkdocs/config/defaults.py
index 9d7bcd6d..2c2d929f 100644
--- a/mkdocs/config/defaults.py
+++ b/mkdocs/config/defaults.py
@@ -90,8 +90,12 @@ DEFAULT_SCHEMA = (
('include_next_prev', config_options.NumPages()),
# PyMarkdown extension names.
- ('markdown_extensions', config_options.Type(
- (list, dict, tuple), default=())),
+ ('markdown_extensions', config_options.MarkdownExtensions(
+ builtins=['meta', 'toc', 'tables', 'fenced_code'],
+ configkey='mdx_configs', default=[])),
+
+ # PyMarkdown Extension Configs. For internal use only.
+ ('mdx_configs', config_options.Private()),
# enabling strict mode causes MkDocs to stop the build when a problem is
# encountered rather than display an error.
diff --git a/mkdocs/utils.py b/mkdocs/utils.py
index de7c67a5..7ff7f07e 100644
--- a/mkdocs/utils.py
+++ b/mkdocs/utils.py
@@ -12,30 +12,8 @@ import shutil
import markdown
import six
-import yaml
from mkdocs import toc
-from mkdocs.legacy import OrderedDict
-
-
-def yaml_load(stream, Loader=yaml.Loader, object_pairs_hook=OrderedDict):
- """
- Make all YAML dictionaries load as ordered Dicts.
- http://stackoverflow.com/a/21912744/3609487
- """
- class OrderedLoader(Loader):
- pass
-
- def construct_mapping(loader, node):
- loader.flatten_mapping(node)
- return object_pairs_hook(loader.construct_pairs(node))
-
- OrderedLoader.add_constructor(
- yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG,
- construct_mapping
- )
-
- return yaml.load(stream, OrderedLoader)
def reduce_list(data_set):
@@ -279,12 +257,9 @@ def convert_markdown(markdown_source, extensions=None, extension_configs=None):
`extensions` is an optional sequence of Python Markdown extensions to add
to the default set.
"""
- extensions = extensions or []
- extension_configs = extension_configs or {}
-
md = markdown.Markdown(
- extensions=extensions,
- extension_configs=extension_configs
+ extensions=extensions or [],
+ extension_configs=extension_configs or {}
)
html_content = md.convert(markdown_source)
| smartypants extension error
I'm new to mkdocs and have recently installed it. I'm running on Windows and am using Python 3.4.
I was walking though some of the mkdocs documentation and wanted to try to use smartypants. Initially I found out I had to install the extension itself which wasn't mentioned in the mkdocs documentation (might be helpful to add that). After installing the extension with pip I tried to use it using all 3 of the below configuration formats..
```
markdown_extensions: [smartypants]
```
```
markdown_extensions:
- smartypants
```
```
markdown_extensions:
smartypants:
```
Either way, when I try to run mkdocs serve I get the below error
```
ERROR - Error building page index.md
[E 150512 11:21:27 build:221] Error building page index.md
Traceback (most recent call last):
File "C:\tools\python\Scripts\mkdocs-script.py", line 9, in <module>
load_entry_point('mkdocs==0.12.2', 'console_scripts', 'mkdocs')()
File "C:\tools\python\lib\site-packages\mkdocs\main.py", line 77, in run_main
main(cmd, args=sys.argv[2:], options=dict(opts))
File "C:\tools\python\lib\site-packages\mkdocs\main.py", line 49, in main
serve(config, options=options)
File "C:\tools\python\lib\site-packages\mkdocs\serve.py", line 22, in serve
builder()
File "C:\tools\python\lib\site-packages\mkdocs\serve.py", line 19, in builder
build(config, live_server=True)
File "C:\tools\python\lib\site-packages\mkdocs\build.py", line 252, in build
build_pages(config)
File "C:\tools\python\lib\site-packages\mkdocs\build.py", line 219, in build_pages
_build_page(page, config, site_navigation, env, dump_json)
File "C:\tools\python\lib\site-packages\mkdocs\build.py", line 173, in _build_page
extensions=config['markdown_extensions'], strict=config['strict']
File "C:\tools\python\lib\site-packages\mkdocs\build.py", line 36, in convert_markdown
extensions=extensions
File "C:\tools\python\lib\site-packages\markdown\__init__.py", line 159, in __init__
configs=kwargs.get('extension_configs', {}))
File "C:\tools\python\lib\site-packages\markdown\__init__.py", line 185, in registerExtensions
ext = self.build_extension(ext, configs.get(ext, {}))
File "C:\tools\python\lib\site-packages\markdown\__init__.py", line 291, in build_extension
return module.makeExtension(**configs)
File "C:\tools\python\lib\site-packages\mdx_smartypants\core.py", line 52, in makeExtension
return SmartypantsExt(configs=configs)
File "C:\tools\python\lib\site-packages\mdx_smartypants\core.py", line 41, in __init__
self.configs = dict(configs)
TypeError: 'NoneType' object is not iterable
``` | mkdocs/mkdocs | diff --git a/mkdocs/tests/build_tests.py b/mkdocs/tests/build_tests.py
index 470dac46..d474925b 100644
--- a/mkdocs/tests/build_tests.py
+++ b/mkdocs/tests/build_tests.py
@@ -9,16 +9,26 @@ import unittest
from six.moves import zip
import mock
-from mkdocs import build, nav
-from mkdocs.config import base as config_base, defaults as config_defaults
+from mkdocs import build, nav, config
from mkdocs.exceptions import MarkdownNotFound
from mkdocs.tests.base import dedent
+def load_config(cfg=None):
+ """ Helper to build a simple config for testing. """
+ cfg = cfg or {}
+ if 'site_name' not in cfg:
+ cfg['site_name'] = 'Example'
+ conf = config.base.Config(schema=config.defaults.DEFAULT_SCHEMA)
+ conf.load_dict(cfg)
+ assert(conf.validate() == ([], []))
+ return conf
+
+
class BuildTests(unittest.TestCase):
def test_empty_document(self):
- html, toc, meta = build.convert_markdown("")
+ html, toc, meta = build.convert_markdown("", load_config())
self.assertEqual(html, '')
self.assertEqual(len(list(toc)), 0)
@@ -28,7 +38,6 @@ class BuildTests(unittest.TestCase):
"""
Ensure that basic Markdown -> HTML and TOC works.
"""
-
html, toc, meta = build.convert_markdown(dedent("""
page_title: custom title
@@ -39,7 +48,7 @@ class BuildTests(unittest.TestCase):
# Heading 2
And some more text.
- """))
+ """), load_config())
expected_html = dedent("""
<h1 id="heading-1">Heading 1</h1>
@@ -62,25 +71,25 @@ class BuildTests(unittest.TestCase):
def test_convert_internal_link(self):
md_text = 'An [internal link](internal.md) to another document.'
expected = '<p>An <a href="internal/">internal link</a> to another document.</p>'
- html, toc, meta = build.convert_markdown(md_text)
+ html, toc, meta = build.convert_markdown(md_text, load_config())
self.assertEqual(html.strip(), expected.strip())
def test_convert_multiple_internal_links(self):
md_text = '[First link](first.md) [second link](second.md).'
expected = '<p><a href="first/">First link</a> <a href="second/">second link</a>.</p>'
- html, toc, meta = build.convert_markdown(md_text)
+ html, toc, meta = build.convert_markdown(md_text, load_config())
self.assertEqual(html.strip(), expected.strip())
def test_convert_internal_link_differing_directory(self):
md_text = 'An [internal link](../internal.md) to another document.'
expected = '<p>An <a href="../internal/">internal link</a> to another document.</p>'
- html, toc, meta = build.convert_markdown(md_text)
+ html, toc, meta = build.convert_markdown(md_text, load_config())
self.assertEqual(html.strip(), expected.strip())
def test_convert_internal_link_with_anchor(self):
md_text = 'An [internal link](internal.md#section1.1) to another document.'
expected = '<p>An <a href="internal/#section1.1">internal link</a> to another document.</p>'
- html, toc, meta = build.convert_markdown(md_text)
+ html, toc, meta = build.convert_markdown(md_text, load_config())
self.assertEqual(html.strip(), expected.strip())
def test_convert_internal_media(self):
@@ -103,7 +112,7 @@ class BuildTests(unittest.TestCase):
for (page, expected) in zip(site_navigation.walk_pages(), expected_results):
md_text = ''
- html, _, _ = build.convert_markdown(md_text, site_navigation=site_navigation)
+ html, _, _ = build.convert_markdown(md_text, load_config(), site_navigation=site_navigation)
self.assertEqual(html, template % expected)
def test_convert_internal_asbolute_media(self):
@@ -126,7 +135,7 @@ class BuildTests(unittest.TestCase):
for (page, expected) in zip(site_navigation.walk_pages(), expected_results):
md_text = ''
- html, _, _ = build.convert_markdown(md_text, site_navigation=site_navigation)
+ html, _, _ = build.convert_markdown(md_text, load_config(), site_navigation=site_navigation)
self.assertEqual(html, template % expected)
def test_dont_convert_code_block_urls(self):
@@ -146,11 +155,10 @@ class BuildTests(unittest.TestCase):
for page in site_navigation.walk_pages():
markdown = 'An HTML Anchor::\n\n <a href="index.md">My example link</a>\n'
- html, _, _ = build.convert_markdown(markdown, site_navigation=site_navigation)
+ html, _, _ = build.convert_markdown(markdown, load_config(), site_navigation=site_navigation)
self.assertEqual(dedent(html), expected)
def test_anchor_only_link(self):
-
pages = [
'index.md',
'internal.md',
@@ -161,13 +169,13 @@ class BuildTests(unittest.TestCase):
for page in site_navigation.walk_pages():
markdown = '[test](#test)'
- html, _, _ = build.convert_markdown(markdown, site_navigation=site_navigation)
+ html, _, _ = build.convert_markdown(markdown, load_config(), site_navigation=site_navigation)
self.assertEqual(html, '<p><a href="#test">test</a></p>')
def test_ignore_external_link(self):
md_text = 'An [external link](http://example.com/external.md).'
expected = '<p>An <a href="http://example.com/external.md">external link</a>.</p>'
- html, toc, meta = build.convert_markdown(md_text)
+ html, toc, meta = build.convert_markdown(md_text, load_config())
self.assertEqual(html.strip(), expected.strip())
def test_not_use_directory_urls(self):
@@ -177,20 +185,19 @@ class BuildTests(unittest.TestCase):
'internal.md',
]
site_navigation = nav.SiteNavigation(pages, use_directory_urls=False)
- html, toc, meta = build.convert_markdown(md_text, site_navigation=site_navigation)
+ html, toc, meta = build.convert_markdown(md_text, load_config(), site_navigation=site_navigation)
self.assertEqual(html.strip(), expected.strip())
def test_markdown_table_extension(self):
"""
Ensure that the table extension is supported.
"""
-
html, toc, meta = build.convert_markdown(dedent("""
First Header | Second Header
-------------- | --------------
Content Cell 1 | Content Cell 2
Content Cell 3 | Content Cell 4
- """))
+ """), load_config())
expected_html = dedent("""
<table>
@@ -219,12 +226,11 @@ class BuildTests(unittest.TestCase):
"""
Ensure that the fenced code extension is supported.
"""
-
html, toc, meta = build.convert_markdown(dedent("""
```
print 'foo'
```
- """))
+ """), load_config())
expected_html = dedent("""
<pre><code>print 'foo'\n</code></pre>
@@ -241,24 +247,29 @@ class BuildTests(unittest.TestCase):
# Check that the plugin is not active when not requested.
expected_without_smartstrong = "<p>foo<strong>bar</strong>baz</p>"
- html_base, _, _ = build.convert_markdown(md_input)
+ html_base, _, _ = build.convert_markdown(md_input, load_config())
self.assertEqual(html_base.strip(), expected_without_smartstrong)
# Check that the plugin is active when requested.
+ cfg = load_config({
+ 'markdown_extensions': ['smart_strong']
+ })
expected_with_smartstrong = "<p>foo__bar__baz</p>"
- html_ext, _, _ = build.convert_markdown(md_input, extensions=['smart_strong'])
+ html_ext, _, _ = build.convert_markdown(md_input, cfg)
self.assertEqual(html_ext.strip(), expected_with_smartstrong)
def test_markdown_duplicate_custom_extension(self):
"""
Duplicated extension names should not cause problems.
"""
+ cfg = load_config({
+ 'markdown_extensions': ['toc']
+ })
md_input = "foo"
- html_ext, _, _ = build.convert_markdown(md_input, ['toc'])
+ html_ext, _, _ = build.convert_markdown(md_input, cfg)
self.assertEqual(html_ext.strip(), '<p>foo</p>')
def test_copying_media(self):
-
docs_dir = tempfile.mkdtemp()
site_dir = tempfile.mkdtemp()
try:
@@ -281,14 +292,11 @@ class BuildTests(unittest.TestCase):
os.mkdir(os.path.join(docs_dir, '.git'))
open(os.path.join(docs_dir, '.git/hidden'), 'w').close()
- conf = config_base.Config(schema=config_defaults.DEFAULT_SCHEMA)
- conf.load_dict({
- 'site_name': 'Example',
+ cfg = load_config({
'docs_dir': docs_dir,
'site_dir': site_dir
})
- conf.validate()
- build.build(conf)
+ build.build(cfg)
# Verify only the markdown (coverted to html) and the image are copied.
self.assertTrue(os.path.isfile(os.path.join(site_dir, 'index.html')))
@@ -308,8 +316,8 @@ class BuildTests(unittest.TestCase):
site_nav = nav.SiteNavigation(pages)
valid = "[test](internal.md)"
- build.convert_markdown(valid, site_nav, strict=False)
- build.convert_markdown(valid, site_nav, strict=True)
+ build.convert_markdown(valid, load_config({'strict': False}), site_nav)
+ build.convert_markdown(valid, load_config({'strict': True}), site_nav)
def test_strict_mode_invalid(self):
pages = [
@@ -320,24 +328,24 @@ class BuildTests(unittest.TestCase):
site_nav = nav.SiteNavigation(pages)
invalid = "[test](bad_link.md)"
- build.convert_markdown(invalid, site_nav, strict=False)
+ build.convert_markdown(invalid, load_config({'strict': False}), site_nav)
self.assertRaises(
MarkdownNotFound,
- build.convert_markdown, invalid, site_nav, strict=True)
+ build.convert_markdown, invalid, load_config({'strict': True}), site_nav)
def test_extension_config(self):
"""
Test that a dictionary of 'markdown_extensions' is recognized as
both a list of extensions and a dictionary of extnesion configs.
"""
- markdown_extensions = {
- 'toc': {'permalink': True},
- 'meta': None # This gets ignored as it is an invalid config
- }
+ cfg = load_config({
+ 'markdown_extensions': [{'toc': {'permalink': True}}]
+ })
+
html, toc, meta = build.convert_markdown(dedent("""
# A Header
- """), extensions=markdown_extensions)
+ """), cfg)
expected_html = dedent("""
<h1 id="a-header">A Header<a class="headerlink" href="#a-header" title="Permanent link">¶</a></h1>
@@ -348,17 +356,14 @@ class BuildTests(unittest.TestCase):
def test_extra_context(self):
# Same as the default schema, but don't verify the docs_dir exists.
- config = config_base.Config(schema=config_defaults.DEFAULT_SCHEMA)
- config.load_dict({
+ cfg = load_config({
'site_name': "Site",
'extra': {
'a': 1
}
})
- self.assertEqual(config.validate(), ([], []))
-
- context = build.get_global_context(mock.Mock(), config)
+ context = build.get_global_context(mock.Mock(), cfg)
self.assertEqual(context['config']['extra'], {
'a': 1
diff --git a/mkdocs/tests/config/config_options_tests.py b/mkdocs/tests/config/config_options_tests.py
index a499ece5..c4a42f94 100644
--- a/mkdocs/tests/config/config_options_tests.py
+++ b/mkdocs/tests/config/config_options_tests.py
@@ -325,3 +325,170 @@ class NumPagesTest(unittest.TestCase):
'key': True,
'pages': None
}, config)
+
+
+class PrivateTest(unittest.TestCase):
+
+ def test_defined(self):
+
+ option = config_options.Private()
+ self.assertRaises(config_options.ValidationError,
+ option.validate, 'somevalue')
+
+
+class MarkdownExtensionsTest(unittest.TestCase):
+
+ def test_simple_list(self):
+ option = config_options.MarkdownExtensions()
+ config = {
+ 'markdown_extensions': ['foo', 'bar']
+ }
+ config['markdown_extensions'] = option.validate(config['markdown_extensions'])
+ option.post_validation(config, 'markdown_extensions')
+ self.assertEqual({
+ 'markdown_extensions': ['foo', 'bar'],
+ 'mdx_configs': {}
+ }, config)
+
+ def test_list_dicts(self):
+ option = config_options.MarkdownExtensions()
+ config = {
+ 'markdown_extensions': [
+ {'foo': {'foo_option': 'foo value'}},
+ {'bar': {'bar_option': 'bar value'}},
+ {'baz': None}
+ ]
+ }
+ config['markdown_extensions'] = option.validate(config['markdown_extensions'])
+ option.post_validation(config, 'markdown_extensions')
+ self.assertEqual({
+ 'markdown_extensions': ['foo', 'bar', 'baz'],
+ 'mdx_configs': {
+ 'foo': {'foo_option': 'foo value'},
+ 'bar': {'bar_option': 'bar value'}
+ }
+ }, config)
+
+ def test_mixed_list(self):
+ option = config_options.MarkdownExtensions()
+ config = {
+ 'markdown_extensions': [
+ 'foo',
+ {'bar': {'bar_option': 'bar value'}}
+ ]
+ }
+ config['markdown_extensions'] = option.validate(config['markdown_extensions'])
+ option.post_validation(config, 'markdown_extensions')
+ self.assertEqual({
+ 'markdown_extensions': ['foo', 'bar'],
+ 'mdx_configs': {
+ 'bar': {'bar_option': 'bar value'}
+ }
+ }, config)
+
+ def test_builtins(self):
+ option = config_options.MarkdownExtensions(builtins=['meta', 'toc'])
+ config = {
+ 'markdown_extensions': ['foo', 'bar']
+ }
+ config['markdown_extensions'] = option.validate(config['markdown_extensions'])
+ option.post_validation(config, 'markdown_extensions')
+ self.assertEqual({
+ 'markdown_extensions': ['meta', 'toc', 'foo', 'bar'],
+ 'mdx_configs': {}
+ }, config)
+
+ def test_duplicates(self):
+ option = config_options.MarkdownExtensions(builtins=['meta', 'toc'])
+ config = {
+ 'markdown_extensions': ['meta', 'toc']
+ }
+ config['markdown_extensions'] = option.validate(config['markdown_extensions'])
+ option.post_validation(config, 'markdown_extensions')
+ self.assertEqual({
+ 'markdown_extensions': ['meta', 'toc'],
+ 'mdx_configs': {}
+ }, config)
+
+ def test_builtins_config(self):
+ option = config_options.MarkdownExtensions(builtins=['meta', 'toc'])
+ config = {
+ 'markdown_extensions': [
+ {'toc': {'permalink': True}}
+ ]
+ }
+ config['markdown_extensions'] = option.validate(config['markdown_extensions'])
+ option.post_validation(config, 'markdown_extensions')
+ self.assertEqual({
+ 'markdown_extensions': ['meta', 'toc'],
+ 'mdx_configs': {'toc': {'permalink': True}}
+ }, config)
+
+ def test_configkey(self):
+ option = config_options.MarkdownExtensions(configkey='bar')
+ config = {
+ 'markdown_extensions': [
+ {'foo': {'foo_option': 'foo value'}}
+ ]
+ }
+ config['markdown_extensions'] = option.validate(config['markdown_extensions'])
+ option.post_validation(config, 'markdown_extensions')
+ self.assertEqual({
+ 'markdown_extensions': ['foo'],
+ 'bar': {
+ 'foo': {'foo_option': 'foo value'}
+ }
+ }, config)
+
+ def test_none(self):
+ option = config_options.MarkdownExtensions(default=[])
+ config = {
+ 'markdown_extensions': None
+ }
+ config['markdown_extensions'] = option.validate(config['markdown_extensions'])
+ option.post_validation(config, 'markdown_extensions')
+ self.assertEqual({
+ 'markdown_extensions': [],
+ 'mdx_configs': {}
+ }, config)
+
+ def test_not_list(self):
+ option = config_options.MarkdownExtensions()
+ self.assertRaises(config_options.ValidationError,
+ option.validate, 'not a list')
+
+ def test_invalid_config_option(self):
+ option = config_options.MarkdownExtensions()
+ config = {
+ 'markdown_extensions': [
+ {'foo': 'not a dict'}
+ ]
+ }
+ self.assertRaises(
+ config_options.ValidationError,
+ option.validate, config['markdown_extensions']
+ )
+
+ def test_invalid_config_item(self):
+ option = config_options.MarkdownExtensions()
+ config = {
+ 'markdown_extensions': [
+ ['not a dict']
+ ]
+ }
+ self.assertRaises(
+ config_options.ValidationError,
+ option.validate, config['markdown_extensions']
+ )
+
+ def test_invalid_dict_item(self):
+ option = config_options.MarkdownExtensions()
+ config = {
+ 'markdown_extensions': [
+ {'key1': 'value', 'key2': 'too many keys'}
+ ]
+ }
+ self.assertRaises(
+ config_options.ValidationError,
+ option.validate, config['markdown_extensions']
+ )
diff --git a/mkdocs/tests/utils_tests.py b/mkdocs/tests/utils_tests.py
index 41d066e6..44af6799 100644
--- a/mkdocs/tests/utils_tests.py
+++ b/mkdocs/tests/utils_tests.py
@@ -5,7 +5,6 @@ import os
import unittest
from mkdocs import nav, utils
-from mkdocs.tests.base import dedent
class UtilsTests(unittest.TestCase):
@@ -70,32 +69,6 @@ class UtilsTests(unittest.TestCase):
urls = utils.create_media_urls(site_navigation, [path])
self.assertEqual(urls[0], expected_result)
- def test_yaml_load(self):
- try:
- from collections import OrderedDict
- except ImportError:
- # Don't test if can't import OrderdDict
- # Exception can be removed when Py26 support is removed
- return
-
- yaml_text = dedent('''
- test:
- key1: 1
- key2: 2
- key3: 3
- key4: 4
- key5: 5
- key5: 6
- key3: 7
- ''')
-
- self.assertEqual(
- utils.yaml_load(yaml_text),
- OrderedDict([('test', OrderedDict([('key1', 1), ('key2', 2),
- ('key3', 7), ('key4', 4),
- ('key5', 6)]))])
- )
-
def test_reduce_list(self):
self.assertEqual(
utils.reduce_list([1, 2, 3, 4, 5, 5, 2, 4, 6, 7, 8]),
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 0,
"issue_text_score": 1,
"test_score": 3
},
"num_modified_files": 7
} | 0.12 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[dev]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest",
"pytest-cov",
"pytest-xdist",
"pytest-mock",
"pytest-asyncio",
"mock"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.9",
"reqs_path": [
"requirements/project.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | click==8.1.8
coverage==7.8.0
exceptiongroup==1.2.2
execnet==2.1.1
ghp-import==2.1.0
importlib_metadata==8.6.1
iniconfig==2.1.0
Jinja2==3.1.6
livereload==2.7.1
Markdown==3.7
MarkupSafe==3.0.2
-e git+https://github.com/mkdocs/mkdocs.git@93a181a208af0440f44e7f51081b9df9d9f30568#egg=mkdocs
mock==5.2.0
packaging==24.2
pluggy==1.5.0
pytest==8.3.5
pytest-asyncio==0.26.0
pytest-cov==6.0.0
pytest-mock==3.14.0
pytest-xdist==3.6.1
python-dateutil==2.9.0.post0
PyYAML==6.0.2
six==1.17.0
tomli==2.2.1
tornado==6.4.2
typing_extensions==4.13.0
zipp==3.21.0
| name: mkdocs
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=3.0.16=h5eee18b_0
- pip=25.0=py39h06a4308_0
- python=3.9.21=he870216_1
- readline=8.2=h5eee18b_0
- setuptools=75.8.0=py39h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- tzdata=2025a=h04d1e81_0
- wheel=0.45.1=py39h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- click==8.1.8
- coverage==7.8.0
- exceptiongroup==1.2.2
- execnet==2.1.1
- ghp-import==2.1.0
- importlib-metadata==8.6.1
- iniconfig==2.1.0
- jinja2==3.1.6
- livereload==2.7.1
- markdown==3.7
- markupsafe==3.0.2
- mock==5.2.0
- packaging==24.2
- pluggy==1.5.0
- pytest==8.3.5
- pytest-asyncio==0.26.0
- pytest-cov==6.0.0
- pytest-mock==3.14.0
- pytest-xdist==3.6.1
- python-dateutil==2.9.0.post0
- pyyaml==6.0.2
- six==1.17.0
- tomli==2.2.1
- tornado==6.4.2
- typing-extensions==4.13.0
- zipp==3.21.0
prefix: /opt/conda/envs/mkdocs
| [
"mkdocs/tests/config/config_options_tests.py::PrivateTest::test_defined",
"mkdocs/tests/config/config_options_tests.py::MarkdownExtensionsTest::test_builtins",
"mkdocs/tests/config/config_options_tests.py::MarkdownExtensionsTest::test_builtins_config",
"mkdocs/tests/config/config_options_tests.py::MarkdownExtensionsTest::test_configkey",
"mkdocs/tests/config/config_options_tests.py::MarkdownExtensionsTest::test_duplicates",
"mkdocs/tests/config/config_options_tests.py::MarkdownExtensionsTest::test_invalid_config_item",
"mkdocs/tests/config/config_options_tests.py::MarkdownExtensionsTest::test_invalid_config_option",
"mkdocs/tests/config/config_options_tests.py::MarkdownExtensionsTest::test_invalid_dict_item",
"mkdocs/tests/config/config_options_tests.py::MarkdownExtensionsTest::test_list_dicts",
"mkdocs/tests/config/config_options_tests.py::MarkdownExtensionsTest::test_mixed_list",
"mkdocs/tests/config/config_options_tests.py::MarkdownExtensionsTest::test_none",
"mkdocs/tests/config/config_options_tests.py::MarkdownExtensionsTest::test_not_list",
"mkdocs/tests/config/config_options_tests.py::MarkdownExtensionsTest::test_simple_list"
] | [
"mkdocs/tests/build_tests.py::BuildTests::test_anchor_only_link",
"mkdocs/tests/build_tests.py::BuildTests::test_convert_internal_asbolute_media",
"mkdocs/tests/build_tests.py::BuildTests::test_convert_internal_link",
"mkdocs/tests/build_tests.py::BuildTests::test_convert_internal_link_differing_directory",
"mkdocs/tests/build_tests.py::BuildTests::test_convert_internal_link_with_anchor",
"mkdocs/tests/build_tests.py::BuildTests::test_convert_internal_media",
"mkdocs/tests/build_tests.py::BuildTests::test_convert_markdown",
"mkdocs/tests/build_tests.py::BuildTests::test_convert_multiple_internal_links",
"mkdocs/tests/build_tests.py::BuildTests::test_copying_media",
"mkdocs/tests/build_tests.py::BuildTests::test_dont_convert_code_block_urls",
"mkdocs/tests/build_tests.py::BuildTests::test_empty_document",
"mkdocs/tests/build_tests.py::BuildTests::test_extension_config",
"mkdocs/tests/build_tests.py::BuildTests::test_ignore_external_link",
"mkdocs/tests/build_tests.py::BuildTests::test_markdown_custom_extension",
"mkdocs/tests/build_tests.py::BuildTests::test_markdown_duplicate_custom_extension",
"mkdocs/tests/build_tests.py::BuildTests::test_markdown_fenced_code_extension",
"mkdocs/tests/build_tests.py::BuildTests::test_markdown_table_extension",
"mkdocs/tests/build_tests.py::BuildTests::test_not_use_directory_urls",
"mkdocs/tests/build_tests.py::BuildTests::test_strict_mode_invalid",
"mkdocs/tests/build_tests.py::BuildTests::test_strict_mode_valid",
"mkdocs/tests/utils_tests.py::UtilsTests::test_create_media_urls"
] | [
"mkdocs/tests/build_tests.py::BuildTests::test_extra_context",
"mkdocs/tests/config/config_options_tests.py::BaseConfigOptionTest::test_default",
"mkdocs/tests/config/config_options_tests.py::BaseConfigOptionTest::test_empty",
"mkdocs/tests/config/config_options_tests.py::BaseConfigOptionTest::test_replace_default",
"mkdocs/tests/config/config_options_tests.py::BaseConfigOptionTest::test_required",
"mkdocs/tests/config/config_options_tests.py::BaseConfigOptionTest::test_required_no_default",
"mkdocs/tests/config/config_options_tests.py::TypeTest::test_length",
"mkdocs/tests/config/config_options_tests.py::TypeTest::test_multiple_types",
"mkdocs/tests/config/config_options_tests.py::TypeTest::test_single_type",
"mkdocs/tests/config/config_options_tests.py::URLTest::test_invalid",
"mkdocs/tests/config/config_options_tests.py::URLTest::test_invalid_url",
"mkdocs/tests/config/config_options_tests.py::URLTest::test_valid_url",
"mkdocs/tests/config/config_options_tests.py::RepoURLTest::test_repo_name_bitbucket",
"mkdocs/tests/config/config_options_tests.py::RepoURLTest::test_repo_name_custom",
"mkdocs/tests/config/config_options_tests.py::RepoURLTest::test_repo_name_github",
"mkdocs/tests/config/config_options_tests.py::DirTest::test_file",
"mkdocs/tests/config/config_options_tests.py::DirTest::test_incorrect_type_attribute_error",
"mkdocs/tests/config/config_options_tests.py::DirTest::test_incorrect_type_type_error",
"mkdocs/tests/config/config_options_tests.py::DirTest::test_missing_dir",
"mkdocs/tests/config/config_options_tests.py::DirTest::test_missing_dir_but_required",
"mkdocs/tests/config/config_options_tests.py::DirTest::test_valid_dir",
"mkdocs/tests/config/config_options_tests.py::SiteDirTest::test_doc_dir_in_site_dir",
"mkdocs/tests/config/config_options_tests.py::ThemeTest::test_theme",
"mkdocs/tests/config/config_options_tests.py::ThemeTest::test_theme_invalid",
"mkdocs/tests/config/config_options_tests.py::ExtrasTest::test_empty",
"mkdocs/tests/config/config_options_tests.py::ExtrasTest::test_invalid",
"mkdocs/tests/config/config_options_tests.py::ExtrasTest::test_provided",
"mkdocs/tests/config/config_options_tests.py::PagesTest::test_invalid_config",
"mkdocs/tests/config/config_options_tests.py::PagesTest::test_invalid_type",
"mkdocs/tests/config/config_options_tests.py::PagesTest::test_provided",
"mkdocs/tests/config/config_options_tests.py::PagesTest::test_provided_dict",
"mkdocs/tests/config/config_options_tests.py::PagesTest::test_provided_empty",
"mkdocs/tests/config/config_options_tests.py::NumPagesTest::test_invalid_pages",
"mkdocs/tests/config/config_options_tests.py::NumPagesTest::test_many_pages",
"mkdocs/tests/config/config_options_tests.py::NumPagesTest::test_one_page",
"mkdocs/tests/config/config_options_tests.py::NumPagesTest::test_provided",
"mkdocs/tests/utils_tests.py::UtilsTests::test_get_themes",
"mkdocs/tests/utils_tests.py::UtilsTests::test_html_path",
"mkdocs/tests/utils_tests.py::UtilsTests::test_is_html_file",
"mkdocs/tests/utils_tests.py::UtilsTests::test_is_markdown_file",
"mkdocs/tests/utils_tests.py::UtilsTests::test_nest_paths",
"mkdocs/tests/utils_tests.py::UtilsTests::test_reduce_list",
"mkdocs/tests/utils_tests.py::UtilsTests::test_url_path"
] | [] | BSD 2-Clause "Simplified" License | 138 |
drincruz__python-trie-20 | 57d83c22c0f5eb9faa10a54c138c4e2e5a0f88d8 | 2015-05-15 12:31:04 | 57d83c22c0f5eb9faa10a54c138c4e2e5a0f88d8 | diff --git a/README.md b/README.md
index 77303a0..ba35836 100644
--- a/README.md
+++ b/README.md
@@ -19,7 +19,7 @@ Example
>>> t.contains_word("dogg")
False
>>> t.root
- {'d': {'o': {'g': {'!THIS_IS_THE_END!': {'word': 'dog'}, 's': {'!THIS_IS_THE_END!': {'word': 'dogs'}}, 'g': {'y': {'!THIS_IS_THE_END!': {'word': 'doggy'}}}}}}}
+ {'d': {'o': {'g': {'\0': {'word': 'dog'}, 's': {'\0': {'word': 'dogs'}}, 'g': {'y': {'\0': {'word': 'doggy'}}}}}}}
Unit Testing
diff --git a/trie/trie.py b/trie/trie.py
index 96f3fdb..4bd31f7 100644
--- a/trie/trie.py
+++ b/trie/trie.py
@@ -10,7 +10,7 @@ class TriePy(object):
"""
# A terminator to represent and end of a path
- __TRIE_TERMINATOR = '!THIS_IS_THE_END!'
+ __TRIE_TERMINATOR = '\0'
def __init__(self):
"""
| change default TRIE_TERMINATOR default
'!THIS_IS_THE_END!' was _really_ just an example. Using a \0 terminator makes the most sense. Let's do that. | drincruz/python-trie | diff --git a/tests/test_trie.py b/tests/test_trie.py
index 0b3aa6b..7b1fa5e 100644
--- a/tests/test_trie.py
+++ b/tests/test_trie.py
@@ -15,7 +15,7 @@ def test_abc_add_word():
my_test = {"a":
{"b":
{"c":
- {"!THIS_IS_THE_END!":
+ {"\0":
{"word": "abc"}
}
}
@@ -34,8 +34,8 @@ def test_asterisk_add_word():
my_test = {"*":
{"x":
{"*":
- { "z":
- {"!THIS_IS_THE_END!":
+ {"z":
+ {"\0":
{"word": "*x*z"}
}
}
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 0,
"issue_text_score": 2,
"test_score": 2
},
"num_modified_files": 2
} | 0.1 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "pytest",
"pip_packages": [
"nose",
"pytest"
],
"pre_install": null,
"python": "3.9",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | exceptiongroup @ file:///croot/exceptiongroup_1706031385326/work
iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work
nose==1.3.7
packaging @ file:///croot/packaging_1734472117206/work
pluggy @ file:///croot/pluggy_1733169602837/work
pytest @ file:///croot/pytest_1738938843180/work
tomli @ file:///opt/conda/conda-bld/tomli_1657175507142/work
-e git+https://github.com/drincruz/python-trie.git@57d83c22c0f5eb9faa10a54c138c4e2e5a0f88d8#egg=TriePy
| name: python-trie
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- exceptiongroup=1.2.0=py39h06a4308_0
- iniconfig=1.1.1=pyhd3eb1b0_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=3.0.16=h5eee18b_0
- packaging=24.2=py39h06a4308_0
- pip=25.0=py39h06a4308_0
- pluggy=1.5.0=py39h06a4308_0
- pytest=8.3.4=py39h06a4308_0
- python=3.9.21=he870216_1
- readline=8.2=h5eee18b_0
- setuptools=75.8.0=py39h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- tomli=2.0.1=py39h06a4308_0
- tzdata=2025a=h04d1e81_0
- wheel=0.45.1=py39h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- nose==1.3.7
prefix: /opt/conda/envs/python-trie
| [
"tests/test_trie.py::test_abc_add_word",
"tests/test_trie.py::test_asterisk_add_word"
] | [] | [
"tests/test_trie.py::test_contains_true",
"tests/test_trie.py::test_contains_false"
] | [] | BSD 3-Clause "New" or "Revised" License | 139 |
|
yolothreat__utilitybelt-53 | ef2526c4e15c886c2a68162b67e7d7fb25ec9ee3 | 2015-05-15 17:38:13 | ef2526c4e15c886c2a68162b67e7d7fb25ec9ee3 | diff --git a/.gitignore b/.gitignore
index c26136f..601e383 100644
--- a/.gitignore
+++ b/.gitignore
@@ -57,6 +57,7 @@ venv
## Data
data/*
+*.json
# swap files
*.swp
diff --git a/utilitybelt/utilitybelt.py b/utilitybelt/utilitybelt.py
index 180865c..8307e7a 100644
--- a/utilitybelt/utilitybelt.py
+++ b/utilitybelt/utilitybelt.py
@@ -143,6 +143,24 @@ def is_url(url):
return bool(re.match(re_url, url))
+def is_hash(fhash):
+ """Returns true for valid hashes, false for invalid."""
+
+ # Intentionally doing if/else statement for ease of testing and reading
+ if re.match(re_md5, fhash):
+ return True
+ elif re.match(re_sha1, fhash):
+ return True
+ elif re.match(re_sha256, fhash):
+ return True
+ elif re.match(re_sha512, fhash):
+ return True
+ elif re.match(re_ssdeep, fhash):
+ return True
+ else:
+ return False
+
+
def ip_to_geo(ipaddress):
"""Convert IP to Geographic Information"""
@@ -245,7 +263,10 @@ def vt_ip_check(ip, vt_api):
url = 'https://www.virustotal.com/vtapi/v2/ip-address/report'
parameters = {'ip': ip, 'apikey': vt_api}
response = requests.get(url, params=parameters)
- return response.json()
+ try:
+ return response.json()
+ except ValueError:
+ return None
def vt_name_check(domain, vt_api):
@@ -256,7 +277,24 @@ def vt_name_check(domain, vt_api):
url = 'https://www.virustotal.com/vtapi/v2/domain/report'
parameters = {'domain': domain, 'apikey': vt_api}
response = requests.get(url, params=parameters)
- return response.json()
+ try:
+ return response.json()
+ except ValueError:
+ return None
+
+
+def vt_hash_check(fhash, vt_api):
+ """Checks VirusTotal for occurrences of a file hash"""
+ if not is_hash(fhash):
+ return None
+
+ url = 'https://www.virustotal.com/vtapi/v2/file/report'
+ parameters = {'resource': fhash, 'apikey': vt_api}
+ response = requests.get(url, params=parameters)
+ try:
+ return response.json()
+ except ValueError:
+ return None
def ipinfo_ip_check(ip):
| `vt_name_check()` and `vt_api_check()` do not handle errors properly
If VirusTotal returns an error (such as exceeding rate limits), these functions throw a `JSONDecodeError`. | yolothreat/utilitybelt | diff --git a/utilitybelt/tests/tests.py b/utilitybelt/tests/tests.py
index b826966..ea1f525 100644
--- a/utilitybelt/tests/tests.py
+++ b/utilitybelt/tests/tests.py
@@ -1,4 +1,5 @@
import os
+import time
import unittest
from utilitybelt import utilitybelt as ub
@@ -94,6 +95,21 @@ class TestUB(unittest.TestCase):
self.assertFalse(ub.is_reserved("8.8.4.4"))
self.assertFalse(ub.is_reserved("192.30.252.131"))
+ def test_is_hash(self):
+ # all hashes of the empty string
+ self.assertIsInstance(ub.is_hash("d41d8cd98f00b204e9800998ecf8427e"), bool)
+ # MD5
+ self.assertTrue(ub.is_hash("d41d8cd98f00b204e9800998ecf8427e"))
+ # SHA1
+ self.assertTrue(ub.is_hash("da39a3ee5e6b4b0d3255bfef95601890afd80709"))
+ # SHA256
+ self.assertTrue(ub.is_hash("e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"))
+ # SHA512
+ self.assertTrue(ub.is_hash("cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e"))
+ # ssdeep
+ self.assertTrue(ub.is_hash("96:EQOJvOl4ab3hhiNFXc4wwcweomr0cNJDBoqXjmAHKX8dEt001nfEhVIuX0dDcs:3mzpAsZpprbshfu3oujjdENdp21"))
+ self.assertFalse(ub.is_hash("KilroyWasHere"))
+
def test_vt_ip_check(self):
vt_api = os.environ["VT_API"]
self.assertIsNone(ub.vt_ip_check('asdf', vt_api))
@@ -108,6 +124,7 @@ class TestUB(unittest.TestCase):
if resolution['hostname'] == "github.com":
is_gh = True
self.assertTrue(is_gh)
+ time.sleep(15) # VT rate limiting
def test_vt_name_check(self):
vt_api = os.environ["VT_API"]
@@ -120,6 +137,37 @@ class TestUB(unittest.TestCase):
if resolution['ip_address'] == '192.30.252.130':
is_gh = True
self.assertTrue(is_gh)
+ time.sleep(15) # VT rate limiting
+
+ def test_vt_hash_check(self):
+ vt_api = os.environ["VT_API"]
+ self.assertIsNone(ub.vt_hash_check('asdf', vt_api))
+ vt_hash_data = ub.vt_hash_check("fe03b4181707f1ea1f3c69dc0a9904181c6fce91", vt_api)
+ self.assertIsInstance(vt_hash_data, dict)
+ self.assertIn('resource', vt_hash_data)
+ self.assertIn('positives', vt_hash_data)
+ self.assertGreater(vt_hash_data['positives'], 0)
+ time.sleep(15) # VT rate limiting
+ vt_hash_data = ub.vt_hash_check("d41d8cd98f00b204e9800998ecf8427e", vt_api)
+ self.assertIn('positives', vt_hash_data)
+ self.assertEqual(vt_hash_data['positives'], 0)
+ time.sleep(15) # VT rate limiting
+
+ def test_vt_rate_limiting(self):
+ vt_api = os.environ["VT_API"]
+ # Exceed 4x in 60 seconds
+ data = ub.vt_hash_check("d41d8cd98f00b204e9800998ecf8427e", vt_api)
+ self.assertIsInstance(data, dict)
+ data = ub.vt_hash_check("d41d8cd98f00b204e9800998ecf8427e", vt_api)
+ data = ub.vt_hash_check("d41d8cd98f00b204e9800998ecf8427e", vt_api)
+ data = ub.vt_hash_check("d41d8cd98f00b204e9800998ecf8427e", vt_api)
+ data = ub.vt_name_check("example.org", vt_api)
+ self.assertIsNone(data)
+ data = ub.vt_ip_check("192.30.252.130", vt_api)
+ self.assertIsNone(data)
+ data = ub.vt_hash_check("d41d8cd98f00b204e9800998ecf8427e", vt_api)
+ self.assertIsNone(data)
+ time.sleep(15)
def test_ipinfo(self):
self.assertIsNone(ub.ipinfo_ip_check('asdf'))
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 1,
"issue_text_score": 1,
"test_score": 2
},
"num_modified_files": 2
} | 0.2 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc libgeoip-dev"
],
"python": "3.9",
"reqs_path": [
"requirements.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | beautifulsoup4==4.13.3
certifi==2025.1.31
cfgv==3.4.0
charset-normalizer==3.4.1
-e git+https://github.com/yolothreat/utilitybelt.git@ef2526c4e15c886c2a68162b67e7d7fb25ec9ee3#egg=cnd_utilitybelt
coverage==7.8.0
coveralls==4.0.1
distlib==0.3.9
docopt==0.6.2
exceptiongroup==1.2.2
filelock==3.18.0
identify==2.6.9
idna==3.10
iniconfig==2.1.0
netaddr==1.3.0
nodeenv==1.9.1
packaging==24.2
platformdirs==4.3.7
pluggy==1.5.0
pre_commit==4.2.0
pygeoip==0.3.2
pytest==8.3.5
pytest-cov==6.0.0
PyYAML==6.0.2
requests==2.32.3
soupsieve==2.6
tomli==2.2.1
typing_extensions==4.13.0
urllib3==2.3.0
virtualenv==20.29.3
| name: utilitybelt
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=3.0.16=h5eee18b_0
- pip=25.0=py39h06a4308_0
- python=3.9.21=he870216_1
- readline=8.2=h5eee18b_0
- setuptools=75.8.0=py39h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- tzdata=2025a=h04d1e81_0
- wheel=0.45.1=py39h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- beautifulsoup4==4.13.3
- certifi==2025.1.31
- cfgv==3.4.0
- charset-normalizer==3.4.1
- coverage==7.8.0
- coveralls==4.0.1
- distlib==0.3.9
- docopt==0.6.2
- exceptiongroup==1.2.2
- filelock==3.18.0
- identify==2.6.9
- idna==3.10
- iniconfig==2.1.0
- netaddr==1.3.0
- nodeenv==1.9.1
- packaging==24.2
- platformdirs==4.3.7
- pluggy==1.5.0
- pre-commit==4.2.0
- pygeoip==0.3.2
- pytest==8.3.5
- pytest-cov==6.0.0
- pyyaml==6.0.2
- requests==2.32.3
- soupsieve==2.6
- tomli==2.2.1
- typing-extensions==4.13.0
- urllib3==2.3.0
- virtualenv==20.29.3
prefix: /opt/conda/envs/utilitybelt
| [
"utilitybelt/tests/tests.py::TestUB::test_is_hash"
] | [
"utilitybelt/tests/tests.py::TestUB::test_domain_to_geo",
"utilitybelt/tests/tests.py::TestUB::test_dshield_ip_check",
"utilitybelt/tests/tests.py::TestUB::test_ipinfo",
"utilitybelt/tests/tests.py::TestUB::test_ipvoid_check",
"utilitybelt/tests/tests.py::TestUB::test_reverse_dns",
"utilitybelt/tests/tests.py::TestUB::test_reverse_dns_sna",
"utilitybelt/tests/tests.py::TestUB::test_urlvoid_check",
"utilitybelt/tests/tests.py::TestUB::test_urlvoid_ip_check",
"utilitybelt/tests/tests.py::TestUB::test_vt_hash_check",
"utilitybelt/tests/tests.py::TestUB::test_vt_ip_check",
"utilitybelt/tests/tests.py::TestUB::test_vt_name_check",
"utilitybelt/tests/tests.py::TestUB::test_vt_rate_limiting"
] | [
"utilitybelt/tests/tests.py::TestUB::test_ip_between",
"utilitybelt/tests/tests.py::TestUB::test_ip_to_geo",
"utilitybelt/tests/tests.py::TestUB::test_ip_to_geojson",
"utilitybelt/tests/tests.py::TestUB::test_ip_to_long",
"utilitybelt/tests/tests.py::TestUB::test_ips_to_geojson",
"utilitybelt/tests/tests.py::TestUB::test_is_IPv4Address",
"utilitybelt/tests/tests.py::TestUB::test_is_reserved",
"utilitybelt/tests/tests.py::TestUB::test_is_rfc1918",
"utilitybelt/tests/tests.py::TestUB::test_is_url"
] | [] | MIT License | 140 |
|
sympy__sympy-9403 | 3766b9ca505bb3645e81912b3cc883df73c7a32b | 2015-05-16 01:11:09 | 0241b35cae5f2adc04dc37b25f7dc9c5f00bd746 | diff --git a/sympy/core/mod.py b/sympy/core/mod.py
index 23bdd33399..cefbf8c913 100644
--- a/sympy/core/mod.py
+++ b/sympy/core/mod.py
@@ -84,7 +84,7 @@ def doit(p, q):
# extract gcd; any further simplification should be done by the user
G = gcd(p, q)
- if G is not S.One:
+ if G != 1:
p, q = [
gcd_terms(i/G, clear=False, fraction=False) for i in (p, q)]
pwas, qwas = p, q
diff --git a/sympy/polys/constructor.py b/sympy/polys/constructor.py
index bb86da60fa..409e0c2b8f 100644
--- a/sympy/polys/constructor.py
+++ b/sympy/polys/constructor.py
@@ -6,6 +6,7 @@
from sympy.polys.polyoptions import build_options
from sympy.polys.polyerrors import GeneratorsNeeded
from sympy.polys.domains import ZZ, QQ, RR, EX
+from sympy.polys.domains.realfield import RealField
from sympy.utilities import public
from sympy.core import sympify
@@ -44,7 +45,10 @@ def _construct_simple(coeffs, opt):
domain, result = _construct_algebraic(coeffs, opt)
else:
if reals:
- domain = RR
+ # Use the maximum precision of all coefficients for the RR's
+ # precision
+ max_prec = max([c._prec for c in coeffs])
+ domain = RealField(prec=max_prec)
else:
if opt.field or rationals:
domain = QQ
diff --git a/sympy/polys/domains/mpelements.py b/sympy/polys/domains/mpelements.py
index d44a6f38c7..e5a89220e2 100644
--- a/sympy/polys/domains/mpelements.py
+++ b/sympy/polys/domains/mpelements.py
@@ -1,4 +1,4 @@
-"""Real and complex elements with built-in truncation. """
+"""Real and complex elements. """
from __future__ import print_function, division
@@ -19,13 +19,7 @@ class RealElement(_mpf, DomainElement):
__slots__ = ['__mpf__']
def _set_mpf(self, val):
- prec, rounding = self.context._prec_rounding
- tol = self.context.tol
-
- if mpf_lt(mpf_abs(val, prec, rounding), tol):
- self.__mpf__ = fzero
- else:
- self.__mpf__ = val
+ self.__mpf__ = val
_mpf_ = property(lambda self: self.__mpf__, _set_mpf)
@@ -39,20 +33,7 @@ class ComplexElement(_mpc, DomainElement):
__slots__ = ['__mpc__']
def _set_mpc(self, val):
- prec, rounding = self.context._prec_rounding
- tol = self.context.tol
-
- # norm = mpc_abs(val, prec, rounding)
- # tol = mpf_max(tol, mpf_mul(norm, tol))
-
- re, im = val
-
- if mpf_lt(mpf_abs(re, prec, rounding), tol):
- re = fzero
- if mpf_lt(mpf_abs(im, prec, rounding), tol):
- im = fzero
-
- self.__mpc__ = (re, im)
+ self.__mpc__ = val
_mpc_ = property(lambda self: self.__mpc__, _set_mpc)
| Simplify of small imaginary number yields 0
Using the most recent release (0.7.6) the following expression yields 0:
from sympy import *
(I*Number(1.)*Number(10)**Number(-14)).simplify()
Using the absolute value this does not happen.
(Number(1.)*Number(10)**Number(-14)).simplify()
| sympy/sympy | diff --git a/sympy/core/tests/test_arit.py b/sympy/core/tests/test_arit.py
index eaff343528..222c732c24 100644
--- a/sympy/core/tests/test_arit.py
+++ b/sympy/core/tests/test_arit.py
@@ -1553,7 +1553,14 @@ def test_Mod():
assert (x + 3) % 1 == Mod(x, 1)
assert (x + 3.0) % 1 == Mod(1.*x, 1)
assert (x - S(33)/10) % 1 == Mod(x + S(7)/10, 1)
- assert str(Mod(.6*x + y, .3*y)) == str(Mod(0.1*y + 0.6*x, 0.3*y))
+
+ a = Mod(.6*x + y, .3*y)
+ b = Mod(0.1*y + 0.6*x, 0.3*y)
+ # Test that a, b are equal, with 1e-14 accuracy in coefficients
+ eps = 1e-14
+ assert abs((a.args[0] - b.args[0]).subs({x: 1, y: 1})) < eps
+ assert abs((a.args[1] - b.args[1]).subs({x: 1, y: 1})) < eps
+
assert (x + 1) % x == 1 % x
assert (x + y) % x == y % x
assert (x + y + 2) % x == (y + 2) % x
@@ -1564,7 +1571,7 @@ def test_Mod():
assert (-3*x) % (-2*y) == -Mod(3*x, 2*y)
assert (.6*pi) % (.3*x*pi) == 0.3*pi*Mod(2, x)
assert (.6*pi) % (.31*x*pi) == pi*Mod(0.6, 0.31*x)
- assert (6*pi) % (.3*x*pi) == pi*Mod(6, 0.3*x)
+ assert (6*pi) % (.3*x*pi) == 0.3*pi*Mod(20, x)
assert (6*pi) % (.31*x*pi) == pi*Mod(6, 0.31*x)
assert (6*pi) % (.42*x*pi) == pi*Mod(6, 0.42*x)
assert (12*x) % (2*y) == 2*Mod(6*x, y)
diff --git a/sympy/integrals/tests/test_integrals.py b/sympy/integrals/tests/test_integrals.py
index 650c24b306..9b0575bdab 100644
--- a/sympy/integrals/tests/test_integrals.py
+++ b/sympy/integrals/tests/test_integrals.py
@@ -11,7 +11,7 @@
from sympy.physics import units
from sympy.core.compatibility import range
from sympy.utilities.pytest import XFAIL, raises, slow
-
+from sympy.utilities.randtest import verify_numerically
x, y, a, t, x_1, x_2, z, s = symbols('x y a t x_1 x_2 z s')
@@ -1026,12 +1026,9 @@ def test_risch_option():
# TODO: How to test risch=False?
def test_issue_6828():
- # TODO: Currently `h' is the result (all three are equivalent). Improve
- # simplify() to find the form with simplest real coefficients.
f = 1/(1.08*x**2 - 4.3)
- g = 300.0/(324.0*x**2 - 1290.0)
- h = 0.925925925925926/(1.0*x**2 - 3.98148148148148)
- assert integrate(f, x).diff(x).simplify().equals(f) is True
+ g = integrate(f, x).diff(x)
+ assert verify_numerically(f, g, tol=1e-12)
@XFAIL
def test_integrate_Piecewise_rational_over_reals():
diff --git a/sympy/physics/optics/tests/test_medium.py b/sympy/physics/optics/tests/test_medium.py
index 66ec8664cf..e574e719b5 100644
--- a/sympy/physics/optics/tests/test_medium.py
+++ b/sympy/physics/optics/tests/test_medium.py
@@ -29,8 +29,11 @@ def test_medium():
assert m4.refractive_index < m1.refractive_index
assert m4 < m1
m5 = Medium('m5', permittivity=710*10**(-12)*s**4*A**2/(m**3*kg), n=1.33)
- assert simplify(m5.intrinsic_impedance - 6.24845417765552*kg*m**2/(A**2*s**3)) == 0
+ assert abs(m5.intrinsic_impedance - 6.24845417765552*kg*m**2/(A**2*s**3)) \
+ < 1e-12*kg*m**2/(A**2*s**3)
assert abs(m5.speed - 225407863.157895*m/s) < 1e-6*m/s
- assert simplify(m5.refractive_index - 1.33000000000000) == 0
- assert simplify(m5.permittivity - 7.1e-10*A**2*s**4/(kg*m**3)) == 0
- assert simplify(m5.permeability - 2.77206575232851e-8*kg*m/(A**2*s**2)) == 0
+ assert abs(m5.refractive_index - 1.33000000000000) < 1e-12
+ assert abs(m5.permittivity - 7.1e-10*A**2*s**4/(kg*m**3)) \
+ < 1e-20*A**2*s**4/(kg*m**3)
+ assert abs(m5.permeability - 2.77206575232851e-8*kg*m/(A**2*s**2)) \
+ < 1e-20*kg*m/(A**2*s**2)
diff --git a/sympy/polys/domains/tests/test_domains.py b/sympy/polys/domains/tests/test_domains.py
index c71ee686d4..6efd1575cc 100644
--- a/sympy/polys/domains/tests/test_domains.py
+++ b/sympy/polys/domains/tests/test_domains.py
@@ -1,9 +1,10 @@
"""Tests for classes defining properties of ground domains, e.g. ZZ, QQ, ZZ[x] ... """
-from sympy import S, sqrt, sin, oo, Poly
+from sympy import S, sqrt, sin, oo, Poly, Float
from sympy.abc import x, y, z
from sympy.polys.domains import ZZ, QQ, RR, CC, FF, GF, EX
+from sympy.polys.domains.realfield import RealField
from sympy.polys.rings import ring
from sympy.polys.fields import field
@@ -732,3 +733,38 @@ def test_ModularInteger():
def test_QQ_int():
assert int(QQ(2**2000, 3**1250)) == 455431
assert int(QQ(2**100, 3)) == 422550200076076467165567735125
+
+def test_RR_double():
+ assert RR(3.14) > 1e-50
+ assert RR(1e-13) > 1e-50
+ assert RR(1e-14) > 1e-50
+ assert RR(1e-15) > 1e-50
+ assert RR(1e-20) > 1e-50
+ assert RR(1e-40) > 1e-50
+
+def test_RR_Float():
+ f1 = Float("1.01")
+ f2 = Float("1.0000000000000000000001")
+ assert f1._prec == 53
+ assert f2._prec == 80
+ assert RR(f1)-1 > 1e-50
+ assert RR(f2)-1 < 1e-50 # RR's precision is lower than f2's
+
+ RR2 = RealField(prec=f2._prec)
+ assert RR2(f1)-1 > 1e-50
+ assert RR2(f2)-1 > 1e-50 # RR's precision is equal to f2's
+
+def test_CC_double():
+ assert CC(3.14).real > 1e-50
+ assert CC(1e-13).real > 1e-50
+ assert CC(1e-14).real > 1e-50
+ assert CC(1e-15).real > 1e-50
+ assert CC(1e-20).real > 1e-50
+ assert CC(1e-40).real > 1e-50
+
+ assert CC(3.14j).imag > 1e-50
+ assert CC(1e-13j).imag > 1e-50
+ assert CC(1e-14j).imag > 1e-50
+ assert CC(1e-15j).imag > 1e-50
+ assert CC(1e-20j).imag > 1e-50
+ assert CC(1e-40j).imag > 1e-50
diff --git a/sympy/polys/tests/test_constructor.py b/sympy/polys/tests/test_constructor.py
index 62466e27a5..5238ec52af 100644
--- a/sympy/polys/tests/test_constructor.py
+++ b/sympy/polys/tests/test_constructor.py
@@ -2,8 +2,9 @@
from sympy.polys.constructor import construct_domain
from sympy.polys.domains import ZZ, QQ, RR, EX
+from sympy.polys.domains.realfield import RealField
-from sympy import S, sqrt, sin
+from sympy import S, sqrt, sin, Float
from sympy.abc import x, y
def test_construct_domain():
@@ -14,7 +15,9 @@ def test_construct_domain():
assert construct_domain([S(1), S(2), S(3)], field=True) == (QQ, [QQ(1), QQ(2), QQ(3)])
assert construct_domain([S(1)/2, S(2)]) == (QQ, [QQ(1, 2), QQ(2)])
- assert construct_domain([3.14, 1, S(1)/2]) == (RR, [RR(3.14), RR(1.0), RR(0.5)])
+ result = construct_domain([3.14, 1, S(1)/2])
+ assert isinstance(result[0], RealField)
+ assert result[1] == [RR(3.14), RR(1.0), RR(0.5)]
assert construct_domain([3.14, sqrt(2)], extension=None) == (EX, [EX(3.14), EX(sqrt(2))])
assert construct_domain([3.14, sqrt(2)], extension=True) == (EX, [EX(3.14), EX(sqrt(2))])
@@ -101,3 +104,20 @@ def test_composite_option():
assert construct_domain({(1, 0): y}, composite=False) == \
(EX, {(1, 0): EX(y)})
+
+def test_precision():
+ f1 = Float("1.01")
+ f2 = Float("1.0000000000000000000001")
+ for x in [1, 1e-2, 1e-6, 1e-13, 1e-14, 1e-16, 1e-20, 1e-100, 1e-300,
+ f1, f2]:
+ result = construct_domain([x])
+ y = float(result[1][0])
+ assert abs(x - y) / x < 1e-14 # Test relative accuracy
+
+ result = construct_domain([f1])
+ y = result[1][0]
+ assert y-1 > 1e-50
+
+ result = construct_domain([f2])
+ y = result[1][0]
+ assert y-1 > 1e-50
diff --git a/sympy/polys/tests/test_polytools.py b/sympy/polys/tests/test_polytools.py
index 56ccb0c726..38deab20d5 100644
--- a/sympy/polys/tests/test_polytools.py
+++ b/sympy/polys/tests/test_polytools.py
@@ -47,6 +47,7 @@
from sympy.polys.fields import field
from sympy.polys.domains import FF, ZZ, QQ, RR, EX
+from sympy.polys.domains.realfield import RealField
from sympy.polys.orderings import lex, grlex, grevlex
from sympy import (
@@ -346,7 +347,7 @@ def test_Poly__new__():
Poly(3*x**5 + 65536*x**4 + x**3 + 65536*x** 2 + 1, x,
modulus=65537, symmetric=False)
- assert Poly(x**2 + x + 1.0).get_domain() == RR
+ assert isinstance(Poly(x**2 + x + 1.0).get_domain(), RealField)
def test_Poly__args():
@@ -560,7 +561,7 @@ def test_Poly_get_domain():
raises(CoercionFailed, lambda: Poly(x/2, domain='ZZ'))
assert Poly(x/2, domain='QQ').get_domain() == QQ
- assert Poly(0.2*x).get_domain() == RR
+ assert isinstance(Poly(0.2*x).get_domain(), RealField)
def test_Poly_set_domain():
diff --git a/sympy/simplify/tests/test_simplify.py b/sympy/simplify/tests/test_simplify.py
index 4705bdd359..22deb4f78f 100644
--- a/sympy/simplify/tests/test_simplify.py
+++ b/sympy/simplify/tests/test_simplify.py
@@ -229,7 +229,7 @@ def test_issue_3210():
def test_issue_7263():
assert abs((simplify(30.8**2 - 82.5**2 * sin(rad(11.6))**2)).evalf() - \
- 673.447451402970) < 1e-15
+ 673.447451402970) < 1e-12
def test_trigsimp_issues():
@@ -1914,6 +1914,34 @@ def test_inequality_no_auto_simplify():
assert e == Lt(lhs, rhs, evaluate=False)
assert simplify(e)
+def test_issue_9398():
+ from sympy import Number, cancel
+ assert cancel(1e-14) != 0
+ assert cancel(1e-14*I) != 0
+
+ assert simplify(1e-14) != 0
+ assert simplify(1e-14*I) != 0
+
+ assert (I*Number(1.)*Number(10)**Number(-14)).simplify() != 0
+
+ assert cancel(1e-20) != 0
+ assert cancel(1e-20*I) != 0
+
+ assert simplify(1e-20) != 0
+ assert simplify(1e-20*I) != 0
+
+ assert cancel(1e-100) != 0
+ assert cancel(1e-100*I) != 0
+
+ assert simplify(1e-100) != 0
+ assert simplify(1e-100*I) != 0
+
+ f = Float("1e-1000")
+ assert cancel(f) != 0
+ assert cancel(f*I) != 0
+
+ assert simplify(f) != 0
+ assert simplify(f*I) != 0
def test_issue_9324_simplify():
M = MatrixSymbol('M', 10, 10)
diff --git a/sympy/solvers/tests/test_solvers.py b/sympy/solvers/tests/test_solvers.py
index 09fa1537ae..cfd5ca0c74 100644
--- a/sympy/solvers/tests/test_solvers.py
+++ b/sympy/solvers/tests/test_solvers.py
@@ -16,7 +16,7 @@
from sympy.physics.units import cm
from sympy.polys.rootoftools import RootOf
-from sympy.utilities.pytest import slow, XFAIL, raises, skip, ON_TRAVIS
+from sympy.utilities.pytest import slow, XFAIL, SKIP, raises, skip, ON_TRAVIS
from sympy.utilities.randtest import verify_numerically as tn
from sympy.abc import a, b, c, d, k, h, p, x, y, z, t, q, m
@@ -743,8 +743,8 @@ def test_issue_5335():
assert len(solve(eqs, sym, manual=True, minimal=True, simplify=False)) == 2
-@XFAIL
-def test_issue_5335_float():
+@SKIP("Hangs")
+def _test_issue_5335_float():
# gives ZeroDivisionError: polynomial division
lam, a0, conc = symbols('lam a0 conc')
eqs = [lam + 2*y - a0*(1 - x/2)*x - 0.005*x/2*x,
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 2,
"issue_text_score": 0,
"test_score": 3
},
"num_modified_files": 3
} | 0.7 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[dev]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "pytest",
"pip_packages": [
"pytest"
],
"pre_install": null,
"python": "3.7",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | attrs @ file:///croot/attrs_1668696182826/work
certifi @ file:///croot/certifi_1671487769961/work/certifi
flit_core @ file:///opt/conda/conda-bld/flit-core_1644941570762/work/source/flit_core
importlib-metadata @ file:///tmp/build/80754af9/importlib-metadata_1648562407465/work
iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work
mpmath==1.3.0
packaging @ file:///croot/packaging_1671697413597/work
pluggy @ file:///tmp/build/80754af9/pluggy_1648042572264/work
py @ file:///opt/conda/conda-bld/py_1644396412707/work
pytest==7.1.2
-e git+https://github.com/sympy/sympy.git@3766b9ca505bb3645e81912b3cc883df73c7a32b#egg=sympy
tomli @ file:///opt/conda/conda-bld/tomli_1657175507142/work
typing_extensions @ file:///croot/typing_extensions_1669924550328/work
zipp @ file:///croot/zipp_1672387121353/work
| name: sympy
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- attrs=22.1.0=py37h06a4308_0
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2022.12.7=py37h06a4308_0
- flit-core=3.6.0=pyhd3eb1b0_0
- importlib-metadata=4.11.3=py37h06a4308_0
- importlib_metadata=4.11.3=hd3eb1b0_0
- iniconfig=1.1.1=pyhd3eb1b0_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- packaging=22.0=py37h06a4308_0
- pip=22.3.1=py37h06a4308_0
- pluggy=1.0.0=py37h06a4308_1
- py=1.11.0=pyhd3eb1b0_0
- pytest=7.1.2=py37h06a4308_0
- python=3.7.16=h7a1cb2a_0
- readline=8.2=h5eee18b_0
- setuptools=65.6.3=py37h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- tomli=2.0.1=py37h06a4308_0
- typing_extensions=4.4.0=py37h06a4308_0
- wheel=0.38.4=py37h06a4308_0
- xz=5.6.4=h5eee18b_1
- zipp=3.11.0=py37h06a4308_0
- zlib=1.2.13=h5eee18b_1
- pip:
- mpmath==1.3.0
prefix: /opt/conda/envs/sympy
| [
"sympy/polys/domains/tests/test_domains.py::test_RR_double",
"sympy/polys/domains/tests/test_domains.py::test_RR_Float",
"sympy/polys/domains/tests/test_domains.py::test_CC_double",
"sympy/polys/tests/test_constructor.py::test_precision",
"sympy/simplify/tests/test_simplify.py::test_issue_9398"
] | [] | [
"sympy/core/tests/test_arit.py::test_bug1",
"sympy/core/tests/test_arit.py::test_Symbol",
"sympy/core/tests/test_arit.py::test_arit0",
"sympy/core/tests/test_arit.py::test_div",
"sympy/core/tests/test_arit.py::test_pow",
"sympy/core/tests/test_arit.py::test_pow2",
"sympy/core/tests/test_arit.py::test_pow3",
"sympy/core/tests/test_arit.py::test_pow_E",
"sympy/core/tests/test_arit.py::test_pow_issue_3516",
"sympy/core/tests/test_arit.py::test_pow_im",
"sympy/core/tests/test_arit.py::test_real_mul",
"sympy/core/tests/test_arit.py::test_ncmul",
"sympy/core/tests/test_arit.py::test_ncpow",
"sympy/core/tests/test_arit.py::test_powerbug",
"sympy/core/tests/test_arit.py::test_Mul_doesnt_expand_exp",
"sympy/core/tests/test_arit.py::test_Add_Mul_is_integer",
"sympy/core/tests/test_arit.py::test_Add_Mul_is_finite",
"sympy/core/tests/test_arit.py::test_Mul_is_even_odd",
"sympy/core/tests/test_arit.py::test_evenness_in_ternary_integer_product_with_even",
"sympy/core/tests/test_arit.py::test_oddness_in_ternary_integer_product_with_even",
"sympy/core/tests/test_arit.py::test_Mul_is_rational",
"sympy/core/tests/test_arit.py::test_Add_is_rational",
"sympy/core/tests/test_arit.py::test_Add_is_even_odd",
"sympy/core/tests/test_arit.py::test_Mul_is_negative_positive",
"sympy/core/tests/test_arit.py::test_Mul_is_negative_positive_2",
"sympy/core/tests/test_arit.py::test_Mul_is_nonpositive_nonnegative",
"sympy/core/tests/test_arit.py::test_Add_is_negative_positive",
"sympy/core/tests/test_arit.py::test_Add_is_nonpositive_nonnegative",
"sympy/core/tests/test_arit.py::test_Pow_is_integer",
"sympy/core/tests/test_arit.py::test_Pow_is_real",
"sympy/core/tests/test_arit.py::test_real_Pow",
"sympy/core/tests/test_arit.py::test_Pow_is_finite",
"sympy/core/tests/test_arit.py::test_Pow_is_even_odd",
"sympy/core/tests/test_arit.py::test_Pow_is_negative_positive",
"sympy/core/tests/test_arit.py::test_Pow_is_zero",
"sympy/core/tests/test_arit.py::test_Pow_is_nonpositive_nonnegative",
"sympy/core/tests/test_arit.py::test_Mul_is_imaginary_real",
"sympy/core/tests/test_arit.py::test_Mul_hermitian_antihermitian",
"sympy/core/tests/test_arit.py::test_Add_is_comparable",
"sympy/core/tests/test_arit.py::test_Mul_is_comparable",
"sympy/core/tests/test_arit.py::test_Pow_is_comparable",
"sympy/core/tests/test_arit.py::test_Add_is_positive_2",
"sympy/core/tests/test_arit.py::test_Add_is_irrational",
"sympy/core/tests/test_arit.py::test_issue_3531b",
"sympy/core/tests/test_arit.py::test_bug3",
"sympy/core/tests/test_arit.py::test_suppressed_evaluation",
"sympy/core/tests/test_arit.py::test_Add_as_coeff_mul",
"sympy/core/tests/test_arit.py::test_Pow_as_coeff_mul_doesnt_expand",
"sympy/core/tests/test_arit.py::test_issue_3514",
"sympy/core/tests/test_arit.py::test_make_args",
"sympy/core/tests/test_arit.py::test_issue_5126",
"sympy/core/tests/test_arit.py::test_Rational_as_content_primitive",
"sympy/core/tests/test_arit.py::test_Add_as_content_primitive",
"sympy/core/tests/test_arit.py::test_Mul_as_content_primitive",
"sympy/core/tests/test_arit.py::test_Pow_as_content_primitive",
"sympy/core/tests/test_arit.py::test_issue_5460",
"sympy/core/tests/test_arit.py::test_product_irrational",
"sympy/core/tests/test_arit.py::test_issue_5919",
"sympy/core/tests/test_arit.py::test_Mod",
"sympy/core/tests/test_arit.py::test_Mod_is_integer",
"sympy/core/tests/test_arit.py::test_Mod_is_nonposneg",
"sympy/core/tests/test_arit.py::test_issue_6001",
"sympy/core/tests/test_arit.py::test_polar",
"sympy/core/tests/test_arit.py::test_issue_6040",
"sympy/core/tests/test_arit.py::test_issue_6082",
"sympy/core/tests/test_arit.py::test_issue_6077",
"sympy/core/tests/test_arit.py::test_mul_flatten_oo",
"sympy/core/tests/test_arit.py::test_add_flatten",
"sympy/core/tests/test_arit.py::test_issue_5160_6087_6089_6090",
"sympy/core/tests/test_arit.py::test_float_int",
"sympy/core/tests/test_arit.py::test_issue_6611a",
"sympy/core/tests/test_arit.py::test_denest_add_mul",
"sympy/core/tests/test_arit.py::test_mul_coeff",
"sympy/core/tests/test_arit.py::test_mul_zero_detection",
"sympy/core/tests/test_arit.py::test_Mul_with_zero_infinite",
"sympy/core/tests/test_arit.py::test_issue_8247_8354",
"sympy/integrals/tests/test_integrals.py::test_improper_integral",
"sympy/integrals/tests/test_integrals.py::test_constructor",
"sympy/integrals/tests/test_integrals.py::test_basics",
"sympy/integrals/tests/test_integrals.py::test_basics_multiple",
"sympy/integrals/tests/test_integrals.py::test_conjugate_transpose",
"sympy/integrals/tests/test_integrals.py::test_integration",
"sympy/integrals/tests/test_integrals.py::test_multiple_integration",
"sympy/integrals/tests/test_integrals.py::test_issue_3532",
"sympy/integrals/tests/test_integrals.py::test_issue_3560",
"sympy/integrals/tests/test_integrals.py::test_integrate_poly",
"sympy/integrals/tests/test_integrals.py::test_integrate_poly_defined",
"sympy/integrals/tests/test_integrals.py::test_integrate_omit_var",
"sympy/integrals/tests/test_integrals.py::test_integrate_poly_accurately",
"sympy/integrals/tests/test_integrals.py::test_issue_3635",
"sympy/integrals/tests/test_integrals.py::test_integrate_linearterm_pow",
"sympy/integrals/tests/test_integrals.py::test_issue_3618",
"sympy/integrals/tests/test_integrals.py::test_issue_3623",
"sympy/integrals/tests/test_integrals.py::test_issue_3664",
"sympy/integrals/tests/test_integrals.py::test_issue_3679",
"sympy/integrals/tests/test_integrals.py::test_issue_3686",
"sympy/integrals/tests/test_integrals.py::test_integrate_units",
"sympy/integrals/tests/test_integrals.py::test_transcendental_functions",
"sympy/integrals/tests/test_integrals.py::test_issue_3740",
"sympy/integrals/tests/test_integrals.py::test_issue_3788",
"sympy/integrals/tests/test_integrals.py::test_issue_3952",
"sympy/integrals/tests/test_integrals.py::test_issue_4516",
"sympy/integrals/tests/test_integrals.py::test_issue_7450",
"sympy/integrals/tests/test_integrals.py::test_matrices",
"sympy/integrals/tests/test_integrals.py::test_integrate_functions",
"sympy/integrals/tests/test_integrals.py::test_integrate_derivatives",
"sympy/integrals/tests/test_integrals.py::test_transform",
"sympy/integrals/tests/test_integrals.py::test_issue_4052",
"sympy/integrals/tests/test_integrals.py::test_evalf_integrals",
"sympy/integrals/tests/test_integrals.py::test_evalf_issue_939",
"sympy/integrals/tests/test_integrals.py::test_integrate_DiracDelta",
"sympy/integrals/tests/test_integrals.py::test_integrate_returns_piecewise",
"sympy/integrals/tests/test_integrals.py::test_subs1",
"sympy/integrals/tests/test_integrals.py::test_subs2",
"sympy/integrals/tests/test_integrals.py::test_subs3",
"sympy/integrals/tests/test_integrals.py::test_subs4",
"sympy/integrals/tests/test_integrals.py::test_subs5",
"sympy/integrals/tests/test_integrals.py::test_subs6",
"sympy/integrals/tests/test_integrals.py::test_subs7",
"sympy/integrals/tests/test_integrals.py::test_expand",
"sympy/integrals/tests/test_integrals.py::test_integration_variable",
"sympy/integrals/tests/test_integrals.py::test_expand_integral",
"sympy/integrals/tests/test_integrals.py::test_as_sum_midpoint1",
"sympy/integrals/tests/test_integrals.py::test_as_sum_midpoint2",
"sympy/integrals/tests/test_integrals.py::test_as_sum_left",
"sympy/integrals/tests/test_integrals.py::test_as_sum_right",
"sympy/integrals/tests/test_integrals.py::test_as_sum_raises",
"sympy/integrals/tests/test_integrals.py::test_nested_doit",
"sympy/integrals/tests/test_integrals.py::test_issue_4665",
"sympy/integrals/tests/test_integrals.py::test_integral_reconstruct",
"sympy/integrals/tests/test_integrals.py::test_doit_integrals",
"sympy/integrals/tests/test_integrals.py::test_issue_4884",
"sympy/integrals/tests/test_integrals.py::test_is_number",
"sympy/integrals/tests/test_integrals.py::test_symbols",
"sympy/integrals/tests/test_integrals.py::test_is_zero",
"sympy/integrals/tests/test_integrals.py::test_series",
"sympy/integrals/tests/test_integrals.py::test_issue_4403",
"sympy/integrals/tests/test_integrals.py::test_issue_4403_2",
"sympy/integrals/tests/test_integrals.py::test_issue_4100",
"sympy/integrals/tests/test_integrals.py::test_issue_5167",
"sympy/integrals/tests/test_integrals.py::test_issue_4890",
"sympy/integrals/tests/test_integrals.py::test_issue_4376",
"sympy/integrals/tests/test_integrals.py::test_issue_4517",
"sympy/integrals/tests/test_integrals.py::test_issue_4527",
"sympy/integrals/tests/test_integrals.py::test_issue_4199",
"sympy/integrals/tests/test_integrals.py::test_issue_3940",
"sympy/integrals/tests/test_integrals.py::test_issue_5413",
"sympy/integrals/tests/test_integrals.py::test_issue_4892a",
"sympy/integrals/tests/test_integrals.py::test_issue_4892b",
"sympy/integrals/tests/test_integrals.py::test_issue_5178",
"sympy/integrals/tests/test_integrals.py::test_integrate_series",
"sympy/integrals/tests/test_integrals.py::test_atom_bug",
"sympy/integrals/tests/test_integrals.py::test_limit_bug",
"sympy/integrals/tests/test_integrals.py::test_issue_4703",
"sympy/integrals/tests/test_integrals.py::test_issue_1888",
"sympy/integrals/tests/test_integrals.py::test_issue_3558",
"sympy/integrals/tests/test_integrals.py::test_issue_4422",
"sympy/integrals/tests/test_integrals.py::test_issue_4493",
"sympy/integrals/tests/test_integrals.py::test_issue_4737",
"sympy/integrals/tests/test_integrals.py::test_issue_4992",
"sympy/integrals/tests/test_integrals.py::test_issue_4487",
"sympy/integrals/tests/test_integrals.py::test_issue_4400",
"sympy/integrals/tests/test_integrals.py::test_issue_6253",
"sympy/integrals/tests/test_integrals.py::test_issue_4153",
"sympy/integrals/tests/test_integrals.py::test_issue_4326",
"sympy/integrals/tests/test_integrals.py::test_powers",
"sympy/integrals/tests/test_integrals.py::test_risch_option",
"sympy/integrals/tests/test_integrals.py::test_issue_6828",
"sympy/integrals/tests/test_integrals.py::test_issue_4803",
"sympy/integrals/tests/test_integrals.py::test_issue_4234",
"sympy/integrals/tests/test_integrals.py::test_issue_4492",
"sympy/integrals/tests/test_integrals.py::test_issue_2708",
"sympy/integrals/tests/test_integrals.py::test_issue_8368",
"sympy/integrals/tests/test_integrals.py::test_issue_8901",
"sympy/integrals/tests/test_integrals.py::test_issue_7130",
"sympy/physics/optics/tests/test_medium.py::test_medium",
"sympy/polys/domains/tests/test_domains.py::test_Domain_unify",
"sympy/polys/domains/tests/test_domains.py::test_Domain_unify_composite",
"sympy/polys/domains/tests/test_domains.py::test_Domain_unify_algebraic",
"sympy/polys/domains/tests/test_domains.py::test_Domain_unify_with_symbols",
"sympy/polys/domains/tests/test_domains.py::test_Domain__contains__",
"sympy/polys/domains/tests/test_domains.py::test_Domain_get_ring",
"sympy/polys/domains/tests/test_domains.py::test_Domain_get_field",
"sympy/polys/domains/tests/test_domains.py::test_Domain_get_exact",
"sympy/polys/domains/tests/test_domains.py::test_Domain_convert",
"sympy/polys/domains/tests/test_domains.py::test_PolynomialRing__init",
"sympy/polys/domains/tests/test_domains.py::test_FractionField__init",
"sympy/polys/domains/tests/test_domains.py::test_inject",
"sympy/polys/domains/tests/test_domains.py::test_Domain_map",
"sympy/polys/domains/tests/test_domains.py::test_Domain___eq__",
"sympy/polys/domains/tests/test_domains.py::test_Domain__algebraic_field",
"sympy/polys/domains/tests/test_domains.py::test_PolynomialRing_from_FractionField",
"sympy/polys/domains/tests/test_domains.py::test_FractionField_from_PolynomialRing",
"sympy/polys/domains/tests/test_domains.py::test_FF_of_type",
"sympy/polys/domains/tests/test_domains.py::test___eq__",
"sympy/polys/domains/tests/test_domains.py::test_RealField_from_sympy",
"sympy/polys/domains/tests/test_domains.py::test_ModularInteger",
"sympy/polys/domains/tests/test_domains.py::test_QQ_int",
"sympy/polys/tests/test_constructor.py::test_construct_domain",
"sympy/polys/tests/test_constructor.py::test_composite_option",
"sympy/polys/tests/test_polytools.py::test_Poly_from_dict",
"sympy/polys/tests/test_polytools.py::test_Poly_from_list",
"sympy/polys/tests/test_polytools.py::test_Poly_from_poly",
"sympy/polys/tests/test_polytools.py::test_Poly_from_expr",
"sympy/polys/tests/test_polytools.py::test_Poly__new__",
"sympy/polys/tests/test_polytools.py::test_Poly__args",
"sympy/polys/tests/test_polytools.py::test_Poly__gens",
"sympy/polys/tests/test_polytools.py::test_Poly_zero",
"sympy/polys/tests/test_polytools.py::test_Poly_one",
"sympy/polys/tests/test_polytools.py::test_Poly__unify",
"sympy/polys/tests/test_polytools.py::test_Poly_free_symbols",
"sympy/polys/tests/test_polytools.py::test_PurePoly_free_symbols",
"sympy/polys/tests/test_polytools.py::test_Poly__eq__",
"sympy/polys/tests/test_polytools.py::test_PurePoly__eq__",
"sympy/polys/tests/test_polytools.py::test_PurePoly_Poly",
"sympy/polys/tests/test_polytools.py::test_Poly_get_domain",
"sympy/polys/tests/test_polytools.py::test_Poly_set_domain",
"sympy/polys/tests/test_polytools.py::test_Poly_get_modulus",
"sympy/polys/tests/test_polytools.py::test_Poly_set_modulus",
"sympy/polys/tests/test_polytools.py::test_Poly_add_ground",
"sympy/polys/tests/test_polytools.py::test_Poly_sub_ground",
"sympy/polys/tests/test_polytools.py::test_Poly_mul_ground",
"sympy/polys/tests/test_polytools.py::test_Poly_quo_ground",
"sympy/polys/tests/test_polytools.py::test_Poly_exquo_ground",
"sympy/polys/tests/test_polytools.py::test_Poly_abs",
"sympy/polys/tests/test_polytools.py::test_Poly_neg",
"sympy/polys/tests/test_polytools.py::test_Poly_add",
"sympy/polys/tests/test_polytools.py::test_Poly_sub",
"sympy/polys/tests/test_polytools.py::test_Poly_mul",
"sympy/polys/tests/test_polytools.py::test_Poly_sqr",
"sympy/polys/tests/test_polytools.py::test_Poly_pow",
"sympy/polys/tests/test_polytools.py::test_Poly_divmod",
"sympy/polys/tests/test_polytools.py::test_Poly_eq_ne",
"sympy/polys/tests/test_polytools.py::test_Poly_nonzero",
"sympy/polys/tests/test_polytools.py::test_Poly_properties",
"sympy/polys/tests/test_polytools.py::test_Poly_is_irreducible",
"sympy/polys/tests/test_polytools.py::test_Poly_subs",
"sympy/polys/tests/test_polytools.py::test_Poly_replace",
"sympy/polys/tests/test_polytools.py::test_Poly_reorder",
"sympy/polys/tests/test_polytools.py::test_Poly_ltrim",
"sympy/polys/tests/test_polytools.py::test_Poly_has_only_gens",
"sympy/polys/tests/test_polytools.py::test_Poly_to_ring",
"sympy/polys/tests/test_polytools.py::test_Poly_to_field",
"sympy/polys/tests/test_polytools.py::test_Poly_to_exact",
"sympy/polys/tests/test_polytools.py::test_Poly_retract",
"sympy/polys/tests/test_polytools.py::test_Poly_slice",
"sympy/polys/tests/test_polytools.py::test_Poly_coeffs",
"sympy/polys/tests/test_polytools.py::test_Poly_monoms",
"sympy/polys/tests/test_polytools.py::test_Poly_terms",
"sympy/polys/tests/test_polytools.py::test_Poly_all_coeffs",
"sympy/polys/tests/test_polytools.py::test_Poly_all_monoms",
"sympy/polys/tests/test_polytools.py::test_Poly_all_terms",
"sympy/polys/tests/test_polytools.py::test_Poly_termwise",
"sympy/polys/tests/test_polytools.py::test_Poly_length",
"sympy/polys/tests/test_polytools.py::test_Poly_as_dict",
"sympy/polys/tests/test_polytools.py::test_Poly_as_expr",
"sympy/polys/tests/test_polytools.py::test_Poly_lift",
"sympy/polys/tests/test_polytools.py::test_Poly_deflate",
"sympy/polys/tests/test_polytools.py::test_Poly_inject",
"sympy/polys/tests/test_polytools.py::test_Poly_eject",
"sympy/polys/tests/test_polytools.py::test_Poly_exclude",
"sympy/polys/tests/test_polytools.py::test_Poly__gen_to_level",
"sympy/polys/tests/test_polytools.py::test_Poly_degree",
"sympy/polys/tests/test_polytools.py::test_Poly_degree_list",
"sympy/polys/tests/test_polytools.py::test_Poly_total_degree",
"sympy/polys/tests/test_polytools.py::test_Poly_homogenize",
"sympy/polys/tests/test_polytools.py::test_Poly_homogeneous_order",
"sympy/polys/tests/test_polytools.py::test_Poly_LC",
"sympy/polys/tests/test_polytools.py::test_Poly_TC",
"sympy/polys/tests/test_polytools.py::test_Poly_EC",
"sympy/polys/tests/test_polytools.py::test_Poly_coeff",
"sympy/polys/tests/test_polytools.py::test_Poly_nth",
"sympy/polys/tests/test_polytools.py::test_Poly_LM",
"sympy/polys/tests/test_polytools.py::test_Poly_LM_custom_order",
"sympy/polys/tests/test_polytools.py::test_Poly_EM",
"sympy/polys/tests/test_polytools.py::test_Poly_LT",
"sympy/polys/tests/test_polytools.py::test_Poly_ET",
"sympy/polys/tests/test_polytools.py::test_Poly_max_norm",
"sympy/polys/tests/test_polytools.py::test_Poly_l1_norm",
"sympy/polys/tests/test_polytools.py::test_Poly_clear_denoms",
"sympy/polys/tests/test_polytools.py::test_Poly_rat_clear_denoms",
"sympy/polys/tests/test_polytools.py::test_Poly_integrate",
"sympy/polys/tests/test_polytools.py::test_Poly_diff",
"sympy/polys/tests/test_polytools.py::test_Poly_eval",
"sympy/polys/tests/test_polytools.py::test_Poly___call__",
"sympy/polys/tests/test_polytools.py::test_parallel_poly_from_expr",
"sympy/polys/tests/test_polytools.py::test_pdiv",
"sympy/polys/tests/test_polytools.py::test_div",
"sympy/polys/tests/test_polytools.py::test_gcdex",
"sympy/polys/tests/test_polytools.py::test_revert",
"sympy/polys/tests/test_polytools.py::test_subresultants",
"sympy/polys/tests/test_polytools.py::test_resultant",
"sympy/polys/tests/test_polytools.py::test_discriminant",
"sympy/polys/tests/test_polytools.py::test_dispersion",
"sympy/polys/tests/test_polytools.py::test_gcd_list",
"sympy/polys/tests/test_polytools.py::test_lcm_list",
"sympy/polys/tests/test_polytools.py::test_gcd",
"sympy/polys/tests/test_polytools.py::test_gcd_numbers_vs_polys",
"sympy/polys/tests/test_polytools.py::test_terms_gcd",
"sympy/polys/tests/test_polytools.py::test_trunc",
"sympy/polys/tests/test_polytools.py::test_monic",
"sympy/polys/tests/test_polytools.py::test_content",
"sympy/polys/tests/test_polytools.py::test_primitive",
"sympy/polys/tests/test_polytools.py::test_compose",
"sympy/polys/tests/test_polytools.py::test_shift",
"sympy/polys/tests/test_polytools.py::test_sturm",
"sympy/polys/tests/test_polytools.py::test_gff",
"sympy/polys/tests/test_polytools.py::test_sqf_norm",
"sympy/polys/tests/test_polytools.py::test_sqf",
"sympy/polys/tests/test_polytools.py::test_factor",
"sympy/polys/tests/test_polytools.py::test_factor_large",
"sympy/polys/tests/test_polytools.py::test_intervals",
"sympy/polys/tests/test_polytools.py::test_refine_root",
"sympy/polys/tests/test_polytools.py::test_count_roots",
"sympy/polys/tests/test_polytools.py::test_Poly_root",
"sympy/polys/tests/test_polytools.py::test_real_roots",
"sympy/polys/tests/test_polytools.py::test_all_roots",
"sympy/polys/tests/test_polytools.py::test_nroots",
"sympy/polys/tests/test_polytools.py::test_ground_roots",
"sympy/polys/tests/test_polytools.py::test_nth_power_roots_poly",
"sympy/polys/tests/test_polytools.py::test_torational_factor_list",
"sympy/polys/tests/test_polytools.py::test_cancel",
"sympy/polys/tests/test_polytools.py::test_reduced",
"sympy/polys/tests/test_polytools.py::test_groebner",
"sympy/polys/tests/test_polytools.py::test_fglm",
"sympy/polys/tests/test_polytools.py::test_is_zero_dimensional",
"sympy/polys/tests/test_polytools.py::test_GroebnerBasis",
"sympy/polys/tests/test_polytools.py::test_poly",
"sympy/polys/tests/test_polytools.py::test_keep_coeff",
"sympy/polys/tests/test_polytools.py::test_noncommutative",
"sympy/polys/tests/test_polytools.py::test_to_rational_coeffs",
"sympy/simplify/tests/test_simplify.py::test_ratsimp",
"sympy/simplify/tests/test_simplify.py::test_ratsimpmodprime",
"sympy/simplify/tests/test_simplify.py::test_trigsimp1",
"sympy/simplify/tests/test_simplify.py::test_trigsimp1a",
"sympy/simplify/tests/test_simplify.py::test_trigsimp2",
"sympy/simplify/tests/test_simplify.py::test_issue_4373",
"sympy/simplify/tests/test_simplify.py::test_trigsimp3",
"sympy/simplify/tests/test_simplify.py::test_issue_4661",
"sympy/simplify/tests/test_simplify.py::test_issue_4494",
"sympy/simplify/tests/test_simplify.py::test_issue_5948",
"sympy/simplify/tests/test_simplify.py::test_issue_4775",
"sympy/simplify/tests/test_simplify.py::test_issue_4280",
"sympy/simplify/tests/test_simplify.py::test_issue_3210",
"sympy/simplify/tests/test_simplify.py::test_issue_7263",
"sympy/simplify/tests/test_simplify.py::test_trigsimp_issues",
"sympy/simplify/tests/test_simplify.py::test_trigsimp_issue_2515",
"sympy/simplify/tests/test_simplify.py::test_trigsimp_issue_3826",
"sympy/simplify/tests/test_simplify.py::test_trigsimp_issue_4032",
"sympy/simplify/tests/test_simplify.py::test_trigsimp_issue_7761",
"sympy/simplify/tests/test_simplify.py::test_trigsimp_noncommutative",
"sympy/simplify/tests/test_simplify.py::test_hyperbolic_simp",
"sympy/simplify/tests/test_simplify.py::test_trigsimp_groebner",
"sympy/simplify/tests/test_simplify.py::test_simplify_expr",
"sympy/simplify/tests/test_simplify.py::test_issue_3557",
"sympy/simplify/tests/test_simplify.py::test_simplify_other",
"sympy/simplify/tests/test_simplify.py::test_simplify_complex",
"sympy/simplify/tests/test_simplify.py::test_simplify_ratio",
"sympy/simplify/tests/test_simplify.py::test_simplify_measure",
"sympy/simplify/tests/test_simplify.py::test_simplify_issue_1308",
"sympy/simplify/tests/test_simplify.py::test_issue_5652",
"sympy/simplify/tests/test_simplify.py::test_simplify_fail1",
"sympy/simplify/tests/test_simplify.py::test_fraction",
"sympy/simplify/tests/test_simplify.py::test_powsimp",
"sympy/simplify/tests/test_simplify.py::test_issue_6367",
"sympy/simplify/tests/test_simplify.py::test_powsimp_negated_base",
"sympy/simplify/tests/test_simplify.py::test_issue_6440",
"sympy/simplify/tests/test_simplify.py::test_powsimp_polar",
"sympy/simplify/tests/test_simplify.py::test_powsimp_nc",
"sympy/simplify/tests/test_simplify.py::test_nthroot",
"sympy/simplify/tests/test_simplify.py::test_nthroot1",
"sympy/simplify/tests/test_simplify.py::test_collect_1",
"sympy/simplify/tests/test_simplify.py::test_collect_2",
"sympy/simplify/tests/test_simplify.py::test_collect_3",
"sympy/simplify/tests/test_simplify.py::test_collect_4",
"sympy/simplify/tests/test_simplify.py::test_collect_5",
"sympy/simplify/tests/test_simplify.py::test_collect_D",
"sympy/simplify/tests/test_simplify.py::test_collect_D_0",
"sympy/simplify/tests/test_simplify.py::test_collect_Wild",
"sympy/simplify/tests/test_simplify.py::test_collect_func",
"sympy/simplify/tests/test_simplify.py::test_collect_order",
"sympy/simplify/tests/test_simplify.py::test_rcollect",
"sympy/simplify/tests/test_simplify.py::test_separatevars",
"sympy/simplify/tests/test_simplify.py::test_separatevars_advanced_factor",
"sympy/simplify/tests/test_simplify.py::test_hypersimp",
"sympy/simplify/tests/test_simplify.py::test_nsimplify",
"sympy/simplify/tests/test_simplify.py::test_extract_minus_sign",
"sympy/simplify/tests/test_simplify.py::test_diff",
"sympy/simplify/tests/test_simplify.py::test_logcombine_1",
"sympy/simplify/tests/test_simplify.py::test_logcombine_complex_coeff",
"sympy/simplify/tests/test_simplify.py::test_posify",
"sympy/simplify/tests/test_simplify.py::test_powdenest",
"sympy/simplify/tests/test_simplify.py::test_powdenest_polar",
"sympy/simplify/tests/test_simplify.py::test_issue_5805",
"sympy/simplify/tests/test_simplify.py::test_issue_4194",
"sympy/simplify/tests/test_simplify.py::test_combsimp",
"sympy/simplify/tests/test_simplify.py::test_issue_5615",
"sympy/simplify/tests/test_simplify.py::test_issue_5728",
"sympy/simplify/tests/test_simplify.py::test_as_content_primitive",
"sympy/simplify/tests/test_simplify.py::test_radsimp",
"sympy/simplify/tests/test_simplify.py::test_radsimp_issue_3214",
"sympy/simplify/tests/test_simplify.py::test_collect_const",
"sympy/simplify/tests/test_simplify.py::test_issue_5933",
"sympy/simplify/tests/test_simplify.py::test_fraction_expand",
"sympy/simplify/tests/test_simplify.py::test_combsimp_gamma",
"sympy/simplify/tests/test_simplify.py::test_polarify",
"sympy/simplify/tests/test_simplify.py::test_unpolarify",
"sympy/simplify/tests/test_simplify.py::test_issue_6097",
"sympy/simplify/tests/test_simplify.py::test_signsimp",
"sympy/simplify/tests/test_simplify.py::test_besselsimp",
"sympy/simplify/tests/test_simplify.py::test_Piecewise",
"sympy/simplify/tests/test_simplify.py::test_polymorphism",
"sympy/simplify/tests/test_simplify.py::test_issue_from_PR1599",
"sympy/simplify/tests/test_simplify.py::test_issue_6811",
"sympy/simplify/tests/test_simplify.py::test_issue_6920",
"sympy/simplify/tests/test_simplify.py::test_issue_7001",
"sympy/simplify/tests/test_simplify.py::test_exptrigsimp",
"sympy/simplify/tests/test_simplify.py::test_issue_2827_trigsimp_methods",
"sympy/simplify/tests/test_simplify.py::test_powsimp_on_numbers",
"sympy/simplify/tests/test_simplify.py::test_inequality_no_auto_simplify",
"sympy/simplify/tests/test_simplify.py::test_issue_9324_simplify",
"sympy/simplify/tests/test_simplify.py::test_issue_9324_powsimp_on_matrix_symbol",
"sympy/solvers/tests/test_solvers.py::test_swap_back",
"sympy/solvers/tests/test_solvers.py::test_guess_poly",
"sympy/solvers/tests/test_solvers.py::test_guess_poly_cv",
"sympy/solvers/tests/test_solvers.py::test_guess_rational_cv",
"sympy/solvers/tests/test_solvers.py::test_guess_transcendental",
"sympy/solvers/tests/test_solvers.py::test_solve_args",
"sympy/solvers/tests/test_solvers.py::test_solve_polynomial1",
"sympy/solvers/tests/test_solvers.py::test_solve_polynomial2",
"sympy/solvers/tests/test_solvers.py::test_solve_polynomial_cv_1a",
"sympy/solvers/tests/test_solvers.py::test_solve_polynomial_cv_1b",
"sympy/solvers/tests/test_solvers.py::test_solve_polynomial_cv_2",
"sympy/solvers/tests/test_solvers.py::test_quintics_1",
"sympy/solvers/tests/test_solvers.py::test_highorder_poly",
"sympy/solvers/tests/test_solvers.py::test_quintics_2",
"sympy/solvers/tests/test_solvers.py::test_solve_rational",
"sympy/solvers/tests/test_solvers.py::test_solve_nonlinear",
"sympy/solvers/tests/test_solvers.py::test_issue_8666",
"sympy/solvers/tests/test_solvers.py::test_issue_7228",
"sympy/solvers/tests/test_solvers.py::test_issue_7190",
"sympy/solvers/tests/test_solvers.py::test_linear_system",
"sympy/solvers/tests/test_solvers.py::test_linear_system_function",
"sympy/solvers/tests/test_solvers.py::test_linear_systemLU",
"sympy/solvers/tests/test_solvers.py::test_solve_transcendental",
"sympy/solvers/tests/test_solvers.py::test_solve_for_functions_derivatives",
"sympy/solvers/tests/test_solvers.py::test_issue_3725",
"sympy/solvers/tests/test_solvers.py::test_issue_3870",
"sympy/solvers/tests/test_solvers.py::test_solve_linear",
"sympy/solvers/tests/test_solvers.py::test_solve_undetermined_coeffs",
"sympy/solvers/tests/test_solvers.py::test_solve_inequalities",
"sympy/solvers/tests/test_solvers.py::test_issue_4793",
"sympy/solvers/tests/test_solvers.py::test_PR1964",
"sympy/solvers/tests/test_solvers.py::test_issue_5197",
"sympy/solvers/tests/test_solvers.py::test_checking",
"sympy/solvers/tests/test_solvers.py::test_issue_4671_4463_4467",
"sympy/solvers/tests/test_solvers.py::test_issue_5132",
"sympy/solvers/tests/test_solvers.py::test_issue_5335",
"sympy/solvers/tests/test_solvers.py::test_issue_5767",
"sympy/solvers/tests/test_solvers.py::test_polysys",
"sympy/solvers/tests/test_solvers.py::test_unrad1",
"sympy/solvers/tests/test_solvers.py::test_unrad_slow",
"sympy/solvers/tests/test_solvers.py::test__invert",
"sympy/solvers/tests/test_solvers.py::test_issue_4463",
"sympy/solvers/tests/test_solvers.py::test_issue_5114",
"sympy/solvers/tests/test_solvers.py::test_issue_5849",
"sympy/solvers/tests/test_solvers.py::test_issue_5849_matrix",
"sympy/solvers/tests/test_solvers.py::test_issue_5901",
"sympy/solvers/tests/test_solvers.py::test_issue_5912",
"sympy/solvers/tests/test_solvers.py::test_float_handling",
"sympy/solvers/tests/test_solvers.py::test_check_assumptions",
"sympy/solvers/tests/test_solvers.py::test_issue_6056",
"sympy/solvers/tests/test_solvers.py::test_issue_6060",
"sympy/solvers/tests/test_solvers.py::test_issue_5673",
"sympy/solvers/tests/test_solvers.py::test_exclude",
"sympy/solvers/tests/test_solvers.py::test_high_order_roots",
"sympy/solvers/tests/test_solvers.py::test_minsolve_linear_system",
"sympy/solvers/tests/test_solvers.py::test_real_roots",
"sympy/solvers/tests/test_solvers.py::test_issue_6528",
"sympy/solvers/tests/test_solvers.py::test_overdetermined",
"sympy/solvers/tests/test_solvers.py::test_issue_6605",
"sympy/solvers/tests/test_solvers.py::test__ispow",
"sympy/solvers/tests/test_solvers.py::test_issue_6644",
"sympy/solvers/tests/test_solvers.py::test_issue_6752",
"sympy/solvers/tests/test_solvers.py::test_issue_6792",
"sympy/solvers/tests/test_solvers.py::test_issues_6819_6820_6821_6248_8692",
"sympy/solvers/tests/test_solvers.py::test_issue_6989",
"sympy/solvers/tests/test_solvers.py::test_lambert_multivariate",
"sympy/solvers/tests/test_solvers.py::test_rewrite_trig",
"sympy/solvers/tests/test_solvers.py::test_uselogcombine",
"sympy/solvers/tests/test_solvers.py::test_atan2",
"sympy/solvers/tests/test_solvers.py::test_errorinverses",
"sympy/solvers/tests/test_solvers.py::test_issue_2725",
"sympy/solvers/tests/test_solvers.py::test_issue_5114_6611",
"sympy/solvers/tests/test_solvers.py::test_det_quick",
"sympy/solvers/tests/test_solvers.py::test_piecewise",
"sympy/solvers/tests/test_solvers.py::test_real_imag_splitting",
"sympy/solvers/tests/test_solvers.py::test_issue_7110",
"sympy/solvers/tests/test_solvers.py::test_units",
"sympy/solvers/tests/test_solvers.py::test_issue_7547",
"sympy/solvers/tests/test_solvers.py::test_issue_7895",
"sympy/solvers/tests/test_solvers.py::test_issue_2777",
"sympy/solvers/tests/test_solvers.py::test_issue_7322",
"sympy/solvers/tests/test_solvers.py::test_nsolve",
"sympy/solvers/tests/test_solvers.py::test_issue_8587",
"sympy/solvers/tests/test_solvers.py::test_high_order_multivariate",
"sympy/solvers/tests/test_solvers.py::test_base_0_exp_0",
"sympy/solvers/tests/test_solvers.py::test__simple_dens",
"sympy/solvers/tests/test_solvers.py::test_issue_8755",
"sympy/solvers/tests/test_solvers.py::test_issue_8828",
"sympy/solvers/tests/test_solvers.py::test_issue_2840_8155"
] | [] | BSD | 141 |
|
pysmt__pysmt-114 | 4fd83af49e7784a874f57620809404d530929366 | 2015-05-17 17:12:04 | 689cc79ff2731837903b14daa266afc99b4feb21 | diff --git a/pysmt/simplifier.py b/pysmt/simplifier.py
index 418bc0d..3303577 100644
--- a/pysmt/simplifier.py
+++ b/pysmt/simplifier.py
@@ -445,7 +445,7 @@ class Simplifier(walkers.DagWalker):
res = args[0].bv_unsigned_value() // args[1].bv_unsigned_value()
res = res % 2**formula.bv_width()
return self.manager.BV(res, width=formula.bv_width())
- return self.manager.BVUdiv(*args)
+ return self.manager.BVUDiv(*args)
def walk_bv_urem(self, formula, args):
if args[0].is_bv_constant() and args[1].is_bv_constant:
@@ -454,7 +454,7 @@ class Simplifier(walkers.DagWalker):
else:
res = args[0].bv_unsigned_value() % args[1].bv_unsigned_value()
return self.manager.BV(res, width=formula.bv_width())
- return self.manager.BVUrem(*args)
+ return self.manager.BVURem(*args)
def walk_bv_ult(self, formula, args):
if args[0].is_bv_constant() and args[1].is_bv_constant:
@@ -506,7 +506,7 @@ class Simplifier(walkers.DagWalker):
filler = bitstr[0]
res = filler*formula.bv_extend_step() + bitstr
return self.manager.BV(res, width=formula.bv_width())
- return self.manager.BVSext(args[0], formula.bv_extend_step())
+ return self.manager.BVSExt(args[0], formula.bv_extend_step())
def walk_bv_zext(self, formula, args):
if args[0].is_bv_constant():
@@ -517,7 +517,7 @@ class Simplifier(walkers.DagWalker):
return self.manager.BVZExt(args[0], formula.bv_extend_step())
def walk_bv_concat(self, formula, args):
- if args[0].is_bv_constant() and args[1].is_bv_constant:
+ if args[0].is_bv_constant() and args[1].is_bv_constant():
w0 = args[0].bv_width()
w1 = args[1].bv_width()
res = (2**w1) * args[0].bv_unsigned_value() + \
@@ -526,14 +526,14 @@ class Simplifier(walkers.DagWalker):
return self.manager.BVConcat(*args)
def walk_bv_lshl(self, formula, args):
- if args[0].is_bv_constant() and args[1].is_bv_constant:
+ if args[0].is_bv_constant() and args[1].is_bv_constant():
res = args[0].bv_unsigned_value() << args[1].bv_unsigned_value()
w = args[0].bv_width()
return self.manager.BV(res % (2 ** w), w)
return self.manager.BVLShl(*args)
def walk_bv_lshr(self, formula, args):
- if args[0].is_bv_constant() and args[1].is_bv_constant:
+ if args[0].is_bv_constant() and args[1].is_bv_constant():
res = args[0].bv_unsigned_value() >> args[1].bv_unsigned_value()
w = args[0].bv_width()
return self.manager.BV(res % (2 ** w), w)
diff --git a/pysmt/walkers/identitydag.py b/pysmt/walkers/identitydag.py
index 1fc1915..b422926 100644
--- a/pysmt/walkers/identitydag.py
+++ b/pysmt/walkers/identitydag.py
@@ -31,72 +31,135 @@ class IdentityDagWalker(DagWalker):
DagWalker.__init__(self,
env=env,
invalidate_memoization=invalidate_memoization)
+ self.mgr = self.env.formula_manager
def walk_symbol(self, formula, args):
- return self.env.formula_manager.Symbol(formula.symbol_name(),
+ return self.mgr.Symbol(formula.symbol_name(),
formula.symbol_type())
def walk_real_constant(self, formula, args):
- return self.env.formula_manager.Real(formula.constant_value())
+ return self.mgr.Real(formula.constant_value())
def walk_int_constant(self, formula, args):
- return self.env.formula_manager.Int(formula.constant_value())
+ return self.mgr.Int(formula.constant_value())
def walk_bool_constant(self, formula, args):
- return self.env.formula_manager.Bool(formula.constant_value())
+ return self.mgr.Bool(formula.constant_value())
def walk_and(self, formula, args):
- return self.env.formula_manager.And(args)
+ return self.mgr.And(args)
def walk_or(self, formula, args):
- return self.env.formula_manager.Or(args)
+ return self.mgr.Or(args)
def walk_not(self, formula, args):
- return self.env.formula_manager.Not(args[0])
+ return self.mgr.Not(*args)
def walk_iff(self, formula, args):
- return self.env.formula_manager.Iff(args[0], args[1])
+ return self.mgr.Iff(*args)
def walk_implies(self, formula, args):
- return self.env.formula_manager.Implies(args[0], args[1])
+ return self.mgr.Implies(*args)
def walk_equals(self, formula, args):
- return self.env.formula_manager.Equals(args[0], args[1])
+ return self.mgr.Equals(*args)
def walk_ite(self, formula, args):
- return self.env.formula_manager.Ite(args[0], args[1], args[2])
+ return self.mgr.Ite(*args)
def walk_ge(self, formula, args):
- return self.env.formula_manager.GE(args[0], args[1])
+ return self.mgr.GE(*args)
def walk_le(self, formula, args):
- return self.env.formula_manager.LE(args[0], args[1])
+ return self.mgr.LE(*args)
def walk_gt(self, formula, args):
- return self.env.formula_manager.GT(args[0], args[1])
+ return self.mgr.GT(*args)
def walk_lt(self, formula, args):
- return self.env.formula_manager.LT(args[0], args[1])
+ return self.mgr.LT(*args)
def walk_forall(self, formula, args):
qvars = [self.walk_symbol(v, None) for v in formula.quantifier_vars()]
- return self.env.formula_manager.ForAll(qvars,args[0])
+ return self.mgr.ForAll(qvars, *args)
def walk_exists(self, formula, args):
qvars = [self.walk_symbol(v, None) for v in formula.quantifier_vars()]
- return self.env.formula_manager.Exists(qvars,args[0])
+ return self.mgr.Exists(qvars, *args)
def walk_plus(self, formula, args):
- return self.env.formula_manager.Plus(args)
+ return self.mgr.Plus(args)
def walk_times(self, formula, args):
- return self.env.formula_manager.Times(args[0], args[1])
+ return self.mgr.Times(*args)
def walk_minus(self, formula, args):
- return self.env.formula_manager.Minus(args[0], args[1])
+ return self.mgr.Minus(*args)
def walk_function(self, formula, args):
- return self.env.formula_manager.Function(formula.function_name(), args)
+ return self.mgr.Function(formula.function_name(), args)
def walk_toreal(self, formula, args):
- return self.env.formula_manager.ToReal(args[0])
+ return self.mgr.ToReal(*args)
+
+ def walk_bv_constant(self, formula, args):
+ return self.mgr.BV(formula.constant_value(), formula.bv_width())
+
+ def walk_bv_and(self, formula, args):
+ return self.mgr.BVAnd(*args)
+
+ def walk_bv_not(self, formula, args):
+ return self.mgr.BVNot(*args)
+
+ def walk_bv_neg(self, formula, args):
+ return self.mgr.BVNeg(*args)
+
+ def walk_bv_or(self, formula, args):
+ return self.mgr.BVOr(*args)
+
+ def walk_bv_xor(self, formula, args):
+ return self.mgr.BVXor(*args)
+
+ def walk_bv_add(self, formula, args):
+ return self.mgr.BVAdd(*args)
+
+ def walk_bv_mul(self, formula, args):
+ return self.mgr.BVMul(*args)
+
+ def walk_bv_udiv(self, formula, args):
+ return self.mgr.BVUDiv(*args)
+
+ def walk_bv_urem(self, formula, args):
+ return self.mgr.BVURem(*args)
+
+ def walk_bv_ult(self, formula, args):
+ return self.mgr.BVULT(*args)
+
+ def walk_bv_ule(self, formula, args):
+ return self.mgr.BVULE(*args)
+
+ def walk_bv_extract(self, formula, args):
+ return self.mgr.BVExtract(args[0],
+ start=formula.bv_extract_start(),
+ end=formula.bv_extract_end())
+
+ def walk_bv_ror(self, formula, args):
+ return self.mgr.BVRor(args[0], formula.bv_rotation_step())
+
+ def walk_bv_rol(self, formula, args):
+ return self.mgr.BVRol(args[0], formula.bv_rotation_step())
+
+ def walk_bv_sext(self, formula, args):
+ return self.mgr.BVSExt(args[0], formula.bv_extend_step())
+
+ def walk_bv_zext(self, formula, args):
+ return self.mgr.BVZExt(args[0], formula.bv_extend_step())
+
+ def walk_bv_concat(self, formula, args):
+ return self.mgr.BVConcat(*args)
+
+ def walk_bv_lshl(self, formula, args):
+ return self.mgr.BVLShl(*args)
+
+ def walk_bv_lshr(self, formula, args):
+ return self.mgr.BVLShr(*args)
| IdentityDagWalker lacks BV support | pysmt/pysmt | diff --git a/pysmt/test/test_walkers.py b/pysmt/test/test_walkers.py
index 22a96c7..6defb39 100644
--- a/pysmt/test/test_walkers.py
+++ b/pysmt/test/test_walkers.py
@@ -25,6 +25,7 @@ from pysmt.typing import INT, BOOL, REAL, FunctionType
from pysmt.walkers import TreeWalker, DagWalker, IdentityDagWalker
from pysmt.test import TestCase
from pysmt.formula import FormulaManager
+from pysmt.test.examples import get_example_formulae
from six.moves import xrange
@@ -100,7 +101,7 @@ class TestWalkers(TestCase):
self.assertFalse(tree_walker.is_complete())
- def test_identity_walker(self):
+ def test_identity_walker_simple(self):
def walk_and_to_or(formula, args, **kwargs):
return Or(args)
@@ -125,6 +126,11 @@ class TestWalkers(TestCase):
result = walker.walk(alternation)
self.assertEqual(result, expected)
+ def test_identity_dag_walker(self):
+ idw = IdentityDagWalker()
+ for (f, _, _, _) in get_example_formulae():
+ rebuilt = idw.walk(f)
+ self.assertTrue(rebuilt == f, "Rebuilt formula is not identical")
def test_substitution_on_quantifiers(self):
x, y = FreshSymbol(), FreshSymbol()
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 1,
"issue_text_score": 3,
"test_score": 0
},
"num_modified_files": 2
} | 0.3 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[dev]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"nose",
"pytest"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.9",
"reqs_path": [
"requirements/base.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | exceptiongroup==1.2.2
iniconfig==2.1.0
nose==1.3.7
packaging==24.2
pluggy==1.5.0
-e git+https://github.com/pysmt/pysmt.git@4fd83af49e7784a874f57620809404d530929366#egg=PySMT
pytest==8.3.5
six==1.17.0
tomli==2.2.1
| name: pysmt
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=3.0.16=h5eee18b_0
- pip=25.0=py39h06a4308_0
- python=3.9.21=he870216_1
- readline=8.2=h5eee18b_0
- setuptools=75.8.0=py39h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- tzdata=2025a=h04d1e81_0
- wheel=0.45.1=py39h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- exceptiongroup==1.2.2
- iniconfig==2.1.0
- nose==1.3.7
- packaging==24.2
- pluggy==1.5.0
- pytest==8.3.5
- six==1.17.0
- tomli==2.2.1
prefix: /opt/conda/envs/pysmt
| [
"pysmt/test/test_walkers.py::TestWalkers::test_identity_dag_walker"
] | [] | [
"pysmt/test/test_walkers.py::TestWalkers::test_identity_walker_simple",
"pysmt/test/test_walkers.py::TestWalkers::test_iterative_get_free_variables",
"pysmt/test/test_walkers.py::TestWalkers::test_subst",
"pysmt/test/test_walkers.py::TestWalkers::test_substituter_conditions",
"pysmt/test/test_walkers.py::TestWalkers::test_substitution_complex",
"pysmt/test/test_walkers.py::TestWalkers::test_substitution_on_functions",
"pysmt/test/test_walkers.py::TestWalkers::test_substitution_on_quantifiers",
"pysmt/test/test_walkers.py::TestWalkers::test_substitution_term",
"pysmt/test/test_walkers.py::TestWalkers::test_undefined_node",
"pysmt/test/test_walkers.py::TestWalkers::test_walker_is_complete"
] | [] | Apache License 2.0 | 142 |
|
pre-commit__pre-commit-231 | 9515ca06378d74f1e4f8013db2b5230c1f15edaa | 2015-05-18 19:48:14 | 9515ca06378d74f1e4f8013db2b5230c1f15edaa | asottile: @Lucas-C look correct?
coveralls:
[](https://coveralls.io/builds/2591860)
Coverage decreased (-0.04%) to 99.96% when pulling **b140f92cd7e20368b27d19ea01227402e71c294a on no_defaults_in_config_227** into **9515ca06378d74f1e4f8013db2b5230c1f15edaa on master**.
| diff --git a/pre_commit/clientlib/validate_config.py b/pre_commit/clientlib/validate_config.py
index bdd0e2c..e4a90a6 100644
--- a/pre_commit/clientlib/validate_config.py
+++ b/pre_commit/clientlib/validate_config.py
@@ -33,7 +33,7 @@ CONFIG_JSON_SCHEMA = {
'properties': {
'id': {'type': 'string'},
'files': {'type': 'string'},
- 'exclude': {'type': 'string', 'default': '^$'},
+ 'exclude': {'type': 'string'},
'language_version': {'type': 'string'},
'args': {
'type': 'array',
@@ -71,7 +71,7 @@ def validate_config_extra(config):
)
for hook in repo['hooks']:
try_regex(repo, hook['id'], hook.get('files', ''), 'files')
- try_regex(repo, hook['id'], hook['exclude'], 'exclude')
+ try_regex(repo, hook['id'], hook.get('exclude', ''), 'exclude')
load_config = get_validator(
diff --git a/pre_commit/clientlib/validate_manifest.py b/pre_commit/clientlib/validate_manifest.py
index 283d7c4..4295014 100644
--- a/pre_commit/clientlib/validate_manifest.py
+++ b/pre_commit/clientlib/validate_manifest.py
@@ -20,6 +20,7 @@ MANIFEST_JSON_SCHEMA = {
'name': {'type': 'string'},
'description': {'type': 'string', 'default': ''},
'entry': {'type': 'string'},
+ 'exclude': {'type': 'string', 'default': '^$'},
'language': {'type': 'string'},
'language_version': {'type': 'string', 'default': 'default'},
'files': {'type': 'string'},
@@ -52,8 +53,14 @@ def validate_files(hook_config):
if not is_regex_valid(hook_config['files']):
raise InvalidManifestError(
'Invalid files regex at {0}: {1}'.format(
- hook_config['id'],
- hook_config['files'],
+ hook_config['id'], hook_config['files'],
+ )
+ )
+
+ if not is_regex_valid(hook_config.get('exclude', '')):
+ raise InvalidManifestError(
+ 'Invalid exclude regex at {0}: {1}'.format(
+ hook_config['id'], hook_config['exclude'],
)
)
| Bug: base manifest value for 'exclude' is always ignored
I stumbled upon this bug while working on #226: the culprit is [`Repository.hooks`](https://github.com/pre-commit/pre-commit/blob/master/pre_commit/repository.py#L48).
A quick fix for this would be to simply remove the default value from `pre_commit/clientlib/validate_config.py`, but the root cause is that any default value defined for a field in this file will make the corresponding manifest field useless.
Basically here is what happens in `Repository.hooks`:
- all the hooks defined in the current repository are enumerated
- at this stage, a `hook` is a dict closely matching the Yaml the config file content, **plus** default values for fields not defined in the Yaml but having a JSON schema 'default'
- when doing the dict merge, **every** (key,value) pair in `hook` overrides the corresponding manifest entry. This includes default config value like `exclude: '$^'` overriding a base manifest value like `exclude: '.bak$'`
Hence I suggest either adding a test ensuring there will never be any 'default' defined in `CONFIG_JSON_SCHEMA`, or improving the merge logic. | pre-commit/pre-commit | diff --git a/tests/clientlib/validate_config_test.py b/tests/clientlib/validate_config_test.py
index c507f28..b474f1b 100644
--- a/tests/clientlib/validate_config_test.py
+++ b/tests/clientlib/validate_config_test.py
@@ -174,3 +174,23 @@ def test_config_with_local_hooks_definition_passes(config_obj):
jsonschema.validate(config_obj, CONFIG_JSON_SCHEMA)
config = apply_defaults(config_obj, CONFIG_JSON_SCHEMA)
validate_config_extra(config)
+
+
+def test_does_not_contain_defaults():
+ """Due to the way our merging works, if this schema has any defaults they
+ will clobber potentially useful values in the backing manifest. #227
+ """
+ to_process = [(CONFIG_JSON_SCHEMA, ())]
+ while to_process:
+ schema, route = to_process.pop()
+ # Check this value
+ if isinstance(schema, dict):
+ if 'default' in schema:
+ raise AssertionError(
+ 'Unexpected default in schema at {0}'.format(
+ ' => '.join(route),
+ )
+ )
+
+ for key, value in schema.items():
+ to_process.append((value, route + (key,)))
diff --git a/tests/clientlib/validate_manifest_test.py b/tests/clientlib/validate_manifest_test.py
index 5e5690e..937f432 100644
--- a/tests/clientlib/validate_manifest_test.py
+++ b/tests/clientlib/validate_manifest_test.py
@@ -46,6 +46,9 @@ def test_additional_manifest_check_passing(obj):
[{'id': 'a', 'language': 'not a language', 'files': ''}],
[{'id': 'a', 'language': 'python3', 'files': ''}],
[{'id': 'a', 'language': 'python', 'files': 'invalid regex('}],
+ [{'id': 'a', 'language': 'not a language', 'files': ''}],
+ [{'id': 'a', 'language': 'python3', 'files': ''}],
+ [{'id': 'a', 'language': 'python', 'files': '', 'exclude': '('}],
),
)
def test_additional_manifest_failing(obj):
diff --git a/tests/manifest_test.py b/tests/manifest_test.py
index ba30d42..39ecc74 100644
--- a/tests/manifest_test.py
+++ b/tests/manifest_test.py
@@ -22,6 +22,7 @@ def test_manifest_contents(manifest):
'args': [],
'description': '',
'entry': 'bin/hook.sh',
+ 'exclude': '^$',
'expected_return_value': 0,
'files': '',
'id': 'bash_hook',
@@ -36,6 +37,7 @@ def test_hooks(manifest):
'args': [],
'description': '',
'entry': 'bin/hook.sh',
+ 'exclude': '^$',
'expected_return_value': 0,
'files': '',
'id': 'bash_hook',
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 1,
"issue_text_score": 1,
"test_score": 0
},
"num_modified_files": 2
} | 0.4 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[dev]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.5",
"reqs_path": [
"requirements-dev.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | aspy.yaml==1.3.0
astroid==1.3.2
attrs==22.2.0
cached-property==1.5.2
certifi==2021.5.30
coverage==6.2
distlib==0.3.9
filelock==3.4.1
flake8==5.0.4
importlib-metadata==4.8.3
importlib-resources==5.4.0
iniconfig==1.1.1
jsonschema==3.2.0
logilab-common==1.9.7
mccabe==0.7.0
mock==5.2.0
mypy-extensions==1.0.0
nodeenv==1.6.0
ordereddict==1.1
packaging==21.3
platformdirs==2.4.0
pluggy==1.0.0
-e git+https://github.com/pre-commit/pre-commit.git@9515ca06378d74f1e4f8013db2b5230c1f15edaa#egg=pre_commit
py==1.11.0
pycodestyle==2.9.1
pyflakes==2.5.0
pylint==1.3.1
pyparsing==3.1.4
pyrsistent==0.18.0
pytest==7.0.1
PyYAML==6.0.1
simplejson==3.20.1
six==1.17.0
tomli==1.2.3
typing_extensions==4.1.1
virtualenv==20.17.1
zipp==3.6.0
| name: pre-commit
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- pip=21.2.2=py36h06a4308_0
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_0
- setuptools=58.0.4=py36h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- argparse==1.4.0
- aspy-yaml==1.3.0
- astroid==1.3.2
- attrs==22.2.0
- cached-property==1.5.2
- coverage==6.2
- distlib==0.3.9
- filelock==3.4.1
- flake8==5.0.4
- importlib-metadata==4.8.3
- importlib-resources==5.4.0
- iniconfig==1.1.1
- jsonschema==3.2.0
- logilab-common==1.9.7
- mccabe==0.7.0
- mock==5.2.0
- mypy-extensions==1.0.0
- nodeenv==1.6.0
- ordereddict==1.1
- packaging==21.3
- platformdirs==2.4.0
- pluggy==1.0.0
- py==1.11.0
- pycodestyle==2.9.1
- pyflakes==2.5.0
- pylint==1.3.1
- pyparsing==3.1.4
- pyrsistent==0.18.0
- pytest==7.0.1
- pyyaml==6.0.1
- simplejson==3.20.1
- six==1.17.0
- tomli==1.2.3
- typing-extensions==4.1.1
- virtualenv==20.17.1
- zipp==3.6.0
prefix: /opt/conda/envs/pre-commit
| [
"tests/clientlib/validate_config_test.py::test_does_not_contain_defaults",
"tests/clientlib/validate_manifest_test.py::test_additional_manifest_failing[obj5]"
] | [
"tests/clientlib/validate_config_test.py::test_run[input0-0]",
"tests/clientlib/validate_config_test.py::test_run[input1-0]",
"tests/clientlib/validate_manifest_test.py::test_run[input0-0]",
"tests/clientlib/validate_manifest_test.py::test_run[input1-0]",
"tests/manifest_test.py::test_manifest_contents",
"tests/manifest_test.py::test_hooks"
] | [
"tests/clientlib/validate_config_test.py::test_run[input2-1]",
"tests/clientlib/validate_config_test.py::test_run[input3-1]",
"tests/clientlib/validate_config_test.py::test_run[input4-1]",
"tests/clientlib/validate_config_test.py::test_is_valid_according_to_schema[config_obj0-False]",
"tests/clientlib/validate_config_test.py::test_is_valid_according_to_schema[config_obj1-True]",
"tests/clientlib/validate_config_test.py::test_is_valid_according_to_schema[config_obj2-True]",
"tests/clientlib/validate_config_test.py::test_is_valid_according_to_schema[config_obj3-False]",
"tests/clientlib/validate_config_test.py::test_config_with_failing_regexes_fails",
"tests/clientlib/validate_config_test.py::test_config_with_ok_regexes_passes",
"tests/clientlib/validate_config_test.py::test_config_with_invalid_exclude_regex_fails",
"tests/clientlib/validate_config_test.py::test_config_with_ok_exclude_regex_passes",
"tests/clientlib/validate_config_test.py::test_config_with_local_hooks_definition_fails[config_obj0]",
"tests/clientlib/validate_config_test.py::test_config_with_local_hooks_definition_passes[config_obj0]",
"tests/clientlib/validate_config_test.py::test_config_with_local_hooks_definition_passes[config_obj1]",
"tests/clientlib/validate_manifest_test.py::test_run[input2-1]",
"tests/clientlib/validate_manifest_test.py::test_run[input3-1]",
"tests/clientlib/validate_manifest_test.py::test_run[input4-1]",
"tests/clientlib/validate_manifest_test.py::test_additional_manifest_check_raises_for_bad_language",
"tests/clientlib/validate_manifest_test.py::test_additional_manifest_check_passing[obj0]",
"tests/clientlib/validate_manifest_test.py::test_additional_manifest_check_passing[obj1]",
"tests/clientlib/validate_manifest_test.py::test_additional_manifest_failing[obj0]",
"tests/clientlib/validate_manifest_test.py::test_additional_manifest_failing[obj1]",
"tests/clientlib/validate_manifest_test.py::test_additional_manifest_failing[obj2]",
"tests/clientlib/validate_manifest_test.py::test_additional_manifest_failing[obj3]",
"tests/clientlib/validate_manifest_test.py::test_additional_manifest_failing[obj4]",
"tests/clientlib/validate_manifest_test.py::test_is_valid_according_to_schema[manifest_obj0-False]",
"tests/clientlib/validate_manifest_test.py::test_is_valid_according_to_schema[manifest_obj1-True]",
"tests/clientlib/validate_manifest_test.py::test_is_valid_according_to_schema[manifest_obj2-True]"
] | [] | MIT License | 143 |
mne-tools__mne-python-2126 | edceb8f38349d6dc0cade1c9f8384cc0707ce3e8 | 2015-05-20 03:39:59 | edceb8f38349d6dc0cade1c9f8384cc0707ce3e8 | diff --git a/.gitignore b/.gitignore
old mode 100644
new mode 100755
index a32ce2aea..cdad72a3d
--- a/.gitignore
+++ b/.gitignore
@@ -1,6 +1,5 @@
*.pyc
*.pyo
-*.sh
*.so
*.fif
*.tar.gz
diff --git a/Makefile b/Makefile
index 7b7102444..484275006 100755
--- a/Makefile
+++ b/Makefile
@@ -108,10 +108,3 @@ manpages:
>| ../build/manpages/$$f.1; \
done
-build-doc-dev:
- cd doc; make clean
- cd doc; DISPLAY=:1.0 xvfb-run -n 1 -s "-screen 0 1280x1024x24 -noreset -ac +extension GLX +render" make html_dev
-
-build-doc-stable:
- cd doc; make clean
- cd doc; DISPLAY=:1.0 xvfb-run -n 1 -s "-screen 0 1280x1024x24 -noreset -ac +extension GLX +render" make html
diff --git a/doc/source/_static/navy.css b/doc/source/_static/navy.css
index c8419184a..04912f9ad 100755
--- a/doc/source/_static/navy.css
+++ b/doc/source/_static/navy.css
@@ -4,7 +4,7 @@
*/
body {
- font-family: 'Open Sans', 'Lucida Grande', 'Lucida Sans Unicode', 'Geneva', 'Verdana', sans-serif;
+ font-family: 'Lucida Grande', 'Lucida Sans Unicode', 'Geneva', 'Verdana', sans-serif;
font-size: 14px;
letter-spacing: -0.01em;
line-height: 150%;
diff --git a/doc/source/_templates/layout.html b/doc/source/_templates/layout.html
index 7178e1f11..c71a45092 100755
--- a/doc/source/_templates/layout.html
+++ b/doc/source/_templates/layout.html
@@ -1,9 +1,6 @@
{% extends "!layout.html" %}
{% block extrahead %}
-
-<link href='http://fonts.googleapis.com/css?family=Open+Sans:400italic,700italic,400,700' rel='stylesheet' type='text/css'>
-
{% if use_google_analytics|tobool %}
<script type="text/javascript">
var _gaq = _gaq || [];
diff --git a/examples/README.txt b/examples/README.txt
index 75dff2db0..aebe56991 100644
--- a/examples/README.txt
+++ b/examples/README.txt
@@ -1,4 +1,6 @@
-Introductory examples
----------------------
-Introductory examples to MNE.
+General examples
+-------------------
+
+General-purpose and introductory examples to MNE.
+
diff --git a/examples/connectivity/plot_mne_inverse_coherence_epochs.py b/examples/connectivity/plot_mne_inverse_coherence_epochs.py
index d09357237..c8c973e7b 100644
--- a/examples/connectivity/plot_mne_inverse_coherence_epochs.py
+++ b/examples/connectivity/plot_mne_inverse_coherence_epochs.py
@@ -5,7 +5,7 @@ Compute coherence in source space using a MNE inverse solution
This examples computes the coherence between a seed in the left
auditory cortex and the rest of the brain based on single-trial
-MNE-dSPM inverse solutions.
+MNE-dSPM inverse soltions.
"""
# Author: Martin Luessi <[email protected]>
diff --git a/examples/forward/README.txt b/examples/forward/README.txt
deleted file mode 100644
index 89db5587d..000000000
--- a/examples/forward/README.txt
+++ /dev/null
@@ -1,6 +0,0 @@
-
-Forward modeling
-----------------
-
-From BEM segmentation, coregistration, setting up source spaces
-to actual computation of forward solution.
diff --git a/examples/plot_compute_mne_inverse.py b/examples/inverse/plot_compute_mne_inverse.py
similarity index 100%
rename from examples/plot_compute_mne_inverse.py
rename to examples/inverse/plot_compute_mne_inverse.py
diff --git a/examples/io/README.txt b/examples/io/README.txt
deleted file mode 100644
index 45f88d173..000000000
--- a/examples/io/README.txt
+++ /dev/null
@@ -1,5 +0,0 @@
-
-Input/Ouput
------------
-
-Reading and writing files.
diff --git a/examples/forward/plot_bem_contour_mri.py b/examples/plot_bem_contour_mri.py
similarity index 100%
rename from examples/forward/plot_bem_contour_mri.py
rename to examples/plot_bem_contour_mri.py
diff --git a/examples/visualization/plot_channel_epochs_image.py b/examples/plot_channel_epochs_image.py
similarity index 100%
rename from examples/visualization/plot_channel_epochs_image.py
rename to examples/plot_channel_epochs_image.py
diff --git a/examples/visualization/plot_clickable_image.py b/examples/plot_clickable_image.py
similarity index 100%
rename from examples/visualization/plot_clickable_image.py
rename to examples/plot_clickable_image.py
diff --git a/examples/forward/plot_coregistration_transform.py b/examples/plot_coregistration_transform.py
similarity index 100%
rename from examples/forward/plot_coregistration_transform.py
rename to examples/plot_coregistration_transform.py
diff --git a/examples/forward/plot_decimate_head_surface.py b/examples/plot_decimate_head_surface.py
similarity index 100%
rename from examples/forward/plot_decimate_head_surface.py
rename to examples/plot_decimate_head_surface.py
diff --git a/examples/preprocessing/plot_define_target_events.py b/examples/plot_define_target_events.py
similarity index 100%
rename from examples/preprocessing/plot_define_target_events.py
rename to examples/plot_define_target_events.py
diff --git a/examples/io/plot_epochs_to_data_frame.py b/examples/plot_epochs_to_data_frame.py
similarity index 100%
rename from examples/io/plot_epochs_to_data_frame.py
rename to examples/plot_epochs_to_data_frame.py
diff --git a/examples/preprocessing/plot_estimate_covariance_matrix_baseline.py b/examples/plot_estimate_covariance_matrix_baseline.py
similarity index 100%
rename from examples/preprocessing/plot_estimate_covariance_matrix_baseline.py
rename to examples/plot_estimate_covariance_matrix_baseline.py
diff --git a/examples/preprocessing/plot_estimate_covariance_matrix_raw.py b/examples/plot_estimate_covariance_matrix_raw.py
similarity index 100%
rename from examples/preprocessing/plot_estimate_covariance_matrix_raw.py
rename to examples/plot_estimate_covariance_matrix_raw.py
diff --git a/examples/visualization/plot_evoked_delayed_ssp.py b/examples/plot_evoked_delayed_ssp.py
similarity index 100%
rename from examples/visualization/plot_evoked_delayed_ssp.py
rename to examples/plot_evoked_delayed_ssp.py
diff --git a/examples/visualization/plot_evoked_topomap.py b/examples/plot_evoked_topomap.py
similarity index 100%
rename from examples/visualization/plot_evoked_topomap.py
rename to examples/plot_evoked_topomap.py
diff --git a/examples/visualization/plot_evoked_topomap_delayed_ssp.py b/examples/plot_evoked_topomap_delayed_ssp.py
similarity index 100%
rename from examples/visualization/plot_evoked_topomap_delayed_ssp.py
rename to examples/plot_evoked_topomap_delayed_ssp.py
diff --git a/examples/visualization/plot_evoked_whitening.py b/examples/plot_evoked_whitening.py
similarity index 100%
rename from examples/visualization/plot_evoked_whitening.py
rename to examples/plot_evoked_whitening.py
diff --git a/examples/plot_extract_events_from_raw.py b/examples/plot_extract_events_from_raw.py
index 4d52daf6b..4d8c1a283 100644
--- a/examples/plot_extract_events_from_raw.py
+++ b/examples/plot_extract_events_from_raw.py
@@ -25,7 +25,7 @@ raw = Raw(fname)
events = mne.find_events(raw, stim_channel='STI 014')
# Writing events
-mne.write_events('sample_audvis_raw-eve.fif', events)
+mne.write_events('events.fif', events)
for ind, before, after in events[:5]:
print("At sample %d stim channel went from %d to %d"
diff --git a/examples/plot_from_raw_to_epochs_to_evoked.py b/examples/plot_from_raw_to_epochs_to_evoked.py
index d36bff025..c2934c685 100644
--- a/examples/plot_from_raw_to_epochs_to_evoked.py
+++ b/examples/plot_from_raw_to_epochs_to_evoked.py
@@ -16,6 +16,7 @@ data and then saved to disk.
import mne
from mne import io
from mne.datasets import sample
+import matplotlib.pyplot as plt
print(__doc__)
@@ -25,17 +26,14 @@ data_path = sample.data_path()
# Set parameters
raw_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw.fif'
event_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw-eve.fif'
-tmin, tmax = -0.2, 0.5
-
-# Select events to extract epochs from.
-event_id = {'Auditory/Left': 1, 'Auditory/Right': 2}
+event_id, tmin, tmax = 1, -0.2, 0.5
# Setup for reading the raw data
raw = io.Raw(raw_fname)
events = mne.read_events(event_fname)
# Plot raw data
-fig = raw.plot(events=events, event_color={1: 'cyan', -1: 'lightgray'})
+fig = raw.plot(events=events, event_color={event_id: 'cyan', -1: 'lightgray'})
# Set up pick list: EEG + STI 014 - bad channels (modify to your needs)
include = [] # or stim channels ['STI 014']
@@ -56,21 +54,26 @@ epochs.plot()
epochs.drop_bad_epochs()
epochs.plot_drop_log(subject='sample')
-# Average epochs and get evoked data corresponding to the left stimulation
-evoked = epochs['Left'].average()
+evoked = epochs.average() # average epochs and get an Evoked dataset.
evoked.save('sample_audvis_eeg-ave.fif') # save evoked data to disk
###############################################################################
# View evoked response
+times = 1e3 * epochs.times # time in miliseconds
+
+ch_max_name, latency = evoked.get_peak(mode='neg')
evoked.plot()
-###############################################################################
-# Save evoked responses for different conditions to disk
+plt.xlim([times[0], times[-1]])
+plt.xlabel('time (ms)')
+plt.ylabel('Potential (uV)')
+plt.title('EEG evoked potential')
-# average epochs and get Evoked datasets
-evokeds = [epochs[cond].average() for cond in ['Left', 'Right']]
+plt.axvline(latency * 1e3, color='red',
+ label=ch_max_name, linewidth=2,
+ linestyle='--')
+plt.legend(loc='best')
-# save evoked data to disk
-mne.write_evokeds('sample_auditory_and_visual_eeg-ave.fif', evokeds)
+plt.show()
diff --git a/examples/plot_from_raw_to_multiple_epochs_to_evoked.py b/examples/plot_from_raw_to_multiple_epochs_to_evoked.py
new file mode 100644
index 000000000..410239032
--- /dev/null
+++ b/examples/plot_from_raw_to_multiple_epochs_to_evoked.py
@@ -0,0 +1,72 @@
+"""
+====================================================================
+Extract epochs for multiple conditions, save evoked response to disk
+====================================================================
+
+This script shows how to read the epochs for multiple conditions from
+a raw file given a list of events. The epochs are averaged to produce
+evoked data and then saved to disk.
+
+"""
+# Authors: Alexandre Gramfort <[email protected]>
+# Eric Larson <[email protected]>
+# Denis Engemann <[email protected]>
+#
+# License: BSD (3-clause)
+
+import mne
+from mne import io
+from mne.datasets import sample
+from mne.epochs import combine_event_ids
+import matplotlib.pyplot as plt
+
+print(__doc__)
+
+data_path = sample.data_path()
+
+###############################################################################
+# Set parameters
+raw_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw.fif'
+event_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw-eve.fif'
+event_ids = {'AudL': 1, 'AudR': 2, 'VisL': 3, 'VisR': 4}
+tmin = -0.2
+tmax = 0.5
+
+# Setup for reading the raw data
+raw = io.Raw(raw_fname)
+events = mne.read_events(event_fname)
+
+# Set up pick list: EEG + STI 014 - bad channels (modify to your needs)
+include = [] # or stim channels ['STI 014']
+raw.info['bads'] += ['EEG 053'] # bads + 1 more
+
+# pick EEG channels
+picks = mne.pick_types(raw.info, meg=False, eeg=True, stim=False, eog=True,
+ include=include, exclude='bads')
+# Read epochs
+epochs = mne.Epochs(raw, events, event_ids, tmin, tmax, picks=picks,
+ baseline=(None, 0), reject=dict(eeg=80e-6, eog=150e-6))
+# Let's equalize the trial counts in each condition
+epochs.equalize_event_counts(['AudL', 'AudR', 'VisL', 'VisR'], copy=False)
+# Now let's combine some conditions
+combine_event_ids(epochs, ['AudL', 'AudR'], {'Auditory': 12}, copy=False)
+combine_event_ids(epochs, ['VisL', 'VisR'], {'Visual': 34}, copy=False)
+
+# average epochs and get Evoked datasets
+evokeds = [epochs[cond].average() for cond in ['Auditory', 'Visual']]
+
+# save evoked data to disk
+mne.write_evokeds('sample_auditory_and_visual_eeg-ave.fif', evokeds)
+
+###############################################################################
+# View evoked response
+plt.clf()
+ax = plt.subplot(2, 1, 1)
+evokeds[0].plot(axes=ax)
+plt.title('EEG evoked potential, auditory trials')
+plt.ylabel('Potential (uV)')
+ax = plt.subplot(2, 1, 2)
+evokeds[1].plot(axes=ax)
+plt.title('EEG evoked potential, visual trials')
+plt.ylabel('Potential (uV)')
+plt.show()
diff --git a/examples/preprocessing/plot_interpolate_bad_channels.py b/examples/plot_interpolate_bad_channels.py
similarity index 100%
rename from examples/preprocessing/plot_interpolate_bad_channels.py
rename to examples/plot_interpolate_bad_channels.py
diff --git a/examples/forward/plot_left_cerebellum_volume_source.py b/examples/plot_left_cerebellum_volume_source.py
similarity index 100%
rename from examples/forward/plot_left_cerebellum_volume_source.py
rename to examples/plot_left_cerebellum_volume_source.py
diff --git a/examples/forward/plot_make_forward.py b/examples/plot_make_forward.py
similarity index 100%
rename from examples/forward/plot_make_forward.py
rename to examples/plot_make_forward.py
diff --git a/examples/visualization/plot_meg_eeg_fields_3d.py b/examples/plot_meg_eeg_fields_3d.py
similarity index 100%
rename from examples/visualization/plot_meg_eeg_fields_3d.py
rename to examples/plot_meg_eeg_fields_3d.py
diff --git a/examples/io/plot_objects_from_arrays.py b/examples/plot_objects_from_arrays.py
similarity index 100%
rename from examples/io/plot_objects_from_arrays.py
rename to examples/plot_objects_from_arrays.py
diff --git a/examples/io/plot_read_and_write_raw_data.py b/examples/plot_read_and_write_raw_data.py
similarity index 100%
rename from examples/io/plot_read_and_write_raw_data.py
rename to examples/plot_read_and_write_raw_data.py
diff --git a/examples/forward/plot_read_bem_surfaces.py b/examples/plot_read_bem_surfaces.py
similarity index 100%
rename from examples/forward/plot_read_bem_surfaces.py
rename to examples/plot_read_bem_surfaces.py
diff --git a/examples/io/plot_read_epochs.py b/examples/plot_read_epochs.py
similarity index 100%
rename from examples/io/plot_read_epochs.py
rename to examples/plot_read_epochs.py
diff --git a/examples/io/plot_read_evoked.py b/examples/plot_read_evoked.py
similarity index 100%
rename from examples/io/plot_read_evoked.py
rename to examples/plot_read_evoked.py
diff --git a/examples/forward/plot_read_forward.py b/examples/plot_read_forward.py
similarity index 100%
rename from examples/forward/plot_read_forward.py
rename to examples/plot_read_forward.py
diff --git a/examples/io/plot_read_noise_covariance_matrix.py b/examples/plot_read_noise_covariance_matrix.py
similarity index 100%
rename from examples/io/plot_read_noise_covariance_matrix.py
rename to examples/plot_read_noise_covariance_matrix.py
diff --git a/examples/preprocessing/plot_rereference_eeg.py b/examples/plot_rereference_eeg.py
similarity index 100%
rename from examples/preprocessing/plot_rereference_eeg.py
rename to examples/plot_rereference_eeg.py
diff --git a/examples/preprocessing/plot_shift_evoked.py b/examples/plot_shift_evoked.py
similarity index 100%
rename from examples/preprocessing/plot_shift_evoked.py
rename to examples/plot_shift_evoked.py
diff --git a/examples/simulation/plot_simulate_evoked_data.py b/examples/plot_simulate_evoked_data.py
similarity index 100%
rename from examples/simulation/plot_simulate_evoked_data.py
rename to examples/plot_simulate_evoked_data.py
diff --git a/examples/visualization/plot_ssp_projs_sensitivity_map.py b/examples/plot_ssp_projs_sensitivity_map.py
similarity index 100%
rename from examples/visualization/plot_ssp_projs_sensitivity_map.py
rename to examples/plot_ssp_projs_sensitivity_map.py
diff --git a/examples/visualization/plot_ssp_projs_topomaps.py b/examples/plot_ssp_projs_topomaps.py
similarity index 100%
rename from examples/visualization/plot_ssp_projs_topomaps.py
rename to examples/plot_ssp_projs_topomaps.py
diff --git a/examples/visualization/plot_topo_channel_epochs_image.py b/examples/plot_topo_channel_epochs_image.py
similarity index 100%
rename from examples/visualization/plot_topo_channel_epochs_image.py
rename to examples/plot_topo_channel_epochs_image.py
diff --git a/examples/visualization/plot_topo_compare_conditions.py b/examples/plot_topo_compare_conditions.py
similarity index 100%
rename from examples/visualization/plot_topo_compare_conditions.py
rename to examples/plot_topo_compare_conditions.py
diff --git a/examples/visualization/plot_topo_customized.py b/examples/plot_topo_customized.py
similarity index 100%
rename from examples/visualization/plot_topo_customized.py
rename to examples/plot_topo_customized.py
diff --git a/examples/visualization/plot_topography.py b/examples/plot_topography.py
similarity index 100%
rename from examples/visualization/plot_topography.py
rename to examples/plot_topography.py
diff --git a/examples/preprocessing/plot_virtual_evoked.py b/examples/plot_virtual_evoked.py
similarity index 100%
rename from examples/preprocessing/plot_virtual_evoked.py
rename to examples/plot_virtual_evoked.py
diff --git a/examples/io/read_events.py b/examples/read_events.py
similarity index 100%
rename from examples/io/read_events.py
rename to examples/read_events.py
diff --git a/examples/simulation/README.txt b/examples/simulation/README.txt
deleted file mode 100644
index bec6bcce3..000000000
--- a/examples/simulation/README.txt
+++ /dev/null
@@ -1,5 +0,0 @@
-
-Data Simulation
----------------
-
-Tools to generate simulation data.
diff --git a/examples/visualization/README.txt b/examples/visualization/README.txt
deleted file mode 100644
index 25af47af5..000000000
--- a/examples/visualization/README.txt
+++ /dev/null
@@ -1,5 +0,0 @@
-
-Visualization
--------------
-
-Looking at data and processing output.
diff --git a/examples/visualization/plot_evoked_erf_erp.py b/examples/visualization/plot_evoked_erf_erp.py
deleted file mode 100644
index db9f68b01..000000000
--- a/examples/visualization/plot_evoked_erf_erp.py
+++ /dev/null
@@ -1,48 +0,0 @@
-"""
-=================================
-Plotting ERF/ERP with evoked data
-=================================
-
-Load evoked data and plot.
-
-"""
-# Authors: Alexandre Gramfort <[email protected]>
-#
-# License: BSD (3-clause)
-
-import matplotlib.pyplot as plt
-from mne.datasets import sample
-from mne import read_evokeds
-
-print(__doc__)
-
-path = sample.data_path()
-fname = path + '/MEG/sample/sample_audvis-ave.fif'
-
-# load evoked and subtract baseline
-condition = 'Left Auditory'
-evoked = read_evokeds(fname, condition=condition, baseline=(None, 0))
-
-evoked.plot()
-
-###############################################################################
-# Or plot manually after extracting peak latency
-
-evoked = evoked.pick_types(meg=False, eeg=True)
-times = 1e3 * evoked.times # time in miliseconds
-
-ch_max_name, latency = evoked.get_peak(mode='neg')
-
-plt.figure()
-plt.plot(times, 1e6 * evoked.data.T, 'k-')
-plt.xlim([times[0], times[-1]])
-plt.xlabel('time (ms)')
-plt.ylabel('Potential (uV)')
-plt.title('EEG evoked potential')
-
-plt.axvline(latency * 1e3, color='red',
- label=ch_max_name, linewidth=2,
- linestyle='--')
-plt.legend(loc='best')
-
-plt.show()
diff --git a/mne/connectivity/spectral.py b/mne/connectivity/spectral.py
index a1bc27bce..5c0c7cbd5 100644
--- a/mne/connectivity/spectral.py
+++ b/mne/connectivity/spectral.py
@@ -539,8 +539,8 @@ def spectral_connectivity(data, method='coh', indices=None, sfreq=2 * np.pi,
to compute the connectivity between the signal with index 0 and signals
"2, 3, 4" (a total of 3 connections) one can use the following::
- indices = (np.array([0, 0, 0]), # row indices
- np.array([2, 3, 4])) # col indices
+ indices = (np.array([0, 0, 0], # row indices
+ np.array([2, 3, 4]))) # col indices
con_flat = spectral_connectivity(data, method='coh',
indices=indices, ...)
diff --git a/mne/datasets/utils.py b/mne/datasets/utils.py
index e7745e3e7..be6f5fb0d 100644
--- a/mne/datasets/utils.py
+++ b/mne/datasets/utils.py
@@ -120,7 +120,7 @@ def _data_path(path=None, force_update=False, update_path=True, download=True,
archive_name = "MNE-sample-data-processed.tar.gz"
folder_name = "MNE-sample-data"
url = "ftp://surfer.nmr.mgh.harvard.edu/pub/data/MNE/" + archive_name
- hash_ = 'f73186795af820428e5e8e779ce5bfcf'
+ hash_ = '1bb9f993bfba2057e0039c306a717109'
elif name == 'spm':
archive_name = 'MNE-spm-face.tar.bz2'
folder_name = "MNE-spm-face"
diff --git a/mne/decoding/time_gen.py b/mne/decoding/time_gen.py
index 9332ae63a..c6598c8b6 100644
--- a/mne/decoding/time_gen.py
+++ b/mne/decoding/time_gen.py
@@ -119,12 +119,8 @@ class GeneralizationAcrossTime(object):
The categories used for training.
estimators_ : list of list of sklearn.base.BaseEstimator subclasses.
The estimators for each time point and each fold.
- y_pred_ : list of lists of arrays of floats,
- shape (n_train_times, n_test_times, n_epochs, n_prediction_dims)
- The single-trial predictions estimated by self.predict() at each
- training time and each testing time. Note that the number of testing
- times per training time need not be regular, else
- np.shape(y_pred_) = [n_train_time, n_test_time, n_epochs].
+ y_pred_ : np.ndarray, shape (n_train_times, n_test_times, n_epochs, n_prediction_dims)
+ Class labels for samples in X.
scores_ : list of lists of float
The scores estimated by self.scorer_ at each training time and each
testing time (e.g. mean accuracy of self.predict(X)). Note that the
@@ -307,12 +303,9 @@ class GeneralizationAcrossTime(object):
Returns
-------
- y_pred : list of lists of arrays of floats,
- shape (n_train_t, n_test_t, n_epochs, n_prediction_dims)
- The single-trial predictions at each training time and each testing
- time. Note that the number of testing times per training time need
- not be regular;
- else, np.shape(y_pred_) = [n_train_time, n_test_time, n_epochs].
+ y_pred_ : np.ndarray, shape (n_train_time, n_test_time, n_epochs,
+ n_prediction_dim)
+ Class labels for samples in X.
"""
# clean in case gat.predict() is called at unexpected moments
@@ -365,10 +358,12 @@ class GeneralizationAcrossTime(object):
parallel, p_time_gen, _ = parallel_func(_predict_time_loop, n_jobs)
# Loop across estimators (i.e. training times)
- self.y_pred_ = parallel(p_time_gen(X, self.estimators_[t_train], cv,
- slices, self.predict_mode)
- for t_train, slices in
- enumerate(test_times_['slices']))
+ packed = parallel(p_time_gen(X, self.estimators_[t_train], cv,
+ slices, self.predict_mode)
+ for t_train, slices in
+ enumerate(test_times_['slices']))
+
+ self.y_pred_ = np.transpose(tuple(zip(*packed)), (1, 0, 2, 3))
return self.y_pred_
def score(self, epochs=None, y=None, scorer=None, test_times=None):
@@ -463,7 +458,7 @@ class GeneralizationAcrossTime(object):
self.y_true_ = y # true regressor to be compared with y_pred
# Preprocessing for parallelization:
- n_jobs = min(len(self.y_pred_[0][0]), check_n_jobs(self.n_jobs))
+ n_jobs = min(self.y_pred_.shape[2], check_n_jobs(self.n_jobs))
parallel, p_time_gen, n_jobs = parallel_func(_score_loop, n_jobs)
# Score each training and testing time point
diff --git a/mne/forward/forward.py b/mne/forward/forward.py
index c41a70fce..abacd7091 100644
--- a/mne/forward/forward.py
+++ b/mne/forward/forward.py
@@ -1226,6 +1226,7 @@ def apply_forward_raw(fwd, stc, raw_template, start=None, stop=None,
raw.info = _fill_measurement_info(raw.info, fwd, sfreq)
raw.info['projs'] = []
raw._projector = None
+ raw._update_times()
return raw
diff --git a/mne/io/base.py b/mne/io/base.py
index 578109de7..a2ab5b8b1 100644
--- a/mne/io/base.py
+++ b/mne/io/base.py
@@ -233,7 +233,7 @@ class _BaseRaw(ProjMixin, ContainsMixin, PickDropChannelsMixin,
'not %s' % preload.dtype)
self._data = preload
self.preload = True
- self._last_samps = np.array([self._data.shape[1] - 1])
+ last_samps = [self._data.shape[1] - 1]
load_from_disk = False
else:
if last_samps is None:
@@ -246,7 +246,8 @@ class _BaseRaw(ProjMixin, ContainsMixin, PickDropChannelsMixin,
raise ValueError('bad preload: %s' % preload)
else:
load_from_disk = True
- self._last_samps = np.array(last_samps)
+ self._last_samps = np.array(last_samps)
+ self._first_samps = np.array(first_samps)
self.info = info
cals = np.empty(info['nchan'])
for k in range(info['nchan']):
@@ -257,13 +258,13 @@ class _BaseRaw(ProjMixin, ContainsMixin, PickDropChannelsMixin,
self.comp = comp
self._orig_comp_grade = orig_comp_grade
self._filenames = list(filenames)
- self._first_samps = np.array(first_samps)
self.orig_format = orig_format
self._projectors = list()
self._projector = None
# If we have True or a string, actually do the preloading
if load_from_disk:
self._preload_data(preload)
+ self._update_times()
def _read_segment(start, stop, sel, data_buffer, projector, verbose):
"""Read a chunk of raw data
@@ -321,6 +322,12 @@ class _BaseRaw(ProjMixin, ContainsMixin, PickDropChannelsMixin,
self.preload = True
self.close()
+ def _update_times(self):
+ """Helper to update times"""
+ self._times = np.arange(self.n_times) / float(self.info['sfreq'])
+ # make it immutable
+ self._times.flags.writeable = False
+
@property
def first_samp(self):
return self._first_samps[0]
@@ -868,6 +875,7 @@ class _BaseRaw(ProjMixin, ContainsMixin, PickDropChannelsMixin,
# adjust affected variables
self._data = np.concatenate(new_data, axis=1)
self.info['sfreq'] = sfreq
+ self._update_times()
def crop(self, tmin=0.0, tmax=None, copy=True):
"""Crop raw data file.
@@ -922,6 +930,7 @@ class _BaseRaw(ProjMixin, ContainsMixin, PickDropChannelsMixin,
if raw.preload:
# slice and copy to avoid the reference to large array
raw._data = raw._data[:, smin:smax + 1].copy()
+ raw._update_times()
return raw
@verbose
@@ -1355,7 +1364,7 @@ class _BaseRaw(ProjMixin, ContainsMixin, PickDropChannelsMixin,
@property
def times(self):
"""Time points"""
- return np.arange(self.n_times) / float(self.info['sfreq'])
+ return self._times
@property
def n_times(self):
@@ -1477,6 +1486,7 @@ class _BaseRaw(ProjMixin, ContainsMixin, PickDropChannelsMixin,
self._last_samps = np.r_[self._last_samps, r._last_samps]
self._rawdirs += r._rawdirs
self._filenames += r._filenames
+ self._update_times()
def close(self):
"""Clean up the object.
diff --git a/mne/io/kit/kit.py b/mne/io/kit/kit.py
index 447715681..8de71ac9a 100644
--- a/mne/io/kit/kit.py
+++ b/mne/io/kit/kit.py
@@ -114,8 +114,7 @@ class RawKIT(_BaseRaw):
def __repr__(self):
s = ('%r' % op.basename(self._kit_info['fname']),
"n_channels x n_times : %s x %s" % (len(self.info['ch_names']),
- self.last_samp + 1 -
- self.first_samp))
+ self._kit_info['n_samples']))
return "<RawKIT | %s>" % ', '.join(s)
def read_stim_ch(self, buffer_size=1e5):
@@ -495,7 +494,7 @@ def _set_dig_kit(mrk, elp, hsp, auto_decimate=True):
hsp = _read_dig_points(hsp)
n_pts = len(hsp)
if n_pts > KIT.DIG_POINTS:
- hsp = _decimate_points(hsp, res=5)
+ hsp = _decimate_points(hsp, decim=5)
n_new = len(hsp)
msg = ("The selected head shape contained {n_in} points, which is "
"more than recommended ({n_rec}), and was automatically "
@@ -550,8 +549,6 @@ def get_kit_info(rawfile):
Returns
-------
- info : instance of Info
- An Info for the instance.
sqd : dict
A dict containing all the sqd parameter settings.
"""
@@ -679,7 +676,7 @@ def get_kit_info(rawfile):
info['sfreq'] = float(sqd['sfreq'])
info['bads'] = []
info['acq_pars'], info['acq_stim'] = None, None
- info['filename'] = rawfile
+ info['filename'] = None
info['ctf_head_t'] = None
info['dev_ctf_t'] = []
info['nchan'] = sqd['nchan']
diff --git a/mne/preprocessing/ica.py b/mne/preprocessing/ica.py
index c7ba1ef94..1db0a2678 100644
--- a/mne/preprocessing/ica.py
+++ b/mne/preprocessing/ica.py
@@ -666,6 +666,7 @@ class ICA(ContainsMixin):
out._projector = None
self._export_info(out.info, raw, add_channels)
+ out._update_times()
return out
| Epoch-ing too slow when #events is large..
So I have several ABR dataset where I have about 8000 trials. Epoching is way too slow and I suspect that the issue is related to not pre-allocating memory in ```_get_data_from_disk``` and growing the ```_data``` array one epoch at a time. When I don't do ```preload=True```, when I eventually have to average, ```epochs.average()``` is too slow.
Am I missing something or is there room to speed things up? | mne-tools/mne-python | diff --git a/mne/decoding/tests/test_time_gen.py b/mne/decoding/tests/test_time_gen.py
index c1a2328a5..16ef8c904 100644
--- a/mne/decoding/tests/test_time_gen.py
+++ b/mne/decoding/tests/test_time_gen.py
@@ -124,7 +124,7 @@ def test_generalization_across_time():
# --- number of trials
assert_true(gat.y_train_.shape[0] ==
gat.y_true_.shape[0] ==
- len(gat.y_pred_[0][0]) == 14)
+ gat.y_pred_.shape[2] == 14)
# --- number of folds
assert_true(np.shape(gat.estimators_)[1] == gat.cv)
# --- length training size
diff --git a/mne/realtime/tests/test_mockclient.py b/mne/realtime/tests/test_mockclient.py
index 631ca003e..a16217f45 100644
--- a/mne/realtime/tests/test_mockclient.py
+++ b/mne/realtime/tests/test_mockclient.py
@@ -86,6 +86,7 @@ def test_find_events():
raw._data[stim_channel_idx, 520:530] = 6
raw._data[stim_channel_idx, 530:532] = 5
raw._data[stim_channel_idx, 540] = 6
+ raw._update_times()
# consecutive=False
find_events = dict(consecutive=False)
diff --git a/mne/tests/test_event.py b/mne/tests/test_event.py
index 2cde41291..8bffa5e7a 100644
--- a/mne/tests/test_event.py
+++ b/mne/tests/test_event.py
@@ -150,6 +150,7 @@ def test_find_events():
# Reset some data for ease of comparison
raw._first_samps[0] = 0
raw.info['sfreq'] = 1000
+ raw._update_times()
stim_channel = 'STI 014'
stim_channel_idx = pick_channels(raw.info['ch_names'],
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_added_files",
"has_removed_files",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 1,
"issue_text_score": 2,
"test_score": 3
},
"num_modified_files": 15
} | 0.8 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[dev]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"numpy>=1.16.0",
"pandas>=1.0.0",
"scikit-learn",
"h5py",
"pysurfer",
"nose",
"nose-timer",
"pytest"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.7",
"reqs_path": [
"requirements/base.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | apptools==5.2.1
certifi @ file:///croot/certifi_1671487769961/work/certifi
configobj==5.0.9
cycler==0.11.0
envisage==7.0.3
exceptiongroup==1.2.2
fonttools==4.38.0
h5py==3.8.0
importlib-metadata==6.7.0
importlib-resources==5.12.0
iniconfig==2.0.0
joblib==1.3.2
kiwisolver==1.4.5
matplotlib==3.5.3
mayavi==4.8.1
-e git+https://github.com/mne-tools/mne-python.git@edceb8f38349d6dc0cade1c9f8384cc0707ce3e8#egg=mne
nibabel==4.0.2
nose==1.3.7
nose-timer==1.0.1
numpy==1.21.6
packaging==24.0
pandas==1.3.5
Pillow==9.5.0
pluggy==1.2.0
pyface==8.0.0
Pygments==2.17.2
pyparsing==3.1.4
pysurfer==0.11.2
pytest==7.4.4
python-dateutil==2.9.0.post0
pytz==2025.2
scikit-learn==1.0.2
scipy==1.7.3
six==1.17.0
threadpoolctl==3.1.0
tomli==2.0.1
traits==6.4.3
traitsui==8.0.0
typing_extensions==4.7.1
vtk==9.3.1
zipp==3.15.0
| name: mne-python
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2022.12.7=py37h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- pip=22.3.1=py37h06a4308_0
- python=3.7.16=h7a1cb2a_0
- readline=8.2=h5eee18b_0
- setuptools=65.6.3=py37h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- wheel=0.38.4=py37h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- apptools==5.2.1
- configobj==5.0.9
- cycler==0.11.0
- envisage==7.0.3
- exceptiongroup==1.2.2
- fonttools==4.38.0
- h5py==3.8.0
- importlib-metadata==6.7.0
- importlib-resources==5.12.0
- iniconfig==2.0.0
- joblib==1.3.2
- kiwisolver==1.4.5
- matplotlib==3.5.3
- mayavi==4.8.1
- nibabel==4.0.2
- nose==1.3.7
- nose-timer==1.0.1
- numpy==1.21.6
- packaging==24.0
- pandas==1.3.5
- pillow==9.5.0
- pluggy==1.2.0
- pyface==8.0.0
- pygments==2.17.2
- pyparsing==3.1.4
- pysurfer==0.11.2
- pytest==7.4.4
- python-dateutil==2.9.0.post0
- pytz==2025.2
- scikit-learn==1.0.2
- scipy==1.7.3
- six==1.17.0
- threadpoolctl==3.1.0
- tomli==2.0.1
- traits==6.4.3
- traitsui==8.0.0
- typing-extensions==4.7.1
- vtk==9.3.1
- zipp==3.15.0
prefix: /opt/conda/envs/mne-python
| [
"mne/tests/test_event.py::test_find_events"
] | [
"mne/decoding/tests/test_time_gen.py::test_time_generalization",
"mne/decoding/tests/test_time_gen.py::test_generalization_across_time",
"mne/realtime/tests/test_mockclient.py::test_find_events",
"mne/tests/test_event.py::test_io_events"
] | [
"mne/realtime/tests/test_mockclient.py::test_mockclient",
"mne/realtime/tests/test_mockclient.py::test_get_event_data",
"mne/tests/test_event.py::test_add_events",
"mne/tests/test_event.py::test_merge_events",
"mne/tests/test_event.py::test_pick_events",
"mne/tests/test_event.py::test_make_fixed_length_events",
"mne/tests/test_event.py::test_define_events"
] | [] | BSD 3-Clause "New" or "Revised" License | 144 |
|
web2py__pydal-195 | 0f4c0f8c47193c6f4957d61d781fafcd36782d3f | 2015-05-20 20:21:15 | 0f4c0f8c47193c6f4957d61d781fafcd36782d3f | diff --git a/CHANGES b/CHANGES
index d14a85c1..0bce22ec 100644
--- a/CHANGES
+++ b/CHANGES
@@ -13,7 +13,16 @@ Next
- Implemented JSON serialization for objects
- Refactored many internal objects to improve performance
- Added python 3.x support (experimental)
-
+- New (and, as such, experimental) unicode handling in MSSQL
+ Use mssql4n:// or mssqn3n:// uris. NB: These adapters will probably
+ become the de-facto standard for MSSQL handling.
+ Any other adapter will continue to be supported just for legacy
+ databases
+- Restricted table and field names to a "dotted-notation-friendly" syntax,
+ meaning basically anything:
+ - alphanumeric
+ - not starting with underscore or an integer
+ you need to use the "rname" attribute for anything funnier than that
Version 15.03
-------------
diff --git a/pydal/helpers/regex.py b/pydal/helpers/regex.py
index 1139aaa4..c79094b6 100644
--- a/pydal/helpers/regex.py
+++ b/pydal/helpers/regex.py
@@ -10,7 +10,7 @@ REGEX_NO_GREEDY_ENTITY_NAME = r'(.+?)'
REGEX_UPLOAD_PATTERN = re.compile('(?P<table>[\w\-]+)\.(?P<field>[\w\-]+)\.(?P<uuidkey>[\w\-]+)(\.(?P<name>\w+))?\.\w+$')
REGEX_CLEANUP_FN = re.compile('[\'"\s;]+')
REGEX_UNPACK = re.compile('(?<!\|)\|(?!\|)')
-REGEX_PYTHON_KEYWORDS = re.compile('^(and|del|from|not|while|as|elif|global|or|with|assert|else|if|pass|yield|break|except|import|print|class|exec|in|raise|continue|finally|is|return|def|for|lambda|try)$')
+REGEX_PYTHON_KEYWORDS = re.compile('^(and|del|from|not|while|as|elif|global|or|with|assert|else|if|pass|yield|break|except|import|print|class|exec|in|raise|continue|finally|is|return|def|for|lambda|try|False|True|nonlocal)$')
REGEX_SELECT_AS_PARSER = re.compile("\s+AS\s+(\S+)")
REGEX_CONST_STRING = re.compile('(\"[^\"]*?\")|(\'[^\']*?\')')
REGEX_SEARCH_PATTERN = re.compile('^{[^\.]+\.[^\.]+(\.(lt|gt|le|ge|eq|ne|contains|startswith|year|month|day|hour|minute|second))?(\.not)?}$')
@@ -20,3 +20,4 @@ REGEX_QUOTES = re.compile("'[^']*'")
REGEX_ALPHANUMERIC = re.compile('^[0-9a-zA-Z]\w*$')
REGEX_PASSWORD = re.compile('\://([^:@]*)\:')
REGEX_NOPASSWD = re.compile('\/\/[\w\.\-]+[\:\/](.+)(?=@)') # was '(?<=[\:\/])([^:@/]+)(?=@.+)'
+REGEX_VALID_TB_FLD = re.compile(r'^[^\d_][_0-9a-zA-Z]*\Z')
diff --git a/pydal/objects.py b/pydal/objects.py
index 7e5e18ca..28d20dde 100644
--- a/pydal/objects.py
+++ b/pydal/objects.py
@@ -19,7 +19,7 @@ from ._gae import Key
from .exceptions import NotFoundException, NotAuthorizedException
from .helpers.regex import REGEX_TABLE_DOT_FIELD, REGEX_ALPHANUMERIC, \
REGEX_PYTHON_KEYWORDS, REGEX_STORE_PATTERN, REGEX_UPLOAD_PATTERN, \
- REGEX_CLEANUP_FN
+ REGEX_CLEANUP_FN, REGEX_VALID_TB_FLD
from .helpers.classes import Reference, MethodAdder, SQLCallableList, SQLALL, \
Serializable, BasicStorage
from .helpers.methods import list_represent, bar_decode_integer, \
@@ -205,8 +205,8 @@ class Table(Serializable, BasicStorage):
self._actual = False # set to True by define_table()
self._db = db
self._tablename = tablename
- if (not isinstance(tablename, str) or tablename[0] == '_'
- or hasattr(DAL, tablename) or '.' in tablename
+ if (not isinstance(tablename, str) or hasattr(DAL, tablename)
+ or not REGEX_VALID_TB_FLD.match(tablename)
or REGEX_PYTHON_KEYWORDS.match(tablename)
):
raise SyntaxError('Field: invalid table name: %s, '
@@ -1396,9 +1396,10 @@ class Field(Expression, Serializable):
except UnicodeEncodeError:
raise SyntaxError('Field: invalid unicode field name')
self.name = fieldname = cleanup(fieldname)
- if not isinstance(fieldname, str) or hasattr(Table, fieldname) or \
- fieldname[0] == '_' or '.' in fieldname or \
- REGEX_PYTHON_KEYWORDS.match(fieldname):
+ if (not isinstance(fieldname, str) or hasattr(Table, fieldname)
+ or not REGEX_VALID_TB_FLD.match(fieldname)
+ or REGEX_PYTHON_KEYWORDS.match(fieldname)
+ ):
raise SyntaxError('Field: invalid field name: %s, '
'use rname for "funny" names' % fieldname)
| fix allowed table and field names
As discussed in web2py-developers (such as [here](https://groups.google.com/d/msg/web2py-developers/1r4bq-ZFFkY/fYNfGSjqKeUJ "discussion") ), we should avoid any table and field name that is not coherent with python identifiers. The cleanup() needs a revision and tests should be added to avoid regressions. We have rname for legacy and/or funny names. | web2py/pydal | diff --git a/tests/sql.py b/tests/sql.py
index a422c6f1..7da2275b 100644
--- a/tests/sql.py
+++ b/tests/sql.py
@@ -52,6 +52,18 @@ def tearDownModule():
class TestFields(unittest.TestCase):
def testFieldName(self):
+ """
+ - a "str" something
+ - not a method or property of Table
+ - "dotted-notation" friendly:
+ - a valid python identifier
+ - not a python keyword
+ - not starting with underscore or an integer
+ - not containing dots
+
+ Basically, anything alphanumeric, no symbols, only underscore as
+ punctuation
+ """
# Check that Fields cannot start with underscores
self.assertRaises(SyntaxError, Field, '_abc', 'string')
@@ -64,31 +76,48 @@ class TestFields(unittest.TestCase):
self.assertRaises(SyntaxError, Field, x, 'string')
# Check that Fields allows underscores in the body of a field name.
- self.assert_(Field('a_bc', 'string'),
+ self.assertTrue(Field('a_bc', 'string'),
"Field isn't allowing underscores in fieldnames. It should.")
+ # Check that Field names don't allow a python keyword
+ self.assertRaises(SyntaxError, Field, 'True', 'string')
+ self.assertRaises(SyntaxError, Field, 'elif', 'string')
+ self.assertRaises(SyntaxError, Field, 'while', 'string')
+
+ # Check that Field names don't allow a non-valid python identifier
+ non_valid_examples = ["1x", "xx$%@%", "xx yy", "yy\na", "yy\n"]
+ for a in non_valid_examples:
+ self.assertRaises(SyntaxError, Field, a, 'string')
+
+ # Check that Field names don't allow a unicode string
+ non_valid_examples = non_valid_examples = ["ℙƴ☂ℌøἤ", u"ℙƴ☂ℌøἤ",
+ u'àè', u'ṧøмℯ', u'тεṧт', u'♥αłüℯṧ',
+ u'ℊεᾔ℮яαт℮∂', u'♭ƴ', u'ᾔ☤ρℌℓ☺ḓ']
+ for a in non_valid_examples:
+ self.assertRaises(SyntaxError, Field, a, 'string')
+
def testFieldTypes(self):
# Check that string, and password default length is 512
for typ in ['string', 'password']:
- self.assert_(Field('abc', typ).length == 512,
+ self.assertTrue(Field('abc', typ).length == 512,
"Default length for type '%s' is not 512 or 255" % typ)
# Check that upload default length is 512
- self.assert_(Field('abc', 'upload').length == 512,
+ self.assertTrue(Field('abc', 'upload').length == 512,
"Default length for type 'upload' is not 512")
# Check that Tables passed in the type creates a reference
- self.assert_(Field('abc', Table(None, 'temp')).type
+ self.assertTrue(Field('abc', Table(None, 'temp')).type
== 'reference temp',
'Passing an Table does not result in a reference type.')
def testFieldLabels(self):
# Check that a label is successfully built from the supplied fieldname
- self.assert_(Field('abc', 'string').label == 'Abc',
+ self.assertTrue(Field('abc', 'string').label == 'Abc',
'Label built is incorrect')
- self.assert_(Field('abc_def', 'string').label == 'Abc Def',
+ self.assertTrue(Field('abc_def', 'string').label == 'Abc Def',
'Label built is incorrect')
def testFieldFormatters(self): # Formatter should be called Validator
@@ -190,6 +219,18 @@ class TestFields(unittest.TestCase):
class TestTables(unittest.TestCase):
def testTableNames(self):
+ """
+ - a "str" something
+ - not a method or property of DAL
+ - "dotted-notation" friendly:
+ - a valid python identifier
+ - not a python keyword
+ - not starting with underscore or an integer
+ - not containing dots
+
+ Basically, anything alphanumeric, no symbols, only underscore as
+ punctuation
+ """
# Check that Tables cannot start with underscores
self.assertRaises(SyntaxError, Table, None, '_abc')
@@ -202,9 +243,26 @@ class TestTables(unittest.TestCase):
self.assertRaises(SyntaxError, Table, None, x)
# Check that Table allows underscores in the body of a field name.
- self.assert_(Table(None, 'a_bc'),
+ self.assertTrue(Table(None, 'a_bc'),
"Table isn't allowing underscores in tablename. It should.")
+ # Check that Table names don't allow a python keyword
+ self.assertRaises(SyntaxError, Table, None, 'True')
+ self.assertRaises(SyntaxError, Table, None, 'elif')
+ self.assertRaises(SyntaxError, Table, None, 'while')
+
+ # Check that Table names don't allow a non-valid python identifier
+ non_valid_examples = ["1x", "xx$%@%", "xx yy", "yy\na", "yy\n"]
+ for a in non_valid_examples:
+ self.assertRaises(SyntaxError, Table, None, a)
+
+ # Check that Table names don't allow a unicode string
+ non_valid_examples = ["ℙƴ☂ℌøἤ", u"ℙƴ☂ℌøἤ",
+ u'àè', u'ṧøмℯ', u'тεṧт', u'♥αłüℯṧ',
+ u'ℊεᾔ℮яαт℮∂', u'♭ƴ', u'ᾔ☤ρℌℓ☺ḓ']
+ for a in non_valid_examples:
+ self.assertRaises(SyntaxError, Table, None, a)
+
class TestAll(unittest.TestCase):
@@ -230,12 +288,12 @@ class TestTable(unittest.TestCase):
# Does it have the correct fields?
- self.assert_(set(persons.fields).issuperset(set(['firstname',
+ self.assertTrue(set(persons.fields).issuperset(set(['firstname',
'lastname'])))
# ALL is set correctly
- self.assert_('persons.firstname, persons.lastname'
+ self.assertTrue('persons.firstname, persons.lastname'
in str(persons.ALL))
def testTableAlias(self):
@@ -246,8 +304,8 @@ class TestTable(unittest.TestCase):
# Are the different table instances with the same fields
- self.assert_(persons is not aliens)
- self.assert_(set(persons.fields) == set(aliens.fields))
+ self.assertTrue(persons is not aliens)
+ self.assertTrue(set(persons.fields) == set(aliens.fields))
db.close()
def testTableInheritance(self):
@@ -256,7 +314,7 @@ class TestTable(unittest.TestCase):
customers = Table(None, 'customers',
Field('items_purchased', 'integer'),
persons)
- self.assert_(set(customers.fields).issuperset(set(
+ self.assertTrue(set(customers.fields).issuperset(set(
['items_purchased', 'firstname', 'lastname'])))
@@ -1698,7 +1756,6 @@ class TestQuotesByDefault(unittest.TestCase):
def testme(self):
return
-
class TestGis(unittest.TestCase):
def testGeometry(self):
@@ -1897,7 +1954,7 @@ class TestRecordVersioning(unittest.TestCase):
db.t0.insert(name='web2py2')
db(db.t0.name == 'web2py2').delete()
self.assertEqual(len(db(db.t0).select()), 1)
- self.assertEquals(db(db.t0).count(), 1)
+ self.assertEqual(db(db.t0).count(), 1)
db(db.t0.id == i_id).update(name='web2py3')
self.assertEqual(len(db(db.t0).select()), 1)
self.assertEqual(db(db.t0).count(), 1)
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_hyperlinks",
"has_many_modified_files",
"has_many_hunks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 1,
"issue_text_score": 3,
"test_score": 0
},
"num_modified_files": 3
} | 15.03 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "pytest",
"pip_packages": [
"pytest"
],
"pre_install": null,
"python": "3.7",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | attrs @ file:///croot/attrs_1668696182826/work
certifi @ file:///croot/certifi_1671487769961/work/certifi
flit_core @ file:///opt/conda/conda-bld/flit-core_1644941570762/work/source/flit_core
importlib-metadata @ file:///tmp/build/80754af9/importlib-metadata_1648562407465/work
iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work
packaging @ file:///croot/packaging_1671697413597/work
pluggy @ file:///tmp/build/80754af9/pluggy_1648042572264/work
py @ file:///opt/conda/conda-bld/py_1644396412707/work
-e git+https://github.com/web2py/pydal.git@0f4c0f8c47193c6f4957d61d781fafcd36782d3f#egg=pyDAL
pytest==7.1.2
tomli @ file:///opt/conda/conda-bld/tomli_1657175507142/work
typing_extensions @ file:///croot/typing_extensions_1669924550328/work
zipp @ file:///croot/zipp_1672387121353/work
| name: pydal
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- attrs=22.1.0=py37h06a4308_0
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2022.12.7=py37h06a4308_0
- flit-core=3.6.0=pyhd3eb1b0_0
- importlib-metadata=4.11.3=py37h06a4308_0
- importlib_metadata=4.11.3=hd3eb1b0_0
- iniconfig=1.1.1=pyhd3eb1b0_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- packaging=22.0=py37h06a4308_0
- pip=22.3.1=py37h06a4308_0
- pluggy=1.0.0=py37h06a4308_1
- py=1.11.0=pyhd3eb1b0_0
- pytest=7.1.2=py37h06a4308_0
- python=3.7.16=h7a1cb2a_0
- readline=8.2=h5eee18b_0
- setuptools=65.6.3=py37h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- tomli=2.0.1=py37h06a4308_0
- typing_extensions=4.4.0=py37h06a4308_0
- wheel=0.38.4=py37h06a4308_0
- xz=5.6.4=h5eee18b_1
- zipp=3.11.0=py37h06a4308_0
- zlib=1.2.13=h5eee18b_1
prefix: /opt/conda/envs/pydal
| [
"tests/sql.py::TestFields::testFieldName",
"tests/sql.py::TestTables::testTableNames"
] | [
"tests/sql.py::TestSerializers::testSelectIterselect",
"tests/sql.py::TestIterselect::testRun"
] | [
"tests/sql.py::TestFields::testFieldFormatters",
"tests/sql.py::TestFields::testFieldLabels",
"tests/sql.py::TestFields::testFieldTypes",
"tests/sql.py::TestFields::testRun",
"tests/sql.py::TestAll::testSQLALL",
"tests/sql.py::TestTable::testTableAlias",
"tests/sql.py::TestTable::testTableCreation",
"tests/sql.py::TestTable::testTableInheritance",
"tests/sql.py::TestInsert::testRun",
"tests/sql.py::TestSelect::testListInteger",
"tests/sql.py::TestSelect::testListReference",
"tests/sql.py::TestSelect::testListString",
"tests/sql.py::TestSelect::testRun",
"tests/sql.py::TestSelect::testTestQuery",
"tests/sql.py::TestAddMethod::testRun",
"tests/sql.py::TestBelongs::testRun",
"tests/sql.py::TestContains::testRun",
"tests/sql.py::TestLike::testRun",
"tests/sql.py::TestDatetime::testRun",
"tests/sql.py::TestExpressions::testOps",
"tests/sql.py::TestExpressions::testRun",
"tests/sql.py::TestExpressions::testSubstring",
"tests/sql.py::TestJoin::testRun",
"tests/sql.py::TestMinMaxSumAvg::testRun",
"tests/sql.py::TestMigrations::testRun",
"tests/sql.py::TestReference::testRun",
"tests/sql.py::TestClientLevelOps::testRun",
"tests/sql.py::TestVirtualFields::testRun",
"tests/sql.py::TestComputedFields::testRun",
"tests/sql.py::TestCommonFilters::testRun",
"tests/sql.py::TestImportExportFields::testRun",
"tests/sql.py::TestImportExportUuidFields::testRun",
"tests/sql.py::TestDALDictImportExport::testRun",
"tests/sql.py::TestSelectAsDict::testSelect",
"tests/sql.py::TestRNameTable::testJoin",
"tests/sql.py::TestRNameTable::testSelect",
"tests/sql.py::TestRNameFields::testInsert",
"tests/sql.py::TestRNameFields::testJoin",
"tests/sql.py::TestRNameFields::testRun",
"tests/sql.py::TestRNameFields::testSelect",
"tests/sql.py::TestQuoting::testCase",
"tests/sql.py::TestQuoting::testPKFK",
"tests/sql.py::TestTableAndFieldCase::testme",
"tests/sql.py::TestQuotesByDefault::testme",
"tests/sql.py::TestGis::testGeometry",
"tests/sql.py::TestGis::testGeometryCase",
"tests/sql.py::TestGis::testGisMigration",
"tests/sql.py::TestSQLCustomType::testRun",
"tests/sql.py::TestLazy::testLazyGetter",
"tests/sql.py::TestLazy::testRowNone",
"tests/sql.py::TestLazy::testRun",
"tests/sql.py::TestRedefine::testRun",
"tests/sql.py::TestUpdateInsert::testRun",
"tests/sql.py::TestBulkInsert::testRun",
"tests/sql.py::TestRecordVersioning::testRun",
"tests/sql.py::TestSerializers::testAsJson"
] | [] | BSD 3-Clause "New" or "Revised" License | 145 |
|
rthalley__dnspython-98 | 0b8ae7fd1107f330f94afc03311f233d51968a66 | 2015-05-21 12:36:37 | a4774eea299e6a0ce01c074973dbddbe6fe20636 | diff --git a/dns/exception.py b/dns/exception.py
index 60b4912..cbcdb57 100644
--- a/dns/exception.py
+++ b/dns/exception.py
@@ -15,14 +15,86 @@
"""Common DNS Exceptions."""
+
class DNSException(Exception):
- """Abstract base class shared by all dnspython exceptions."""
- def __init__(self, *args):
+ """Abstract base class shared by all dnspython exceptions.
+
+ It supports two basic modes of operation:
+
+ a) Old/compatible mode is used if __init__ was called with
+ empty **kwargs.
+ In compatible mode all *args are passed to standard Python Exception class
+ as before and all *args are printed by standard __str__ implementation.
+ Class variable msg (or doc string if msg is None) is returned from str()
+ if *args is empty.
+
+ b) New/parametrized mode is used if __init__ was called with
+ non-empty **kwargs.
+ In the new mode *args has to be empty and all kwargs has to exactly match
+ set in class variable self.supp_kwargs. All kwargs are stored inside
+ self.kwargs and used in new __str__ implementation to construct
+ formated message based on self.fmt string.
+
+ In the simplest case it is enough to override supp_kwargs and fmt
+ class variables to get nice parametrized messages.
+ """
+ msg = None # non-parametrized message
+ supp_kwargs = set() # accepted parameters for _fmt_kwargs (sanity check)
+ fmt = None # message parametrized with results from _fmt_kwargs
+
+ def __init__(self, *args, **kwargs):
+ self._check_params(*args, **kwargs)
+ self._check_kwargs(**kwargs)
+ self.kwargs = kwargs
+ if self.msg is None:
+ # doc string is better implicit message than empty string
+ self.msg = self.__doc__
if args:
super(DNSException, self).__init__(*args)
else:
- # doc string is better implicit message than empty string
- super(DNSException, self).__init__(self.__doc__)
+ super(DNSException, self).__init__(self.msg)
+
+ def _check_params(self, *args, **kwargs):
+ """Old exceptions supported only args and not kwargs.
+
+ For sanity we do not allow to mix old and new behavior."""
+ if args or kwargs:
+ assert bool(args) != bool(kwargs), \
+ 'keyword arguments are mutually exclusive with positional args'
+
+ def _check_kwargs(self, **kwargs):
+ if kwargs:
+ assert set(kwargs.keys()) == self.supp_kwargs, \
+ 'following set of keyword args is required: %s' % (
+ self.supp_kwargs)
+
+ def _fmt_kwargs(self, **kwargs):
+ """Format kwargs before printing them.
+
+ Resulting dictionary has to have keys necessary for str.format call
+ on fmt class variable.
+ """
+ fmtargs = {}
+ for kw, data in kwargs.items():
+ if isinstance(data, (list, set)):
+ # convert list of <someobj> to list of str(<someobj>)
+ fmtargs[kw] = list(map(str, data))
+ if len(fmtargs[kw]) == 1:
+ # remove list brackets [] from single-item lists
+ fmtargs[kw] = fmtargs[kw].pop()
+ else:
+ fmtargs[kw] = data
+ return fmtargs
+
+ def __str__(self):
+ if self.kwargs and self.fmt:
+ # provide custom message constructed from keyword arguments
+ fmtargs = self._fmt_kwargs(**self.kwargs)
+ return self.fmt.format(**fmtargs)
+ else:
+ # print *args directly in the same way as old DNSException
+ return super(DNSException, self).__str__()
+
class FormError(DNSException):
"""DNS message is malformed."""
@@ -38,3 +110,5 @@ class TooBig(DNSException):
class Timeout(DNSException):
"""The DNS operation timed out."""
+ supp_kwargs = set(['timeout'])
+ fmt = "%s after {timeout} seconds" % __doc__[:-1]
diff --git a/dns/resolver.py b/dns/resolver.py
index 387bd50..443e1d0 100644
--- a/dns/resolver.py
+++ b/dns/resolver.py
@@ -48,6 +48,21 @@ if sys.platform == 'win32':
class NXDOMAIN(dns.exception.DNSException):
"""The DNS query name does not exist."""
+ supp_kwargs = set(['qname'])
+
+ def __str__(self):
+ if not 'qname' in self.kwargs:
+ return super(NXDOMAIN, self).__str__()
+
+ qname = self.kwargs['qname']
+ msg = self.__doc__[:-1]
+ if isinstance(qname, (list, set)):
+ if len(qname) > 1:
+ msg = 'None of DNS query names exist'
+ qname = list(map(str, qname))
+ else:
+ qname = qname[0]
+ return "%s: %s" % (msg, (str(qname)))
class YXDOMAIN(dns.exception.DNSException):
"""The DNS query name is too long after DNAME substitution."""
@@ -58,40 +73,36 @@ class YXDOMAIN(dns.exception.DNSException):
Timeout = dns.exception.Timeout
+
class NoAnswer(dns.exception.DNSException):
"""The DNS response does not contain an answer to the question."""
- def __init__(self, question=None):
- super(dns.exception.DNSException, self).__init__()
- self.question = question
-
- def __str__(self):
- message = self.__doc__
- if self.question:
- message = message[0:-1]
- for q in self.question:
- message += ' %s' % q
- return message
+ fmt = '%s: {query}' % __doc__[:-1]
+ supp_kwargs = set(['response'])
+ def _fmt_kwargs(self, **kwargs):
+ return super(NoAnswer, self)._fmt_kwargs(
+ query=kwargs['response'].question)
class NoNameservers(dns.exception.DNSException):
- """No non-broken nameservers are available to answer the query."""
- def __init__(self, errors=[]):
- """Optionally construct message with list of servers and errors.
+ """All nameservers failed to answer the query.
- @param errors: list of servers and respective errors
- @type errors: [(server ip address, any object convertible to string)]
- """
- super(dns.exception.DNSException, self).__init__()
- self.errors = errors
+ @param errors: list of servers and respective errors
+ @type errors: [(server ip address, any object convertible to string)]
+ Non-empty errors list will add explanatory message ()
+ """
+
+ msg = "All nameservers failed to answer the query."
+ fmt = "%s {query}: {errors}" % msg[:-1]
+ supp_kwargs = set(['request', 'errors'])
+
+ def _fmt_kwargs(self, **kwargs):
+ srv_msgs = []
+ for err in kwargs['errors']:
+ srv_msgs.append('Server %s %s port %s anwered %s' % (err[0],
+ 'TCP' if err[1] else 'UDP', err[2], err[3]))
+ return super(NoNameservers, self)._fmt_kwargs(
+ query=kwargs['request'].question, errors='; '.join(srv_msgs))
- def __str__(self):
- message = self.__doc__
- if self.errors:
- srv_msgs = []
- for err in self.errors:
- srv_msgs.append('Server %s %s' % (err[0], err[1]))
- message += ' %s' % '; '.join(srv_msgs)
- return message
class NotAbsolute(dns.exception.DNSException):
"""An absolute domain name is required but a relative name was provided."""
@@ -164,9 +175,9 @@ class Answer(object):
if raise_on_no_answer:
raise NoAnswer(question=response.question)
if raise_on_no_answer:
- raise NoAnswer(question=response.question)
+ raise NoAnswer(response=response)
if rrset is None and raise_on_no_answer:
- raise NoAnswer(question=response.question)
+ raise NoAnswer(response=response)
self.canonical_name = qname
self.rrset = rrset
if rrset is None:
@@ -742,18 +753,18 @@ class Resolver(object):
def _compute_timeout(self, start):
now = time.time()
- if now < start:
- if start - now > 1:
+ duration = now - start
+ if duration < 0:
+ if duration < -1:
# Time going backwards is bad. Just give up.
- raise Timeout
+ raise Timeout(timeout=duration)
else:
# Time went backwards, but only a little. This can
# happen, e.g. under vmware with older linux kernels.
# Pretend it didn't happen.
now = start
- duration = now - start
if duration >= self.lifetime:
- raise Timeout
+ raise Timeout(timeout=duration)
return min(self.lifetime - duration, self.timeout)
def query(self, qname, rdtype=dns.rdatatype.A, rdclass=dns.rdataclass.IN,
@@ -839,10 +850,11 @@ class Resolver(object):
backoff = 0.10
while response is None:
if len(nameservers) == 0:
- raise NoNameservers(errors)
+ raise NoNameservers(request=request, errors=errors)
for nameserver in nameservers[:]:
timeout = self._compute_timeout(start)
try:
+ tcp_attempt = tcp
if tcp:
response = dns.query.tcp(request, nameserver,
timeout, self.port,
@@ -855,6 +867,7 @@ class Resolver(object):
source_port=source_port)
if response.flags & dns.flags.TC:
# Response truncated; retry with TCP.
+ tcp_attempt = True
timeout = self._compute_timeout(start)
response = dns.query.tcp(request, nameserver,
timeout, self.port,
@@ -865,15 +878,17 @@ class Resolver(object):
# Communication failure or timeout. Go to the
# next server
#
+ errors.append((nameserver, tcp_attempt, self.port, ex,
+ response))
response = None
- errors.append((nameserver, ex))
continue
except dns.query.UnexpectedSource as ex:
#
# Who knows? Keep going.
#
+ errors.append((nameserver, tcp_attempt, self.port, ex,
+ response))
response = None
- errors.append((nameserver, ex))
continue
except dns.exception.FormError as ex:
#
@@ -882,8 +897,9 @@ class Resolver(object):
# continue.
#
nameservers.remove(nameserver)
+ errors.append((nameserver, tcp_attempt, self.port, ex,
+ response))
response = None
- errors.append((nameserver, ex))
continue
except EOFError as ex:
#
@@ -893,13 +909,15 @@ class Resolver(object):
# mix and continue.
#
nameservers.remove(nameserver)
+ errors.append((nameserver, tcp_attempt, self.port, ex,
+ response))
response = None
- errors.append((nameserver, ex))
continue
rcode = response.rcode()
if rcode == dns.rcode.YXDOMAIN:
ex = YXDOMAIN()
- errors.append((nameserver, ex))
+ errors.append((nameserver, tcp_attempt, self.port, ex,
+ response))
raise ex
if rcode == dns.rcode.NOERROR or \
rcode == dns.rcode.NXDOMAIN:
@@ -911,7 +929,8 @@ class Resolver(object):
#
if rcode != dns.rcode.SERVFAIL or not self.retry_servfail:
nameservers.remove(nameserver)
- errors.append((nameserver, dns.rcode.to_text(rcode)))
+ errors.append((nameserver, tcp_attempt, self.port,
+ dns.rcode.to_text(rcode), response))
response = None
if not response is None:
break
@@ -932,7 +951,7 @@ class Resolver(object):
all_nxdomain = False
break
if all_nxdomain:
- raise NXDOMAIN
+ raise NXDOMAIN(qname=qnames_to_try)
answer = Answer(qname, rdtype, rdclass, response,
raise_on_no_answer)
if self.cache:
| Python3 branch is missing commits from pull #92
Please be so kind and merge #92 to python3 branch too. Currently Python2 and Python3 exceptions are very different when it comes to str().
Thank you! | rthalley/dnspython | diff --git a/tests/test_exceptions.py b/tests/test_exceptions.py
index 3fd7331..90a6af4 100644
--- a/tests/test_exceptions.py
+++ b/tests/test_exceptions.py
@@ -18,6 +18,12 @@ import unittest
from dns.exception import DNSException
+
+class FormatedError(DNSException):
+ fmt = "Custom format: {parameter}"
+ supp_kwargs = set(['parameter'])
+
+
class ExceptionTestCase(unittest.TestCase):
def test_custom_message(self):
@@ -33,6 +39,24 @@ class ExceptionTestCase(unittest.TestCase):
except DNSException as ex:
self.assertEqual(ex.__class__.__doc__, str(ex))
+ def test_formatted_error(self):
+ """Exceptions with explicit format has to respect it."""
+ params = {'parameter': 'value'}
+ try:
+ raise FormatedError(**params)
+ except FormatedError as ex:
+ msg = FormatedError.fmt.format(**params)
+ self.assertEqual(msg, str(ex))
+
+ def test_kwargs_only(self):
+ """Kwargs cannot be combined with args."""
+ with self.assertRaises(AssertionError):
+ raise FormatedError(1, a=2)
+
+ def test_kwargs_unsupported(self):
+ """Only supported kwargs are accepted."""
+ with self.assertRaises(AssertionError):
+ raise FormatedError(unsupported=2)
if __name__ == '__main__':
unittest.main()
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files",
"has_many_hunks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 2,
"issue_text_score": 3,
"test_score": 3
},
"num_modified_files": 2
} | 1.12 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "pytest",
"pip_packages": [
"pytest"
],
"pre_install": null,
"python": "3.9",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | -e git+https://github.com/rthalley/dnspython.git@0b8ae7fd1107f330f94afc03311f233d51968a66#egg=dnspython3
exceptiongroup @ file:///croot/exceptiongroup_1706031385326/work
iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work
packaging @ file:///croot/packaging_1734472117206/work
pluggy @ file:///croot/pluggy_1733169602837/work
pytest @ file:///croot/pytest_1738938843180/work
tomli @ file:///opt/conda/conda-bld/tomli_1657175507142/work
| name: dnspython
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- exceptiongroup=1.2.0=py39h06a4308_0
- iniconfig=1.1.1=pyhd3eb1b0_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=3.0.16=h5eee18b_0
- packaging=24.2=py39h06a4308_0
- pip=25.0=py39h06a4308_0
- pluggy=1.5.0=py39h06a4308_0
- pytest=8.3.4=py39h06a4308_0
- python=3.9.21=he870216_1
- readline=8.2=h5eee18b_0
- setuptools=75.8.0=py39h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- tomli=2.0.1=py39h06a4308_0
- tzdata=2025a=h04d1e81_0
- wheel=0.45.1=py39h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
prefix: /opt/conda/envs/dnspython
| [
"tests/test_exceptions.py::ExceptionTestCase::test_formatted_error",
"tests/test_exceptions.py::ExceptionTestCase::test_kwargs_only",
"tests/test_exceptions.py::ExceptionTestCase::test_kwargs_unsupported"
] | [] | [
"tests/test_exceptions.py::ExceptionTestCase::test_custom_message",
"tests/test_exceptions.py::ExceptionTestCase::test_implicit_message"
] | [] | ISC License | 146 |
|
sympy__sympy-9421 | 050d769144cdc35b486b58eb63343b08554e4a3b | 2015-05-23 06:10:16 | 0241b35cae5f2adc04dc37b25f7dc9c5f00bd746 | diff --git a/sympy/core/facts.py b/sympy/core/facts.py
index 0ef1e92e94..4cc36ac997 100644
--- a/sympy/core/facts.py
+++ b/sympy/core/facts.py
@@ -79,7 +79,7 @@ def transitive_closure(implications):
Computes the transitive closure of a list of implications
Uses Warshall's algorithm, as described at
- http://www.cs.hope.edu/~cusack/Notes/Notes/DiscreteMath/Warshall.pdf.
+ http://chuck.ferzle.com/Notes/Notes/DiscreteMath/Warshall.pdf.
"""
full_implications = set(implications)
literals = set().union(*map(set, full_implications))
diff --git a/sympy/core/mul.py b/sympy/core/mul.py
index 982d8db475..e877c5ac71 100644
--- a/sympy/core/mul.py
+++ b/sympy/core/mul.py
@@ -1025,7 +1025,9 @@ def _eval_is_polar(self):
all(arg.is_polar or arg.is_positive for arg in self.args)
def _eval_is_real(self):
- real = True
+ return self._eval_real_imag(True)
+
+ def _eval_real_imag(self, real):
zero = one_neither = False
for t in self.args:
@@ -1062,10 +1064,12 @@ def _eval_is_imaginary(self):
if z:
return False
elif z is False:
- return (S.ImaginaryUnit*self).is_real
+ return self._eval_real_imag(False)
def _eval_is_hermitian(self):
- real = True
+ return self._eval_herm_antiherm(True)
+
+ def _eval_herm_antiherm(self, real):
one_nc = zero = one_neither = False
for t in self.args:
@@ -1077,10 +1081,14 @@ def _eval_is_hermitian(self):
if t.is_antihermitian:
real = not real
elif t.is_hermitian:
- if zero is False:
- zero = fuzzy_not(t.is_nonzero)
- if zero:
- return True
+ if not zero:
+ z = t.is_zero
+ if not z and zero is False:
+ zero = z
+ elif z:
+ if all(a.is_finite for a in self.args):
+ return True
+ return
elif t.is_hermitian is False:
if one_neither:
return
@@ -1099,7 +1107,7 @@ def _eval_is_antihermitian(self):
if z:
return False
elif z is False:
- return (S.ImaginaryUnit*self).is_hermitian
+ return self._eval_herm_antiherm(False)
def _eval_is_irrational(self):
for t in self.args:
@@ -1127,8 +1135,9 @@ def _eval_is_positive(self):
pos * neg * nonpositive -> pos or zero -> None is returned
pos * neg * nonnegative -> neg or zero -> False is returned
"""
+ return self._eval_pos_neg(1)
- sign = 1
+ def _eval_pos_neg(self, sign):
saw_NON = False
for t in self.args:
if t.is_positive:
@@ -1136,7 +1145,9 @@ def _eval_is_positive(self):
elif t.is_negative:
sign = -sign
elif t.is_zero:
- return False
+ if all(a.is_finite for a in self.args):
+ return False
+ return
elif t.is_nonpositive:
sign = -sign
saw_NON = True
@@ -1150,7 +1161,9 @@ def _eval_is_positive(self):
return False
def _eval_is_negative(self):
- return (-self).is_positive
+ if self.args[0] == -1:
+ return (-self).is_positive # remove -1
+ return self._eval_pos_neg(-1)
def _eval_is_odd(self):
is_integer = self.is_integer
| Circularity in assumptions of products
Running ``(2*z).is_complex`` with SYMPY_USE_CACHE=no leads to
```
RuntimeError: maximum recursion depth exceeded
```
This also happens with other assumptions (except ``is_commutative``). | sympy/sympy | diff --git a/sympy/core/tests/test_arit.py b/sympy/core/tests/test_arit.py
index d79df338d8..8ec0bb33d0 100644
--- a/sympy/core/tests/test_arit.py
+++ b/sympy/core/tests/test_arit.py
@@ -1812,6 +1812,17 @@ def test(z, b, e):
e = Mul(b, z, evaluate=False)
test(z, b, e)
+def test_Mul_with_zero_infinite():
+ zer = Dummy(zero=True)
+ inf = Dummy(finite=False)
+
+ e = Mul(zer, inf, evaluate=False)
+ assert e.is_positive is None
+ assert e.is_hermitian is None
+
+ e = Mul(inf, zer, evaluate=False)
+ assert e.is_positive is None
+ assert e.is_hermitian is None
def test_issue_8247_8354():
from sympy import tan
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 2,
"issue_text_score": 1,
"test_score": 0
},
"num_modified_files": 2
} | 0.7 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "pytest",
"pip_packages": [
"mpmath>=0.19",
"pytest"
],
"pre_install": [
"apt-get update",
"apt-get install -y python3-dev python3-pip"
],
"python": "3.6",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | attrs @ file:///opt/conda/conda-bld/attrs_1642510447205/work
certifi==2021.5.30
importlib-metadata @ file:///tmp/build/80754af9/importlib-metadata_1631916693255/work
iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work
more-itertools @ file:///tmp/build/80754af9/more-itertools_1637733554872/work
mpmath==1.3.0
packaging @ file:///tmp/build/80754af9/packaging_1637314298585/work
pluggy @ file:///tmp/build/80754af9/pluggy_1615976315926/work
py @ file:///opt/conda/conda-bld/py_1644396412707/work
pyparsing @ file:///tmp/build/80754af9/pyparsing_1635766073266/work
pytest==6.2.4
-e git+https://github.com/sympy/sympy.git@050d769144cdc35b486b58eb63343b08554e4a3b#egg=sympy
toml @ file:///tmp/build/80754af9/toml_1616166611790/work
typing_extensions @ file:///opt/conda/conda-bld/typing_extensions_1647553014482/work
zipp @ file:///tmp/build/80754af9/zipp_1633618647012/work
| name: sympy
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- attrs=21.4.0=pyhd3eb1b0_0
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- importlib-metadata=4.8.1=py36h06a4308_0
- importlib_metadata=4.8.1=hd3eb1b0_0
- iniconfig=1.1.1=pyhd3eb1b0_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- more-itertools=8.12.0=pyhd3eb1b0_0
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- packaging=21.3=pyhd3eb1b0_0
- pip=21.2.2=py36h06a4308_0
- pluggy=0.13.1=py36h06a4308_0
- py=1.11.0=pyhd3eb1b0_0
- pyparsing=3.0.4=pyhd3eb1b0_0
- pytest=6.2.4=py36h06a4308_2
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_0
- setuptools=58.0.4=py36h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- toml=0.10.2=pyhd3eb1b0_0
- typing_extensions=4.1.1=pyh06a4308_0
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- zipp=3.6.0=pyhd3eb1b0_0
- zlib=1.2.13=h5eee18b_1
- pip:
- mpmath==1.3.0
prefix: /opt/conda/envs/sympy
| [
"sympy/core/tests/test_arit.py::test_Mul_with_zero_infinite"
] | [] | [
"sympy/core/tests/test_arit.py::test_bug1",
"sympy/core/tests/test_arit.py::test_Symbol",
"sympy/core/tests/test_arit.py::test_arit0",
"sympy/core/tests/test_arit.py::test_div",
"sympy/core/tests/test_arit.py::test_pow",
"sympy/core/tests/test_arit.py::test_pow2",
"sympy/core/tests/test_arit.py::test_pow3",
"sympy/core/tests/test_arit.py::test_pow_E",
"sympy/core/tests/test_arit.py::test_pow_issue_3516",
"sympy/core/tests/test_arit.py::test_pow_im",
"sympy/core/tests/test_arit.py::test_real_mul",
"sympy/core/tests/test_arit.py::test_ncmul",
"sympy/core/tests/test_arit.py::test_ncpow",
"sympy/core/tests/test_arit.py::test_powerbug",
"sympy/core/tests/test_arit.py::test_Mul_doesnt_expand_exp",
"sympy/core/tests/test_arit.py::test_Add_Mul_is_integer",
"sympy/core/tests/test_arit.py::test_Add_Mul_is_finite",
"sympy/core/tests/test_arit.py::test_Mul_is_even_odd",
"sympy/core/tests/test_arit.py::test_Mul_is_rational",
"sympy/core/tests/test_arit.py::test_Add_is_rational",
"sympy/core/tests/test_arit.py::test_Add_is_even_odd",
"sympy/core/tests/test_arit.py::test_Mul_is_negative_positive",
"sympy/core/tests/test_arit.py::test_Mul_is_negative_positive_2",
"sympy/core/tests/test_arit.py::test_Mul_is_nonpositive_nonnegative",
"sympy/core/tests/test_arit.py::test_Add_is_negative_positive",
"sympy/core/tests/test_arit.py::test_Add_is_nonpositive_nonnegative",
"sympy/core/tests/test_arit.py::test_Pow_is_integer",
"sympy/core/tests/test_arit.py::test_Pow_is_real",
"sympy/core/tests/test_arit.py::test_real_Pow",
"sympy/core/tests/test_arit.py::test_Pow_is_finite",
"sympy/core/tests/test_arit.py::test_Pow_is_even_odd",
"sympy/core/tests/test_arit.py::test_Pow_is_negative_positive",
"sympy/core/tests/test_arit.py::test_Pow_is_zero",
"sympy/core/tests/test_arit.py::test_Pow_is_nonpositive_nonnegative",
"sympy/core/tests/test_arit.py::test_Mul_is_imaginary_real",
"sympy/core/tests/test_arit.py::test_Mul_hermitian_antihermitian",
"sympy/core/tests/test_arit.py::test_Add_is_comparable",
"sympy/core/tests/test_arit.py::test_Mul_is_comparable",
"sympy/core/tests/test_arit.py::test_Pow_is_comparable",
"sympy/core/tests/test_arit.py::test_Add_is_positive_2",
"sympy/core/tests/test_arit.py::test_Add_is_irrational",
"sympy/core/tests/test_arit.py::test_issue_3531b",
"sympy/core/tests/test_arit.py::test_bug3",
"sympy/core/tests/test_arit.py::test_suppressed_evaluation",
"sympy/core/tests/test_arit.py::test_Add_as_coeff_mul",
"sympy/core/tests/test_arit.py::test_Pow_as_coeff_mul_doesnt_expand",
"sympy/core/tests/test_arit.py::test_issue_3514",
"sympy/core/tests/test_arit.py::test_make_args",
"sympy/core/tests/test_arit.py::test_issue_5126",
"sympy/core/tests/test_arit.py::test_Rational_as_content_primitive",
"sympy/core/tests/test_arit.py::test_Add_as_content_primitive",
"sympy/core/tests/test_arit.py::test_Mul_as_content_primitive",
"sympy/core/tests/test_arit.py::test_Pow_as_content_primitive",
"sympy/core/tests/test_arit.py::test_issue_5460",
"sympy/core/tests/test_arit.py::test_product_irrational",
"sympy/core/tests/test_arit.py::test_issue_5919",
"sympy/core/tests/test_arit.py::test_Mod",
"sympy/core/tests/test_arit.py::test_Mod_is_integer",
"sympy/core/tests/test_arit.py::test_Mod_is_nonposneg",
"sympy/core/tests/test_arit.py::test_issue_6001",
"sympy/core/tests/test_arit.py::test_polar",
"sympy/core/tests/test_arit.py::test_issue_6040",
"sympy/core/tests/test_arit.py::test_issue_6082",
"sympy/core/tests/test_arit.py::test_issue_6077",
"sympy/core/tests/test_arit.py::test_mul_flatten_oo",
"sympy/core/tests/test_arit.py::test_add_flatten",
"sympy/core/tests/test_arit.py::test_issue_5160_6087_6089_6090",
"sympy/core/tests/test_arit.py::test_float_int",
"sympy/core/tests/test_arit.py::test_issue_6611a",
"sympy/core/tests/test_arit.py::test_denest_add_mul",
"sympy/core/tests/test_arit.py::test_mul_coeff",
"sympy/core/tests/test_arit.py::test_mul_zero_detection",
"sympy/core/tests/test_arit.py::test_issue_8247_8354"
] | [] | BSD | 147 |
|
pre-commit__pre-commit-235 | b4bc5e47423635e187d50d8730584d2c8ff06772 | 2015-05-24 03:03:11 | 5791d84236d82f8aa8609c3ff1c69a991d8c6607 | diff --git a/pre_commit/commands/install_uninstall.py b/pre_commit/commands/install_uninstall.py
index c84d29b..47c9484 100644
--- a/pre_commit/commands/install_uninstall.py
+++ b/pre_commit/commands/install_uninstall.py
@@ -48,6 +48,9 @@ def install(runner, overwrite=False, hooks=False, hook_type='pre-commit'):
hook_path = runner.get_hook_path(hook_type)
legacy_path = hook_path + '.legacy'
+ if not os.path.exists(os.path.dirname(hook_path)):
+ os.makedirs(os.path.dirname(hook_path))
+
# If we have an existing hook, move it to pre-commit.legacy
if (
os.path.exists(hook_path) and
| Some versions of git don't create .git/hooks directory
Noticed here: https://github.com/victorlin/bugbuzz-python/pull/1#issuecomment-104971132 | pre-commit/pre-commit | diff --git a/tests/commands/install_uninstall_test.py b/tests/commands/install_uninstall_test.py
index 9e1806e..ca82c06 100644
--- a/tests/commands/install_uninstall_test.py
+++ b/tests/commands/install_uninstall_test.py
@@ -5,6 +5,7 @@ import io
import os
import os.path
import re
+import shutil
import subprocess
import sys
@@ -78,6 +79,15 @@ def test_install_pre_commit(tmpdir_factory):
assert pre_push_contents == expected_contents
+def test_install_hooks_directory_not_present(tmpdir_factory):
+ path = git_dir(tmpdir_factory)
+ # Simulate some git clients which don't make .git/hooks #234
+ shutil.rmtree(os.path.join(path, '.git', 'hooks'))
+ runner = Runner(path)
+ install(runner)
+ assert os.path.exists(runner.pre_commit_path)
+
+
def test_uninstall_does_not_blow_up_when_not_there(tmpdir_factory):
path = git_dir(tmpdir_factory)
runner = Runner(path)
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_short_problem_statement",
"has_hyperlinks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 1,
"issue_text_score": 2,
"test_score": 2
},
"num_modified_files": 1
} | 0.5 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[dev]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.5",
"reqs_path": [
"requirements-dev.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | aspy.yaml==1.3.0
astroid==1.3.2
attrs==22.2.0
cached-property==1.5.2
certifi==2021.5.30
coverage==6.2
distlib==0.3.9
filelock==3.4.1
flake8==5.0.4
importlib-metadata==4.8.3
importlib-resources==5.4.0
iniconfig==1.1.1
jsonschema==3.2.0
logilab-common==1.9.7
mccabe==0.7.0
mock==5.2.0
mypy-extensions==1.0.0
nodeenv==1.6.0
ordereddict==1.1
packaging==21.3
platformdirs==2.4.0
pluggy==1.0.0
-e git+https://github.com/pre-commit/pre-commit.git@b4bc5e47423635e187d50d8730584d2c8ff06772#egg=pre_commit
py==1.11.0
pycodestyle==2.9.1
pyflakes==2.5.0
pylint==1.3.1
pyparsing==3.1.4
pyrsistent==0.18.0
pytest==7.0.1
PyYAML==6.0.1
simplejson==3.20.1
six==1.17.0
tomli==1.2.3
typing_extensions==4.1.1
virtualenv==20.17.1
zipp==3.6.0
| name: pre-commit
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- pip=21.2.2=py36h06a4308_0
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_0
- setuptools=58.0.4=py36h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- argparse==1.4.0
- aspy-yaml==1.3.0
- astroid==1.3.2
- attrs==22.2.0
- cached-property==1.5.2
- coverage==6.2
- distlib==0.3.9
- filelock==3.4.1
- flake8==5.0.4
- importlib-metadata==4.8.3
- importlib-resources==5.4.0
- iniconfig==1.1.1
- jsonschema==3.2.0
- logilab-common==1.9.7
- mccabe==0.7.0
- mock==5.2.0
- mypy-extensions==1.0.0
- nodeenv==1.6.0
- ordereddict==1.1
- packaging==21.3
- platformdirs==2.4.0
- pluggy==1.0.0
- py==1.11.0
- pycodestyle==2.9.1
- pyflakes==2.5.0
- pylint==1.3.1
- pyparsing==3.1.4
- pyrsistent==0.18.0
- pytest==7.0.1
- pyyaml==6.0.1
- simplejson==3.20.1
- six==1.17.0
- tomli==1.2.3
- typing-extensions==4.1.1
- virtualenv==20.17.1
- zipp==3.6.0
prefix: /opt/conda/envs/pre-commit
| [
"tests/commands/install_uninstall_test.py::test_install_hooks_directory_not_present"
] | [
"tests/commands/install_uninstall_test.py::test_install_pre_commit_and_run",
"tests/commands/install_uninstall_test.py::test_install_idempotent",
"tests/commands/install_uninstall_test.py::test_environment_not_sourced",
"tests/commands/install_uninstall_test.py::test_failing_hooks_returns_nonzero",
"tests/commands/install_uninstall_test.py::test_install_existing_hooks_no_overwrite",
"tests/commands/install_uninstall_test.py::test_install_existing_hook_no_overwrite_idempotent",
"tests/commands/install_uninstall_test.py::test_failing_existing_hook_returns_1",
"tests/commands/install_uninstall_test.py::test_install_overwrite_no_existing_hooks",
"tests/commands/install_uninstall_test.py::test_install_overwrite",
"tests/commands/install_uninstall_test.py::test_uninstall_restores_legacy_hooks",
"tests/commands/install_uninstall_test.py::test_replace_old_commit_script",
"tests/commands/install_uninstall_test.py::test_installs_hooks_with_hooks_True",
"tests/commands/install_uninstall_test.py::test_installed_from_venv",
"tests/commands/install_uninstall_test.py::test_pre_push_integration_failing",
"tests/commands/install_uninstall_test.py::test_pre_push_integration_accepted"
] | [
"tests/commands/install_uninstall_test.py::test_is_not_our_pre_commit",
"tests/commands/install_uninstall_test.py::test_is_our_pre_commit",
"tests/commands/install_uninstall_test.py::test_is_not_previous_pre_commit",
"tests/commands/install_uninstall_test.py::test_is_also_not_previous_pre_commit",
"tests/commands/install_uninstall_test.py::test_is_previous_pre_commit",
"tests/commands/install_uninstall_test.py::test_install_pre_commit",
"tests/commands/install_uninstall_test.py::test_uninstall_does_not_blow_up_when_not_there",
"tests/commands/install_uninstall_test.py::test_uninstall",
"tests/commands/install_uninstall_test.py::test_uninstall_doesnt_remove_not_our_hooks"
] | [] | MIT License | 148 |
|
wndhydrnt__python-oauth2-48 | f37a26ccb2a0bd5c6682a798f0e1669d75aacd5a | 2015-05-24 16:36:53 | 9d56b2202515aaaf3bed7a5b3bc3b61f7fe17199 | diff --git a/CHANGELOG.md b/CHANGELOG.md
index f15bc9e..b5fcbb5 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -13,6 +13,7 @@ Improvements:
- Move WSGI server code into its own module ([@wndhydrnt][])
- Renamed class acting as entrypoint for WSGI server from 'Server' to 'Application' ([@wndhydrnt][])
- Client Credentials Grant example ([@shupp][])
+ - Methods `authenticate` and `render_auth_page` of a Site Adapter accept an instance of `oauth2.datatype.Client` ([@wndhydrnt][])
Bugfixes:
diff --git a/README.rst b/README.rst
index 0b77e9b..a745d83 100644
--- a/README.rst
+++ b/README.rst
@@ -42,14 +42,15 @@ Example Authorization server
# This can be used to display confirmation dialogs and the like.
class ExampleSiteAdapter(oauth2.web.AuthorizationCodeGrantSiteAdapter,
oauth2.web.ImplicitGrantSiteAdapter):
- def authenticate(self, request, environ, scopes):
+ def authenticate(self, request, environ, scopes, client):
# Check if the user has granted access
if request.post_param("confirm") == "confirm":
return {}
raise oauth2.error.UserNotAuthenticated
- def render_auth_page(self, request, response, environ, scopes):
+ def render_auth_page(self, request, response, environ, scopes,
+ client):
response.body = '''
<html>
<body>
diff --git a/docs/examples/authorization_code_grant.py b/docs/examples/authorization_code_grant.py
index a8ecf82..ff82b4c 100644
--- a/docs/examples/authorization_code_grant.py
+++ b/docs/examples/authorization_code_grant.py
@@ -68,12 +68,12 @@ class TestSiteAdapter(AuthorizationCodeGrantSiteAdapter):
</html>
"""
- def render_auth_page(self, request, response, environ, scopes):
+ def render_auth_page(self, request, response, environ, scopes, client):
response.body = self.CONFIRMATION_TEMPLATE
return response
- def authenticate(self, request, environ, scopes):
+ def authenticate(self, request, environ, scopes, client):
if request.method == "POST":
if request.post_param("confirm") == "1":
return
diff --git a/docs/examples/base_server.py b/docs/examples/base_server.py
index be43cb5..27ac9b1 100644
--- a/docs/examples/base_server.py
+++ b/docs/examples/base_server.py
@@ -11,14 +11,14 @@ import oauth2.web.wsgi
# This can be used to display confirmation dialogs and the like.
class ExampleSiteAdapter(oauth2.web.AuthorizationCodeGrantSiteAdapter,
oauth2.web.ImplicitGrantSiteAdapter):
- def authenticate(self, request, environ, scopes):
+ def authenticate(self, request, environ, scopes, client):
# Check if the user has granted access
if request.post_param("confirm") == "confirm":
return {}
raise oauth2.error.UserNotAuthenticated
- def render_auth_page(self, request, response, environ, scopes):
+ def render_auth_page(self, request, response, environ, scopes, client):
response.body = '''
<html>
<body>
diff --git a/docs/examples/implicit_grant.py b/docs/examples/implicit_grant.py
index 4368f98..0d244d3 100644
--- a/docs/examples/implicit_grant.py
+++ b/docs/examples/implicit_grant.py
@@ -40,13 +40,13 @@ class TestSiteAdapter(ImplicitGrantSiteAdapter):
</html>
"""
- def render_auth_page(self, request, response, environ, scopes):
+ def render_auth_page(self, request, response, environ, scopes, client):
# Add check if the user is logged or a redirect to the login page here
response.body = self.CONFIRMATION_TEMPLATE
return response
- def authenticate(self, request, environ, scopes):
+ def authenticate(self, request, environ, scopes, client):
if request.method == "POST":
if request.post_param("confirm") == "1":
return
diff --git a/docs/examples/resource_owner_grant.py b/docs/examples/resource_owner_grant.py
index 16d7990..d539ee6 100644
--- a/docs/examples/resource_owner_grant.py
+++ b/docs/examples/resource_owner_grant.py
@@ -157,7 +157,7 @@ class ClientApplication(object):
class TestSiteAdapter(ResourceOwnerGrantSiteAdapter):
- def authenticate(self, request, environ, scopes):
+ def authenticate(self, request, environ, scopes, client):
username = request.post_param("username")
password = request.post_param("password")
# A real world application could connect to a database, try to
diff --git a/docs/examples/tornado_server.py b/docs/examples/tornado_server.py
index 869be94..f9a77b6 100644
--- a/docs/examples/tornado_server.py
+++ b/docs/examples/tornado_server.py
@@ -70,12 +70,12 @@ class TestSiteAdapter(AuthorizationCodeGrantSiteAdapter):
</html>
"""
- def render_auth_page(self, request, response, environ, scopes):
+ def render_auth_page(self, request, response, environ, scopes, client):
response.body = self.CONFIRMATION_TEMPLATE
return response
- def authenticate(self, request, environ, scopes):
+ def authenticate(self, request, environ, scopes, client):
if request.method == "POST":
if request.post_param("confirm") == "1":
return
diff --git a/docs/migration.rst b/docs/migration.rst
index 218db95..c4ccf14 100644
--- a/docs/migration.rst
+++ b/docs/migration.rst
@@ -83,3 +83,32 @@ After:
# Instantiating storage and provider...
app = Application(provider=provider)
+
+
+Client passed to methods authenticate and render_auth_page of a Site Adapter
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+Before:
+
+.. code-block:: python
+
+ class ExampleSiteAdapter(AuthenticatingSiteAdapter, UserFacingSiteAdapter):
+ def authenticate(self, request, environ, scopes):
+ # code
+
+ def render_auth_page(self, request, response, environ, scopes):
+ # code
+
+
+After:
+
+.. code-block:: python
+
+ class ExampleSiteAdapter(AuthenticatingSiteAdapter, UserFacingSiteAdapter):
+ def authenticate(self, request, environ, scopes, client):
+ # code
+
+ def render_auth_page(self, request, response, environ, scopes, client):
+ # code
+
+
diff --git a/oauth2/grant.py b/oauth2/grant.py
index a792edd..1407af0 100644
--- a/oauth2/grant.py
+++ b/oauth2/grant.py
@@ -306,12 +306,14 @@ class AuthorizeMixin(object):
explanation="Authorization denied by user")
try:
- result = self.site_adapter.authenticate(request, environ, scopes)
+ result = self.site_adapter.authenticate(request, environ, scopes,
+ self.client)
return self.sanitize_return_value(result)
except UserNotAuthenticated:
return self.site_adapter.render_auth_page(request, response,
- environ, scopes)
+ environ, scopes,
+ self.client)
@staticmethod
def sanitize_return_value(value):
@@ -816,7 +818,8 @@ class ResourceOwnerGrantHandler(GrantHandler, AccessTokenMixin):
"""
try:
data = self.site_adapter.authenticate(request, environ,
- self.scope_handler.scopes)
+ self.scope_handler.scopes,
+ self.client)
data = AuthorizeMixin.sanitize_return_value(data)
except UserNotAuthenticated:
raise OAuthInvalidError(error="invalid_client",
diff --git a/oauth2/web/__init__.py b/oauth2/web/__init__.py
index 279692e..4e98019 100644
--- a/oauth2/web/__init__.py
+++ b/oauth2/web/__init__.py
@@ -6,7 +6,7 @@ class AuthenticatingSiteAdapter(object):
"""
Extended by site adapters that need to authenticate the user.
"""
- def authenticate(self, request, environ, scopes):
+ def authenticate(self, request, environ, scopes, client):
"""
Authenticates a user and checks if she has authorized access.
@@ -20,6 +20,9 @@ class AuthenticatingSiteAdapter(object):
scope.
:type scopes: list
+ :param client: The client that initiated the authorization process
+ :type client: oauth2.datatype.Client
+
:return: A ``dict`` containing arbitrary data that will be passed to
the current storage adapter and saved with auth code and
access token. Return a tuple in the form
@@ -40,7 +43,7 @@ class UserFacingSiteAdapter(object):
Display HTML or redirect the user agent to another page of your website
where she can do something before being returned to the OAuth 2.0 server.
"""
- def render_auth_page(self, request, response, environ, scopes):
+ def render_auth_page(self, request, response, environ, scopes, client):
"""
Defines how to display a confirmation page to the user.
@@ -57,6 +60,9 @@ class UserFacingSiteAdapter(object):
scope.
:type scopes: list
+ :param client: The client that initiated the authorization process
+ :type client: oauth2.datatype.Client
+
:return: The response passed in as a parameter.
It can contain HTML or issue a redirect.
:rtype: oauth2.web.Response
diff --git a/setup.py b/setup.py
index f026e85..4200b67 100644
--- a/setup.py
+++ b/setup.py
@@ -1,3 +1,4 @@
+import os
import sys
from setuptools import setup
@@ -15,8 +16,7 @@ setup(name="python-oauth2",
author="Markus Meyer",
author_email="[email protected]",
url="https://github.com/wndhydrnt/python-oauth2",
- packages=["oauth2", "oauth2.web", "oauth2.store", "oauth2.store.dbapi",
- "oauth2.test"],
+ packages=[d[0].replace("/", ".") for d in os.walk("oauth2") if not d[0].endswith("__pycache__")],
extras_require={
"memcache": [memcache_require],
"mongodb": ["pymongo"],
| New parameter client
**AuthenticatingSiteAdapter.authenticate** and **UserFacingSiteAdapter.render_auth_page** could have a parameter to receive the client retrieved from the store.
In my case, my client table has extra columns that I need to render the authentication page, If I had access to the client object it would be easier.
Thanks! | wndhydrnt/python-oauth2 | diff --git a/oauth2/test/functional/test_authorization_code.py b/oauth2/test/functional/test_authorization_code.py
index 6706ad2..bd2ef3a 100644
--- a/oauth2/test/functional/test_authorization_code.py
+++ b/oauth2/test/functional/test_authorization_code.py
@@ -203,7 +203,7 @@ class AuthorizationCodeTestCase(unittest.TestCase):
class TestSiteAdapter(AuthorizationCodeGrantSiteAdapter):
- def authenticate(self, request, environ, scopes):
+ def authenticate(self, request, environ, scopes, client):
return {"additional": "data"}, 1
def user_has_denied_access(self, request):
diff --git a/oauth2/test/test_grant.py b/oauth2/test/test_grant.py
index e3f80b8..cfbb05b 100644
--- a/oauth2/test/test_grant.py
+++ b/oauth2/test/test_grant.py
@@ -149,6 +149,8 @@ class AuthorizeMixinTestCase(unittest.TestCase):
"""
AuthorizeMixin.authorize should return a tuple even if the SiteAdapter returns a dict
"""
+ client_mock = Mock(spec=Client)
+
test_data = {"test": "data"}
site_adapter_mock = Mock(spec=ImplicitGrantSiteAdapter)
@@ -156,6 +158,7 @@ class AuthorizeMixinTestCase(unittest.TestCase):
site_adapter_mock.authenticate.return_value = test_data
auth_mixin = AuthorizeMixin(site_adapter=site_adapter_mock)
+ auth_mixin.client = client_mock
result = auth_mixin.authorize(Mock(spec=Request), Mock(spec=Response),
environ={}, scopes=[])
@@ -167,6 +170,8 @@ class AuthorizeMixinTestCase(unittest.TestCase):
"""
AuthorizeMixin.authorize should return the tuple returned by the SiteAdapter
"""
+ client_mock = Mock(spec=Client)
+
test_data = ({"test": "data"}, 123)
site_adapter_mock = Mock(spec=ImplicitGrantSiteAdapter)
@@ -174,6 +179,7 @@ class AuthorizeMixinTestCase(unittest.TestCase):
site_adapter_mock.authenticate.return_value = test_data
auth_mixin = AuthorizeMixin(site_adapter=site_adapter_mock)
+ auth_mixin.client = client_mock
result = auth_mixin.authorize(Mock(spec=Request), Mock(spec=Response),
environ={}, scopes=[])
@@ -182,6 +188,8 @@ class AuthorizeMixinTestCase(unittest.TestCase):
self.assertEqual(result[1], test_data[1])
def test_authorize_user_not_authenticated(self):
+ client_mock = Mock(spec=Client)
+
response_mock = Mock(spec=Response)
site_adapter_mock = Mock(spec=ImplicitGrantSiteAdapter)
@@ -190,6 +198,7 @@ class AuthorizeMixinTestCase(unittest.TestCase):
site_adapter_mock.render_auth_page.return_value = response_mock
auth_mixin = AuthorizeMixin(site_adapter=site_adapter_mock)
+ auth_mixin.client = client_mock
result = auth_mixin.authorize(Mock(spec=Request), response_mock,
environ={}, scopes=[])
@@ -209,6 +218,9 @@ class AuthorizationCodeAuthHandlerTestCase(unittest.TestCase):
auth_code_store_mock = Mock(spec=AuthCodeStore)
+ client = Client(identifier="abc", secret="xyz",
+ redirect_uris=[redirect_uri])
+
response_mock = Mock(spec=Response)
request_mock = Mock(spec=Request)
@@ -231,14 +243,14 @@ class AuthorizationCodeAuthHandlerTestCase(unittest.TestCase):
token_generator=token_generator_mock
)
- handler.client = Client(identifier="abc", secret="xyz",
- redirect_uris=[redirect_uri])
+ handler.client = client
handler.state = state
response = handler.process(request_mock, response_mock, environ)
token_generator_mock.generate.assert_called_with()
site_adapter_mock.authenticate.assert_called_with(request_mock,
- environ, scopes)
+ environ, scopes,
+ client)
self.assertTrue(auth_code_store_mock.save_code.called)
self.assertEqual(response.status_code, 302)
self.assertEqual(response.body, "")
@@ -252,6 +264,8 @@ class AuthorizationCodeAuthHandlerTestCase(unittest.TestCase):
response_mock = Mock(spec=Response)
scopes = ["scopes"]
+ client_mock = Mock(spec=Client)
+
request_mock = Mock(spec=Request)
scope_handler_mock = Mock(Scope)
@@ -266,12 +280,14 @@ class AuthorizationCodeAuthHandlerTestCase(unittest.TestCase):
scope_handler=scope_handler_mock, site_adapter=site_adapter_mock,
token_generator=Mock()
)
+ handler.client = client_mock
response = handler.process(request_mock, response_mock, environ)
site_adapter_mock.render_auth_page.assert_called_with(request_mock,
response_mock,
environ,
- scopes)
+ scopes,
+ client_mock)
self.assertEqual(response, response_mock)
def test_redirect_oauth_error(self):
@@ -801,7 +817,6 @@ class ImplicitGrantTestCase(unittest.TestCase):
class ImplicitGrantHandlerTestCase(unittest.TestCase):
def test_process_redirect_with_token(self):
- client_id = "abc"
environ = {"session": "data"}
redirect_uri = "http://callback"
scopes = ["scopes"]
@@ -810,6 +825,9 @@ class ImplicitGrantHandlerTestCase(unittest.TestCase):
access_token_store_mock = Mock(spec=AccessTokenStore)
+ client = Client(identifier="abc", secret="xyz",
+ redirect_uris=[redirect_uri])
+
request_mock = Mock(spec=Request)
responseMock = Mock(spec=Response)
@@ -831,12 +849,12 @@ class ImplicitGrantHandlerTestCase(unittest.TestCase):
client_authenticator=Mock(), scope_handler=scope_handler_mock,
site_adapter=site_adapter_mock,
token_generator=token_generator_mock)
- handler.client = Client(identifier="abc", secret="xyz",
- redirect_uris=[redirect_uri])
+ handler.client = client
result_response = handler.process(request_mock, responseMock, environ)
site_adapter_mock.authenticate.assert_called_with(request_mock,
- environ, scopes)
+ environ, scopes,
+ client)
access_token, = access_token_store_mock.save_token.call_args[0]
self.assertTrue(isinstance(access_token, AccessToken))
@@ -934,6 +952,8 @@ class ImplicitGrantHandlerTestCase(unittest.TestCase):
scopes = ["scopes"]
environ = {"session": "data"}
+ client_mock = Mock(spec=Client)
+
request_mock = Mock(spec=Request)
response_mock = Mock(spec=Response)
@@ -950,14 +970,17 @@ class ImplicitGrantHandlerTestCase(unittest.TestCase):
scope_handler=scope_handler_mock, site_adapter=site_adapter_mock,
token_generator=Mock()
)
+ handler.client = client_mock
result_response = handler.process(request_mock, response_mock, environ)
site_adapter_mock.authenticate.assert_called_with(request_mock,
- environ, scopes)
+ environ, scopes,
+ client_mock)
site_adapter_mock.render_auth_page.assert_called_with(request_mock,
response_mock,
environ,
- scopes)
+ scopes,
+ client_mock)
self.assertEqual(result_response, response_mock)
def test_process_user_denied_access(self):
@@ -1057,6 +1080,7 @@ class ResourceOwnerGrantTestCase(unittest.TestCase):
class ResourceOwnerGrantHandlerTestCase(unittest.TestCase):
def test_process(self):
access_token = "0aef"
+ client = Client(identifier="abc", secret="xyz")
expected_response_body = {"access_token": access_token,
"token_type": "Bearer"}
scopes = ["scope"]
@@ -1085,11 +1109,11 @@ class ResourceOwnerGrantHandlerTestCase(unittest.TestCase):
scope_handler=scope_handler_mock,
site_adapter=site_adapter_mock,
token_generator=token_generator_mock)
- handler.client = Client(identifier="abc", secret="xyz")
+ handler.client = client
result = handler.process(request_mock, response_mock, {})
site_adapter_mock.authenticate.assert_called_with(request_mock, {},
- scopes)
+ scopes, client)
token_generator_mock.create_access_token_data.assert_called_with(ResourceOwnerGrant.grant_type)
access_token, = access_token_store_mock.save_token.call_args[0]
self.assertTrue(isinstance(access_token, AccessToken))
@@ -1107,6 +1131,7 @@ class ResourceOwnerGrantHandlerTestCase(unittest.TestCase):
@patch("time.time", mock_time)
def test_process_with_refresh_token(self):
access_token = "0aef"
+ client = Client(identifier="abc", secret="xyz")
expected_response_body = {"access_token": access_token,
"token_type": "Bearer",
"refresh_token": "wxyz", "expires_in": 600}
@@ -1138,11 +1163,11 @@ class ResourceOwnerGrantHandlerTestCase(unittest.TestCase):
scope_handler=scope_handler_mock,
site_adapter=site_adapter_mock,
token_generator=token_generator_mock)
- handler.client = Client(identifier="abc", secret="xyz")
+ handler.client = client
result = handler.process(request_mock, response_mock, {})
site_adapter_mock.authenticate.assert_called_with(request_mock, {},
- scopes)
+ scopes, client)
token_generator_mock.create_access_token_data.assert_called_with(ResourceOwnerGrant.grant_type)
access_token, = access_token_store_mock.save_token.call_args[0]
self.assertTrue(isinstance(access_token, AccessToken))
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 2,
"issue_text_score": 0,
"test_score": 0
},
"num_modified_files": 11
} | 0.7 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[dev]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest",
"numpy>=1.16.0",
"pandas>=1.0.0"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.9",
"reqs_path": [
"requirements.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | async-timeout==5.0.1
dnspython==2.7.0
exceptiongroup==1.2.2
iniconfig==2.1.0
mock==5.2.0
mysql-connector-python @ http://dev.mysql.com/get/Downloads/Connector-Python/mysql-connector-python-1.1.7.tar.gz#sha256=66f9aeadf2b908be0e31bf683cfa199c1c13401eb7c0acce7cec56d75d76e24a
nose==1.3.7
numpy==2.0.2
packaging==24.2
pandas==2.2.3
pluggy==1.5.0
pymongo==4.11.3
pytest==8.3.5
python-dateutil==2.9.0.post0
-e git+https://github.com/wndhydrnt/python-oauth2.git@f37a26ccb2a0bd5c6682a798f0e1669d75aacd5a#egg=python_oauth2
pytz==2025.2
redis==5.2.1
six==1.17.0
tomli==2.2.1
tornado==6.4.2
tzdata==2025.2
| name: python-oauth2
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=3.0.16=h5eee18b_0
- pip=25.0=py39h06a4308_0
- python=3.9.21=he870216_1
- readline=8.2=h5eee18b_0
- setuptools=75.8.0=py39h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- wheel=0.45.1=py39h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- async-timeout==5.0.1
- dnspython==2.7.0
- exceptiongroup==1.2.2
- iniconfig==2.1.0
- mock==5.2.0
- mysql-connector-python==1.1.7
- nose==1.3.7
- numpy==2.0.2
- packaging==24.2
- pandas==2.2.3
- pluggy==1.5.0
- pymongo==4.11.3
- pytest==8.3.5
- python-dateutil==2.9.0.post0
- pytz==2025.2
- redis==5.2.1
- six==1.17.0
- tomli==2.2.1
- tornado==6.4.2
- tzdata==2025.2
prefix: /opt/conda/envs/python-oauth2
| [
"oauth2/test/functional/test_authorization_code.py::AuthorizationCodeTestCase::test_tornado",
"oauth2/test/functional/test_authorization_code.py::AuthorizationCodeTestCase::test_wsgi",
"oauth2/test/test_grant.py::AuthorizationCodeAuthHandlerTestCase::test_process",
"oauth2/test/test_grant.py::AuthorizationCodeAuthHandlerTestCase::test_process_not_confirmed",
"oauth2/test/test_grant.py::ImplicitGrantHandlerTestCase::test_process_redirect_with_token",
"oauth2/test/test_grant.py::ImplicitGrantHandlerTestCase::test_process_unconfirmed",
"oauth2/test/test_grant.py::ResourceOwnerGrantHandlerTestCase::test_process",
"oauth2/test/test_grant.py::ResourceOwnerGrantHandlerTestCase::test_process_with_refresh_token"
] | [] | [
"oauth2/test/test_grant.py::AuthorizationCodeGrantTestCase::test_create_auth_handler",
"oauth2/test/test_grant.py::AuthorizationCodeGrantTestCase::test_create_no_match",
"oauth2/test/test_grant.py::AuthorizationCodeGrantTestCase::test_create_token_handler",
"oauth2/test/test_grant.py::AuthRequestMixinTestCase::test_read_validate_params_all_valid",
"oauth2/test/test_grant.py::AuthorizeMixinTestCase::test_authorize_dict_return",
"oauth2/test/test_grant.py::AuthorizeMixinTestCase::test_authorize_tuple_return",
"oauth2/test/test_grant.py::AuthorizeMixinTestCase::test_authorize_user_denied_access",
"oauth2/test/test_grant.py::AuthorizeMixinTestCase::test_authorize_user_not_authenticated",
"oauth2/test/test_grant.py::AuthorizationCodeAuthHandlerTestCase::test_redirect_oauth_error",
"oauth2/test/test_grant.py::AuthorizationCodeTokenHandlerTestCase::test_process_no_refresh_token",
"oauth2/test/test_grant.py::AuthorizationCodeTokenHandlerTestCase::test_process_with_refresh_token",
"oauth2/test/test_grant.py::AuthorizationCodeTokenHandlerTestCase::test_process_with_unique_access_token",
"oauth2/test/test_grant.py::AuthorizationCodeTokenHandlerTestCase::test_process_with_unique_access_token_different_scope",
"oauth2/test/test_grant.py::AuthorizationCodeTokenHandlerTestCase::test_process_with_unique_access_token_expired_token",
"oauth2/test/test_grant.py::AuthorizationCodeTokenHandlerTestCase::test_process_with_unique_access_token_no_user_id",
"oauth2/test/test_grant.py::AuthorizationCodeTokenHandlerTestCase::test_process_with_unique_access_token_not_found",
"oauth2/test/test_grant.py::AuthorizationCodeTokenHandlerTestCase::test_read_validate_params",
"oauth2/test/test_grant.py::AuthorizationCodeTokenHandlerTestCase::test_read_validate_params_missing_code",
"oauth2/test/test_grant.py::AuthorizationCodeTokenHandlerTestCase::test_read_validate_params_no_auth_code_found",
"oauth2/test/test_grant.py::AuthorizationCodeTokenHandlerTestCase::test_read_validate_params_token_expired",
"oauth2/test/test_grant.py::AuthorizationCodeTokenHandlerTestCase::test_read_validate_params_unknown_code",
"oauth2/test/test_grant.py::AuthorizationCodeTokenHandlerTestCase::test_read_validate_params_wrong_redirect_uri_in_code_data",
"oauth2/test/test_grant.py::ImplicitGrantTestCase::test_create_matching_response_type",
"oauth2/test/test_grant.py::ImplicitGrantTestCase::test_create_not_matching_response_type",
"oauth2/test/test_grant.py::ImplicitGrantHandlerTestCase::test_process_redirect_with_state",
"oauth2/test/test_grant.py::ImplicitGrantHandlerTestCase::test_process_user_denied_access",
"oauth2/test/test_grant.py::ImplicitGrantHandlerTestCase::test_process_with_scope",
"oauth2/test/test_grant.py::ImplicitGrantHandlerTestCase::test_redirect_oauth_error",
"oauth2/test/test_grant.py::ResourceOwnerGrantTestCase::test_call",
"oauth2/test/test_grant.py::ResourceOwnerGrantTestCase::test_call_no_resource_request",
"oauth2/test/test_grant.py::ResourceOwnerGrantHandlerTestCase::test_handle_error_owner_not_authenticated",
"oauth2/test/test_grant.py::ResourceOwnerGrantHandlerTestCase::test_process_invalid_user",
"oauth2/test/test_grant.py::ResourceOwnerGrantHandlerTestCase::test_process_redirect_with_scope",
"oauth2/test/test_grant.py::ResourceOwnerGrantHandlerTestCase::test_read_validate_params",
"oauth2/test/test_grant.py::ScopeTestCase::test_compare_invalid_scope_requested",
"oauth2/test/test_grant.py::ScopeTestCase::test_compare_scopes_equal",
"oauth2/test/test_grant.py::ScopeTestCase::test_compare_valid_scope_subset",
"oauth2/test/test_grant.py::ScopeTestCase::test_parse_scope_default_on_no_matching_scopes",
"oauth2/test/test_grant.py::ScopeTestCase::test_parse_scope_default_on_no_scope",
"oauth2/test/test_grant.py::ScopeTestCase::test_parse_scope_exception_on_available_scopes_no_scope_given",
"oauth2/test/test_grant.py::ScopeTestCase::test_parse_scope_no_value_on_no_scope_no_default",
"oauth2/test/test_grant.py::ScopeTestCase::test_parse_scope_scope_present_in_body",
"oauth2/test/test_grant.py::ScopeTestCase::test_parse_scope_scope_present_in_query",
"oauth2/test/test_grant.py::RefreshTokenTestCase::test_call",
"oauth2/test/test_grant.py::RefreshTokenTestCase::test_call_other_grant_type",
"oauth2/test/test_grant.py::RefreshTokenTestCase::test_call_wrong_path",
"oauth2/test/test_grant.py::RefreshTokenHandlerTestCase::test_process_no_reissue",
"oauth2/test/test_grant.py::RefreshTokenHandlerTestCase::test_process_with_reissue",
"oauth2/test/test_grant.py::RefreshTokenHandlerTestCase::test_read_validate_params",
"oauth2/test/test_grant.py::RefreshTokenHandlerTestCase::test_read_validate_params_expired_refresh_token",
"oauth2/test/test_grant.py::RefreshTokenHandlerTestCase::test_read_validate_params_invalid_refresh_token",
"oauth2/test/test_grant.py::RefreshTokenHandlerTestCase::test_read_validate_params_no_refresh_token",
"oauth2/test/test_grant.py::ClientCredentialsGrantTestCase::test_call",
"oauth2/test/test_grant.py::ClientCredentialsGrantTestCase::test_call_other_grant_type",
"oauth2/test/test_grant.py::ClientCredentialsGrantTestCase::test_call_wrong_request_path",
"oauth2/test/test_grant.py::ClientCredentialsHandlerTestCase::test_process",
"oauth2/test/test_grant.py::ClientCredentialsHandlerTestCase::test_process_with_refresh_token",
"oauth2/test/test_grant.py::ClientCredentialsHandlerTestCase::test_read_validate_params"
] | [] | MIT License | 149 |
|
scieloorg__xylose-70 | dfb62b8a662baba1c7563ac7815a1e2f41597b22 | 2015-05-25 20:06:35 | dfb62b8a662baba1c7563ac7815a1e2f41597b22 | diff --git a/setup.py b/setup.py
index 3e2e89c..09e541f 100755
--- a/setup.py
+++ b/setup.py
@@ -7,7 +7,7 @@ except ImportError:
setup(
name="xylose",
- version='0.6b',
+ version='0.7b',
description="A SciELO library to abstract a JSON data structure that is a product of the ISIS2JSON conversion using the ISIS2JSON type 3 data model.",
author="SciELO",
author_email="[email protected]",
diff --git a/xylose/scielodocument.py b/xylose/scielodocument.py
index bed9cfc..a16ee47 100644
--- a/xylose/scielodocument.py
+++ b/xylose/scielodocument.py
@@ -788,8 +788,9 @@ class Article(object):
This method deals with the legacy fields (14).
"""
if 'v14' in self.data['article']:
- if 'f' in self.data['article']['v14'][0]:
- return self.data['article']['v14'][0]['f']
+ for item in self.data['article']['v14']:
+ if 'f' in item:
+ return item['f']
@property
def end_page(self):
@@ -798,8 +799,9 @@ class Article(object):
This method deals with the legacy fields (14).
"""
if 'v14' in self.data['article']:
- if 'l' in self.data['article']['v14'][0]:
- return self.data['article']['v14'][0]['l']
+ for item in self.data['article']['v14']:
+ if 'l' in item:
+ return item['l']
@property
def doi(self):
| Pages com bug na leitura do registro JSON.
Os novos registros quando carregados a partir do XML passaram a vir com uma estrutura de dados diferente do original:
antes:
```
[
{
_: "",
f: "1099",
l: "1101",
}
],
```
depois:
```
[
{
_: "",
f: "1099"
},
{
l: "1101",
_: ""
}
],
```
O Xylose deverá abstrair as duas formas de persistência das páginas. | scieloorg/xylose | diff --git a/tests/test_document.py b/tests/test_document.py
index 5236fdd..71a7da4 100644
--- a/tests/test_document.py
+++ b/tests/test_document.py
@@ -956,6 +956,22 @@ class ArticleTests(unittest.TestCase):
del(article.data['article']['v14'][0]['f'])
self.assertEqual(article.start_page, None)
+ def test_start_page_loaded_through_xml(self):
+ article = self.article
+
+ article.data['article']['v14'] = [
+ {
+ u'_': u'',
+ u'l': u'122'
+ },
+ {
+ u'_': u'',
+ u'f': u'110'
+ }
+ ]
+
+ self.assertEqual(article.start_page, u'110')
+
def test_last_page(self):
article = self.article
@@ -967,6 +983,23 @@ class ArticleTests(unittest.TestCase):
del(article.data['article']['v14'][0]['l'])
self.assertEqual(article.end_page, None)
+ def test_end_page_loaded_through_xml(self):
+ article = self.article
+
+ article.data['article']['v14'] = [
+ {
+ u'_': u'',
+ u'f': u'110'
+ },
+ {
+ u'_': u'',
+ u'l': u'122'
+ }
+ ]
+
+ self.assertEqual(article.end_page, u'122')
+
+
def test_without_pages(self):
article = self.article
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 2,
"issue_text_score": 2,
"test_score": 2
},
"num_modified_files": 2
} | 0.6 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "",
"pip_packages": [
"nose",
"coverage",
"mocker",
"pytest"
],
"pre_install": null,
"python": "3.9",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | coverage==7.8.0
exceptiongroup==1.2.2
iniconfig==2.1.0
mocker==1.1.1
nose==1.3.7
packaging==24.2
pluggy==1.5.0
pytest==8.3.5
tomli==2.2.1
-e git+https://github.com/scieloorg/xylose.git@dfb62b8a662baba1c7563ac7815a1e2f41597b22#egg=xylose
| name: xylose
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=3.0.16=h5eee18b_0
- pip=25.0=py39h06a4308_0
- python=3.9.21=he870216_1
- readline=8.2=h5eee18b_0
- setuptools=75.8.0=py39h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- tzdata=2025a=h04d1e81_0
- wheel=0.45.1=py39h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- coverage==7.8.0
- exceptiongroup==1.2.2
- iniconfig==2.1.0
- mocker==1.1.1
- nose==1.3.7
- packaging==24.2
- pluggy==1.5.0
- pytest==8.3.5
- tomli==2.2.1
prefix: /opt/conda/envs/xylose
| [
"tests/test_document.py::ArticleTests::test_end_page_loaded_through_xml",
"tests/test_document.py::ArticleTests::test_start_page_loaded_through_xml"
] | [] | [
"tests/test_document.py::ToolsTests::test_get_language_iso639_1_defined",
"tests/test_document.py::ToolsTests::test_get_language_iso639_1_undefined",
"tests/test_document.py::ToolsTests::test_get_language_iso639_2_defined",
"tests/test_document.py::ToolsTests::test_get_language_iso639_2_undefined",
"tests/test_document.py::ToolsTests::test_get_language_without_iso_format",
"tests/test_document.py::ToolsTests::test_get_publication_date_wrong_day",
"tests/test_document.py::ToolsTests::test_get_publication_date_wrong_day_month",
"tests/test_document.py::ToolsTests::test_get_publication_date_wrong_day_month_not_int",
"tests/test_document.py::ToolsTests::test_get_publication_date_wrong_day_not_int",
"tests/test_document.py::ToolsTests::test_get_publication_date_wrong_month_not_int",
"tests/test_document.py::ToolsTests::test_get_publication_date_year",
"tests/test_document.py::ToolsTests::test_get_publication_date_year_day",
"tests/test_document.py::ToolsTests::test_get_publication_date_year_month",
"tests/test_document.py::ToolsTests::test_get_publication_date_year_month_day",
"tests/test_document.py::JournalTests::test_any_issn_priority_electronic",
"tests/test_document.py::JournalTests::test_any_issn_priority_electronic_without_electronic",
"tests/test_document.py::JournalTests::test_any_issn_priority_print",
"tests/test_document.py::JournalTests::test_any_issn_priority_print_without_print",
"tests/test_document.py::JournalTests::test_collection_acronym",
"tests/test_document.py::JournalTests::test_creation_date",
"tests/test_document.py::JournalTests::test_current_status",
"tests/test_document.py::JournalTests::test_current_status_lots_of_changes_study_case_1",
"tests/test_document.py::JournalTests::test_current_status_some_changes",
"tests/test_document.py::JournalTests::test_current_without_v51",
"tests/test_document.py::JournalTests::test_journal",
"tests/test_document.py::JournalTests::test_journal_abbreviated_title",
"tests/test_document.py::JournalTests::test_journal_acronym",
"tests/test_document.py::JournalTests::test_journal_title",
"tests/test_document.py::JournalTests::test_journal_title_nlm",
"tests/test_document.py::JournalTests::test_journal_url",
"tests/test_document.py::JournalTests::test_languages",
"tests/test_document.py::JournalTests::test_languages_without_v350",
"tests/test_document.py::JournalTests::test_load_issn_with_v935_and_v35_ONLINE",
"tests/test_document.py::JournalTests::test_load_issn_with_v935_and_v35_PRINT",
"tests/test_document.py::JournalTests::test_load_issn_with_v935_equal_v400_and_v35_ONLINE",
"tests/test_document.py::JournalTests::test_load_issn_with_v935_equal_v400_and_v35_PRINT",
"tests/test_document.py::JournalTests::test_load_issn_with_v935_without_v35",
"tests/test_document.py::JournalTests::test_load_issn_without_v935_and_v35_ONLINE",
"tests/test_document.py::JournalTests::test_load_issn_without_v935_and_v35_PRINT",
"tests/test_document.py::JournalTests::test_load_issn_without_v935_without_v35",
"tests/test_document.py::JournalTests::test_permission_id",
"tests/test_document.py::JournalTests::test_permission_text",
"tests/test_document.py::JournalTests::test_permission_url",
"tests/test_document.py::JournalTests::test_permission_without_v540",
"tests/test_document.py::JournalTests::test_permission_without_v540_t",
"tests/test_document.py::JournalTests::test_publisher_loc",
"tests/test_document.py::JournalTests::test_publisher_name",
"tests/test_document.py::JournalTests::test_scielo_issn",
"tests/test_document.py::JournalTests::test_status",
"tests/test_document.py::JournalTests::test_status_lots_of_changes",
"tests/test_document.py::JournalTests::test_status_lots_of_changes_study_case_1",
"tests/test_document.py::JournalTests::test_status_some_changes",
"tests/test_document.py::JournalTests::test_status_without_v51",
"tests/test_document.py::JournalTests::test_subject_areas",
"tests/test_document.py::JournalTests::test_update_date",
"tests/test_document.py::JournalTests::test_without_journal_abbreviated_title",
"tests/test_document.py::JournalTests::test_without_journal_acronym",
"tests/test_document.py::JournalTests::test_without_journal_title",
"tests/test_document.py::JournalTests::test_without_journal_title_nlm",
"tests/test_document.py::JournalTests::test_without_journal_url",
"tests/test_document.py::JournalTests::test_without_publisher_loc",
"tests/test_document.py::JournalTests::test_without_publisher_name",
"tests/test_document.py::JournalTests::test_without_scielo_domain",
"tests/test_document.py::JournalTests::test_without_scielo_domain_title_v690",
"tests/test_document.py::JournalTests::test_without_subject_areas",
"tests/test_document.py::JournalTests::test_without_wos_citation_indexes",
"tests/test_document.py::JournalTests::test_without_wos_subject_areas",
"tests/test_document.py::JournalTests::test_wos_citation_indexes",
"tests/test_document.py::JournalTests::test_wos_subject_areas",
"tests/test_document.py::ArticleTests::test_acceptance_date",
"tests/test_document.py::ArticleTests::test_affiliation_just_with_affiliation_name",
"tests/test_document.py::ArticleTests::test_affiliation_without_affiliation_name",
"tests/test_document.py::ArticleTests::test_affiliations",
"tests/test_document.py::ArticleTests::test_ahead_publication_date",
"tests/test_document.py::ArticleTests::test_article",
"tests/test_document.py::ArticleTests::test_author_with_two_affiliations",
"tests/test_document.py::ArticleTests::test_author_with_two_role",
"tests/test_document.py::ArticleTests::test_author_without_affiliations",
"tests/test_document.py::ArticleTests::test_author_without_surname_and_given_names",
"tests/test_document.py::ArticleTests::test_authors",
"tests/test_document.py::ArticleTests::test_collection_acronym",
"tests/test_document.py::ArticleTests::test_collection_acronym_priorizing_collection",
"tests/test_document.py::ArticleTests::test_collection_acronym_retrieving_v992",
"tests/test_document.py::ArticleTests::test_collection_name_brazil",
"tests/test_document.py::ArticleTests::test_collection_name_undefined",
"tests/test_document.py::ArticleTests::test_corporative_authors",
"tests/test_document.py::ArticleTests::test_document_type",
"tests/test_document.py::ArticleTests::test_doi",
"tests/test_document.py::ArticleTests::test_file_code",
"tests/test_document.py::ArticleTests::test_file_code_crazy_slashs_1",
"tests/test_document.py::ArticleTests::test_file_code_crazy_slashs_2",
"tests/test_document.py::ArticleTests::test_first_author",
"tests/test_document.py::ArticleTests::test_first_author_without_author",
"tests/test_document.py::ArticleTests::test_fulltexts_field_fulltexts",
"tests/test_document.py::ArticleTests::test_fulltexts_without_field_fulltexts",
"tests/test_document.py::ArticleTests::test_html_url",
"tests/test_document.py::ArticleTests::test_invalid_document_type",
"tests/test_document.py::ArticleTests::test_issue",
"tests/test_document.py::ArticleTests::test_issue_label_field_v4",
"tests/test_document.py::ArticleTests::test_issue_label_without_field_v4",
"tests/test_document.py::ArticleTests::test_issue_url",
"tests/test_document.py::ArticleTests::test_journal_abbreviated_title",
"tests/test_document.py::ArticleTests::test_journal_acronym",
"tests/test_document.py::ArticleTests::test_journal_title",
"tests/test_document.py::ArticleTests::test_keywords",
"tests/test_document.py::ArticleTests::test_keywords_iso639_2",
"tests/test_document.py::ArticleTests::test_keywords_with_undefined_language",
"tests/test_document.py::ArticleTests::test_keywords_without_subfield_k",
"tests/test_document.py::ArticleTests::test_keywords_without_subfield_l",
"tests/test_document.py::ArticleTests::test_languages_field_fulltexts",
"tests/test_document.py::ArticleTests::test_languages_field_v40",
"tests/test_document.py::ArticleTests::test_last_page",
"tests/test_document.py::ArticleTests::test_mixed_affiliations",
"tests/test_document.py::ArticleTests::test_normalized_affiliations",
"tests/test_document.py::ArticleTests::test_normalized_affiliations_undefined_ISO_3166_CODE",
"tests/test_document.py::ArticleTests::test_normalized_affiliations_without_p",
"tests/test_document.py::ArticleTests::test_original_abstract_with_just_one_language_defined",
"tests/test_document.py::ArticleTests::test_original_abstract_with_language_defined",
"tests/test_document.py::ArticleTests::test_original_abstract_with_language_defined_but_different_of_the_article_original_language",
"tests/test_document.py::ArticleTests::test_original_abstract_without_language_defined",
"tests/test_document.py::ArticleTests::test_original_language_invalid_iso639_2",
"tests/test_document.py::ArticleTests::test_original_language_iso639_2",
"tests/test_document.py::ArticleTests::test_original_language_original",
"tests/test_document.py::ArticleTests::test_original_title_with_just_one_language_defined",
"tests/test_document.py::ArticleTests::test_original_title_with_language_defined",
"tests/test_document.py::ArticleTests::test_original_title_with_language_defined_but_different_of_the_article_original_language",
"tests/test_document.py::ArticleTests::test_original_title_without_language_defined",
"tests/test_document.py::ArticleTests::test_pdf_url",
"tests/test_document.py::ArticleTests::test_processing_date",
"tests/test_document.py::ArticleTests::test_project_name",
"tests/test_document.py::ArticleTests::test_project_sponsors",
"tests/test_document.py::ArticleTests::test_publication_contract",
"tests/test_document.py::ArticleTests::test_publication_date",
"tests/test_document.py::ArticleTests::test_publisher_id",
"tests/test_document.py::ArticleTests::test_publisher_loc",
"tests/test_document.py::ArticleTests::test_publisher_name",
"tests/test_document.py::ArticleTests::test_receive_date",
"tests/test_document.py::ArticleTests::test_review_date",
"tests/test_document.py::ArticleTests::test_start_page",
"tests/test_document.py::ArticleTests::test_subject_areas",
"tests/test_document.py::ArticleTests::test_supplement_issue",
"tests/test_document.py::ArticleTests::test_supplement_volume",
"tests/test_document.py::ArticleTests::test_thesis_degree",
"tests/test_document.py::ArticleTests::test_thesis_organization",
"tests/test_document.py::ArticleTests::test_thesis_organization_and_division",
"tests/test_document.py::ArticleTests::test_thesis_organization_without_name",
"tests/test_document.py::ArticleTests::test_translated_abstracts",
"tests/test_document.py::ArticleTests::test_translated_abstracts_without_v83",
"tests/test_document.py::ArticleTests::test_translated_abtracts_iso639_2",
"tests/test_document.py::ArticleTests::test_translated_titles",
"tests/test_document.py::ArticleTests::test_translated_titles_iso639_2",
"tests/test_document.py::ArticleTests::test_translated_titles_without_v12",
"tests/test_document.py::ArticleTests::test_volume",
"tests/test_document.py::ArticleTests::test_whitwout_acceptance_date",
"tests/test_document.py::ArticleTests::test_whitwout_ahead_publication_date",
"tests/test_document.py::ArticleTests::test_whitwout_receive_date",
"tests/test_document.py::ArticleTests::test_whitwout_review_date",
"tests/test_document.py::ArticleTests::test_without_affiliations",
"tests/test_document.py::ArticleTests::test_without_authors",
"tests/test_document.py::ArticleTests::test_without_citations",
"tests/test_document.py::ArticleTests::test_without_collection_acronym",
"tests/test_document.py::ArticleTests::test_without_corporative_authors",
"tests/test_document.py::ArticleTests::test_without_document_type",
"tests/test_document.py::ArticleTests::test_without_doi",
"tests/test_document.py::ArticleTests::test_without_html_url",
"tests/test_document.py::ArticleTests::test_without_issue",
"tests/test_document.py::ArticleTests::test_without_issue_url",
"tests/test_document.py::ArticleTests::test_without_journal_abbreviated_title",
"tests/test_document.py::ArticleTests::test_without_journal_acronym",
"tests/test_document.py::ArticleTests::test_without_journal_title",
"tests/test_document.py::ArticleTests::test_without_keywords",
"tests/test_document.py::ArticleTests::test_without_last_page",
"tests/test_document.py::ArticleTests::test_without_normalized_affiliations",
"tests/test_document.py::ArticleTests::test_without_original_abstract",
"tests/test_document.py::ArticleTests::test_without_original_title",
"tests/test_document.py::ArticleTests::test_without_pages",
"tests/test_document.py::ArticleTests::test_without_pdf_url",
"tests/test_document.py::ArticleTests::test_without_processing_date",
"tests/test_document.py::ArticleTests::test_without_project_name",
"tests/test_document.py::ArticleTests::test_without_project_sponsor",
"tests/test_document.py::ArticleTests::test_without_publication_contract",
"tests/test_document.py::ArticleTests::test_without_publication_date",
"tests/test_document.py::ArticleTests::test_without_publisher_id",
"tests/test_document.py::ArticleTests::test_without_publisher_loc",
"tests/test_document.py::ArticleTests::test_without_publisher_name",
"tests/test_document.py::ArticleTests::test_without_scielo_domain",
"tests/test_document.py::ArticleTests::test_without_scielo_domain_article_v69",
"tests/test_document.py::ArticleTests::test_without_scielo_domain_article_v69_and_with_title_v690",
"tests/test_document.py::ArticleTests::test_without_scielo_domain_title_v690",
"tests/test_document.py::ArticleTests::test_without_start_page",
"tests/test_document.py::ArticleTests::test_without_subject_areas",
"tests/test_document.py::ArticleTests::test_without_suplement_issue",
"tests/test_document.py::ArticleTests::test_without_supplement_volume",
"tests/test_document.py::ArticleTests::test_without_thesis_degree",
"tests/test_document.py::ArticleTests::test_without_thesis_organization",
"tests/test_document.py::ArticleTests::test_without_volume",
"tests/test_document.py::ArticleTests::test_without_wos_citation_indexes",
"tests/test_document.py::ArticleTests::test_without_wos_subject_areas",
"tests/test_document.py::ArticleTests::test_wos_citation_indexes",
"tests/test_document.py::ArticleTests::test_wos_subject_areas",
"tests/test_document.py::CitationTest::test_a_link_access_date",
"tests/test_document.py::CitationTest::test_analytic_institution_for_a_article_citation",
"tests/test_document.py::CitationTest::test_analytic_institution_for_a_book_citation",
"tests/test_document.py::CitationTest::test_article_title",
"tests/test_document.py::CitationTest::test_article_without_title",
"tests/test_document.py::CitationTest::test_authors_article",
"tests/test_document.py::CitationTest::test_authors_book",
"tests/test_document.py::CitationTest::test_authors_link",
"tests/test_document.py::CitationTest::test_authors_thesis",
"tests/test_document.py::CitationTest::test_book_chapter_title",
"tests/test_document.py::CitationTest::test_book_edition",
"tests/test_document.py::CitationTest::test_book_volume",
"tests/test_document.py::CitationTest::test_book_without_chapter_title",
"tests/test_document.py::CitationTest::test_citation_sample_congress",
"tests/test_document.py::CitationTest::test_citation_sample_link",
"tests/test_document.py::CitationTest::test_citation_sample_link_without_comment",
"tests/test_document.py::CitationTest::test_conference_edition",
"tests/test_document.py::CitationTest::test_conference_name",
"tests/test_document.py::CitationTest::test_conference_sponsor",
"tests/test_document.py::CitationTest::test_conference_without_name",
"tests/test_document.py::CitationTest::test_conference_without_sponsor",
"tests/test_document.py::CitationTest::test_date",
"tests/test_document.py::CitationTest::test_doi",
"tests/test_document.py::CitationTest::test_editor",
"tests/test_document.py::CitationTest::test_end_page_14",
"tests/test_document.py::CitationTest::test_end_page_514",
"tests/test_document.py::CitationTest::test_end_page_withdout_data",
"tests/test_document.py::CitationTest::test_first_author_article",
"tests/test_document.py::CitationTest::test_first_author_book",
"tests/test_document.py::CitationTest::test_first_author_link",
"tests/test_document.py::CitationTest::test_first_author_thesis",
"tests/test_document.py::CitationTest::test_first_author_without_monographic_authors",
"tests/test_document.py::CitationTest::test_first_author_without_monographic_authors_but_not_a_book_citation",
"tests/test_document.py::CitationTest::test_index_number",
"tests/test_document.py::CitationTest::test_institutions_all_fields",
"tests/test_document.py::CitationTest::test_institutions_v11",
"tests/test_document.py::CitationTest::test_institutions_v17",
"tests/test_document.py::CitationTest::test_institutions_v29",
"tests/test_document.py::CitationTest::test_institutions_v50",
"tests/test_document.py::CitationTest::test_institutions_v58",
"tests/test_document.py::CitationTest::test_invalid_edition",
"tests/test_document.py::CitationTest::test_isbn",
"tests/test_document.py::CitationTest::test_isbn_but_not_a_book",
"tests/test_document.py::CitationTest::test_issn",
"tests/test_document.py::CitationTest::test_issn_but_not_an_article",
"tests/test_document.py::CitationTest::test_issue_part",
"tests/test_document.py::CitationTest::test_issue_title",
"tests/test_document.py::CitationTest::test_journal_issue",
"tests/test_document.py::CitationTest::test_journal_volume",
"tests/test_document.py::CitationTest::test_link",
"tests/test_document.py::CitationTest::test_link_title",
"tests/test_document.py::CitationTest::test_link_without_title",
"tests/test_document.py::CitationTest::test_monographic_authors",
"tests/test_document.py::CitationTest::test_monographic_first_author",
"tests/test_document.py::CitationTest::test_pages_14",
"tests/test_document.py::CitationTest::test_pages_514",
"tests/test_document.py::CitationTest::test_pages_withdout_data",
"tests/test_document.py::CitationTest::test_publication_type_article",
"tests/test_document.py::CitationTest::test_publication_type_book",
"tests/test_document.py::CitationTest::test_publication_type_conference",
"tests/test_document.py::CitationTest::test_publication_type_link",
"tests/test_document.py::CitationTest::test_publication_type_thesis",
"tests/test_document.py::CitationTest::test_publication_type_undefined",
"tests/test_document.py::CitationTest::test_publisher",
"tests/test_document.py::CitationTest::test_publisher_address",
"tests/test_document.py::CitationTest::test_publisher_address_without_e",
"tests/test_document.py::CitationTest::test_series_book",
"tests/test_document.py::CitationTest::test_series_but_neither_journal_book_or_conference_citation",
"tests/test_document.py::CitationTest::test_series_conference",
"tests/test_document.py::CitationTest::test_series_journal",
"tests/test_document.py::CitationTest::test_source_book_title",
"tests/test_document.py::CitationTest::test_source_journal",
"tests/test_document.py::CitationTest::test_source_journal_without_journal_title",
"tests/test_document.py::CitationTest::test_sponsor",
"tests/test_document.py::CitationTest::test_start_page_14",
"tests/test_document.py::CitationTest::test_start_page_514",
"tests/test_document.py::CitationTest::test_start_page_withdout_data",
"tests/test_document.py::CitationTest::test_thesis_institution",
"tests/test_document.py::CitationTest::test_thesis_title",
"tests/test_document.py::CitationTest::test_thesis_without_title",
"tests/test_document.py::CitationTest::test_title_when_article_citation",
"tests/test_document.py::CitationTest::test_title_when_conference_citation",
"tests/test_document.py::CitationTest::test_title_when_link_citation",
"tests/test_document.py::CitationTest::test_title_when_thesis_citation",
"tests/test_document.py::CitationTest::test_with_volume_but_not_a_journal_article_neither_a_book",
"tests/test_document.py::CitationTest::test_without_analytic_institution",
"tests/test_document.py::CitationTest::test_without_authors",
"tests/test_document.py::CitationTest::test_without_date",
"tests/test_document.py::CitationTest::test_without_doi",
"tests/test_document.py::CitationTest::test_without_edition",
"tests/test_document.py::CitationTest::test_without_editor",
"tests/test_document.py::CitationTest::test_without_first_author",
"tests/test_document.py::CitationTest::test_without_index_number",
"tests/test_document.py::CitationTest::test_without_institutions",
"tests/test_document.py::CitationTest::test_without_issue",
"tests/test_document.py::CitationTest::test_without_issue_part",
"tests/test_document.py::CitationTest::test_without_issue_title",
"tests/test_document.py::CitationTest::test_without_link",
"tests/test_document.py::CitationTest::test_without_monographic_authors",
"tests/test_document.py::CitationTest::test_without_monographic_authors_but_not_a_book_citation",
"tests/test_document.py::CitationTest::test_without_publisher",
"tests/test_document.py::CitationTest::test_without_publisher_address",
"tests/test_document.py::CitationTest::test_without_series",
"tests/test_document.py::CitationTest::test_without_sponsor",
"tests/test_document.py::CitationTest::test_without_thesis_institution",
"tests/test_document.py::CitationTest::test_without_volume"
] | [] | BSD 2-Clause "Simplified" License | 150 |
|
scieloorg__xylose-72 | 5a22638f77c1428300b0be056387459b9832a42e | 2015-05-25 20:31:06 | 5a22638f77c1428300b0be056387459b9832a42e | diff --git a/setup.py b/setup.py
index 09e541f..e3f1883 100755
--- a/setup.py
+++ b/setup.py
@@ -7,7 +7,7 @@ except ImportError:
setup(
name="xylose",
- version='0.7b',
+ version='0.8b',
description="A SciELO library to abstract a JSON data structure that is a product of the ISIS2JSON conversion using the ISIS2JSON type 3 data model.",
author="SciELO",
author_email="[email protected]",
diff --git a/xylose/scielodocument.py b/xylose/scielodocument.py
index a16ee47..39d94e3 100644
--- a/xylose/scielodocument.py
+++ b/xylose/scielodocument.py
@@ -792,6 +792,12 @@ class Article(object):
if 'f' in item:
return item['f']
+ # if nothing works until now. we will try once more. It's tested.
+
+ pages = sorted(self.data['article']['v14'][0]['_'].split('-'))
+
+ return pages[0] or None
+
@property
def end_page(self):
"""
@@ -803,6 +809,12 @@ class Article(object):
if 'l' in item:
return item['l']
+ # if nothing works until now. we will try once more. It's tested.
+
+ pages = sorted(self.data['article']['v14'][0]['_'].split('-'))
+
+ return pages[-1] or None
+
@property
def doi(self):
"""
| Outra forma de persistir páginas.
Nova forma encontrada de persistir páginas no SciELO.
```
v14: [
{
_: "23-32"
}
]
``` | scieloorg/xylose | diff --git a/tests/test_document.py b/tests/test_document.py
index 71a7da4..a409140 100644
--- a/tests/test_document.py
+++ b/tests/test_document.py
@@ -972,6 +972,28 @@ class ArticleTests(unittest.TestCase):
self.assertEqual(article.start_page, u'110')
+ def test_start_page_loaded_crazy_legacy_way_1(self):
+ article = self.article
+
+ article.data['article']['v14'] = [
+ {
+ u'_': u'110-122',
+ }
+ ]
+
+ self.assertEqual(article.start_page, u'110')
+
+ def test_start_page_loaded_crazy_legacy_way_2(self):
+ article = self.article
+
+ article.data['article']['v14'] = [
+ {
+ u'_': u'122-110',
+ }
+ ]
+
+ self.assertEqual(article.start_page, u'110')
+
def test_last_page(self):
article = self.article
@@ -999,6 +1021,27 @@ class ArticleTests(unittest.TestCase):
self.assertEqual(article.end_page, u'122')
+ def test_end_page_loaded_crazy_legacy_way_1(self):
+ article = self.article
+
+ article.data['article']['v14'] = [
+ {
+ u'_': u'110-122',
+ }
+ ]
+
+ self.assertEqual(article.end_page, u'122')
+
+ def test_end_page_loaded_crazy_legacy_way_2(self):
+ article = self.article
+
+ article.data['article']['v14'] = [
+ {
+ u'_': u'122-110',
+ }
+ ]
+
+ self.assertEqual(article.end_page, u'122')
def test_without_pages(self):
article = self.article
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 0,
"issue_text_score": 3,
"test_score": 3
},
"num_modified_files": 2
} | 0.7 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[dev]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest",
"coverage",
"mocker"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.9",
"reqs_path": [
"requirements/base.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | coverage==7.8.0
exceptiongroup==1.2.2
iniconfig==2.1.0
mocker==1.1.1
packaging==24.2
pluggy==1.5.0
pytest==8.3.5
tomli==2.2.1
-e git+https://github.com/scieloorg/xylose.git@5a22638f77c1428300b0be056387459b9832a42e#egg=xylose
| name: xylose
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=3.0.16=h5eee18b_0
- pip=25.0=py39h06a4308_0
- python=3.9.21=he870216_1
- readline=8.2=h5eee18b_0
- setuptools=75.8.0=py39h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- tzdata=2025a=h04d1e81_0
- wheel=0.45.1=py39h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- coverage==7.8.0
- exceptiongroup==1.2.2
- iniconfig==2.1.0
- mocker==1.1.1
- packaging==24.2
- pluggy==1.5.0
- pytest==8.3.5
- tomli==2.2.1
prefix: /opt/conda/envs/xylose
| [
"tests/test_document.py::ArticleTests::test_end_page_loaded_crazy_legacy_way_1",
"tests/test_document.py::ArticleTests::test_end_page_loaded_crazy_legacy_way_2",
"tests/test_document.py::ArticleTests::test_start_page_loaded_crazy_legacy_way_1",
"tests/test_document.py::ArticleTests::test_start_page_loaded_crazy_legacy_way_2"
] | [] | [
"tests/test_document.py::ToolsTests::test_get_language_iso639_1_defined",
"tests/test_document.py::ToolsTests::test_get_language_iso639_1_undefined",
"tests/test_document.py::ToolsTests::test_get_language_iso639_2_defined",
"tests/test_document.py::ToolsTests::test_get_language_iso639_2_undefined",
"tests/test_document.py::ToolsTests::test_get_language_without_iso_format",
"tests/test_document.py::ToolsTests::test_get_publication_date_wrong_day",
"tests/test_document.py::ToolsTests::test_get_publication_date_wrong_day_month",
"tests/test_document.py::ToolsTests::test_get_publication_date_wrong_day_month_not_int",
"tests/test_document.py::ToolsTests::test_get_publication_date_wrong_day_not_int",
"tests/test_document.py::ToolsTests::test_get_publication_date_wrong_month_not_int",
"tests/test_document.py::ToolsTests::test_get_publication_date_year",
"tests/test_document.py::ToolsTests::test_get_publication_date_year_day",
"tests/test_document.py::ToolsTests::test_get_publication_date_year_month",
"tests/test_document.py::ToolsTests::test_get_publication_date_year_month_day",
"tests/test_document.py::JournalTests::test_any_issn_priority_electronic",
"tests/test_document.py::JournalTests::test_any_issn_priority_electronic_without_electronic",
"tests/test_document.py::JournalTests::test_any_issn_priority_print",
"tests/test_document.py::JournalTests::test_any_issn_priority_print_without_print",
"tests/test_document.py::JournalTests::test_collection_acronym",
"tests/test_document.py::JournalTests::test_creation_date",
"tests/test_document.py::JournalTests::test_current_status",
"tests/test_document.py::JournalTests::test_current_status_lots_of_changes_study_case_1",
"tests/test_document.py::JournalTests::test_current_status_some_changes",
"tests/test_document.py::JournalTests::test_current_without_v51",
"tests/test_document.py::JournalTests::test_journal",
"tests/test_document.py::JournalTests::test_journal_abbreviated_title",
"tests/test_document.py::JournalTests::test_journal_acronym",
"tests/test_document.py::JournalTests::test_journal_title",
"tests/test_document.py::JournalTests::test_journal_title_nlm",
"tests/test_document.py::JournalTests::test_journal_url",
"tests/test_document.py::JournalTests::test_languages",
"tests/test_document.py::JournalTests::test_languages_without_v350",
"tests/test_document.py::JournalTests::test_load_issn_with_v935_and_v35_ONLINE",
"tests/test_document.py::JournalTests::test_load_issn_with_v935_and_v35_PRINT",
"tests/test_document.py::JournalTests::test_load_issn_with_v935_equal_v400_and_v35_ONLINE",
"tests/test_document.py::JournalTests::test_load_issn_with_v935_equal_v400_and_v35_PRINT",
"tests/test_document.py::JournalTests::test_load_issn_with_v935_without_v35",
"tests/test_document.py::JournalTests::test_load_issn_without_v935_and_v35_ONLINE",
"tests/test_document.py::JournalTests::test_load_issn_without_v935_and_v35_PRINT",
"tests/test_document.py::JournalTests::test_load_issn_without_v935_without_v35",
"tests/test_document.py::JournalTests::test_permission_id",
"tests/test_document.py::JournalTests::test_permission_text",
"tests/test_document.py::JournalTests::test_permission_url",
"tests/test_document.py::JournalTests::test_permission_without_v540",
"tests/test_document.py::JournalTests::test_permission_without_v540_t",
"tests/test_document.py::JournalTests::test_publisher_loc",
"tests/test_document.py::JournalTests::test_publisher_name",
"tests/test_document.py::JournalTests::test_scielo_issn",
"tests/test_document.py::JournalTests::test_status",
"tests/test_document.py::JournalTests::test_status_lots_of_changes",
"tests/test_document.py::JournalTests::test_status_lots_of_changes_study_case_1",
"tests/test_document.py::JournalTests::test_status_some_changes",
"tests/test_document.py::JournalTests::test_status_without_v51",
"tests/test_document.py::JournalTests::test_subject_areas",
"tests/test_document.py::JournalTests::test_update_date",
"tests/test_document.py::JournalTests::test_without_journal_abbreviated_title",
"tests/test_document.py::JournalTests::test_without_journal_acronym",
"tests/test_document.py::JournalTests::test_without_journal_title",
"tests/test_document.py::JournalTests::test_without_journal_title_nlm",
"tests/test_document.py::JournalTests::test_without_journal_url",
"tests/test_document.py::JournalTests::test_without_publisher_loc",
"tests/test_document.py::JournalTests::test_without_publisher_name",
"tests/test_document.py::JournalTests::test_without_scielo_domain",
"tests/test_document.py::JournalTests::test_without_scielo_domain_title_v690",
"tests/test_document.py::JournalTests::test_without_subject_areas",
"tests/test_document.py::JournalTests::test_without_wos_citation_indexes",
"tests/test_document.py::JournalTests::test_without_wos_subject_areas",
"tests/test_document.py::JournalTests::test_wos_citation_indexes",
"tests/test_document.py::JournalTests::test_wos_subject_areas",
"tests/test_document.py::ArticleTests::test_acceptance_date",
"tests/test_document.py::ArticleTests::test_affiliation_just_with_affiliation_name",
"tests/test_document.py::ArticleTests::test_affiliation_without_affiliation_name",
"tests/test_document.py::ArticleTests::test_affiliations",
"tests/test_document.py::ArticleTests::test_ahead_publication_date",
"tests/test_document.py::ArticleTests::test_article",
"tests/test_document.py::ArticleTests::test_author_with_two_affiliations",
"tests/test_document.py::ArticleTests::test_author_with_two_role",
"tests/test_document.py::ArticleTests::test_author_without_affiliations",
"tests/test_document.py::ArticleTests::test_author_without_surname_and_given_names",
"tests/test_document.py::ArticleTests::test_authors",
"tests/test_document.py::ArticleTests::test_collection_acronym",
"tests/test_document.py::ArticleTests::test_collection_acronym_priorizing_collection",
"tests/test_document.py::ArticleTests::test_collection_acronym_retrieving_v992",
"tests/test_document.py::ArticleTests::test_collection_name_brazil",
"tests/test_document.py::ArticleTests::test_collection_name_undefined",
"tests/test_document.py::ArticleTests::test_corporative_authors",
"tests/test_document.py::ArticleTests::test_document_type",
"tests/test_document.py::ArticleTests::test_doi",
"tests/test_document.py::ArticleTests::test_end_page_loaded_through_xml",
"tests/test_document.py::ArticleTests::test_file_code",
"tests/test_document.py::ArticleTests::test_file_code_crazy_slashs_1",
"tests/test_document.py::ArticleTests::test_file_code_crazy_slashs_2",
"tests/test_document.py::ArticleTests::test_first_author",
"tests/test_document.py::ArticleTests::test_first_author_without_author",
"tests/test_document.py::ArticleTests::test_fulltexts_field_fulltexts",
"tests/test_document.py::ArticleTests::test_fulltexts_without_field_fulltexts",
"tests/test_document.py::ArticleTests::test_html_url",
"tests/test_document.py::ArticleTests::test_invalid_document_type",
"tests/test_document.py::ArticleTests::test_issue",
"tests/test_document.py::ArticleTests::test_issue_label_field_v4",
"tests/test_document.py::ArticleTests::test_issue_label_without_field_v4",
"tests/test_document.py::ArticleTests::test_issue_url",
"tests/test_document.py::ArticleTests::test_journal_abbreviated_title",
"tests/test_document.py::ArticleTests::test_journal_acronym",
"tests/test_document.py::ArticleTests::test_journal_title",
"tests/test_document.py::ArticleTests::test_keywords",
"tests/test_document.py::ArticleTests::test_keywords_iso639_2",
"tests/test_document.py::ArticleTests::test_keywords_with_undefined_language",
"tests/test_document.py::ArticleTests::test_keywords_without_subfield_k",
"tests/test_document.py::ArticleTests::test_keywords_without_subfield_l",
"tests/test_document.py::ArticleTests::test_languages_field_fulltexts",
"tests/test_document.py::ArticleTests::test_languages_field_v40",
"tests/test_document.py::ArticleTests::test_last_page",
"tests/test_document.py::ArticleTests::test_mixed_affiliations",
"tests/test_document.py::ArticleTests::test_normalized_affiliations",
"tests/test_document.py::ArticleTests::test_normalized_affiliations_undefined_ISO_3166_CODE",
"tests/test_document.py::ArticleTests::test_normalized_affiliations_without_p",
"tests/test_document.py::ArticleTests::test_original_abstract_with_just_one_language_defined",
"tests/test_document.py::ArticleTests::test_original_abstract_with_language_defined",
"tests/test_document.py::ArticleTests::test_original_abstract_with_language_defined_but_different_of_the_article_original_language",
"tests/test_document.py::ArticleTests::test_original_abstract_without_language_defined",
"tests/test_document.py::ArticleTests::test_original_language_invalid_iso639_2",
"tests/test_document.py::ArticleTests::test_original_language_iso639_2",
"tests/test_document.py::ArticleTests::test_original_language_original",
"tests/test_document.py::ArticleTests::test_original_title_with_just_one_language_defined",
"tests/test_document.py::ArticleTests::test_original_title_with_language_defined",
"tests/test_document.py::ArticleTests::test_original_title_with_language_defined_but_different_of_the_article_original_language",
"tests/test_document.py::ArticleTests::test_original_title_without_language_defined",
"tests/test_document.py::ArticleTests::test_pdf_url",
"tests/test_document.py::ArticleTests::test_processing_date",
"tests/test_document.py::ArticleTests::test_project_name",
"tests/test_document.py::ArticleTests::test_project_sponsors",
"tests/test_document.py::ArticleTests::test_publication_contract",
"tests/test_document.py::ArticleTests::test_publication_date",
"tests/test_document.py::ArticleTests::test_publisher_id",
"tests/test_document.py::ArticleTests::test_publisher_loc",
"tests/test_document.py::ArticleTests::test_publisher_name",
"tests/test_document.py::ArticleTests::test_receive_date",
"tests/test_document.py::ArticleTests::test_review_date",
"tests/test_document.py::ArticleTests::test_start_page",
"tests/test_document.py::ArticleTests::test_start_page_loaded_through_xml",
"tests/test_document.py::ArticleTests::test_subject_areas",
"tests/test_document.py::ArticleTests::test_supplement_issue",
"tests/test_document.py::ArticleTests::test_supplement_volume",
"tests/test_document.py::ArticleTests::test_thesis_degree",
"tests/test_document.py::ArticleTests::test_thesis_organization",
"tests/test_document.py::ArticleTests::test_thesis_organization_and_division",
"tests/test_document.py::ArticleTests::test_thesis_organization_without_name",
"tests/test_document.py::ArticleTests::test_translated_abstracts",
"tests/test_document.py::ArticleTests::test_translated_abstracts_without_v83",
"tests/test_document.py::ArticleTests::test_translated_abtracts_iso639_2",
"tests/test_document.py::ArticleTests::test_translated_titles",
"tests/test_document.py::ArticleTests::test_translated_titles_iso639_2",
"tests/test_document.py::ArticleTests::test_translated_titles_without_v12",
"tests/test_document.py::ArticleTests::test_volume",
"tests/test_document.py::ArticleTests::test_whitwout_acceptance_date",
"tests/test_document.py::ArticleTests::test_whitwout_ahead_publication_date",
"tests/test_document.py::ArticleTests::test_whitwout_receive_date",
"tests/test_document.py::ArticleTests::test_whitwout_review_date",
"tests/test_document.py::ArticleTests::test_without_affiliations",
"tests/test_document.py::ArticleTests::test_without_authors",
"tests/test_document.py::ArticleTests::test_without_citations",
"tests/test_document.py::ArticleTests::test_without_collection_acronym",
"tests/test_document.py::ArticleTests::test_without_corporative_authors",
"tests/test_document.py::ArticleTests::test_without_document_type",
"tests/test_document.py::ArticleTests::test_without_doi",
"tests/test_document.py::ArticleTests::test_without_html_url",
"tests/test_document.py::ArticleTests::test_without_issue",
"tests/test_document.py::ArticleTests::test_without_issue_url",
"tests/test_document.py::ArticleTests::test_without_journal_abbreviated_title",
"tests/test_document.py::ArticleTests::test_without_journal_acronym",
"tests/test_document.py::ArticleTests::test_without_journal_title",
"tests/test_document.py::ArticleTests::test_without_keywords",
"tests/test_document.py::ArticleTests::test_without_last_page",
"tests/test_document.py::ArticleTests::test_without_normalized_affiliations",
"tests/test_document.py::ArticleTests::test_without_original_abstract",
"tests/test_document.py::ArticleTests::test_without_original_title",
"tests/test_document.py::ArticleTests::test_without_pages",
"tests/test_document.py::ArticleTests::test_without_pdf_url",
"tests/test_document.py::ArticleTests::test_without_processing_date",
"tests/test_document.py::ArticleTests::test_without_project_name",
"tests/test_document.py::ArticleTests::test_without_project_sponsor",
"tests/test_document.py::ArticleTests::test_without_publication_contract",
"tests/test_document.py::ArticleTests::test_without_publication_date",
"tests/test_document.py::ArticleTests::test_without_publisher_id",
"tests/test_document.py::ArticleTests::test_without_publisher_loc",
"tests/test_document.py::ArticleTests::test_without_publisher_name",
"tests/test_document.py::ArticleTests::test_without_scielo_domain",
"tests/test_document.py::ArticleTests::test_without_scielo_domain_article_v69",
"tests/test_document.py::ArticleTests::test_without_scielo_domain_article_v69_and_with_title_v690",
"tests/test_document.py::ArticleTests::test_without_scielo_domain_title_v690",
"tests/test_document.py::ArticleTests::test_without_start_page",
"tests/test_document.py::ArticleTests::test_without_subject_areas",
"tests/test_document.py::ArticleTests::test_without_suplement_issue",
"tests/test_document.py::ArticleTests::test_without_supplement_volume",
"tests/test_document.py::ArticleTests::test_without_thesis_degree",
"tests/test_document.py::ArticleTests::test_without_thesis_organization",
"tests/test_document.py::ArticleTests::test_without_volume",
"tests/test_document.py::ArticleTests::test_without_wos_citation_indexes",
"tests/test_document.py::ArticleTests::test_without_wos_subject_areas",
"tests/test_document.py::ArticleTests::test_wos_citation_indexes",
"tests/test_document.py::ArticleTests::test_wos_subject_areas",
"tests/test_document.py::CitationTest::test_a_link_access_date",
"tests/test_document.py::CitationTest::test_analytic_institution_for_a_article_citation",
"tests/test_document.py::CitationTest::test_analytic_institution_for_a_book_citation",
"tests/test_document.py::CitationTest::test_article_title",
"tests/test_document.py::CitationTest::test_article_without_title",
"tests/test_document.py::CitationTest::test_authors_article",
"tests/test_document.py::CitationTest::test_authors_book",
"tests/test_document.py::CitationTest::test_authors_link",
"tests/test_document.py::CitationTest::test_authors_thesis",
"tests/test_document.py::CitationTest::test_book_chapter_title",
"tests/test_document.py::CitationTest::test_book_edition",
"tests/test_document.py::CitationTest::test_book_volume",
"tests/test_document.py::CitationTest::test_book_without_chapter_title",
"tests/test_document.py::CitationTest::test_citation_sample_congress",
"tests/test_document.py::CitationTest::test_citation_sample_link",
"tests/test_document.py::CitationTest::test_citation_sample_link_without_comment",
"tests/test_document.py::CitationTest::test_conference_edition",
"tests/test_document.py::CitationTest::test_conference_name",
"tests/test_document.py::CitationTest::test_conference_sponsor",
"tests/test_document.py::CitationTest::test_conference_without_name",
"tests/test_document.py::CitationTest::test_conference_without_sponsor",
"tests/test_document.py::CitationTest::test_date",
"tests/test_document.py::CitationTest::test_doi",
"tests/test_document.py::CitationTest::test_editor",
"tests/test_document.py::CitationTest::test_end_page_14",
"tests/test_document.py::CitationTest::test_end_page_514",
"tests/test_document.py::CitationTest::test_end_page_withdout_data",
"tests/test_document.py::CitationTest::test_first_author_article",
"tests/test_document.py::CitationTest::test_first_author_book",
"tests/test_document.py::CitationTest::test_first_author_link",
"tests/test_document.py::CitationTest::test_first_author_thesis",
"tests/test_document.py::CitationTest::test_first_author_without_monographic_authors",
"tests/test_document.py::CitationTest::test_first_author_without_monographic_authors_but_not_a_book_citation",
"tests/test_document.py::CitationTest::test_index_number",
"tests/test_document.py::CitationTest::test_institutions_all_fields",
"tests/test_document.py::CitationTest::test_institutions_v11",
"tests/test_document.py::CitationTest::test_institutions_v17",
"tests/test_document.py::CitationTest::test_institutions_v29",
"tests/test_document.py::CitationTest::test_institutions_v50",
"tests/test_document.py::CitationTest::test_institutions_v58",
"tests/test_document.py::CitationTest::test_invalid_edition",
"tests/test_document.py::CitationTest::test_isbn",
"tests/test_document.py::CitationTest::test_isbn_but_not_a_book",
"tests/test_document.py::CitationTest::test_issn",
"tests/test_document.py::CitationTest::test_issn_but_not_an_article",
"tests/test_document.py::CitationTest::test_issue_part",
"tests/test_document.py::CitationTest::test_issue_title",
"tests/test_document.py::CitationTest::test_journal_issue",
"tests/test_document.py::CitationTest::test_journal_volume",
"tests/test_document.py::CitationTest::test_link",
"tests/test_document.py::CitationTest::test_link_title",
"tests/test_document.py::CitationTest::test_link_without_title",
"tests/test_document.py::CitationTest::test_monographic_authors",
"tests/test_document.py::CitationTest::test_monographic_first_author",
"tests/test_document.py::CitationTest::test_pages_14",
"tests/test_document.py::CitationTest::test_pages_514",
"tests/test_document.py::CitationTest::test_pages_withdout_data",
"tests/test_document.py::CitationTest::test_publication_type_article",
"tests/test_document.py::CitationTest::test_publication_type_book",
"tests/test_document.py::CitationTest::test_publication_type_conference",
"tests/test_document.py::CitationTest::test_publication_type_link",
"tests/test_document.py::CitationTest::test_publication_type_thesis",
"tests/test_document.py::CitationTest::test_publication_type_undefined",
"tests/test_document.py::CitationTest::test_publisher",
"tests/test_document.py::CitationTest::test_publisher_address",
"tests/test_document.py::CitationTest::test_publisher_address_without_e",
"tests/test_document.py::CitationTest::test_series_book",
"tests/test_document.py::CitationTest::test_series_but_neither_journal_book_or_conference_citation",
"tests/test_document.py::CitationTest::test_series_conference",
"tests/test_document.py::CitationTest::test_series_journal",
"tests/test_document.py::CitationTest::test_source_book_title",
"tests/test_document.py::CitationTest::test_source_journal",
"tests/test_document.py::CitationTest::test_source_journal_without_journal_title",
"tests/test_document.py::CitationTest::test_sponsor",
"tests/test_document.py::CitationTest::test_start_page_14",
"tests/test_document.py::CitationTest::test_start_page_514",
"tests/test_document.py::CitationTest::test_start_page_withdout_data",
"tests/test_document.py::CitationTest::test_thesis_institution",
"tests/test_document.py::CitationTest::test_thesis_title",
"tests/test_document.py::CitationTest::test_thesis_without_title",
"tests/test_document.py::CitationTest::test_title_when_article_citation",
"tests/test_document.py::CitationTest::test_title_when_conference_citation",
"tests/test_document.py::CitationTest::test_title_when_link_citation",
"tests/test_document.py::CitationTest::test_title_when_thesis_citation",
"tests/test_document.py::CitationTest::test_with_volume_but_not_a_journal_article_neither_a_book",
"tests/test_document.py::CitationTest::test_without_analytic_institution",
"tests/test_document.py::CitationTest::test_without_authors",
"tests/test_document.py::CitationTest::test_without_date",
"tests/test_document.py::CitationTest::test_without_doi",
"tests/test_document.py::CitationTest::test_without_edition",
"tests/test_document.py::CitationTest::test_without_editor",
"tests/test_document.py::CitationTest::test_without_first_author",
"tests/test_document.py::CitationTest::test_without_index_number",
"tests/test_document.py::CitationTest::test_without_institutions",
"tests/test_document.py::CitationTest::test_without_issue",
"tests/test_document.py::CitationTest::test_without_issue_part",
"tests/test_document.py::CitationTest::test_without_issue_title",
"tests/test_document.py::CitationTest::test_without_link",
"tests/test_document.py::CitationTest::test_without_monographic_authors",
"tests/test_document.py::CitationTest::test_without_monographic_authors_but_not_a_book_citation",
"tests/test_document.py::CitationTest::test_without_publisher",
"tests/test_document.py::CitationTest::test_without_publisher_address",
"tests/test_document.py::CitationTest::test_without_series",
"tests/test_document.py::CitationTest::test_without_sponsor",
"tests/test_document.py::CitationTest::test_without_thesis_institution",
"tests/test_document.py::CitationTest::test_without_volume"
] | [] | BSD 2-Clause "Simplified" License | 151 |
|
nose-devs__nose2-245 | bf9945309d5118ad4723619452c486593964d1b8 | 2015-05-27 19:59:26 | bbf5897eb1aa224100e86ba594042e4399fd2f5f | landscape-bot: [](https://landscape.io/diff/163690)
Repository health decreased by 0.00% when pulling **[28cda3a](https://github.com/dlax/nose2/commit/28cda3abf4d51b58fd686b0b6c0ff5c46c38f51b) on dlax:generator-exception** into **[bf99453](https://github.com/nose-devs/nose2/commit/bf9945309d5118ad4723619452c486593964d1b8) on nose-devs:master**.
* [1 new problem was found](https://landscape.io/diff/163690) (including 0 errors and 1 code smell).
* [1 problem was fixed](https://landscape.io/diff/163690/fixed) (including 0 errors and 1 code smell).
coveralls:
[](https://coveralls.io/builds/2664738)
Coverage decreased (-0.06%) to 84.25% when pulling **28cda3abf4d51b58fd686b0b6c0ff5c46c38f51b on dlax:generator-exception** into **bf9945309d5118ad4723619452c486593964d1b8 on nose-devs:master**.
coveralls:
[](https://coveralls.io/builds/2664738)
Coverage decreased (-0.06%) to 84.25% when pulling **28cda3abf4d51b58fd686b0b6c0ff5c46c38f51b on dlax:generator-exception** into **bf9945309d5118ad4723619452c486593964d1b8 on nose-devs:master**.
landscape-bot: [](https://landscape.io/diff/163709)
Repository health increased by 0.07% when pulling **[ce05d05](https://github.com/dlax/nose2/commit/ce05d05f4ed1d9bb60cade4ccdb031637385585b) on dlax:generator-exception** into **[bf99453](https://github.com/nose-devs/nose2/commit/bf9945309d5118ad4723619452c486593964d1b8) on nose-devs:master**.
* No new problems were introduced.
* [1 problem was fixed](https://landscape.io/diff/163709/fixed) (including 0 errors and 1 code smell).
coveralls:
[](https://coveralls.io/builds/2664909)
Coverage increased (+0.02%) to 84.32% when pulling **ce05d05f4ed1d9bb60cade4ccdb031637385585b on dlax:generator-exception** into **bf9945309d5118ad4723619452c486593964d1b8 on nose-devs:master**.
dlax: Hmm, this does not actually fixes #48 completly since the exception context is not forwarded down to the test failure. Will work further on this...
dlax: Pushed a new version.
coveralls:
[](https://coveralls.io/builds/2668668)
Coverage decreased (-2.57%) to 81.73% when pulling **778265de7a289dda9ab9755ba2c08c89642b80ac on dlax:generator-exception** into **bf9945309d5118ad4723619452c486593964d1b8 on nose-devs:master**.
landscape-bot: [](https://landscape.io/diff/164010)
Code quality remained the same when pulling **[778265d](https://github.com/dlax/nose2/commit/778265de7a289dda9ab9755ba2c08c89642b80ac) on dlax:generator-exception** into **[bf99453](https://github.com/nose-devs/nose2/commit/bf9945309d5118ad4723619452c486593964d1b8) on nose-devs:master**. | diff --git a/nose2/loader.py b/nose2/loader.py
index 2778280..394899f 100644
--- a/nose2/loader.py
+++ b/nose2/loader.py
@@ -7,6 +7,8 @@
import logging
import traceback
+import six
+
from nose2 import events
from nose2.compat import unittest
@@ -114,7 +116,11 @@ class PluggableTestLoader(object):
def _makeFailedTest(self, classname, methodname, exception):
def testFailure(self):
- raise exception
+ if isinstance(exception, Exception):
+ raise exception
+ else:
+ # exception tuple (type, value, traceback)
+ six.reraise(*exception)
attrs = {methodname: testFailure}
TestClass = type(classname, (unittest.TestCase,), attrs)
return self.suiteClass((TestClass(methodname),))
| Loader errors throw away tracebacks and exception detail
For instance if a generator test throws an AttributeError, the details of the attribute error are lost and the user only sees "AttributeError" -- not very helpful. | nose-devs/nose2 | diff --git a/nose2/tests/unit/test_loader.py b/nose2/tests/unit/test_loader.py
index 24114e5..8dc152c 100644
--- a/nose2/tests/unit/test_loader.py
+++ b/nose2/tests/unit/test_loader.py
@@ -8,6 +8,21 @@ class TestPluggableTestLoader(TestCase):
self.session = session.Session()
self.loader = loader.PluggableTestLoader(self.session)
+ def test_failed_load_tests_exception(self):
+ suite = self.loader.failedLoadTests('test', RuntimeError('err'))
+ tc = suite._tests[0]
+ with self.assertRaises(RuntimeError) as cm:
+ tc.test()
+ self.assertEqual(cm.exception.args, ('err', ))
+
+ def test_failed_load_tests_exc_info(self):
+ suite = self.loader.failedLoadTests(
+ 'test', (RuntimeError, RuntimeError('err'), None))
+ tc = suite._tests[0]
+ with self.assertRaises(RuntimeError) as cm:
+ tc.test()
+ self.assertEqual(cm.exception.args, ('err', ))
+
def test_load_from_module_calls_hook(self):
self.session.hooks.register('loadTestsFromModule', FakePlugin())
evt = events.LoadFromModuleEvent(self.loader, 'some_module')
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_short_problem_statement",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 1,
"issue_text_score": 0,
"test_score": 2
},
"num_modified_files": 1
} | 0.5 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"nose2",
"pytest"
],
"pre_install": [],
"python": "3.7",
"reqs_path": [
"requirements.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | certifi @ file:///croot/certifi_1671487769961/work/certifi
cov-core==1.15.0
coverage==7.2.7
exceptiongroup==1.2.2
importlib-metadata==6.7.0
iniconfig==2.0.0
-e git+https://github.com/nose-devs/nose2.git@bf9945309d5118ad4723619452c486593964d1b8#egg=nose2
packaging==24.0
pluggy==1.2.0
pytest==7.4.4
six==1.17.0
tomli==2.0.1
typing_extensions==4.7.1
zipp==3.15.0
| name: nose2
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2022.12.7=py37h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- pip=22.3.1=py37h06a4308_0
- python=3.7.16=h7a1cb2a_0
- readline=8.2=h5eee18b_0
- setuptools=65.6.3=py37h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- wheel=0.38.4=py37h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- cov-core==1.15.0
- coverage==7.2.7
- exceptiongroup==1.2.2
- importlib-metadata==6.7.0
- iniconfig==2.0.0
- packaging==24.0
- pluggy==1.2.0
- pytest==7.4.4
- six==1.17.0
- tomli==2.0.1
- typing-extensions==4.7.1
- zipp==3.15.0
prefix: /opt/conda/envs/nose2
| [
"nose2/tests/unit/test_loader.py::TestPluggableTestLoader::test_failed_load_tests_exc_info"
] | [] | [
"nose2/tests/unit/test_loader.py::TestPluggableTestLoader::test_failed_load_tests_exception",
"nose2/tests/unit/test_loader.py::TestPluggableTestLoader::test_load_from_module_calls_hook",
"nose2/tests/unit/test_loader.py::TestPluggableTestLoader::test_load_from_name_calls_hook",
"nose2/tests/unit/test_loader.py::TestPluggableTestLoader::test_load_from_names_calls_hook",
"nose2/tests/unit/test_loader.py::TestPluggableTestLoader::test_loader_from_names_calls_module_hook",
"nose2/tests/unit/test_loader.py::TestPluggableTestLoader::test_loader_from_names_calls_name_hook",
"nose2/tests/unit/test_loader.py::TestPluggableTestLoader::test_loader_from_names_calls_names_hook"
] | [] | BSD | 152 |
docker-tow__tow-62 | 08473f45c43a0f0f6a63e811266c4f1d746ff78a | 2015-05-29 12:55:52 | 08473f45c43a0f0f6a63e811266c4f1d746ff78a | diff --git a/tow/commands/build.py b/tow/commands/build.py
index f072ae0..9343554 100644
--- a/tow/commands/build.py
+++ b/tow/commands/build.py
@@ -31,11 +31,17 @@ class BuildCommand(Command):
# Check if you would like to patch Dockerfile in order to use
# reconfiguration on run phase
if namespace.tow_run:
+ command = []
(entrypoint, cmd) = dockerfile.find_entrypoint_or_cmd()
+ if cmd:
+ command += cmd
+ if entrypoint:
+ command = entrypoint + command
+ command.append("$@")
templates.process_template("tow.sh.tmpl",
os.path.join(workingdir, "tow.sh"),
- {"entrypoint": entrypoint,
- "cmd": cmd, "mapping": file_mapping,
+ {"command": command,
+ "mapping": file_mapping,
"volume_name": TOW_VOLUME})
file_mapping.append(("tow.sh", "/tow.sh", 755))
dockerfile.replace_entrypoint_or_cmd_by_tow_cmd("sh /tow.sh")
diff --git a/tow/dockerfile.py b/tow/dockerfile.py
index afd1290..7d15b2f 100644
--- a/tow/dockerfile.py
+++ b/tow/dockerfile.py
@@ -60,9 +60,9 @@ class Dockerfile(object):
# Handle array command
if command.startswith("[") and command.endswith("]"):
command = command[1:-1]
- return " ".join([sh.strip()[1:-1] for sh in command.split(",")])
+ return [sh.strip()[1:-1] for sh in command.split(",")]
else: # It's just shell notation
- return command.strip()
+ return [command.strip()]
return None
def envs(self):
diff --git a/tow/templates/tow.sh.tmpl b/tow/templates/tow.sh.tmpl
index 64d612f..9cf076b 100644
--- a/tow/templates/tow.sh.tmpl
+++ b/tow/templates/tow.sh.tmpl
@@ -7,12 +7,4 @@ fi
PATH=$PATH:`pwd`
-{% if entrypoint %}
-{% if cmd %}
-"{{entrypoint}}" "{{cmd}}" "$@"
-{% else %}
-"{{entrypoint}}" "$@"
-{% endif %}
-{% else %}
-"{{cmd}}"
-{% endif %}
+{% for cmd in command -%}"{{ cmd }}" {% endfor %}
| CMD and ENTRYPOINT arrays should stay arrays in tow.sh
```Dockerfile
ENTRYPOINT ["test"]
CMD ["arg1", "arg2"]
```
should be converted to tow.sh
```bash
"test" "arg1" "arg2" "$@"
```
but not to
```bash
"test" "arg1 arg2" "$@"
``` | docker-tow/tow | diff --git a/tests/dockerfile_tests.py b/tests/dockerfile_tests.py
index 160b5f1..00f563a 100644
--- a/tests/dockerfile_tests.py
+++ b/tests/dockerfile_tests.py
@@ -61,22 +61,22 @@ class DockerfileTest(unittest.TestCase):
def test_find_entrypoint_or_cmd(self):
d = Dockerfile("Dockerfile")
d._Dockerfile__dockerfile = ['FROM ubuntu', 'ENTRYPOINT ["/bin/sh"]', 'CMD ["-c"]']
- self.assertEqual(d.find_entrypoint_or_cmd(), ("/bin/sh", "-c"))
+ self.assertEqual(d.find_entrypoint_or_cmd(), (["/bin/sh"], ["-c"]))
def test_find_entrypoint_or_cmd_shell_style(self):
d = Dockerfile("Dockerfile")
d._Dockerfile__dockerfile = ['FROM ubuntu', 'ENTRYPOINT /bin/sh', 'CMD ["-c"]']
- self.assertEqual(d.find_entrypoint_or_cmd(), ("/bin/sh", "-c"))
+ self.assertEqual(d.find_entrypoint_or_cmd(), (["/bin/sh"], ["-c"]))
def test_find_entrypoint_or_cmd_cmd_only(self):
d = Dockerfile("Dockerfile")
d._Dockerfile__dockerfile = ['FROM ubuntu', 'CMD ["/bin/sh", "-c", "-x"]']
- self.assertEqual(d.find_entrypoint_or_cmd(), (None, "/bin/sh -c -x"))
+ self.assertEqual(d.find_entrypoint_or_cmd(), (None, ["/bin/sh", "-c", "-x"]))
def test_find_entrypoint_or_cmd_entrypoint_only(self):
d = Dockerfile("Dockerfile")
d._Dockerfile__dockerfile = ['FROM ubuntu', 'ENTRYPOINT ["/bin/sh"]']
- self.assertEqual(d.find_entrypoint_or_cmd(), ("/bin/sh", None))
+ self.assertEqual(d.find_entrypoint_or_cmd(), (["/bin/sh"], None))
def test_find_entrypoint_or_cmd_none(self):
d = Dockerfile("Dockerfile")
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 2,
"issue_text_score": 0,
"test_score": 0
},
"num_modified_files": 3
} | unknown | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "pytest",
"pip_packages": [
"pytest"
],
"pre_install": null,
"python": "3.9",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | exceptiongroup @ file:///croot/exceptiongroup_1706031385326/work
iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work
Jinja2==3.1.6
MarkupSafe==3.0.2
packaging @ file:///croot/packaging_1734472117206/work
pluggy @ file:///croot/pluggy_1733169602837/work
pytest @ file:///croot/pytest_1738938843180/work
tomli @ file:///opt/conda/conda-bld/tomli_1657175507142/work
-e git+https://github.com/docker-tow/tow.git@08473f45c43a0f0f6a63e811266c4f1d746ff78a#egg=tow
| name: tow
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- exceptiongroup=1.2.0=py39h06a4308_0
- iniconfig=1.1.1=pyhd3eb1b0_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=3.0.16=h5eee18b_0
- packaging=24.2=py39h06a4308_0
- pip=25.0=py39h06a4308_0
- pluggy=1.5.0=py39h06a4308_0
- pytest=8.3.4=py39h06a4308_0
- python=3.9.21=he870216_1
- readline=8.2=h5eee18b_0
- setuptools=75.8.0=py39h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- tomli=2.0.1=py39h06a4308_0
- tzdata=2025a=h04d1e81_0
- wheel=0.45.1=py39h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- jinja2==3.1.6
- markupsafe==3.0.2
prefix: /opt/conda/envs/tow
| [
"tests/dockerfile_tests.py::DockerfileTest::test_find_entrypoint_or_cmd",
"tests/dockerfile_tests.py::DockerfileTest::test_find_entrypoint_or_cmd_cmd_only",
"tests/dockerfile_tests.py::DockerfileTest::test_find_entrypoint_or_cmd_entrypoint_only",
"tests/dockerfile_tests.py::DockerfileTest::test_find_entrypoint_or_cmd_shell_style"
] | [] | [
"tests/dockerfile_tests.py::DockerfileTest::test_add_copy",
"tests/dockerfile_tests.py::DockerfileTest::test_add_copy_after_from",
"tests/dockerfile_tests.py::DockerfileTest::test_add_copy_after_maintainer",
"tests/dockerfile_tests.py::DockerfileTest::test_find_entrypoint_or_cmd_none",
"tests/dockerfile_tests.py::DockerfileTest::test_parse_many_envs",
"tests/dockerfile_tests.py::DockerfileTest::test_parse_multiline",
"tests/dockerfile_tests.py::DockerfileTest::test_parse_spaced_envs"
] | [] | Apache License 2.0 | 153 |
|
scieloorg__xylose-74 | 59090451a1aa5b226666035fc326011f1623c90c | 2015-05-29 20:39:29 | 59090451a1aa5b226666035fc326011f1623c90c | diff --git a/setup.py b/setup.py
index e3f1883..0c97773 100755
--- a/setup.py
+++ b/setup.py
@@ -7,7 +7,7 @@ except ImportError:
setup(
name="xylose",
- version='0.8b',
+ version='0.9b',
description="A SciELO library to abstract a JSON data structure that is a product of the ISIS2JSON conversion using the ISIS2JSON type 3 data model.",
author="SciELO",
author_email="[email protected]",
diff --git a/xylose/scielodocument.py b/xylose/scielodocument.py
index 39d94e3..8e5df08 100644
--- a/xylose/scielodocument.py
+++ b/xylose/scielodocument.py
@@ -27,6 +27,7 @@ else:
LICENSE_REGEX = re.compile(r'a.+href="(.+)"')
LICENSE_CREATIVE_COMMONS = re.compile(r'licenses/(.*)/.') # Extracts the creative commons id from the url.
+DOI_REGEX = re.compile(r'\d{2}\.\d+/.*$')
def html_decode(string):
@@ -820,11 +821,22 @@ class Article(object):
"""
This method retrieves the DOI of the given article, if it exists.
"""
+ raw_doi = None
+
if 'doi' in self.data:
- return self.data['doi']
+ raw_doi = self.data['doi']
if 'v237' in self.data['article']:
- return self.data['article']['v237'][0]['_']
+ raw_doi = self.data['article']['v237'][0]['_']
+
+
+ if not raw_doi:
+ return None
+
+ doi = DOI_REGEX.findall(raw_doi)
+
+ if len(doi) == 1:
+ return doi[0]
@property
def publisher_id(self):
| recuperação de DOI do documento.
Alguns DOI's estão registrados nas bases ISIS incluindo o domínio do crossref.
O Xylose deve remover qualquer conteúdo que não seja para do DOI.
ex:
http://www.crossref.org/10.1590/S2179-975X2012005000004
doi: 10.4322/actalb.02203010
O correto deve ser:
10.1590/S2179-975X2012005000004
10.4322/actalb.02203010
| scieloorg/xylose | diff --git a/tests/test_document.py b/tests/test_document.py
index a409140..4d0af56 100644
--- a/tests/test_document.py
+++ b/tests/test_document.py
@@ -1056,6 +1056,29 @@ class ArticleTests(unittest.TestCase):
self.assertEqual(article.doi, u'10.1590/S2179-975X2012005000004')
+ def test_doi_v237(self):
+ article = self.article
+
+ article.data['article']['v237'] = [{'_': u'10.1590/S2179-975X2012005000004'}]
+
+ self.assertEqual(article.doi, u'10.1590/S2179-975X2012005000004')
+
+
+ def test_doi_clean_1(self):
+ article = self.article
+
+ article.data['doi'] = u'http://www.crossref.org/10.1590/S2179-975X2012005000004'
+
+ self.assertEqual(article.doi, u'10.1590/S2179-975X2012005000004')
+
+
+ def test_doi_clean_2(self):
+ article = self.article
+
+ article.data['doi'] = u'doi: 10.4322/actalb.02203010'
+
+ self.assertEqual(article.doi, u'10.4322/actalb.02203010')
+
def test_without_doi(self):
article = self.article
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_short_problem_statement",
"has_hyperlinks",
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 0,
"issue_text_score": 0,
"test_score": 0
},
"num_modified_files": 2
} | 0.8 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "",
"pip_packages": [
"nose",
"coverage",
"mocker",
"pytest"
],
"pre_install": null,
"python": "3.9",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | coverage==7.8.0
exceptiongroup==1.2.2
iniconfig==2.1.0
mocker==1.1.1
nose==1.3.7
packaging==24.2
pluggy==1.5.0
pytest==8.3.5
tomli==2.2.1
-e git+https://github.com/scieloorg/xylose.git@59090451a1aa5b226666035fc326011f1623c90c#egg=xylose
| name: xylose
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=3.0.16=h5eee18b_0
- pip=25.0=py39h06a4308_0
- python=3.9.21=he870216_1
- readline=8.2=h5eee18b_0
- setuptools=75.8.0=py39h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- tzdata=2025a=h04d1e81_0
- wheel=0.45.1=py39h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- coverage==7.8.0
- exceptiongroup==1.2.2
- iniconfig==2.1.0
- mocker==1.1.1
- nose==1.3.7
- packaging==24.2
- pluggy==1.5.0
- pytest==8.3.5
- tomli==2.2.1
prefix: /opt/conda/envs/xylose
| [
"tests/test_document.py::ArticleTests::test_doi_clean_1",
"tests/test_document.py::ArticleTests::test_doi_clean_2"
] | [] | [
"tests/test_document.py::ToolsTests::test_get_language_iso639_1_defined",
"tests/test_document.py::ToolsTests::test_get_language_iso639_1_undefined",
"tests/test_document.py::ToolsTests::test_get_language_iso639_2_defined",
"tests/test_document.py::ToolsTests::test_get_language_iso639_2_undefined",
"tests/test_document.py::ToolsTests::test_get_language_without_iso_format",
"tests/test_document.py::ToolsTests::test_get_publication_date_wrong_day",
"tests/test_document.py::ToolsTests::test_get_publication_date_wrong_day_month",
"tests/test_document.py::ToolsTests::test_get_publication_date_wrong_day_month_not_int",
"tests/test_document.py::ToolsTests::test_get_publication_date_wrong_day_not_int",
"tests/test_document.py::ToolsTests::test_get_publication_date_wrong_month_not_int",
"tests/test_document.py::ToolsTests::test_get_publication_date_year",
"tests/test_document.py::ToolsTests::test_get_publication_date_year_day",
"tests/test_document.py::ToolsTests::test_get_publication_date_year_month",
"tests/test_document.py::ToolsTests::test_get_publication_date_year_month_day",
"tests/test_document.py::JournalTests::test_any_issn_priority_electronic",
"tests/test_document.py::JournalTests::test_any_issn_priority_electronic_without_electronic",
"tests/test_document.py::JournalTests::test_any_issn_priority_print",
"tests/test_document.py::JournalTests::test_any_issn_priority_print_without_print",
"tests/test_document.py::JournalTests::test_collection_acronym",
"tests/test_document.py::JournalTests::test_creation_date",
"tests/test_document.py::JournalTests::test_current_status",
"tests/test_document.py::JournalTests::test_current_status_lots_of_changes_study_case_1",
"tests/test_document.py::JournalTests::test_current_status_some_changes",
"tests/test_document.py::JournalTests::test_current_without_v51",
"tests/test_document.py::JournalTests::test_journal",
"tests/test_document.py::JournalTests::test_journal_abbreviated_title",
"tests/test_document.py::JournalTests::test_journal_acronym",
"tests/test_document.py::JournalTests::test_journal_title",
"tests/test_document.py::JournalTests::test_journal_title_nlm",
"tests/test_document.py::JournalTests::test_journal_url",
"tests/test_document.py::JournalTests::test_languages",
"tests/test_document.py::JournalTests::test_languages_without_v350",
"tests/test_document.py::JournalTests::test_load_issn_with_v935_and_v35_ONLINE",
"tests/test_document.py::JournalTests::test_load_issn_with_v935_and_v35_PRINT",
"tests/test_document.py::JournalTests::test_load_issn_with_v935_equal_v400_and_v35_ONLINE",
"tests/test_document.py::JournalTests::test_load_issn_with_v935_equal_v400_and_v35_PRINT",
"tests/test_document.py::JournalTests::test_load_issn_with_v935_without_v35",
"tests/test_document.py::JournalTests::test_load_issn_without_v935_and_v35_ONLINE",
"tests/test_document.py::JournalTests::test_load_issn_without_v935_and_v35_PRINT",
"tests/test_document.py::JournalTests::test_load_issn_without_v935_without_v35",
"tests/test_document.py::JournalTests::test_permission_id",
"tests/test_document.py::JournalTests::test_permission_text",
"tests/test_document.py::JournalTests::test_permission_url",
"tests/test_document.py::JournalTests::test_permission_without_v540",
"tests/test_document.py::JournalTests::test_permission_without_v540_t",
"tests/test_document.py::JournalTests::test_publisher_loc",
"tests/test_document.py::JournalTests::test_publisher_name",
"tests/test_document.py::JournalTests::test_scielo_issn",
"tests/test_document.py::JournalTests::test_status",
"tests/test_document.py::JournalTests::test_status_lots_of_changes",
"tests/test_document.py::JournalTests::test_status_lots_of_changes_study_case_1",
"tests/test_document.py::JournalTests::test_status_some_changes",
"tests/test_document.py::JournalTests::test_status_without_v51",
"tests/test_document.py::JournalTests::test_subject_areas",
"tests/test_document.py::JournalTests::test_update_date",
"tests/test_document.py::JournalTests::test_without_journal_abbreviated_title",
"tests/test_document.py::JournalTests::test_without_journal_acronym",
"tests/test_document.py::JournalTests::test_without_journal_title",
"tests/test_document.py::JournalTests::test_without_journal_title_nlm",
"tests/test_document.py::JournalTests::test_without_journal_url",
"tests/test_document.py::JournalTests::test_without_publisher_loc",
"tests/test_document.py::JournalTests::test_without_publisher_name",
"tests/test_document.py::JournalTests::test_without_scielo_domain",
"tests/test_document.py::JournalTests::test_without_scielo_domain_title_v690",
"tests/test_document.py::JournalTests::test_without_subject_areas",
"tests/test_document.py::JournalTests::test_without_wos_citation_indexes",
"tests/test_document.py::JournalTests::test_without_wos_subject_areas",
"tests/test_document.py::JournalTests::test_wos_citation_indexes",
"tests/test_document.py::JournalTests::test_wos_subject_areas",
"tests/test_document.py::ArticleTests::test_acceptance_date",
"tests/test_document.py::ArticleTests::test_affiliation_just_with_affiliation_name",
"tests/test_document.py::ArticleTests::test_affiliation_without_affiliation_name",
"tests/test_document.py::ArticleTests::test_affiliations",
"tests/test_document.py::ArticleTests::test_ahead_publication_date",
"tests/test_document.py::ArticleTests::test_article",
"tests/test_document.py::ArticleTests::test_author_with_two_affiliations",
"tests/test_document.py::ArticleTests::test_author_with_two_role",
"tests/test_document.py::ArticleTests::test_author_without_affiliations",
"tests/test_document.py::ArticleTests::test_author_without_surname_and_given_names",
"tests/test_document.py::ArticleTests::test_authors",
"tests/test_document.py::ArticleTests::test_collection_acronym",
"tests/test_document.py::ArticleTests::test_collection_acronym_priorizing_collection",
"tests/test_document.py::ArticleTests::test_collection_acronym_retrieving_v992",
"tests/test_document.py::ArticleTests::test_collection_name_brazil",
"tests/test_document.py::ArticleTests::test_collection_name_undefined",
"tests/test_document.py::ArticleTests::test_corporative_authors",
"tests/test_document.py::ArticleTests::test_document_type",
"tests/test_document.py::ArticleTests::test_doi",
"tests/test_document.py::ArticleTests::test_doi_v237",
"tests/test_document.py::ArticleTests::test_end_page_loaded_crazy_legacy_way_1",
"tests/test_document.py::ArticleTests::test_end_page_loaded_crazy_legacy_way_2",
"tests/test_document.py::ArticleTests::test_end_page_loaded_through_xml",
"tests/test_document.py::ArticleTests::test_file_code",
"tests/test_document.py::ArticleTests::test_file_code_crazy_slashs_1",
"tests/test_document.py::ArticleTests::test_file_code_crazy_slashs_2",
"tests/test_document.py::ArticleTests::test_first_author",
"tests/test_document.py::ArticleTests::test_first_author_without_author",
"tests/test_document.py::ArticleTests::test_fulltexts_field_fulltexts",
"tests/test_document.py::ArticleTests::test_fulltexts_without_field_fulltexts",
"tests/test_document.py::ArticleTests::test_html_url",
"tests/test_document.py::ArticleTests::test_invalid_document_type",
"tests/test_document.py::ArticleTests::test_issue",
"tests/test_document.py::ArticleTests::test_issue_label_field_v4",
"tests/test_document.py::ArticleTests::test_issue_label_without_field_v4",
"tests/test_document.py::ArticleTests::test_issue_url",
"tests/test_document.py::ArticleTests::test_journal_abbreviated_title",
"tests/test_document.py::ArticleTests::test_journal_acronym",
"tests/test_document.py::ArticleTests::test_journal_title",
"tests/test_document.py::ArticleTests::test_keywords",
"tests/test_document.py::ArticleTests::test_keywords_iso639_2",
"tests/test_document.py::ArticleTests::test_keywords_with_undefined_language",
"tests/test_document.py::ArticleTests::test_keywords_without_subfield_k",
"tests/test_document.py::ArticleTests::test_keywords_without_subfield_l",
"tests/test_document.py::ArticleTests::test_languages_field_fulltexts",
"tests/test_document.py::ArticleTests::test_languages_field_v40",
"tests/test_document.py::ArticleTests::test_last_page",
"tests/test_document.py::ArticleTests::test_mixed_affiliations",
"tests/test_document.py::ArticleTests::test_normalized_affiliations",
"tests/test_document.py::ArticleTests::test_normalized_affiliations_undefined_ISO_3166_CODE",
"tests/test_document.py::ArticleTests::test_normalized_affiliations_without_p",
"tests/test_document.py::ArticleTests::test_original_abstract_with_just_one_language_defined",
"tests/test_document.py::ArticleTests::test_original_abstract_with_language_defined",
"tests/test_document.py::ArticleTests::test_original_abstract_with_language_defined_but_different_of_the_article_original_language",
"tests/test_document.py::ArticleTests::test_original_abstract_without_language_defined",
"tests/test_document.py::ArticleTests::test_original_language_invalid_iso639_2",
"tests/test_document.py::ArticleTests::test_original_language_iso639_2",
"tests/test_document.py::ArticleTests::test_original_language_original",
"tests/test_document.py::ArticleTests::test_original_title_with_just_one_language_defined",
"tests/test_document.py::ArticleTests::test_original_title_with_language_defined",
"tests/test_document.py::ArticleTests::test_original_title_with_language_defined_but_different_of_the_article_original_language",
"tests/test_document.py::ArticleTests::test_original_title_without_language_defined",
"tests/test_document.py::ArticleTests::test_pdf_url",
"tests/test_document.py::ArticleTests::test_processing_date",
"tests/test_document.py::ArticleTests::test_project_name",
"tests/test_document.py::ArticleTests::test_project_sponsors",
"tests/test_document.py::ArticleTests::test_publication_contract",
"tests/test_document.py::ArticleTests::test_publication_date",
"tests/test_document.py::ArticleTests::test_publisher_id",
"tests/test_document.py::ArticleTests::test_publisher_loc",
"tests/test_document.py::ArticleTests::test_publisher_name",
"tests/test_document.py::ArticleTests::test_receive_date",
"tests/test_document.py::ArticleTests::test_review_date",
"tests/test_document.py::ArticleTests::test_start_page",
"tests/test_document.py::ArticleTests::test_start_page_loaded_crazy_legacy_way_1",
"tests/test_document.py::ArticleTests::test_start_page_loaded_crazy_legacy_way_2",
"tests/test_document.py::ArticleTests::test_start_page_loaded_through_xml",
"tests/test_document.py::ArticleTests::test_subject_areas",
"tests/test_document.py::ArticleTests::test_supplement_issue",
"tests/test_document.py::ArticleTests::test_supplement_volume",
"tests/test_document.py::ArticleTests::test_thesis_degree",
"tests/test_document.py::ArticleTests::test_thesis_organization",
"tests/test_document.py::ArticleTests::test_thesis_organization_and_division",
"tests/test_document.py::ArticleTests::test_thesis_organization_without_name",
"tests/test_document.py::ArticleTests::test_translated_abstracts",
"tests/test_document.py::ArticleTests::test_translated_abstracts_without_v83",
"tests/test_document.py::ArticleTests::test_translated_abtracts_iso639_2",
"tests/test_document.py::ArticleTests::test_translated_titles",
"tests/test_document.py::ArticleTests::test_translated_titles_iso639_2",
"tests/test_document.py::ArticleTests::test_translated_titles_without_v12",
"tests/test_document.py::ArticleTests::test_volume",
"tests/test_document.py::ArticleTests::test_whitwout_acceptance_date",
"tests/test_document.py::ArticleTests::test_whitwout_ahead_publication_date",
"tests/test_document.py::ArticleTests::test_whitwout_receive_date",
"tests/test_document.py::ArticleTests::test_whitwout_review_date",
"tests/test_document.py::ArticleTests::test_without_affiliations",
"tests/test_document.py::ArticleTests::test_without_authors",
"tests/test_document.py::ArticleTests::test_without_citations",
"tests/test_document.py::ArticleTests::test_without_collection_acronym",
"tests/test_document.py::ArticleTests::test_without_corporative_authors",
"tests/test_document.py::ArticleTests::test_without_document_type",
"tests/test_document.py::ArticleTests::test_without_doi",
"tests/test_document.py::ArticleTests::test_without_html_url",
"tests/test_document.py::ArticleTests::test_without_issue",
"tests/test_document.py::ArticleTests::test_without_issue_url",
"tests/test_document.py::ArticleTests::test_without_journal_abbreviated_title",
"tests/test_document.py::ArticleTests::test_without_journal_acronym",
"tests/test_document.py::ArticleTests::test_without_journal_title",
"tests/test_document.py::ArticleTests::test_without_keywords",
"tests/test_document.py::ArticleTests::test_without_last_page",
"tests/test_document.py::ArticleTests::test_without_normalized_affiliations",
"tests/test_document.py::ArticleTests::test_without_original_abstract",
"tests/test_document.py::ArticleTests::test_without_original_title",
"tests/test_document.py::ArticleTests::test_without_pages",
"tests/test_document.py::ArticleTests::test_without_pdf_url",
"tests/test_document.py::ArticleTests::test_without_processing_date",
"tests/test_document.py::ArticleTests::test_without_project_name",
"tests/test_document.py::ArticleTests::test_without_project_sponsor",
"tests/test_document.py::ArticleTests::test_without_publication_contract",
"tests/test_document.py::ArticleTests::test_without_publication_date",
"tests/test_document.py::ArticleTests::test_without_publisher_id",
"tests/test_document.py::ArticleTests::test_without_publisher_loc",
"tests/test_document.py::ArticleTests::test_without_publisher_name",
"tests/test_document.py::ArticleTests::test_without_scielo_domain",
"tests/test_document.py::ArticleTests::test_without_scielo_domain_article_v69",
"tests/test_document.py::ArticleTests::test_without_scielo_domain_article_v69_and_with_title_v690",
"tests/test_document.py::ArticleTests::test_without_scielo_domain_title_v690",
"tests/test_document.py::ArticleTests::test_without_start_page",
"tests/test_document.py::ArticleTests::test_without_subject_areas",
"tests/test_document.py::ArticleTests::test_without_suplement_issue",
"tests/test_document.py::ArticleTests::test_without_supplement_volume",
"tests/test_document.py::ArticleTests::test_without_thesis_degree",
"tests/test_document.py::ArticleTests::test_without_thesis_organization",
"tests/test_document.py::ArticleTests::test_without_volume",
"tests/test_document.py::ArticleTests::test_without_wos_citation_indexes",
"tests/test_document.py::ArticleTests::test_without_wos_subject_areas",
"tests/test_document.py::ArticleTests::test_wos_citation_indexes",
"tests/test_document.py::ArticleTests::test_wos_subject_areas",
"tests/test_document.py::CitationTest::test_a_link_access_date",
"tests/test_document.py::CitationTest::test_analytic_institution_for_a_article_citation",
"tests/test_document.py::CitationTest::test_analytic_institution_for_a_book_citation",
"tests/test_document.py::CitationTest::test_article_title",
"tests/test_document.py::CitationTest::test_article_without_title",
"tests/test_document.py::CitationTest::test_authors_article",
"tests/test_document.py::CitationTest::test_authors_book",
"tests/test_document.py::CitationTest::test_authors_link",
"tests/test_document.py::CitationTest::test_authors_thesis",
"tests/test_document.py::CitationTest::test_book_chapter_title",
"tests/test_document.py::CitationTest::test_book_edition",
"tests/test_document.py::CitationTest::test_book_volume",
"tests/test_document.py::CitationTest::test_book_without_chapter_title",
"tests/test_document.py::CitationTest::test_citation_sample_congress",
"tests/test_document.py::CitationTest::test_citation_sample_link",
"tests/test_document.py::CitationTest::test_citation_sample_link_without_comment",
"tests/test_document.py::CitationTest::test_conference_edition",
"tests/test_document.py::CitationTest::test_conference_name",
"tests/test_document.py::CitationTest::test_conference_sponsor",
"tests/test_document.py::CitationTest::test_conference_without_name",
"tests/test_document.py::CitationTest::test_conference_without_sponsor",
"tests/test_document.py::CitationTest::test_date",
"tests/test_document.py::CitationTest::test_doi",
"tests/test_document.py::CitationTest::test_editor",
"tests/test_document.py::CitationTest::test_end_page_14",
"tests/test_document.py::CitationTest::test_end_page_514",
"tests/test_document.py::CitationTest::test_end_page_withdout_data",
"tests/test_document.py::CitationTest::test_first_author_article",
"tests/test_document.py::CitationTest::test_first_author_book",
"tests/test_document.py::CitationTest::test_first_author_link",
"tests/test_document.py::CitationTest::test_first_author_thesis",
"tests/test_document.py::CitationTest::test_first_author_without_monographic_authors",
"tests/test_document.py::CitationTest::test_first_author_without_monographic_authors_but_not_a_book_citation",
"tests/test_document.py::CitationTest::test_index_number",
"tests/test_document.py::CitationTest::test_institutions_all_fields",
"tests/test_document.py::CitationTest::test_institutions_v11",
"tests/test_document.py::CitationTest::test_institutions_v17",
"tests/test_document.py::CitationTest::test_institutions_v29",
"tests/test_document.py::CitationTest::test_institutions_v50",
"tests/test_document.py::CitationTest::test_institutions_v58",
"tests/test_document.py::CitationTest::test_invalid_edition",
"tests/test_document.py::CitationTest::test_isbn",
"tests/test_document.py::CitationTest::test_isbn_but_not_a_book",
"tests/test_document.py::CitationTest::test_issn",
"tests/test_document.py::CitationTest::test_issn_but_not_an_article",
"tests/test_document.py::CitationTest::test_issue_part",
"tests/test_document.py::CitationTest::test_issue_title",
"tests/test_document.py::CitationTest::test_journal_issue",
"tests/test_document.py::CitationTest::test_journal_volume",
"tests/test_document.py::CitationTest::test_link",
"tests/test_document.py::CitationTest::test_link_title",
"tests/test_document.py::CitationTest::test_link_without_title",
"tests/test_document.py::CitationTest::test_monographic_authors",
"tests/test_document.py::CitationTest::test_monographic_first_author",
"tests/test_document.py::CitationTest::test_pages_14",
"tests/test_document.py::CitationTest::test_pages_514",
"tests/test_document.py::CitationTest::test_pages_withdout_data",
"tests/test_document.py::CitationTest::test_publication_type_article",
"tests/test_document.py::CitationTest::test_publication_type_book",
"tests/test_document.py::CitationTest::test_publication_type_conference",
"tests/test_document.py::CitationTest::test_publication_type_link",
"tests/test_document.py::CitationTest::test_publication_type_thesis",
"tests/test_document.py::CitationTest::test_publication_type_undefined",
"tests/test_document.py::CitationTest::test_publisher",
"tests/test_document.py::CitationTest::test_publisher_address",
"tests/test_document.py::CitationTest::test_publisher_address_without_e",
"tests/test_document.py::CitationTest::test_series_book",
"tests/test_document.py::CitationTest::test_series_but_neither_journal_book_or_conference_citation",
"tests/test_document.py::CitationTest::test_series_conference",
"tests/test_document.py::CitationTest::test_series_journal",
"tests/test_document.py::CitationTest::test_source_book_title",
"tests/test_document.py::CitationTest::test_source_journal",
"tests/test_document.py::CitationTest::test_source_journal_without_journal_title",
"tests/test_document.py::CitationTest::test_sponsor",
"tests/test_document.py::CitationTest::test_start_page_14",
"tests/test_document.py::CitationTest::test_start_page_514",
"tests/test_document.py::CitationTest::test_start_page_withdout_data",
"tests/test_document.py::CitationTest::test_thesis_institution",
"tests/test_document.py::CitationTest::test_thesis_title",
"tests/test_document.py::CitationTest::test_thesis_without_title",
"tests/test_document.py::CitationTest::test_title_when_article_citation",
"tests/test_document.py::CitationTest::test_title_when_conference_citation",
"tests/test_document.py::CitationTest::test_title_when_link_citation",
"tests/test_document.py::CitationTest::test_title_when_thesis_citation",
"tests/test_document.py::CitationTest::test_with_volume_but_not_a_journal_article_neither_a_book",
"tests/test_document.py::CitationTest::test_without_analytic_institution",
"tests/test_document.py::CitationTest::test_without_authors",
"tests/test_document.py::CitationTest::test_without_date",
"tests/test_document.py::CitationTest::test_without_doi",
"tests/test_document.py::CitationTest::test_without_edition",
"tests/test_document.py::CitationTest::test_without_editor",
"tests/test_document.py::CitationTest::test_without_first_author",
"tests/test_document.py::CitationTest::test_without_index_number",
"tests/test_document.py::CitationTest::test_without_institutions",
"tests/test_document.py::CitationTest::test_without_issue",
"tests/test_document.py::CitationTest::test_without_issue_part",
"tests/test_document.py::CitationTest::test_without_issue_title",
"tests/test_document.py::CitationTest::test_without_link",
"tests/test_document.py::CitationTest::test_without_monographic_authors",
"tests/test_document.py::CitationTest::test_without_monographic_authors_but_not_a_book_citation",
"tests/test_document.py::CitationTest::test_without_publisher",
"tests/test_document.py::CitationTest::test_without_publisher_address",
"tests/test_document.py::CitationTest::test_without_series",
"tests/test_document.py::CitationTest::test_without_sponsor",
"tests/test_document.py::CitationTest::test_without_thesis_institution",
"tests/test_document.py::CitationTest::test_without_volume"
] | [] | BSD 2-Clause "Simplified" License | 154 |
|
eve-val__evelink-212 | db9e7bfeef9478a047f4f7db4f88324e185e4873 | 2015-06-01 04:28:15 | 4061903e92787ce22eddb75b3776c407fb70837b | diff --git a/evelink/char.py b/evelink/char.py
index 609d76d..0514dc6 100644
--- a/evelink/char.py
+++ b/evelink/char.py
@@ -137,7 +137,7 @@ class Char(object):
"""Get a list of PI routing entries for a character's planet."""
return api.APIResult(parse_planetary_routes(api_result.result), api_result.timestamp, api_result.expires)
- @auto_call('char/KillLog', map_params={'before_kill': 'beforeKillID'})
+ @auto_call('char/KillMails', map_params={'before_kill': 'beforeKillID'})
def kills(self, before_kill=None, api_result=None):
"""Look up recent kills for a character.
@@ -147,6 +147,19 @@ class Char(object):
return api.APIResult(parse_kills(api_result.result), api_result.timestamp, api_result.expires)
+ @auto_call('char/KillLog', map_params={'before_kill': 'beforeKillID'})
+ def kill_log(self, before_kill=None, api_result=None):
+ """Look up recent kills for a character.
+
+ Note: this method uses the long cache version of the endpoint. If you
+ want to use the short cache version (recommended), use kills().
+
+ before_kill:
+ Optional. Only show kills before this kill id. (Used for paging.)
+ """
+
+ return api.APIResult(parse_kills(api_result.result), api_result.timestamp, api_result.expires)
+
@auto_call('char/Notifications')
def notifications(self, api_result=None):
"""Returns the message headers for notifications."""
diff --git a/evelink/corp.py b/evelink/corp.py
index 5e98fcc..ebf1133 100644
--- a/evelink/corp.py
+++ b/evelink/corp.py
@@ -136,7 +136,7 @@ class Corp(object):
return api.APIResult(results, api_result.timestamp, api_result.expires)
- @api.auto_call('corp/KillLog', map_params={'before_kill': 'beforeKillID'})
+ @api.auto_call('corp/KillMails', map_params={'before_kill': 'beforeKillID'})
def kills(self, before_kill=None, api_result=None):
"""Look up recent kills for a corporation.
@@ -146,6 +146,19 @@ class Corp(object):
return api.APIResult(parse_kills(api_result.result), api_result.timestamp, api_result.expires)
+ @api.auto_call('corp/KillLog', map_params={'before_kill': 'beforeKillID'})
+ def kill_log(self, before_kill=None, api_result=None):
+ """Look up recent kills for a corporation.
+
+ Note: this method uses the long cache version of the endpoint. If you
+ want to use the short cache version (recommended), use kills().
+
+ before_kill:
+ Optional. Only show kills before this kill id. (Used for paging.)
+ """
+
+ return api.APIResult(parse_kills(api_result.result), api_result.timestamp, api_result.expires)
+
@api.auto_call('corp/AccountBalance')
def wallet_info(self, api_result=None):
"""Get information about corp wallets."""
| kills() uses KillLog rather than KillMails
KillLog is a long cache endpoint, so you can only query it once.
KillMails isn't a long cache, so you can query it as often as you want. | eve-val/evelink | diff --git a/tests/test_char.py b/tests/test_char.py
index ca37666..64e3631 100644
--- a/tests/test_char.py
+++ b/tests/test_char.py
@@ -291,6 +291,23 @@ class CharTestCase(APITestCase):
self.assertEqual(current, 12345)
self.assertEqual(expires, 67890)
+ self.assertEqual(result, mock.sentinel.kills)
+ self.assertEqual(self.api.mock_calls, [
+ mock.call.get('char/KillMails', params={'characterID': 1}),
+ ])
+ self.assertEqual(mock_parse.mock_calls, [
+ mock.call(mock.sentinel.api_result),
+ ])
+
+ @mock.patch('evelink.char.parse_kills')
+ def test_kill_log(self, mock_parse):
+ self.api.get.return_value = API_RESULT_SENTINEL
+ mock_parse.return_value = mock.sentinel.kills
+
+ result, current, expires = self.char.kill_log()
+ self.assertEqual(current, 12345)
+ self.assertEqual(expires, 67890)
+
self.assertEqual(result, mock.sentinel.kills)
self.assertEqual(self.api.mock_calls, [
mock.call.get('char/KillLog', params={'characterID': 1}),
@@ -304,7 +321,7 @@ class CharTestCase(APITestCase):
self.char.kills(before_kill=12345)
self.assertEqual(self.api.mock_calls, [
- mock.call.get('char/KillLog', params={'characterID': 1, 'beforeKillID': 12345}),
+ mock.call.get('char/KillMails', params={'characterID': 1, 'beforeKillID': 12345}),
])
def test_character_sheet(self):
diff --git a/tests/test_corp.py b/tests/test_corp.py
index 0e96533..5738401 100644
--- a/tests/test_corp.py
+++ b/tests/test_corp.py
@@ -165,6 +165,23 @@ class CorpTestCase(APITestCase):
result, current, expires = self.corp.kills()
+ self.assertEqual(result, mock.sentinel.kills)
+ self.assertEqual(self.api.mock_calls, [
+ mock.call.get('corp/KillMails', params={}),
+ ])
+ self.assertEqual(mock_parse.mock_calls, [
+ mock.call(mock.sentinel.api_result),
+ ])
+ self.assertEqual(current, 12345)
+ self.assertEqual(expires, 67890)
+
+ @mock.patch('evelink.corp.parse_kills')
+ def test_kill_log(self, mock_parse):
+ self.api.get.return_value = API_RESULT_SENTINEL
+ mock_parse.return_value = mock.sentinel.kills
+
+ result, current, expires = self.corp.kill_log()
+
self.assertEqual(result, mock.sentinel.kills)
self.assertEqual(self.api.mock_calls, [
mock.call.get('corp/KillLog', params={}),
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 1,
"issue_text_score": 1,
"test_score": 2
},
"num_modified_files": 2
} | 0.6 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"mock",
"nose",
"pytest"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.9",
"reqs_path": [
"requirements_py3.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | certifi==2025.1.31
charset-normalizer==3.4.1
-e git+https://github.com/eve-val/evelink.git@db9e7bfeef9478a047f4f7db4f88324e185e4873#egg=EVELink
exceptiongroup==1.2.2
idna==3.10
iniconfig==2.1.0
mock==1.0b1
nose==1.1.2
packaging==24.2
pluggy==1.5.0
pytest==8.3.5
requests==2.32.3
six==1.17.0
tomli==2.2.1
urllib3==2.3.0
| name: evelink
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=3.0.16=h5eee18b_0
- pip=25.0=py39h06a4308_0
- python=3.9.21=he870216_1
- readline=8.2=h5eee18b_0
- setuptools=75.8.0=py39h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- tzdata=2025a=h04d1e81_0
- wheel=0.45.1=py39h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- argparse==1.4.0
- certifi==2025.1.31
- charset-normalizer==3.4.1
- exceptiongroup==1.2.2
- idna==3.10
- iniconfig==2.1.0
- mock==1.0b1
- nose==1.1.2
- packaging==24.2
- pluggy==1.5.0
- pytest==8.3.5
- requests==2.32.3
- six==1.17.0
- tomli==2.2.1
- urllib3==2.3.0
prefix: /opt/conda/envs/evelink
| [
"tests/test_char.py::CharTestCase::test_kill_log",
"tests/test_char.py::CharTestCase::test_kills",
"tests/test_char.py::CharTestCase::test_kills_paged",
"tests/test_corp.py::CorpTestCase::test_kill_log",
"tests/test_corp.py::CorpTestCase::test_kills"
] | [] | [
"tests/test_char.py::CharTestCase::test_assets",
"tests/test_char.py::CharTestCase::test_blueprints",
"tests/test_char.py::CharTestCase::test_calendar_attendees",
"tests/test_char.py::CharTestCase::test_calendar_events",
"tests/test_char.py::CharTestCase::test_character_sheet",
"tests/test_char.py::CharTestCase::test_contact_notifications",
"tests/test_char.py::CharTestCase::test_contacts",
"tests/test_char.py::CharTestCase::test_contract_bids",
"tests/test_char.py::CharTestCase::test_contract_items",
"tests/test_char.py::CharTestCase::test_contracts",
"tests/test_char.py::CharTestCase::test_current_training",
"tests/test_char.py::CharTestCase::test_event_attendees",
"tests/test_char.py::CharTestCase::test_faction_warfare_stats",
"tests/test_char.py::CharTestCase::test_industry_jobs",
"tests/test_char.py::CharTestCase::test_industry_jobs_history",
"tests/test_char.py::CharTestCase::test_locations",
"tests/test_char.py::CharTestCase::test_mailing_lists",
"tests/test_char.py::CharTestCase::test_medals",
"tests/test_char.py::CharTestCase::test_message_bodies",
"tests/test_char.py::CharTestCase::test_messages",
"tests/test_char.py::CharTestCase::test_notification_texts",
"tests/test_char.py::CharTestCase::test_notifications",
"tests/test_char.py::CharTestCase::test_orders",
"tests/test_char.py::CharTestCase::test_planetary_colonies",
"tests/test_char.py::CharTestCase::test_planetary_links",
"tests/test_char.py::CharTestCase::test_planetary_pins",
"tests/test_char.py::CharTestCase::test_planetary_routes",
"tests/test_char.py::CharTestCase::test_research",
"tests/test_char.py::CharTestCase::test_skill_queue",
"tests/test_char.py::CharTestCase::test_standings",
"tests/test_char.py::CharTestCase::test_wallet_balance",
"tests/test_char.py::CharTestCase::test_wallet_info",
"tests/test_char.py::CharTestCase::test_wallet_journal",
"tests/test_char.py::CharTestCase::test_wallet_limit",
"tests/test_char.py::CharTestCase::test_wallet_paged",
"tests/test_char.py::CharTestCase::test_wallet_transactions_limit",
"tests/test_char.py::CharTestCase::test_wallet_transactions_paged",
"tests/test_char.py::CharTestCase::test_wallet_transcations",
"tests/test_corp.py::CorpTestCase::test_assets",
"tests/test_corp.py::CorpTestCase::test_blueprints",
"tests/test_corp.py::CorpTestCase::test_contacts",
"tests/test_corp.py::CorpTestCase::test_container_log",
"tests/test_corp.py::CorpTestCase::test_contract_bids",
"tests/test_corp.py::CorpTestCase::test_contract_items",
"tests/test_corp.py::CorpTestCase::test_contracts",
"tests/test_corp.py::CorpTestCase::test_corporation_sheet",
"tests/test_corp.py::CorpTestCase::test_corporation_sheet_public",
"tests/test_corp.py::CorpTestCase::test_customs_offices",
"tests/test_corp.py::CorpTestCase::test_facilities",
"tests/test_corp.py::CorpTestCase::test_faction_warfare_stats",
"tests/test_corp.py::CorpTestCase::test_industry_jobs",
"tests/test_corp.py::CorpTestCase::test_industry_jobs_history",
"tests/test_corp.py::CorpTestCase::test_locations",
"tests/test_corp.py::CorpTestCase::test_medals",
"tests/test_corp.py::CorpTestCase::test_member_medals",
"tests/test_corp.py::CorpTestCase::test_members",
"tests/test_corp.py::CorpTestCase::test_members_not_extended",
"tests/test_corp.py::CorpTestCase::test_npc_standings",
"tests/test_corp.py::CorpTestCase::test_orders",
"tests/test_corp.py::CorpTestCase::test_permissions",
"tests/test_corp.py::CorpTestCase::test_permissions_log",
"tests/test_corp.py::CorpTestCase::test_shareholders",
"tests/test_corp.py::CorpTestCase::test_starbase_details",
"tests/test_corp.py::CorpTestCase::test_starbases",
"tests/test_corp.py::CorpTestCase::test_station_services",
"tests/test_corp.py::CorpTestCase::test_stations",
"tests/test_corp.py::CorpTestCase::test_titles",
"tests/test_corp.py::CorpTestCase::test_wallet_info",
"tests/test_corp.py::CorpTestCase::test_wallet_journal",
"tests/test_corp.py::CorpTestCase::test_wallet_journal_account_key",
"tests/test_corp.py::CorpTestCase::test_wallet_journal_limit",
"tests/test_corp.py::CorpTestCase::test_wallet_journal_paged",
"tests/test_corp.py::CorpTestCase::test_wallet_transactions_account_key",
"tests/test_corp.py::CorpTestCase::test_wallet_transactions_limit",
"tests/test_corp.py::CorpTestCase::test_wallet_transactions_paged",
"tests/test_corp.py::CorpTestCase::test_wallet_transcations"
] | [] | MIT License | 155 |
|
pre-commit__pre-commit-239 | 1c46446427ab0dfa6293221426b855420533ef8d | 2015-06-02 19:44:23 | 5791d84236d82f8aa8609c3ff1c69a991d8c6607 | coveralls:
[](https://coveralls.io/builds/2711896)
Coverage decreased (-0.03%) to 99.97% when pulling **971060d4b9756a9d102e5bb3ee4d04027d35011c on Lucas-C:master** into **1c46446427ab0dfa6293221426b855420533ef8d on pre-commit:master**.
asottile: ++ thanks for the quick code! I was going to get to this later but you beat me to it! test-n-ship | diff --git a/pre_commit/commands/autoupdate.py b/pre_commit/commands/autoupdate.py
index 1a24b09..9e1e79f 100644
--- a/pre_commit/commands/autoupdate.py
+++ b/pre_commit/commands/autoupdate.py
@@ -8,6 +8,7 @@ from aspy.yaml import ordered_load
import pre_commit.constants as C
from pre_commit.clientlib.validate_config import CONFIG_JSON_SCHEMA
+from pre_commit.clientlib.validate_config import is_local_hooks
from pre_commit.clientlib.validate_config import load_config
from pre_commit.jsonschema_extensions import remove_defaults
from pre_commit.ordereddict import OrderedDict
@@ -67,6 +68,8 @@ def autoupdate(runner):
)
for repo_config in input_configs:
+ if is_local_hooks(repo_config):
+ continue
sys.stdout.write('Updating {0}...'.format(repo_config['repo']))
sys.stdout.flush()
try:
diff --git a/pre_commit/repository.py b/pre_commit/repository.py
index 71cc356..83a3c01 100644
--- a/pre_commit/repository.py
+++ b/pre_commit/repository.py
@@ -125,9 +125,8 @@ class Repository(object):
class LocalRepository(Repository):
- def __init__(self, repo_config, repo_path_getter=None):
- repo_path_getter = None
- super(LocalRepository, self).__init__(repo_config, repo_path_getter)
+ def __init__(self, repo_config):
+ super(LocalRepository, self).__init__(repo_config, None)
@cached_property
def hooks(self):
| pre-commit autoupdate fails on `local` hooks repos
```
$ pre-commit autoupdate
Updating [email protected]:pre-commit/pre-commit-hooks...updating 9ce45609a92f648c87b42207410386fd69a5d1e5 -> cf550fcab3f12015f8676b8278b30e1a5bc10e70.
Updating [email protected]:pre-commit/pre-commit...updating 4352d45451296934bc17494073b82bcacca3205c -> 1c46446427ab0dfa6293221426b855420533ef8d.
Updating [email protected]:asottile/reorder_python_imports...updating aeda21eb7df6af8c9f6cd990abb086375c71c953 -> 3d86483455ab5bd06cc1069fdd5ac57be5463f10.
Updating local...An unexpected error has occurred: AttributeError: 'NoneType' object has no attribute 'repo_path'
Check the log at ~/.pre-commit/pre-commit.log
(venv-pre_commit)asottile@work:~/workspace/pre-commit$ cat ~/.pre-commit/pre-commit.log
An unexpected error has occurred: AttributeError: 'NoneType' object has no attribute 'repo_path'
Traceback (most recent call last):
File "/home/asottile/workspace/pre-commit/pre_commit/error_handler.py", line 34, in error_handler
yield
File "/home/asottile/workspace/pre-commit/pre_commit/main.py", line 142, in main
return autoupdate(runner)
File "/home/asottile/workspace/pre-commit/pre_commit/commands/autoupdate.py", line 73, in autoupdate
new_repo_config = _update_repository(repo_config, runner)
File "/home/asottile/workspace/pre-commit/pre_commit/commands/autoupdate.py", line 33, in _update_repository
with cwd(repo.repo_path_getter.repo_path):
AttributeError: 'NoneType' object has no attribute 'repo_path'
(venv-pre_commit)asottile@work:~/workspace/pre-commit$ git diff
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml
index 397ee72..20393a7 100644
--- a/.pre-commit-config.yaml
+++ b/.pre-commit-config.yaml
@@ -20,3 +20,10 @@
sha: aeda21eb7df6af8c9f6cd990abb086375c71c953
hooks:
- id: reorder-python-imports
+- repo: local
+ hooks:
+ - id: herp
+ name: Herp
+ entry: echo derp
+ language: system
+ files: ^$
``` | pre-commit/pre-commit | diff --git a/testing/fixtures.py b/testing/fixtures.py
index 1c0184a..820a72b 100644
--- a/testing/fixtures.py
+++ b/testing/fixtures.py
@@ -35,6 +35,19 @@ def make_repo(tmpdir_factory, repo_source):
return path
+def config_with_local_hooks():
+ return OrderedDict((
+ ('repo', 'local'),
+ ('hooks', [OrderedDict((
+ ('id', 'do_not_commit'),
+ ('name', 'Block if "DO NOT COMMIT" is found'),
+ ('entry', 'DO NOT COMMIT'),
+ ('language', 'pcre'),
+ ('files', '^(.*)$'),
+ ))])
+ ))
+
+
def make_config_from_repo(repo_path, sha=None, hooks=None, check=True):
manifest = load_manifest(os.path.join(repo_path, C.MANIFEST_FILE))
config = OrderedDict((
diff --git a/tests/commands/autoupdate_test.py b/tests/commands/autoupdate_test.py
index 5dbc439..771e67b 100644
--- a/tests/commands/autoupdate_test.py
+++ b/tests/commands/autoupdate_test.py
@@ -13,6 +13,9 @@ from pre_commit.runner import Runner
from pre_commit.util import cmd_output
from pre_commit.util import cwd
from testing.auto_namedtuple import auto_namedtuple
+from testing.fixtures import add_config_to_repo
+from testing.fixtures import config_with_local_hooks
+from testing.fixtures import git_dir
from testing.fixtures import make_config_from_repo
from testing.fixtures import make_repo
from testing.fixtures import write_config
@@ -137,3 +140,10 @@ def test_autoupdate_hook_disappearing_repo(
after = open(C.CONFIG_FILE).read()
assert ret == 1
assert before == after
+
+
+def test_autoupdate_local_hooks(tmpdir_factory):
+ git_path = git_dir(tmpdir_factory)
+ config = config_with_local_hooks()
+ path = add_config_to_repo(git_path, config)
+ assert autoupdate(Runner(path)) == 0
diff --git a/tests/repository_test.py b/tests/repository_test.py
index f2e8850..e7ad227 100644
--- a/tests/repository_test.py
+++ b/tests/repository_test.py
@@ -12,10 +12,10 @@ from pre_commit.clientlib.validate_config import CONFIG_JSON_SCHEMA
from pre_commit.clientlib.validate_config import validate_config_extra
from pre_commit.jsonschema_extensions import apply_defaults
from pre_commit.languages.python import PythonEnv
-from pre_commit.ordereddict import OrderedDict
from pre_commit.repository import Repository
from pre_commit.util import cmd_output
from pre_commit.util import cwd
+from testing.fixtures import config_with_local_hooks
from testing.fixtures import git_dir
from testing.fixtures import make_config_from_repo
from testing.fixtures import make_repo
@@ -404,16 +404,7 @@ def test_tags_on_repositories(in_tmpdir, tmpdir_factory, store):
def test_local_repository():
- config = OrderedDict((
- ('repo', 'local'),
- ('hooks', [OrderedDict((
- ('id', 'do_not_commit'),
- ('name', 'Block if "DO NOT COMMIT" is found'),
- ('entry', 'DO NOT COMMIT'),
- ('language', 'pcre'),
- ('files', '^(.*)$'),
- ))])
- ))
+ config = config_with_local_hooks()
local_repo = Repository.create(config, 'dummy')
with pytest.raises(NotImplementedError):
local_repo.sha
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_git_commit_hash",
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 1,
"issue_text_score": 0,
"test_score": 3
},
"num_modified_files": 2
} | 0.5 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[dev]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.5",
"reqs_path": [
"requirements-dev.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | aspy.yaml==1.3.0
astroid==1.3.2
attrs==22.2.0
cached-property==1.5.2
certifi==2021.5.30
coverage==6.2
distlib==0.3.9
filelock==3.4.1
flake8==5.0.4
importlib-metadata==4.8.3
importlib-resources==5.4.0
iniconfig==1.1.1
jsonschema==3.2.0
logilab-common==1.9.7
mccabe==0.7.0
mock==5.2.0
mypy-extensions==1.0.0
nodeenv==1.6.0
ordereddict==1.1
packaging==21.3
platformdirs==2.4.0
pluggy==1.0.0
-e git+https://github.com/pre-commit/pre-commit.git@1c46446427ab0dfa6293221426b855420533ef8d#egg=pre_commit
py==1.11.0
pycodestyle==2.9.1
pyflakes==2.5.0
pylint==1.3.1
pyparsing==3.1.4
pyrsistent==0.18.0
pytest==7.0.1
PyYAML==6.0.1
simplejson==3.20.1
six==1.17.0
tomli==1.2.3
typing_extensions==4.1.1
virtualenv==20.17.1
zipp==3.6.0
| name: pre-commit
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- pip=21.2.2=py36h06a4308_0
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_0
- setuptools=58.0.4=py36h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- argparse==1.4.0
- aspy-yaml==1.3.0
- astroid==1.3.2
- attrs==22.2.0
- cached-property==1.5.2
- coverage==6.2
- distlib==0.3.9
- filelock==3.4.1
- flake8==5.0.4
- importlib-metadata==4.8.3
- importlib-resources==5.4.0
- iniconfig==1.1.1
- jsonschema==3.2.0
- logilab-common==1.9.7
- mccabe==0.7.0
- mock==5.2.0
- mypy-extensions==1.0.0
- nodeenv==1.6.0
- ordereddict==1.1
- packaging==21.3
- platformdirs==2.4.0
- pluggy==1.0.0
- py==1.11.0
- pycodestyle==2.9.1
- pyflakes==2.5.0
- pylint==1.3.1
- pyparsing==3.1.4
- pyrsistent==0.18.0
- pytest==7.0.1
- pyyaml==6.0.1
- simplejson==3.20.1
- six==1.17.0
- tomli==1.2.3
- typing-extensions==4.1.1
- virtualenv==20.17.1
- zipp==3.6.0
prefix: /opt/conda/envs/pre-commit
| [
"tests/commands/autoupdate_test.py::test_autoupdate_local_hooks"
] | [
"tests/commands/autoupdate_test.py::test_up_to_date_repo",
"tests/commands/autoupdate_test.py::test_autoupdate_up_to_date_repo",
"tests/commands/autoupdate_test.py::test_out_of_date_repo",
"tests/commands/autoupdate_test.py::test_autoupdate_out_of_date_repo",
"tests/commands/autoupdate_test.py::test_hook_disppearing_repo_raises",
"tests/commands/autoupdate_test.py::test_autoupdate_hook_disappearing_repo",
"tests/repository_test.py::test_python_hook",
"tests/repository_test.py::test_python_hook_args_with_spaces",
"tests/repository_test.py::test_switch_language_versions_doesnt_clobber",
"tests/repository_test.py::test_versioned_python_hook",
"tests/repository_test.py::test_run_a_node_hook",
"tests/repository_test.py::test_run_versioned_node_hook",
"tests/repository_test.py::test_run_a_ruby_hook",
"tests/repository_test.py::test_run_versioned_ruby_hook",
"tests/repository_test.py::test_system_hook_with_spaces",
"tests/repository_test.py::test_run_a_script_hook",
"tests/repository_test.py::test_run_hook_with_spaced_args",
"tests/repository_test.py::test_pcre_hook_no_match",
"tests/repository_test.py::test_pcre_hook_matching",
"tests/repository_test.py::test_pcre_many_files",
"tests/repository_test.py::test_cwd_of_hook",
"tests/repository_test.py::test_lots_of_files",
"tests/repository_test.py::test_languages",
"tests/repository_test.py::test_reinstall",
"tests/repository_test.py::test_control_c_control_c_on_install",
"tests/repository_test.py::test_really_long_file_paths",
"tests/repository_test.py::test_config_overrides_repo_specifics",
"tests/repository_test.py::test_tags_on_repositories"
] | [
"tests/repository_test.py::test_repo_url",
"tests/repository_test.py::test_sha",
"tests/repository_test.py::test_local_repository"
] | [] | MIT License | 156 |
sympy__sympy-9468 | 3766b9ca505bb3645e81912b3cc883df73c7a32b | 2015-06-04 04:04:15 | 0241b35cae5f2adc04dc37b25f7dc9c5f00bd746 | diff --git a/sympy/matrices/dense.py b/sympy/matrices/dense.py
index 2295100baa..700b96203a 100644
--- a/sympy/matrices/dense.py
+++ b/sympy/matrices/dense.py
@@ -880,7 +880,9 @@ def row_del(self, i):
row
col_del
"""
- self._mat = self._mat[:i*self.cols] + self._mat[(i + 1)*self.cols:]
+ if i < -self.rows or i >= self.rows:
+ raise IndexError("Index out of range: 'i = %s', valid -%s <= i < %s" % (i, self.rows, self.rows))
+ del self._mat[i*self.cols:(i+1)*self.cols]
self.rows -= 1
def col_del(self, i):
@@ -904,6 +906,8 @@ def col_del(self, i):
col
row_del
"""
+ if i < -self.cols or i >= self.cols:
+ raise IndexError("Index out of range: 'i=%s', valid -%s <= i < %s" % (i, self.cols, self.cols))
for j in range(self.rows - 1, -1, -1):
del self._mat[i + j*self.cols]
self.cols -= 1
| Matrix `row_del` and `col_del` should error on out-of-range
Suppose `A` is an `n` by `n` matrix. The following should raise an error for out-of-range:
````
A.row_del(n+1)
A.row_del(-(n+1))
````
See also discussion in #9459. | sympy/sympy | diff --git a/sympy/matrices/tests/test_matrices.py b/sympy/matrices/tests/test_matrices.py
index f5fe30bbc8..01f1472884 100644
--- a/sympy/matrices/tests/test_matrices.py
+++ b/sympy/matrices/tests/test_matrices.py
@@ -2467,3 +2467,28 @@ def test_doit():
a = Matrix([[Add(x,x, evaluate=False)]])
assert a[0] != 2*x
assert a.doit() == Matrix([[2*x]])
+
+def test_issue_9457_9467():
+ # for row_del(index)
+ M = Matrix([[1, 2, 3], [2, 3, 4], [3, 4, 5]])
+ M.row_del(1)
+ assert M == Matrix([[1, 2, 3], [3, 4, 5]])
+ N = Matrix([[1, 2, 3], [2, 3, 4], [3, 4, 5]])
+ N.row_del(-2)
+ assert N == Matrix([[1, 2, 3], [3, 4, 5]])
+ P = Matrix([[1, 2, 3], [2, 3, 4], [3, 4, 5]])
+ raises(IndexError, lambda: P.row_del(10))
+ Q = Matrix([[1, 2, 3], [2, 3, 4], [3, 4, 5]])
+ raises(IndexError, lambda: Q.row_del(-10))
+
+ # for col_del(index)
+ M = Matrix([[1, 2, 3], [2, 3, 4], [3, 4, 5]])
+ M.col_del(1)
+ assert M == Matrix([[1, 3], [2, 4], [3, 5]])
+ N = Matrix([[1, 2, 3], [2, 3, 4], [3, 4, 5]])
+ N.col_del(-2)
+ assert N == Matrix([[1, 3], [2, 4], [3, 5]])
+ P = Matrix([[1, 2, 3], [2, 3, 4], [3, 4, 5]])
+ raises(IndexError, lambda: P.col_del(10))
+ Q = Matrix([[1, 2, 3], [2, 3, 4], [3, 4, 5]])
+ raises(IndexError, lambda: Q.col_del(-10))
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_short_problem_statement"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 1,
"issue_text_score": 1,
"test_score": 3
},
"num_modified_files": 1
} | 0.7 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "pytest",
"pip_packages": [
"mpmath>=0.19",
"pytest"
],
"pre_install": [
"apt-get update",
"apt-get install -y python3-pip"
],
"python": "3.6",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | attrs @ file:///opt/conda/conda-bld/attrs_1642510447205/work
certifi==2021.5.30
importlib-metadata @ file:///tmp/build/80754af9/importlib-metadata_1631916693255/work
iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work
more-itertools @ file:///tmp/build/80754af9/more-itertools_1637733554872/work
mpmath==1.3.0
packaging @ file:///tmp/build/80754af9/packaging_1637314298585/work
pluggy @ file:///tmp/build/80754af9/pluggy_1615976315926/work
py @ file:///opt/conda/conda-bld/py_1644396412707/work
pyparsing @ file:///tmp/build/80754af9/pyparsing_1635766073266/work
pytest==6.2.4
-e git+https://github.com/sympy/sympy.git@3766b9ca505bb3645e81912b3cc883df73c7a32b#egg=sympy
toml @ file:///tmp/build/80754af9/toml_1616166611790/work
typing_extensions @ file:///opt/conda/conda-bld/typing_extensions_1647553014482/work
zipp @ file:///tmp/build/80754af9/zipp_1633618647012/work
| name: sympy
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- attrs=21.4.0=pyhd3eb1b0_0
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- importlib-metadata=4.8.1=py36h06a4308_0
- importlib_metadata=4.8.1=hd3eb1b0_0
- iniconfig=1.1.1=pyhd3eb1b0_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- more-itertools=8.12.0=pyhd3eb1b0_0
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- packaging=21.3=pyhd3eb1b0_0
- pip=21.2.2=py36h06a4308_0
- pluggy=0.13.1=py36h06a4308_0
- py=1.11.0=pyhd3eb1b0_0
- pyparsing=3.0.4=pyhd3eb1b0_0
- pytest=6.2.4=py36h06a4308_2
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_0
- setuptools=58.0.4=py36h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- toml=0.10.2=pyhd3eb1b0_0
- typing_extensions=4.1.1=pyh06a4308_0
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- zipp=3.6.0=pyhd3eb1b0_0
- zlib=1.2.13=h5eee18b_1
- pip:
- mpmath==1.3.0
prefix: /opt/conda/envs/sympy
| [
"sympy/matrices/tests/test_matrices.py::test_issue_9457_9467"
] | [] | [
"sympy/matrices/tests/test_matrices.py::test_args",
"sympy/matrices/tests/test_matrices.py::test_division",
"sympy/matrices/tests/test_matrices.py::test_sum",
"sympy/matrices/tests/test_matrices.py::test_addition",
"sympy/matrices/tests/test_matrices.py::test_fancy_index_matrix",
"sympy/matrices/tests/test_matrices.py::test_multiplication",
"sympy/matrices/tests/test_matrices.py::test_power",
"sympy/matrices/tests/test_matrices.py::test_creation",
"sympy/matrices/tests/test_matrices.py::test_tolist",
"sympy/matrices/tests/test_matrices.py::test_as_mutable",
"sympy/matrices/tests/test_matrices.py::test_determinant",
"sympy/matrices/tests/test_matrices.py::test_det_LU_decomposition",
"sympy/matrices/tests/test_matrices.py::test_berkowitz_minors",
"sympy/matrices/tests/test_matrices.py::test_slicing",
"sympy/matrices/tests/test_matrices.py::test_submatrix_assignment",
"sympy/matrices/tests/test_matrices.py::test_extract",
"sympy/matrices/tests/test_matrices.py::test_reshape",
"sympy/matrices/tests/test_matrices.py::test_applyfunc",
"sympy/matrices/tests/test_matrices.py::test_expand",
"sympy/matrices/tests/test_matrices.py::test_random",
"sympy/matrices/tests/test_matrices.py::test_LUdecomp",
"sympy/matrices/tests/test_matrices.py::test_LUsolve",
"sympy/matrices/tests/test_matrices.py::test_QRsolve",
"sympy/matrices/tests/test_matrices.py::test_inverse",
"sympy/matrices/tests/test_matrices.py::test_matrix_inverse_mod",
"sympy/matrices/tests/test_matrices.py::test_util",
"sympy/matrices/tests/test_matrices.py::test_jacobian_hessian",
"sympy/matrices/tests/test_matrices.py::test_QR",
"sympy/matrices/tests/test_matrices.py::test_QR_non_square",
"sympy/matrices/tests/test_matrices.py::test_nullspace",
"sympy/matrices/tests/test_matrices.py::test_columnspace",
"sympy/matrices/tests/test_matrices.py::test_wronskian",
"sympy/matrices/tests/test_matrices.py::test_eigen",
"sympy/matrices/tests/test_matrices.py::test_subs",
"sympy/matrices/tests/test_matrices.py::test_simplify",
"sympy/matrices/tests/test_matrices.py::test_transpose",
"sympy/matrices/tests/test_matrices.py::test_conjugate",
"sympy/matrices/tests/test_matrices.py::test_conj_dirac",
"sympy/matrices/tests/test_matrices.py::test_trace",
"sympy/matrices/tests/test_matrices.py::test_shape",
"sympy/matrices/tests/test_matrices.py::test_col_row_op",
"sympy/matrices/tests/test_matrices.py::test_zip_row_op",
"sympy/matrices/tests/test_matrices.py::test_issue_3950",
"sympy/matrices/tests/test_matrices.py::test_issue_3981",
"sympy/matrices/tests/test_matrices.py::test_evalf",
"sympy/matrices/tests/test_matrices.py::test_is_symbolic",
"sympy/matrices/tests/test_matrices.py::test_is_upper",
"sympy/matrices/tests/test_matrices.py::test_is_lower",
"sympy/matrices/tests/test_matrices.py::test_is_nilpotent",
"sympy/matrices/tests/test_matrices.py::test_zeros_ones_fill",
"sympy/matrices/tests/test_matrices.py::test_empty_zeros",
"sympy/matrices/tests/test_matrices.py::test_issue_3749",
"sympy/matrices/tests/test_matrices.py::test_inv_iszerofunc",
"sympy/matrices/tests/test_matrices.py::test_jacobian_metrics",
"sympy/matrices/tests/test_matrices.py::test_jacobian2",
"sympy/matrices/tests/test_matrices.py::test_issue_4564",
"sympy/matrices/tests/test_matrices.py::test_nonvectorJacobian",
"sympy/matrices/tests/test_matrices.py::test_vec",
"sympy/matrices/tests/test_matrices.py::test_vech",
"sympy/matrices/tests/test_matrices.py::test_vech_errors",
"sympy/matrices/tests/test_matrices.py::test_diag",
"sympy/matrices/tests/test_matrices.py::test_get_diag_blocks1",
"sympy/matrices/tests/test_matrices.py::test_get_diag_blocks2",
"sympy/matrices/tests/test_matrices.py::test_inv_block",
"sympy/matrices/tests/test_matrices.py::test_creation_args",
"sympy/matrices/tests/test_matrices.py::test_diagonal_symmetrical",
"sympy/matrices/tests/test_matrices.py::test_diagonalization",
"sympy/matrices/tests/test_matrices.py::test_jordan_form",
"sympy/matrices/tests/test_matrices.py::test_jordan_form_complex_issue_9274",
"sympy/matrices/tests/test_matrices.py::test_Matrix_berkowitz_charpoly",
"sympy/matrices/tests/test_matrices.py::test_exp",
"sympy/matrices/tests/test_matrices.py::test_has",
"sympy/matrices/tests/test_matrices.py::test_errors",
"sympy/matrices/tests/test_matrices.py::test_len",
"sympy/matrices/tests/test_matrices.py::test_integrate",
"sympy/matrices/tests/test_matrices.py::test_limit",
"sympy/matrices/tests/test_matrices.py::test_diff",
"sympy/matrices/tests/test_matrices.py::test_getattr",
"sympy/matrices/tests/test_matrices.py::test_hessenberg",
"sympy/matrices/tests/test_matrices.py::test_cholesky",
"sympy/matrices/tests/test_matrices.py::test_LDLdecomposition",
"sympy/matrices/tests/test_matrices.py::test_cholesky_solve",
"sympy/matrices/tests/test_matrices.py::test_LDLsolve",
"sympy/matrices/tests/test_matrices.py::test_lower_triangular_solve",
"sympy/matrices/tests/test_matrices.py::test_upper_triangular_solve",
"sympy/matrices/tests/test_matrices.py::test_diagonal_solve",
"sympy/matrices/tests/test_matrices.py::test_matrix_norm",
"sympy/matrices/tests/test_matrices.py::test_singular_values",
"sympy/matrices/tests/test_matrices.py::test_condition_number",
"sympy/matrices/tests/test_matrices.py::test_equality",
"sympy/matrices/tests/test_matrices.py::test_col_join",
"sympy/matrices/tests/test_matrices.py::test_row_insert",
"sympy/matrices/tests/test_matrices.py::test_col_insert",
"sympy/matrices/tests/test_matrices.py::test_normalized",
"sympy/matrices/tests/test_matrices.py::test_print_nonzero",
"sympy/matrices/tests/test_matrices.py::test_zeros_eye",
"sympy/matrices/tests/test_matrices.py::test_is_zero",
"sympy/matrices/tests/test_matrices.py::test_rotation_matrices",
"sympy/matrices/tests/test_matrices.py::test_DeferredVector",
"sympy/matrices/tests/test_matrices.py::test_DeferredVector_not_iterable",
"sympy/matrices/tests/test_matrices.py::test_DeferredVector_Matrix",
"sympy/matrices/tests/test_matrices.py::test_GramSchmidt",
"sympy/matrices/tests/test_matrices.py::test_casoratian",
"sympy/matrices/tests/test_matrices.py::test_zero_dimension_multiply",
"sympy/matrices/tests/test_matrices.py::test_slice_issue_2884",
"sympy/matrices/tests/test_matrices.py::test_slice_issue_3401",
"sympy/matrices/tests/test_matrices.py::test_copyin",
"sympy/matrices/tests/test_matrices.py::test_invertible_check",
"sympy/matrices/tests/test_matrices.py::test_issue_5964",
"sympy/matrices/tests/test_matrices.py::test_issue_7604",
"sympy/matrices/tests/test_matrices.py::test_is_Identity",
"sympy/matrices/tests/test_matrices.py::test_dot",
"sympy/matrices/tests/test_matrices.py::test_dual",
"sympy/matrices/tests/test_matrices.py::test_anti_symmetric",
"sympy/matrices/tests/test_matrices.py::test_normalize_sort_diogonalization",
"sympy/matrices/tests/test_matrices.py::test_issue_5321",
"sympy/matrices/tests/test_matrices.py::test_issue_5320",
"sympy/matrices/tests/test_matrices.py::test_cross",
"sympy/matrices/tests/test_matrices.py::test_hash",
"sympy/matrices/tests/test_matrices.py::test_adjoint",
"sympy/matrices/tests/test_matrices.py::test_simplify_immutable",
"sympy/matrices/tests/test_matrices.py::test_rank",
"sympy/matrices/tests/test_matrices.py::test_replace",
"sympy/matrices/tests/test_matrices.py::test_replace_map",
"sympy/matrices/tests/test_matrices.py::test_atoms",
"sympy/matrices/tests/test_matrices.py::test_pinv",
"sympy/matrices/tests/test_matrices.py::test_pinv_solve",
"sympy/matrices/tests/test_matrices.py::test_issue_7201",
"sympy/matrices/tests/test_matrices.py::test_free_symbols",
"sympy/matrices/tests/test_matrices.py::test_hermitian",
"sympy/matrices/tests/test_matrices.py::test_doit"
] | [] | BSD | 157 |
|
ethanrowe__python-merky-6 | a624893701ffa9b3f1b7c990c62e62725383b0cb | 2015-06-06 15:37:29 | a624893701ffa9b3f1b7c990c62e62725383b0cb | diff --git a/README.md b/README.md
index faeee9a..b504439 100644
--- a/README.md
+++ b/README.md
@@ -197,6 +197,44 @@ Some example uses of this:
See `merky.cases.tokendict.TokenDict` for more.
+# Storage options
+
+Complex storage options are outside the scope of `merky`. However, for convenience, `merky
+does provide some minimal storage options that can serve for some cases.
+
+An arbitrary transformed structure can be stored/restored using various classes found in the
+`merky.store.structure` module. For instance:
+
+```python
+# Suppose this gives me some `merky.cases.attrgraph.AttributeGraph` instance.
+g = get_my_graph()
+
+# Now I'm going to store it a file.
+transformed = merky.AnnotationTransformer().transform(g)
+
+# Get a JSON file writer for the path 'my-graph.json'
+store = merky.store.structure.JSONFileWriteStructure('my-graph.json')
+
+# Populate the writer with the transformed data.
+store.populate(transformed)
+
+# Write the file.
+store.close()
+```
+
+Now later you want to restore it. Like so:
+
+```python
+# Get the reader.
+store = merky.store.structure.JSONFileReadStructure('my-graph.json')
+
+# And away we go.
+g = merky.cases.attrgraph.AttributeGraph.from_token(store.head, store.get)
+```
+
+For a more complex example, see `merky.test.misc.graph_storage_test`, which
+assembles a `TokenDict` of `AttributeGraphs`, writes to JSON, then restores from JSON.
+
# Don't wear a tie.
It's an anachronistic absurdity that needs to be abolished. Direct your respect elsewhere.
diff --git a/merky/cases/tokendict.py b/merky/cases/tokendict.py
index 3c6ebbc..aba991d 100644
--- a/merky/cases/tokendict.py
+++ b/merky/cases/tokendict.py
@@ -82,13 +82,14 @@ class TokenDict(object):
to be converted to a `TokenDict`.
`reader`: a function that, given a "token", returns the
corresponding structure.
- `builder`: (Optional) a function to apply to each value in the
- `TokenDict` when assembling; use this to, for instance,
+ `builder`: (Optional) a function to apply to each token in the
+ `TokenDict` when assembling; it will be called with the
+ token seen and the `reader` above. Ue this to, for instance,
convert each value into a more specific object.
Returns a new `TokenDict` instance.
"""
dict_ = reader(token)
- handler = reader if builder is None else lambda val: builder(reader(val))
+ handler = reader if builder is None else lambda val: builder(val, reader)
return cls(dict((k, handler(v)) for k, v in six.iteritems(dict_)))
diff --git a/merky/serialization.py b/merky/serialization.py
new file mode 100644
index 0000000..0e654ef
--- /dev/null
+++ b/merky/serialization.py
@@ -0,0 +1,14 @@
+import json
+
+def json_serializer(sort=True):
+ """
+ Returns a function that can serialize to JSON, with unicode enabled,
+ nans disallowed, keys sorted, and whitespace-free separators.
+
+ You can override the sorted keys via `sort=False`.
+ """
+ return json.JSONEncoder(ensure_ascii=False,
+ allow_nan=False,
+ sort_keys=sort,
+ separators=(",",":")).encode
+
diff --git a/merky/store/__init__.py b/merky/store/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/merky/store/structure.py b/merky/store/structure.py
new file mode 100644
index 0000000..dabc581
--- /dev/null
+++ b/merky/store/structure.py
@@ -0,0 +1,152 @@
+import codecs
+import collections
+import json
+from .. import serialization
+
+class Structure(object):
+ """
+ Basic interface for a serializ(ed/able) "structure".
+
+ Without providing specifics for read/write operations, gives
+ the basic interface that these things should have in common.
+
+ The purpose of the structure is to combine:
+ * The map of token/structure pairs one gets from transformation
+ * A "head" token indicating which structure is the top-level
+ structure.
+
+ The combination of the `head` token and the `get` method would
+ allow for load of specific cases like the
+ `merky.cases.attrgraph.AttributeGraph` and similar (the `from_token`
+ classmethod).
+ """
+ def populate(self, token_structure_pairs):
+ raise NotImplementedError("populate() not implemented.")
+
+ def get(self, key):
+ raise NotImplementedError("get() not implemented.")
+
+ def __getitem__(self, key):
+ raise NotImplementedError("__getitem()__ not implemented.")
+
+
+
+class TokenMapStructure(Structure):
+ """
+ Maintains an internal in-memory map of token/structure pairs.
+
+ While the `head` can be explicitly set, the `head` defaults to the
+ last token seen via `populate()`.
+ """
+ @staticmethod
+ def default_tokenmap():
+ return collections.OrderedDict()
+
+ def populate(self, token_structure_pairs):
+ """
+ Ingests the `token_structure_pairs` into the internal token map.
+
+ Sets `head` to the last token seen, regardless of the current state of `head`.
+ """
+ self.tokenmap.update(token_structure_pairs)
+ self.head = next(iter(reversed(self.tokenmap))) if len(self.tokenmap) > 0 else None
+
+ def get(self, key):
+ """
+ Returns the corresponding structure from the internal map given the token `key`.
+ """
+ return self.tokenmap.get(key)
+
+
+ def __getitem__(self, key):
+ """
+ Returns the corresponding structure from the internal map given the token 'key'.
+ """
+ return self.tokenmap[key]
+
+
+class InMemoryStructure(TokenMapStructure):
+ """
+ An in-memory "store" that has both the read and write interfaces.
+ """
+ def __init__(self, tokenmap=None, head=None):
+ self.tokenmap = self.default_tokenmap() if tokenmap is None else tokenmap
+ self.head = head
+
+ def close(self):
+ pass
+
+
+class JSONStreamReadStructure(TokenMapStructure):
+ """
+ Reads merkified structure from a utf-8 JSON stream.
+ """
+ def __init__(self, stream):
+ self.stream = stream
+ self.tokenmap, self.head = self.deserialize_from_stream(stream)
+
+ @classmethod
+ def deserialize_from_stream(cls, stream):
+ return json.load(stream, encoding='utf-8')
+
+
+class JSONStreamWriteStructure(TokenMapStructure):
+ """
+ Writes merkified structure to a utf-8 JSON stream.
+
+ The instance accumulates state internally and only serializes to stream
+ at close().
+ """
+ serializer = serialization.json_serializer(sort=False)
+
+ def __init__(self, stream):
+ self.tokenmap = self.default_tokenmap()
+ self.stream = stream
+
+ def serialize_to_stream(self, stream):
+ stream.write(self.serializer([self.tokenmap, self.head]))
+
+ def close(self):
+ self.serialize_to_stream(self.stream)
+ self.stream.flush()
+
+
+class JSONFileReadStructure(JSONStreamReadStructure):
+ """
+ Reads merkified structure from utf-8 JSON file.
+ """
+ def __init__(self, path):
+ self.path = path
+ self.tokenmap, self.head = self.deserialize_from_file(self.path)
+
+ @classmethod
+ def deserialize_from_file(cls, path):
+ with codecs.open(path, encoding="utf-8", mode="rb") as f:
+ return cls.deserialize_from_stream(f)
+
+
+class JSONFileWriteStructure(JSONStreamWriteStructure):
+ """
+ Writes merkified structure to utf-8 JSON file.
+
+ The instance accumulates state internally and only serializes to the file
+ at close().
+ """
+ def __init__(self, path):
+ self.tokenmap = self.default_tokenmap()
+ self.path = path
+
+ def serialize_to_file(self, path):
+ """
+ Writes the current state to the `path` specified.
+ """
+ with codecs.open(path, encoding="utf-8", mode="wb") as f:
+ self.serialize_to_stream(f)
+
+ def close(self):
+ """
+ Writes the state out to the file at `self.path`.
+ """
+ self.serialize_to_file(self.path)
+
+
diff --git a/merky/transformer.py b/merky/transformer.py
index b6be506..a4a370f 100644
--- a/merky/transformer.py
+++ b/merky/transformer.py
@@ -1,6 +1,5 @@
-import json
-
from . import digest
+from . import serialization
from . import tree
class Transformer(object):
@@ -75,10 +74,8 @@ class Transformer(object):
Subclasses could override this to use an alternate serialization approach; the result must
support `encode()`.
"""
- return json.JSONEncoder(ensure_ascii=False,
- allow_nan=False,
- sort_keys=True,
- separators=(",",":")).encode
+ return serialization.json_serializer()
+
def get_dispatcher(self):
"""
diff --git a/setup.py b/setup.py
index a0eed15..a16dfee 100644
--- a/setup.py
+++ b/setup.py
@@ -11,7 +11,10 @@ setup(
url = "https://github.com/ethanrowe/python-merky",
packages = ["merky",
"merky.cases",
+ "merky.store",
"merky.test",
+ "merky.test.misc",
+ "merky.test.store",
"merky.test.usecases",
],
long_description = """
| An in-memory store provides a simple token/structure storage interface
We want a simple interface for storing token/structure pairs, so we can build some higher-level abstractions around them without coupling ourselves to any particular storage mechanism (noting that the most obvious "storage" is an in-memory dict).
Do the in-memory case first, to work out the basics. Probably should have:
* get by key
* set by key; return value should indicate whether key was actually new or not.
* serialize (to JSON, probably)
* deserialize (from JSON, probably)
* close (to flush and release any resources related to the thing)
* `__enter__`/`__exit__` for context manager behavior; close on exit. | ethanrowe/python-merky | diff --git a/merky/test/misc/__init__.py b/merky/test/misc/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/merky/test/misc/graph_storage_test.py b/merky/test/misc/graph_storage_test.py
new file mode 100644
index 0000000..f1a6984
--- /dev/null
+++ b/merky/test/misc/graph_storage_test.py
@@ -0,0 +1,96 @@
+import os
+import tempfile
+import shutil
+
+from nose import tools
+
+import merky
+from merky.cases import attrgraph
+from merky.cases import tokendict
+from merky.store import structure
+
+def tempdir(func):
+ def wrapper(*p, **kw):
+ dir_ = tempfile.mkdtemp()
+ try:
+ return func(*(p + (dir_,)), **kw)
+ finally:
+ shutil.rmtree(dir_)
+ wrapper.__name__ = func.__name__
+ return wrapper
+
+
+def dag(attrs, members):
+ return attrgraph.AttributeGraph(attrs=attrs, members=members)
+
+def getpath(reader, *keys):
+ current = reader.get(reader.head)
+ for key in keys:
+ current = reader.get(current[key])
+ return current
+
+@tempdir
+def test_versioned_graph_save_and_restore(workdir):
+ path = os.path.join(workdir, 'my-graph.json')
+ static = dag({"unchanging": "eternal"}, {})
+
+ graph_s0 = dag({"name": "graph", "version": 0}, {
+ "static": static,
+ "changing": dag({"a": "A"}, {}),
+ "removed": dag({"bleep": "blorp"}, {}),
+ })
+
+ graph_s1 = dag({"name": "graph", "version": 1}, {
+ "static": static,
+ "changing": dag({"b": "B"}, {}),
+ })
+
+ version_map = tokendict.TokenDict({"v0": graph_s0,
+ "v1": graph_s0,
+ "v2": graph_s1,
+ "v3": graph_s1})
+
+ transformer = merky.AnnotationTransformer()
+ writer = structure.JSONFileWriteStructure(path)
+ writer.populate(transformer.transform(version_map))
+ writer.close()
+
+ reader = structure.JSONFileReadStructure(path)
+ tokens = tokendict.TokenDict.from_token(reader.head, reader.get)
+
+ tools.assert_equal(["v0", "v1", "v2", "v3"], list(tokens.keys()))
+
+ # Same states get same tokens.
+ tools.assert_equal(tokens.dict_["v0"], tokens.dict_["v1"])
+ tools.assert_equal(tokens.dict_["v2"], tokens.dict_["v3"])
+ tools.assert_equal(getpath(reader, "v0", 1, "static"),
+ getpath(reader, "v2", 1, "static"))
+
+ # Different states, different tokens.
+ tools.assert_not_equal(tokens.dict_["v1"], tokens.dict_["v2"])
+ tools.assert_not_equal(getpath(reader, "v0", 1, "changing"),
+ getpath(reader, "v2", 1, "changing"))
+
+
+ restored = tokendict.TokenDict.from_token(
+ reader.head,
+ reader.get,
+ attrgraph.AttributeGraph.from_token
+ )
+
+ tools.assert_equal(["v0", "v1", "v2", "v3"],
+ list(restored.keys()))
+
+ tools.assert_equal(dict(graph_s0.attrs), dict(restored["v0"].attrs))
+ tools.assert_equal(dict(graph_s1.attrs), dict(restored["v2"].attrs))
+ tools.assert_equal(["changing", "removed", "static"],
+ list(sorted(restored["v0"].members.keys())))
+ tools.assert_equal(["changing", "static"],
+ list(sorted(restored["v2"].members.keys())))
+ tools.assert_equal(dict(graph_s0.members["changing"].attrs),
+ dict(restored["v1"].members["changing"].attrs))
+ tools.assert_equal(dict(graph_s1.members["changing"].attrs),
+ dict(restored["v3"].members["changing"].attrs))
+ tools.assert_equal(dict(restored["v0"].members["static"].attrs),
+ dict(restored["v3"].members["static"].attrs))
+
diff --git a/merky/test/store/__init__.py b/merky/test/store/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/merky/test/store/structure_test.py b/merky/test/store/structure_test.py
new file mode 100644
index 0000000..8a2f071
--- /dev/null
+++ b/merky/test/store/structure_test.py
@@ -0,0 +1,166 @@
+import codecs
+import collections
+import os
+import tempfile
+import shutil
+from nose import tools
+from six.moves import StringIO
+from .. import words
+from merky.store import structure
+
+def od(*p, **kw):
+ return collections.OrderedDict(*p, **kw)
+
+class TestInMemoryStructure(object):
+
+ HEAD_TOKEN = 'sometoptoken'
+ LIST_TOKEN = 'somelisttoken'
+ DICT_TOKEN = 'somedicttoken'
+ HEAD = od((('a', 'somelisttoken'), ('b', 'somedicttoken')))
+ DICT = od(((words.EUROS, words.SHEKELS), (words.EPEES, words.ANGSTROM)))
+ LIST = ["some", "list", words.SHEKELS]
+
+ PAIRS = (
+ (LIST_TOKEN, LIST),
+ (DICT_TOKEN, DICT),
+ (HEAD_TOKEN, HEAD),
+ )
+
+
+ def get_read_store(self):
+ return structure.InMemoryStructure(od(self.PAIRS), self.HEAD_TOKEN)
+
+
+ def get_write_store(self):
+ return structure.InMemoryStructure()
+
+
+ def verify_dict(self, received, expect):
+ tools.assert_equal(expect, received)
+
+
+ def verify_list(self, received, expect):
+ tools.assert_equal(expect, received)
+
+
+ def verify_head(self, store, head):
+ tools.assert_equal(head, store.head)
+
+
+ def verify_write(self, store, head):
+ # In-memory guy has same state before and after close() call.
+ tools.assert_equal(od(self.PAIRS), store.tokenmap)
+ store.close()
+ tools.assert_equal(head, store.head)
+ tools.assert_equal(od(self.PAIRS), store.tokenmap)
+
+
+ def test_head_from_last_by_default(self):
+ store = self.get_write_store()
+ store.populate(iter(self.PAIRS))
+ self.verify_head(store, self.HEAD_TOKEN)
+ self.verify_write(store, self.HEAD_TOKEN)
+
+
+ def test_overriddable_head(self):
+ store = self.get_write_store()
+ store.populate(iter(self.PAIRS))
+ store.head = self.DICT_TOKEN
+ self.verify_head(store, self.DICT_TOKEN)
+ self.verify_write(store, self.DICT_TOKEN)
+
+
+ def test_read_operations(self):
+ store = self.get_read_store()
+ self.verify_head(store, self.HEAD_TOKEN)
+ self.verify_dict(store.get(self.HEAD_TOKEN), self.HEAD)
+ self.verify_dict(store[self.HEAD_TOKEN], self.HEAD)
+ self.verify_list(store.get(self.LIST_TOKEN), self.LIST)
+ self.verify_list(store[self.LIST_TOKEN], self.LIST)
+ self.verify_dict(store.get(self.DICT_TOKEN), self.DICT)
+ self.verify_dict(store[self.DICT_TOKEN], self.DICT)
+ tools.assert_equal(None, store.get('no no no'))
+ tools.assert_raises(KeyError, lambda: store['no no no'])
+
+
+q = lambda word: words.unify('"', word, '"')
+def commify(*w):
+ terms = []
+ for word in w[:-1]:
+ terms.append(word)
+ terms.append(',')
+ if len(w) > 0:
+ terms.append(w[-1])
+ return words.unify(*terms)
+
+jl = lambda *w: words.unify('[', commify(*w), ']')
+def jd(*pairs):
+ return words.unify('{',
+ commify(*(words.unify(k, ':', w)
+ for k, w in pairs)),
+ '}')
+
+
+class TestStreamStructure(TestInMemoryStructure):
+ def json(self, head):
+ return jl(
+ jd(
+ (q(self.LIST_TOKEN), jl(*(q(w) for w in self.LIST))),
+ (q(self.DICT_TOKEN), jd(*((q(k), q(v)) for k,v in self.DICT.items()))),
+ (q(self.HEAD_TOKEN), jd(*((q(k), q(v)) for k,v in self.HEAD.items()))),
+ ),
+ q(head),
+ )
+
+ def get_read_store(self):
+ self.stream = StringIO(self.json(self.HEAD_TOKEN))
+ return structure.JSONStreamReadStructure(self.stream)
+
+ def get_write_store(self):
+ self.stream = StringIO()
+ return structure.JSONStreamWriteStructure(self.stream)
+
+ def verify_dict(self, received, expect):
+ tools.assert_equal(dict(expect), received)
+
+ def verify_list(self, received, expect):
+ tools.assert_equal(list(expect), received)
+
+ def verify_write(self, store, head):
+ # Nothing written to stream until close().
+ tools.assert_equal(0, self.stream.tell())
+ tools.assert_equal('', self.stream.read())
+ store.close()
+ self.stream.seek(0)
+ tools.assert_equal(self.json(head), self.stream.read())
+
+ def test_no_close(self):
+ store = self.get_read_store()
+ tools.assert_raises(AttributeError, getattr, store, 'close')
+
+
+class TestFileStructure(TestStreamStructure):
+ def setup(self):
+ self.workdir = tempfile.mkdtemp()
+ self.path = os.path.join(self.workdir, "some-file.json")
+
+ def teardown(self):
+ shutil.rmtree(self.workdir)
+
+ def get_read_store(self):
+ with codecs.open(self.path, mode="wb", encoding="utf-8") as f:
+ f.write(self.json(self.HEAD_TOKEN))
+ return structure.JSONFileReadStructure(self.path)
+
+ def get_write_store(self):
+ return structure.JSONFileWriteStructure(self.path)
+
+ def verify_write(self, store, head):
+ # File doesn't even exist before close.
+ tools.assert_false(os.path.exists(self.path))
+ # But it will after close()
+ store.close()
+ tools.assert_true(os.path.exists(self.path))
+ with codecs.open(self.path, mode='rb', encoding='utf-8') as f:
+ tools.assert_equal(self.json(head), f.read())
+
diff --git a/merky/test/usecases/tokendict_test.py b/merky/test/usecases/tokendict_test.py
index 57c109f..48d6341 100644
--- a/merky/test/usecases/tokendict_test.py
+++ b/merky/test/usecases/tokendict_test.py
@@ -67,9 +67,9 @@ def test_restoration():
def test_restoration_with_builder():
- def wrapper(value):
+ def wrapper(token, reader):
def wrapped():
- return ('called me!', value)
+ return ('called me!', reader(token))
return wrapped
g = tokendict.TokenDict.from_token(TOK.token, CACHE.get, wrapper)
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_added_files",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 2,
"issue_text_score": 1,
"test_score": 1
},
"num_modified_files": 4
} | unknown | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[dev]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"nose",
"mock>=1.0.1",
"pytest"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.9",
"reqs_path": [
"requirements/base.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | exceptiongroup==1.2.2
iniconfig==2.1.0
-e git+https://github.com/ethanrowe/python-merky.git@a624893701ffa9b3f1b7c990c62e62725383b0cb#egg=merky
mock==5.2.0
nose==1.3.7
packaging==24.2
pluggy==1.5.0
pytest==8.3.5
six==1.17.0
tomli==2.2.1
| name: python-merky
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=3.0.16=h5eee18b_0
- pip=25.0=py39h06a4308_0
- python=3.9.21=he870216_1
- readline=8.2=h5eee18b_0
- setuptools=75.8.0=py39h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- tzdata=2025a=h04d1e81_0
- wheel=0.45.1=py39h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- exceptiongroup==1.2.2
- iniconfig==2.1.0
- mock==5.2.0
- nose==1.3.7
- packaging==24.2
- pluggy==1.5.0
- pytest==8.3.5
- six==1.17.0
- tomli==2.2.1
prefix: /opt/conda/envs/python-merky
| [
"merky/test/store/structure_test.py::TestInMemoryStructure::test_head_from_last_by_default",
"merky/test/store/structure_test.py::TestInMemoryStructure::test_overriddable_head",
"merky/test/store/structure_test.py::TestInMemoryStructure::test_read_operations",
"merky/test/store/structure_test.py::TestStreamStructure::test_head_from_last_by_default",
"merky/test/store/structure_test.py::TestStreamStructure::test_overriddable_head",
"merky/test/usecases/tokendict_test.py::test_dict_",
"merky/test/usecases/tokendict_test.py::test_get_and_set",
"merky/test/usecases/tokendict_test.py::test_key_sort",
"merky/test/usecases/tokendict_test.py::test_value_annotation",
"merky/test/usecases/tokendict_test.py::test_tokenization",
"merky/test/usecases/tokendict_test.py::test_restoration",
"merky/test/usecases/tokendict_test.py::test_restoration_with_builder"
] | [
"merky/test/misc/graph_storage_test.py::test_versioned_graph_save_and_restore",
"merky/test/store/structure_test.py::TestStreamStructure::test_read_operations",
"merky/test/store/structure_test.py::TestStreamStructure::test_no_close",
"merky/test/store/structure_test.py::TestFileStructure::test_head_from_last_by_default",
"merky/test/store/structure_test.py::TestFileStructure::test_overriddable_head",
"merky/test/store/structure_test.py::TestFileStructure::test_read_operations",
"merky/test/store/structure_test.py::TestFileStructure::test_no_close"
] | [] | [] | MIT License | 158 |
|
sympy__sympy-9482 | b7c9ba075bab9e47b5978b582f54aa552fac4f78 | 2015-06-07 14:43:50 | 0241b35cae5f2adc04dc37b25f7dc9c5f00bd746 | diff --git a/sympy/assumptions/handlers/ntheory.py b/sympy/assumptions/handlers/ntheory.py
index 539d9fca15..dcd12163b3 100644
--- a/sympy/assumptions/handlers/ntheory.py
+++ b/sympy/assumptions/handlers/ntheory.py
@@ -85,6 +85,10 @@ def Basic(expr, assumptions):
_prime = ask(Q.prime(expr), assumptions)
if _prime is None:
return
+ # Positive integer which is not prime is not
+ # necessarily composite
+ if expr.equals(1):
+ return False
return not _prime
else:
return _integer
| One is composite in new assumptions
```
In [1]: from sympy import *
In [2]: S(1).is_composite
Out[2]: False
In [3]: ask(Q.composite(1))
Out[3]: True # should be False
``` | sympy/sympy | diff --git a/sympy/assumptions/tests/test_query.py b/sympy/assumptions/tests/test_query.py
index e11f5dcdc7..4bf8e2639b 100644
--- a/sympy/assumptions/tests/test_query.py
+++ b/sympy/assumptions/tests/test_query.py
@@ -39,7 +39,7 @@ def test_int_1():
assert ask(Q.finite(z)) is True
assert ask(Q.infinitesimal(z)) is False
assert ask(Q.prime(z)) is False
- assert ask(Q.composite(z)) is True
+ assert ask(Q.composite(z)) is False
assert ask(Q.hermitian(z)) is True
assert ask(Q.antihermitian(z)) is False
@@ -102,7 +102,7 @@ def test_float_1():
assert ask(Q.finite(z)) is True
assert ask(Q.infinitesimal(z)) is False
assert ask(Q.prime(z)) is False
- assert ask(Q.composite(z)) is True
+ assert ask(Q.composite(z)) is False
assert ask(Q.hermitian(z)) is True
assert ask(Q.antihermitian(z)) is False
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_short_problem_statement"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 0,
"issue_text_score": 0,
"test_score": 2
},
"num_modified_files": 1
} | 0.7 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "pytest",
"pip_packages": [
"pytest"
],
"pre_install": [
"apt-get update",
"apt-get install -y libgmp-dev"
],
"python": "3.6",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | attrs @ file:///opt/conda/conda-bld/attrs_1642510447205/work
certifi==2021.5.30
importlib-metadata @ file:///tmp/build/80754af9/importlib-metadata_1631916693255/work
iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work
more-itertools @ file:///tmp/build/80754af9/more-itertools_1637733554872/work
mpmath==1.3.0
packaging @ file:///tmp/build/80754af9/packaging_1637314298585/work
pluggy @ file:///tmp/build/80754af9/pluggy_1615976315926/work
py @ file:///opt/conda/conda-bld/py_1644396412707/work
pyparsing @ file:///tmp/build/80754af9/pyparsing_1635766073266/work
pytest==6.2.4
-e git+https://github.com/sympy/sympy.git@b7c9ba075bab9e47b5978b582f54aa552fac4f78#egg=sympy
toml @ file:///tmp/build/80754af9/toml_1616166611790/work
typing_extensions @ file:///opt/conda/conda-bld/typing_extensions_1647553014482/work
zipp @ file:///tmp/build/80754af9/zipp_1633618647012/work
| name: sympy
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- attrs=21.4.0=pyhd3eb1b0_0
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- importlib-metadata=4.8.1=py36h06a4308_0
- importlib_metadata=4.8.1=hd3eb1b0_0
- iniconfig=1.1.1=pyhd3eb1b0_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- more-itertools=8.12.0=pyhd3eb1b0_0
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- packaging=21.3=pyhd3eb1b0_0
- pip=21.2.2=py36h06a4308_0
- pluggy=0.13.1=py36h06a4308_0
- py=1.11.0=pyhd3eb1b0_0
- pyparsing=3.0.4=pyhd3eb1b0_0
- pytest=6.2.4=py36h06a4308_2
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_0
- setuptools=58.0.4=py36h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- toml=0.10.2=pyhd3eb1b0_0
- typing_extensions=4.1.1=pyh06a4308_0
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- zipp=3.6.0=pyhd3eb1b0_0
- zlib=1.2.13=h5eee18b_1
- pip:
- mpmath==1.3.0
prefix: /opt/conda/envs/sympy
| [
"sympy/assumptions/tests/test_query.py::test_int_1",
"sympy/assumptions/tests/test_query.py::test_float_1"
] | [
"sympy/assumptions/tests/test_query.py::test_deprecated_Q_bounded",
"sympy/assumptions/tests/test_query.py::test_deprecated_Q_infinity"
] | [
"sympy/assumptions/tests/test_query.py::test_int_11",
"sympy/assumptions/tests/test_query.py::test_int_12",
"sympy/assumptions/tests/test_query.py::test_zero_0",
"sympy/assumptions/tests/test_query.py::test_negativeone",
"sympy/assumptions/tests/test_query.py::test_infinity",
"sympy/assumptions/tests/test_query.py::test_neg_infinity",
"sympy/assumptions/tests/test_query.py::test_nan",
"sympy/assumptions/tests/test_query.py::test_Rational_number",
"sympy/assumptions/tests/test_query.py::test_sqrt_2",
"sympy/assumptions/tests/test_query.py::test_pi",
"sympy/assumptions/tests/test_query.py::test_E",
"sympy/assumptions/tests/test_query.py::test_GoldenRatio",
"sympy/assumptions/tests/test_query.py::test_I",
"sympy/assumptions/tests/test_query.py::test_bounded",
"sympy/assumptions/tests/test_query.py::test_commutative",
"sympy/assumptions/tests/test_query.py::test_complex",
"sympy/assumptions/tests/test_query.py::test_even",
"sympy/assumptions/tests/test_query.py::test_evenness_in_ternary_integer_product_with_even",
"sympy/assumptions/tests/test_query.py::test_extended_real",
"sympy/assumptions/tests/test_query.py::test_rational",
"sympy/assumptions/tests/test_query.py::test_hermitian",
"sympy/assumptions/tests/test_query.py::test_imaginary",
"sympy/assumptions/tests/test_query.py::test_infinitesimal",
"sympy/assumptions/tests/test_query.py::test_integer",
"sympy/assumptions/tests/test_query.py::test_negative",
"sympy/assumptions/tests/test_query.py::test_nonzero",
"sympy/assumptions/tests/test_query.py::test_zero",
"sympy/assumptions/tests/test_query.py::test_odd",
"sympy/assumptions/tests/test_query.py::test_oddness_in_ternary_integer_product_with_even",
"sympy/assumptions/tests/test_query.py::test_prime",
"sympy/assumptions/tests/test_query.py::test_positive",
"sympy/assumptions/tests/test_query.py::test_nonpositive",
"sympy/assumptions/tests/test_query.py::test_nonnegative",
"sympy/assumptions/tests/test_query.py::test_real",
"sympy/assumptions/tests/test_query.py::test_algebraic",
"sympy/assumptions/tests/test_query.py::test_global",
"sympy/assumptions/tests/test_query.py::test_custom_context",
"sympy/assumptions/tests/test_query.py::test_functions_in_assumptions",
"sympy/assumptions/tests/test_query.py::test_composite_ask",
"sympy/assumptions/tests/test_query.py::test_composite_proposition",
"sympy/assumptions/tests/test_query.py::test_composite_assumptions",
"sympy/assumptions/tests/test_query.py::test_incompatible_resolutors",
"sympy/assumptions/tests/test_query.py::test_key_extensibility",
"sympy/assumptions/tests/test_query.py::test_type_extensibility",
"sympy/assumptions/tests/test_query.py::test_single_fact_lookup",
"sympy/assumptions/tests/test_query.py::test_compute_known_facts",
"sympy/assumptions/tests/test_query.py::test_known_facts_consistent",
"sympy/assumptions/tests/test_query.py::test_Add_queries",
"sympy/assumptions/tests/test_query.py::test_positive_assuming",
"sympy/assumptions/tests/test_query.py::test_issue_5421",
"sympy/assumptions/tests/test_query.py::test_issue_3906",
"sympy/assumptions/tests/test_query.py::test_issue_5833",
"sympy/assumptions/tests/test_query.py::test_issue_6732",
"sympy/assumptions/tests/test_query.py::test_issue_7246"
] | [] | BSD | 159 |
|
pydoit__doit-58 | dcefd2159bca7fa80e236fc3fec91688a39ba7c4 | 2015-06-07 18:22:26 | e551006a0a5a93a197d413b663bd455061e3f74d | diff --git a/doit/cmd_run.py b/doit/cmd_run.py
index 8a3693a..50e34b9 100644
--- a/doit/cmd_run.py
+++ b/doit/cmd_run.py
@@ -116,6 +116,18 @@ opt_pdb = {
}
+# use ".*" as default regex for delayed tasks without explicitly specified regex
+opt_auto_delayed_regex = {
+ 'name': 'auto_delayed_regex',
+ 'short': '',
+ 'long': 'auto-delayed-regex',
+ 'type': bool,
+ 'default': False,
+ 'help':
+"""Uses the default regex ".*" for every delayed task loader for which no regex was explicitly defined"""
+}
+
+
class Run(DoitCmdBase):
doc_purpose = "run tasks"
doc_usage = "[TASK/TARGET...]"
@@ -124,7 +136,8 @@ class Run(DoitCmdBase):
cmd_options = (opt_always, opt_continue, opt_verbosity,
opt_reporter, opt_outfile, opt_num_process,
- opt_parallel_type, opt_pdb, opt_single)
+ opt_parallel_type, opt_pdb, opt_single,
+ opt_auto_delayed_regex)
def __init__(self, **kwargs):
@@ -162,7 +175,7 @@ class Run(DoitCmdBase):
def _execute(self, outfile,
verbosity=None, always=False, continue_=False,
reporter='console', num_process=0, par_type='process',
- single=False):
+ single=False, auto_delayed_regex=False):
"""
@param reporter:
(str) one of provided reporters or ...
@@ -172,7 +185,7 @@ class Run(DoitCmdBase):
"""
# get tasks to be executed
# self.control is saved on instance to be used by 'auto' command
- self.control = TaskControl(self.task_list)
+ self.control = TaskControl(self.task_list, auto_delayed_regex=auto_delayed_regex)
self.control.process(self.sel_tasks)
if single:
diff --git a/doit/control.py b/doit/control.py
index 6350b99..c60d688 100644
--- a/doit/control.py
+++ b/doit/control.py
@@ -26,9 +26,10 @@ class TaskControl(object):
Value: task_name
"""
- def __init__(self, task_list):
+ def __init__(self, task_list, auto_delayed_regex=False):
self.tasks = {}
self.targets = {}
+ self.auto_delayed_regex = auto_delayed_regex
# name of task in order to be executed
# this the order as in the dodo file. the real execution
@@ -174,22 +175,51 @@ class TaskControl(object):
# by task name
if filter_ in self.tasks:
selected_task.append(filter_)
+ continue
+
# by target
- elif filter_ in self.targets:
+ if filter_ in self.targets:
selected_task.append(self.targets[filter_])
- else:
- # if can not find name check if it is a sub-task of a delayed
- basename = filter_.split(':', 1)[0]
- if basename in self.tasks:
- loader = self.tasks[basename].loader
- loader.basename = basename
- self.tasks[filter_] = Task(filter_, None, loader=loader)
- selected_task.append(filter_)
+ continue
+
+ # if can not find name check if it is a sub-task of a delayed
+ basename = filter_.split(':', 1)[0]
+ if basename in self.tasks:
+ loader = self.tasks[basename].loader
+ loader.basename = basename
+ self.tasks[filter_] = Task(filter_, None, loader=loader)
+ selected_task.append(filter_)
+ continue
+
+ # check if target matches any regex
+ import re
+ tasks = []
+ for task in list(self.tasks.values()):
+ if task.loader and (task.loader.target_regex or self.auto_delayed_regex):
+ if re.match(task.loader.target_regex if task.loader.target_regex else '.*', filter_):
+ tasks.append(task)
+ if len(tasks) > 0:
+ if len(tasks) == 1:
+ task = tasks[0]
+ loader = task.loader
+ loader.basename = task.name
+ name = '_regex_target_' + filter_
+ self.tasks[name] = Task(name, None,
+ loader=loader,
+ file_dep=[filter_])
+ selected_task.append(name)
else:
- msg = ('cmd `run` invalid parameter: "%s".' +
- ' Must be a task, or a target.\n' +
- 'Type "doit list" to see available tasks')
- raise InvalidCommand(msg % filter_)
+ name = '_regex_target_' + filter_
+ self.tasks[name] = Task(name, None,
+ task_dep=[task.name for task in tasks],
+ file_dep=[filter_])
+ selected_task.append(name)
+ else:
+ # not found
+ msg = ('cmd `run` invalid parameter: "%s".' +
+ ' Must be a task, or a target.\n' +
+ 'Type "doit list" to see available tasks')
+ raise InvalidCommand(msg % filter_)
return selected_task
@@ -416,6 +446,9 @@ class TaskDispatcher(object):
basename = this_task.loader.basename or this_task.name
new_tasks = generate_tasks(basename, ref(), ref.__doc__)
TaskControl.set_implicit_deps(self.targets, new_tasks)
+ # check itself for implicit dep (used by regex_target)
+ TaskControl.add_implicit_task_dep(
+ self.targets, this_task, this_task.file_dep)
for nt in new_tasks:
if not nt.loader:
nt.loader = DelayedLoaded
diff --git a/doit/loader.py b/doit/loader.py
index 1f3bcd4..123d0f4 100644
--- a/doit/loader.py
+++ b/doit/loader.py
@@ -98,10 +98,11 @@ def get_module(dodo_file, cwd=None, seek_parent=False):
-def create_after(executed=None):
+def create_after(executed=None, target_regex=None):
"""Annotate a task-creator function with delayed loader info"""
def decorated(func):
- func.doit_create_after = DelayedLoader(func, executed=executed)
+ func.doit_create_after = DelayedLoader(func, executed=executed,
+ target_regex=target_regex)
return func
return decorated
diff --git a/doit/reporter.py b/doit/reporter.py
index 4f5cbe3..18df356 100644
--- a/doit/reporter.py
+++ b/doit/reporter.py
@@ -53,7 +53,8 @@ class ConsoleReporter(object):
def skip_uptodate(self, task):
"""skipped up-to-date task"""
- self.write("-- %s\n" % task.title())
+ if task.actions and (task.name[0] != '_'):
+ self.write("-- %s\n" % task.title())
def skip_ignore(self, task):
"""skipped ignored task"""
diff --git a/doit/task.py b/doit/task.py
index 7595877..3440123 100644
--- a/doit/task.py
+++ b/doit/task.py
@@ -31,9 +31,10 @@ class DelayedLoader(object):
the loader call the creator function
:ivar basename: (str) basename used when creating tasks
"""
- def __init__(self, creator, executed=None):
+ def __init__(self, creator, executed=None, target_regex=None):
self.creator = creator
self.task_dep = executed
+ self.target_regex = target_regex
self.basename = None
self.created = False
| specify target of a DelayedTask on command line
Since not all tasks are created before execution starts, it is required some special handling for target names of targets that have not been created yet.
See discussion on https://github.com/getnikola/nikola/issues/1562#issuecomment-70836094
General idea is that if a target is not found, before raising an error to the user try to load DelayedTasks (as done by command list) to look for the given `target` name.
Some considerations:
1) as of now a DelayedTask creates an implicit `task_dep` for the task given in it's `executed` param. But this `task_dep` is not preserved when the DelayedTask is re-created. It should not only be preserved but all created tasks should include this `task_dep` because the guarantee that the dependent task was already executed wont exist anymore!
2) if the selected tasks for execution includes know tasks and targets they should be executed **before**, any DelayedTask is loaded to look for an unknown `target`. This will ensure that same command line will work nicely even if it is on its first execution.
<bountysource-plugin>
---
Want to back this issue? **[Post a bounty on it!](https://www.bountysource.com/issues/7952756-specify-target-of-a-delayedtask-on-command-line?utm_campaign=plugin&utm_content=tracker%2F1885485&utm_medium=issues&utm_source=github)** We accept bounties via [Bountysource](https://www.bountysource.com/?utm_campaign=plugin&utm_content=tracker%2F1885485&utm_medium=issues&utm_source=github).
</bountysource-plugin> | pydoit/doit | diff --git a/tests/test_control.py b/tests/test_control.py
index 4237acb..734b449 100644
--- a/tests/test_control.py
+++ b/tests/test_control.py
@@ -111,6 +111,43 @@ class TestTaskControlCmdOptions(object):
assert control.tasks['taskY:foo'].loader.basename == 'taskY'
assert control.tasks['taskY:foo'].loader is t2.loader
+ def test_filter_delayed_regex_single(self):
+ t1 = Task("taskX", None)
+ t2 = Task("taskY", None, loader=DelayedLoader(lambda: None, target_regex='a.*'))
+ t3 = Task("taskZ", None, loader=DelayedLoader(lambda: None, target_regex='b.*'))
+ t4 = Task("taskW", None, loader=DelayedLoader(lambda: None))
+ control = TaskControl([t1, t2, t3, t4], auto_delayed_regex=False)
+ l = control._filter_tasks(['abc'])
+ assert isinstance(t2.loader, DelayedLoader)
+ assert len(l) == 1
+ assert l[0] == '_regex_target_abc'
+ assert control.tasks[l[0]].file_dep == {'abc'}
+ assert control.tasks[l[0]].loader.basename == 'taskY'
+ assert control.tasks[l[0]].loader is t2.loader
+
+ def test_filter_delayed_regex_multiple(self):
+ t1 = Task("taskX", None)
+ t2 = Task("taskY", None, loader=DelayedLoader(lambda: None, target_regex='a.*'))
+ t3 = Task("taskZ", None, loader=DelayedLoader(lambda: None, target_regex='ab.'))
+ t4 = Task("taskW", None, loader=DelayedLoader(lambda: None))
+ control = TaskControl([t1, t2, t3, t4], auto_delayed_regex=False)
+ l = control._filter_tasks(['abc'])
+ assert len(l) == 1
+ assert l[0] == '_regex_target_abc'
+ assert control.tasks[l[0]].file_dep == {'abc'}
+ assert set(control.tasks[l[0]].task_dep) == {t2.name, t3.name}
+
+ def test_filter_delayed_regex_auto(self):
+ t1 = Task("taskX", None)
+ t2 = Task("taskY", None, loader=DelayedLoader(lambda: None, target_regex='a.*'))
+ t3 = Task("taskZ", None, loader=DelayedLoader(lambda: None))
+ control = TaskControl([t1, t2, t3], auto_delayed_regex=True)
+ l = control._filter_tasks(['abc'])
+ assert len(l) == 1
+ assert l[0] == '_regex_target_abc'
+ assert control.tasks[l[0]].file_dep == {'abc'}
+ assert set(control.tasks[l[0]].task_dep) == {t2.name, t3.name}
+
# filter a non-existent task raises an error
def testFilterWrongName(self):
tc = TaskControl(TASKS_SAMPLE)
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_hyperlinks",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 1,
"issue_text_score": 0,
"test_score": 2
},
"num_modified_files": 5
} | 0.28 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[test]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "numpy>=1.10 pytest",
"pip_packages": [
"pytest"
],
"pre_install": [
"apt-get update",
"apt-get install -y libgeos-dev"
],
"python": "3.7",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | attrs @ file:///croot/attrs_1668696182826/work
certifi @ file:///croot/certifi_1671487769961/work/certifi
-e git+https://github.com/pydoit/doit.git@dcefd2159bca7fa80e236fc3fec91688a39ba7c4#egg=doit
flit_core @ file:///opt/conda/conda-bld/flit-core_1644941570762/work/source/flit_core
importlib-metadata @ file:///tmp/build/80754af9/importlib-metadata_1648562407465/work
iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work
numpy @ file:///opt/conda/conda-bld/numpy_and_numpy_base_1653915516269/work
packaging @ file:///croot/packaging_1671697413597/work
pluggy @ file:///tmp/build/80754af9/pluggy_1648042572264/work
py @ file:///opt/conda/conda-bld/py_1644396412707/work
pyinotify==0.9.6
pytest==7.1.2
six==1.17.0
tomli @ file:///opt/conda/conda-bld/tomli_1657175507142/work
typing_extensions @ file:///croot/typing_extensions_1669924550328/work
zipp @ file:///croot/zipp_1672387121353/work
| name: doit
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- attrs=22.1.0=py37h06a4308_0
- blas=1.0=openblas
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2022.12.7=py37h06a4308_0
- flit-core=3.6.0=pyhd3eb1b0_0
- importlib-metadata=4.11.3=py37h06a4308_0
- importlib_metadata=4.11.3=hd3eb1b0_0
- iniconfig=1.1.1=pyhd3eb1b0_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgfortran-ng=11.2.0=h00389a5_1
- libgfortran5=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libopenblas=0.3.21=h043d6bf_0
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- numpy=1.21.5=py37hf838250_3
- numpy-base=1.21.5=py37h1e6e340_3
- openssl=1.1.1w=h7f8727e_0
- packaging=22.0=py37h06a4308_0
- pip=22.3.1=py37h06a4308_0
- pluggy=1.0.0=py37h06a4308_1
- py=1.11.0=pyhd3eb1b0_0
- pytest=7.1.2=py37h06a4308_0
- python=3.7.16=h7a1cb2a_0
- readline=8.2=h5eee18b_0
- setuptools=65.6.3=py37h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- tomli=2.0.1=py37h06a4308_0
- typing_extensions=4.4.0=py37h06a4308_0
- wheel=0.38.4=py37h06a4308_0
- xz=5.6.4=h5eee18b_1
- zipp=3.11.0=py37h06a4308_0
- zlib=1.2.13=h5eee18b_1
- pip:
- pyinotify==0.9.6
- six==1.17.0
prefix: /opt/conda/envs/doit
| [
"tests/test_control.py::TestTaskControlCmdOptions::test_filter_delayed_regex_single",
"tests/test_control.py::TestTaskControlCmdOptions::test_filter_delayed_regex_multiple",
"tests/test_control.py::TestTaskControlCmdOptions::test_filter_delayed_regex_auto"
] | [] | [
"tests/test_control.py::TestTaskControlInit::test_addTask",
"tests/test_control.py::TestTaskControlInit::test_targetDependency",
"tests/test_control.py::TestTaskControlInit::test_addTaskSameName",
"tests/test_control.py::TestTaskControlInit::test_addInvalidTask",
"tests/test_control.py::TestTaskControlInit::test_userErrorTaskDependency",
"tests/test_control.py::TestTaskControlInit::test_userErrorSetupTask",
"tests/test_control.py::TestTaskControlInit::test_sameTarget",
"tests/test_control.py::TestTaskControlInit::test_wild",
"tests/test_control.py::TestTaskControlInit::test_bug770150_task_dependency_from_target",
"tests/test_control.py::TestTaskControlCmdOptions::testFilter",
"tests/test_control.py::TestTaskControlCmdOptions::testProcessSelection",
"tests/test_control.py::TestTaskControlCmdOptions::testProcessAll",
"tests/test_control.py::TestTaskControlCmdOptions::testFilterPattern",
"tests/test_control.py::TestTaskControlCmdOptions::testFilterSubtask",
"tests/test_control.py::TestTaskControlCmdOptions::testFilterTarget",
"tests/test_control.py::TestTaskControlCmdOptions::test_filter_delayed_subtask",
"tests/test_control.py::TestTaskControlCmdOptions::testFilterWrongName",
"tests/test_control.py::TestTaskControlCmdOptions::testFilterEmptyList",
"tests/test_control.py::TestTaskControlCmdOptions::testOptions",
"tests/test_control.py::TestTaskControlCmdOptions::testPosParam",
"tests/test_control.py::TestExecNode::test_repr",
"tests/test_control.py::TestExecNode::test_ready_select__not_waiting",
"tests/test_control.py::TestExecNode::test_parent_status_failure",
"tests/test_control.py::TestExecNode::test_parent_status_ignore",
"tests/test_control.py::TestExecNode::test_step",
"tests/test_control.py::TestDecoratorNoNone::test_filtering",
"tests/test_control.py::TestTaskDispatcher_GenNone::test_create",
"tests/test_control.py::TestTaskDispatcher_GenNone::test_already_created",
"tests/test_control.py::TestTaskDispatcher_GenNone::test_cyclic",
"tests/test_control.py::TestTaskDispatcher_node_add_wait_run::test_wait",
"tests/test_control.py::TestTaskDispatcher_node_add_wait_run::test_none",
"tests/test_control.py::TestTaskDispatcher_node_add_wait_run::test_deps_not_ok",
"tests/test_control.py::TestTaskDispatcher_node_add_wait_run::test_calc_dep_already_executed",
"tests/test_control.py::TestTaskDispatcher_add_task::test_no_deps",
"tests/test_control.py::TestTaskDispatcher_add_task::test_task_deps",
"tests/test_control.py::TestTaskDispatcher_add_task::test_task_deps_already_created",
"tests/test_control.py::TestTaskDispatcher_add_task::test_task_deps_no_wait",
"tests/test_control.py::TestTaskDispatcher_add_task::test_calc_dep",
"tests/test_control.py::TestTaskDispatcher_add_task::test_calc_dep_already_executed",
"tests/test_control.py::TestTaskDispatcher_add_task::test_setup_task__run",
"tests/test_control.py::TestTaskDispatcher_add_task::test_delayed_creation",
"tests/test_control.py::TestTaskDispatcher_add_task::test_delayed_creation_sub_task",
"tests/test_control.py::TestTaskDispatcher_get_next_node::test_none",
"tests/test_control.py::TestTaskDispatcher_get_next_node::test_ready",
"tests/test_control.py::TestTaskDispatcher_get_next_node::test_to_run",
"tests/test_control.py::TestTaskDispatcher_get_next_node::test_to_run_none",
"tests/test_control.py::TestTaskDispatcher_update_waiting::test_wait_select",
"tests/test_control.py::TestTaskDispatcher_update_waiting::test_wait_run",
"tests/test_control.py::TestTaskDispatcher_update_waiting::test_wait_run_deps_not_ok",
"tests/test_control.py::TestTaskDispatcher_update_waiting::test_waiting_node_updated",
"tests/test_control.py::TestTaskDispatcher_dispatcher_generator::test_normal",
"tests/test_control.py::TestTaskDispatcher_dispatcher_generator::test_delayed_creation"
] | [] | MIT License | 160 |
|
mne-tools__mne-python-2193 | 6ccf41c6295760dcf36e2a1062132e5b319a4812 | 2015-06-08 23:11:35 | 632e49f0470fc9526936dbb474fd6aa46501fe4d | Eric89GXL: It seems to be working for me now, but it is horribly slow. Hopefully I can speed it up tomorrow.
dgwakeman: You are awesome! I am so excited for this!
Eric89GXL: FYI I added a couple more files to the testing dataset. BEMs have now been created for ico-2 surfaces (320 instead of 5120 or 1280) which is much faster.
The code at this point seems to work for homog 1-layer, I just need to track down a bug in the 3-layer case. Speed isn't too much worse than C for small shells (<= 1280) and actually faster for standard size (5120) because, while calculating the matrix coefficients is slower in Python, the inversion is much faster:
```
ico type layers time
2 (320) C 1 0.0300931930542
2 (320) Python 1 0.250679969788
2 (320) C 3 0.347531795502
2 (320) Python 3 2.41311502457
3 (1280) C 1 0.621548891068
3 (1280) Python 1 2.16235113144
3 (1280) C 3 12.2742669582
3 (1280) Python 3 21.4681899548
4 (5120) C 1 24.4842910767
4 (5120) Python 1 27.2853899002
4 (5120) C 3 643.578150034
4 (5120) Python 3 282.933717012
```
Just need to track down where that bug is, which I probably won't get to until next week.
Eric89GXL: Okay, 1- and 3-layer model and solution computation works now. Ready for review/merge from my end.
Eric89GXL: Ping @agramfort @dengemann this is ready for review
dengemann: @Eric89GXL amazing! How fast is it compared to the original code?
Eric89GXL: See comment above, faster for normal use case (3-layer 5120)
Eric89GXL: There might be additional ways of optimizing it, too, if there is interest
dengemann: > here might be additional ways of optimizing it, too, if there is interest
I'm already very impressed. Eric what do we need here, any testing desired?
Eric89GXL: Hopefully the unit tests are sufficient to make us confident in using it. But sure, if you want to test it out and make comments, it's welcome.
dengemann: > But sure, if you want to test it out and make comments, it's welcome.
I will trust you if you're confident ;)
Eric89GXL: Check out the tests, hopefully those will make us confident :) If they don't, then they can be expanded.
Eric89GXL: @dengemann comments addressed. FYI you asked about speed, and that made me optimize a bit more:
```
2 (320) 1 C 0.283627033234
2 (320) 1 Python 0.291443109512
2 (320) 3 C 0.465950012207
2 (320) 3 Python 2.45959687233
3 (1280) 1 C 0.660896062851
3 (1280) 1 Python 1.62492084503
3 (1280) 3 C 12.4721641541
3 (1280) 3 Python 11.3650319576
4 (5120) 1 C 24.9352688789
4 (5120) 1 Python 11.2639200687
4 (5120) 3 C 644.138396025
4 (5120) 3 Python 118.89906311
```
dengemann: Great!!! I will recompute all my BEMs to enjoy the speedy drive :)
> On 09 Jul 2015, at 18:31, Eric Larson <[email protected]> wrote:
>
> @dengemann comments addressed. FYI you asked about speed, and that made me optimize a bit more:
>
> 2 (320) 1 C 0.283627033234
> 2 (320) 1 Python 0.291443109512
> 2 (320) 3 C 0.465950012207
> 2 (320) 3 Python 2.45959687233
> 3 (1280) 1 C 0.660896062851
> 3 (1280) 1 Python 1.62492084503
> 3 (1280) 3 C 12.4721641541
> 3 (1280) 3 Python 11.3650319576
> 4 (5120) 1 C 24.9352688789
> 4 (5120) 1 Python 11.2639200687
> 4 (5120) 3 C 644.138396025
> 4 (5120) 3 Python 118.89906311
> —
> Reply to this email directly or view it on GitHub.
>
agramfort: please update what's new, rebase and +1 for merge !
thanks awesome ! | diff --git a/doc/source/python_reference.rst b/doc/source/python_reference.rst
index dc0967bcd..8ac585031 100644
--- a/doc/source/python_reference.rst
+++ b/doc/source/python_reference.rst
@@ -159,7 +159,8 @@ Functions:
read_trans
save_stc_as_volume
write_labels_to_annot
- write_bem_surface
+ write_bem_solution
+ write_bem_surfaces
write_cov
write_events
write_evokeds
@@ -544,6 +545,8 @@ Functions:
average_forward_solutions
convert_forward_solution
do_forward_solution
+ make_bem_model
+ make_bem_solution
make_forward_solution
make_field_map
make_sphere_model
diff --git a/doc/source/python_tutorial.rst b/doc/source/python_tutorial.rst
index bc3c9613c..0f2011a59 100644
--- a/doc/source/python_tutorial.rst
+++ b/doc/source/python_tutorial.rst
@@ -18,6 +18,7 @@ What you can do with MNE Python
- **Averaging** to get Evoked data
- **Compute SSP pojectors** to remove ECG and EOG artifacts
- **Compute ICA** to remove artifacts or select latent sources.
+ - **Boundary Element Modeling**: single and three-layer BEM model creation and solution computation.
- **Forward modeling**: BEM computation and mesh creation (see :ref:`ch_forward`)
- **Linear inverse solvers** (dSPM, sLORETA, MNE, LCMV, DICS)
- **Sparse inverse solvers** (L1/L2 mixed norm MxNE, Gamma Map, Time-Frequency MxNE)
@@ -35,8 +36,7 @@ What you can do with MNE Python
What you're not supposed to do with MNE Python
----------------------------------------------
- - **Boundary Element Modeling** use MNE and Freesurfer.
-
+ - **Brain and head surface segmentation** for use with BEM models -- use Freesurfer.
.. note:: Package based on the FIF file format from Neuromag. It can read and convert CTF, BTI/4D, KIT and various EEG formats to FIF.
diff --git a/doc/source/whats_new.rst b/doc/source/whats_new.rst
index 4b2c09803..04bd663b2 100644
--- a/doc/source/whats_new.rst
+++ b/doc/source/whats_new.rst
@@ -23,6 +23,10 @@ Changelog
- Add support to hide/show all sections with a single keypress ('h') in :class:`mne.report.Report` by `Mainak Jas`_
+ - Add support for BEM model creation :func:`mne.make_bem_model` by `Eric Larson`_
+
+ - Add support for BEM solution computation :func:`mne.make_bem_solution` by `Eric Larson`_
+
BUG
~~~
diff --git a/mne/__init__.py b/mne/__init__.py
index 04e1fc1c3..04566bc47 100644
--- a/mne/__init__.py
+++ b/mne/__init__.py
@@ -31,6 +31,9 @@ from .io.base import concatenate_raws
from .io.chpi import get_chpi_positions
from .io.meas_info import create_info
from .io.kit import read_epochs_kit
+from .bem import (make_sphere_model, make_bem_model, make_bem_solution,
+ read_bem_surfaces, write_bem_surface, write_bem_surfaces,
+ read_bem_solution, write_bem_solution)
from .cov import (read_cov, write_cov, Covariance,
compute_covariance, compute_raw_data_covariance,
whiten_evoked, make_ad_hoc_cov)
@@ -52,10 +55,8 @@ from .source_estimate import (read_source_estimate, MixedSourceEstimate,
spatio_temporal_tris_connectivity,
spatio_temporal_dist_connectivity,
save_stc_as_volume, extract_label_time_course)
-from .surface import (read_bem_surfaces, read_surface, write_bem_surface,
- write_surface, decimate_surface, read_morph_map,
- read_bem_solution, get_head_surf,
- get_meg_helmet_surf)
+from .surface import (read_surface, write_surface, decimate_surface,
+ read_morph_map, get_head_surf, get_meg_helmet_surf)
from .source_space import (read_source_spaces, vertex_to_mni,
write_source_spaces, setup_source_space,
setup_volume_source_space, SourceSpaces,
@@ -78,7 +79,6 @@ from .selection import read_selection
from .dipole import read_dipole, Dipole, fit_dipole
from . import channels
from .channels import equalize_channels, rename_channels, find_layout
-from .bem import make_sphere_model
from . import beamformer
from . import commands
diff --git a/mne/bem.py b/mne/bem.py
index d401bd6d2..a14d8f21c 100644
--- a/mne/bem.py
+++ b/mne/bem.py
@@ -12,10 +12,518 @@ import numpy as np
from scipy import linalg
from .fixes import partial
-from .utils import (verbose, logger, run_subprocess, get_subjects_dir)
+from .utils import (verbose, logger, run_subprocess, deprecated,
+ get_subjects_dir)
from .io.constants import FIFF
+from .io.write import (start_file, start_block, write_float, write_int,
+ write_float_matrix, write_int_matrix, end_block,
+ end_file)
+from .io.tag import find_tag
+from .io.tree import dir_tree_find
+from .io.open import fiff_open
from .externals.six import string_types
-from .surface import read_surface, write_bem_surface
+
+
+# ############################################################################
+# Compute BEM solution
+
+# define VEC_DIFF(from,to,diff) {\
+# (diff)[X] = (to)[X] - (from)[X];\
+
+# The following approach is based on:
+#
+# de Munck JC: "A linear discretization of the volume conductor boundary
+# integral equation using analytically integrated elements",
+# IEEE Trans Biomed Eng. 1992 39(9) : 986 - 990
+#
+
+
+def _calc_beta(rk, rk_norm, rk1, rk1_norm):
+ """These coefficients are used to calculate the magic vector omega"""
+ rkk1 = rk1[0] - rk[0]
+ size = np.sqrt(np.dot(rkk1, rkk1))
+ rkk1 /= size
+ num = rk_norm + np.dot(rk, rkk1)
+ den = rk1_norm + np.dot(rk1, rkk1)
+ res = np.log(num / den) / size
+ return res
+
+
+def _lin_pot_coeff(fros, tri_rr, tri_nn, tri_area):
+ """The linear potential matrix element computations"""
+ from .source_space import _fast_cross_nd_sum
+ omega = np.zeros((len(fros), 3))
+
+ # we replicate a little bit of the _get_solids code here for speed
+ v1 = tri_rr[np.newaxis, 0, :] - fros
+ v2 = tri_rr[np.newaxis, 1, :] - fros
+ v3 = tri_rr[np.newaxis, 2, :] - fros
+ triples = _fast_cross_nd_sum(v1, v2, v3)
+ l1 = np.sqrt(np.sum(v1 * v1, axis=1))
+ l2 = np.sqrt(np.sum(v2 * v2, axis=1))
+ l3 = np.sqrt(np.sum(v3 * v3, axis=1))
+ ss = (l1 * l2 * l3 +
+ np.sum(v1 * v2, axis=1) * l3 +
+ np.sum(v1 * v3, axis=1) * l2 +
+ np.sum(v2 * v3, axis=1) * l1)
+ solids = np.arctan2(triples, ss)
+
+ # We *could* subselect the good points from v1, v2, v3, triples, solids,
+ # l1, l2, and l3, but there are *very* few bad points. So instead we do
+ # some unnecessary calculations, and then omit them from the final
+ # solution. These three lines ensure we don't get invalid values in
+ # _calc_beta.
+ bad_mask = np.abs(solids) < np.pi / 1e6
+ l1[bad_mask] = 1.
+ l2[bad_mask] = 1.
+ l3[bad_mask] = 1.
+
+ # Calculate the magic vector vec_omega
+ beta = [_calc_beta(v1, l1, v2, l2)[:, np.newaxis],
+ _calc_beta(v2, l2, v3, l3)[:, np.newaxis],
+ _calc_beta(v3, l3, v1, l1)[:, np.newaxis]]
+ vec_omega = (beta[2] - beta[0]) * v1
+ vec_omega += (beta[0] - beta[1]) * v2
+ vec_omega += (beta[1] - beta[2]) * v3
+
+ area2 = 2.0 * tri_area
+ n2 = 1.0 / (area2 * area2)
+ # leave omega = 0 otherwise
+ # Put it all together...
+ yys = [v1, v2, v3]
+ idx = [0, 1, 2, 0, 2]
+ for k in range(3):
+ diff = yys[idx[k - 1]] - yys[idx[k + 1]]
+ zdots = _fast_cross_nd_sum(yys[idx[k + 1]], yys[idx[k - 1]], tri_nn)
+ omega[:, k] = -n2 * (area2 * zdots * 2. * solids -
+ triples * (diff * vec_omega).sum(axis=-1))
+ # omit the bad points from the solution
+ omega[bad_mask] = 0.
+ return omega
+
+
+def _correct_auto_elements(surf, mat):
+ """Improve auto-element approximation..."""
+ pi2 = 2.0 * np.pi
+ tris_flat = surf['tris'].ravel()
+ misses = pi2 - mat.sum(axis=1)
+ for j, miss in enumerate(misses):
+ # How much is missing?
+ n_memb = len(surf['neighbor_tri'][j])
+ # The node itself receives one half
+ mat[j, j] = miss / 2.0
+ # The rest is divided evenly among the member nodes...
+ miss /= (4.0 * n_memb)
+ members = np.where(j == tris_flat)[0]
+ mods = members % 3
+ offsets = np.array([[1, 2], [-1, 1], [-1, -2]])
+ tri_1 = members + offsets[mods, 0]
+ tri_2 = members + offsets[mods, 1]
+ for t1, t2 in zip(tri_1, tri_2):
+ mat[j, tris_flat[t1]] += miss
+ mat[j, tris_flat[t2]] += miss
+ return
+
+
+def _fwd_bem_lin_pot_coeff(surfs):
+ """Calculate the coefficients for linear collocation approach"""
+ # taken from fwd_bem_linear_collocation.c
+ nps = [surf['np'] for surf in surfs]
+ np_tot = sum(nps)
+ coeff = np.zeros((np_tot, np_tot))
+ offsets = np.cumsum(np.concatenate(([0], nps)))
+ for si_1, surf1 in enumerate(surfs):
+ rr_ord = np.arange(nps[si_1])
+ for si_2, surf2 in enumerate(surfs):
+ logger.info(" %s (%d) -> %s (%d) ..." %
+ (_bem_explain_surface(surf1['id']), nps[si_1],
+ _bem_explain_surface(surf2['id']), nps[si_2]))
+ tri_rr = surf2['rr'][surf2['tris']]
+ tri_nn = surf2['tri_nn']
+ tri_area = surf2['tri_area']
+ submat = coeff[offsets[si_1]:offsets[si_1 + 1],
+ offsets[si_2]:offsets[si_2 + 1]] # view
+ for k in range(surf2['ntri']):
+ tri = surf2['tris'][k]
+ if si_1 == si_2:
+ skip_idx = ((rr_ord == tri[0]) |
+ (rr_ord == tri[1]) |
+ (rr_ord == tri[2]))
+ else:
+ skip_idx = list()
+ # No contribution from a triangle that
+ # this vertex belongs to
+ # if sidx1 == sidx2 and (tri == j).any():
+ # continue
+ # Otherwise do the hard job
+ coeffs = _lin_pot_coeff(surf1['rr'], tri_rr[k], tri_nn[k],
+ tri_area[k])
+ coeffs[skip_idx] = 0.
+ submat[:, tri] -= coeffs
+ if si_1 == si_2:
+ _correct_auto_elements(surf1, submat)
+ return coeff
+
+
+def _fwd_bem_multi_solution(solids, gamma, nps):
+ """Do multi surface solution
+
+ * Invert I - solids/(2*M_PI)
+ * Take deflation into account
+ * The matrix is destroyed after inversion
+ * This is the general multilayer case
+
+ """
+ pi2 = 1.0 / (2 * np.pi)
+ n_tot = np.sum(nps)
+ assert solids.shape == (n_tot, n_tot)
+ nsurf = len(nps)
+ defl = 1.0 / n_tot
+ # Modify the matrix
+ offsets = np.cumsum(np.concatenate(([0], nps)))
+ for si_1 in range(nsurf):
+ for si_2 in range(nsurf):
+ mult = pi2 if gamma is None else pi2 * gamma[si_1, si_2]
+ slice_j = slice(offsets[si_1], offsets[si_1 + 1])
+ slice_k = slice(offsets[si_2], offsets[si_2 + 1])
+ solids[slice_j, slice_k] = defl - solids[slice_j, slice_k] * mult
+ solids += np.eye(n_tot)
+ return linalg.inv(solids, overwrite_a=True)
+
+
+def _fwd_bem_homog_solution(solids, nps):
+ """Helper to make a homogeneous solution"""
+ return _fwd_bem_multi_solution(solids, None, nps)
+
+
+def _fwd_bem_ip_modify_solution(solution, ip_solution, ip_mult, n_tri):
+ """Modify the solution according to the IP approach"""
+ n_last = n_tri[-1]
+ mult = (1.0 + ip_mult) / ip_mult
+
+ logger.info(' Combining...')
+ offsets = np.cumsum(np.concatenate(([0], n_tri)))
+ for si in range(len(n_tri)):
+ # Pick the correct submatrix (right column) and multiply
+ sub = solution[offsets[si]:offsets[si + 1], np.sum(n_tri[:-1]):]
+ # Multiply
+ sub -= 2 * np.dot(sub, ip_solution)
+
+ # The lower right corner is a special case
+ sub[-n_last:, -n_last:] += mult * ip_solution
+
+ # Final scaling
+ logger.info(' Scaling...')
+ solution *= ip_mult
+ return
+
+
+def _fwd_bem_linear_collocation_solution(m):
+ """Compute the linear collocation potential solution"""
+ # first, add surface geometries
+ from .surface import _complete_surface_info
+ for surf in m['surfs']:
+ _complete_surface_info(surf, verbose=False)
+
+ logger.info('Computing the linear collocation solution...')
+ logger.info(' Matrix coefficients...')
+ coeff = _fwd_bem_lin_pot_coeff(m['surfs'])
+ m['nsol'] = len(coeff)
+ logger.info(" Inverting the coefficient matrix...")
+ nps = [surf['np'] for surf in m['surfs']]
+ m['solution'] = _fwd_bem_multi_solution(coeff, m['gamma'], nps)
+ if len(m['surfs']) == 3:
+ ip_mult = m['sigma'][1] / m['sigma'][2]
+ if ip_mult <= FIFF.FWD_BEM_IP_APPROACH_LIMIT:
+ logger.info('IP approach required...')
+ logger.info(' Matrix coefficients (homog)...')
+ coeff = _fwd_bem_lin_pot_coeff([m['surfs'][-1]])
+ logger.info(' Inverting the coefficient matrix (homog)...')
+ ip_solution = _fwd_bem_homog_solution(coeff,
+ [m['surfs'][-1]['np']])
+ logger.info(' Modify the original solution to incorporate '
+ 'IP approach...')
+ _fwd_bem_ip_modify_solution(m['solution'], ip_solution, ip_mult,
+ nps)
+ m['bem_method'] = FIFF.FWD_BEM_LINEAR_COLL
+ logger.info("Solution ready.")
+
+
+@verbose
+def make_bem_solution(surfs, verbose=None):
+ """Create a BEM solution using the linear collocation approach
+
+ Parameters
+ ----------
+ surfs : list of dict
+ The BEM surfaces to use.
+ verbose : bool, str, int, or None
+ If not None, override default verbose level (see mne.verbose).
+
+ Returns
+ -------
+ bem : dict
+ The BEM solution.
+
+ Notes
+ -----
+ .. versionadded:: 0.10.0
+
+ See Also
+ --------
+ make_bem_model
+ read_bem_surfaces
+ write_bem_surfaces
+ read_bem_solution
+ write_bem_solution
+ """
+ logger.info('Approximation method : Linear collocation\n')
+ if isinstance(surfs, string_types):
+ # Load the surfaces
+ logger.info('Loading surfaces...')
+ surfs = read_bem_surfaces(surfs)
+ bem = dict(surfs=surfs)
+ _add_gamma_multipliers(bem)
+ if len(bem['surfs']) == 3:
+ logger.info('Three-layer model surfaces loaded.')
+ elif len(bem['surfs']) == 1:
+ logger.info('Homogeneous model surface loaded.')
+ else:
+ raise RuntimeError('Only 1- or 3-layer BEM computations supported')
+ _fwd_bem_linear_collocation_solution(bem)
+ logger.info('BEM geometry computations complete.')
+ return bem
+
+
+# ############################################################################
+# Make BEM model
+
+def _ico_downsample(surf, dest_grade):
+ """Downsample the surface if isomorphic to a subdivided icosahedron"""
+ from .surface import _get_ico_surface
+ n_tri = surf['ntri']
+ found = -1
+ bad_msg = ("A surface with %d triangles cannot be isomorphic with a "
+ "subdivided icosahedron." % surf['ntri'])
+ if n_tri % 20 != 0:
+ raise RuntimeError(bad_msg)
+ n_tri = n_tri // 20
+ found = int(round(np.log(n_tri) / np.log(4)))
+ if n_tri != 4 ** found:
+ raise RuntimeError(bad_msg)
+ del n_tri
+
+ if dest_grade > found:
+ raise RuntimeError('For this surface, decimation grade should be %d '
+ 'or less, not %s.' % (found, dest_grade))
+
+ source = _get_ico_surface(found)
+ dest = _get_ico_surface(dest_grade, patch_stats=True)
+ del dest['tri_cent']
+ del dest['tri_nn']
+ del dest['neighbor_tri']
+ del dest['tri_area']
+ if not np.array_equal(source['tris'], surf['tris']):
+ raise RuntimeError('The source surface has a matching number of '
+ 'triangles but ordering is wrong')
+ logger.info('Going from %dth to %dth subdivision of an icosahedron '
+ '(n_tri: %d -> %d)' % (found, dest_grade, surf['ntri'],
+ dest['ntri']))
+ # Find the mapping
+ dest['rr'] = surf['rr'][_get_ico_map(source, dest)]
+ return dest
+
+
+def _get_ico_map(fro, to):
+ """Helper to get a mapping between ico surfaces"""
+ from .surface import _compute_nearest
+ nearest, dists = _compute_nearest(fro['rr'], to['rr'], return_dists=True)
+ n_bads = (dists > 5e-3).sum()
+ if n_bads > 0:
+ raise RuntimeError('No matching vertex for %d destination vertices'
+ % (n_bads))
+ return nearest
+
+
+def _order_surfaces(surfs):
+ """Reorder the surfaces"""
+ if len(surfs) != 3:
+ return surfs
+ # we have three surfaces
+ surf_order = [FIFF.FIFFV_BEM_SURF_ID_HEAD,
+ FIFF.FIFFV_BEM_SURF_ID_SKULL,
+ FIFF.FIFFV_BEM_SURF_ID_BRAIN]
+ ids = np.array([surf['id'] for surf in surfs])
+ if set(ids) != set(surf_order):
+ raise RuntimeError('bad surface ids: %s' % ids)
+ order = [np.where(ids == id_)[0][0] for id_ in surf_order]
+ surfs = [surfs[idx] for idx in order]
+ return surfs
+
+
+def _assert_complete_surface(surf):
+ """Check the sum of solid angles as seen from inside"""
+ # from surface_checks.c
+ from .source_space import _get_solids
+ tot_angle = 0.
+ # Center of mass....
+ cm = surf['rr'].mean(axis=0)
+ logger.info('%s CM is %6.2f %6.2f %6.2f mm' %
+ (_surf_name[surf['id']],
+ 1000 * cm[0], 1000 * cm[1], 1000 * cm[2]))
+ tot_angle = _get_solids(surf['rr'][surf['tris']], cm[np.newaxis, :])[0]
+ if np.abs(tot_angle / (2 * np.pi) - 1.0) > 1e-5:
+ raise RuntimeError('Surface %s is not complete (sum of solid angles '
+ '= %g * 4*PI instead).' %
+ (_surf_name[surf['id']], tot_angle))
+
+
+_surf_name = {
+ FIFF.FIFFV_BEM_SURF_ID_HEAD: 'outer skin ',
+ FIFF.FIFFV_BEM_SURF_ID_SKULL: 'outer skull',
+ FIFF.FIFFV_BEM_SURF_ID_BRAIN: 'inner skull',
+ FIFF.FIFFV_BEM_SURF_ID_UNKNOWN: 'unknown ',
+}
+
+
+def _assert_inside(fro, to):
+ """Helper to check one set of points is inside a surface"""
+ # this is "is_inside" in surface_checks.c
+ from .source_space import _get_solids
+ tot_angle = _get_solids(to['rr'][to['tris']], fro['rr'])
+ if (np.abs(tot_angle / (2 * np.pi) - 1.0) > 1e-5).any():
+ raise RuntimeError('Surface %s is not completely inside surface %s'
+ % (_surf_name[fro['id']], _surf_name[to['id']]))
+
+
+def _check_surfaces(surfs):
+ """Check that the surfaces are complete and non-intersecting"""
+ for surf in surfs:
+ _assert_complete_surface(surf)
+ # Then check the topology
+ for surf_1, surf_2 in zip(surfs[:-1], surfs[1:]):
+ logger.info('Checking that %s surface is inside %s surface...' %
+ (_surf_name[surf_2['id']], _surf_name[surf_1['id']]))
+ _assert_inside(surf_2, surf_1)
+
+
+def _check_surface_size(surf):
+ """Check that the coordinate limits are reasonable"""
+ sizes = surf['rr'].max(axis=0) - surf['rr'].min(axis=0)
+ if (sizes < 0.05).any():
+ raise RuntimeError('Dimensions of the surface %s seem too small '
+ '(%9.5f mm). Maybe the the unit of measure is '
+ 'meters instead of mm' %
+ (_surf_name[surf['id']], 1000 * sizes.min()))
+
+
+def _check_thicknesses(surfs):
+ """How close are we?"""
+ from .surface import _compute_nearest
+ for surf_1, surf_2 in zip(surfs[:-1], surfs[1:]):
+ min_dist = _compute_nearest(surf_1['rr'], surf_2['rr'],
+ return_dists=True)[0]
+ min_dist = min_dist.min()
+ logger.info('Checking distance between %s and %s surfaces...' %
+ (_surf_name[surf_1['id']], _surf_name[surf_2['id']]))
+ logger.info('Minimum distance between the %s and %s surfaces is '
+ 'approximately %6.1f mm' %
+ (_surf_name[surf_1['id']], _surf_name[surf_2['id']],
+ 1000 * min_dist))
+
+
+def _surfaces_to_bem(fname_surfs, ids, sigmas, ico=None):
+ """Convert surfaces to a BEM
+ """
+ from .surface import _read_surface_geom
+ # equivalent of mne_surf2bem
+ surfs = list()
+ assert len(fname_surfs) in (1, 3)
+ for fname in fname_surfs:
+ surfs.append(_read_surface_geom(fname, patch_stats=False,
+ verbose=False))
+ surfs[-1]['rr'] /= 1000.
+ # Downsampling if the surface is isomorphic with a subdivided icosahedron
+ if ico is not None:
+ for si, surf in enumerate(surfs):
+ surfs[si] = _ico_downsample(surf, ico)
+ for surf, id_ in zip(surfs, ids):
+ surf['id'] = id_
+
+ # Shifting surfaces is not implemented here
+
+ # Order the surfaces for the benefit of the topology checks
+ for surf, sigma in zip(surfs, sigmas):
+ surf['sigma'] = sigma
+ surfs = _order_surfaces(surfs)
+
+ # Check topology as best we can
+ _check_surfaces(surfs)
+ for surf in surfs:
+ _check_surface_size(surf)
+ _check_thicknesses(surfs)
+ logger.info('Surfaces passed the basic topology checks.')
+ return surfs
+
+
+@verbose
+def make_bem_model(subject, ico=4, conductivity=(0.3, 0.006, 0.3),
+ subjects_dir=None, verbose=None):
+ """Create a BEM model for a subject
+
+ Parameters
+ ----------
+ subject : str
+ The subject.
+ ico : int | None
+ The surface ico downsampling to use, e.g. 5=20484, 4=5120, 3=1280.
+ conductivity : array of int, shape (3,) or (1,)
+ The conductivities to use for each shell. Should be a single element
+ for a one-layer model, or three elements for a three-layer model.
+ Defaults to ``[0.3, 0.006, 0.3]``. The MNE-C default for a
+ single-layer model would be ``[0.3]``.
+ subjects_dir : string, or None
+ Path to SUBJECTS_DIR if it is not set in the environment.
+ verbose : bool, str, int, or None
+ If not None, override default verbose level (see mne.verbose).
+
+ Returns
+ -------
+ surfaces : list of dict
+ The BEM surfaces.
+
+ Notes
+ -----
+ .. versionadded:: 0.10.0
+
+ See Also
+ --------
+ make_bem_solution
+ make_sphere_model
+ read_bem_surfaces
+ write_bem_surfaces
+ """
+ conductivity = np.array(conductivity, float)
+ if conductivity.ndim != 1 or conductivity.size not in (1, 3):
+ raise ValueError('conductivity must be 1D array-like with 1 or 3 '
+ 'elements')
+ subjects_dir = get_subjects_dir(subjects_dir, raise_error=True)
+ subject_dir = op.join(subjects_dir, subject)
+ bem_dir = op.join(subject_dir, 'bem')
+ inner_skull = op.join(bem_dir, 'inner_skull.surf')
+ outer_skull = op.join(bem_dir, 'outer_skull.surf')
+ outer_skin = op.join(bem_dir, 'outer_skin.surf')
+ surfaces = [inner_skull, outer_skull, outer_skin]
+ ids = [FIFF.FIFFV_BEM_SURF_ID_BRAIN,
+ FIFF.FIFFV_BEM_SURF_ID_SKULL,
+ FIFF.FIFFV_BEM_SURF_ID_HEAD]
+ logger.info('Creating the BEM geometry...')
+ if len(conductivity) == 1:
+ surfaces = surfaces[:1]
+ ids = ids[:1]
+ surfaces = _surfaces_to_bem(surfaces, ids, conductivity, ico)
+ logger.info('Complete.\n')
+ return surfaces
# ############################################################################
@@ -134,7 +642,7 @@ def _fwd_eeg_fit_berg_scherg(m, nterms, nfit):
# Do the nonlinear minimization, constraining mu to the interval [-1, +1]
mu_0 = np.random.RandomState(0).rand(nfit) * f
fun = partial(_one_step, u=u)
- cons = []
+ cons = list()
for ii in range(nfit):
for val in [1., -1.]:
cons.append({'type': 'ineq',
@@ -188,6 +696,11 @@ def make_sphere_model(r0=(0., 0., 0.04), head_radius=0.09, info=None,
Notes
-----
.. versionadded:: 0.9.0
+
+ See Also
+ --------
+ make_bem_model
+ make_bem_solution
"""
for name in ('r0', 'head_radius'):
param = locals()[name]
@@ -207,7 +720,7 @@ def make_sphere_model(r0=(0., 0., 0.04), head_radius=0.09, info=None,
head_radius = head_radius_fit / 1000.
sphere = dict(r0=np.array(r0), is_sphere=True,
coord_frame=FIFF.FIFFV_COORD_HEAD)
- sphere['layers'] = []
+ sphere['layers'] = list()
if head_radius is not None:
# Eventually these could be configurable...
relative_radii = np.array(relative_radii, float)
@@ -239,7 +752,7 @@ def make_sphere_model(r0=(0., 0., 0.04), head_radius=0.09, info=None,
rv = _fwd_eeg_fit_berg_scherg(sphere, 200, 3)
logger.info('\nEquiv. model fitting -> RV = %g %%' % (100 * rv))
for k in range(3):
- logger.info('mu%d = %g\tlambda%d = %g'
+ logger.info('mu%d = %g lambda%d = %g'
% (k + 1, sphere['mu'][k], k + 1,
layers[-1]['sigma'] * sphere['lambda'][k]))
logger.info('Set up EEG sphere model with scalp radius %7.1f mm\n'
@@ -371,6 +884,7 @@ def make_watershed_bem(subject, subjects_dir=None, overwrite=False,
.. versionadded:: 0.10
"""
+ from .surface import read_surface
env = os.environ.copy()
if not os.environ.get('FREESURFER_HOME'):
@@ -447,6 +961,358 @@ def make_watershed_bem(subject, subjects_dir=None, overwrite=False,
points *= 1e-3
surf = dict(coord_frame=5, id=4, nn=None, np=len(points),
ntri=len(tris), rr=points, sigma=1, tris=tris)
- write_bem_surface(subject + '-head.fif', surf)
+ write_bem_surfaces(subject + '-head.fif', surf)
logger.info('Created %s/%s-head.fif\n\nComplete.' % (bem_dir, subject))
+
+
+# ############################################################################
+# Read
+
+@verbose
+def read_bem_surfaces(fname, patch_stats=False, s_id=None, verbose=None):
+ """Read the BEM surfaces from a FIF file
+
+ Parameters
+ ----------
+ fname : string
+ The name of the file containing the surfaces.
+ patch_stats : bool, optional (default False)
+ Calculate and add cortical patch statistics to the surfaces.
+ s_id : int | None
+ If int, only read and return the surface with the given s_id.
+ An error will be raised if it doesn't exist. If None, all
+ surfaces are read and returned.
+ verbose : bool, str, int, or None
+ If not None, override default verbose level (see mne.verbose).
+
+ Returns
+ -------
+ surf: list | dict
+ A list of dictionaries that each contain a surface. If s_id
+ is not None, only the requested surface will be returned.
+ """
+ from .surface import _complete_surface_info
+ # Default coordinate frame
+ coord_frame = FIFF.FIFFV_COORD_MRI
+ # Open the file, create directory
+ f, tree, _ = fiff_open(fname)
+ with f as fid:
+ # Find BEM
+ bem = dir_tree_find(tree, FIFF.FIFFB_BEM)
+ if bem is None or len(bem) == 0:
+ raise ValueError('BEM data not found')
+
+ bem = bem[0]
+ # Locate all surfaces
+ bemsurf = dir_tree_find(bem, FIFF.FIFFB_BEM_SURF)
+ if bemsurf is None:
+ raise ValueError('BEM surface data not found')
+
+ logger.info(' %d BEM surfaces found' % len(bemsurf))
+ # Coordinate frame possibly at the top level
+ tag = find_tag(fid, bem, FIFF.FIFF_BEM_COORD_FRAME)
+ if tag is not None:
+ coord_frame = tag.data
+ # Read all surfaces
+ if s_id is not None:
+ surf = [_read_bem_surface(fid, bsurf, coord_frame, s_id)
+ for bsurf in bemsurf]
+ surf = [s for s in surf if s is not None]
+ if not len(surf) == 1:
+ raise ValueError('surface with id %d not found' % s_id)
+ else:
+ surf = list()
+ for bsurf in bemsurf:
+ logger.info(' Reading a surface...')
+ this = _read_bem_surface(fid, bsurf, coord_frame)
+ surf.append(this)
+ logger.info('[done]')
+ logger.info(' %d BEM surfaces read' % len(surf))
+ if patch_stats:
+ for this in surf:
+ _complete_surface_info(this)
+ return surf[0] if s_id is not None else surf
+
+
+def _read_bem_surface(fid, this, def_coord_frame, s_id=None):
+ """Read one bem surface
+ """
+ # fid should be open as a context manager here
+ res = dict()
+ # Read all the interesting stuff
+ tag = find_tag(fid, this, FIFF.FIFF_BEM_SURF_ID)
+
+ if tag is None:
+ res['id'] = FIFF.FIFFV_BEM_SURF_ID_UNKNOWN
+ else:
+ res['id'] = int(tag.data)
+
+ if s_id is not None and res['id'] != s_id:
+ return None
+
+ tag = find_tag(fid, this, FIFF.FIFF_BEM_SIGMA)
+ res['sigma'] = 1.0 if tag is None else float(tag.data)
+
+ tag = find_tag(fid, this, FIFF.FIFF_BEM_SURF_NNODE)
+ if tag is None:
+ raise ValueError('Number of vertices not found')
+
+ res['np'] = int(tag.data)
+
+ tag = find_tag(fid, this, FIFF.FIFF_BEM_SURF_NTRI)
+ if tag is None:
+ raise ValueError('Number of triangles not found')
+ res['ntri'] = int(tag.data)
+
+ tag = find_tag(fid, this, FIFF.FIFF_MNE_COORD_FRAME)
+ if tag is None:
+ tag = find_tag(fid, this, FIFF.FIFF_BEM_COORD_FRAME)
+ if tag is None:
+ res['coord_frame'] = def_coord_frame
+ else:
+ res['coord_frame'] = tag.data
+ else:
+ res['coord_frame'] = tag.data
+
+ # Vertices, normals, and triangles
+ tag = find_tag(fid, this, FIFF.FIFF_BEM_SURF_NODES)
+ if tag is None:
+ raise ValueError('Vertex data not found')
+
+ res['rr'] = tag.data.astype(np.float) # XXX : double because of mayavi bug
+ if res['rr'].shape[0] != res['np']:
+ raise ValueError('Vertex information is incorrect')
+
+ tag = find_tag(fid, this, FIFF.FIFF_MNE_SOURCE_SPACE_NORMALS)
+ if tag is None:
+ tag = tag = find_tag(fid, this, FIFF.FIFF_BEM_SURF_NORMALS)
+ if tag is None:
+ res['nn'] = list()
+ else:
+ res['nn'] = tag.data
+ if res['nn'].shape[0] != res['np']:
+ raise ValueError('Vertex normal information is incorrect')
+
+ tag = find_tag(fid, this, FIFF.FIFF_BEM_SURF_TRIANGLES)
+ if tag is None:
+ raise ValueError('Triangulation not found')
+
+ res['tris'] = tag.data - 1 # index start at 0 in Python
+ if res['tris'].shape[0] != res['ntri']:
+ raise ValueError('Triangulation information is incorrect')
+
+ return res
+
+
+@verbose
+def read_bem_solution(fname, verbose=None):
+ """Read the BEM solution from a file
+
+ Parameters
+ ----------
+ fname : string
+ The file containing the BEM solution.
+ verbose : bool, str, int, or None
+ If not None, override default verbose level (see mne.verbose).
+
+ Returns
+ -------
+ bem : dict
+ The BEM solution.
+ """
+ # mirrors fwd_bem_load_surfaces from fwd_bem_model.c
+ logger.info('Loading surfaces...')
+ bem_surfs = read_bem_surfaces(fname, patch_stats=True, verbose=False)
+ if len(bem_surfs) == 3:
+ logger.info('Three-layer model surfaces loaded.')
+ needed = np.array([FIFF.FIFFV_BEM_SURF_ID_HEAD,
+ FIFF.FIFFV_BEM_SURF_ID_SKULL,
+ FIFF.FIFFV_BEM_SURF_ID_BRAIN])
+ if not all(x['id'] in needed for x in bem_surfs):
+ raise RuntimeError('Could not find necessary BEM surfaces')
+ # reorder surfaces as necessary (shouldn't need to?)
+ reorder = [None] * 3
+ for x in bem_surfs:
+ reorder[np.where(x['id'] == needed)[0][0]] = x
+ bem_surfs = reorder
+ elif len(bem_surfs) == 1:
+ if not bem_surfs[0]['id'] == FIFF.FIFFV_BEM_SURF_ID_BRAIN:
+ raise RuntimeError('BEM Surfaces not found')
+ logger.info('Homogeneous model surface loaded.')
+
+ # convert from surfaces to solution
+ bem = dict(surfs=bem_surfs)
+ logger.info('\nLoading the solution matrix...\n')
+ f, tree, _ = fiff_open(fname)
+ with f as fid:
+ # Find the BEM data
+ nodes = dir_tree_find(tree, FIFF.FIFFB_BEM)
+ if len(nodes) == 0:
+ raise RuntimeError('No BEM data in %s' % fname)
+ bem_node = nodes[0]
+
+ # Approximation method
+ tag = find_tag(f, bem_node, FIFF.FIFF_BEM_APPROX)
+ if tag is None:
+ raise RuntimeError('No BEM solution found in %s' % fname)
+ method = tag.data[0]
+ if method not in (FIFF.FIFFV_BEM_APPROX_CONST,
+ FIFF.FIFFV_BEM_APPROX_LINEAR):
+ raise RuntimeError('Cannot handle BEM approximation method : %d'
+ % method)
+
+ tag = find_tag(fid, bem_node, FIFF.FIFF_BEM_POT_SOLUTION)
+ dims = tag.data.shape
+ if len(dims) != 2:
+ raise RuntimeError('Expected a two-dimensional solution matrix '
+ 'instead of a %d dimensional one' % dims[0])
+
+ dim = 0
+ for surf in bem['surfs']:
+ if method == FIFF.FIFFV_BEM_APPROX_LINEAR:
+ dim += surf['np']
+ else: # method == FIFF.FIFFV_BEM_APPROX_CONST
+ dim += surf['ntri']
+
+ if dims[0] != dim or dims[1] != dim:
+ raise RuntimeError('Expected a %d x %d solution matrix instead of '
+ 'a %d x %d one' % (dim, dim, dims[1], dims[0]))
+ sol = tag.data
+ nsol = dims[0]
+
+ bem['solution'] = sol
+ bem['nsol'] = nsol
+ bem['bem_method'] = method
+
+ # Gamma factors and multipliers
+ _add_gamma_multipliers(bem)
+ kind = {
+ FIFF.FIFFV_BEM_APPROX_CONST: 'constant collocation',
+ FIFF.FIFFV_BEM_APPROX_LINEAR: 'linear_collocation',
+ }[bem['bem_method']]
+ logger.info('Loaded %s BEM solution from %s', kind, fname)
+ return bem
+
+
+def _add_gamma_multipliers(bem):
+ """Helper to add gamma and multipliers in-place"""
+ bem['sigma'] = np.array([surf['sigma'] for surf in bem['surfs']])
+ # Dirty trick for the zero conductivity outside
+ sigma = np.r_[0.0, bem['sigma']]
+ bem['source_mult'] = 2.0 / (sigma[1:] + sigma[:-1])
+ bem['field_mult'] = sigma[1:] - sigma[:-1]
+ # make sure subsequent "zip"s work correctly
+ assert len(bem['surfs']) == len(bem['field_mult'])
+ bem['gamma'] = ((sigma[1:] - sigma[:-1])[np.newaxis, :] /
+ (sigma[1:] + sigma[:-1])[:, np.newaxis])
+ bem['is_sphere'] = False
+
+
+_surf_dict = {'inner_skull': FIFF.FIFFV_BEM_SURF_ID_BRAIN,
+ 'outer_skull': FIFF.FIFFV_BEM_SURF_ID_SKULL,
+ 'head': FIFF.FIFFV_BEM_SURF_ID_HEAD}
+
+
+def _bem_find_surface(bem, id_):
+ """Find surface from already-loaded BEM"""
+ if isinstance(id_, string_types):
+ name = id_
+ id_ = _surf_dict[id_]
+ else:
+ name = _bem_explain_surface(id_)
+ idx = np.where(np.array([s['id'] for s in bem['surfs']]) == id_)[0]
+ if len(idx) != 1:
+ raise RuntimeError('BEM model does not have the %s triangulation'
+ % name.replace('_', ' '))
+ return bem['surfs'][idx[0]]
+
+
+def _bem_explain_surface(id_):
+ """Return a string corresponding to the given surface ID"""
+ _rev_dict = dict((val, key) for key, val in _surf_dict.items())
+ return _rev_dict[id_]
+
+
+# ############################################################################
+# Write
+
+@deprecated('write_bem_surface is deprecated and will be removed in 0.11, '
+ 'use write_bem_surfaces instead')
+def write_bem_surface(fname, surf):
+ """Write one bem surface
+
+ Parameters
+ ----------
+ fname : string
+ File to write
+ surf : dict
+ A surface structured as obtained with read_bem_surfaces
+ """
+ write_bem_surfaces(fname, surf)
+
+
+def write_bem_surfaces(fname, surfs):
+ """Write BEM surfaces to a fiff file
+
+ Parameters
+ ----------
+ fname : str
+ Filename to write.
+ surfs : dict | list of dict
+ The surfaces, or a single surface.
+ """
+ if isinstance(surfs, dict):
+ surfs = [surfs]
+ with start_file(fname) as fid:
+ start_block(fid, FIFF.FIFFB_BEM)
+ write_int(fid, FIFF.FIFF_BEM_COORD_FRAME, surfs[0]['coord_frame'])
+ _write_bem_surfaces_block(fid, surfs)
+ end_block(fid, FIFF.FIFFB_BEM)
+ end_file(fid)
+
+
+def _write_bem_surfaces_block(fid, surfs):
+ """Helper to actually write bem surfaces"""
+ for surf in surfs:
+ start_block(fid, FIFF.FIFFB_BEM_SURF)
+ write_float(fid, FIFF.FIFF_BEM_SIGMA, surf['sigma'])
+ write_int(fid, FIFF.FIFF_BEM_SURF_ID, surf['id'])
+ write_int(fid, FIFF.FIFF_MNE_COORD_FRAME, surf['coord_frame'])
+ write_int(fid, FIFF.FIFF_BEM_SURF_NNODE, surf['np'])
+ write_int(fid, FIFF.FIFF_BEM_SURF_NTRI, surf['ntri'])
+ write_float_matrix(fid, FIFF.FIFF_BEM_SURF_NODES, surf['rr'])
+ # index start at 0 in Python
+ write_int_matrix(fid, FIFF.FIFF_BEM_SURF_TRIANGLES,
+ surf['tris'] + 1)
+ if 'nn' in surf and surf['nn'] is not None and len(surf['nn']) > 0:
+ write_float_matrix(fid, FIFF.FIFF_BEM_SURF_NORMALS, surf['nn'])
+ end_block(fid, FIFF.FIFFB_BEM_SURF)
+
+
+def write_bem_solution(fname, bem):
+ """Write a BEM model with solution
+
+ Parameters
+ ----------
+ fname : str
+ The filename to use.
+ bem : dict
+ The BEM model with solution to save.
+ """
+ with start_file(fname) as fid:
+ start_block(fid, FIFF.FIFFB_BEM)
+ # Coordinate frame (mainly for backward compatibility)
+ write_int(fid, FIFF.FIFF_BEM_COORD_FRAME,
+ bem['surfs'][0]['coord_frame'])
+ # Surfaces
+ _write_bem_surfaces_block(fid, bem['surfs'])
+ # The potential solution
+ if 'solution' in bem:
+ if bem['bem_method'] != FIFF.FWD_BEM_LINEAR_COLL:
+ raise RuntimeError('Only linear collocation supported')
+ write_int(fid, FIFF.FIFF_BEM_APPROX, FIFF.FIFFV_BEM_APPROX_LINEAR)
+ write_float_matrix(fid, FIFF.FIFF_BEM_POT_SOLUTION,
+ bem['solution'])
+ end_block(fid, FIFF.FIFFB_BEM)
+ end_file(fid)
diff --git a/mne/coreg.py b/mne/coreg.py
index 0ff42a35d..d3df15089 100644
--- a/mne/coreg.py
+++ b/mne/coreg.py
@@ -21,8 +21,8 @@ from .io.meas_info import read_fiducials, write_fiducials
from .label import read_label, Label
from .source_space import (add_source_space_distances, read_source_spaces,
write_source_spaces)
-from .surface import (read_surface, write_surface, read_bem_surfaces,
- write_bem_surface)
+from .surface import read_surface, write_surface
+from .bem import read_bem_surfaces, write_bem_surfaces
from .transforms import rotation, rotation3d, scaling, translation
from .utils import get_config, get_subjects_dir, logger, pformat
from functools import reduce
@@ -851,7 +851,7 @@ def scale_bem(subject_to, bem_name, subject_from=None, scale=None,
% src)
surf0 = surfs[0]
surf0['rr'] = surf0['rr'] * scale
- write_bem_surface(dst, surf0)
+ write_bem_surfaces(dst, surf0)
def scale_labels(subject_to, pattern=None, overwrite=False, subject_from=None,
diff --git a/mne/dipole.py b/mne/dipole.py
index 38d12bac5..5e86deb2e 100644
--- a/mne/dipole.py
+++ b/mne/dipole.py
@@ -22,9 +22,9 @@ from .forward._compute_forward import (_compute_forwards_meeg,
_prep_field_computation)
from .externals.six import string_types
-from .surface import (_bem_find_surface, transform_surface_to,
- _normalize_vectors, _get_ico_surface,
- _bem_explain_surface, _compute_nearest)
+from .surface import (transform_surface_to, _normalize_vectors,
+ _get_ico_surface, _compute_nearest)
+from .bem import _bem_find_surface, _bem_explain_surface
from .source_space import (_make_volume_source_space, SourceSpaces,
_points_outside_surface)
from .parallel import parallel_func
diff --git a/mne/forward/_compute_forward.py b/mne/forward/_compute_forward.py
index 5db0afb6c..668ca4f8a 100644
--- a/mne/forward/_compute_forward.py
+++ b/mne/forward/_compute_forward.py
@@ -687,7 +687,7 @@ def _prep_field_computation(rr, bem, fwd_data, n_jobs, verbose=None):
bem_rr = mults = mri_Q = head_mri_t = None
if not bem['is_sphere']:
- if bem['bem_method'] != 'linear collocation':
+ if bem['bem_method'] != FIFF.FWD_BEM_LINEAR_COLL:
raise RuntimeError('only linear collocation supported')
# Store (and apply soon) μ_0/(4π) factor before source computations
mults = np.repeat(bem['source_mult'] / (4.0 * np.pi),
diff --git a/mne/forward/_make_forward.py b/mne/forward/_make_forward.py
index bd8b6b312..c70d5347c 100644
--- a/mne/forward/_make_forward.py
+++ b/mne/forward/_make_forward.py
@@ -22,7 +22,8 @@ from ..transforms import (invert_transform, transform_surface_to, apply_trans,
from ..utils import logger, verbose
from ..source_space import (read_source_spaces, _filter_source_spaces,
SourceSpaces)
-from ..surface import read_bem_solution, _normalize_vectors, _bem_find_surface
+from ..surface import _normalize_vectors
+from ..bem import read_bem_solution, _bem_find_surface
from ..externals.six import string_types
diff --git a/mne/source_space.py b/mne/source_space.py
index 3a180db60..e58e52390 100644
--- a/mne/source_space.py
+++ b/mne/source_space.py
@@ -17,8 +17,9 @@ from .io.write import (start_block, end_block, write_int,
write_float_sparse_rcs, write_string,
write_float_matrix, write_int_matrix,
write_coord_trans, start_file, end_file, write_id)
+from .bem import read_bem_surfaces
from .surface import (read_surface, _create_surf_spacing, _get_ico_surface,
- _tessellate_sphere_surf, read_bem_surfaces,
+ _tessellate_sphere_surf,
_read_surface_geom, _normalize_vectors,
_complete_surface_info, _compute_nearest,
fast_cross_3d, _fast_cross_nd_sum)
diff --git a/mne/surface.py b/mne/surface.py
index 012d23c9b..d4a04e9b1 100644
--- a/mne/surface.py
+++ b/mne/surface.py
@@ -13,12 +13,12 @@ from glob import glob
import numpy as np
from scipy import sparse
+from .bem import read_bem_surfaces
from .io.constants import FIFF
from .io.open import fiff_open
from .io.tree import dir_tree_find
from .io.tag import find_tag
-from .io.write import (write_int, write_float, write_float_matrix,
- write_int_matrix, start_file, end_block,
+from .io.write import (write_int, start_file, end_block,
start_block, end_file, write_string,
write_float_sparse_rcs)
from .channels.channels import _get_meg_system
@@ -27,265 +27,6 @@ from .utils import logger, verbose, get_subjects_dir
from .externals.six import string_types
-##############################################################################
-# BEM
-
-@verbose
-def read_bem_surfaces(fname, patch_stats=False, s_id=None, verbose=None):
- """Read the BEM surfaces from a FIF file
-
- Parameters
- ----------
- fname : string
- The name of the file containing the surfaces.
- patch_stats : bool, optional (default False)
- Calculate and add cortical patch statistics to the surfaces.
- s_id : int | None
- If int, only read and return the surface with the given s_id.
- An error will be raised if it doesn't exist. If None, all
- surfaces are read and returned.
- verbose : bool, str, int, or None
- If not None, override default verbose level (see mne.verbose).
-
- Returns
- -------
- surf: list | dict
- A list of dictionaries that each contain a surface. If s_id
- is not None, only the requested surface will be returned.
- """
- # Default coordinate frame
- coord_frame = FIFF.FIFFV_COORD_MRI
- # Open the file, create directory
- f, tree, _ = fiff_open(fname)
- with f as fid:
- # Find BEM
- bem = dir_tree_find(tree, FIFF.FIFFB_BEM)
- if bem is None:
- raise ValueError('BEM data not found')
-
- bem = bem[0]
- # Locate all surfaces
- bemsurf = dir_tree_find(bem, FIFF.FIFFB_BEM_SURF)
- if bemsurf is None:
- raise ValueError('BEM surface data not found')
-
- logger.info(' %d BEM surfaces found' % len(bemsurf))
- # Coordinate frame possibly at the top level
- tag = find_tag(fid, bem, FIFF.FIFF_BEM_COORD_FRAME)
- if tag is not None:
- coord_frame = tag.data
- # Read all surfaces
- if s_id is not None:
- surfs = [_read_bem_surface(fid, bsurf, coord_frame, s_id)
- for bsurf in bemsurf]
- surfs = [s for s in surfs if s is not None]
- if not len(surfs) == 1:
- raise ValueError('surface with id %d not found' % s_id)
- return surfs[0]
-
- surf = []
- for bsurf in bemsurf:
- logger.info(' Reading a surface...')
- this = _read_bem_surface(fid, bsurf, coord_frame)
- logger.info('[done]')
- if patch_stats:
- _complete_surface_info(this)
- surf.append(this)
-
- logger.info(' %d BEM surfaces read' % len(surf))
- return surf
-
-
-def _read_bem_surface(fid, this, def_coord_frame, s_id=None):
- """Read one bem surface
- """
- # fid should be open as a context manager here
- res = dict()
- # Read all the interesting stuff
- tag = find_tag(fid, this, FIFF.FIFF_BEM_SURF_ID)
-
- if tag is None:
- res['id'] = FIFF.FIFFV_BEM_SURF_ID_UNKNOWN
- else:
- res['id'] = int(tag.data)
-
- if s_id is not None and res['id'] != s_id:
- return None
-
- tag = find_tag(fid, this, FIFF.FIFF_BEM_SIGMA)
- res['sigma'] = 1.0 if tag is None else float(tag.data)
-
- tag = find_tag(fid, this, FIFF.FIFF_BEM_SURF_NNODE)
- if tag is None:
- raise ValueError('Number of vertices not found')
-
- res['np'] = int(tag.data)
-
- tag = find_tag(fid, this, FIFF.FIFF_BEM_SURF_NTRI)
- if tag is None:
- raise ValueError('Number of triangles not found')
- res['ntri'] = int(tag.data)
-
- tag = find_tag(fid, this, FIFF.FIFF_MNE_COORD_FRAME)
- if tag is None:
- tag = find_tag(fid, this, FIFF.FIFF_BEM_COORD_FRAME)
- if tag is None:
- res['coord_frame'] = def_coord_frame
- else:
- res['coord_frame'] = tag.data
- else:
- res['coord_frame'] = tag.data
-
- # Vertices, normals, and triangles
- tag = find_tag(fid, this, FIFF.FIFF_BEM_SURF_NODES)
- if tag is None:
- raise ValueError('Vertex data not found')
-
- res['rr'] = tag.data.astype(np.float) # XXX : double because of mayavi bug
- if res['rr'].shape[0] != res['np']:
- raise ValueError('Vertex information is incorrect')
-
- tag = find_tag(fid, this, FIFF.FIFF_MNE_SOURCE_SPACE_NORMALS)
- if tag is None:
- tag = tag = find_tag(fid, this, FIFF.FIFF_BEM_SURF_NORMALS)
- if tag is None:
- res['nn'] = []
- else:
- res['nn'] = tag.data
- if res['nn'].shape[0] != res['np']:
- raise ValueError('Vertex normal information is incorrect')
-
- tag = find_tag(fid, this, FIFF.FIFF_BEM_SURF_TRIANGLES)
- if tag is None:
- raise ValueError('Triangulation not found')
-
- res['tris'] = tag.data - 1 # index start at 0 in Python
- if res['tris'].shape[0] != res['ntri']:
- raise ValueError('Triangulation information is incorrect')
-
- return res
-
-
-@verbose
-def read_bem_solution(fname, verbose=None):
- """Read the BEM solution from a file
-
- Parameters
- ----------
- fname : string
- The file containing the BEM solution.
- verbose : bool, str, int, or None
- If not None, override default verbose level (see mne.verbose).
-
- Returns
- -------
- bem : dict
- The BEM solution.
- """
- logger.info('Loading surfaces...')
- bem_surfs = read_bem_surfaces(fname, patch_stats=True, verbose=False)
- if len(bem_surfs) == 3:
- logger.info('Three-layer model surfaces loaded.')
- needed = np.array([FIFF.FIFFV_BEM_SURF_ID_HEAD,
- FIFF.FIFFV_BEM_SURF_ID_SKULL,
- FIFF.FIFFV_BEM_SURF_ID_BRAIN])
- if not all(x['id'] in needed for x in bem_surfs):
- raise RuntimeError('Could not find necessary BEM surfaces')
- # reorder surfaces as necessary (shouldn't need to?)
- reorder = [None] * 3
- for x in bem_surfs:
- reorder[np.where(x['id'] == needed)[0][0]] = x
- bem_surfs = reorder
- elif len(bem_surfs) == 1:
- if not bem_surfs[0]['id'] == FIFF.FIFFV_BEM_SURF_ID_BRAIN:
- raise RuntimeError('BEM Surfaces not found')
- logger.info('Homogeneous model surface loaded.')
-
- # convert from surfaces to solution
- bem = dict(surfs=bem_surfs)
- logger.info('\nLoading the solution matrix...\n')
- f, tree, _ = fiff_open(fname)
- with f as fid:
- # Find the BEM data
- nodes = dir_tree_find(tree, FIFF.FIFFB_BEM)
- if len(nodes) == 0:
- raise RuntimeError('No BEM data in %s' % fname)
- bem_node = nodes[0]
-
- # Approximation method
- tag = find_tag(f, bem_node, FIFF.FIFF_BEM_APPROX)
- method = tag.data[0]
- if method == FIFF.FIFFV_BEM_APPROX_CONST:
- method = 'constant collocation'
- elif method == FIFF.FIFFV_BEM_APPROX_LINEAR:
- method = 'linear collocation'
- else:
- raise RuntimeError('Cannot handle BEM approximation method : %d'
- % method)
-
- tag = find_tag(fid, bem_node, FIFF.FIFF_BEM_POT_SOLUTION)
- dims = tag.data.shape
- if len(dims) != 2:
- raise RuntimeError('Expected a two-dimensional solution matrix '
- 'instead of a %d dimensional one' % dims[0])
-
- dim = 0
- for surf in bem['surfs']:
- if method == 'linear collocation':
- dim += surf['np']
- else:
- dim += surf['ntri']
-
- if dims[0] != dim or dims[1] != dim:
- raise RuntimeError('Expected a %d x %d solution matrix instead of '
- 'a %d x %d one' % (dim, dim, dims[1], dims[0]))
- sol = tag.data
- nsol = dims[0]
-
- # Gamma factors and multipliers
- bem['sigma'] = np.array([surf['sigma'] for surf in bem['surfs']])
- # Dirty trick for the zero conductivity outside
- sigma = np.r_[0.0, bem['sigma']]
- bem['source_mult'] = 2.0 / (sigma[1:] + sigma[:-1])
- bem['field_mult'] = sigma[1:] - sigma[:-1]
- # make sure subsequent "zip"s work correctly
- assert len(bem['surfs']) == len(bem['field_mult'])
- bem['gamma'] = ((sigma[1:] - sigma[:-1])[np.newaxis, :] /
- (sigma[1:] + sigma[:-1])[:, np.newaxis])
- bem['sol_name'] = fname
- bem['solution'] = sol
- bem['nsol'] = nsol
- bem['bem_method'] = method
- bem['is_sphere'] = False
- logger.info('Loaded %s BEM solution from %s', bem['bem_method'], fname)
- return bem
-
-
-_surf_dict = {'inner_skull': FIFF.FIFFV_BEM_SURF_ID_BRAIN,
- 'outer_skull': FIFF.FIFFV_BEM_SURF_ID_SKULL,
- 'head': FIFF.FIFFV_BEM_SURF_ID_HEAD}
-
-
-def _bem_find_surface(bem, id_):
- """Find surface from already-loaded BEM"""
- if isinstance(id_, string_types):
- name = id_
- id_ = _surf_dict[id_]
- else:
- name = _bem_explain_surface[id_]
- idx = np.where(np.array([s['id'] for s in bem['surfs']]) == id_)[0]
- if len(idx) != 1:
- raise RuntimeError('BEM model does not have the %s triangulation'
- % name.replace('_', ' '))
- return bem['surfs'][idx[0]]
-
-
-def _bem_explain_surface(id_):
- """Return a string corresponding to the given surface ID"""
- _rev_dict = dict((val, key) for key, val in _surf_dict.items())
- return _rev_dict[id_]
-
-
###############################################################################
# AUTOMATED SURFACE FINDING
@@ -485,7 +226,8 @@ def _triangle_coords(r, geom, best):
return x, y, z
-def _complete_surface_info(this, do_neighbor_vert=False):
+@verbose
+def _complete_surface_info(this, do_neighbor_vert=False, verbose=None):
"""Complete surface info"""
# based on mne_source_space_add_geometry_info() in mne_add_geometry_info.c
@@ -736,13 +478,14 @@ def _read_surface_geom(fname, patch_stats=True, norm_rr=False, verbose=None):
##############################################################################
# SURFACE CREATION
-def _get_ico_surface(grade):
+def _get_ico_surface(grade, patch_stats=False):
"""Return an icosahedral surface of the desired grade"""
# always use verbose=False since users don't need to know we're pulling
# these from a file
ico_file_name = op.join(op.dirname(__file__), 'data',
'icos.fif.gz')
- ico = read_bem_surfaces(ico_file_name, s_id=9000 + grade, verbose=False)
+ ico = read_bem_surfaces(ico_file_name, patch_stats, s_id=9000 + grade,
+ verbose=False)
return ico
@@ -944,43 +687,7 @@ def write_surface(fname, coords, faces, create_stamp=''):
###############################################################################
-# Write
-
-def write_bem_surface(fname, surf):
- """Write one bem surface
-
- Parameters
- ----------
- fname : string
- File to write
- surf : dict
- A surface structured as obtained with read_bem_surfaces
- """
-
- # Create the file and save the essentials
- fid = start_file(fname)
-
- start_block(fid, FIFF.FIFFB_BEM)
- start_block(fid, FIFF.FIFFB_BEM_SURF)
-
- write_int(fid, FIFF.FIFF_BEM_SURF_ID, surf['id'])
- write_float(fid, FIFF.FIFF_BEM_SIGMA, surf['sigma'])
- write_int(fid, FIFF.FIFF_BEM_SURF_NNODE, surf['np'])
- write_int(fid, FIFF.FIFF_BEM_SURF_NTRI, surf['ntri'])
- write_int(fid, FIFF.FIFF_BEM_COORD_FRAME, surf['coord_frame'])
- write_float_matrix(fid, FIFF.FIFF_BEM_SURF_NODES, surf['rr'])
-
- if 'nn' in surf and surf['nn'] is not None and len(surf['nn']) > 0:
- write_float_matrix(fid, FIFF.FIFF_MNE_SOURCE_SPACE_NORMALS, surf['nn'])
-
- # index start at 0 in Python
- write_int_matrix(fid, FIFF.FIFF_BEM_SURF_TRIANGLES, surf['tris'] + 1)
-
- end_block(fid, FIFF.FIFFB_BEM_SURF)
- end_block(fid, FIFF.FIFFB_BEM)
-
- end_file(fid)
-
+# Decimation
def _decimate_surface(points, triangles, reduction):
"""Aux function"""
| implement bem-sol.fif code in python
for @Eric89GXL ... | mne-tools/mne-python | diff --git a/mne/tests/test_bem.py b/mne/tests/test_bem.py
index 8e7e06c2f..c8c0fc69b 100644
--- a/mne/tests/test_bem.py
+++ b/mne/tests/test_bem.py
@@ -2,16 +2,166 @@
#
# License: BSD 3 clause
+import os.path as op
import numpy as np
-from numpy.testing import assert_almost_equal
+from nose.tools import assert_raises
+from numpy.testing import assert_almost_equal, assert_equal, assert_allclose
+from mne import (make_bem_model, read_bem_surfaces, write_bem_surfaces,
+ make_bem_solution, read_bem_solution, write_bem_solution,
+ make_sphere_model)
from mne.preprocessing.maxfilter import fit_sphere_to_headshape
from mne.io.constants import FIFF
from mne.transforms import rotation
+from mne.datasets import testing
+from mne.utils import run_tests_if_main, _TempDir, slow_test
+from mne.bem import (_ico_downsample, _get_ico_map, _order_surfaces,
+ _assert_complete_surface, _assert_inside,
+ _check_surface_size, _bem_find_surface)
+from mne.io import read_info
+
+fname_raw = op.join(op.dirname(__file__), '..', 'io', 'tests', 'data',
+ 'test_raw.fif')
+subjects_dir = op.join(testing.data_path(download=False), 'subjects')
+fname_bem_3 = op.join(subjects_dir, 'sample', 'bem',
+ 'sample-320-320-320-bem.fif')
+fname_bem_1 = op.join(subjects_dir, 'sample', 'bem',
+ 'sample-320-bem.fif')
+fname_bem_sol_3 = op.join(subjects_dir, 'sample', 'bem',
+ 'sample-320-320-320-bem-sol.fif')
+fname_bem_sol_1 = op.join(subjects_dir, 'sample', 'bem',
+ 'sample-320-bem-sol.fif')
+
+
+def _compare_bem_surfaces(surfs_1, surfs_2):
+ """Helper to compare BEM surfaces"""
+ names = ['id', 'nn', 'rr', 'coord_frame', 'tris', 'sigma', 'ntri', 'np']
+ ignores = ['tri_cent', 'tri_nn', 'tri_area', 'neighbor_tri']
+ for s0, s1 in zip(surfs_1, surfs_2):
+ assert_equal(set(names), set(s0.keys()) - set(ignores))
+ assert_equal(set(names), set(s1.keys()) - set(ignores))
+ for name in names:
+ assert_allclose(s0[name], s1[name], rtol=1e-3, atol=1e-6,
+ err_msg='Mismatch: "%s"' % name)
+
+
+def _compare_bem_solutions(sol_a, sol_b):
+ """Helper to compare BEM solutions"""
+ # compare the surfaces we used
+ _compare_bem_surfaces(sol_a['surfs'], sol_b['surfs'])
+ # compare the actual solutions
+ names = ['bem_method', 'field_mult', 'gamma', 'is_sphere',
+ 'nsol', 'sigma', 'source_mult', 'solution']
+ assert_equal(set(sol_a.keys()), set(sol_b.keys()))
+ assert_equal(set(names + ['surfs']), set(sol_b.keys()))
+ for key in names:
+ assert_allclose(sol_a[key], sol_b[key], rtol=1e-3, atol=1e-5,
+ err_msg='Mismatch: %s' % key)
+
+
[email protected]_testing_data
+def test_io_bem():
+ """Test reading and writing of bem surfaces and solutions
+ """
+ tempdir = _TempDir()
+ temp_bem = op.join(tempdir, 'temp-bem.fif')
+ assert_raises(ValueError, read_bem_surfaces, fname_raw)
+ assert_raises(ValueError, read_bem_surfaces, fname_bem_3, s_id=10)
+ surf = read_bem_surfaces(fname_bem_3, patch_stats=True)
+ surf = read_bem_surfaces(fname_bem_3, patch_stats=False)
+ write_bem_surfaces(temp_bem, surf[0])
+ surf_read = read_bem_surfaces(temp_bem, patch_stats=False)
+ _compare_bem_surfaces(surf, surf_read)
+
+ assert_raises(RuntimeError, read_bem_solution, fname_bem_3)
+ temp_sol = op.join(tempdir, 'temp-sol.fif')
+ sol = read_bem_solution(fname_bem_sol_3)
+ write_bem_solution(temp_sol, sol)
+ sol_read = read_bem_solution(temp_sol)
+ _compare_bem_solutions(sol, sol_read)
+ sol = read_bem_solution(fname_bem_sol_1)
+ assert_raises(RuntimeError, _bem_find_surface, sol, 3)
+
+
+def test_make_sphere_model():
+ """Test making a sphere model"""
+ info = read_info(fname_raw)
+ assert_raises(ValueError, make_sphere_model, 'foo', 'auto', info)
+ assert_raises(ValueError, make_sphere_model, 'auto', 'auto', None)
+ # here we just make sure it works -- the functionality is actually
+ # tested more extensively e.g. in the forward and dipole code
+ make_sphere_model('auto', 'auto', info)
+
+
[email protected]_testing_data
+def test_bem_model():
+ """Test BEM model creation from Python with I/O"""
+ tempdir = _TempDir()
+ fname_temp = op.join(tempdir, 'temp-bem.fif')
+ for kwargs, fname in zip((dict(), dict(conductivity=[0.3])),
+ [fname_bem_3, fname_bem_1]):
+ model = make_bem_model('sample', ico=2, subjects_dir=subjects_dir,
+ **kwargs)
+ model_c = read_bem_surfaces(fname)
+ _compare_bem_surfaces(model, model_c)
+ write_bem_surfaces(fname_temp, model)
+ model_read = read_bem_surfaces(fname_temp)
+ _compare_bem_surfaces(model, model_c)
+ _compare_bem_surfaces(model_read, model_c)
+ assert_raises(ValueError, make_bem_model, 'sample', # bad conductivity
+ conductivity=[0.3, 0.006], subjects_dir=subjects_dir)
+
+
+@slow_test
[email protected]_testing_data
+def test_bem_solution():
+ """Test making a BEM solution from Python with I/O"""
+ # test degenerate conditions
+ surf = read_bem_surfaces(fname_bem_1)[0]
+ assert_raises(RuntimeError, _ico_downsample, surf, 10) # bad dec grade
+ s_bad = dict(tris=surf['tris'][1:], ntri=surf['ntri'] - 1, rr=surf['rr'])
+ assert_raises(RuntimeError, _ico_downsample, s_bad, 1) # not isomorphic
+ s_bad = dict(tris=surf['tris'].copy(), ntri=surf['ntri'],
+ rr=surf['rr']) # bad triangulation
+ s_bad['tris'][0] = [0, 0, 0]
+ assert_raises(RuntimeError, _ico_downsample, s_bad, 1)
+ s_bad['id'] = 1
+ assert_raises(RuntimeError, _assert_complete_surface, s_bad)
+ s_bad = dict(tris=surf['tris'], ntri=surf['ntri'], rr=surf['rr'].copy())
+ s_bad['rr'][0] = 0.
+ assert_raises(RuntimeError, _get_ico_map, surf, s_bad)
+
+ surfs = read_bem_surfaces(fname_bem_3)
+ assert_raises(RuntimeError, _assert_inside, surfs[0], surfs[1]) # outside
+ surfs[0]['id'] = 100 # bad surfs
+ assert_raises(RuntimeError, _order_surfaces, surfs)
+ surfs[1]['rr'] /= 1000.
+ assert_raises(RuntimeError, _check_surface_size, surfs[1])
+
+ # actually test functionality
+ tempdir = _TempDir()
+ fname_temp = op.join(tempdir, 'temp-bem-sol.fif')
+ # use a model and solution made in Python
+ conductivities = [(0.3,), (0.3, 0.006, 0.3)]
+ fnames = [fname_bem_sol_1, fname_bem_sol_3]
+ for cond, fname in zip(conductivities, fnames):
+ for model_type in ('python', 'c'):
+ if model_type == 'python':
+ model = make_bem_model('sample', conductivity=cond, ico=2,
+ subjects_dir=subjects_dir)
+ else:
+ model = fname_bem_1 if len(cond) == 1 else fname_bem_3
+ solution = make_bem_solution(model)
+ solution_c = read_bem_solution(fname)
+ _compare_bem_solutions(solution, solution_c)
+ write_bem_solution(fname_temp, solution)
+ solution_read = read_bem_solution(fname_temp)
+ _compare_bem_solutions(solution, solution_c)
+ _compare_bem_solutions(solution_read, solution_c)
def test_fit_sphere_to_headshape():
- """ Test fitting a sphere to digitization points. """
+ """Test fitting a sphere to digitization points"""
# Create points of various kinds
dig = [
# Left auricular
@@ -89,3 +239,6 @@ def test_fit_sphere_to_headshape():
assert_almost_equal(r / 1000, 1.0, decimal=2)
assert_almost_equal(oh / 1000, [0.0, 0.0, 0.0], decimal=2)
assert_almost_equal(od / 1000, [0.0, 0.0, 0.0], decimal=2)
+
+
+run_tests_if_main()
diff --git a/mne/tests/test_dipole.py b/mne/tests/test_dipole.py
index d93e38074..1ee82e682 100644
--- a/mne/tests/test_dipole.py
+++ b/mne/tests/test_dipole.py
@@ -17,7 +17,8 @@ from mne.proj import make_eeg_average_ref_proj
from mne.io import Raw
-from mne.surface import _bem_find_surface, _compute_nearest, read_bem_solution
+from mne.surface import _compute_nearest
+from mne.bem import _bem_find_surface, read_bem_solution
from mne.transforms import (read_trans, apply_trans, _get_mri_head_t)
warnings.simplefilter('always')
diff --git a/mne/tests/test_docstring_parameters.py b/mne/tests/test_docstring_parameters.py
index a3c50cf65..8cb83466d 100644
--- a/mne/tests/test_docstring_parameters.py
+++ b/mne/tests/test_docstring_parameters.py
@@ -59,7 +59,8 @@ def get_name(func):
_deprecation_ignores = [
'mne.io.write', # always ignore these
'mne.fixes._in1d', # fix function
- 'mne.utils.plot_epochs_trellis'
+ 'mne.utils.plot_epochs_trellis', # deprecated
+ 'mne.utils.write_bem_surface', # deprecated
]
diff --git a/mne/tests/test_surface.py b/mne/tests/test_surface.py
index f03d1b855..a7e0c1db5 100644
--- a/mne/tests/test_surface.py
+++ b/mne/tests/test_surface.py
@@ -6,12 +6,10 @@ import warnings
from shutil import copyfile
from scipy import sparse
from nose.tools import assert_true, assert_raises
-from numpy.testing import (assert_array_equal, assert_array_almost_equal,
- assert_allclose, assert_equal)
+from numpy.testing import assert_array_equal, assert_allclose, assert_equal
from mne.datasets import testing
-from mne import (read_bem_surfaces, write_bem_surface, read_surface,
- write_surface, decimate_surface)
+from mne import read_surface, write_surface, decimate_surface
from mne.surface import (read_morph_map, _compute_nearest,
fast_cross_3d, get_head_surf, read_curvature,
get_meg_helmet_surf)
@@ -117,23 +115,6 @@ def test_make_morph_maps():
assert_true((mm - sparse.eye(mm.shape[0], mm.shape[0])).sum() == 0)
[email protected]_testing_data
-def test_io_bem_surfaces():
- """Test reading of bem surfaces
- """
- tempdir = _TempDir()
- surf = read_bem_surfaces(fname, patch_stats=True)
- surf = read_bem_surfaces(fname, patch_stats=False)
- print("Number of surfaces : %d" % len(surf))
-
- write_bem_surface(op.join(tempdir, 'bem_surf.fif'), surf[0])
- surf_read = read_bem_surfaces(op.join(tempdir, 'bem_surf.fif'),
- patch_stats=False)
-
- for key in surf[0].keys():
- assert_array_almost_equal(surf[0][key], surf_read[0][key])
-
-
@testing.requires_testing_data
def test_io_surface():
"""Test reading and writing of Freesurfer surface mesh files
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 2,
"issue_text_score": 3,
"test_score": 3
},
"num_modified_files": 11
} | 0.9 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[dev]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"numpy>=1.16.0",
"pandas>=1.0.0",
"scikit-learn",
"h5py",
"pysurfer",
"nose",
"nose-timer",
"pytest"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.7",
"reqs_path": [
"requirements/base.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | apptools==5.2.1
certifi @ file:///croot/certifi_1671487769961/work/certifi
configobj==5.0.9
cycler==0.11.0
envisage==7.0.3
exceptiongroup==1.2.2
fonttools==4.38.0
h5py==3.8.0
importlib-metadata==6.7.0
importlib-resources==5.12.0
iniconfig==2.0.0
joblib==1.3.2
kiwisolver==1.4.5
matplotlib==3.5.3
mayavi==4.8.1
-e git+https://github.com/mne-tools/mne-python.git@6ccf41c6295760dcf36e2a1062132e5b319a4812#egg=mne
nibabel==4.0.2
nose==1.3.7
nose-timer==1.0.1
numpy==1.21.6
packaging==24.0
pandas==1.3.5
Pillow==9.5.0
pluggy==1.2.0
pyface==8.0.0
Pygments==2.17.2
pyparsing==3.1.4
pysurfer==0.11.2
pytest==7.4.4
python-dateutil==2.9.0.post0
pytz==2025.2
scikit-learn==1.0.2
scipy==1.7.3
six==1.17.0
threadpoolctl==3.1.0
tomli==2.0.1
traits==6.4.3
traitsui==8.0.0
typing_extensions==4.7.1
vtk==9.3.1
zipp==3.15.0
| name: mne-python
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2022.12.7=py37h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- pip=22.3.1=py37h06a4308_0
- python=3.7.16=h7a1cb2a_0
- readline=8.2=h5eee18b_0
- setuptools=65.6.3=py37h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- wheel=0.38.4=py37h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- apptools==5.2.1
- configobj==5.0.9
- cycler==0.11.0
- envisage==7.0.3
- exceptiongroup==1.2.2
- fonttools==4.38.0
- h5py==3.8.0
- importlib-metadata==6.7.0
- importlib-resources==5.12.0
- iniconfig==2.0.0
- joblib==1.3.2
- kiwisolver==1.4.5
- matplotlib==3.5.3
- mayavi==4.8.1
- nibabel==4.0.2
- nose==1.3.7
- nose-timer==1.0.1
- numpy==1.21.6
- packaging==24.0
- pandas==1.3.5
- pillow==9.5.0
- pluggy==1.2.0
- pyface==8.0.0
- pygments==2.17.2
- pyparsing==3.1.4
- pysurfer==0.11.2
- pytest==7.4.4
- python-dateutil==2.9.0.post0
- pytz==2025.2
- scikit-learn==1.0.2
- scipy==1.7.3
- six==1.17.0
- threadpoolctl==3.1.0
- tomli==2.0.1
- traits==6.4.3
- traitsui==8.0.0
- typing-extensions==4.7.1
- vtk==9.3.1
- zipp==3.15.0
prefix: /opt/conda/envs/mne-python
| [
"mne/tests/test_bem.py::test_make_sphere_model",
"mne/tests/test_bem.py::test_fit_sphere_to_headshape",
"mne/tests/test_docstring_parameters.py::test_docstring_parameters",
"mne/tests/test_surface.py::test_helmet",
"mne/tests/test_surface.py::test_huge_cross",
"mne/tests/test_surface.py::test_compute_nearest"
] | [] | [] | [] | BSD 3-Clause "New" or "Revised" License | 161 |
sympy__sympy-9493 | 8e592a0a34fed68ba3b88a58251d3ed9fa5f020c | 2015-06-09 15:16:19 | 0241b35cae5f2adc04dc37b25f7dc9c5f00bd746 | diff --git a/sympy/core/numbers.py b/sympy/core/numbers.py
index d1e4f02f47..22d6dc94e8 100644
--- a/sympy/core/numbers.py
+++ b/sympy/core/numbers.py
@@ -2467,6 +2467,8 @@ def _eval_power(self, expt):
return S.Zero
if expt is S.NaN:
return S.NaN
+ if expt is S.ComplexInfinity:
+ return S.NaN
if expt.is_number:
return self**expt.evalf()
| oo**zoo
oo**zoo give recursion error. | sympy/sympy | diff --git a/sympy/core/tests/test_numbers.py b/sympy/core/tests/test_numbers.py
index c5f5537266..b276249c85 100644
--- a/sympy/core/tests/test_numbers.py
+++ b/sympy/core/tests/test_numbers.py
@@ -1482,3 +1482,7 @@ def test_comp():
assert comp(sqrt(2).n(2), Float(1.4, 2), '')
raises(ValueError, lambda: comp(sqrt(2).n(2), 1.4, ''))
assert comp(sqrt(2).n(2), Float(1.4, 3), '') is False
+
+
+def test_issue_9491():
+ assert oo**zoo == nan
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_short_problem_statement"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 0,
"issue_text_score": 3,
"test_score": 2
},
"num_modified_files": 1
} | 0.7 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "pytest",
"pip_packages": [
"pytest"
],
"pre_install": null,
"python": "3.4",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | attrs @ file:///opt/conda/conda-bld/attrs_1642510447205/work
certifi==2021.5.30
importlib-metadata @ file:///tmp/build/80754af9/importlib-metadata_1631916693255/work
iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work
more-itertools @ file:///tmp/build/80754af9/more-itertools_1637733554872/work
mpmath==1.3.0
packaging @ file:///tmp/build/80754af9/packaging_1637314298585/work
pluggy @ file:///tmp/build/80754af9/pluggy_1615976315926/work
py @ file:///opt/conda/conda-bld/py_1644396412707/work
pyparsing @ file:///tmp/build/80754af9/pyparsing_1635766073266/work
pytest==6.2.4
-e git+https://github.com/sympy/sympy.git@8e592a0a34fed68ba3b88a58251d3ed9fa5f020c#egg=sympy
toml @ file:///tmp/build/80754af9/toml_1616166611790/work
typing_extensions @ file:///opt/conda/conda-bld/typing_extensions_1647553014482/work
zipp @ file:///tmp/build/80754af9/zipp_1633618647012/work
| name: sympy
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- attrs=21.4.0=pyhd3eb1b0_0
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- importlib-metadata=4.8.1=py36h06a4308_0
- importlib_metadata=4.8.1=hd3eb1b0_0
- iniconfig=1.1.1=pyhd3eb1b0_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- more-itertools=8.12.0=pyhd3eb1b0_0
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- packaging=21.3=pyhd3eb1b0_0
- pip=21.2.2=py36h06a4308_0
- pluggy=0.13.1=py36h06a4308_0
- py=1.11.0=pyhd3eb1b0_0
- pyparsing=3.0.4=pyhd3eb1b0_0
- pytest=6.2.4=py36h06a4308_2
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_0
- setuptools=58.0.4=py36h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- toml=0.10.2=pyhd3eb1b0_0
- typing_extensions=4.1.1=pyh06a4308_0
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- zipp=3.6.0=pyhd3eb1b0_0
- zlib=1.2.13=h5eee18b_1
- pip:
- mpmath==1.3.0
prefix: /opt/conda/envs/sympy
| [
"sympy/core/tests/test_numbers.py::test_issue_9491"
] | [] | [
"sympy/core/tests/test_numbers.py::test_integers_cache",
"sympy/core/tests/test_numbers.py::test_seterr",
"sympy/core/tests/test_numbers.py::test_mod",
"sympy/core/tests/test_numbers.py::test_divmod",
"sympy/core/tests/test_numbers.py::test_igcd",
"sympy/core/tests/test_numbers.py::test_ilcm",
"sympy/core/tests/test_numbers.py::test_igcdex",
"sympy/core/tests/test_numbers.py::test_Integer_new",
"sympy/core/tests/test_numbers.py::test_Rational_new",
"sympy/core/tests/test_numbers.py::test_Number_new",
"sympy/core/tests/test_numbers.py::test_Rational_cmp",
"sympy/core/tests/test_numbers.py::test_Float",
"sympy/core/tests/test_numbers.py::test_Float_default_to_highprec_from_str",
"sympy/core/tests/test_numbers.py::test_Float_eval",
"sympy/core/tests/test_numbers.py::test_Float_issue_2107",
"sympy/core/tests/test_numbers.py::test_Infinity",
"sympy/core/tests/test_numbers.py::test_Infinity_2",
"sympy/core/tests/test_numbers.py::test_Mul_Infinity_Zero",
"sympy/core/tests/test_numbers.py::test_Div_By_Zero",
"sympy/core/tests/test_numbers.py::test_Infinity_inequations",
"sympy/core/tests/test_numbers.py::test_NaN",
"sympy/core/tests/test_numbers.py::test_special_numbers",
"sympy/core/tests/test_numbers.py::test_powers",
"sympy/core/tests/test_numbers.py::test_integer_nthroot_overflow",
"sympy/core/tests/test_numbers.py::test_powers_Integer",
"sympy/core/tests/test_numbers.py::test_powers_Rational",
"sympy/core/tests/test_numbers.py::test_powers_Float",
"sympy/core/tests/test_numbers.py::test_abs1",
"sympy/core/tests/test_numbers.py::test_accept_int",
"sympy/core/tests/test_numbers.py::test_dont_accept_str",
"sympy/core/tests/test_numbers.py::test_int",
"sympy/core/tests/test_numbers.py::test_long",
"sympy/core/tests/test_numbers.py::test_real_bug",
"sympy/core/tests/test_numbers.py::test_bug_sqrt",
"sympy/core/tests/test_numbers.py::test_pi_Pi",
"sympy/core/tests/test_numbers.py::test_no_len",
"sympy/core/tests/test_numbers.py::test_issue_3321",
"sympy/core/tests/test_numbers.py::test_issue_3692",
"sympy/core/tests/test_numbers.py::test_issue_3423",
"sympy/core/tests/test_numbers.py::test_issue_3449",
"sympy/core/tests/test_numbers.py::test_Integer_factors",
"sympy/core/tests/test_numbers.py::test_Rational_factors",
"sympy/core/tests/test_numbers.py::test_issue_4107",
"sympy/core/tests/test_numbers.py::test_IntegerInteger",
"sympy/core/tests/test_numbers.py::test_Rational_gcd_lcm_cofactors",
"sympy/core/tests/test_numbers.py::test_Float_gcd_lcm_cofactors",
"sympy/core/tests/test_numbers.py::test_issue_4611",
"sympy/core/tests/test_numbers.py::test_conversion_to_mpmath",
"sympy/core/tests/test_numbers.py::test_relational",
"sympy/core/tests/test_numbers.py::test_Integer_as_index",
"sympy/core/tests/test_numbers.py::test_Rational_int",
"sympy/core/tests/test_numbers.py::test_zoo",
"sympy/core/tests/test_numbers.py::test_issue_4122",
"sympy/core/tests/test_numbers.py::test_GoldenRatio_expand",
"sympy/core/tests/test_numbers.py::test_as_content_primitive",
"sympy/core/tests/test_numbers.py::test_hashing_sympy_integers",
"sympy/core/tests/test_numbers.py::test_issue_4172",
"sympy/core/tests/test_numbers.py::test_Catalan_EulerGamma_prec",
"sympy/core/tests/test_numbers.py::test_Float_eq",
"sympy/core/tests/test_numbers.py::test_int_NumberSymbols",
"sympy/core/tests/test_numbers.py::test_issue_6640",
"sympy/core/tests/test_numbers.py::test_issue_6349",
"sympy/core/tests/test_numbers.py::test_mpf_norm",
"sympy/core/tests/test_numbers.py::test_latex",
"sympy/core/tests/test_numbers.py::test_issue_7742",
"sympy/core/tests/test_numbers.py::test_simplify_AlgebraicNumber",
"sympy/core/tests/test_numbers.py::test_Float_idempotence",
"sympy/core/tests/test_numbers.py::test_comp"
] | [] | BSD | 162 |
|
peterbe__premailer-128 | d2a2a4afdd06e5931545bc76b9ee940fdefdb543 | 2015-06-10 16:40:55 | d2a2a4afdd06e5931545bc76b9ee940fdefdb543 | diff --git a/README.rst b/README.rst
index 272a0b9..a3af844 100644
--- a/README.rst
+++ b/README.rst
@@ -221,7 +221,38 @@ attribute ``bgcolor="#eee"``.
Having these extra attributes basically as a "back up" for really shit
email clients that can't even take the style attributes. A lot of
professional HTML newsletters such as Amazon's use this. You can disable
-some attributes in ``disable_basic_attributes``
+some attributes in ``disable_basic_attributes``.
+
+
+Capturing logging from ``cssutils``
+-----------------------------------
+
+`cssutils <https://pypi.python.org/pypi/cssutils/>`__ is the library that
+``premailer`` uses to parse CSS. It will use the python ``logging`` module
+to mention all issues it has with parsing your CSS. If you want to capture
+this, you have to pass in ``cssutils_logging_handler`` and
+``cssutils_logging_level`` (optional). For example like this:
+
+.. code:: python
+
+ >>> import logging
+ >>> import premailer
+ >>> from io import StringIO
+ >>> mylog = StringIO()
+ >>> myhandler = logging.StreamHandler(mylog)
+ >>> p = premailer.Premailer("""
+ ... <html>
+ ... <style type="text/css">
+ ... @keyframes foo { from { opacity: 0; } to { opacity: 1; } }
+ ... </style>
+ ... <p>Hej</p>
+ ... </html>
+ ... """,
+ ... cssutils_logging_handler=myhandler,
+ ... cssutils_logging_level=logging.INFO)
+ >>> result = p.transform()
+ >>> mylog.getvalue()
+ 'CSSStylesheet: Unknown @rule found. [2:1: @keyframes]\n'
Running tests with tox
----------------------
diff --git a/premailer/premailer.py b/premailer/premailer.py
index e0ac5eb..4e5d49f 100644
--- a/premailer/premailer.py
+++ b/premailer/premailer.py
@@ -111,7 +111,9 @@ class Premailer(object):
base_path=None,
disable_basic_attributes=None,
disable_validation=False,
- cache_css_parsing=True):
+ cache_css_parsing=True,
+ cssutils_logging_handler=None,
+ cssutils_logging_level=None):
self.html = html
self.base_url = base_url
self.preserve_internal_links = preserve_internal_links
@@ -138,6 +140,11 @@ class Premailer(object):
self.disable_validation = disable_validation
self.cache_css_parsing = cache_css_parsing
+ if cssutils_logging_handler:
+ cssutils.log.addHandler(cssutils_logging_handler)
+ if cssutils_logging_level:
+ cssutils.log.setLevel(cssutils_logging_level)
+
def _parse_css_string(self, css_body, validate=True):
if self.cache_css_parsing:
return _cache_parse_css_string(css_body, validate=validate)
| Unknown property names
Property: Unknown Property name. [31:17: -ms-interpolation-mode]
Property: Unknown Property name. [4:17: mso-line-height-rule]
Property: Unknown Property name. [106:17: -webkit-text-size-adjust]
Property: Unknown Property name. [107:17: -ms-text-size-adjust]
Property: Unknown Property name. [188:21: text-rendering]
Property: Unknown Property name. [613:17: mso-text-raise]
Property: Unknown Property name. [624:17: transition]
Property: Unknown Property name.
I'm not sure what is this and what can I do about that..
Thanks for any help!
| peterbe/premailer | diff --git a/premailer/tests/test_premailer.py b/premailer/tests/test_premailer.py
index 4390a4e..dd9c07e 100644
--- a/premailer/tests/test_premailer.py
+++ b/premailer/tests/test_premailer.py
@@ -2,6 +2,7 @@ from __future__ import absolute_import, unicode_literals
import sys
import re
import unittest
+import logging
from contextlib import contextmanager
if sys.version_info >= (3, ): # As in, Python 3
from urllib.request import urlopen
@@ -2124,6 +2125,47 @@ ent:"" !important;display:block !important}
p = Premailer(html, disable_validation=True)
p.transform() # it should just work
+ def test_capture_cssutils_logging(self):
+ """you can capture all the warnings, errors etc. from cssutils
+ with your own logging. """
+ html = """<!doctype html>
+ <html>
+ <head>
+ <meta charset="UTF-8">
+ <title>Document</title>
+ <style>
+ @keyframes fadein {
+ from { opacity: 0; }
+ to { opacity: 1; }
+ }
+ </style>
+ </head>
+ <body></body>
+ </html>"""
+
+ mylog = StringIO()
+ myhandler = logging.StreamHandler(mylog)
+ p = Premailer(
+ html,
+ cssutils_logging_handler=myhandler,
+ )
+ p.transform() # it should work
+ eq_(
+ mylog.getvalue(),
+ 'CSSStylesheet: Unknown @rule found. [2:13: @keyframes]\n'
+ )
+
+ # only log errors now
+ mylog = StringIO()
+ myhandler = logging.StreamHandler(mylog)
+ p = Premailer(
+ html,
+ cssutils_logging_handler=myhandler,
+ cssutils_logging_level=logging.ERROR,
+ )
+ p.transform() # it should work
+ eq_(mylog.getvalue(), '')
+
def test_type_test(self):
"""test the correct type is returned"""
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 1,
"issue_text_score": 2,
"test_score": 3
},
"num_modified_files": 2
} | unknown | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"nose",
"mock",
"pytest"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.7",
"reqs_path": [
"requirements/base.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | certifi @ file:///croot/certifi_1671487769961/work/certifi
cssselect==1.2.0
cssutils==2.7.1
exceptiongroup==1.2.2
importlib-metadata==6.7.0
iniconfig==2.0.0
lxml==5.3.1
mock==5.2.0
nose==1.3.7
packaging==24.0
pluggy==1.2.0
-e git+https://github.com/peterbe/premailer.git@d2a2a4afdd06e5931545bc76b9ee940fdefdb543#egg=premailer
pytest==7.4.4
tomli==2.0.1
typing_extensions==4.7.1
zipp==3.15.0
| name: premailer
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2022.12.7=py37h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- pip=22.3.1=py37h06a4308_0
- python=3.7.16=h7a1cb2a_0
- readline=8.2=h5eee18b_0
- setuptools=65.6.3=py37h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- wheel=0.38.4=py37h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- cssselect==1.2.0
- cssutils==2.7.1
- exceptiongroup==1.2.2
- importlib-metadata==6.7.0
- iniconfig==2.0.0
- lxml==5.3.1
- mock==5.2.0
- nose==1.3.7
- packaging==24.0
- pluggy==1.2.0
- pytest==7.4.4
- tomli==2.0.1
- typing-extensions==4.7.1
- zipp==3.15.0
prefix: /opt/conda/envs/premailer
| [
"premailer/tests/test_premailer.py::Tests::test_capture_cssutils_logging"
] | [] | [
"premailer/tests/test_premailer.py::Tests::test_apple_newsletter_example",
"premailer/tests/test_premailer.py::Tests::test_base_url_fixer",
"premailer/tests/test_premailer.py::Tests::test_base_url_with_path",
"premailer/tests/test_premailer.py::Tests::test_basic_html",
"premailer/tests/test_premailer.py::Tests::test_basic_html_shortcut_function",
"premailer/tests/test_premailer.py::Tests::test_basic_html_with_pseudo_selector",
"premailer/tests/test_premailer.py::Tests::test_basic_xml",
"premailer/tests/test_premailer.py::Tests::test_broken_xml",
"premailer/tests/test_premailer.py::Tests::test_child_selector",
"premailer/tests/test_premailer.py::Tests::test_command_line_fileinput_from_argument",
"premailer/tests/test_premailer.py::Tests::test_command_line_fileinput_from_stdin",
"premailer/tests/test_premailer.py::Tests::test_command_line_preserve_style_tags",
"premailer/tests/test_premailer.py::Tests::test_comments_in_media_queries",
"premailer/tests/test_premailer.py::Tests::test_css_disable_basic_html_attributes",
"premailer/tests/test_premailer.py::Tests::test_css_text",
"premailer/tests/test_premailer.py::Tests::test_css_text_with_only_body_present",
"premailer/tests/test_premailer.py::Tests::test_css_with_html_attributes",
"premailer/tests/test_premailer.py::Tests::test_css_with_pseudoclasses_excluded",
"premailer/tests/test_premailer.py::Tests::test_css_with_pseudoclasses_included",
"premailer/tests/test_premailer.py::Tests::test_disabled_validator",
"premailer/tests/test_premailer.py::Tests::test_doctype",
"premailer/tests/test_premailer.py::Tests::test_empty_style_tag",
"premailer/tests/test_premailer.py::Tests::test_external_links",
"premailer/tests/test_premailer.py::Tests::test_external_links_unfindable",
"premailer/tests/test_premailer.py::Tests::test_external_styles_and_links",
"premailer/tests/test_premailer.py::Tests::test_external_styles_on_http",
"premailer/tests/test_premailer.py::Tests::test_external_styles_on_https",
"premailer/tests/test_premailer.py::Tests::test_external_styles_with_base_url",
"premailer/tests/test_premailer.py::Tests::test_favour_rule_with_class_over_generic",
"premailer/tests/test_premailer.py::Tests::test_favour_rule_with_element_over_generic",
"premailer/tests/test_premailer.py::Tests::test_favour_rule_with_id_over_others",
"premailer/tests/test_premailer.py::Tests::test_favour_rule_with_important_over_others",
"premailer/tests/test_premailer.py::Tests::test_fontface_selectors_with_no_selectortext",
"premailer/tests/test_premailer.py::Tests::test_ignore_some_external_stylesheets",
"premailer/tests/test_premailer.py::Tests::test_ignore_some_incorrectly",
"premailer/tests/test_premailer.py::Tests::test_ignore_some_inline_stylesheets",
"premailer/tests/test_premailer.py::Tests::test_ignore_style_elements_with_media_attribute",
"premailer/tests/test_premailer.py::Tests::test_include_star_selector",
"premailer/tests/test_premailer.py::Tests::test_inline_wins_over_external",
"premailer/tests/test_premailer.py::Tests::test_keyframe_selectors",
"premailer/tests/test_premailer.py::Tests::test_last_child",
"premailer/tests/test_premailer.py::Tests::test_last_child_exclude_pseudo",
"premailer/tests/test_premailer.py::Tests::test_leftover_important",
"premailer/tests/test_premailer.py::Tests::test_links_without_protocol",
"premailer/tests/test_premailer.py::Tests::test_load_external_url",
"premailer/tests/test_premailer.py::Tests::test_load_external_url_gzip",
"premailer/tests/test_premailer.py::Tests::test_mailto_url",
"premailer/tests/test_premailer.py::Tests::test_mediaquery",
"premailer/tests/test_premailer.py::Tests::test_merge_styles_basic",
"premailer/tests/test_premailer.py::Tests::test_merge_styles_non_trivial",
"premailer/tests/test_premailer.py::Tests::test_merge_styles_with_class",
"premailer/tests/test_premailer.py::Tests::test_mixed_pseudo_selectors",
"premailer/tests/test_premailer.py::Tests::test_multiple_style_elements",
"premailer/tests/test_premailer.py::Tests::test_multithreading",
"premailer/tests/test_premailer.py::Tests::test_parse_style_rules",
"premailer/tests/test_premailer.py::Tests::test_precedence_comparison",
"premailer/tests/test_premailer.py::Tests::test_prefer_inline_to_class",
"premailer/tests/test_premailer.py::Tests::test_shortcut_function",
"premailer/tests/test_premailer.py::Tests::test_strip_important",
"premailer/tests/test_premailer.py::Tests::test_style_attribute_specificity",
"premailer/tests/test_premailer.py::Tests::test_style_block_with_external_urls",
"premailer/tests/test_premailer.py::Tests::test_turnoff_cache_works_as_expected",
"premailer/tests/test_premailer.py::Tests::test_type_test",
"premailer/tests/test_premailer.py::Tests::test_xml_cdata"
] | [] | BSD 3-Clause "New" or "Revised" License | 163 |
|
Juniper__py-junos-eznc-386 | d850258f53611146f48db76842108beb9c4060b3 | 2015-06-11 18:43:09 | 4097eb9662e6caad8362b98e36a7ca50b122f92c | diff --git a/lib/jnpr/junos/facts/domain.py b/lib/jnpr/junos/facts/domain.py
index ed104f01..92eb03ad 100644
--- a/lib/jnpr/junos/facts/domain.py
+++ b/lib/jnpr/junos/facts/domain.py
@@ -1,4 +1,5 @@
from jnpr.junos.utils.fs import FS
+from jnpr.junos.exception import RpcError
from lxml.builder import E
@@ -11,14 +12,17 @@ def facts_domain(junos, facts):
facts['domain']
facts['fqdn']
"""
- # changes done to fix issue #332
- domain_filter_xml = E('configuration', E('system', E('domain-name')))
- domain = junos.rpc.get_config(domain_filter_xml)
- domain_name = domain.xpath('.//domain-name')
- if len(domain_name) > 0:
- facts['domain'] = domain_name[0].text
- facts['fqdn'] = facts['hostname'] + '.' + facts['domain']
- return
+
+ try:
+ domain_filter_xml = E('configuration', E('system', E('domain-name')))
+ domain = junos.rpc.get_config(domain_filter_xml)
+ domain_name = domain.xpath('.//domain-name')
+ if len(domain_name) > 0:
+ facts['domain'] = domain_name[0].text
+ facts['fqdn'] = facts['hostname'] + '.' + facts['domain']
+ return
+ except RpcError:
+ pass
fs = FS(junos)
file_content = fs.cat('/etc/resolv.conf') or fs.cat('/var/etc/resolv.conf')
| Domain fact gathering not in try block, RPCerror uncaught.
Was using 1.1.0 until this morning with ssh key authentication. After upgrade, connecting to the devices fails:
from jnpr.junos import Device
router = 'somerouter'
username = 'netconf'
path2keyfile = 'path2privatekey'
dev = Device(router, user=username, ssh_private_key_file=path2keyfile)
dev.open()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python2.7/dist-packages/jnpr/junos/device.py", line 494, in open
self.facts_refresh()
File "/usr/local/lib/python2.7/dist-packages/jnpr/junos/device.py", line 758, in facts_refresh
gather(self, self._facts)
File "/usr/local/lib/python2.7/dist-packages/jnpr/junos/facts/domain.py", line 16, in facts_domain
domain = junos.rpc.get_config(domain_filter_xml)
File "/usr/local/lib/python2.7/dist-packages/jnpr/junos/rpcmeta.py", line 43, in get_config
return self._junos.execute(rpc)
File "/usr/local/lib/python2.7/dist-packages/jnpr/junos/decorators.py", line 71, in wrapper
return function(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/jnpr/junos/decorators.py", line 26, in wrapper
return function(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/jnpr/junos/device.py", line 569, in execute
raise e(cmd=rpc_cmd_e, rsp=rsp)
jnpr.junos.exception.PermissionError: PermissionError(severity: error, bad_element: system, message: permission denied)
rolled back to 1.1.0 to confirm, and authentication was successful. With both versions, the target router logs the following in 'messages':
Jun 11 11:43:31 sshd[1258]: Accepted publickey for netconf from x.x.x.x port 40132 ssh2
Jun 11 11:43:31 sshd[1258]: subsystem request for netconf by user netconf
I am able to login interactively with the username/key combination.
| Juniper/py-junos-eznc | diff --git a/tests/unit/facts/test_domain.py b/tests/unit/facts/test_domain.py
index 62062557..e92a3313 100644
--- a/tests/unit/facts/test_domain.py
+++ b/tests/unit/facts/test_domain.py
@@ -8,6 +8,7 @@ from lxml import etree
from jnpr.junos.facts.domain import facts_domain
from jnpr.junos import Device
+from jnpr.junos.exception import RpcError
@attr('unit')
@@ -61,3 +62,16 @@ class TestDomain(unittest.TestCase):
facts_domain(self.dev, self.facts)
self.assertEqual(self.facts['domain'], 'testing.net')
self.assertEqual(self.facts['fqdn'], 'test.testing.net')
+
+ @patch('jnpr.junos.facts.domain.FS.cat')
+ def test_domain_rpc_error(self, mock_fs_cat):
+ self.dev.rpc.get_config = MagicMock(side_effect=RpcError)
+ mock_fs_cat.return_value =\
+ """# domain juniper.net
+ search englab.juniper.net spglab.juniper.net juniper.net jnpr.net
+ nameserver 10.11.12.13
+ """
+ self.facts['hostname'] = 'test'
+ facts_domain(self.dev, self.facts)
+ self.assertEqual(self.facts['domain'], 'juniper.net')
+ self.assertEqual(self.facts['fqdn'], 'test.juniper.net')
| {
"commit_name": "head_commit",
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true,
"llm_score": {
"difficulty_score": 0,
"issue_text_score": 1,
"test_score": 0
},
"num_modified_files": 1
} | 1.2 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[dev]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"coverage",
"mock",
"nose",
"pep8",
"pyflakes",
"coveralls",
"ntc_templates",
"cryptography==3.2",
"pytest"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.7",
"reqs_path": [
"requirements.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | bcrypt==4.2.1
certifi @ file:///croot/certifi_1671487769961/work/certifi
cffi==1.15.1
charset-normalizer==3.4.1
coverage==6.5.0
coveralls==3.3.1
cryptography==44.0.2
docopt==0.6.2
exceptiongroup==1.2.2
future==1.0.0
idna==3.10
importlib-metadata==6.7.0
iniconfig==2.0.0
Jinja2==3.1.6
-e git+https://github.com/Juniper/py-junos-eznc.git@d850258f53611146f48db76842108beb9c4060b3#egg=junos_eznc
lxml==5.3.1
MarkupSafe==2.1.5
mock==5.2.0
ncclient==0.6.19
netaddr==1.3.0
nose==1.3.7
ntc_templates==4.0.1
packaging==24.0
paramiko==3.5.1
pep8==1.7.1
pluggy==1.2.0
pycparser==2.21
pyflakes==3.0.1
PyNaCl==1.5.0
pytest==7.4.4
PyYAML==6.0.1
requests==2.31.0
scp==0.15.0
six==1.17.0
textfsm==1.1.3
tomli==2.0.1
typing_extensions==4.7.1
urllib3==2.0.7
zipp==3.15.0
| name: py-junos-eznc
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2022.12.7=py37h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- pip=22.3.1=py37h06a4308_0
- python=3.7.16=h7a1cb2a_0
- readline=8.2=h5eee18b_0
- setuptools=65.6.3=py37h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- wheel=0.38.4=py37h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- bcrypt==4.2.1
- cffi==1.15.1
- charset-normalizer==3.4.1
- coverage==6.5.0
- coveralls==3.3.1
- cryptography==44.0.2
- docopt==0.6.2
- exceptiongroup==1.2.2
- future==1.0.0
- idna==3.10
- importlib-metadata==6.7.0
- iniconfig==2.0.0
- jinja2==3.1.6
- lxml==5.3.1
- markupsafe==2.1.5
- mock==5.2.0
- ncclient==0.6.19
- netaddr==1.3.0
- nose==1.3.7
- ntc-templates==4.0.1
- packaging==24.0
- paramiko==3.5.1
- pep8==1.7.1
- pluggy==1.2.0
- pycparser==2.21
- pyflakes==3.0.1
- pynacl==1.5.0
- pytest==7.4.4
- pyyaml==6.0.1
- requests==2.31.0
- scp==0.15.0
- six==1.17.0
- textfsm==1.1.3
- tomli==2.0.1
- typing-extensions==4.7.1
- urllib3==2.0.7
- zipp==3.15.0
prefix: /opt/conda/envs/py-junos-eznc
| [
"tests/unit/facts/test_domain.py::TestDomain::test_domain_rpc_error"
] | [] | [
"tests/unit/facts/test_domain.py::TestDomain::test_domain_in_configuration",
"tests/unit/facts/test_domain.py::TestDomain::test_resolv_conf",
"tests/unit/facts/test_domain.py::TestDomain::test_resolv_conf_file_absent_under_etc",
"tests/unit/facts/test_domain.py::TestDomain::test_resolv_conf_no_domain"
] | [] | Apache License 2.0 | 164 |
|
pre-commit__pre-commit-hooks-66 | 6077f2fefb542fa4ffd3e2f305d1986645110645 | 2015-06-11 20:44:35 | f82fb149af2c1b552b50e3e38e38ed3a44d4cda1 | diff --git a/pre_commit_hooks/detect_private_key.py b/pre_commit_hooks/detect_private_key.py
index 215ad56..782b680 100644
--- a/pre_commit_hooks/detect_private_key.py
+++ b/pre_commit_hooks/detect_private_key.py
@@ -1,7 +1,6 @@
from __future__ import print_function
import argparse
-import io
import sys
@@ -13,12 +12,11 @@ def detect_private_key(argv=None):
private_key_files = []
for filename in args.filenames:
- with io.open(filename, 'r') as f:
- content = f.read()
- if 'BEGIN RSA PRIVATE KEY' in content:
- private_key_files.append(content)
- if 'BEGIN DSA PRIVATE KEY' in content:
- private_key_files.append(content)
+ content = open(filename, 'rb').read()
+ if b'BEGIN RSA PRIVATE KEY' in content:
+ private_key_files.append(content)
+ if b'BEGIN DSA PRIVATE KEY' in content:
+ private_key_files.append(content)
if private_key_files:
for private_key_file in private_key_files:
| detect-private-key hook appears to crash with images in the directory
Just added some images and a resources.qrc file to my PyQt4 project and got this error out of it. Is it because it tries to decode images as text?
```
Detect Private Key.......................................................Failed
hookid: detect-private-key
Traceback (most recent call last):
File "C:\cygwin64\home\builder\.pre-commit\repo7jrxo4\py_env-default\Scripts\detect-private-key-script.py", line 9, in \<module\>
load_entry_point('pre-commit-hooks==0.4.2', 'console_scripts', 'detect-private-key')()
File "C:\cygwin64\home\builder\.pre-commit\repo7jrxo4\py_env-default\lib\site-packages\pre_commit_hooks\detect_private_key.py", line 17, in detect_private_key
content = f.read()
File "C:\cygwin64\home\builder\.pre-commit\repo7jrxo4\py_env-default\lib\encodings\cp1252.py", line 23, in decode
return codecs.charmap_decode(input,self.errors,decoding_table)[0]
UnicodeDecodeError: 'charmap' codec can't decode byte 0x8f in position 44: character maps to \<undefined\>
``` | pre-commit/pre-commit-hooks | diff --git a/tests/detect_private_key_test.py b/tests/detect_private_key_test.py
index 6d2e627..c912624 100644
--- a/tests/detect_private_key_test.py
+++ b/tests/detect_private_key_test.py
@@ -10,6 +10,8 @@ TESTS = (
(b'-----BEGIN DSA PRIVATE KEY-----', 1),
(b'ssh-rsa DATA', 0),
(b'ssh-dsa DATA', 0),
+ # Some arbitrary binary data
+ (b'\xa2\xf1\x93\x12', 0),
)
| {
"commit_name": "head_commit",
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true,
"llm_score": {
"difficulty_score": 0,
"issue_text_score": 1,
"test_score": 1
},
"num_modified_files": 1
} | 0.4 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "pytest",
"pip_packages": [
"pytest"
],
"pre_install": null,
"python": "3.9",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | autopep8==2.3.2
exceptiongroup @ file:///croot/exceptiongroup_1706031385326/work
flake8==7.2.0
iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work
mccabe==0.7.0
packaging @ file:///croot/packaging_1734472117206/work
pluggy @ file:///croot/pluggy_1733169602837/work
-e git+https://github.com/pre-commit/pre-commit-hooks.git@6077f2fefb542fa4ffd3e2f305d1986645110645#egg=pre_commit_hooks
pycodestyle==2.13.0
pyflakes==3.3.1
pytest @ file:///croot/pytest_1738938843180/work
PyYAML==6.0.2
simplejson==3.20.1
tomli @ file:///opt/conda/conda-bld/tomli_1657175507142/work
| name: pre-commit-hooks
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- exceptiongroup=1.2.0=py39h06a4308_0
- iniconfig=1.1.1=pyhd3eb1b0_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=3.0.16=h5eee18b_0
- packaging=24.2=py39h06a4308_0
- pip=25.0=py39h06a4308_0
- pluggy=1.5.0=py39h06a4308_0
- pytest=8.3.4=py39h06a4308_0
- python=3.9.21=he870216_1
- readline=8.2=h5eee18b_0
- setuptools=75.8.0=py39h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- tomli=2.0.1=py39h06a4308_0
- tzdata=2025a=h04d1e81_0
- wheel=0.45.1=py39h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- argparse==1.4.0
- autopep8==2.3.2
- flake8==7.2.0
- mccabe==0.7.0
- pycodestyle==2.13.0
- pyflakes==3.3.1
- pyyaml==6.0.2
- simplejson==3.20.1
prefix: /opt/conda/envs/pre-commit-hooks
| [
"tests/detect_private_key_test.py::test_detect_private_key[\\xa2\\xf1\\x93\\x12-0]"
] | [] | [
"tests/detect_private_key_test.py::test_detect_private_key[-----BEGIN",
"tests/detect_private_key_test.py::test_detect_private_key[ssh-rsa",
"tests/detect_private_key_test.py::test_detect_private_key[ssh-dsa"
] | [] | MIT License | 165 |
|
scieloorg__xylose-77 | 35ee660d381ec682445b2014aadc4b1fa96e414a | 2015-06-12 18:46:22 | c0be8f42edd0a64900280c871c76b856c2a191f7 | diff --git a/setup.py b/setup.py
index 0193a00..bb78b72 100755
--- a/setup.py
+++ b/setup.py
@@ -7,7 +7,7 @@ except ImportError:
setup(
name="xylose",
- version='0.10b',
+ version='0.11b',
description="A SciELO library to abstract a JSON data structure that is a product of the ISIS2JSON conversion using the ISIS2JSON type 3 data model.",
author="SciELO",
author_email="[email protected]",
diff --git a/xylose/scielodocument.py b/xylose/scielodocument.py
index 5e7c073..59a6a86 100644
--- a/xylose/scielodocument.py
+++ b/xylose/scielodocument.py
@@ -25,8 +25,8 @@ else:
html_parser = unescape
# --------------
-LICENSE_REGEX = re.compile(r'a.+href="(.+)"')
-LICENSE_CREATIVE_COMMONS = re.compile(r'licenses/(.*?)/.') # Extracts the creative commons id from the url.
+LICENSE_REGEX = re.compile(r'a.+?href="(.+?)"')
+LICENSE_CREATIVE_COMMONS = re.compile(r'licenses/(.*?/\d\.\d)') # Extracts the creative commons id from the url.
DOI_REGEX = re.compile(r'\d{2}\.\d+/.*$')
def html_decode(string):
@@ -90,6 +90,7 @@ class Journal(object):
for dlicense in self.data['v540']:
if not 't' in dlicense:
continue
+
license_url = LICENSE_REGEX.findall(dlicense['t'])
if len(license_url) == 0:
continue
@@ -400,6 +401,7 @@ class Article(object):
for dlicense in self.data['v540']:
if not 't' in dlicense:
continue
+
license_url = LICENSE_REGEX.findall(dlicense['t'])
if len(license_url) == 0:
continue
| Ajustar identificação de licença
A identificação de licença coleta atualmente apenas o tipo da licença, ex:
by, by-nc.....
É importante também considerar a versão ex:
by/3.0
by/4.0
by-nc/3.0 | scieloorg/xylose | diff --git a/tests/test_document.py b/tests/test_document.py
index 745859f..db84c57 100644
--- a/tests/test_document.py
+++ b/tests/test_document.py
@@ -351,13 +351,13 @@ class JournalTests(unittest.TestCase):
journal = Journal(self.fulldoc['title'])
- self.assertEqual(journal.permissions['id'], 'by')
+ self.assertEqual(journal.permissions['id'], 'by/3.0')
def test_permission_id(self):
journal = Journal(self.fulldoc['title'])
- self.assertEqual(journal.permissions['id'], 'by-nc')
+ self.assertEqual(journal.permissions['id'], 'by-nc/3.0')
def test_permission_url(self):
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 1,
"issue_text_score": 2,
"test_score": 0
},
"num_modified_files": 2
} | 0.10 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "",
"pip_packages": [
"nose",
"coverage",
"mocker",
"pytest"
],
"pre_install": null,
"python": "3.9",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | coverage==7.8.0
exceptiongroup==1.2.2
iniconfig==2.1.0
mocker==1.1.1
nose==1.3.7
packaging==24.2
pluggy==1.5.0
pytest==8.3.5
tomli==2.2.1
-e git+https://github.com/scieloorg/xylose.git@35ee660d381ec682445b2014aadc4b1fa96e414a#egg=xylose
| name: xylose
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=3.0.16=h5eee18b_0
- pip=25.0=py39h06a4308_0
- python=3.9.21=he870216_1
- readline=8.2=h5eee18b_0
- setuptools=75.8.0=py39h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- tzdata=2025a=h04d1e81_0
- wheel=0.45.1=py39h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- coverage==7.8.0
- exceptiongroup==1.2.2
- iniconfig==2.1.0
- mocker==1.1.1
- nose==1.3.7
- packaging==24.2
- pluggy==1.5.0
- pytest==8.3.5
- tomli==2.2.1
prefix: /opt/conda/envs/xylose
| [
"tests/test_document.py::JournalTests::test_permission_id",
"tests/test_document.py::JournalTests::test_permission_t1"
] | [] | [
"tests/test_document.py::ToolsTests::test_get_language_iso639_1_defined",
"tests/test_document.py::ToolsTests::test_get_language_iso639_1_undefined",
"tests/test_document.py::ToolsTests::test_get_language_iso639_2_defined",
"tests/test_document.py::ToolsTests::test_get_language_iso639_2_undefined",
"tests/test_document.py::ToolsTests::test_get_language_without_iso_format",
"tests/test_document.py::ToolsTests::test_get_publication_date_wrong_day",
"tests/test_document.py::ToolsTests::test_get_publication_date_wrong_day_month",
"tests/test_document.py::ToolsTests::test_get_publication_date_wrong_day_month_not_int",
"tests/test_document.py::ToolsTests::test_get_publication_date_wrong_day_not_int",
"tests/test_document.py::ToolsTests::test_get_publication_date_wrong_month_not_int",
"tests/test_document.py::ToolsTests::test_get_publication_date_year",
"tests/test_document.py::ToolsTests::test_get_publication_date_year_day",
"tests/test_document.py::ToolsTests::test_get_publication_date_year_month",
"tests/test_document.py::ToolsTests::test_get_publication_date_year_month_day",
"tests/test_document.py::JournalTests::test_any_issn_priority_electronic",
"tests/test_document.py::JournalTests::test_any_issn_priority_electronic_without_electronic",
"tests/test_document.py::JournalTests::test_any_issn_priority_print",
"tests/test_document.py::JournalTests::test_any_issn_priority_print_without_print",
"tests/test_document.py::JournalTests::test_collection_acronym",
"tests/test_document.py::JournalTests::test_creation_date",
"tests/test_document.py::JournalTests::test_current_status",
"tests/test_document.py::JournalTests::test_current_status_lots_of_changes_study_case_1",
"tests/test_document.py::JournalTests::test_current_status_some_changes",
"tests/test_document.py::JournalTests::test_current_without_v51",
"tests/test_document.py::JournalTests::test_journal",
"tests/test_document.py::JournalTests::test_journal_abbreviated_title",
"tests/test_document.py::JournalTests::test_journal_acronym",
"tests/test_document.py::JournalTests::test_journal_title",
"tests/test_document.py::JournalTests::test_journal_title_nlm",
"tests/test_document.py::JournalTests::test_journal_url",
"tests/test_document.py::JournalTests::test_languages",
"tests/test_document.py::JournalTests::test_languages_without_v350",
"tests/test_document.py::JournalTests::test_load_issn_with_v935_and_v35_ONLINE",
"tests/test_document.py::JournalTests::test_load_issn_with_v935_and_v35_PRINT",
"tests/test_document.py::JournalTests::test_load_issn_with_v935_equal_v400_and_v35_ONLINE",
"tests/test_document.py::JournalTests::test_load_issn_with_v935_equal_v400_and_v35_PRINT",
"tests/test_document.py::JournalTests::test_load_issn_with_v935_without_v35",
"tests/test_document.py::JournalTests::test_load_issn_without_v935_and_v35_ONLINE",
"tests/test_document.py::JournalTests::test_load_issn_without_v935_and_v35_PRINT",
"tests/test_document.py::JournalTests::test_load_issn_without_v935_without_v35",
"tests/test_document.py::JournalTests::test_permission_text",
"tests/test_document.py::JournalTests::test_permission_url",
"tests/test_document.py::JournalTests::test_permission_without_v540",
"tests/test_document.py::JournalTests::test_permission_without_v540_t",
"tests/test_document.py::JournalTests::test_publisher_loc",
"tests/test_document.py::JournalTests::test_publisher_name",
"tests/test_document.py::JournalTests::test_scielo_issn",
"tests/test_document.py::JournalTests::test_status",
"tests/test_document.py::JournalTests::test_status_lots_of_changes",
"tests/test_document.py::JournalTests::test_status_lots_of_changes_study_case_1",
"tests/test_document.py::JournalTests::test_status_some_changes",
"tests/test_document.py::JournalTests::test_status_without_v51",
"tests/test_document.py::JournalTests::test_subject_areas",
"tests/test_document.py::JournalTests::test_update_date",
"tests/test_document.py::JournalTests::test_without_journal_abbreviated_title",
"tests/test_document.py::JournalTests::test_without_journal_acronym",
"tests/test_document.py::JournalTests::test_without_journal_title",
"tests/test_document.py::JournalTests::test_without_journal_title_nlm",
"tests/test_document.py::JournalTests::test_without_journal_url",
"tests/test_document.py::JournalTests::test_without_publisher_loc",
"tests/test_document.py::JournalTests::test_without_publisher_name",
"tests/test_document.py::JournalTests::test_without_scielo_domain",
"tests/test_document.py::JournalTests::test_without_scielo_domain_title_v690",
"tests/test_document.py::JournalTests::test_without_subject_areas",
"tests/test_document.py::JournalTests::test_without_wos_citation_indexes",
"tests/test_document.py::JournalTests::test_without_wos_subject_areas",
"tests/test_document.py::JournalTests::test_wos_citation_indexes",
"tests/test_document.py::JournalTests::test_wos_subject_areas",
"tests/test_document.py::ArticleTests::test_acceptance_date",
"tests/test_document.py::ArticleTests::test_affiliation_just_with_affiliation_name",
"tests/test_document.py::ArticleTests::test_affiliation_without_affiliation_name",
"tests/test_document.py::ArticleTests::test_affiliations",
"tests/test_document.py::ArticleTests::test_ahead_publication_date",
"tests/test_document.py::ArticleTests::test_article",
"tests/test_document.py::ArticleTests::test_author_with_two_affiliations",
"tests/test_document.py::ArticleTests::test_author_with_two_role",
"tests/test_document.py::ArticleTests::test_author_without_affiliations",
"tests/test_document.py::ArticleTests::test_author_without_surname_and_given_names",
"tests/test_document.py::ArticleTests::test_authors",
"tests/test_document.py::ArticleTests::test_collection_acronym",
"tests/test_document.py::ArticleTests::test_collection_acronym_priorizing_collection",
"tests/test_document.py::ArticleTests::test_collection_acronym_retrieving_v992",
"tests/test_document.py::ArticleTests::test_collection_name_brazil",
"tests/test_document.py::ArticleTests::test_collection_name_undefined",
"tests/test_document.py::ArticleTests::test_corporative_authors",
"tests/test_document.py::ArticleTests::test_document_type",
"tests/test_document.py::ArticleTests::test_doi",
"tests/test_document.py::ArticleTests::test_doi_clean_1",
"tests/test_document.py::ArticleTests::test_doi_clean_2",
"tests/test_document.py::ArticleTests::test_doi_v237",
"tests/test_document.py::ArticleTests::test_end_page_loaded_crazy_legacy_way_1",
"tests/test_document.py::ArticleTests::test_end_page_loaded_crazy_legacy_way_2",
"tests/test_document.py::ArticleTests::test_end_page_loaded_through_xml",
"tests/test_document.py::ArticleTests::test_file_code",
"tests/test_document.py::ArticleTests::test_file_code_crazy_slashs_1",
"tests/test_document.py::ArticleTests::test_file_code_crazy_slashs_2",
"tests/test_document.py::ArticleTests::test_first_author",
"tests/test_document.py::ArticleTests::test_first_author_without_author",
"tests/test_document.py::ArticleTests::test_fulltexts_field_fulltexts",
"tests/test_document.py::ArticleTests::test_fulltexts_without_field_fulltexts",
"tests/test_document.py::ArticleTests::test_html_url",
"tests/test_document.py::ArticleTests::test_invalid_document_type",
"tests/test_document.py::ArticleTests::test_issue",
"tests/test_document.py::ArticleTests::test_issue_label_field_v4",
"tests/test_document.py::ArticleTests::test_issue_label_without_field_v4",
"tests/test_document.py::ArticleTests::test_issue_url",
"tests/test_document.py::ArticleTests::test_journal_abbreviated_title",
"tests/test_document.py::ArticleTests::test_journal_acronym",
"tests/test_document.py::ArticleTests::test_journal_title",
"tests/test_document.py::ArticleTests::test_keywords",
"tests/test_document.py::ArticleTests::test_keywords_iso639_2",
"tests/test_document.py::ArticleTests::test_keywords_with_undefined_language",
"tests/test_document.py::ArticleTests::test_keywords_without_subfield_k",
"tests/test_document.py::ArticleTests::test_keywords_without_subfield_l",
"tests/test_document.py::ArticleTests::test_languages_field_fulltexts",
"tests/test_document.py::ArticleTests::test_languages_field_v40",
"tests/test_document.py::ArticleTests::test_last_page",
"tests/test_document.py::ArticleTests::test_mixed_affiliations",
"tests/test_document.py::ArticleTests::test_normalized_affiliations",
"tests/test_document.py::ArticleTests::test_normalized_affiliations_undefined_ISO_3166_CODE",
"tests/test_document.py::ArticleTests::test_normalized_affiliations_without_p",
"tests/test_document.py::ArticleTests::test_original_abstract_with_just_one_language_defined",
"tests/test_document.py::ArticleTests::test_original_abstract_with_language_defined",
"tests/test_document.py::ArticleTests::test_original_abstract_with_language_defined_but_different_of_the_article_original_language",
"tests/test_document.py::ArticleTests::test_original_abstract_without_language_defined",
"tests/test_document.py::ArticleTests::test_original_language_invalid_iso639_2",
"tests/test_document.py::ArticleTests::test_original_language_iso639_2",
"tests/test_document.py::ArticleTests::test_original_language_original",
"tests/test_document.py::ArticleTests::test_original_title_with_just_one_language_defined",
"tests/test_document.py::ArticleTests::test_original_title_with_language_defined",
"tests/test_document.py::ArticleTests::test_original_title_with_language_defined_but_different_of_the_article_original_language",
"tests/test_document.py::ArticleTests::test_original_title_without_language_defined",
"tests/test_document.py::ArticleTests::test_pdf_url",
"tests/test_document.py::ArticleTests::test_processing_date",
"tests/test_document.py::ArticleTests::test_project_name",
"tests/test_document.py::ArticleTests::test_project_sponsors",
"tests/test_document.py::ArticleTests::test_publication_contract",
"tests/test_document.py::ArticleTests::test_publication_date",
"tests/test_document.py::ArticleTests::test_publisher_id",
"tests/test_document.py::ArticleTests::test_publisher_loc",
"tests/test_document.py::ArticleTests::test_publisher_name",
"tests/test_document.py::ArticleTests::test_receive_date",
"tests/test_document.py::ArticleTests::test_review_date",
"tests/test_document.py::ArticleTests::test_start_page",
"tests/test_document.py::ArticleTests::test_start_page_loaded_crazy_legacy_way_1",
"tests/test_document.py::ArticleTests::test_start_page_loaded_crazy_legacy_way_2",
"tests/test_document.py::ArticleTests::test_start_page_loaded_through_xml",
"tests/test_document.py::ArticleTests::test_subject_areas",
"tests/test_document.py::ArticleTests::test_supplement_issue",
"tests/test_document.py::ArticleTests::test_supplement_volume",
"tests/test_document.py::ArticleTests::test_thesis_degree",
"tests/test_document.py::ArticleTests::test_thesis_organization",
"tests/test_document.py::ArticleTests::test_thesis_organization_and_division",
"tests/test_document.py::ArticleTests::test_thesis_organization_without_name",
"tests/test_document.py::ArticleTests::test_translated_abstracts",
"tests/test_document.py::ArticleTests::test_translated_abstracts_without_v83",
"tests/test_document.py::ArticleTests::test_translated_abtracts_iso639_2",
"tests/test_document.py::ArticleTests::test_translated_titles",
"tests/test_document.py::ArticleTests::test_translated_titles_iso639_2",
"tests/test_document.py::ArticleTests::test_translated_titles_without_v12",
"tests/test_document.py::ArticleTests::test_volume",
"tests/test_document.py::ArticleTests::test_whitwout_acceptance_date",
"tests/test_document.py::ArticleTests::test_whitwout_ahead_publication_date",
"tests/test_document.py::ArticleTests::test_whitwout_receive_date",
"tests/test_document.py::ArticleTests::test_whitwout_review_date",
"tests/test_document.py::ArticleTests::test_without_affiliations",
"tests/test_document.py::ArticleTests::test_without_authors",
"tests/test_document.py::ArticleTests::test_without_citations",
"tests/test_document.py::ArticleTests::test_without_collection_acronym",
"tests/test_document.py::ArticleTests::test_without_corporative_authors",
"tests/test_document.py::ArticleTests::test_without_document_type",
"tests/test_document.py::ArticleTests::test_without_doi",
"tests/test_document.py::ArticleTests::test_without_html_url",
"tests/test_document.py::ArticleTests::test_without_issue",
"tests/test_document.py::ArticleTests::test_without_issue_url",
"tests/test_document.py::ArticleTests::test_without_journal_abbreviated_title",
"tests/test_document.py::ArticleTests::test_without_journal_acronym",
"tests/test_document.py::ArticleTests::test_without_journal_title",
"tests/test_document.py::ArticleTests::test_without_keywords",
"tests/test_document.py::ArticleTests::test_without_last_page",
"tests/test_document.py::ArticleTests::test_without_normalized_affiliations",
"tests/test_document.py::ArticleTests::test_without_original_abstract",
"tests/test_document.py::ArticleTests::test_without_original_title",
"tests/test_document.py::ArticleTests::test_without_pages",
"tests/test_document.py::ArticleTests::test_without_pdf_url",
"tests/test_document.py::ArticleTests::test_without_processing_date",
"tests/test_document.py::ArticleTests::test_without_project_name",
"tests/test_document.py::ArticleTests::test_without_project_sponsor",
"tests/test_document.py::ArticleTests::test_without_publication_contract",
"tests/test_document.py::ArticleTests::test_without_publication_date",
"tests/test_document.py::ArticleTests::test_without_publisher_id",
"tests/test_document.py::ArticleTests::test_without_publisher_loc",
"tests/test_document.py::ArticleTests::test_without_publisher_name",
"tests/test_document.py::ArticleTests::test_without_scielo_domain",
"tests/test_document.py::ArticleTests::test_without_scielo_domain_article_v69",
"tests/test_document.py::ArticleTests::test_without_scielo_domain_article_v69_and_with_title_v690",
"tests/test_document.py::ArticleTests::test_without_scielo_domain_title_v690",
"tests/test_document.py::ArticleTests::test_without_start_page",
"tests/test_document.py::ArticleTests::test_without_subject_areas",
"tests/test_document.py::ArticleTests::test_without_suplement_issue",
"tests/test_document.py::ArticleTests::test_without_supplement_volume",
"tests/test_document.py::ArticleTests::test_without_thesis_degree",
"tests/test_document.py::ArticleTests::test_without_thesis_organization",
"tests/test_document.py::ArticleTests::test_without_volume",
"tests/test_document.py::ArticleTests::test_without_wos_citation_indexes",
"tests/test_document.py::ArticleTests::test_without_wos_subject_areas",
"tests/test_document.py::ArticleTests::test_wos_citation_indexes",
"tests/test_document.py::ArticleTests::test_wos_subject_areas",
"tests/test_document.py::CitationTest::test_a_link_access_date",
"tests/test_document.py::CitationTest::test_analytic_institution_for_a_article_citation",
"tests/test_document.py::CitationTest::test_analytic_institution_for_a_book_citation",
"tests/test_document.py::CitationTest::test_article_title",
"tests/test_document.py::CitationTest::test_article_without_title",
"tests/test_document.py::CitationTest::test_authors_article",
"tests/test_document.py::CitationTest::test_authors_book",
"tests/test_document.py::CitationTest::test_authors_link",
"tests/test_document.py::CitationTest::test_authors_thesis",
"tests/test_document.py::CitationTest::test_book_chapter_title",
"tests/test_document.py::CitationTest::test_book_edition",
"tests/test_document.py::CitationTest::test_book_volume",
"tests/test_document.py::CitationTest::test_book_without_chapter_title",
"tests/test_document.py::CitationTest::test_citation_sample_congress",
"tests/test_document.py::CitationTest::test_citation_sample_link",
"tests/test_document.py::CitationTest::test_citation_sample_link_without_comment",
"tests/test_document.py::CitationTest::test_conference_edition",
"tests/test_document.py::CitationTest::test_conference_name",
"tests/test_document.py::CitationTest::test_conference_sponsor",
"tests/test_document.py::CitationTest::test_conference_without_name",
"tests/test_document.py::CitationTest::test_conference_without_sponsor",
"tests/test_document.py::CitationTest::test_date",
"tests/test_document.py::CitationTest::test_doi",
"tests/test_document.py::CitationTest::test_editor",
"tests/test_document.py::CitationTest::test_end_page_14",
"tests/test_document.py::CitationTest::test_end_page_514",
"tests/test_document.py::CitationTest::test_end_page_withdout_data",
"tests/test_document.py::CitationTest::test_first_author_article",
"tests/test_document.py::CitationTest::test_first_author_book",
"tests/test_document.py::CitationTest::test_first_author_link",
"tests/test_document.py::CitationTest::test_first_author_thesis",
"tests/test_document.py::CitationTest::test_first_author_without_monographic_authors",
"tests/test_document.py::CitationTest::test_first_author_without_monographic_authors_but_not_a_book_citation",
"tests/test_document.py::CitationTest::test_index_number",
"tests/test_document.py::CitationTest::test_institutions_all_fields",
"tests/test_document.py::CitationTest::test_institutions_v11",
"tests/test_document.py::CitationTest::test_institutions_v17",
"tests/test_document.py::CitationTest::test_institutions_v29",
"tests/test_document.py::CitationTest::test_institutions_v50",
"tests/test_document.py::CitationTest::test_institutions_v58",
"tests/test_document.py::CitationTest::test_invalid_edition",
"tests/test_document.py::CitationTest::test_isbn",
"tests/test_document.py::CitationTest::test_isbn_but_not_a_book",
"tests/test_document.py::CitationTest::test_issn",
"tests/test_document.py::CitationTest::test_issn_but_not_an_article",
"tests/test_document.py::CitationTest::test_issue_part",
"tests/test_document.py::CitationTest::test_issue_title",
"tests/test_document.py::CitationTest::test_journal_issue",
"tests/test_document.py::CitationTest::test_journal_volume",
"tests/test_document.py::CitationTest::test_link",
"tests/test_document.py::CitationTest::test_link_title",
"tests/test_document.py::CitationTest::test_link_without_title",
"tests/test_document.py::CitationTest::test_monographic_authors",
"tests/test_document.py::CitationTest::test_monographic_first_author",
"tests/test_document.py::CitationTest::test_pages_14",
"tests/test_document.py::CitationTest::test_pages_514",
"tests/test_document.py::CitationTest::test_pages_withdout_data",
"tests/test_document.py::CitationTest::test_publication_type_article",
"tests/test_document.py::CitationTest::test_publication_type_book",
"tests/test_document.py::CitationTest::test_publication_type_conference",
"tests/test_document.py::CitationTest::test_publication_type_link",
"tests/test_document.py::CitationTest::test_publication_type_thesis",
"tests/test_document.py::CitationTest::test_publication_type_undefined",
"tests/test_document.py::CitationTest::test_publisher",
"tests/test_document.py::CitationTest::test_publisher_address",
"tests/test_document.py::CitationTest::test_publisher_address_without_e",
"tests/test_document.py::CitationTest::test_series_book",
"tests/test_document.py::CitationTest::test_series_but_neither_journal_book_or_conference_citation",
"tests/test_document.py::CitationTest::test_series_conference",
"tests/test_document.py::CitationTest::test_series_journal",
"tests/test_document.py::CitationTest::test_source_book_title",
"tests/test_document.py::CitationTest::test_source_journal",
"tests/test_document.py::CitationTest::test_source_journal_without_journal_title",
"tests/test_document.py::CitationTest::test_sponsor",
"tests/test_document.py::CitationTest::test_start_page_14",
"tests/test_document.py::CitationTest::test_start_page_514",
"tests/test_document.py::CitationTest::test_start_page_withdout_data",
"tests/test_document.py::CitationTest::test_thesis_institution",
"tests/test_document.py::CitationTest::test_thesis_title",
"tests/test_document.py::CitationTest::test_thesis_without_title",
"tests/test_document.py::CitationTest::test_title_when_article_citation",
"tests/test_document.py::CitationTest::test_title_when_conference_citation",
"tests/test_document.py::CitationTest::test_title_when_link_citation",
"tests/test_document.py::CitationTest::test_title_when_thesis_citation",
"tests/test_document.py::CitationTest::test_with_volume_but_not_a_journal_article_neither_a_book",
"tests/test_document.py::CitationTest::test_without_analytic_institution",
"tests/test_document.py::CitationTest::test_without_authors",
"tests/test_document.py::CitationTest::test_without_date",
"tests/test_document.py::CitationTest::test_without_doi",
"tests/test_document.py::CitationTest::test_without_edition",
"tests/test_document.py::CitationTest::test_without_editor",
"tests/test_document.py::CitationTest::test_without_first_author",
"tests/test_document.py::CitationTest::test_without_index_number",
"tests/test_document.py::CitationTest::test_without_institutions",
"tests/test_document.py::CitationTest::test_without_issue",
"tests/test_document.py::CitationTest::test_without_issue_part",
"tests/test_document.py::CitationTest::test_without_issue_title",
"tests/test_document.py::CitationTest::test_without_link",
"tests/test_document.py::CitationTest::test_without_monographic_authors",
"tests/test_document.py::CitationTest::test_without_monographic_authors_but_not_a_book_citation",
"tests/test_document.py::CitationTest::test_without_publisher",
"tests/test_document.py::CitationTest::test_without_publisher_address",
"tests/test_document.py::CitationTest::test_without_series",
"tests/test_document.py::CitationTest::test_without_sponsor",
"tests/test_document.py::CitationTest::test_without_thesis_institution",
"tests/test_document.py::CitationTest::test_without_volume"
] | [] | BSD 2-Clause "Simplified" License | 166 |
|
sympy__sympy-9517 | 7309abc4280aed095f2bc6128bb1f616a9c17693 | 2015-06-13 09:24:16 | 0241b35cae5f2adc04dc37b25f7dc9c5f00bd746 | diff --git a/sympy/core/evalf.py b/sympy/core/evalf.py
index 3e65cb7c6e..5c81d69c78 100644
--- a/sympy/core/evalf.py
+++ b/sympy/core/evalf.py
@@ -767,6 +767,9 @@ def evalf_trig(v, prec, options):
def evalf_log(expr, prec, options):
from sympy import Abs, Add, log
+ if len(expr.args)>1:
+ expr = expr.doit()
+ return evalf(expr, prec, options)
arg = expr.args[0]
workprec = prec + 10
xre, xim, xacc, _ = evalf(arg, workprec, options)
| log(100, 10, evaluate=False).evalf() != 2
```
>>> log(100, 10, evaluate=False).evalf()
4.60517018598809
```
This should be 2. It works if you don't add evaluate=False, so it might be related to that.
I'm using SymPy 3766b9ca505bb3645e81912b3cc883df73c7a32b | sympy/sympy | diff --git a/sympy/core/tests/test_evalf.py b/sympy/core/tests/test_evalf.py
index ef121ba210..45730131f5 100644
--- a/sympy/core/tests/test_evalf.py
+++ b/sympy/core/tests/test_evalf.py
@@ -128,6 +128,7 @@ def test_evalf_logs():
assert NS("log(3+pi*I)", 15) == '1.46877619736226 + 0.808448792630022*I'
assert NS("log(pi*I)", 15) == '1.14472988584940 + 1.57079632679490*I'
assert NS('log(-1 + 0.00001)', 2) == '-1.0e-5 + 3.1*I'
+ assert NS('log(100, 10, evaluate=False)', 15) == '2.00000000000000'
def test_evalf_trig():
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_short_problem_statement",
"has_git_commit_hash"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 0,
"issue_text_score": 0,
"test_score": 0
},
"num_modified_files": 1
} | 0.7 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "pytest",
"pip_packages": [
"pytest"
],
"pre_install": [
"apt-get update",
"apt-get install -y build-essential"
],
"python": "3.6",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | attrs @ file:///opt/conda/conda-bld/attrs_1642510447205/work
certifi==2021.5.30
importlib-metadata @ file:///tmp/build/80754af9/importlib-metadata_1631916693255/work
iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work
more-itertools @ file:///tmp/build/80754af9/more-itertools_1637733554872/work
mpmath==1.3.0
packaging @ file:///tmp/build/80754af9/packaging_1637314298585/work
pluggy @ file:///tmp/build/80754af9/pluggy_1615976315926/work
py @ file:///opt/conda/conda-bld/py_1644396412707/work
pyparsing @ file:///tmp/build/80754af9/pyparsing_1635766073266/work
pytest==6.2.4
-e git+https://github.com/sympy/sympy.git@7309abc4280aed095f2bc6128bb1f616a9c17693#egg=sympy
toml @ file:///tmp/build/80754af9/toml_1616166611790/work
typing_extensions @ file:///opt/conda/conda-bld/typing_extensions_1647553014482/work
zipp @ file:///tmp/build/80754af9/zipp_1633618647012/work
| name: sympy
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- attrs=21.4.0=pyhd3eb1b0_0
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- importlib-metadata=4.8.1=py36h06a4308_0
- importlib_metadata=4.8.1=hd3eb1b0_0
- iniconfig=1.1.1=pyhd3eb1b0_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- more-itertools=8.12.0=pyhd3eb1b0_0
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- packaging=21.3=pyhd3eb1b0_0
- pip=21.2.2=py36h06a4308_0
- pluggy=0.13.1=py36h06a4308_0
- py=1.11.0=pyhd3eb1b0_0
- pyparsing=3.0.4=pyhd3eb1b0_0
- pytest=6.2.4=py36h06a4308_2
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_0
- setuptools=58.0.4=py36h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- toml=0.10.2=pyhd3eb1b0_0
- typing_extensions=4.1.1=pyh06a4308_0
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- zipp=3.6.0=pyhd3eb1b0_0
- zlib=1.2.13=h5eee18b_1
- pip:
- mpmath==1.3.0
prefix: /opt/conda/envs/sympy
| [
"sympy/core/tests/test_evalf.py::test_evalf_logs"
] | [] | [
"sympy/core/tests/test_evalf.py::test_evalf_helpers",
"sympy/core/tests/test_evalf.py::test_evalf_basic",
"sympy/core/tests/test_evalf.py::test_cancellation",
"sympy/core/tests/test_evalf.py::test_evalf_powers",
"sympy/core/tests/test_evalf.py::test_evalf_rump",
"sympy/core/tests/test_evalf.py::test_evalf_complex",
"sympy/core/tests/test_evalf.py::test_evalf_complex_powers",
"sympy/core/tests/test_evalf.py::test_evalf_exponentiation",
"sympy/core/tests/test_evalf.py::test_evalf_complex_cancellation",
"sympy/core/tests/test_evalf.py::test_evalf_trig",
"sympy/core/tests/test_evalf.py::test_evalf_near_integers",
"sympy/core/tests/test_evalf.py::test_evalf_ramanujan",
"sympy/core/tests/test_evalf.py::test_evalf_bugs",
"sympy/core/tests/test_evalf.py::test_evalf_integer_parts",
"sympy/core/tests/test_evalf.py::test_evalf_trig_zero_detection",
"sympy/core/tests/test_evalf.py::test_evalf_sum",
"sympy/core/tests/test_evalf.py::test_evalf_divergent_series",
"sympy/core/tests/test_evalf.py::test_evalf_product",
"sympy/core/tests/test_evalf.py::test_evalf_py_methods",
"sympy/core/tests/test_evalf.py::test_evalf_power_subs_bugs",
"sympy/core/tests/test_evalf.py::test_evalf_arguments",
"sympy/core/tests/test_evalf.py::test_implemented_function_evalf",
"sympy/core/tests/test_evalf.py::test_evaluate_false",
"sympy/core/tests/test_evalf.py::test_evalf_relational",
"sympy/core/tests/test_evalf.py::test_issue_5486",
"sympy/core/tests/test_evalf.py::test_issue_5486_bug",
"sympy/core/tests/test_evalf.py::test_bugs",
"sympy/core/tests/test_evalf.py::test_subs",
"sympy/core/tests/test_evalf.py::test_issue_4956_5204",
"sympy/core/tests/test_evalf.py::test_old_docstring",
"sympy/core/tests/test_evalf.py::test_issue_4806",
"sympy/core/tests/test_evalf.py::test_evalf_mul",
"sympy/core/tests/test_evalf.py::test_scaled_zero",
"sympy/core/tests/test_evalf.py::test_chop_value",
"sympy/core/tests/test_evalf.py::test_infinities",
"sympy/core/tests/test_evalf.py::test_to_mpmath",
"sympy/core/tests/test_evalf.py::test_issue_6632_evalf",
"sympy/core/tests/test_evalf.py::test_issue_4945",
"sympy/core/tests/test_evalf.py::test_evalf_integral",
"sympy/core/tests/test_evalf.py::test_issue_8821_highprec_from_str",
"sympy/core/tests/test_evalf.py::test_issue_8853"
] | [] | BSD | 167 |
|
praw-dev__praw-426 | eb91d191eb09d94df144589ba6561f387a3a2922 | 2015-06-15 14:08:27 | eb91d191eb09d94df144589ba6561f387a3a2922 | diff --git a/praw/objects.py b/praw/objects.py
index df96fbf1..f4014f10 100755
--- a/praw/objects.py
+++ b/praw/objects.py
@@ -75,7 +75,7 @@ class RedditContentObject(object):
def __getattr__(self, attr):
"""Return the value of the `attr` attribute."""
- if not self.has_fetched:
+ if attr != '__setstate__' and not self.has_fetched:
self.has_fetched = self._populate(None, True)
return getattr(self, attr)
raise AttributeError('\'%s\' has no attribute \'%s\'' % (type(self),
| Can't unpickle Comment objects (maximum recursion depth exceeded)
Here's the stack trace:
```pytb
>>> import pickle
>>> import praw
>>> r = praw.Reddit('test')
>>> comment = r.get_info(thing_id='t1_cs6woop')
>>> pickled = pickle.dumps(comment)
>>> pickle.loads(pickled)
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/usr/lib/python2.7/pickle.py", line 1382, in loads
return Unpickler(file).load()
File "/usr/lib/python2.7/pickle.py", line 858, in load
dispatch[key](self)
File "/usr/lib/python2.7/pickle.py", line 1215, in load_build
setstate = getattr(inst, "__setstate__", None)
File "/home/___/.virtualenvs/___/local/lib/python2.7/site-packages/praw/objects.py", line 82, in __getattr__
if not self.has_fetched:
File "/home/___/.virtualenvs/___/local/lib/python2.7/site-packages/praw/objects.py", line 82, in __getattr__
if not self.has_fetched:
File "/home/___/.virtualenvs/___/local/lib/python2.7/site-packages/praw/objects.py", line 82, in __getattr__
if not self.has_fetched:
...
RuntimeError: maximum recursion depth exceeded
``` | praw-dev/praw | diff --git a/tests/cassettes/test_unpickle_comment.json b/tests/cassettes/test_unpickle_comment.json
new file mode 100644
index 00000000..ce5e4d79
--- /dev/null
+++ b/tests/cassettes/test_unpickle_comment.json
@@ -0,0 +1,1 @@
+{"recorded_with": "betamax/0.4.2", "http_interactions": [{"recorded_at": "2015-06-15T13:50:36", "response": {"status": {"code": 200, "message": "OK"}, "headers": {"transfer-encoding": ["chunked"], "cache-control": ["private, no-cache", "no-cache"], "server": ["cloudflare-nginx"], "set-cookie": ["__cfduid=d28895e21c18fe156bbe302205f9b22ac1434376236; expires=Tue, 14-Jun-16 13:50:36 GMT; path=/; domain=.reddit.com; HttpOnly", "secure_session=; Domain=reddit.com; Max-Age=-1434376237; Path=/; expires=Thu, 01-Jan-1970 00:00:01 GMT; HttpOnly", "reddit_session=7302867%2C2015-06-15T06%3A50%3A37%2Cc0e114b1f45a1bc763984b34c83d31df49a92fed; Domain=reddit.com; Path=/; HttpOnly"], "x-moose": ["majestic"], "x-xss-protection": ["1; mode=block"], "connection": ["keep-alive"], "content-encoding": ["gzip"], "pragma": ["no-cache"], "x-ua-compatible": ["IE=edge"], "x-frame-options": ["SAMEORIGIN"], "cf-ray": ["1f6ebeb510a504a3-CDG"], "date": ["Mon, 15 Jun 2015 13:50:37 GMT"], "content-type": ["application/json; charset=UTF-8"], "x-content-type-options": ["nosniff"]}, "body": {"encoding": "UTF-8", "base64_string": "H4sIAAAAAAAAAxzLTWrDMBBA4auIWSug0c+MpXNkV0oZWaM6TRMV26GL4LuXdPs+3hO+tnGHYp6g6zrWDYp5e7cGmuzyn++q7WPZ958Xdfne1Bq4jbbItkAxcPt8CD+uv3zBPElGVidEnZPXWmtLVSmRsnOkVTwqR7AG5jGuF339HJyfiK13mE6OTpjOjkpyJbCdnSLGij0mwTozhTzFGuI8hRaw9Zgl+64NjuP4AwAA//8DABH3aj7KAAAA"}, "url": "https://api.reddit.com/api/login/.json"}, "request": {"headers": {"Accept-Encoding": ["gzip, deflate"], "Connection": ["keep-alive"], "Accept": ["*/*"], "Content-Length": ["45"], "User-Agent": ["PRAW_test_suite PRAW/3.0a1 Python/2.7.8 Linux-3.16.0-37-generic-x86_64-with-Ubuntu-14.10-utopic"], "Content-Type": ["application/x-www-form-urlencoded"]}, "body": {"encoding": "utf-8", "string": "passwd=1111&api_type=json&user=PyAPITestUser2"}, "uri": "https://api.reddit.com/api/login/.json", "method": "POST"}}, {"recorded_at": "2015-06-15T13:50:37", "response": {"status": {"code": 200, "message": "OK"}, "headers": {"x-ratelimit-remaining": ["299"], "content-type": ["application/json; charset=UTF-8"], "cache-control": ["private, no-cache", "no-cache"], "content-length": ["2574"], "server": ["cloudflare-nginx"], "x-content-type-options": ["nosniff"], "x-moose": ["majestic"], "x-ratelimit-used": ["1"], "x-frame-options": ["SAMEORIGIN"], "x-sup-id": ["http://www.reddit.com/sup.json#e4356386a7"], "x-xss-protection": ["1; mode=block"], "connection": ["keep-alive"], "content-encoding": ["gzip"], "pragma": ["no-cache"], "x-ua-compatible": ["IE=edge"], "x-reddit-tracking": ["https://pixel.redditmedia.com/pixel/of_destiny.png?v=HcLLGdCwZSCTj%2BYMBgG8Ln0%2FKHA5a%2FIoJVNJ%2Fv%2FXrv6TSUaosRpQ67%2Fyfcg6Z7i5Diz8FZevtuCHzUmagS6TUQ7G47Go4bcv"], "cf-ray": ["1f6ebeb9f0cd04a3-CDG"], "date": ["Mon, 15 Jun 2015 13:50:37 GMT"], "x-ratelimit-reset": ["563"], "vary": ["accept-encoding"]}, "body": {"encoding": "UTF-8", "base64_string": "H4sIAC3YflUC/+2cW2/bRhqG/4rgi6KLzcRzPqQoFotFgV1gL3rRYi/qhTAnRox1ikT5FPS/d2ZIKpTkOpJFUrLrG8cmafKd+b734Ts0oy8X1/nUXXwYXPw3Xxb59OPFu8GF04UOm75cTGZupJejuNsvVlO4yPESeWSVdAR7yz3VAmVQQwup4BZxCWVmtDeCIB7PZEf52C38NJzhty/rSxVo4yrLlVl45/JimJe72RAXbJZOMM6n18MiL8Y+7vlffp0PfpoWi/vBbDq4WkFoSfyqbDzW6OnUu6G5D4dOV+Nx2LTwk9mNHg8XXi9nUUW1PZ22uhoZEirvaLG+nF4Vo9ki7vv5/p8//+cXvyx+XfoFLg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QLIzjQVEGgiPYI4bBHuWPJoa7v+ycHy/sgR9mmZjRvAx1bLzEQBDmlHkBtFKASWaA1lUBCzK1h2GJ8oiecBwjsARFloXcRQTtHROjrJiJqK0UnRSNFHzVt9AQiKq3niYhXGy5g+stE14hoM1xs53tuMJUaZUBLFOiNvANGaQE0F4IbKKGxJ3oT6yCJPVCirPUuJUjnS5D2gkSl9Twp8VqDhJU9vej9dXzHUmKPbP/NJQgl+G0J0qj/NjkIx52To618sdZ6nuQghiEmlAwRMkCDMkyA1FkWH2obmyFvnTv6ESdfrHonh7ntJV+kNhWdfB6WIZZyEyDumIOACmuBzCgCIbAaw1i4cdGU/PqPFwcI7B4RVaF3EYE6X4KEvm4iorZSdFI0UvRR00ZPIKLSep6IeK3honpw0DUi2gwX2/ke+swbRRBA3AR68wwCY6UCRuMMcoQhwklR/4w4SGIPlChrvUMJprr9H+ltBola63lS4pUGCfEJJef2QolqfMdSYo9s/80lCGGPfZxLq6TYQ+bplyB1/bfJgSl6ZH7aJUdb+WKt9TzJoUmGHQ/RAmGO438k40BRG3IklJo5IS1l6XWfI8hx9zC77Z0c+bwXcsQ2LW5uJmmOjkXHZsJXFCsBRRbyHnKAYiKAMpkHmBlnEDImY6f9jO59BHaPiKrQO4ggnYeL2NdNRNRWik6KRoo+atrozxFRaz1PRLzWcNHbp2i2Fy528j0nRGhPASc4viOnGVDCGwCxDs5kmUblZzH2z4iDJPZAid1PzKyc93KCRK31PCnxOoNEuLcX6Zp9UKIe37GU2CPbf3MJEu7mfNcZrZJiD5knX4Ks679JDi4JedancB9CjpbyRUNrK+RIfZ0VPrX15iQZn5WdWx75B7y/uSWyaAAA"}, "url": "https://api.reddit.com/user/PyAPITestUser2/comments.json?sort=new&t=all"}, "request": {"headers": {"Connection": ["keep-alive"], "User-Agent": ["PRAW_test_suite PRAW/3.0a1 Python/2.7.8 Linux-3.16.0-37-generic-x86_64-with-Ubuntu-14.10-utopic"], "Accept": ["*/*"], "Accept-Encoding": ["gzip, deflate"], "Cookie": ["reddit_session=7302867%2C2015-06-15T06%3A50%3A37%2Cc0e114b1f45a1bc763984b34c83d31df49a92fed; __cfduid=d28895e21c18fe156bbe302205f9b22ac1434376236"]}, "body": {"encoding": "utf-8", "string": ""}, "uri": "https://api.reddit.com/user/PyAPITestUser2/comments.json?sort=new&t=all", "method": "GET"}}, {"recorded_at": "2015-06-15T13:50:38", "response": {"status": {"code": 200, "message": "OK"}, "headers": {"x-ratelimit-remaining": ["298"], "transfer-encoding": ["chunked"], "cache-control": ["private, no-cache", "no-cache"], "x-moose": ["majestic"], "server": ["cloudflare-nginx"], "x-ratelimit-used": ["2"], "x-frame-options": ["SAMEORIGIN"], "x-xss-protection": ["1; mode=block"], "connection": ["keep-alive"], "content-encoding": ["gzip"], "pragma": ["no-cache"], "x-ua-compatible": ["IE=edge"], "x-reddit-tracking": ["https://pixel.redditmedia.com/pixel/of_destiny.png?v=6qsn21tVL7go5HvVpotLbf0tnpT2hujgxe4105fEz7G1t0%2BHh25pl%2FSGghZNuAZaGB%2FJKaxz67I%3D"], "cf-ray": ["1f6ebebe912c04a3-CDG"], "date": ["Mon, 15 Jun 2015 13:50:38 GMT"], "x-ratelimit-reset": ["562"], "content-type": ["application/json; charset=UTF-8"], "x-content-type-options": ["nosniff"]}, "body": {"encoding": "UTF-8", "base64_string": "H4sIAAAAAAAAA1yRwW7DIBBEfwVxtqrYxgn2rcfecmjPaANLvYqBCnCUNsq/V6AkjXodzQ5vhgs/kjd8Yjx3vGHcQAY+sQufISkHtPCJWVgSNox7cFic++/X/ds7pvyRMNYrSspGwhp0d+uIkLEobSfFth02cnjZNIzPZFDZGJyK4RByerr5DItROqIxVPVid8HMkOby8LYVLq1j+Nl1BzNYsYGulwjCgu7sCOM49LtejhalMJ0WW7krcDcQtWb9gGnFHabUDOZ/1YX8UR0hujJG25WU4Bz6/BDHhvFwwqhaySeW41rOKKlS4SmIavyfozbE8xdFyBQ8n5hfl+UGcsJIltAovOHcY+sHCU1nW9f2h3BWOqw+l42u118AAAD//wMAKxRkF8UBAAA="}, "url": "https://api.reddit.com/user/PyAPITestUser2/about/.json"}, "request": {"headers": {"Connection": ["keep-alive"], "User-Agent": ["PRAW_test_suite PRAW/3.0a1 Python/2.7.8 Linux-3.16.0-37-generic-x86_64-with-Ubuntu-14.10-utopic"], "Accept": ["*/*"], "Accept-Encoding": ["gzip, deflate"], "Cookie": ["reddit_session=7302867%2C2015-06-15T06%3A50%3A37%2Cc0e114b1f45a1bc763984b34c83d31df49a92fed; __cfduid=d28895e21c18fe156bbe302205f9b22ac1434376236"]}, "body": {"encoding": "utf-8", "string": ""}, "uri": "https://api.reddit.com/user/PyAPITestUser2/about/.json", "method": "GET"}}, {"recorded_at": "2015-06-15T13:50:38", "response": {"status": {"code": 200, "message": "OK"}, "headers": {"x-ratelimit-remaining": ["297"], "content-type": ["application/json; charset=UTF-8"], "cache-control": ["private, no-cache", "no-cache"], "content-length": ["682"], "server": ["cloudflare-nginx"], "x-content-type-options": ["nosniff"], "x-moose": ["majestic"], "x-ratelimit-used": ["3"], "x-frame-options": ["SAMEORIGIN"], "x-xss-protection": ["1; mode=block"], "connection": ["keep-alive"], "content-encoding": ["gzip"], "pragma": ["no-cache"], "x-ua-compatible": ["IE=edge"], "x-reddit-tracking": ["https://pixel.redditmedia.com/pixel/of_destiny.png?v=AqxVkrSRF3bN55ymSSdkwfD%2FLdA4QMcYwodHHwNYU4Pccch5s1XTILSk9LACd6ER3FcO3MQmUDmhY5Rn5rzZjrp3D2F%2F%2BvsO"], "cf-ray": ["1f6ebec1714204a3-CDG"], "date": ["Mon, 15 Jun 2015 13:50:38 GMT"], "x-ratelimit-reset": ["562"], "vary": ["accept-encoding"]}, "body": {"encoding": "UTF-8", "base64_string": "H4sIAC7YflUC/61UyU7cQBD9FccHTsx4XwaUAyIimgOLICdC1OqlPNOZ9kJ3e2BA/Hu6G5sxHJCQcrHsqvKrV/Wq6tnf8Ib5R56vM//Q8xnW2Hw9+wQ3DUjE65V1WpfqSc010vCo0VrXwtibXgjj6ZWNVMj9Y8EqLBQYB3fIsc7a3CKMcbRttOSk1600fi17GzuBHzMyrjqBd6jBNVibBMZMCO64CVPahqwBsz3NtdbdURCQuV73NVHz1x9qYBzPaVsH0c/0PF5dIX41u87l7cU5e7g0hPqL5RKj/vIpOl1GJ7ebEHV0/rdbOQ6gqOSd5m0zVu0fCH38bTbzbk7R5dmZN5sdrPSxNTK+9ajASn2/82t254/2zr782CN5BS3ytHpI6D0UjEZZXpQQVqQK0yIvUhpnxYLQjMa0giTJwoyFFiZwOHeNeze5RviRy8VAxfLWXAvXtGvXA+/kaun9Mk3z0oeUb7aPOfRJRXLDglR5SnHF4qLMU8DVgkAZFSRMynBB8pDFFo62QuBOAWIgQAMzGtY1NFpN1O56IjhFk47Z/NOyxT3Uuo8SuSuyKCxTVuRltFiYSqO8jG3hizJb4CysGKQljUqXu92CjMpPE/1Hab7O8avScDP/SPEnK8+wQc402bVhrEcRh6hPOvv1gZqstODNBglMYLLTmNK2N/oiTDXfWhLRvvNa4qridCLJQHio6ncShoeeefx5TWJ5EpB2WOJ4n9edkg95x13XGXq7G1QC1u6wREkcZ1lYFNncJPB76UQPZPDhNASuiZwBwmw6ogMS6rUl/wFtOHnvlRlvVt2a+vC7i+Vcyqi0hhoQNJgIR3JwDxuCFG0lIEem5o1lY5OZFgyc9a5zFb/29k0Wpexcj07c7KYXdN/TsbiXl38Stiz/ywUAAA=="}, "url": "https://api.reddit.com/r/reddit_api_test/about/.json"}, "request": {"headers": {"Connection": ["keep-alive"], "User-Agent": ["PRAW_test_suite PRAW/3.0a1 Python/2.7.8 Linux-3.16.0-37-generic-x86_64-with-Ubuntu-14.10-utopic"], "Accept": ["*/*"], "Accept-Encoding": ["gzip, deflate"], "Cookie": ["reddit_session=7302867%2C2015-06-15T06%3A50%3A37%2Cc0e114b1f45a1bc763984b34c83d31df49a92fed; __cfduid=d28895e21c18fe156bbe302205f9b22ac1434376236"]}, "body": {"encoding": "utf-8", "string": ""}, "uri": "https://api.reddit.com/r/reddit_api_test/about/.json", "method": "GET"}}]}
\ No newline at end of file
diff --git a/tests/test_comments.py b/tests/test_comments.py
index 343e8dc3..2acced95 100644
--- a/tests/test_comments.py
+++ b/tests/test_comments.py
@@ -1,6 +1,7 @@
"""Tests for Comment class."""
from __future__ import print_function, unicode_literals
+import pickle
from praw import helpers
from praw.objects import Comment, MoreComments
from .helper import PRAWTest, betamax
@@ -97,6 +98,15 @@ class CommentTest(PRAWTest):
lambda item: isinstance(item, Comment))
self.assertEqual(comment._replies, None)
+ @betamax
+ def test_unpickle_comment(self):
+ item = next(self.r.user.get_comments())
+ pkl = pickle.dumps(item)
+ try:
+ pickle.loads(pkl)
+ except RuntimeError:
+ self.fail("unpickling shouldn't throw a RuntimeError exception")
+
class MoreCommentsTest(PRAWTest):
def betamax_init(self):
| {
"commit_name": "head_commit",
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true,
"llm_score": {
"difficulty_score": 1,
"issue_text_score": 1,
"test_score": 0
},
"num_modified_files": 1
} | 2.1 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[dev]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "pytest",
"pip_packages": [
"flake8",
"betamax",
"betamax-matchers",
"mock",
"pytest"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.9",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | betamax==0.9.0
betamax-matchers==0.4.0
certifi==2025.1.31
charset-normalizer==3.4.1
exceptiongroup @ file:///croot/exceptiongroup_1706031385326/work
flake8==7.2.0
idna==3.10
iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work
mccabe==0.7.0
mock==5.2.0
packaging @ file:///croot/packaging_1734472117206/work
pluggy @ file:///croot/pluggy_1733169602837/work
-e git+https://github.com/praw-dev/praw.git@eb91d191eb09d94df144589ba6561f387a3a2922#egg=praw
pycodestyle==2.13.0
pyflakes==3.3.1
pytest @ file:///croot/pytest_1738938843180/work
requests==2.32.3
requests-toolbelt==1.0.0
six==1.17.0
tomli @ file:///opt/conda/conda-bld/tomli_1657175507142/work
update-checker==0.18.0
urllib3==2.3.0
| name: praw
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- exceptiongroup=1.2.0=py39h06a4308_0
- iniconfig=1.1.1=pyhd3eb1b0_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=3.0.16=h5eee18b_0
- packaging=24.2=py39h06a4308_0
- pip=25.0=py39h06a4308_0
- pluggy=1.5.0=py39h06a4308_0
- pytest=8.3.4=py39h06a4308_0
- python=3.9.21=he870216_1
- readline=8.2=h5eee18b_0
- setuptools=75.8.0=py39h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- tomli=2.0.1=py39h06a4308_0
- tzdata=2025a=h04d1e81_0
- wheel=0.45.1=py39h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- betamax==0.9.0
- betamax-matchers==0.4.0
- certifi==2025.1.31
- charset-normalizer==3.4.1
- flake8==7.2.0
- idna==3.10
- mccabe==0.7.0
- mock==5.2.0
- pycodestyle==2.13.0
- pyflakes==3.3.1
- requests==2.32.3
- requests-toolbelt==1.0.0
- six==1.17.0
- update-checker==0.18.0
- urllib3==2.3.0
prefix: /opt/conda/envs/praw
| [
"tests/test_comments.py::CommentTest::test_unpickle_comment"
] | [] | [
"tests/test_comments.py::CommentTest::test_add_comment",
"tests/test_comments.py::CommentTest::test_add_reply",
"tests/test_comments.py::CommentTest::test_edit",
"tests/test_comments.py::CommentTest::test_front_page_comment_replies_are_none",
"tests/test_comments.py::CommentTest::test_get_comments_permalink",
"tests/test_comments.py::CommentTest::test_inbox_comment_permalink",
"tests/test_comments.py::CommentTest::test_inbox_comment_replies_are_none",
"tests/test_comments.py::CommentTest::test_save_comment",
"tests/test_comments.py::CommentTest::test_spambox_comments_replies_are_none",
"tests/test_comments.py::CommentTest::test_unicode_comment",
"tests/test_comments.py::CommentTest::test_user_comment_permalink",
"tests/test_comments.py::CommentTest::test_user_comment_replies_are_none",
"tests/test_comments.py::MoreCommentsTest::test_all_comments",
"tests/test_comments.py::MoreCommentsTest::test_comments_method"
] | [] | BSD 2-Clause "Simplified" License | 168 |
|
sympy__sympy-9537 | e9c44ba1f4b7cd394d67f10a066be67513d6c538 | 2015-06-17 20:09:11 | 0241b35cae5f2adc04dc37b25f7dc9c5f00bd746 | diff --git a/sympy/printing/octave.py b/sympy/printing/octave.py
index 5cef62c675..b07c0f7ab8 100644
--- a/sympy/printing/octave.py
+++ b/sympy/printing/octave.py
@@ -45,8 +45,8 @@ class OctaveCodePrinter(CodePrinter):
language = "Octave"
_operators = {
- 'and': '&&',
- 'or': '||',
+ 'and': '&',
+ 'or': '|',
'not': '~',
}
| Logical operators in octave_code
When expressions include logical operators, like &, octave_code uses the wrong logical operator in the produced code. For example the following code:
from sympy import Piecewise
from sympy.abc import x
from sympy.printing import octave_code
print octave_code(Piecewise((1, (x > 0) & (x < 1)), (0, True)))
produces output
((x > 0 && x < 1).*(1) + (~(x > 0 && x < 1)).*(0))
The logical ands (&&) should be single ampersands (&) so that the expression works with vector arguments x in Octave/MATLAB
| sympy/sympy | diff --git a/sympy/printing/tests/test_octave.py b/sympy/printing/tests/test_octave.py
index 4c9a542583..17d57acca7 100644
--- a/sympy/printing/tests/test_octave.py
+++ b/sympy/printing/tests/test_octave.py
@@ -129,13 +129,13 @@ def test_constants_other():
def test_boolean():
- assert mcode(x & y) == "x && y"
- assert mcode(x | y) == "x || y"
+ assert mcode(x & y) == "x & y"
+ assert mcode(x | y) == "x | y"
assert mcode(~x) == "~x"
- assert mcode(x & y & z) == "x && y && z"
- assert mcode(x | y | z) == "x || y || z"
- assert mcode((x & y) | z) == "z || x && y"
- assert mcode((x | y) & z) == "z && (x || y)"
+ assert mcode(x & y & z) == "x & y & z"
+ assert mcode(x | y | z) == "x | y | z"
+ assert mcode((x & y) | z) == "z | x & y"
+ assert mcode((x | y) & z) == "z & (x | y)"
def test_Matrices():
| {
"commit_name": "head_commit",
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true,
"llm_score": {
"difficulty_score": 1,
"issue_text_score": 0,
"test_score": 0
},
"num_modified_files": 1
} | 0.7 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "mpmath>=0.19",
"pip_packages": [
"pytest"
],
"pre_install": null,
"python": "3.7",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | certifi @ file:///croot/certifi_1671487769961/work/certifi
exceptiongroup==1.2.2
importlib-metadata==6.7.0
iniconfig==2.0.0
mpmath==1.2.1
packaging==24.0
pluggy==1.2.0
pytest==7.4.4
-e git+https://github.com/sympy/sympy.git@e9c44ba1f4b7cd394d67f10a066be67513d6c538#egg=sympy
tomli==2.0.1
typing_extensions==4.7.1
zipp==3.15.0
| name: sympy
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2022.12.7=py37h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- mpmath=1.2.1=py37h06a4308_0
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- pip=22.3.1=py37h06a4308_0
- python=3.7.16=h7a1cb2a_0
- readline=8.2=h5eee18b_0
- setuptools=65.6.3=py37h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- wheel=0.38.4=py37h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- exceptiongroup==1.2.2
- importlib-metadata==6.7.0
- iniconfig==2.0.0
- packaging==24.0
- pluggy==1.2.0
- pytest==7.4.4
- tomli==2.0.1
- typing-extensions==4.7.1
- zipp==3.15.0
prefix: /opt/conda/envs/sympy
| [
"sympy/printing/tests/test_octave.py::test_boolean"
] | [
"sympy/printing/tests/test_octave.py::test_Matrices_entries_not_hadamard"
] | [
"sympy/printing/tests/test_octave.py::test_Integer",
"sympy/printing/tests/test_octave.py::test_Rational",
"sympy/printing/tests/test_octave.py::test_Function",
"sympy/printing/tests/test_octave.py::test_Pow",
"sympy/printing/tests/test_octave.py::test_basic_ops",
"sympy/printing/tests/test_octave.py::test_1_over_x_and_sqrt",
"sympy/printing/tests/test_octave.py::test_mix_number_mult_symbols",
"sympy/printing/tests/test_octave.py::test_mix_number_pow_symbols",
"sympy/printing/tests/test_octave.py::test_imag",
"sympy/printing/tests/test_octave.py::test_constants",
"sympy/printing/tests/test_octave.py::test_constants_other",
"sympy/printing/tests/test_octave.py::test_Matrices",
"sympy/printing/tests/test_octave.py::test_vector_entries_hadamard",
"sympy/printing/tests/test_octave.py::test_MatrixSymbol",
"sympy/printing/tests/test_octave.py::test_special_matrices",
"sympy/printing/tests/test_octave.py::test_containers",
"sympy/printing/tests/test_octave.py::test_octave_noninline",
"sympy/printing/tests/test_octave.py::test_octave_piecewise",
"sympy/printing/tests/test_octave.py::test_octave_piecewise_times_const",
"sympy/printing/tests/test_octave.py::test_octave_matrix_assign_to",
"sympy/printing/tests/test_octave.py::test_octave_matrix_assign_to_more",
"sympy/printing/tests/test_octave.py::test_octave_matrix_1x1",
"sympy/printing/tests/test_octave.py::test_octave_matrix_elements",
"sympy/printing/tests/test_octave.py::test_octave_boolean",
"sympy/printing/tests/test_octave.py::test_octave_not_supported",
"sympy/printing/tests/test_octave.py::test_trick_indent_with_end_else_words",
"sympy/printing/tests/test_octave.py::test_haramard",
"sympy/printing/tests/test_octave.py::test_sparse",
"sympy/printing/tests/test_octave.py::test_specfun"
] | [] | BSD | 169 |
|
sigmavirus24__github3.py-397 | 270f6d9c0978d0d2da2e4c98da12cbbb1d10c567 | 2015-06-19 22:55:07 | 05ed0c6a02cffc6ddd0e82ce840c464e1c5fd8c4 | balloob: Tests… working on it. | diff --git a/AUTHORS.rst b/AUTHORS.rst
index 6aeb346b..49e1c5b7 100644
--- a/AUTHORS.rst
+++ b/AUTHORS.rst
@@ -92,3 +92,5 @@ Contributors
- Jürgen Hermann (@jhermann)
- Antoine Giraudmaillet (@antoine-g)
+
+- Paulus Schoutsen (@balloob)
diff --git a/github3/pulls.py b/github3/pulls.py
index 7c257feb..4e00c0a0 100644
--- a/github3/pulls.py
+++ b/github3/pulls.py
@@ -12,7 +12,7 @@ from re import match
from json import dumps
from . import models
-from . import utils
+from .repos.contents import Contents
from .repos.commit import RepoCommit
from .users import User
from .decorators import requires_auth
@@ -78,39 +78,19 @@ class PullFile(models.GitHubCore):
self.raw_url = pfile.get('raw_url')
#: Patch generated by this pull request
self.patch = pfile.get('patch')
+ #: URL to JSON object with content and metadata
+ self.contents_url = pfile.get('contents_url')
def _repr(self):
return '<Pull Request File [{0}]>'.format(self.filename)
def contents(self):
- """Return the contents of the file as bytes.
+ """Return the contents of the file.
- :param stream: When true, the resulting object can be iterated over via
- ``iter_contents``.
+ :returns: :class:`Contents <github3.repos.contents.Contents>`
"""
- headers = {'Accept': 'application/octet-stream'}
- resp = self._get(self.raw_url, headers=headers)
- if self._boolean(resp, 200, 404):
- return resp.content
- return b''
-
- def download(self, path=None):
- """Download the contents for this file to disk.
-
- :param path: (optional), path where the file should be saved
- to, default is the filename provided in the headers and will be
- written in the current directory.
- it can take a file-like object as well
- :type path: str, file-like object
- :returns: bool -- True if successful, False otherwise
- """
- headers = {'Accept': 'application/octet-stream'}
- resp = self._get(self.raw_url, stream=True, headers=headers)
- if path is None:
- path = self.filename
- if self._boolean(resp, 200, 404):
- return utils.stream_response_to_file(resp, path)
- return None
+ json = self._json(self._get(self.contents_url), 200)
+ return self._instance_or_null(Contents, json)
class PullRequest(models.GitHubCore):
diff --git a/github3/repos/contents.py b/github3/repos/contents.py
index 6a563ab3..261d7116 100644
--- a/github3/repos/contents.py
+++ b/github3/repos/contents.py
@@ -62,7 +62,7 @@ class Contents(GitHubCore):
#: with the character set you wish to use, e.g.,
#: ``content.decoded.decode('utf-8')``.
#: .. versionchanged:: 0.5.2
- self.decoded = ''
+ self.decoded = b''
if self.encoding == 'base64' and self.content:
self.decoded = b64decode(self.content.encode())
| PullFile.contents() and PullFile.download() don't work for private repo
I am on the develop branch.
When having a private repo, the methods `contents()` and `download()` on PullFile don't work.
Tried debugging it myself:
Request returns a 404:
```
In [10]: pfile._get(pfile.raw_url)
Out[10]: <Response [404]>
```
Dropping the header `Accept: application/vnd.github.v3.full+json` from the request did not work.
Copy pasting `pfile.raw_url` into my browser where I am logged into GitHub works. | sigmavirus24/github3.py | diff --git a/tests/cassettes/PullFile_contents.json b/tests/cassettes/PullFile_contents.json
index f5bbcc49..8d223722 100644
--- a/tests/cassettes/PullFile_contents.json
+++ b/tests/cassettes/PullFile_contents.json
@@ -1,1 +1,1 @@
-{"recorded_with": "betamax/0.4.1", "http_interactions": [{"recorded_at": "2015-02-21T05:46:46", "response": {"headers": {"Transfer-Encoding": "chunked", "Access-Control-Expose-Headers": "ETag, Link, X-GitHub-OTP, X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset, X-OAuth-Scopes, X-Accepted-OAuth-Scopes, X-Poll-Interval", "Content-Security-Policy": "default-src 'none'", "Access-Control-Allow-Origin": "*", "X-RateLimit-Reset": "1424501206", "X-GitHub-Media-Type": "github.v3; param=full; format=json", "X-RateLimit-Remaining": "59", "Server": "GitHub.com", "Cache-Control": "public, max-age=60, s-maxage=60", "X-XSS-Protection": "1; mode=block", "Access-Control-Allow-Credentials": "true", "ETag": "W/\"ce314491c63b8e4855a6544a8a22dd33\"", "X-Served-By": "318e55760cf7cdb40e61175a4d36cd32", "Date": "Sat, 21 Feb 2015 05:46:46 GMT", "Content-Type": "application/json; charset=utf-8", "Strict-Transport-Security": "max-age=31536000; includeSubdomains; preload", "X-GitHub-Request-Id": "42707723:202B:39AD56E9:54E81BC5", "Status": "200 OK", "Vary": "Accept, Accept-Encoding", "Content-Encoding": "gzip", "X-RateLimit-Limit": "60", "X-Frame-Options": "deny", "X-Content-Type-Options": "nosniff", "Last-Modified": "Fri, 20 Feb 2015 03:03:14 GMT"}, "url": "https://api.github.com/repos/sigmavirus24/github3.py/pulls/286", "body": {"encoding": "utf-8", "string": "", "base64_string": "H4sIAAAAAAAAA+1c32+rOBb+VxDzsqttQoCkSVGns6Ndafc+zWi392Wno8iASawSQPxIby7q/77fsYFAkqZpqWb6gK56lRD787F9fGx/5xxKvUhD3dHXeZ5kjmGwRIxXIl8X7tiLN0bKkzgzMrHasK1Ii8yaGupXe5zsjKQIw8ywFtf6lS583bFsezadz60rwG3CZRe5hXoOr4LzRRC8H2BM1SFUwnJv3QNG1qfOZVnBD3DeNFISoB6qqNi4PMVwLa6v9CxnOccEeGGccR9thbH3iA9OwMKMX+m5yEP6/Wff10QkcsFCLWFZpgVxqnkpZ7mIVlrKt4I/aZiyDY/yDDBFRk2UgFuJCPXbY15P13SysCdXOtuynKWH3ZMPs0oZCM2LoxzgUi8Kw5KVf9r+aANtlVYYpAU6tX5OqQisq1SocbnGoHAQh2H8BJRDobvae9yQ0dRsUDB870RBzdKI8zXH2KFLzzQQIsvfLpSsVWJlZflS+IQDrUhT7r9ZsKoexHqKIFEpF7AELNzMS0WSizh6u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nN/ym0+DIUEYJ6ECWa8RCB4aW+VgHiPZOowbhTANoJwNd9HjJTT+ZOA0V6CU/AvDdluUqQkGH7PXt7KhMA8AeJEn1bOZEscdTIx7Rx7JLfZ5N8TAuY0yajBNj10b8v+NsTJ6RHCHmrS6Wk+m1yR/mrt0wj9f/xoXmHwAXa2qjB9EHXvBC3YtSXD0e0uPBQ5gji4deIuSGn3D/lIj1MdX/Q7yiD9tZgd8dZtLdGcoc82giiykTa5nsRNq3mLHtEo1kOJJQMBf2f3DXJpxfVOUYbIet3oyBFlBS5RknB6A+ciN6jG39r9buRQNYZtUtQYWQ++iKjUfDv2rm+t4aSNRR/WOuUYVs3axQhjVQjRDVsnTTjY914b6IxRhI+iHAn5/mVnOPPNWOXZj23RnKf+Ey6e05X/7CZb+WYfyq962ohfQO/JK0UpdHDn30mxR6Dq9Lr8YH+dYadHnQy6+m7TKmvS3c0XSrna4pZV5Vp/Bdlwl8oE/qsUtHr2AH5jUxGE17QPFmS5afACF+k+a6puXTxQoLhdSEHL7sZXhfynhd8DInTH5w4XZ8ydQfZaEdnZYT5UAHE2+JtCwiJ9H28JgjzhtJzlPfxvoT6O0quEUGNCLGA3iShO7Pn/wOG5zafAkoAAA=="}, "status": {"message": "OK", "code": 200}}, "request": {"uri": "https://api.github.com/repos/sigmavirus24/github3.py/pulls/286", "headers": {"Accept-Charset": "utf-8", "Accept-Encoding": "gzip, deflate", "User-Agent": "github3.py/1.0.0a1", "Connection": "keep-alive", "Content-Type": "application/json", "Accept": "application/vnd.github.v3.full+json"}, "body": {"encoding": "utf-8", "string": ""}, "method": "GET"}}, {"recorded_at": "2015-02-21T05:46:46", "response": {"headers": {"Transfer-Encoding": "chunked", "Access-Control-Expose-Headers": "ETag, Link, X-GitHub-OTP, X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset, X-OAuth-Scopes, X-Accepted-OAuth-Scopes, X-Poll-Interval", "Content-Security-Policy": "default-src 'none'", "Access-Control-Allow-Origin": "*", "X-RateLimit-Reset": "1424501206", "X-GitHub-Media-Type": "github.v3; param=full; format=json", "X-RateLimit-Remaining": "58", "Server": "GitHub.com", "Cache-Control": "public, max-age=60, s-maxage=60", "X-XSS-Protection": "1; mode=block", "Access-Control-Allow-Credentials": "true", "ETag": "W/\"a7649b9ef71da693ea6c76a029bfdcf2\"", "X-Served-By": "065b43cd9674091fec48a221b420fbb3", "Date": "Sat, 21 Feb 2015 05:46:46 GMT", "Content-Type": "application/json; charset=utf-8", "Strict-Transport-Security": "max-age=31536000; includeSubdomains; preload", "X-GitHub-Request-Id": "42707723:202B:39AD5730:54E81BC6", "Status": "200 OK", "Vary": "Accept, Accept-Encoding", "Content-Encoding": "gzip", "X-RateLimit-Limit": "60", "X-Frame-Options": "deny", "X-Content-Type-Options": "nosniff", "Last-Modified": "Fri, 20 Feb 2015 03:03:14 GMT"}, "url": "https://api.github.com/repos/sigmavirus24/github3.py/pulls/286/files?per_page=100", "body": {"encoding": "utf-8", "string": "", "base64_string": "H4sIAAAAAAAAA+19aZfayJLoX+H0++C+T7a1b77jmRECxCJWCQRMz/Fol0Ab2pDoc99vfyFBlalyeetteuZ2dZsqpMzIyMzIyMjIWP7j5x8yT//h3Q8MhxsMxWIcbbOExeMOZXMEQfAGzZO8beKYSeG2rWM/vP7B8QM70kMbarl+7hUGiSZFEGRvkxreZrmeFxm8C2PLd3zbgme6Zfm5H0fwmORf/2DZgX37ir3+wfT0yLVvr4wgNj4UaQD1vTxPsncoem3jrRmHaOa7oV76aZER1O05Ca2iTS3UsWnLoijdIW2DxXFMp3Tc4UySczCTNwyCpEmKdxzmoeI90ql+/v5WodKvatSMo9yO8uxZy3riv73rc2oncfbZnj/A+KRT/5bazvtvHRKYokTPTQ9G/d//vfMG5+nXTAdpfhF0B55YttMxgzizf8zswPnbu5+izsPPTz+0/318kNp5kUadpuDbIrH0/Frpbe7ngf36+tyIrfp151UL0nr1N6j9U4Q0EP89tU+Fn9rZB73IvdvDtvXUBkgfUrv07fMHoIUQ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bp+Jpy46ZvdeK4VaveYfjbai4e1RRNS3BqvHOEaNQJ+KtP9QdPlUEtou3tlg/JID/cHYLhzudzmvrHwfp4IRjZtpU1p+aXTtJtI58ZMtAANCmm3nr6tXVQVedFGn2AGH5Fc/33wJvvhvDrh9IvHLlvM/Pqb2A98P8B/KD1kz2lAAA="}, "status": {"message": "OK", "code": 200}}, "request": {"uri": "https://api.github.com/repos/sigmavirus24/github3.py/pulls/286/files?per_page=100", "headers": {"Accept-Charset": "utf-8", "Accept-Encoding": "gzip, deflate", "User-Agent": "github3.py/1.0.0a1", "Connection": "keep-alive", "Content-Type": "application/json", "Accept": "application/vnd.github.v3.full+json"}, "body": {"encoding": "utf-8", "string": ""}, "method": "GET"}}, {"recorded_at": "2015-02-21T05:46:46", "response": {"headers": {"Transfer-Encoding": "chunked", "X-UA-Compatible": "IE=Edge,chrome=1", "X-Runtime": "0.011358", "X-Served-By": "9835a984a05caa405eb61faaa1546741", "X-Request-Id": "c4405a649e6367f514df656a2c5fc4a0", "X-XSS-Protection": "1; mode=block", "Set-Cookie": "logged_in=no; domain=.github.com; path=/; expires=Wed, 21-Feb-2035 05:46:46 GMT; secure; HttpOnly, _gh_sess=eyJzZXNzaW9uX2lkIjoiMzE5MDVlMjAxZWI5ZmYyYTQ0NWQ4MWY1ZWViNTYyMDgiLCJzcHlfcmVwbyI6InNpZ21hdmlydXMyNC9naXRodWIzLnB5Iiwic3B5X3JlcG9fYXQiOjE0MjQ0OTc2MDZ9--53040268da77d9d2cd665d61f4bb2acee1a4699e; path=/; secure; HttpOnly", "Content-Security-Policy": "default-src *; script-src assets-cdn.github.com collector-cdn.github.com; object-src assets-cdn.github.com; style-src 'self' 'unsafe-inline' 'unsafe-eval' assets-cdn.github.com; img-src 'self' data: assets-cdn.github.com identicons.github.com www.google-analytics.com collector.githubapp.com *.githubusercontent.com *.gravatar.com *.wp.com; media-src 'none'; frame-src 'self' render.githubusercontent.com gist.github.com www.youtube.com player.vimeo.com checkout.paypal.com; font-src assets-cdn.github.com; connect-src 'self' ghconduit.com:25035 live.github.com wss://live.github.com uploads.github.com www.google-analytics.com s3.amazonaws.com", "X-RateLimit-Remaining": "100", "X-GitHub-Request-Id": "42707723:12AB:18279253:54E81BC6", "Cache-Control": "no-cache", "Access-Control-Allow-Origin": "https://render.githubusercontent.com", "Strict-Transport-Security": "max-age=31536000; includeSubdomains; preload", "Server": "GitHub.com", "X-Rack-Cache": "miss", "Date": "Sat, 21 Feb 2015 05:46:46 GMT", "Location": "https://raw.githubusercontent.com/sigmavirus24/github3.py/fe5dd44af3eb7110a4a1f8c38f0c9bb235349ff6/github3/pulls.py", "Content-Type": "text/html; charset=utf-8", "Status": "302 Found", "Vary": "X-PJAX, Accept-Encoding", "X-RateLimit-Limit": "100", "X-Frame-Options": "deny", "X-Content-Type-Options": "nosniff"}, "url": "https://github.com/sigmavirus24/github3.py/raw/fe5dd44af3eb7110a4a1f8c38f0c9bb235349ff6/github3/pulls.py", "body": {"encoding": "utf-8", "string": "<html><body>You are being <a href=\"https://raw.githubusercontent.com/sigmavirus24/github3.py/fe5dd44af3eb7110a4a1f8c38f0c9bb235349ff6/github3/pulls.py\">redirected</a>.</body></html>"}, "status": {"message": "Found", "code": 302}}, "request": {"uri": "https://github.com/sigmavirus24/github3.py/raw/fe5dd44af3eb7110a4a1f8c38f0c9bb235349ff6/github3/pulls.py", "headers": {"Accept-Charset": "utf-8", "Accept-Encoding": "gzip, deflate", "User-Agent": "github3.py/1.0.0a1", "Connection": "keep-alive", "Content-Type": "application/json", "Accept": "application/octet-stream"}, "body": {"encoding": "utf-8", "string": ""}, "method": "GET"}}, {"recorded_at": "2015-02-21T05:46:47", "response": {"headers": {"Keep-Alive": "timeout=10, max=50", "Accept-Ranges": "bytes", "Content-Length": "3416", "Expires": "Sat, 21 Feb 2015 05:51:47 GMT", "Content-Security-Policy": "default-src 'none'", "X-XSS-Protection": "1; mode=block", "ETag": "\"681b647085e72d91f4e82229b5939ec10c41eea0\"", "Connection": "Keep-Alive", "Date": "Sat, 21 Feb 2015 05:46:47 GMT", "Cache-Control": "max-age=300", "Access-Control-Allow-Origin": "https://render.githubusercontent.com", "Strict-Transport-Security": "max-age=31536000", "X-Served-By": "cache-dfw1831-DFW", "Server": "Apache", "X-Cache": "MISS", "Content-Type": "text/plain; charset=utf-8", "Source-Age": "0", "Via": "1.1 varnish", "X-Content-Type-Options": "nosniff", "Content-Encoding": "gzip", "X-Cache-Hits": "0", "X-Frame-Options": "deny", "Vary": "Authorization,Accept-Encoding"}, "url": "https://raw.githubusercontent.com/sigmavirus24/github3.py/fe5dd44af3eb7110a4a1f8c38f0c9bb235349ff6/github3/pulls.py", "body": {"encoding": "utf-8", "string": "", "base64_string": "H4sIAAAAAAAAA+1bX3PcthF/16dA7AdS9YmSkjx0bqykjt3Unskfjy1PHyQPxTvidIh5JEuQUjSq+9m7uwBIAATvJFnp5KF6kO4WwO5isfhhdwE9ZQd/OWDLKhfl5Zx17ergr0jZe/Lkyd6laNfd4puk7opC7p3YP3t7p2sh2abKu4LD8LLNRClZVhSsXQOhyKTkkjW8yFrgzNqKIRcg/KvjspXJHklYNdWGpemqa7uGpykTm7pqWtaVAjTiaSFa3mQgW3VsuOmwydrlWhF/k1VpyHm3qaUiJ6C8Ib+sNhvRajqozAtpmv4h2tfd4tfFb3zZzvS3l1XDZ+yHTHIcyEszspO86Qd+gC+anvNl1WRtNTTiLEXDZZp1rVYzEVLCzJOlYml6vkGqI6ZrYNKbGuzWz/bDuzenmrS3t0e2ZW/Bmq/AkqIEA1dlPKi+P9/bY/AD9j2FpZhT//mFN4A99wjfXbCKzJCo4e85h+WU1Zyt27aeHx7m/IoXVc2bRPkFTuXw6ptD8o7Dp5e8PcgOJCx2wQ+QdqDX2iij2OZ8BQsuStGmaSx5sZoBSYLtczDYEhUB/Zn+kR2Iiz1FZwyH7Sc9Fxy/3495OmevDCtWrcgdN7y55Owa1IalkTU0okO26MH5wHgQC/yTXh92MuhmS/lR+fOKN7xccibbBh1d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yw+qj3ZwxYTz1ZCo0l3d3is7GKX7+5h/r7Qourqc6bt7hVeVAF/ruSP6iYOJJk3rRuIFNISWmLa63v2NkeKu8UnUaPfxmoPafQgQCO+BkRs9mMEUQzGL7BUQcbuqf3xtOlGUKPwxzyGc9Ky2PqHg4n3cNvTS+9NnLqtUWcIBUIahJx4y/+fDBp5PZT/7vOQbkkP6ZZf24SviECUXQ/pluYh3dJ5SLc0D+mWD35IZyZ8nxd1y34h+vWn/0XwMmnCtZBXmPH98HvcXNOz1qGy7G6LiRf5pvx690f5gRHOTYZW+tdGXAqAib5yjD4htIbjV6uV7p723U9c3UYdvPcbb7GkrWPmMXsqeHscqXLrMTHCMdvUle3Q0+4pJQfd8JXDkcM7ULm3bgGEZP7/a/RVZl/KUIp2tT81dfh1V35yedFTJST7vPqGaGL5tK6g/cSCTao57uHJePH2DT0T0JGqc5J79oaWVMNN6qQa2u5e+93fI+tXCwYbQ4+R0ccT+u+K7QEAZiA31m2UH7dAa//q3Lt3ouJGRs/G/GuR6YOcrrHx8sjyKu8m5c997+KvmhWO09WS4UXp3QpocXQIO+sZO7Y6pmT2tK3s7mfEYP5xd2bg3rLcOtDnBSKWLCBa3/pBnx/hhua/XPdKu1g5AAA="}, "status": {"message": "OK", "code": 200}}, "request": {"uri": "https://raw.githubusercontent.com/sigmavirus24/github3.py/fe5dd44af3eb7110a4a1f8c38f0c9bb235349ff6/github3/pulls.py", "headers": {"Accept-Charset": "utf-8", "Accept-Encoding": "gzip, deflate", "User-Agent": "github3.py/1.0.0a1", "Connection": "keep-alive", "Content-Type": "application/json", "Accept": "application/octet-stream"}, "body": {"encoding": "utf-8", "string": ""}, "method": "GET"}}]}
\ No newline at end of file
+{"http_interactions": [{"recorded_at": "2015-06-22T17:07:24", "response": {"status": {"code": 200, "message": "OK"}, "headers": {"transfer-encoding": "chunked", "date": "Mon, 22 Jun 2015 17:05:34 GMT", "cache-control": "public, max-age=60, s-maxage=60", "x-served-by": "07ff1c8a09e44b62e277fae50a1b1dc4", "x-ratelimit-remaining": "58", "x-frame-options": "deny", "status": "200 OK", "content-encoding": "gzip", "x-ratelimit-limit": "60", "access-control-expose-headers": "ETag, Link, X-GitHub-OTP, X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset, X-OAuth-Scopes, X-Accepted-OAuth-Scopes, X-Poll-Interval", "content-security-policy": "default-src 'none'", "x-ratelimit-reset": "1434995993", "x-github-request-id": "AE45F57C:7356:C2431E8:5588405E", "etag": "W/\"3284a16cca05edc9bbed5300363e46c6\"", "strict-transport-security": "max-age=31536000; includeSubdomains; preload", "content-type": "application/json; charset=utf-8", "x-content-type-options": "nosniff", "last-modified": "Mon, 22 Jun 2015 03:13:10 GMT", "access-control-allow-origin": "*", "access-control-allow-credentials": "true", "x-xss-protection": "1; mode=block", "x-github-media-type": "github.v3; param=full; format=json", "server": "GitHub.com", "vary": "Accept"}, "body": {"base64_string": "H4sIAAAAAAAAA+1cW2/juBX+K4L3pUVjy7o4doRstosWaOdpF23mpZuFQUmUTUSWBF2c8Qj57/0OKcmS4ziOFezmQRhkYFHkx0Py8BzyXFSOijQcOaN1nieZo+ssEZOVyNeFO/HijZ7yJM70TKw2bCvSIjNtXb21JslOT4owzHRzcT26Ggl/5JiWNbPnc/MKcJtw2UVuoZ7Cq+B8EQSXA0yoOYhKWO6te8DI9jS4LCv4Ac67ZkoC1FMVFRuXp5iuxfXVKMtZzrEAXhhn3EdfYew94ocTsDDjV6Nc5CG9/9n3NRGJXLBQS1iWaUGcal7KWS6ilZbyreBPGpZsw6M8A0yRURcl4FYiQvv2nNfLZU8X1vRqxLYsZ+nh8GRhVjEDoXlxlANc8kWhm7LxT9sfLaCt0gqDuGBEvZ9iKgLrMhVanM8xqBzEYRg/AeWQ6C73vuxIb1o2KJi+C1HQstTjfM0xdxjSM02EyPL3EyVbldhZWb4UPuGAK9KU++8mrGoHsp4iUFTKDSwBCzfzUpHkIo7eT2CnNdDidMUi8R28dwkaWhOHStny7hHKVmjNt8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LEe+Zjw+ZOQWhHAN/2e8ikP5mGDRTpKTwCc2n2c5UkIUP3e472WDYA4A+SJfr2ciRh4kUnH9PHS7f8PqPkY3rAmjZZJcCuD/99wd+fPCF9QkiBXSomHd0md5QKe8s0Yv8fH5rPEZzBrQ0b2A8jzQtxL0Z7WTimzYVCmSeIwq8Rc0NO+X/KTXqYNf8wuqNk3Fud3b1MyL3Vkzuk5EYgVebkNs9F2PSas+wRnWY5kFAzFPR/ctfksZ7V5iXaGAnEGwUpoqTINcovxnjgSPQe3fhba9wNBbLNuF2DKiP70RcZzYJ/104bvtUVraH4w3qnZN26W70IaaYaIqpp62Qsv+SNS3OWMZPwQoQ7uc5vpC9/rhU7N4G6NZP7HGri3VO8+oetfCtd/VPxXZcL6QkWJimlKCMfHu0T2fqYXJWpjx/0rzPtVNBJ0qdnmZ1f1+5wumTOtxizbiq/CHBWUv2ZNGHMKqu9jh+QTyQymhCDpmRJkp+CI3yR5rum5dLFtw2GL48cfDdn+PLIJd8KGZKnPzh5uj5l4spz5KyMQB+qgJhbfHEBYZG+jy8OYd1Qe476Pr6ZUD+j5hpR1IgSC+ijFCNn9vx/mNP9Nk1KAAA=", "string": "", "encoding": "utf-8"}, "url": "https://api.github.com/repos/sigmavirus24/github3.py/pulls/286"}, "request": {"headers": {"Connection": "keep-alive", "Accept-Encoding": "gzip, deflate", "User-Agent": "github3.py/1.0.0a1", "Accept-Charset": "utf-8", "Accept": "application/vnd.github.v3.full+json", "Content-Type": "application/json"}, "uri": "https://api.github.com/repos/sigmavirus24/github3.py/pulls/286", "method": "GET", "body": {"string": "", "encoding": "utf-8"}}}, {"recorded_at": "2015-06-22T17:07:24", "response": {"status": {"code": 200, "message": "OK"}, "headers": {"transfer-encoding": "chunked", "date": "Mon, 22 Jun 2015 17:05:34 GMT", "cache-control": "public, max-age=60, s-maxage=60", "x-served-by": "a6882e5cd2513376cb9481dbcd83f3a2", "x-ratelimit-remaining": "57", "x-frame-options": "deny", "status": "200 OK", "content-encoding": "gzip", "x-ratelimit-limit": "60", "access-control-expose-headers": "ETag, Link, X-GitHub-OTP, X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset, X-OAuth-Scopes, X-Accepted-OAuth-Scopes, X-Poll-Interval", "content-security-policy": "default-src 'none'", "x-ratelimit-reset": "1434995993", "x-github-request-id": "AE45F57C:7356:C243281:5588405E", "etag": "W/\"a7649b9ef71da693ea6c76a029bfdcf2\"", "strict-transport-security": "max-age=31536000; includeSubdomains; preload", "content-type": "application/json; charset=utf-8", "x-content-type-options": "nosniff", "last-modified": "Mon, 22 Jun 2015 03:13:10 GMT", "access-control-allow-origin": "*", "access-control-allow-credentials": "true", "x-xss-protection": "1; mode=block", "x-github-media-type": "github.v3; param=full; format=json", "server": "GitHub.com", "vary": "Accept"}, "body": {"base64_string": "H4sIAAAAAAAAA+19aZfayJLoX+H0++C+T7a1b77jmRECxCJWCQRMz/Fol0Ab2pDoc99vfyFBlalyeetteuZ2dZsqpMzIyMzIyMjIWP7j5x8yT//h3Q8MhxsMxWIcbbOExeMOZXMEQfAGzZO8beKYSeG2rWM/vP7B8QM70kMbarl+7hUGiSZFEGRvkxreZrmeFxm8C2PLd3zbgme6Zfm5H0fwmORf/2DZgX37ir3+wfT0yLVvr4wgNj4UaQD1vTxPsncoem3jrRmHaOa7oV76aZER1O05Ca2iTS3UsWnLoijdIW2DxXFMp3Tc4UySczCTNwyCpEmKdxzmoeI90ql+/v5WodKvatSMo9yO8uxZy3riv73rc2oncfbZnj/A+KRT/5bazvtvHRKYokTPTQ9G/d//vfMG5+nXTAdpfhF0B55YttMxgzizf8zswPnbu5+izsPPTz+0/318kNp5kUadpuDbIrH0/Frpbe7ngf36+tyIrfp151UL0nr1N6j9U4Q0EP89tU+Fn9rZB73IvdvDtvXUBkgfUrv07fMHoIUQRq7F5nXnCq155ucffOt1B/riwWectUTXoNsCb36u6IottI7eucLr3OB14qiTe37WacgZ3p0KO8vfQu07AAK8SfQUyD+306yjp3ZbEHC2O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TtJtI58ZMtAANCmm3nr6tXVQVedFGn2AGH5Fc/33wJvvhvDrh9IvHLlvM/Pqb2A98P8B/KD1kz2lAAA=", "string": "", "encoding": "utf-8"}, "url": "https://api.github.com/repos/sigmavirus24/github3.py/pulls/286/files?per_page=100"}, "request": {"headers": {"Connection": "keep-alive", "Accept-Encoding": "gzip, deflate", "User-Agent": "github3.py/1.0.0a1", "Accept-Charset": "utf-8", "Accept": "application/vnd.github.v3.full+json", "Content-Type": "application/json"}, "uri": "https://api.github.com/repos/sigmavirus24/github3.py/pulls/286/files?per_page=100", "method": "GET", "body": {"string": "", "encoding": "utf-8"}}}, {"recorded_at": "2015-06-22T17:07:24", "response": {"status": {"code": 200, "message": "OK"}, "headers": {"transfer-encoding": "chunked", "date": "Mon, 22 Jun 2015 17:05:34 GMT", "cache-control": "public, max-age=60, s-maxage=60", "x-served-by": "a30e6f9aa7cf5731b87dfb3b9992202d", "x-ratelimit-remaining": "56", "x-frame-options": "deny", "status": "200 OK", "content-encoding": "gzip", "x-ratelimit-limit": "60", "access-control-expose-headers": "ETag, Link, X-GitHub-OTP, X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset, X-OAuth-Scopes, X-Accepted-OAuth-Scopes, X-Poll-Interval", "content-security-policy": "default-src 'none'", "x-ratelimit-reset": "1434995993", "x-github-request-id": "AE45F57C:7356:C2432CB:5588405E", "etag": "W/\"87cbcbfec670418858b9c13f6382092a\"", "strict-transport-security": "max-age=31536000; includeSubdomains; preload", "content-type": "application/json; charset=utf-8", "x-content-type-options": "nosniff", "last-modified": "Sun, 26 Oct 2014 22:47:16 GMT", "access-control-allow-origin": "*", "access-control-allow-credentials": "true", "x-xss-protection": "1; mode=block", "x-github-media-type": "github.v3; param=full; format=json", "server": "GitHub.com", "vary": "Accept"}, "body": {"base64_string": "H4sIAAAAAAAAA9Vca28iy7X9L/M1UQYa4zGRois3Ni8bbMDmJUsRdNuAaRoygDFE+e9Za1dVU/2wx2eSq6v7Yc6ZA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c+07eUhFFjF7Tp1GAcS+Z9mj9XKFhQt9FU3SUEdB9/r4UaxfLpsfqJ7jWSXklGZWaxqf7yRN2zkXtGrIlFhprK22gldfQh6jd8IBeKVxY705jHTmBYPG3eQqBrIninB9hn1YOOrmGLx4xXWlhnUVhRMEpKt2KVF91PZGe3FXimcRfvQuKbk4DPb8Eh1cubaTPWxxLoN+K8F3ED983ufKW2uOs+32iFXq27II2i7V8rLBll08orJtmKH6nYVvblvIVzkVvWxPS8Taze06NWxW8RcWiJ+4ncJL6wrbWk+Y93w38Y35LIJgMytBq/9UpvXoB3z6H78CZRK4bMQ757S9gXxJG//e0pxCvxnkNv5c/DKd6JNxlvns/P8Nnfg3m42Hz76z+/bZ6Dl//zdybi7YO/u4bfenEh39FoTfi//37Gf/3r3w+pFqYHUwAA", "string": "", "encoding": "utf-8"}, "url": "https://api.github.com/repos/sigmavirus24/github3.py/contents/github3/pulls.py?ref=fe5dd44af3eb7110a4a1f8c38f0c9bb235349ff6"}, "request": {"headers": {"Connection": "keep-alive", "Accept-Encoding": "gzip, deflate", "User-Agent": "github3.py/1.0.0a1", "Accept-Charset": "utf-8", "Accept": "application/vnd.github.v3.full+json", "Content-Type": "application/json"}, "uri": "https://api.github.com/repos/sigmavirus24/github3.py/contents/github3/pulls.py?ref=fe5dd44af3eb7110a4a1f8c38f0c9bb235349ff6", "method": "GET", "body": {"string": "", "encoding": "utf-8"}}}], "recorded_with": "betamax/0.4.2"}
\ No newline at end of file
diff --git a/tests/integration/test_pulls.py b/tests/integration/test_pulls.py
index 331689a5..c934e5cf 100644
--- a/tests/integration/test_pulls.py
+++ b/tests/integration/test_pulls.py
@@ -3,6 +3,7 @@
import tempfile
import github3
+from github3 import repos
from .helper import IntegrationHelper
@@ -151,18 +152,6 @@ class TestPullFile(IntegrationHelper):
owner='sigmavirus24', repo='github3.py', pull_number=286,
filename='github3/pulls.py'
)
-
- assert isinstance(pull_file.contents(), bytes)
-
- def test_download(self):
- """Show that a user can download a file in a pull request."""
- cassette_name = self.cassette_name('download')
- with self.recorder.use_cassette(cassette_name):
- pull_file = self.get_pull_request_file(
- owner='sigmavirus24', repo='github3.py', pull_number=286,
- filename='github3/pulls.py'
- )
-
- with tempfile.NamedTemporaryFile() as fd:
- filename = pull_file.download(fd)
- assert filename is not None
+ contents = pull_file.contents()
+ assert isinstance(contents, repos.contents.Contents)
+ assert contents.decoded != b''
diff --git a/tests/unit/test_pulls.py b/tests/unit/test_pulls.py
index f893f478..a7dfdd80 100644
--- a/tests/unit/test_pulls.py
+++ b/tests/unit/test_pulls.py
@@ -298,40 +298,10 @@ class TestPullFile(UnitHelper):
" module Test")
}
- @mock.patch('github3.utils.stream_response_to_file')
- def test_download(self, stream_response_to_file):
- """Verify the proper request is made to download file contents."""
- response_mock = mock.Mock()
- response_mock.status_code = 200
- self.session.get.return_value = response_mock
-
- self.instance.download()
-
- self.session.get.assert_called_once_with(
- self.example_data['raw_url'], stream=True,
- headers={'Accept': 'application/octet-stream'}
- )
- stream_response_to_file.assert_called_once_with(response_mock,
- 'file1.txt')
-
- @mock.patch('github3.utils.stream_response_to_file')
- def test_download_does_not_stream(self, stream_response_to_file):
- """Verify the proper request is made to download file contents."""
- # Since the default return value for self.session.get is None we do
- # not need to mock out the response object in this test.
- self.instance.download()
-
- self.session.get.assert_called_once_with(
- self.example_data['raw_url'], stream=True,
- headers={'Accept': 'application/octet-stream'}
- )
- assert stream_response_to_file.called is False
-
def test_contents(self):
"""Verify the request made to fetch a pull request file contents."""
self.instance.contents()
self.session.get.assert_called_once_with(
- self.example_data['raw_url'],
- headers={'Accept': 'application/octet-stream'}
+ self.example_data['contents_url']
)
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 2,
"issue_text_score": 1,
"test_score": 2
},
"num_modified_files": 3
} | 1.0 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[test]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest",
"pytest-cov",
"pytest-xdist",
"pytest-mock",
"pytest-asyncio"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.9",
"reqs_path": [
"requirements.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | betamax==0.9.0
betamax-matchers==0.4.0
certifi==2025.1.31
charset-normalizer==3.4.1
coverage==7.8.0
exceptiongroup==1.2.2
execnet==2.1.1
-e git+https://github.com/sigmavirus24/github3.py.git@270f6d9c0978d0d2da2e4c98da12cbbb1d10c567#egg=github3.py
idna==3.10
iniconfig==2.1.0
packaging==24.2
pluggy==1.5.0
pytest==8.3.5
pytest-asyncio==0.26.0
pytest-cov==6.0.0
pytest-mock==3.14.0
pytest-xdist==3.6.1
requests==2.32.3
requests-toolbelt==1.0.0
tomli==2.2.1
typing_extensions==4.13.0
uritemplate==4.1.1
uritemplate.py==3.0.2
urllib3==2.3.0
| name: github3.py
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=3.0.16=h5eee18b_0
- pip=25.0=py39h06a4308_0
- python=3.9.21=he870216_1
- readline=8.2=h5eee18b_0
- setuptools=75.8.0=py39h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- tzdata=2025a=h04d1e81_0
- wheel=0.45.1=py39h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- betamax==0.9.0
- betamax-matchers==0.4.0
- certifi==2025.1.31
- charset-normalizer==3.4.1
- coverage==7.8.0
- exceptiongroup==1.2.2
- execnet==2.1.1
- idna==3.10
- iniconfig==2.1.0
- packaging==24.2
- pluggy==1.5.0
- pytest==8.3.5
- pytest-asyncio==0.26.0
- pytest-cov==6.0.0
- pytest-mock==3.14.0
- pytest-xdist==3.6.1
- requests==2.32.3
- requests-toolbelt==1.0.0
- tomli==2.2.1
- typing-extensions==4.13.0
- uritemplate==4.1.1
- uritemplate-py==3.0.2
- urllib3==2.3.0
prefix: /opt/conda/envs/github3.py
| [
"tests/integration/test_pulls.py::TestPullFile::test_contents",
"tests/unit/test_pulls.py::TestPullFile::test_contents"
] | [
"tests/integration/test_pulls.py::TestPullRequest::test_diff",
"tests/integration/test_pulls.py::TestPullRequest::test_patch"
] | [
"tests/integration/test_pulls.py::TestPullRequest::test_close",
"tests/integration/test_pulls.py::TestPullRequest::test_commits",
"tests/integration/test_pulls.py::TestPullRequest::test_create_review_comment",
"tests/integration/test_pulls.py::TestPullRequest::test_files",
"tests/integration/test_pulls.py::TestPullRequest::test_is_merged",
"tests/integration/test_pulls.py::TestPullRequest::test_issue_comments",
"tests/integration/test_pulls.py::TestPullRequest::test_reopen",
"tests/integration/test_pulls.py::TestPullRequest::test_review_comments",
"tests/integration/test_pulls.py::TestPullRequest::test_update",
"tests/integration/test_pulls.py::TestReviewComment::test_reply",
"tests/unit/test_pulls.py::TestPullRequest::test_close",
"tests/unit/test_pulls.py::TestPullRequest::test_create_review_comment",
"tests/unit/test_pulls.py::TestPullRequest::test_diff",
"tests/unit/test_pulls.py::TestPullRequest::test_is_merged",
"tests/unit/test_pulls.py::TestPullRequest::test_merge",
"tests/unit/test_pulls.py::TestPullRequest::test_patch",
"tests/unit/test_pulls.py::TestPullRequest::test_reopen",
"tests/unit/test_pulls.py::TestPullRequest::test_update",
"tests/unit/test_pulls.py::TestPullRequestRequiresAuthentication::test_close",
"tests/unit/test_pulls.py::TestPullRequestRequiresAuthentication::test_create_review_comment",
"tests/unit/test_pulls.py::TestPullRequestRequiresAuthentication::test_merge",
"tests/unit/test_pulls.py::TestPullRequestRequiresAuthentication::test_reopen",
"tests/unit/test_pulls.py::TestPullRequestRequiresAuthentication::test_update",
"tests/unit/test_pulls.py::TestPullRequestIterator::test_commits",
"tests/unit/test_pulls.py::TestPullRequestIterator::test_files",
"tests/unit/test_pulls.py::TestPullRequestIterator::test_issue_comments",
"tests/unit/test_pulls.py::TestPullRequestIterator::test_review_comments",
"tests/unit/test_pulls.py::TestReviewComment::test_reply",
"tests/unit/test_pulls.py::TestReviewComment::test_reply_requires_authentication"
] | [] | BSD 3-Clause "New" or "Revised" License | 170 |
mne-tools__mne-python-2228 | b143c6df244dca2e6121048fae99cb6e1cfa84ab | 2015-06-21 17:43:19 | 632e49f0470fc9526936dbb474fd6aa46501fe4d | diff --git a/doc/source/whats_new.rst b/doc/source/whats_new.rst
index 5ff2f77d1..3c7c0a5fd 100644
--- a/doc/source/whats_new.rst
+++ b/doc/source/whats_new.rst
@@ -14,6 +14,8 @@ BUG
- Fix ``mne.io.add_reference_channels`` not setting ``info[nchan]`` correctly by `Federico Raimondo`_
+ - Fix ``mne.stats.bonferroni_correction`` reject mask output to use corrected p-values by `Denis Engemann`_
+
.. _changes_0_9:
Changelog
diff --git a/mne/stats/multi_comp.py b/mne/stats/multi_comp.py
index 51751ea1a..a26b4a772 100644
--- a/mne/stats/multi_comp.py
+++ b/mne/stats/multi_comp.py
@@ -98,5 +98,5 @@ def bonferroni_correction(pval, alpha=0.05):
"""
pval = np.asarray(pval)
pval_corrected = pval * float(pval.size)
- reject = pval < alpha
+ reject = pval_corrected < alpha
return reject, pval_corrected
| BUG/API issue with multi_comp.bonferroni_correction
Do people agree that this is a bug, at least a very unexpected output:
https://github.com/mne-tools/mne-python/blob/master/mne/stats/multi_comp.py#L101
`pval_corrected` should instead be used for creating the output mask.
@agramfort @Eric89GXL @mainakjas | mne-tools/mne-python | diff --git a/mne/stats/tests/test_multi_comp.py b/mne/stats/tests/test_multi_comp.py
index 4cba14113..76b2c99db 100644
--- a/mne/stats/tests/test_multi_comp.py
+++ b/mne/stats/tests/test_multi_comp.py
@@ -1,5 +1,6 @@
import numpy as np
-from numpy.testing import assert_almost_equal, assert_allclose, assert_raises
+from numpy.testing import (
+ assert_almost_equal, assert_allclose, assert_raises, assert_array_equal)
from nose.tools import assert_true
from scipy import stats
@@ -25,6 +26,8 @@ def test_multi_pval_correction():
assert_true(pval_bonferroni.ndim == 2)
assert_true(reject_bonferroni.ndim == 2)
assert_allclose(pval_bonferroni / 10000, pval)
+ reject_expected = pval_bonferroni < alpha
+ assert_array_equal(reject_bonferroni, reject_expected)
fwer = np.mean(reject_bonferroni)
assert_almost_equal(fwer, alpha, 1)
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 0,
"issue_text_score": 3,
"test_score": 1
},
"num_modified_files": 2
} | 0.9 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[dev]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"numpy>=1.16.0",
"pandas>=1.0.0",
"scikit-learn",
"h5py",
"pysurfer",
"nose",
"nose-timer",
"pytest"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.7",
"reqs_path": [
"requirements/base.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | apptools==5.2.1
certifi @ file:///croot/certifi_1671487769961/work/certifi
configobj==5.0.9
cycler==0.11.0
envisage==7.0.3
exceptiongroup==1.2.2
fonttools==4.38.0
h5py==3.8.0
importlib-metadata==6.7.0
importlib-resources==5.12.0
iniconfig==2.0.0
joblib==1.3.2
kiwisolver==1.4.5
matplotlib==3.5.3
mayavi==4.8.1
-e git+https://github.com/mne-tools/mne-python.git@b143c6df244dca2e6121048fae99cb6e1cfa84ab#egg=mne
nibabel==4.0.2
nose==1.3.7
nose-timer==1.0.1
numpy==1.21.6
packaging==24.0
pandas==1.3.5
Pillow==9.5.0
pluggy==1.2.0
pyface==8.0.0
Pygments==2.17.2
pyparsing==3.1.4
pysurfer==0.11.2
pytest==7.4.4
python-dateutil==2.9.0.post0
pytz==2025.2
scikit-learn==1.0.2
scipy==1.7.3
six==1.17.0
threadpoolctl==3.1.0
tomli==2.0.1
traits==6.4.3
traitsui==8.0.0
typing_extensions==4.7.1
vtk==9.3.1
zipp==3.15.0
| name: mne-python
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2022.12.7=py37h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- pip=22.3.1=py37h06a4308_0
- python=3.7.16=h7a1cb2a_0
- readline=8.2=h5eee18b_0
- setuptools=65.6.3=py37h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- wheel=0.38.4=py37h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- apptools==5.2.1
- configobj==5.0.9
- cycler==0.11.0
- envisage==7.0.3
- exceptiongroup==1.2.2
- fonttools==4.38.0
- h5py==3.8.0
- importlib-metadata==6.7.0
- importlib-resources==5.12.0
- iniconfig==2.0.0
- joblib==1.3.2
- kiwisolver==1.4.5
- matplotlib==3.5.3
- mayavi==4.8.1
- nibabel==4.0.2
- nose==1.3.7
- nose-timer==1.0.1
- numpy==1.21.6
- packaging==24.0
- pandas==1.3.5
- pillow==9.5.0
- pluggy==1.2.0
- pyface==8.0.0
- pygments==2.17.2
- pyparsing==3.1.4
- pysurfer==0.11.2
- pytest==7.4.4
- python-dateutil==2.9.0.post0
- pytz==2025.2
- scikit-learn==1.0.2
- scipy==1.7.3
- six==1.17.0
- threadpoolctl==3.1.0
- tomli==2.0.1
- traits==6.4.3
- traitsui==8.0.0
- typing-extensions==4.7.1
- vtk==9.3.1
- zipp==3.15.0
prefix: /opt/conda/envs/mne-python
| [
"mne/stats/tests/test_multi_comp.py::test_multi_pval_correction"
] | [] | [] | [] | BSD 3-Clause "New" or "Revised" License | 171 |
|
poliastro__poliastro-51 | f81a56b7ab28391b66091bcf002462749d2a8f65 | 2015-06-23 15:32:34 | f47ee2b0790a82b3a76e24794d2916deb8340d1b | diff --git a/README b/README
index f6d8cd9c..f238398c 100644
--- a/README
+++ b/README
@@ -20,10 +20,6 @@
.. image:: https://ci.appveyor.com/api/projects/status/ajg5j8byv8isslso/branch/master?svg=true
:target: https://ci.appveyor.com/project/poliastro/poliastro/branch/master
-.. image:: https://badge.waffle.io/poliastro/poliastro.png?label=Ready
- :target: https://waffle.io/poliastro/poliastro
- :alt: 'Stories in Ready'
-
.. image:: https://img.shields.io/badge/license-MIT-blue.svg
:target: https://raw.githubusercontent.com/poliastro/poliastro/master/COPYING
diff --git a/poliastro/twobody/propagation.py b/poliastro/twobody/propagation.py
index 70a91f4f..567fd624 100644
--- a/poliastro/twobody/propagation.py
+++ b/poliastro/twobody/propagation.py
@@ -85,7 +85,7 @@ def _kepler(k, r0, v0, tof, numiter, rtol):
norm_r = xi * xi * c2_psi + dot_r0v0 / sqrt_mu * xi * (1 - psi * c3_psi) + norm_r0 * (1 - psi * c2_psi)
xi_new = xi + (sqrt_mu * tof - xi * xi * xi * c3_psi - dot_r0v0 / sqrt_mu * xi * xi * c2_psi -
norm_r0 * xi * (1 - psi * c3_psi)) / norm_r
- if abs((xi_new - xi) / xi_new) < rtol:
+ if abs(np.divide(xi_new - xi, xi_new)) < rtol or abs(xi_new - xi) < rtol:
break
else:
count += 1
| ZeroDivisionError when propagating with time zero
Actually if NUMBA_DISABLE_JIT is exported this appears as a maximum number of iterations error. Why does it change is a matter of study, but still the easiest way to fix it is to contemplate the special case of time = 0.0 at the very beginning of the `_kepler` function. | poliastro/poliastro | diff --git a/poliastro/tests/test_twobody.py b/poliastro/tests/test_twobody.py
index ac0b0e97..5da1ac2d 100644
--- a/poliastro/tests/test_twobody.py
+++ b/poliastro/tests/test_twobody.py
@@ -228,8 +228,23 @@ def test_propagate():
ss0 = State.from_vectors(Earth, r0, v0)
tof = 40 * u.min
ss1 = ss0.propagate(tof)
- r, v = ss1.r, ss1.v
+ r, v = ss1.rv()
assert_array_almost_equal(r.value, [-4219.7527, 4363.0292, -3958.7666],
decimal=1)
assert_array_almost_equal(v.value, [3.689866, -1.916735, -6.112511],
decimal=4)
+
+
+def test_propagation_zero_time_returns_same_state():
+ # Bug #50
+ r0 = [1131.340, -2282.343, 6672.423] * u.km
+ v0 = [-5.64305, 4.30333, 2.42879] * u.km / u.s
+ ss0 = State.from_vectors(Earth, r0, v0)
+ tof = 0 * u.s
+
+ ss1 = ss0.propagate(tof)
+
+ r, v = ss1.rv()
+
+ assert_array_almost_equal(r.value, r0.value)
+ assert_array_almost_equal(v.value, v0.value)
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 1,
"issue_text_score": 1,
"test_score": 0
},
"num_modified_files": 2
} | 0.3 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "numpy>=1.16.0 astropy>=1.0 numba>=0.18 matplotlib jplephem scipy",
"pip_packages": [
"pytest"
],
"pre_install": [
"apt-get update",
"apt-get install -y gfortran"
],
"python": "3.9",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | astropy @ file:///croot/astropy_1697468907928/work
Brotli @ file:///croot/brotli-split_1736182456865/work
contourpy @ file:///croot/contourpy_1738160616259/work
cycler @ file:///tmp/build/80754af9/cycler_1637851556182/work
exceptiongroup==1.2.2
fonttools @ file:///croot/fonttools_1737039080035/work
importlib_resources @ file:///croot/importlib_resources-suite_1720641103994/work
iniconfig==2.1.0
jplephem @ file:///home/conda/feedstock_root/build_artifacts/jplephem_1734349820189/work
kiwisolver @ file:///croot/kiwisolver_1672387140495/work
llvmlite @ file:///croot/llvmlite_1736366675558/work
matplotlib==3.9.2
numba @ file:///croot/numba_1738606613869/work
numpy @ file:///croot/numpy_and_numpy_base_1708638617955/work/dist/numpy-1.26.4-cp39-cp39-linux_x86_64.whl#sha256=b69ac3eb7538c5a224df429dc49031914fb977825ee007f2c77a13f7aa6cd769
packaging @ file:///croot/packaging_1734472117206/work
pillow @ file:///croot/pillow_1738010226202/work
pluggy==1.5.0
-e git+https://github.com/poliastro/poliastro.git@f81a56b7ab28391b66091bcf002462749d2a8f65#egg=poliastro
pyerfa @ file:///croot/pyerfa_1738082786199/work
pyparsing @ file:///croot/pyparsing_1731445506121/work
PyQt6==6.7.1
PyQt6_sip @ file:///croot/pyqt-split_1740498191142/work/pyqt_sip
pytest==8.3.5
python-dateutil @ file:///croot/python-dateutil_1716495738603/work
PyYAML @ file:///croot/pyyaml_1728657952215/work
scipy @ file:///croot/scipy_1733756309941/work/dist/scipy-1.13.1-cp39-cp39-linux_x86_64.whl#sha256=3b247b926209f2d9f719ebae39faf3ff891b2596150ed8f8349adfc3eb19441c
sip @ file:///croot/sip_1738856193618/work
six @ file:///tmp/build/80754af9/six_1644875935023/work
tomli @ file:///opt/conda/conda-bld/tomli_1657175507142/work
tornado @ file:///croot/tornado_1733960490606/work
unicodedata2 @ file:///croot/unicodedata2_1736541023050/work
zipp @ file:///croot/zipp_1732630741423/work
| name: poliastro
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- astropy=5.3.4=py39ha9d4c09_0
- blas=1.0=openblas
- brotli-python=1.0.9=py39h6a678d5_9
- bzip2=1.0.8=h5eee18b_6
- c-ares=1.19.1=h5eee18b_0
- ca-certificates=2025.2.25=h06a4308_0
- contourpy=1.2.1=py39hdb19cb5_1
- cycler=0.11.0=pyhd3eb1b0_0
- cyrus-sasl=2.1.28=h52b45da_1
- expat=2.6.4=h6a678d5_0
- fontconfig=2.14.1=h55d465d_3
- fonttools=4.55.3=py39h5eee18b_0
- freetype=2.12.1=h4a9f257_0
- icu=73.1=h6a678d5_0
- importlib_resources=6.4.0=py39h06a4308_0
- jpeg=9e=h5eee18b_3
- jplephem=2.21=pyh9b8db34_1
- kiwisolver=1.4.4=py39h6a678d5_0
- krb5=1.20.1=h143b758_1
- lcms2=2.16=hb9589c4_0
- ld_impl_linux-64=2.40=h12ee557_0
- lerc=4.0.0=h6a678d5_0
- libabseil=20250127.0=cxx17_h6a678d5_0
- libcups=2.4.2=h2d74bed_1
- libcurl=8.12.1=hc9e6f67_0
- libdeflate=1.22=h5eee18b_0
- libedit=3.1.20230828=h5eee18b_0
- libev=4.33=h7f8727e_1
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgfortran-ng=11.2.0=h00389a5_1
- libgfortran5=11.2.0=h1234567_1
- libglib=2.78.4=hdc74915_0
- libgomp=11.2.0=h1234567_1
- libiconv=1.16=h5eee18b_3
- libllvm14=14.0.6=hecde1de_4
- libnghttp2=1.57.0=h2d74bed_0
- libopenblas=0.3.21=h043d6bf_0
- libpng=1.6.39=h5eee18b_0
- libpq=17.4=hdbd6064_0
- libprotobuf=5.29.3=hc99497a_0
- libssh2=1.11.1=h251f7ec_0
- libstdcxx-ng=11.2.0=h1234567_1
- libtiff=4.5.1=hffd6297_1
- libuuid=1.41.5=h5eee18b_0
- libwebp-base=1.3.2=h5eee18b_1
- libxcb=1.15=h7f8727e_0
- libxkbcommon=1.0.1=h097e994_2
- libxml2=2.13.5=hfdd30dd_0
- llvmlite=0.43.0=py39h6a678d5_1
- lz4-c=1.9.4=h6a678d5_1
- matplotlib=3.9.2=py39h06a4308_1
- matplotlib-base=3.9.2=py39hbfdbfaf_1
- mysql=8.4.0=h721767e_2
- ncurses=6.4=h6a678d5_0
- numba=0.60.0=py39h6a678d5_1
- numpy=1.26.4=py39heeff2f4_0
- numpy-base=1.26.4=py39h8a23956_0
- openjpeg=2.5.2=he7f1fd0_0
- openldap=2.6.4=h42fbc30_0
- openssl=3.0.16=h5eee18b_0
- packaging=24.2=py39h06a4308_0
- pcre2=10.42=hebb0a14_1
- pillow=11.1.0=py39hcea889d_0
- pip=25.0=py39h06a4308_0
- pybind11-abi=4=hd3eb1b0_1
- pyerfa=2.0.1.5=py39h5eee18b_0
- pyparsing=3.2.0=py39h06a4308_0
- pyqt=6.7.1=py39h6a678d5_0
- pyqt6-sip=13.9.1=py39h5eee18b_0
- python=3.9.21=he870216_1
- python-dateutil=2.9.0post0=py39h06a4308_2
- pyyaml=6.0.2=py39h5eee18b_0
- qtbase=6.7.3=hdaa5aa8_0
- qtdeclarative=6.7.3=h6a678d5_0
- qtsvg=6.7.3=he621ea3_0
- qttools=6.7.3=h80c7b02_0
- qtwebchannel=6.7.3=h6a678d5_0
- qtwebsockets=6.7.3=h6a678d5_0
- readline=8.2=h5eee18b_0
- scipy=1.13.1=py39heeff2f4_1
- setuptools=75.8.0=py39h06a4308_0
- sip=6.10.0=py39h6a678d5_0
- six=1.16.0=pyhd3eb1b0_1
- sqlite=3.45.3=h5eee18b_0
- tbb=2021.8.0=hdb19cb5_0
- tk=8.6.14=h39e8969_0
- tomli=2.0.1=py39h06a4308_0
- tornado=6.4.2=py39h5eee18b_0
- tzdata=2025a=h04d1e81_0
- unicodedata2=15.1.0=py39h5eee18b_1
- wheel=0.45.1=py39h06a4308_0
- xcb-util-cursor=0.1.4=h5eee18b_0
- xz=5.6.4=h5eee18b_1
- yaml=0.2.5=h7b6447c_0
- zipp=3.21.0=py39h06a4308_0
- zlib=1.2.13=h5eee18b_1
- zstd=1.5.6=hc292b87_0
- pip:
- exceptiongroup==1.2.2
- iniconfig==2.1.0
- pluggy==1.5.0
- pytest==8.3.5
prefix: /opt/conda/envs/poliastro
| [
"poliastro/tests/test_twobody.py::test_propagation_zero_time_returns_same_state"
] | [
"poliastro/tests/test_twobody.py::test_state_has_attractor_given_in_constructor",
"poliastro/tests/test_twobody.py::test_default_time_for_new_state",
"poliastro/tests/test_twobody.py::test_state_has_elements_given_in_constructor",
"poliastro/tests/test_twobody.py::test_state_has_individual_elements",
"poliastro/tests/test_twobody.py::test_circular_has_proper_semimajor_axis",
"poliastro/tests/test_twobody.py::test_geosync_has_proper_period",
"poliastro/tests/test_twobody.py::test_parabolic_elements_fail_early",
"poliastro/tests/test_twobody.py::test_parabolic_has_proper_eccentricity",
"poliastro/tests/test_twobody.py::test_parabolic_has_zero_energy",
"poliastro/tests/test_twobody.py::test_perigee_and_apogee",
"poliastro/tests/test_twobody.py::test_convert_from_rv_to_coe",
"poliastro/tests/test_twobody.py::test_apply_zero_maneuver_returns_equal_state",
"poliastro/tests/test_twobody.py::test_apply_maneuver_changes_epoch",
"poliastro/tests/test_twobody.py::test_perifocal_points_to_perigee",
"poliastro/tests/test_twobody.py::test_pqw_for_circular_equatorial_orbit"
] | [
"poliastro/tests/test_twobody.py::test_state_raises_unitserror_if_elements_units_are_wrong",
"poliastro/tests/test_twobody.py::test_state_has_rv_given_in_constructor",
"poliastro/tests/test_twobody.py::test_state_raises_unitserror_if_rv_units_are_wrong",
"poliastro/tests/test_twobody.py::test_convert_from_coe_to_rv",
"poliastro/tests/test_twobody.py::test_propagate"
] | [] | MIT License | 172 |
|
CybOXProject__python-cybox-265 | c889ade168e7e0a411af9c836c95d61d7b5c4583 | 2015-06-23 18:29:58 | a378deb68b3ac56360c5cc35ff5aad1cd3dcab83 | diff --git a/cybox/bindings/extensions/location/ciq_address_3_0.py b/cybox/bindings/extensions/location/ciq_address_3_0.py
index ae0ad70..a148347 100644
--- a/cybox/bindings/extensions/location/ciq_address_3_0.py
+++ b/cybox/bindings/extensions/location/ciq_address_3_0.py
@@ -2,7 +2,9 @@
# See LICENSE.txt for complete terms.
import sys
-from cybox.bindings import *
+
+from mixbox.binding_utils import *
+
import cybox.bindings.cybox_common as cybox_common
XML_NS = "http://cybox.mitre.org/extensions/Address#CIQAddress3.0-1"
| CIQ Address extension non mixboxified
I think the `cybox.extensions.location.ciq_address_3_0` module was left out of the mixboxification effort. | CybOXProject/python-cybox | diff --git a/cybox/test/extensions/__init__.py b/cybox/test/extensions/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/cybox/test/extensions/location/__init__.py b/cybox/test/extensions/location/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/cybox/test/extensions/location/ciq_test.py b/cybox/test/extensions/location/ciq_test.py
new file mode 100644
index 0000000..a9d4318
--- /dev/null
+++ b/cybox/test/extensions/location/ciq_test.py
@@ -0,0 +1,26 @@
+# Copyright (c) 2015, The MITRE Corporation. All rights reserved.
+# See LICENSE.txt for complete terms.
+
+"""Tests for various encoding issues throughout the library"""
+
+import unittest
+
+from mixbox.vendor.six import StringIO
+
+from cybox.bindings.extensions.location import ciq_address_3_0
+
+
+class CIQAddressTests(unittest.TestCase):
+
+ def test_can_load_extension(self):
+ addr = ciq_address_3_0.CIQAddress3_0InstanceType()
+
+ # Really basic test to verify the extension works.
+ s = StringIO()
+ addr.export(s.write, 0)
+ xml = s.getvalue()
+ self.assertEqual(165, len(xml))
+
+
+if __name__ == "__main__":
+ unittest.main()
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_short_problem_statement"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 0,
"issue_text_score": 2,
"test_score": 3
},
"num_modified_files": 1
} | 2.1 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[docs,test]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"nose",
"pytest"
],
"pre_install": [
"apt-get update",
"apt-get install -y libxml2-dev libxslt1-dev zlib1g-dev"
],
"python": "2.7",
"reqs_path": [
"requirements.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | alabaster==0.7.13
attrs==22.2.0
Babel==2.11.0
certifi==2021.5.30
-e git+https://github.com/CybOXProject/python-cybox.git@c889ade168e7e0a411af9c836c95d61d7b5c4583#egg=cybox
distlib==0.3.9
docutils==0.18.1
filelock==3.4.1
importlib-metadata==4.8.3
importlib-resources==5.4.0
iniconfig==1.1.1
Jinja2==3.0.3
lxml==5.3.1
MarkupSafe==2.0.1
mixbox==1.0.5
nose==1.3.0
ordered-set==4.0.2
packaging==21.3
platformdirs==2.4.0
pluggy==1.0.0
py==1.11.0
Pygments==2.14.0
pyparsing==3.1.4
pytest==7.0.1
python-dateutil==2.9.0.post0
pytz==2025.2
six==1.17.0
snowballstemmer==2.2.0
Sphinx==1.3.1
sphinx-rtd-theme==0.1.8
tomli==1.2.3
tox==1.6.1
typing_extensions==4.1.1
virtualenv==20.17.1
weakrefmethod==1.0.3
zipp==3.6.0
| name: python-cybox
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- pip=21.2.2=py36h06a4308_0
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_0
- setuptools=58.0.4=py36h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- alabaster==0.7.13
- attrs==22.2.0
- babel==2.11.0
- distlib==0.3.9
- docutils==0.18.1
- filelock==3.4.1
- importlib-metadata==4.8.3
- importlib-resources==5.4.0
- iniconfig==1.1.1
- jinja2==3.0.3
- lxml==5.3.1
- markupsafe==2.0.1
- mixbox==1.0.5
- nose==1.3.0
- ordered-set==4.0.2
- packaging==21.3
- platformdirs==2.4.0
- pluggy==1.0.0
- py==1.11.0
- pygments==2.14.0
- pyparsing==3.1.4
- pytest==7.0.1
- python-dateutil==2.9.0.post0
- pytz==2025.2
- six==1.17.0
- snowballstemmer==2.2.0
- sphinx==1.3.1
- sphinx-rtd-theme==0.1.8
- tomli==1.2.3
- tox==1.6.1
- typing-extensions==4.1.1
- virtualenv==20.17.1
- weakrefmethod==1.0.3
- zipp==3.6.0
prefix: /opt/conda/envs/python-cybox
| [
"cybox/test/extensions/location/ciq_test.py::CIQAddressTests::test_can_load_extension"
] | [] | [] | [] | BSD 3-Clause "New" or "Revised" License | 173 |
|
poliastro__poliastro-52 | ee3390ea90914c4be4048717652860b34413d490 | 2015-06-24 08:31:00 | f47ee2b0790a82b3a76e24794d2916deb8340d1b | diff --git a/.travis.yml b/.travis.yml
index 82f85935..6d65bda5 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -20,6 +20,7 @@ install:
- conda create -q -n test-environment python=$TRAVIS_PYTHON_VERSION
- source activate test-environment
- conda install numpy "numba>=0.18" "astropy>=1.0" matplotlib pytest pip coverage requests pyyaml scipy
+ - conda install jplephem -c poliastro
- pip install coveralls pytest-cov
script:
- py.test -vv
diff --git a/appveyor.yml b/appveyor.yml
index bef87b9e..a0d4b621 100644
--- a/appveyor.yml
+++ b/appveyor.yml
@@ -36,6 +36,7 @@ install:
# Install dependencies
- "conda install -q numpy numba>=0.18 astropy>=1.0 matplotlib pytest scipy"
+ - "conda install jplephem -c poliastro"
build: off
diff --git a/poliastro/ephem.py b/poliastro/ephem.py
index cba4b1d8..3aabcc7f 100644
--- a/poliastro/ephem.py
+++ b/poliastro/ephem.py
@@ -129,5 +129,5 @@ def planet_ephem(body, epoch, kernel=default_kernel):
"""
r, v = kernel[0, body].compute_and_differentiate(epoch.jd1, epoch.jd2)
r *= u.km
- v *= u.km / u.s
+ v *= u.km / u.day
return r, v
| Fix velocity units in ephem
See discussion at https://github.com/brandon-rhodes/python-jplephem/issues/11 | poliastro/poliastro | diff --git a/poliastro/tests/test_ephem.py b/poliastro/tests/test_ephem.py
new file mode 100644
index 00000000..ecda97fc
--- /dev/null
+++ b/poliastro/tests/test_ephem.py
@@ -0,0 +1,29 @@
+# coding: utf-8
+import numpy as np
+
+from astropy import time
+from astropy import units as u
+
+from poliastro import ephem
+
+
+class FakeKernel(object):
+ def __getitem__(self, index):
+ return FakeSegment()
+
+
+class FakeSegment(object):
+ def compute_and_differentiate(self, jd1, jd2=None):
+ r = np.array([1, 1, 1])
+ v = np.array([1, 1, 1])
+ return r, v
+
+
+def test_proper_velocity_units():
+ # Bug #49
+ _body = 0
+ _epoch = time.Time("2000-01-01 00:00")
+
+ r, v = ephem.planet_ephem(_body, _epoch, FakeKernel())
+
+ assert v.unit == u.km / u.day
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_short_problem_statement",
"has_hyperlinks",
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 1,
"issue_text_score": 3,
"test_score": 0
},
"num_modified_files": 3
} | 0.3 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "numpy>=1.16.0 astropy>=1.0 numba>=0.18 matplotlib jplephem scipy",
"pip_packages": [
"pytest"
],
"pre_install": [
"apt-get update",
"apt-get install -y gfortran"
],
"python": "3.9",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | astropy @ file:///croot/astropy_1697468907928/work
Brotli @ file:///croot/brotli-split_1736182456865/work
contourpy @ file:///croot/contourpy_1738160616259/work
cycler @ file:///tmp/build/80754af9/cycler_1637851556182/work
exceptiongroup==1.2.2
fonttools @ file:///croot/fonttools_1737039080035/work
importlib_resources @ file:///croot/importlib_resources-suite_1720641103994/work
iniconfig==2.1.0
jplephem @ file:///home/conda/feedstock_root/build_artifacts/jplephem_1734349820189/work
kiwisolver @ file:///croot/kiwisolver_1672387140495/work
llvmlite @ file:///croot/llvmlite_1736366675558/work
matplotlib==3.9.2
numba @ file:///croot/numba_1738606613869/work
numpy @ file:///croot/numpy_and_numpy_base_1708638617955/work/dist/numpy-1.26.4-cp39-cp39-linux_x86_64.whl#sha256=b69ac3eb7538c5a224df429dc49031914fb977825ee007f2c77a13f7aa6cd769
packaging @ file:///croot/packaging_1734472117206/work
pillow @ file:///croot/pillow_1738010226202/work
pluggy==1.5.0
-e git+https://github.com/poliastro/poliastro.git@ee3390ea90914c4be4048717652860b34413d490#egg=poliastro
pyerfa @ file:///croot/pyerfa_1738082786199/work
pyparsing @ file:///croot/pyparsing_1731445506121/work
PyQt6==6.7.1
PyQt6_sip @ file:///croot/pyqt-split_1740498191142/work/pyqt_sip
pytest==8.3.5
python-dateutil @ file:///croot/python-dateutil_1716495738603/work
PyYAML @ file:///croot/pyyaml_1728657952215/work
scipy @ file:///croot/scipy_1733756309941/work/dist/scipy-1.13.1-cp39-cp39-linux_x86_64.whl#sha256=3b247b926209f2d9f719ebae39faf3ff891b2596150ed8f8349adfc3eb19441c
sip @ file:///croot/sip_1738856193618/work
six @ file:///tmp/build/80754af9/six_1644875935023/work
tomli @ file:///opt/conda/conda-bld/tomli_1657175507142/work
tornado @ file:///croot/tornado_1733960490606/work
unicodedata2 @ file:///croot/unicodedata2_1736541023050/work
zipp @ file:///croot/zipp_1732630741423/work
| name: poliastro
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- astropy=5.3.4=py39ha9d4c09_0
- blas=1.0=openblas
- brotli-python=1.0.9=py39h6a678d5_9
- bzip2=1.0.8=h5eee18b_6
- c-ares=1.19.1=h5eee18b_0
- ca-certificates=2025.2.25=h06a4308_0
- contourpy=1.2.1=py39hdb19cb5_1
- cycler=0.11.0=pyhd3eb1b0_0
- cyrus-sasl=2.1.28=h52b45da_1
- expat=2.6.4=h6a678d5_0
- fontconfig=2.14.1=h55d465d_3
- fonttools=4.55.3=py39h5eee18b_0
- freetype=2.12.1=h4a9f257_0
- icu=73.1=h6a678d5_0
- importlib_resources=6.4.0=py39h06a4308_0
- jpeg=9e=h5eee18b_3
- jplephem=2.21=pyh9b8db34_1
- kiwisolver=1.4.4=py39h6a678d5_0
- krb5=1.20.1=h143b758_1
- lcms2=2.16=hb9589c4_0
- ld_impl_linux-64=2.40=h12ee557_0
- lerc=4.0.0=h6a678d5_0
- libabseil=20250127.0=cxx17_h6a678d5_0
- libcups=2.4.2=h2d74bed_1
- libcurl=8.12.1=hc9e6f67_0
- libdeflate=1.22=h5eee18b_0
- libedit=3.1.20230828=h5eee18b_0
- libev=4.33=h7f8727e_1
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgfortran-ng=11.2.0=h00389a5_1
- libgfortran5=11.2.0=h1234567_1
- libglib=2.78.4=hdc74915_0
- libgomp=11.2.0=h1234567_1
- libiconv=1.16=h5eee18b_3
- libllvm14=14.0.6=hecde1de_4
- libnghttp2=1.57.0=h2d74bed_0
- libopenblas=0.3.21=h043d6bf_0
- libpng=1.6.39=h5eee18b_0
- libpq=17.4=hdbd6064_0
- libprotobuf=5.29.3=hc99497a_0
- libssh2=1.11.1=h251f7ec_0
- libstdcxx-ng=11.2.0=h1234567_1
- libtiff=4.5.1=hffd6297_1
- libuuid=1.41.5=h5eee18b_0
- libwebp-base=1.3.2=h5eee18b_1
- libxcb=1.15=h7f8727e_0
- libxkbcommon=1.0.1=h097e994_2
- libxml2=2.13.5=hfdd30dd_0
- llvmlite=0.43.0=py39h6a678d5_1
- lz4-c=1.9.4=h6a678d5_1
- matplotlib=3.9.2=py39h06a4308_1
- matplotlib-base=3.9.2=py39hbfdbfaf_1
- mysql=8.4.0=h721767e_2
- ncurses=6.4=h6a678d5_0
- numba=0.60.0=py39h6a678d5_1
- numpy=1.26.4=py39heeff2f4_0
- numpy-base=1.26.4=py39h8a23956_0
- openjpeg=2.5.2=he7f1fd0_0
- openldap=2.6.4=h42fbc30_0
- openssl=3.0.16=h5eee18b_0
- packaging=24.2=py39h06a4308_0
- pcre2=10.42=hebb0a14_1
- pillow=11.1.0=py39hcea889d_0
- pip=25.0=py39h06a4308_0
- pybind11-abi=4=hd3eb1b0_1
- pyerfa=2.0.1.5=py39h5eee18b_0
- pyparsing=3.2.0=py39h06a4308_0
- pyqt=6.7.1=py39h6a678d5_0
- pyqt6-sip=13.9.1=py39h5eee18b_0
- python=3.9.21=he870216_1
- python-dateutil=2.9.0post0=py39h06a4308_2
- pyyaml=6.0.2=py39h5eee18b_0
- qtbase=6.7.3=hdaa5aa8_0
- qtdeclarative=6.7.3=h6a678d5_0
- qtsvg=6.7.3=he621ea3_0
- qttools=6.7.3=h80c7b02_0
- qtwebchannel=6.7.3=h6a678d5_0
- qtwebsockets=6.7.3=h6a678d5_0
- readline=8.2=h5eee18b_0
- scipy=1.13.1=py39heeff2f4_1
- setuptools=75.8.0=py39h06a4308_0
- sip=6.10.0=py39h6a678d5_0
- six=1.16.0=pyhd3eb1b0_1
- sqlite=3.45.3=h5eee18b_0
- tbb=2021.8.0=hdb19cb5_0
- tk=8.6.14=h39e8969_0
- tomli=2.0.1=py39h06a4308_0
- tornado=6.4.2=py39h5eee18b_0
- tzdata=2025a=h04d1e81_0
- unicodedata2=15.1.0=py39h5eee18b_1
- wheel=0.45.1=py39h06a4308_0
- xcb-util-cursor=0.1.4=h5eee18b_0
- xz=5.6.4=h5eee18b_1
- yaml=0.2.5=h7b6447c_0
- zipp=3.21.0=py39h06a4308_0
- zlib=1.2.13=h5eee18b_1
- zstd=1.5.6=hc292b87_0
- pip:
- exceptiongroup==1.2.2
- iniconfig==2.1.0
- pluggy==1.5.0
- pytest==8.3.5
prefix: /opt/conda/envs/poliastro
| [
"poliastro/tests/test_ephem.py::test_proper_velocity_units"
] | [] | [] | [] | MIT License | 174 |
|
sympy__sympy-9576 | 45c2fb138e0ed3d08a4b75e9add1d517c08d983b | 2015-06-26 11:39:20 | 0241b35cae5f2adc04dc37b25f7dc9c5f00bd746 | diff --git a/sympy/utilities/codegen.py b/sympy/utilities/codegen.py
index ef653b5b99..bb7eefc2ec 100644
--- a/sympy/utilities/codegen.py
+++ b/sympy/utilities/codegen.py
@@ -669,6 +669,7 @@ def dump_code(self, routines, f, prefix, header=True, empty=True):
code_lines.append("\n")
code_lines.extend(self._get_routine_opening(routine))
code_lines.extend(self._declare_arguments(routine))
+ code_lines.extend(self._declare_globals(routine))
code_lines.extend(self._declare_locals(routine))
if empty:
code_lines.append("\n")
@@ -766,6 +767,10 @@ def _declare_arguments(self, routine):
# arguments are declared in prototype
return []
+ def _declare_globals(self, routine):
+ # global variables are not explicitly declared within C functions
+ return []
+
def _declare_locals(self, routine):
# loop variables are declared in loop statement
return []
@@ -969,6 +974,11 @@ def _declare_arguments(self, routine):
return code_list
+ def _declare_globals(self, routine):
+ # Global variables not explicitly declared within Fortran 90 functions.
+ # Note: a future F77 mode may need to generate "common" blocks.
+ return []
+
def _declare_locals(self, routine):
code_list = []
for var in sorted(routine.local_vars, key=str):
@@ -1246,6 +1256,12 @@ def _get_routine_opening(self, routine):
def _declare_arguments(self, routine):
return []
+ def _declare_globals(self, routine):
+ if not routine.global_vars:
+ return []
+ s = " ".join(sorted([self._get_symbol(g) for g in routine.global_vars]))
+ return ["global " + s + "\n"]
+
def _declare_locals(self, routine):
return []
@@ -1302,6 +1318,7 @@ def dump_m(self, routines, f, prefix, header=True, empty=True, inline=True):
" Autogenerated by sympy\n")
code_lines.append(''.join(self._get_header()))
code_lines.extend(self._declare_arguments(routine))
+ code_lines.extend(self._declare_globals(routine))
code_lines.extend(self._declare_locals(routine))
if empty:
code_lines.append("\n")
| codegen octave global vars should print "global foo" at top of function
After #9535, we should improve the octave printing further to print `global foo bar` in the generated function. | sympy/sympy | diff --git a/sympy/utilities/tests/test_codegen_octave.py b/sympy/utilities/tests/test_codegen_octave.py
index 5fe36f2dda..3d6bce7d94 100644
--- a/sympy/utilities/tests/test_codegen_octave.py
+++ b/sympy/utilities/tests/test_codegen_octave.py
@@ -566,6 +566,7 @@ def test_m_not_supported():
)
assert source == expected
+
def test_global_vars_octave():
x, y, z, t = symbols("x y z t")
result = codegen(('f', x*y), "Octave", header=False, empty=False,
@@ -573,6 +574,7 @@ def test_global_vars_octave():
source = result[0][1]
expected = (
"function out1 = f(x)\n"
+ " global y\n"
" out1 = x.*y;\n"
"end\n"
)
@@ -583,6 +585,7 @@ def test_global_vars_octave():
source = result[0][1]
expected = (
"function out1 = f(x, y)\n"
+ " global t z\n"
" out1 = x.*y + z;\n"
"end\n"
)
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 0,
"issue_text_score": 1,
"test_score": 1
},
"num_modified_files": 1
} | 0.7 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "pytest",
"pip_packages": [
"pytest"
],
"pre_install": null,
"python": "3.6",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | attrs @ file:///opt/conda/conda-bld/attrs_1642510447205/work
certifi==2021.5.30
importlib-metadata @ file:///tmp/build/80754af9/importlib-metadata_1631916693255/work
iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work
more-itertools @ file:///tmp/build/80754af9/more-itertools_1637733554872/work
mpmath==1.3.0
packaging @ file:///tmp/build/80754af9/packaging_1637314298585/work
pluggy @ file:///tmp/build/80754af9/pluggy_1615976315926/work
py @ file:///opt/conda/conda-bld/py_1644396412707/work
pyparsing @ file:///tmp/build/80754af9/pyparsing_1635766073266/work
pytest==6.2.4
-e git+https://github.com/sympy/sympy.git@45c2fb138e0ed3d08a4b75e9add1d517c08d983b#egg=sympy
toml @ file:///tmp/build/80754af9/toml_1616166611790/work
typing_extensions @ file:///opt/conda/conda-bld/typing_extensions_1647553014482/work
zipp @ file:///tmp/build/80754af9/zipp_1633618647012/work
| name: sympy
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- attrs=21.4.0=pyhd3eb1b0_0
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- importlib-metadata=4.8.1=py36h06a4308_0
- importlib_metadata=4.8.1=hd3eb1b0_0
- iniconfig=1.1.1=pyhd3eb1b0_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- more-itertools=8.12.0=pyhd3eb1b0_0
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- packaging=21.3=pyhd3eb1b0_0
- pip=21.2.2=py36h06a4308_0
- pluggy=0.13.1=py36h06a4308_0
- py=1.11.0=pyhd3eb1b0_0
- pyparsing=3.0.4=pyhd3eb1b0_0
- pytest=6.2.4=py36h06a4308_2
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_0
- setuptools=58.0.4=py36h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- toml=0.10.2=pyhd3eb1b0_0
- typing_extensions=4.1.1=pyh06a4308_0
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- zipp=3.6.0=pyhd3eb1b0_0
- zlib=1.2.13=h5eee18b_1
- pip:
- mpmath==1.3.0
prefix: /opt/conda/envs/sympy
| [
"sympy/utilities/tests/test_codegen_octave.py::test_global_vars_octave"
] | [] | [
"sympy/utilities/tests/test_codegen_octave.py::test_empty_m_code",
"sympy/utilities/tests/test_codegen_octave.py::test_m_simple_code",
"sympy/utilities/tests/test_codegen_octave.py::test_m_simple_code_with_header",
"sympy/utilities/tests/test_codegen_octave.py::test_m_simple_code_nameout",
"sympy/utilities/tests/test_codegen_octave.py::test_m_numbersymbol",
"sympy/utilities/tests/test_codegen_octave.py::test_m_code_argument_order",
"sympy/utilities/tests/test_codegen_octave.py::test_multiple_results_m",
"sympy/utilities/tests/test_codegen_octave.py::test_results_named_unordered",
"sympy/utilities/tests/test_codegen_octave.py::test_results_named_ordered",
"sympy/utilities/tests/test_codegen_octave.py::test_complicated_m_codegen",
"sympy/utilities/tests/test_codegen_octave.py::test_m_output_arg_mixed_unordered",
"sympy/utilities/tests/test_codegen_octave.py::test_m_piecewise_",
"sympy/utilities/tests/test_codegen_octave.py::test_m_multifcns_per_file",
"sympy/utilities/tests/test_codegen_octave.py::test_m_multifcns_per_file_w_header",
"sympy/utilities/tests/test_codegen_octave.py::test_m_filename_match_first_fcn",
"sympy/utilities/tests/test_codegen_octave.py::test_m_matrix_named",
"sympy/utilities/tests/test_codegen_octave.py::test_m_matrix_named_matsym",
"sympy/utilities/tests/test_codegen_octave.py::test_m_matrix_output_autoname",
"sympy/utilities/tests/test_codegen_octave.py::test_m_matrix_output_autoname_2",
"sympy/utilities/tests/test_codegen_octave.py::test_m_results_matrix_named_ordered",
"sympy/utilities/tests/test_codegen_octave.py::test_m_matrixsymbol_slice",
"sympy/utilities/tests/test_codegen_octave.py::test_m_matrixsymbol_slice2",
"sympy/utilities/tests/test_codegen_octave.py::test_m_matrixsymbol_slice3",
"sympy/utilities/tests/test_codegen_octave.py::test_m_matrixsymbol_slice_autoname",
"sympy/utilities/tests/test_codegen_octave.py::test_m_loops",
"sympy/utilities/tests/test_codegen_octave.py::test_m_tensor_loops_multiple_contractions",
"sympy/utilities/tests/test_codegen_octave.py::test_m_InOutArgument",
"sympy/utilities/tests/test_codegen_octave.py::test_m_InOutArgument_order",
"sympy/utilities/tests/test_codegen_octave.py::test_m_not_supported"
] | [] | BSD | 175 |
|
mkdocs__mkdocs-668 | 98814de505c9d8f1849292372eff1c5ae492261c | 2015-06-27 22:50:14 | 3dfd95deae8379473714b346e61c1d63e957bb98 | landscape-bot: [](https://landscape.io/diff/187394)
Code quality remained the same when pulling **[a5ab2e1](https://github.com/d0ugal/mkdocs/commit/a5ab2e12e22a199617fcffd129d4762bfc6b712b) on d0ugal:symlink** into **[98814de](https://github.com/mkdocs/mkdocs/commit/98814de505c9d8f1849292372eff1c5ae492261c) on mkdocs:master**. | diff --git a/mkdocs/config/config_options.py b/mkdocs/config/config_options.py
index 38a61442..28ee62c8 100644
--- a/mkdocs/config/config_options.py
+++ b/mkdocs/config/config_options.py
@@ -332,6 +332,13 @@ class Extras(OptionallyRequired):
dirs.sort()
for filename in sorted(filenames):
fullpath = os.path.join(dirpath, filename)
+
+ # Some editors (namely Emacs) will create temporary symlinks
+ # for internal magic. We can just ignore these files.
+ if os.path.islink(fullpath):
+ if not os.path.exists(os.readlink(fullpath)):
+ continue
+
relpath = os.path.normpath(os.path.relpath(fullpath, docs_dir))
if self.file_match(relpath):
yield relpath
| Ignore broken symlinks in mkdocs serve.
What I am experiencing:
* When I am editing `index.md` in Emacs, Emacs creates files like:
```
➜ docs git:(master) ✗ ls -al .#*
lrwxrwxrwx 1 paulproteus paulproteus 36 Jun 17 17:24 .#index.md -> [email protected]:1434311808
```
* These files are Emacs' way of using symlinks to track which computer+process was Emacs-ing the file, so that in case of a crash, Emacs can figure out how to restore its state.
What I expect:
* When I edit `somethingelse.md` and press save, I expect the mkdocs livereload to reload the browser.
What I see instead:
```
INFO - Building documentation...
ERROR - file not found: /home/paulproteus/projects/sandstorm/docs/.#index.md
ERROR - Error building page .#index.md
[E 150617 17:22:21 ioloop:612] Exception in callback (3, <function null_wrapper at 0x7fc883190500>)
Traceback (most recent call last):
File "/home/paulproteus/.local/lib/python2.7/site-packages/tornado/ioloop.py", line 866, in start
handler_func(fd_obj, events)
File "/home/paulproteus/.local/lib/python2.7/site-packages/tornado/stack_context.py", line 275, in null_wrapper
return fn(*args, **kwargs)
File "/usr/lib/python2.7/dist-packages/pyinotify.py", line 1604, in handle_read
self.process_events()
File "/usr/lib/python2.7/dist-packages/pyinotify.py", line 1321, in process_events
self._default_proc_fun(revent)
File "/home/paulproteus/.local/lib/python2.7/site-packages/livereload/watcher.py", line 152, in inotify_event
self.callback()
File "/home/paulproteus/.local/lib/python2.7/site-packages/livereload/handlers.py", line 65, in poll_tasks
filepath, delay = cls.watcher.examine()
File "/home/paulproteus/.local/lib/python2.7/site-packages/livereload/watcher.py", line 72, in examine
func and func()
File "/usr/lib/python2.7/dist-packages/mkdocs/serve.py", line 74, in builder
build(config, live_server=True)
File "/usr/lib/python2.7/dist-packages/mkdocs/build.py", line 299, in build
build_pages(config)
File "/usr/lib/python2.7/dist-packages/mkdocs/build.py", line 259, in build_pages
dump_json)
File "/usr/lib/python2.7/dist-packages/mkdocs/build.py", line 171, in _build_page
input_content = io.open(input_path, 'r', encoding='utf-8').read()
IOError: [Errno 2] No such file or directory: '/home/paulproteus/projects/sandstorm/docs/.#index.md'
```
What I propose:
* If a "No such file or directory" error occurs, but the problem is a broken symlink, the `mkdocs` build should continue as if the file does not exist. Note that this arguably is a special-case to handle Emacs' own weirdness; a different way to do it would be to look at the list of git ignored files.
* Perhaps in general, `mkdocs` should issue a warning (not an error) on broken symlinks, gracefully ignoring them.
I'm open to a bunch of ideas. I wanted to file this in the hopes of sparking a discussion where the maintainers of mkdocs could express their opinion about the best way forward.
Thanks so much! Also hi! I'm twitter.com/asheeshlaroia and was chatting with a mkdocs developer earlier today. Seems like a great project! I learned about it via http://ericholscher.com/blog/2014/feb/27/how-i-judge-documentation-quality/ ! | mkdocs/mkdocs | diff --git a/mkdocs/tests/config/config_options_tests.py b/mkdocs/tests/config/config_options_tests.py
index b1e7bff7..d16f675b 100644
--- a/mkdocs/tests/config/config_options_tests.py
+++ b/mkdocs/tests/config/config_options_tests.py
@@ -1,6 +1,7 @@
from __future__ import unicode_literals
import os
+import tempfile
import unittest
from mkdocs import utils
@@ -251,6 +252,25 @@ class ExtrasTest(unittest.TestCase):
self.assertRaises(config_options.ValidationError,
option.validate, {})
+ def test_talk(self):
+
+ option = config_options.Extras(utils.is_markdown_file)
+
+ tmp_dir = tempfile.mkdtemp()
+
+ f1 = os.path.join(tmp_dir, 'file1.md')
+ f2 = os.path.join(tmp_dir, 'file2.md')
+
+ open(f1, 'a').close()
+
+ # symlink isn't available on Python 2 on Windows.
+ if hasattr(os, 'symlink'):
+ os.symlink('/path/that/doesnt/exist', f2)
+
+ files = list(option.walk_docs_dir(tmp_dir))
+
+ self.assertEqual(['file1.md', ], files)
+
class PagesTest(unittest.TestCase):
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_hyperlinks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 1,
"issue_text_score": 1,
"test_score": 2
},
"num_modified_files": 1
} | 0.14 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.9",
"reqs_path": [
"requirements/project.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | click==8.1.8
exceptiongroup==1.2.2
ghp-import==2.1.0
importlib_metadata==8.6.1
iniconfig==2.1.0
Jinja2==3.1.6
livereload==2.7.1
Markdown==3.7
MarkupSafe==3.0.2
mergedeep==1.3.4
-e git+https://github.com/mkdocs/mkdocs.git@98814de505c9d8f1849292372eff1c5ae492261c#egg=mkdocs
mkdocs-bootstrap==0.2.0
mkdocs-bootswatch==0.5.0
mkdocs-get-deps==0.2.0
packaging==24.2
pathspec==0.12.1
platformdirs==4.3.7
pluggy==1.5.0
pytest==8.3.5
python-dateutil==2.9.0.post0
PyYAML==6.0.2
pyyaml_env_tag==0.1
six==1.17.0
tomli==2.2.1
tornado==6.4.2
watchdog==6.0.0
zipp==3.21.0
| name: mkdocs
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=3.0.16=h5eee18b_0
- pip=25.0=py39h06a4308_0
- python=3.9.21=he870216_1
- readline=8.2=h5eee18b_0
- setuptools=75.8.0=py39h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- tzdata=2025a=h04d1e81_0
- wheel=0.45.1=py39h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- click==8.1.8
- exceptiongroup==1.2.2
- ghp-import==2.1.0
- importlib-metadata==8.6.1
- iniconfig==2.1.0
- jinja2==3.1.6
- livereload==2.7.1
- markdown==3.7
- markupsafe==3.0.2
- mergedeep==1.3.4
- mkdocs-bootstrap==0.2.0
- mkdocs-bootswatch==0.5.0
- mkdocs-get-deps==0.2.0
- packaging==24.2
- pathspec==0.12.1
- platformdirs==4.3.7
- pluggy==1.5.0
- pytest==8.3.5
- python-dateutil==2.9.0.post0
- pyyaml==6.0.2
- pyyaml-env-tag==0.1
- six==1.17.0
- tomli==2.2.1
- tornado==6.4.2
- watchdog==6.0.0
- zipp==3.21.0
prefix: /opt/conda/envs/mkdocs
| [
"mkdocs/tests/config/config_options_tests.py::ExtrasTest::test_talk"
] | [] | [
"mkdocs/tests/config/config_options_tests.py::OptionallyRequiredTest::test_default",
"mkdocs/tests/config/config_options_tests.py::OptionallyRequiredTest::test_empty",
"mkdocs/tests/config/config_options_tests.py::OptionallyRequiredTest::test_replace_default",
"mkdocs/tests/config/config_options_tests.py::OptionallyRequiredTest::test_required",
"mkdocs/tests/config/config_options_tests.py::OptionallyRequiredTest::test_required_no_default",
"mkdocs/tests/config/config_options_tests.py::TypeTest::test_length",
"mkdocs/tests/config/config_options_tests.py::TypeTest::test_multiple_types",
"mkdocs/tests/config/config_options_tests.py::TypeTest::test_single_type",
"mkdocs/tests/config/config_options_tests.py::URLTest::test_invalid",
"mkdocs/tests/config/config_options_tests.py::URLTest::test_invalid_url",
"mkdocs/tests/config/config_options_tests.py::URLTest::test_valid_url",
"mkdocs/tests/config/config_options_tests.py::RepoURLTest::test_repo_name_bitbucket",
"mkdocs/tests/config/config_options_tests.py::RepoURLTest::test_repo_name_custom",
"mkdocs/tests/config/config_options_tests.py::RepoURLTest::test_repo_name_github",
"mkdocs/tests/config/config_options_tests.py::DirTest::test_file",
"mkdocs/tests/config/config_options_tests.py::DirTest::test_incorrect_type_attribute_error",
"mkdocs/tests/config/config_options_tests.py::DirTest::test_incorrect_type_type_error",
"mkdocs/tests/config/config_options_tests.py::DirTest::test_missing_dir",
"mkdocs/tests/config/config_options_tests.py::DirTest::test_missing_dir_but_required",
"mkdocs/tests/config/config_options_tests.py::DirTest::test_valid_dir",
"mkdocs/tests/config/config_options_tests.py::SiteDirTest::test_doc_dir_in_site_dir",
"mkdocs/tests/config/config_options_tests.py::SiteDirTest::test_site_dir_in_docs_dir",
"mkdocs/tests/config/config_options_tests.py::ThemeTest::test_theme",
"mkdocs/tests/config/config_options_tests.py::ThemeTest::test_theme_invalid",
"mkdocs/tests/config/config_options_tests.py::ExtrasTest::test_empty",
"mkdocs/tests/config/config_options_tests.py::ExtrasTest::test_invalid",
"mkdocs/tests/config/config_options_tests.py::ExtrasTest::test_provided",
"mkdocs/tests/config/config_options_tests.py::PagesTest::test_invalid_config",
"mkdocs/tests/config/config_options_tests.py::PagesTest::test_invalid_type",
"mkdocs/tests/config/config_options_tests.py::PagesTest::test_provided",
"mkdocs/tests/config/config_options_tests.py::PagesTest::test_provided_dict",
"mkdocs/tests/config/config_options_tests.py::PagesTest::test_provided_empty",
"mkdocs/tests/config/config_options_tests.py::NumPagesTest::test_invalid_pages",
"mkdocs/tests/config/config_options_tests.py::NumPagesTest::test_many_pages",
"mkdocs/tests/config/config_options_tests.py::NumPagesTest::test_one_page",
"mkdocs/tests/config/config_options_tests.py::NumPagesTest::test_provided",
"mkdocs/tests/config/config_options_tests.py::PrivateTest::test_defined",
"mkdocs/tests/config/config_options_tests.py::MarkdownExtensionsTest::test_builtins",
"mkdocs/tests/config/config_options_tests.py::MarkdownExtensionsTest::test_builtins_config",
"mkdocs/tests/config/config_options_tests.py::MarkdownExtensionsTest::test_configkey",
"mkdocs/tests/config/config_options_tests.py::MarkdownExtensionsTest::test_duplicates",
"mkdocs/tests/config/config_options_tests.py::MarkdownExtensionsTest::test_invalid_config_item",
"mkdocs/tests/config/config_options_tests.py::MarkdownExtensionsTest::test_invalid_config_option",
"mkdocs/tests/config/config_options_tests.py::MarkdownExtensionsTest::test_invalid_dict_item",
"mkdocs/tests/config/config_options_tests.py::MarkdownExtensionsTest::test_list_dicts",
"mkdocs/tests/config/config_options_tests.py::MarkdownExtensionsTest::test_mixed_list",
"mkdocs/tests/config/config_options_tests.py::MarkdownExtensionsTest::test_none",
"mkdocs/tests/config/config_options_tests.py::MarkdownExtensionsTest::test_not_list",
"mkdocs/tests/config/config_options_tests.py::MarkdownExtensionsTest::test_simple_list"
] | [] | BSD 2-Clause "Simplified" License | 176 |
google__yapf-164 | 22c52a696d787ac9e8a45ea70dc6e1cae9b398de | 2015-06-30 07:28:58 | 22c52a696d787ac9e8a45ea70dc6e1cae9b398de | diff --git a/yapf/yapflib/subtype_assigner.py b/yapf/yapflib/subtype_assigner.py
index f8c24cd..34391b3 100644
--- a/yapf/yapflib/subtype_assigner.py
+++ b/yapf/yapflib/subtype_assigner.py
@@ -73,7 +73,11 @@ class _SubtypeAssigner(pytree_visitor.PyTreeVisitor):
self._SetFirstLeafTokenSubtype(child,
format_token.Subtype.DICTIONARY_KEY)
elif last_was_colon:
- self._SetSubtypeRec(child, format_token.Subtype.DICTIONARY_VALUE)
+ if pytree_utils.NodeName(child) == 'power':
+ self._SetFirstLeafTokenSubtype(child,
+ format_token.Subtype.DICTIONARY_VALUE)
+ else:
+ self._SetSubtypeRec(child, format_token.Subtype.DICTIONARY_VALUE)
last_was_comma = isinstance(child, pytree.Leaf) and child.value == ','
last_was_colon = isinstance(child, pytree.Leaf) and child.value == ':'
self.Visit(child)
| Regression in formatting an argument expansion in a dictionary
`{a: b(*c)}` gets formatted to `{a: b( * c)}`
This regression occured in f30c1d26df3449950d95982f17568d03fe4a361f | google/yapf | diff --git a/yapftests/reformatter_test.py b/yapftests/reformatter_test.py
index bd88849..7e35c8b 100644
--- a/yapftests/reformatter_test.py
+++ b/yapftests/reformatter_test.py
@@ -1217,6 +1217,11 @@ format_token.Subtype.NONE))
uwlines = _ParseAndUnwrap(code)
self.assertCodeEqual(code, reformatter.Reformat(uwlines))
+ def testFunctionCallInDict(self):
+ code = "a = {'a': b(c=d, **e)}\n"
+ uwlines = _ParseAndUnwrap(code)
+ self.assertCodeEqual(code, reformatter.Reformat(uwlines))
+
class BuganizerFixes(ReformatterTest):
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_short_problem_statement",
"has_git_commit_hash"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 0,
"issue_text_score": 1,
"test_score": 2
},
"num_modified_files": 1
} | 0.2 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "pytest",
"pip_packages": [
"nose",
"pytest"
],
"pre_install": null,
"python": "3.9",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | exceptiongroup @ file:///croot/exceptiongroup_1706031385326/work
iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work
nose==1.3.7
packaging @ file:///croot/packaging_1734472117206/work
pluggy @ file:///croot/pluggy_1733169602837/work
pytest @ file:///croot/pytest_1738938843180/work
tomli @ file:///opt/conda/conda-bld/tomli_1657175507142/work
-e git+https://github.com/google/yapf.git@22c52a696d787ac9e8a45ea70dc6e1cae9b398de#egg=yapf
| name: yapf
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- exceptiongroup=1.2.0=py39h06a4308_0
- iniconfig=1.1.1=pyhd3eb1b0_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=3.0.16=h5eee18b_0
- packaging=24.2=py39h06a4308_0
- pip=25.0=py39h06a4308_0
- pluggy=1.5.0=py39h06a4308_0
- pytest=8.3.4=py39h06a4308_0
- python=3.9.21=he870216_1
- readline=8.2=h5eee18b_0
- setuptools=75.8.0=py39h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- tomli=2.0.1=py39h06a4308_0
- tzdata=2025a=h04d1e81_0
- wheel=0.45.1=py39h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- nose==1.3.7
prefix: /opt/conda/envs/yapf
| [
"yapftests/reformatter_test.py::BasicReformatterTest::testFunctionCallInDict"
] | [] | [
"yapftests/reformatter_test.py::BasicReformatterTest::testBlankLinesAtEndOfFile",
"yapftests/reformatter_test.py::BasicReformatterTest::testBlankLinesBeforeDecorators",
"yapftests/reformatter_test.py::BasicReformatterTest::testBlankLinesBeforeFunctionsNotInColumnZero",
"yapftests/reformatter_test.py::BasicReformatterTest::testClosingBracketIndent",
"yapftests/reformatter_test.py::BasicReformatterTest::testClosingBracketsInlinedInCall",
"yapftests/reformatter_test.py::BasicReformatterTest::testCommentBeforeFuncDef",
"yapftests/reformatter_test.py::BasicReformatterTest::testCommentBetweenDecorators",
"yapftests/reformatter_test.py::BasicReformatterTest::testComments",
"yapftests/reformatter_test.py::BasicReformatterTest::testCommentsWithContinuationMarkers",
"yapftests/reformatter_test.py::BasicReformatterTest::testContinuationIndent",
"yapftests/reformatter_test.py::BasicReformatterTest::testContinuationMarkers",
"yapftests/reformatter_test.py::BasicReformatterTest::testDictSetGenerator",
"yapftests/reformatter_test.py::BasicReformatterTest::testDictionaryMakerFormatting",
"yapftests/reformatter_test.py::BasicReformatterTest::testDocstringAndMultilineComment",
"yapftests/reformatter_test.py::BasicReformatterTest::testDocstrings",
"yapftests/reformatter_test.py::BasicReformatterTest::testEmptyContainers",
"yapftests/reformatter_test.py::BasicReformatterTest::testEndingWhitespaceAfterSimpleStatement",
"yapftests/reformatter_test.py::BasicReformatterTest::testExcessCharacters",
"yapftests/reformatter_test.py::BasicReformatterTest::testExcessLineCountWithDefaultKeywords",
"yapftests/reformatter_test.py::BasicReformatterTest::testExpressionPenalties",
"yapftests/reformatter_test.py::BasicReformatterTest::testFunctionCallContinuationLine",
"yapftests/reformatter_test.py::BasicReformatterTest::testI18n",
"yapftests/reformatter_test.py::BasicReformatterTest::testI18nNonFormatting",
"yapftests/reformatter_test.py::BasicReformatterTest::testIfConditionalParens",
"yapftests/reformatter_test.py::BasicReformatterTest::testLineDepthOfSingleLineStatement",
"yapftests/reformatter_test.py::BasicReformatterTest::testLineWrapInForExpression",
"yapftests/reformatter_test.py::BasicReformatterTest::testListComprehension",
"yapftests/reformatter_test.py::BasicReformatterTest::testMatchingParenSplittingMatching",
"yapftests/reformatter_test.py::BasicReformatterTest::testMultilineComment",
"yapftests/reformatter_test.py::BasicReformatterTest::testMultilineCommentReformatted",
"yapftests/reformatter_test.py::BasicReformatterTest::testMultilineDocstringAndMultilineComment",
"yapftests/reformatter_test.py::BasicReformatterTest::testMultilineShebang",
"yapftests/reformatter_test.py::BasicReformatterTest::testMultilineString",
"yapftests/reformatter_test.py::BasicReformatterTest::testMultipleUgliness",
"yapftests/reformatter_test.py::BasicReformatterTest::testNoBreakOutsideOfBracket",
"yapftests/reformatter_test.py::BasicReformatterTest::testNoKeywordArgumentBreakage",
"yapftests/reformatter_test.py::BasicReformatterTest::testNoPenaltySplitting",
"yapftests/reformatter_test.py::BasicReformatterTest::testNoQueueSeletionInMiddleOfLine",
"yapftests/reformatter_test.py::BasicReformatterTest::testNoSpaceBetweenUnaryOpAndOpeningParen",
"yapftests/reformatter_test.py::BasicReformatterTest::testNoSpacesBetweenOpeningBracketAndStartingOperator",
"yapftests/reformatter_test.py::BasicReformatterTest::testNoSpacesBetweenSubscriptsAndCalls",
"yapftests/reformatter_test.py::BasicReformatterTest::testNoSplittingAroundTermOperators",
"yapftests/reformatter_test.py::BasicReformatterTest::testNoSplittingWithinSubscriptList",
"yapftests/reformatter_test.py::BasicReformatterTest::testOpeningAndClosingBrackets",
"yapftests/reformatter_test.py::BasicReformatterTest::testRelativeImportStatements",
"yapftests/reformatter_test.py::BasicReformatterTest::testRelaxArraySubscriptAffinity",
"yapftests/reformatter_test.py::BasicReformatterTest::testSimple",
"yapftests/reformatter_test.py::BasicReformatterTest::testSimpleFunctions",
"yapftests/reformatter_test.py::BasicReformatterTest::testSimpleFunctionsWithTrailingComments",
"yapftests/reformatter_test.py::BasicReformatterTest::testSimpleMultilineCode",
"yapftests/reformatter_test.py::BasicReformatterTest::testSimpleMultilineWithComments",
"yapftests/reformatter_test.py::BasicReformatterTest::testSingleComment",
"yapftests/reformatter_test.py::BasicReformatterTest::testSingleLineFunctions",
"yapftests/reformatter_test.py::BasicReformatterTest::testSingleLineIfStatements",
"yapftests/reformatter_test.py::BasicReformatterTest::testSingleLineList",
"yapftests/reformatter_test.py::BasicReformatterTest::testSpaceAfterNotOperator",
"yapftests/reformatter_test.py::BasicReformatterTest::testSplitListWithInterspersedComments",
"yapftests/reformatter_test.py::BasicReformatterTest::testSplitListWithTerminatingComma",
"yapftests/reformatter_test.py::BasicReformatterTest::testSplitStringsIfSurroundedByParens",
"yapftests/reformatter_test.py::BasicReformatterTest::testTrailerOnSingleLine",
"yapftests/reformatter_test.py::BasicReformatterTest::testTrailingCommaAndBracket",
"yapftests/reformatter_test.py::BasicReformatterTest::testTupleCommaBeforeLastParen",
"yapftests/reformatter_test.py::BasicReformatterTest::testUnaryNotOperator",
"yapftests/reformatter_test.py::BasicReformatterTest::testUnaryOpInDictionaryValue",
"yapftests/reformatter_test.py::BuganizerFixes::testB13900309",
"yapftests/reformatter_test.py::BuganizerFixes::testB14406499",
"yapftests/reformatter_test.py::BuganizerFixes::testB14468247",
"yapftests/reformatter_test.py::BuganizerFixes::testB15438132",
"yapftests/reformatter_test.py::BuganizerFixes::testB15542157",
"yapftests/reformatter_test.py::BuganizerFixes::testB15597568",
"yapftests/reformatter_test.py::BuganizerFixes::testB15697268",
"yapftests/reformatter_test.py::BuganizerFixes::testB15884241",
"yapftests/reformatter_test.py::BuganizerFixes::testB16572361",
"yapftests/reformatter_test.py::BuganizerFixes::testB16783631",
"yapftests/reformatter_test.py::BuganizerFixes::testB17011869",
"yapftests/reformatter_test.py::BuganizerFixes::testB17133019",
"yapftests/reformatter_test.py::BuganizerFixes::testB17489866",
"yapftests/reformatter_test.py::BuganizerFixes::testB17534869",
"yapftests/reformatter_test.py::BuganizerFixes::testB18255697",
"yapftests/reformatter_test.py::BuganizerFixes::testB18256666",
"yapftests/reformatter_test.py::BuganizerFixes::testB18256826",
"yapftests/reformatter_test.py::BuganizerFixes::testB18257115",
"yapftests/reformatter_test.py::BuganizerFixes::testB19073499",
"yapftests/reformatter_test.py::BuganizerFixes::testB19194420",
"yapftests/reformatter_test.py::BuganizerFixes::testB19287512",
"yapftests/reformatter_test.py::BuganizerFixes::testB19353268",
"yapftests/reformatter_test.py::BuganizerFixes::testB19372573",
"yapftests/reformatter_test.py::BuganizerFixes::testB19377034",
"yapftests/reformatter_test.py::BuganizerFixes::testB19547210",
"yapftests/reformatter_test.py::BuganizerFixes::testB19626808",
"yapftests/reformatter_test.py::BuganizerFixes::testB20073838",
"yapftests/reformatter_test.py::BuganizerFixes::testB20128830",
"yapftests/reformatter_test.py::BuganizerFixes::testB20562732",
"yapftests/reformatter_test.py::BuganizerFixes::testB20605036",
"yapftests/reformatter_test.py::BuganizerFixes::testB20813997",
"yapftests/reformatter_test.py::TestsForPEP8Style::testAlignClosingBracketWithVisualIndentation",
"yapftests/reformatter_test.py::TestsForPEP8Style::testContinuedNonOudentedLine",
"yapftests/reformatter_test.py::TestsForPEP8Style::testIndent4",
"yapftests/reformatter_test.py::TestsForPEP8Style::testNoBlankBetweenClassAndDef",
"yapftests/reformatter_test.py::TestsForPEP8Style::testSingleWhiteBeforeTrailingComment",
"yapftests/reformatter_test.py::TestsForPEP8Style::testSpaceBetweenEndingCommandAndClosingBracket",
"yapftests/reformatter_test.py::TestsForPEP8Style::testSplittingSemicolonStatements",
"yapftests/reformatter_test.py::TestsForPEP8Style::testWrappingPercentExpressions",
"yapftests/reformatter_test.py::TestingNotInParameters::test_notInParams",
"yapftests/reformatter_test.py::TestsForPython3Code::testAnnotations",
"yapftests/reformatter_test.py::TestsForPython3Code::testExecAsNonKeyword",
"yapftests/reformatter_test.py::TestsForPython3Code::testKeywordOnlyArgSpecifier"
] | [] | Apache License 2.0 | 177 |
|
kevin1024__vcrpy-162 | d14888ccd87ea82ed4252958393a45eb05aea866 | 2015-07-01 08:51:50 | 7d175b0f91c0048eb0de258be8576b84b7a21f52 | IvanMalison: installs are failing with
error in vcrpy setup command: Invalid environment marker: python_version<=2.4
IvanMalison: pkg_resources.DistributionNotFound: contextlib2
graingert: I've arsed this up pretty bad. But I know how to fix this. Please bare with me 😻
IvanMalison: Hah no worries. Thanks for the pr. This issue was annoying me.
IvanMalison: closes #147 | diff --git a/.travis.yml b/.travis.yml
index 594b492..93fea8b 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -33,7 +33,7 @@ python:
- 3.4
- pypy
install:
-- pip install PyYAML pytest pytest-localserver --use-mirrors
+- pip install .
- if [ $WITH_LIB = "requests1.x" ] ; then pip install requests==1.2.3; fi
- if [ $WITH_LIB = "requests2.2" ] ; then pip install requests==2.2.1; fi
- if [ $WITH_LIB = "requests2.3" ] ; then pip install requests==2.3.0; fi
diff --git a/setup.py b/setup.py
index 1c6ec59..aeeb415 100644
--- a/setup.py
+++ b/setup.py
@@ -19,6 +19,7 @@ class PyTest(TestCommand):
errno = pytest.main(self.test_args)
sys.exit(errno)
+
setup(
name='vcrpy',
version='1.5.2',
@@ -31,8 +32,12 @@ setup(
author_email='[email protected]',
url='https://github.com/kevin1024/vcrpy',
packages=find_packages(exclude=("tests*",)),
- install_requires=['PyYAML', 'mock', 'six>=1.5', 'contextlib2',
- 'wrapt', 'backport_collections'],
+ install_requires=['PyYAML', 'wrapt', 'six>=1.5'],
+ extras_require = {
+ ':python_version in "2.4, 2.5, 2.6"':
+ ['contextlib2', 'backport_collections', 'mock'],
+ ':python_version in "2.7, 3.1, 3.2"': ['contextlib2', 'mock'],
+ },
license='MIT',
tests_require=['pytest', 'mock', 'pytest-localserver'],
cmdclass={'test': PyTest},
diff --git a/vcr/cassette.py b/vcr/cassette.py
index 77b5395..87d2598 100644
--- a/vcr/cassette.py
+++ b/vcr/cassette.py
@@ -2,14 +2,11 @@
import functools
import logging
-import contextlib2
+
import wrapt
-try:
- from collections import Counter
-except ImportError:
- from backport_collections import Counter
# Internal imports
+from .compat import contextlib, collections
from .errors import UnhandledHTTPRequestError
from .matchers import requests_match, uri, method
from .patch import CassettePatcherBuilder
@@ -43,7 +40,7 @@ class CassetteContextDecorator(object):
self.__finish = None
def _patch_generator(self, cassette):
- with contextlib2.ExitStack() as exit_stack:
+ with contextlib.ExitStack() as exit_stack:
for patcher in CassettePatcherBuilder(cassette).build():
exit_stack.enter_context(patcher)
log.debug('Entered context for cassette at {0}.'.format(cassette._path))
@@ -148,7 +145,7 @@ class Cassette(object):
# self.data is the list of (req, resp) tuples
self.data = []
- self.play_counts = Counter()
+ self.play_counts = collections.Counter()
self.dirty = False
self.rewound = False
diff --git a/vcr/compat.py b/vcr/compat.py
new file mode 100644
index 0000000..e76c68f
--- /dev/null
+++ b/vcr/compat.py
@@ -0,0 +1,18 @@
+try:
+ from unittest import mock
+except ImportError:
+ import mock
+
+try:
+ import contextlib
+except ImportError:
+ import contextlib2 as contextlib
+else:
+ if not hasattr(contextlib, 'ExitStack'):
+ import contextlib2 as contextlib
+
+import collections
+if not hasattr(collections, 'Counter'):
+ import backport_collections as collections
+
+__all__ = ['mock', 'contextlib', 'collections']
diff --git a/vcr/config.py b/vcr/config.py
index fb03136..1faef3b 100644
--- a/vcr/config.py
+++ b/vcr/config.py
@@ -1,4 +1,3 @@
-import collections
import copy
import functools
import inspect
@@ -6,6 +5,7 @@ import os
import six
+from .compat import collections
from .cassette import Cassette
from .serializers import yamlserializer, jsonserializer
from .util import compose
diff --git a/vcr/filters.py b/vcr/filters.py
index 84f06c8..14159d0 100644
--- a/vcr/filters.py
+++ b/vcr/filters.py
@@ -1,12 +1,10 @@
from six import BytesIO, text_type
from six.moves.urllib.parse import urlparse, urlencode, urlunparse
-try:
- from collections import OrderedDict
-except ImportError:
- from backport_collections import OrderedDict
import copy
import json
+from .compat import collections
+
def remove_headers(request, headers_to_remove):
headers = copy.copy(request.headers)
@@ -40,7 +38,7 @@ def remove_post_data_parameters(request, post_data_parameters_to_remove):
del json_data[k]
request.body = json.dumps(json_data).encode('utf-8')
else:
- post_data = OrderedDict()
+ post_data = collections.OrderedDict()
if isinstance(request.body, text_type):
request.body = request.body.encode('utf-8')
diff --git a/vcr/patch.py b/vcr/patch.py
index 1d9edb5..caed9fa 100644
--- a/vcr/patch.py
+++ b/vcr/patch.py
@@ -2,9 +2,7 @@
import functools
import itertools
-import contextlib2
-import mock
-
+from .compat import contextlib, mock
from .stubs import VCRHTTPConnection, VCRHTTPSConnection
from six.moves import http_client as httplib
@@ -323,9 +321,9 @@ def reset_patchers():
_CertValidatingHTTPSConnection)
[email protected]
[email protected]
def force_reset():
- with contextlib2.ExitStack() as exit_stack:
+ with contextlib.ExitStack() as exit_stack:
for patcher in reset_patchers():
exit_stack.enter_context(patcher)
yield
| Dependency that is only compatible/needed with/in python 2 in setup.py
this causes pip install to fail (at least with my py3.4 system) | kevin1024/vcrpy | diff --git a/tests/unit/test_cassettes.py b/tests/unit/test_cassettes.py
index 947ffa4..e7d8b7c 100644
--- a/tests/unit/test_cassettes.py
+++ b/tests/unit/test_cassettes.py
@@ -3,11 +3,10 @@ import inspect
import os
from six.moves import http_client as httplib
-import contextlib2
-import mock
import pytest
import yaml
+from vcr.compat import mock, contextlib
from vcr.cassette import Cassette
from vcr.errors import UnhandledHTTPRequestError
from vcr.patch import force_reset
@@ -158,7 +157,7 @@ def test_nesting_cassette_context_managers(*args):
second_response = copy.deepcopy(first_response)
second_response['body']['string'] = b'second_response'
- with contextlib2.ExitStack() as exit_stack:
+ with contextlib.ExitStack() as exit_stack:
first_cassette = exit_stack.enter_context(Cassette.use(path='test'))
exit_stack.enter_context(mock.patch.object(first_cassette, 'play_response',
return_value=first_response))
diff --git a/tests/unit/test_serialize.py b/tests/unit/test_serialize.py
index 5f2a9aa..41d97bd 100644
--- a/tests/unit/test_serialize.py
+++ b/tests/unit/test_serialize.py
@@ -1,6 +1,6 @@
-import mock
import pytest
+from vcr.compat import mock
from vcr.serialize import deserialize
from vcr.serializers import yamlserializer, jsonserializer
diff --git a/tests/unit/test_vcr.py b/tests/unit/test_vcr.py
index d58d96c..8b1de97 100644
--- a/tests/unit/test_vcr.py
+++ b/tests/unit/test_vcr.py
@@ -1,9 +1,9 @@
import os
-import mock
import pytest
from vcr import VCR, use_cassette
+from vcr.compat import mock
from vcr.request import Request
from vcr.stubs import VCRHTTPSConnection
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_short_problem_statement",
"has_added_files",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 1,
"issue_text_score": 2,
"test_score": 1
},
"num_modified_files": 6
} | 1.5 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest",
"pytest-localserver",
"mock"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.9",
"reqs_path": [
"requirements/base.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | backport_collections==0.1
contextlib2==21.6.0
exceptiongroup==1.2.2
iniconfig==2.1.0
MarkupSafe==3.0.2
mock==5.2.0
packaging==24.2
pluggy==1.5.0
pytest==8.3.5
pytest-localserver==0.9.0.post0
PyYAML==6.0.2
six==1.17.0
tomli==2.2.1
-e git+https://github.com/kevin1024/vcrpy.git@d14888ccd87ea82ed4252958393a45eb05aea866#egg=vcrpy
Werkzeug==3.1.3
wrapt==1.17.2
| name: vcrpy
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=3.0.16=h5eee18b_0
- pip=25.0=py39h06a4308_0
- python=3.9.21=he870216_1
- readline=8.2=h5eee18b_0
- setuptools=75.8.0=py39h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- tzdata=2025a=h04d1e81_0
- wheel=0.45.1=py39h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- backport-collections==0.1
- contextlib2==21.6.0
- exceptiongroup==1.2.2
- iniconfig==2.1.0
- markupsafe==3.0.2
- mock==5.2.0
- packaging==24.2
- pluggy==1.5.0
- pytest==8.3.5
- pytest-localserver==0.9.0.post0
- pyyaml==6.0.2
- six==1.17.0
- tomli==2.2.1
- werkzeug==3.1.3
- wrapt==1.17.2
prefix: /opt/conda/envs/vcrpy
| [
"tests/unit/test_cassettes.py::test_cassette_load",
"tests/unit/test_cassettes.py::test_cassette_not_played",
"tests/unit/test_cassettes.py::test_cassette_append",
"tests/unit/test_cassettes.py::test_cassette_len",
"tests/unit/test_cassettes.py::test_cassette_contains",
"tests/unit/test_cassettes.py::test_cassette_responses_of",
"tests/unit/test_cassettes.py::test_cassette_get_missing_response",
"tests/unit/test_cassettes.py::test_cassette_cant_read_same_request_twice",
"tests/unit/test_cassettes.py::test_function_decorated_with_use_cassette_can_be_invoked_multiple_times",
"tests/unit/test_cassettes.py::test_arg_getter_functionality",
"tests/unit/test_cassettes.py::test_cassette_not_all_played",
"tests/unit/test_cassettes.py::test_cassette_all_played",
"tests/unit/test_cassettes.py::test_before_record_response",
"tests/unit/test_cassettes.py::test_nesting_cassette_context_managers",
"tests/unit/test_cassettes.py::test_nesting_context_managers_by_checking_references_of_http_connection",
"tests/unit/test_cassettes.py::test_custom_patchers",
"tests/unit/test_cassettes.py::test_decorated_functions_are_reentrant",
"tests/unit/test_cassettes.py::test_cassette_use_called_without_path_uses_function_to_generate_path",
"tests/unit/test_cassettes.py::test_path_transformer_with_function_path",
"tests/unit/test_cassettes.py::test_path_transformer_with_context_manager",
"tests/unit/test_cassettes.py::test_func_path_generator",
"tests/unit/test_serialize.py::test_deserialize_old_yaml_cassette",
"tests/unit/test_serialize.py::test_deserialize_old_json_cassette",
"tests/unit/test_serialize.py::test_deserialize_new_yaml_cassette",
"tests/unit/test_serialize.py::test_deserialize_new_json_cassette",
"tests/unit/test_serialize.py::test_serialize_constructs_UnicodeDecodeError",
"tests/unit/test_vcr.py::test_vcr_use_cassette",
"tests/unit/test_vcr.py::test_vcr_before_record_request_params",
"tests/unit/test_vcr.py::test_fixtures_with_use_cassette",
"tests/unit/test_vcr.py::test_custom_patchers",
"tests/unit/test_vcr.py::test_inject_cassette",
"tests/unit/test_vcr.py::test_with_current_defaults",
"tests/unit/test_vcr.py::test_cassette_library_dir_with_decoration_and_no_explicit_path",
"tests/unit/test_vcr.py::test_cassette_library_dir_with_decoration_and_explicit_path",
"tests/unit/test_vcr.py::test_cassette_library_dir_with_decoration_and_super_explicit_path",
"tests/unit/test_vcr.py::test_cassette_library_dir_with_path_transformer",
"tests/unit/test_vcr.py::test_use_cassette_with_no_extra_invocation",
"tests/unit/test_vcr.py::test_path_transformer",
"tests/unit/test_vcr.py::test_cassette_name_generator_defaults_to_using_module_function_defined_in",
"tests/unit/test_vcr.py::test_ensure_suffix"
] | [] | [] | [] | MIT License | 178 |
sympy__sympy-9599 | 4ea7874a193339cbb879297bfcb357ac73bce9e2 | 2015-07-01 15:26:56 | 0241b35cae5f2adc04dc37b25f7dc9c5f00bd746 | leosartaj: Ping @moorepants @jcrist
moorepants: Looks good here, thanks. Please address my two comments.
moorepants: +1 once tests pass.
leosartaj: There were failures, in codegen probably due to ``free_symbols`` attribute I added in ``Indexed``. This was added to allow evaluation of ``Sum``.
Something like this happened without ``free_symbols``
```
>>> i = symbols('i', cls=Idx)
>>> r = Indexed('r', i)
>>> Sum(r, (i, 1, 3)).doit()
3*r[i]
```
This was probably due to [L-547](https://github.com/leosartaj/sympy/blob/idx/sympy/concrete/summations.py#L547) in summations.py
> if i not in f.free_symbols:
Here ``i ``is an instance of ``Idx`` while ``free_symbols`` contains ``i`` but that is an instance of ``Symbol``. This is due to ``Idx`` internally storing it is an integral Symbol.
So to overcome this, I used the internal integral ``Symbol`` to evaluate ``Sum``.
Please have a look @moorepants.
leosartaj: Ping @moorepants @jcrist | diff --git a/sympy/concrete/expr_with_limits.py b/sympy/concrete/expr_with_limits.py
index ef84e11193..34b8a2aeb1 100644
--- a/sympy/concrete/expr_with_limits.py
+++ b/sympy/concrete/expr_with_limits.py
@@ -14,6 +14,7 @@
from sympy.utilities import flatten
from sympy.utilities.iterables import sift
from sympy.matrices import Matrix
+from sympy.tensor.indexed import Idx
def _process_limits(*symbols):
@@ -25,12 +26,12 @@ def _process_limits(*symbols):
limits = []
orientation = 1
for V in symbols:
- if isinstance(V, Symbol):
+ if isinstance(V, (Symbol, Idx)):
limits.append(Tuple(V))
continue
elif is_sequence(V, Tuple):
V = sympify(flatten(V))
- if V[0].is_Symbol:
+ if isinstance(V[0], (Symbol, Idx)):
newsymbol = V[0]
if len(V) == 2 and isinstance(V[1], Interval):
V[1:] = [V[1].start, V[1].end]
diff --git a/sympy/concrete/summations.py b/sympy/concrete/summations.py
index 3513950223..c2a8f5bb84 100644
--- a/sympy/concrete/summations.py
+++ b/sympy/concrete/summations.py
@@ -11,6 +11,7 @@
from sympy.polys import apart, PolynomialError
from sympy.solvers import solve
from sympy.core.compatibility import range
+from sympy.tensor.indexed import Idx
class Sum(AddWithLimits, ExprWithIntLimits):
@@ -176,6 +177,8 @@ def doit(self, **hints):
if dif.is_integer and (dif < 0) == True:
a, b = b + 1, a - 1
f = -f
+ if isinstance(i, Idx):
+ i = i.label
newf = eval_sum(f, (i, a, b))
if newf is None:
diff --git a/sympy/series/sequences.py b/sympy/series/sequences.py
index 52ff93d804..82ddcc6f63 100644
--- a/sympy/series/sequences.py
+++ b/sympy/series/sequences.py
@@ -14,6 +14,7 @@
from sympy.polys import lcm
from sympy.sets.sets import Interval, Intersection
from sympy.utilities.iterables import flatten
+from sympy.tensor.indexed import Idx
###############################################################################
@@ -92,11 +93,8 @@ def free_symbols(self):
>>> SeqFormula(m*n**2, (n, 0, 5)).free_symbols
set([m])
"""
- fsyms = set().union(*[a.free_symbols for a in self.args])
- for d in self.variables:
- if d in fsyms:
- fsyms.remove(d)
- return fsyms
+ return (set(j for i in self.args for j in i.free_symbols
+ .difference(self.variables)))
@cacheit
def coeff(self, pt):
@@ -452,7 +450,7 @@ def _find_x(periodical):
x = _find_x(periodical)
start, stop = limits
- if not isinstance(x, Symbol) or start is None or stop is None:
+ if not isinstance(x, (Symbol, Idx)) or start is None or stop is None:
raise ValueError('Invalid limits given: %s' % str(limits))
if start is S.NegativeInfinity and stop is S.Infinity:
@@ -594,7 +592,7 @@ def _find_x(formula):
x = _find_x(formula)
start, stop = limits
- if not isinstance(x, Symbol) or start is None or stop is None:
+ if not isinstance(x, (Symbol, Idx)) or start is None or stop is None:
raise ValueError('Invalid limits given: %s' % str(limits))
if start is S.NegativeInfinity and stop is S.Infinity:
diff --git a/sympy/tensor/indexed.py b/sympy/tensor/indexed.py
index fad892a2ab..477b654dad 100644
--- a/sympy/tensor/indexed.py
+++ b/sympy/tensor/indexed.py
@@ -134,7 +134,7 @@ class Indexed(Expr):
"""
is_commutative = True
- def __new__(cls, base, *args, **kw_args):
+ def __new__(cls, base, *args):
from sympy.utilities.misc import filldedent
if not args:
@@ -145,7 +145,7 @@ def __new__(cls, base, *args, **kw_args):
raise TypeError(filldedent("""
Indexed expects string, Symbol or IndexedBase as base."""))
args = list(map(sympify, args))
- return Expr.__new__(cls, base, *args, **kw_args)
+ return Expr.__new__(cls, base, *args)
@property
def base(self):
| Idx instances can't be used as limits in a Sum
```
In [15]: import sympy as sm
In [16]: i = sm.symbols('i', cls=sm.Idx)
In [17]: sm.Sum(sm.Indexed('r', i), (i, 1, 3))
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-17-76d0a23c5a34> in <module>()
----> 1 sm.Sum(sm.Indexed('r', i), (i, 1, 3))
/home/moorepants/anaconda/lib/python2.7/site-packages/sympy/concrete/summations.pyc in __new__(cls, function, *symbols, **assumptions)
138
139 def __new__(cls, function, *symbols, **assumptions):
--> 140 obj = AddWithLimits.__new__(cls, function, *symbols, **assumptions)
141 if not hasattr(obj, 'limits'):
142 return obj
/home/moorepants/anaconda/lib/python2.7/site-packages/sympy/concrete/expr_with_limits.pyc in __new__(cls, function, *symbols, **assumptions)
351
352 if symbols:
--> 353 limits, orientation = _process_limits(*symbols)
354 else:
355 # symbol not provided -- we can still try to compute a general form
/home/moorepants/anaconda/lib/python2.7/site-packages/sympy/concrete/expr_with_limits.pyc in _process_limits(*symbols)
55 continue
56
---> 57 raise ValueError('Invalid limits given: %s' % str(symbols))
58
59 return limits, orientation
ValueError: Invalid limits given: ((i, 1, 3),)
In [18]: i = sm.symbols('i', integer=True)
In [19]: sm.Sum(sm.Indexed('r', i), (i, 1, 3))
Out[19]: Sum(r[i], (i, 1, 3))
``` | sympy/sympy | diff --git a/sympy/concrete/tests/test_sums_products.py b/sympy/concrete/tests/test_sums_products.py
index 4b0c7ba891..55eecda7b1 100644
--- a/sympy/concrete/tests/test_sums_products.py
+++ b/sympy/concrete/tests/test_sums_products.py
@@ -2,8 +2,8 @@
Abs, And, binomial, Catalan, cos, Derivative, E, Eq, exp, EulerGamma,
factorial, Function, harmonic, I, Integral, KroneckerDelta, log,
nan, Ne, Or, oo, pi, Piecewise, Product, product, Rational, S, simplify,
- sqrt, Sum, summation, Symbol, symbols, sympify, zeta, gamma, Le
-)
+ sqrt, Sum, summation, Symbol, symbols, sympify, zeta, gamma, Le, Indexed,
+ Idx)
from sympy.abc import a, b, c, d, f, k, m, x, y, z
from sympy.concrete.summations import telescopic
from sympy.utilities.pytest import XFAIL, raises
@@ -831,3 +831,9 @@ def test_issue_4668():
def test_matrix_sum():
A = Matrix([[0,1],[n,0]])
assert Sum(A,(n,0,3)).doit() == Matrix([[0, 4], [6, 0]])
+
+
+def test_issue_9594():
+ i = symbols('i', cls=Idx)
+ r = Indexed('r', i)
+ Sum(r, (i, 0, 3)).doit() == [r.subs(i, j) for j in range(4)]
diff --git a/sympy/series/tests/test_sequences.py b/sympy/series/tests/test_sequences.py
index be6bdbb014..2c42ccc9c5 100644
--- a/sympy/series/tests/test_sequences.py
+++ b/sympy/series/tests/test_sequences.py
@@ -1,5 +1,5 @@
from sympy import (S, Tuple, symbols, Interval, EmptySequence, oo, SeqPer,
- SeqFormula, sequence, SeqAdd, SeqMul)
+ SeqFormula, sequence, SeqAdd, SeqMul, Indexed, Idx)
from sympy.series.sequences import SeqExpr, SeqExprOp
from sympy.utilities.pytest import raises
@@ -246,3 +246,11 @@ def test_operations():
assert form.coeff_mul(m) == SeqFormula(m*n**2, (n, 0, oo))
assert per.coeff_mul(m) == SeqPer((m, 2*m), (n, 0, oo))
+
+
+def test_Idx_limits():
+ i = symbols('i', cls=Idx)
+ r = Indexed('r', i)
+
+ assert SeqFormula(r, (i, 0, 5))[:] == [r.subs(i, j) for j in range(6)]
+ assert SeqPer((1, 2), (i, 0, 5))[:] == [1, 2, 1, 2, 1, 2]
diff --git a/sympy/tensor/tests/test_indexed.py b/sympy/tensor/tests/test_indexed.py
index 370bd501bd..aac1bb5370 100644
--- a/sympy/tensor/tests/test_indexed.py
+++ b/sympy/tensor/tests/test_indexed.py
@@ -177,6 +177,7 @@ def test_complex_indices():
assert A.rank == 2
assert A.indices == (i, i + j)
+
def test_not_interable():
i, j = symbols('i j', integer=True)
A = Indexed('A', i, i + j)
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 2,
"issue_text_score": 1,
"test_score": 1
},
"num_modified_files": 4
} | 0.7 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "pytest",
"pip_packages": [
"mpmath>=0.19",
"pytest"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.4",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | attrs @ file:///opt/conda/conda-bld/attrs_1642510447205/work
certifi==2021.5.30
importlib-metadata @ file:///tmp/build/80754af9/importlib-metadata_1631916693255/work
iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work
more-itertools @ file:///tmp/build/80754af9/more-itertools_1637733554872/work
mpmath==1.3.0
packaging @ file:///tmp/build/80754af9/packaging_1637314298585/work
pluggy @ file:///tmp/build/80754af9/pluggy_1615976315926/work
py @ file:///opt/conda/conda-bld/py_1644396412707/work
pyparsing @ file:///tmp/build/80754af9/pyparsing_1635766073266/work
pytest==6.2.4
-e git+https://github.com/sympy/sympy.git@4ea7874a193339cbb879297bfcb357ac73bce9e2#egg=sympy
toml @ file:///tmp/build/80754af9/toml_1616166611790/work
typing_extensions @ file:///opt/conda/conda-bld/typing_extensions_1647553014482/work
zipp @ file:///tmp/build/80754af9/zipp_1633618647012/work
| name: sympy
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- attrs=21.4.0=pyhd3eb1b0_0
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- importlib-metadata=4.8.1=py36h06a4308_0
- importlib_metadata=4.8.1=hd3eb1b0_0
- iniconfig=1.1.1=pyhd3eb1b0_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- more-itertools=8.12.0=pyhd3eb1b0_0
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- packaging=21.3=pyhd3eb1b0_0
- pip=21.2.2=py36h06a4308_0
- pluggy=0.13.1=py36h06a4308_0
- py=1.11.0=pyhd3eb1b0_0
- pyparsing=3.0.4=pyhd3eb1b0_0
- pytest=6.2.4=py36h06a4308_2
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_0
- setuptools=58.0.4=py36h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- toml=0.10.2=pyhd3eb1b0_0
- typing_extensions=4.1.1=pyh06a4308_0
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- zipp=3.6.0=pyhd3eb1b0_0
- zlib=1.2.13=h5eee18b_1
- pip:
- mpmath==1.3.0
prefix: /opt/conda/envs/sympy
| [
"sympy/concrete/tests/test_sums_products.py::test_issue_9594",
"sympy/series/tests/test_sequences.py::test_Idx_limits"
] | [] | [
"sympy/concrete/tests/test_sums_products.py::test_karr_convention",
"sympy/concrete/tests/test_sums_products.py::test_karr_proposition_2a",
"sympy/concrete/tests/test_sums_products.py::test_karr_proposition_2b",
"sympy/concrete/tests/test_sums_products.py::test_arithmetic_sums",
"sympy/concrete/tests/test_sums_products.py::test_polynomial_sums",
"sympy/concrete/tests/test_sums_products.py::test_geometric_sums",
"sympy/concrete/tests/test_sums_products.py::test_harmonic_sums",
"sympy/concrete/tests/test_sums_products.py::test_composite_sums",
"sympy/concrete/tests/test_sums_products.py::test_hypergeometric_sums",
"sympy/concrete/tests/test_sums_products.py::test_other_sums",
"sympy/concrete/tests/test_sums_products.py::test_evalf_fast_series",
"sympy/concrete/tests/test_sums_products.py::test_evalf_fast_series_issue_4021",
"sympy/concrete/tests/test_sums_products.py::test_evalf_slow_series",
"sympy/concrete/tests/test_sums_products.py::test_euler_maclaurin",
"sympy/concrete/tests/test_sums_products.py::test_evalf_euler_maclaurin",
"sympy/concrete/tests/test_sums_products.py::test_evalf_symbolic",
"sympy/concrete/tests/test_sums_products.py::test_evalf_issue_3273",
"sympy/concrete/tests/test_sums_products.py::test_simple_products",
"sympy/concrete/tests/test_sums_products.py::test_rational_products",
"sympy/concrete/tests/test_sums_products.py::test_wallis_product",
"sympy/concrete/tests/test_sums_products.py::test_telescopic_sums",
"sympy/concrete/tests/test_sums_products.py::test_sum_reconstruct",
"sympy/concrete/tests/test_sums_products.py::test_limit_subs",
"sympy/concrete/tests/test_sums_products.py::test_function_subs",
"sympy/concrete/tests/test_sums_products.py::test_equality",
"sympy/concrete/tests/test_sums_products.py::test_Sum_doit",
"sympy/concrete/tests/test_sums_products.py::test_Product_doit",
"sympy/concrete/tests/test_sums_products.py::test_Sum_interface",
"sympy/concrete/tests/test_sums_products.py::test_eval_diff",
"sympy/concrete/tests/test_sums_products.py::test_hypersum",
"sympy/concrete/tests/test_sums_products.py::test_issue_4170",
"sympy/concrete/tests/test_sums_products.py::test_is_commutative",
"sympy/concrete/tests/test_sums_products.py::test_is_zero",
"sympy/concrete/tests/test_sums_products.py::test_is_number",
"sympy/concrete/tests/test_sums_products.py::test_free_symbols",
"sympy/concrete/tests/test_sums_products.py::test_conjugate_transpose",
"sympy/concrete/tests/test_sums_products.py::test_issue_4171",
"sympy/concrete/tests/test_sums_products.py::test_issue_6273",
"sympy/concrete/tests/test_sums_products.py::test_issue_6274",
"sympy/concrete/tests/test_sums_products.py::test_simplify",
"sympy/concrete/tests/test_sums_products.py::test_change_index",
"sympy/concrete/tests/test_sums_products.py::test_reorder",
"sympy/concrete/tests/test_sums_products.py::test_reverse_order",
"sympy/concrete/tests/test_sums_products.py::test_issue_7097",
"sympy/concrete/tests/test_sums_products.py::test_factor_expand_subs",
"sympy/concrete/tests/test_sums_products.py::test_distribution_over_equality",
"sympy/concrete/tests/test_sums_products.py::test_issue_2787",
"sympy/concrete/tests/test_sums_products.py::test_issue_4668",
"sympy/concrete/tests/test_sums_products.py::test_matrix_sum",
"sympy/series/tests/test_sequences.py::test_EmptySequence",
"sympy/series/tests/test_sequences.py::test_SeqExpr",
"sympy/series/tests/test_sequences.py::test_SeqPer",
"sympy/series/tests/test_sequences.py::test_SeqFormula",
"sympy/series/tests/test_sequences.py::test_sequence",
"sympy/series/tests/test_sequences.py::test_SeqExprOp",
"sympy/series/tests/test_sequences.py::test_SeqAdd",
"sympy/series/tests/test_sequences.py::test_SeqMul",
"sympy/series/tests/test_sequences.py::test_add",
"sympy/series/tests/test_sequences.py::test_sub",
"sympy/series/tests/test_sequences.py::test_mul__coeff_mul",
"sympy/series/tests/test_sequences.py::test_neg",
"sympy/series/tests/test_sequences.py::test_operations",
"sympy/tensor/tests/test_indexed.py::test_Idx_construction",
"sympy/tensor/tests/test_indexed.py::test_Idx_properties",
"sympy/tensor/tests/test_indexed.py::test_Idx_bounds",
"sympy/tensor/tests/test_indexed.py::test_Idx_fixed_bounds",
"sympy/tensor/tests/test_indexed.py::test_Idx_func_args",
"sympy/tensor/tests/test_indexed.py::test_Idx_subs",
"sympy/tensor/tests/test_indexed.py::test_IndexedBase_sugar",
"sympy/tensor/tests/test_indexed.py::test_IndexedBase_subs",
"sympy/tensor/tests/test_indexed.py::test_IndexedBase_shape",
"sympy/tensor/tests/test_indexed.py::test_Indexed_constructor",
"sympy/tensor/tests/test_indexed.py::test_Indexed_func_args",
"sympy/tensor/tests/test_indexed.py::test_Indexed_subs",
"sympy/tensor/tests/test_indexed.py::test_Indexed_properties",
"sympy/tensor/tests/test_indexed.py::test_Indexed_shape_precedence",
"sympy/tensor/tests/test_indexed.py::test_complex_indices",
"sympy/tensor/tests/test_indexed.py::test_not_interable",
"sympy/tensor/tests/test_indexed.py::test_Indexed_coeff"
] | [] | BSD | 179 |
praw-dev__praw-441 | c64e3f71841e8f0c996d42eb5dc9a91fc0c25dcb | 2015-07-02 19:21:13 | c64e3f71841e8f0c996d42eb5dc9a91fc0c25dcb | diff --git a/praw/objects.py b/praw/objects.py
index 4640a73a..505438ae 100755
--- a/praw/objects.py
+++ b/praw/objects.py
@@ -81,10 +81,26 @@ class RedditContentObject(object):
raise AttributeError('\'%s\' has no attribute \'%s\'' % (type(self),
attr))
+ def __getstate__(self):
+ """Needed for `pickle`.
+
+ Without this, pickle protocol version 0 will make HTTP requests
+ upon serialization, hence slowing it down significantly.
+ """
+ return self.__dict__
+
def __ne__(self, other):
"""Return whether the other instance differs from the current."""
return not self == other
+ def __reduce_ex__(self, protocol):
+ """Needed for `pickle`.
+
+ Without this, `pickle` protocol version 2 will make HTTP requests
+ upon serialization, hence slowing it down significantly.
+ """
+ return self.__reduce__()
+
def __setattr__(self, name, value):
"""Set the `name` attribute to `value."""
if value and name == 'subreddit':
| Pickling Comment objects is slow
Test case:
```python
import pickle, praw
r = praw.Reddit('test')
comment = r.get_info(thing_id='t1_aaaa')
pickle.dumps(comment)
```
Looking at Wireshark, it seems to be caused by an HTTP request.
Good news: implementing `def __getstate__(self): return self.__dict__` in `praw.objects.RedditContentObject` fixes it.
Bad news: I'm not sure why since `pickle` use `__dict__` by default, [as per the docs](https://docs.python.org/2/library/pickle.html#object.__getstate__).
I'm not really familiar with the intricacies of `pickle`, any ideas? | praw-dev/praw | diff --git a/tests/cassettes/test_pickling_v0.json b/tests/cassettes/test_pickling_v0.json
new file mode 100644
index 00000000..784fdddf
--- /dev/null
+++ b/tests/cassettes/test_pickling_v0.json
@@ -0,0 +1,1 @@
+{"recorded_with": "betamax/0.4.2", "http_interactions": [{"response": {"body": {"base64_string": "H4sIAAAAAAAAAxzLy4oDIRBA0V+RWhvQKrXU78huGEK1D3ryMrS9C/3vIbO9h/uG6xxPyOoNbdvGNiGrn1+toMou//nZWr2s+/76Upf7bFrBY9RV5gpZwRxcirzqdIIhogTXBD07omZMXyQsS6JUHZFERl99AK2gjHH7a9+fyWAMrNFYfzJ8Mni2mC1lDNraUrm45LupyXPqYWHxyZYYKLEXF52lXgSO4/gAAAD//wMAkqq30coAAAA=", "encoding": "UTF-8"}, "status": {"message": "OK", "code": 200}, "url": "https://api.reddit.com/api/login/.json", "headers": {"x-xss-protection": ["1; mode=block"], "set-cookie": ["__cfduid=d39c55cd52ddf9bd97d92e1bfab8520cb1435864405; expires=Fri, 01-Jul-16 19:13:25 GMT; path=/; domain=.reddit.com; HttpOnly", "secure_session=; Domain=reddit.com; Max-Age=-1435864406; Path=/; expires=Thu, 01-Jan-1970 00:00:01 GMT; HttpOnly", "reddit_session=7302867%2C2015-07-02T12%3A13%3A26%2C11cd7c495f0d9579f6b7a591c863975a48413fca; Domain=reddit.com; Path=/; HttpOnly"], "server": ["cloudflare-nginx"], "date": ["Thu, 02 Jul 2015 19:13:26 GMT"], "x-content-type-options": ["nosniff"], "cache-control": ["private, no-cache", "no-cache"], "content-type": ["application/json; charset=UTF-8"], "x-moose": ["majestic"], "x-ua-compatible": ["IE=edge"], "pragma": ["no-cache"], "transfer-encoding": ["chunked"], "x-frame-options": ["SAMEORIGIN"], "connection": ["keep-alive"], "content-encoding": ["gzip"], "cf-ray": ["1ffcaaf8bc5f0893-FRA"]}}, "request": {"body": {"encoding": "utf-8", "string": "user=PyAPITestUser2&api_type=json&passwd=1111"}, "uri": "https://api.reddit.com/api/login/.json", "method": "POST", "headers": {"Content-Length": ["45"], "User-Agent": ["PRAW_test_suite PRAW/3.0.0 Python/2.7.8 Linux-3.16.0-41-generic-x86_64-with-Ubuntu-14.10-utopic"], "Content-Type": ["application/x-www-form-urlencoded"], "Accept": ["*/*"], "Connection": ["keep-alive"], "Accept-Encoding": ["gzip, deflate"]}}, "recorded_at": "2015-07-02T19:13:26"}, {"response": {"body": {"base64_string": "H4sIAFeNlVUC/+2cXW/juBWG/4qRi0WLDif8/pjFoiiKBVqgF3uxi17sFAY/x5o4tmPLySSD/e8lKdkj22nGjiXZSXPj2JIsvuQ576NDSvHXi6ti4i4+DC7+VSzKYvLp4t3gwulSx01fL66nbqQXo7T7Vgj96d5+MUZgKL2lKBDBsJHC0+ACkcFJL7hGhEKLJIM0ncmOirGb+0k8w+9f102VaKOVxdLMvXNFOSyq3WyISzbl6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MUXGImJFQg/d8NoDTGWhOB0xRUhKCoItX0+NmkwIsHT7LS/kgxWaprO+mHFN/6dywp9riAf7fOQBQ+clOgVVrsIfPUdca3+G/QA8UUZ+qRZ9RapkeVEk16rFyWTJY8lizWdNjj9GjqfaNHr/RgN33Qo0rV8W1u7Fh8bK4qEq2185QAZq0H1OsYGQ4lIMojaOPkmMITPdh9gMAeMFEF+hFMdL/s2S4mznnZ87VionZu15hos8jYrvUVglRbxkCcmLtY6zMBFMMIWGWV8VYyaE/0tNZBErsnRR3rXVKIF1ZQ1HrPkxTICEsUckByqwHllAETcLwq8HiFsDpOTDU5lhRG5SWoPkkhy0mW3Qsp6v4dS4o96vynpyM52xjZdUertNhD5umnI6v4b9ODEt79TZMqJTZumtQuSyZLHksWazrsf9Jjrfc86WFZgFQ5BhiVsc4wggNNFQSKaI8QjntU/lGzY+ihru77pwcr+qBHlapmNGsDH1sPORAEOaUeQG0UoBJZoDWVQELMrWHYYnyiVc8DBPaAiSrQu5igvWAi5nYTEys7JTclMyUvNa30BCZqveeJiVdbZFQ/Yto1JtosMrZrfW4wlRoFoCWKBEfeAaO0AJoLwQ2U0NgTPa11kMQeSFH/YO0OKUgv05H2Copa73mS4rUWFFb29FD4t/4dS4o96vzvTkcowW/TkUb8t+lBOO6FHm3VGWu950kPYhhiQslYTkZwUIYJkDqEtNhtbEDeOnf0siefL3unh7nrpc7IqSo6+V0tQyzlJoLcMQcBFdYCGSgCsXA1hrF48aK5Auy/zDhAYPeYqAO9iwnUy3Qk5nYTEys7JTclMyUvNa30BCZqveeJiddaZNQLCV1jos0iY7vWhz54owgCiJtIcB4gMFYqYDQOkCMMEc6K+ufEQRJ7IEUV6x1SMNX9f7O3WVCs9J4nKV5pQSE+o+zeXkhR9+9YUuxR5393OkLYYz8J0yot9pB5+unIKv7b9MAUPTI+7dOjrTpjrbcVeuTcDqXPqb05UMaHKnurI/8LycOnWhVpAAA=", "encoding": "UTF-8"}, "status": {"message": "OK", "code": 200}, "url": "https://api.reddit.com/user/PyAPITestUser2/comments.json?t=all&sort=new", "headers": {"x-xss-protection": ["1; mode=block"], "cache-control": ["private, no-cache", "no-cache"], "content-length": ["2606"], "server": ["cloudflare-nginx"], "date": ["Thu, 02 Jul 2015 19:13:27 GMT"], "x-content-type-options": ["nosniff"], "x-ratelimit-reset": ["393"], "content-type": ["application/json; charset=UTF-8"], "x-reddit-tracking": ["https://pixel.redditmedia.com/pixel/of_destiny.png?v=y3Jhs4XJ5ugsyWdG9pnDnfGKSbeEgrfxPSdmstjKjWA%2BUzeRcc2LGH9Yml8p1SiJZyKNuVriYuO2wvi26Sdq9URNAtTXSZSa"], "x-moose": ["majestic"], "x-ua-compatible": ["IE=edge"], "vary": ["accept-encoding"], "pragma": ["no-cache"], "x-sup-id": ["http://www.reddit.com/sup.json#e4356386a7"], "x-ratelimit-used": ["1"], "x-frame-options": ["SAMEORIGIN"], "connection": ["keep-alive"], "content-encoding": ["gzip"], "x-ratelimit-remaining": ["299"], "cf-ray": ["1ffcaafdccd60893-FRA"]}}, "request": {"body": {"encoding": "utf-8", "string": ""}, "uri": "https://api.reddit.com/user/PyAPITestUser2/comments.json?t=all&sort=new", "method": "GET", "headers": {"Cookie": ["__cfduid=d39c55cd52ddf9bd97d92e1bfab8520cb1435864405; reddit_session=7302867%2C2015-07-02T12%3A13%3A26%2C11cd7c495f0d9579f6b7a591c863975a48413fca"], "Connection": ["keep-alive"], "User-Agent": ["PRAW_test_suite PRAW/3.0.0 Python/2.7.8 Linux-3.16.0-41-generic-x86_64-with-Ubuntu-14.10-utopic"], "Accept": ["*/*"], "Accept-Encoding": ["gzip, deflate"]}}, "recorded_at": "2015-07-02T19:13:27"}]}
\ No newline at end of file
diff --git a/tests/cassettes/test_pickling_v1.json b/tests/cassettes/test_pickling_v1.json
new file mode 100644
index 00000000..2b78d924
--- /dev/null
+++ b/tests/cassettes/test_pickling_v1.json
@@ -0,0 +1,1 @@
+{"recorded_with": "betamax/0.4.2", "http_interactions": [{"response": {"body": {"base64_string": "H4sIAAAAAAAAAxzLSW7DMAxA0asIXCsASYmazpFdURSyhtptEhWWVw189yLd/of/hK85HpDUE9q+j31CUm/vWkHNR/7Pj9bqx3ocPy/q+TabVnAfdc1zhaRg3rft1vDXfrpeqVcWH4SWUthxjjFybmhKw+ZNXshFLKAVlDG+t/b6vUEOzmtGkgv6C/KVOJFJHDVTFYk2SJfgoqm9CKJdfCfLjrAGQhRrBc7z/AMAAP//AwBlfaprygAAAA==", "encoding": "UTF-8"}, "status": {"message": "OK", "code": 200}, "url": "https://api.reddit.com/api/login/.json", "headers": {"x-xss-protection": ["1; mode=block"], "set-cookie": ["__cfduid=dea6ea5a6ed306c9a2fbe4aea3094d7ad1435864409; expires=Fri, 01-Jul-16 19:13:29 GMT; path=/; domain=.reddit.com; HttpOnly", "secure_session=; Domain=reddit.com; Max-Age=-1435864409; Path=/; expires=Thu, 01-Jan-1970 00:00:01 GMT; HttpOnly", "reddit_session=7302867%2C2015-07-02T12%3A13%3A29%2C21d559485f58693dfc5004b7f142610d81005445; Domain=reddit.com; Path=/; HttpOnly"], "server": ["cloudflare-nginx"], "date": ["Thu, 02 Jul 2015 19:13:29 GMT"], "x-content-type-options": ["nosniff"], "cache-control": ["private, no-cache", "no-cache"], "content-type": ["application/json; charset=UTF-8"], "x-moose": ["majestic"], "x-ua-compatible": ["IE=edge"], "pragma": ["no-cache"], "transfer-encoding": ["chunked"], "x-frame-options": ["SAMEORIGIN"], "connection": ["keep-alive"], "content-encoding": ["gzip"], "cf-ray": ["1ffcab0cfb8008b1-FRA"]}}, "request": {"body": {"encoding": "utf-8", "string": "user=PyAPITestUser2&api_type=json&passwd=1111"}, "uri": "https://api.reddit.com/api/login/.json", "method": "POST", "headers": {"Content-Length": ["45"], "User-Agent": ["PRAW_test_suite PRAW/3.0.0 Python/2.7.8 Linux-3.16.0-41-generic-x86_64-with-Ubuntu-14.10-utopic"], "Content-Type": ["application/x-www-form-urlencoded"], "Accept": ["*/*"], "Connection": ["keep-alive"], "Accept-Encoding": ["gzip, deflate"]}}, "recorded_at": "2015-07-02T19:13:29"}, {"response": {"body": {"base64_string": "H4sIAFqNlVUC/+2cy27jyBWGX0XwYpAgXe26X3owCIJggATIYhYzyGIcCHVtsS1LskTZbTfm3VNVpGRactySRVKy443bJmnWX3XO//GcEtvfzi6LiTv7NDj7V7Eoi8nnsw+DM6dLHQ99O7uaupFejNLp2WeJb9wdLqnlQmMpMGEYMW8QhlByZRkj3CIRT1sYDBMo3cmOirGb+0m8w+/f1kOV+dx6lMXSzL1zRTksqtNsiEs25emicTG5HJZFOfbpzK9+UQ7+ru3IfxpoiOCN03x+j6ClknHFnRTQciYFE85YyLVXATvLMTchaJPuZ/Rk4t3Q3MXbTZbjcTw091fTGz0ezr1eTJPS+ngeulZEhsRQ/aVcS9LLcjSdp3O/3P3tl38mYb8t/BxXF1z6RTxVzpc+3382LvKBs3R2GS+LY82m8zId+/0/8dhC3/g0UNDjRfqValS7KGZ46tIvfY7LmK+A8Qc9j8v6+Beq+9VTWN/2OZEzHcOyXvHm/BZ2Ok+rjdIdZrP59GZjwex0Uqaj80Whx0WZziRZZurSt2f/iJMZLKZXfrCcFHbqYqz+dLGE0MWL8r/uz2kYHwP+aA6V2mEY62I+tIvF0I71Is2lHtZNb/PUVmMNR+XVOA34w7j80RU3g3z9TxdnV+7i7IfP5Y/p+Cx9s4OidO15vvhikr+PN0w/5QVZ5WcarM5UPSuGZVzP9YINR4VzOdFX85noq5y0JRo2ImljjKp5IxodJCAj8GOOanP6pf+aRwvTqdHzddYt53nCo7KcfTo/v729/VjJ+WinV+fz8w1t5/HoVQzy4rwK7nk6OLTJPucNKcNlaVdyOFe1nOUsrXXKgQiBzXydLK8ah9LlrqLHsliM8uRSzP7448Pg3fQvMf1o3Ifp67xU+dShrv9tUlwv/SDN++7T4Paej5iR11OhvWVKBmK9NxQbB7miUFHlAxaCEGWJ584r2DMSDpXbAy+qJNjmBUYnxYtazjsvjsiLysJd86LNIqH2X51xnwb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xv9DC3vdQZOVVFJ39XyxBLuYkgd8xBQIW1QAaKQCxcjWEsPrxorgD7LzP2ENg9JupAb2MC9dKOxNxuYmJlp+SmZKbkpaaVnsFErfc0MfFWi4x6I6FrTLRZZGzW+tAHbxRBAHETCc4DBMZKBYzGAXKEIcJZUf+c2EtiD6SoYr1FCqa6/9/sbRYUK72nSYo3WlCILyi7txdS1PM7lBQ71PnfbUcIe+pPwrRKix1kHr8dWcV/kx6YoifWp316tFVnrPW2Qo+c26H0ObUfL5Txocre6sr/Atr8huMVaQAA", "encoding": "UTF-8"}, "status": {"message": "OK", "code": 200}, "url": "https://api.reddit.com/user/PyAPITestUser2/comments.json?t=all&sort=new", "headers": {"x-xss-protection": ["1; mode=block"], "cache-control": ["private, no-cache", "no-cache"], "content-length": ["2607"], "server": ["cloudflare-nginx"], "date": ["Thu, 02 Jul 2015 19:13:30 GMT"], "x-content-type-options": ["nosniff"], "x-ratelimit-reset": ["390"], "content-type": ["application/json; charset=UTF-8"], "x-reddit-tracking": ["https://pixel.redditmedia.com/pixel/of_destiny.png?v=9MZApNR3IAPjbhJiKbVbvujo6sivs6GURrLX9KX%2FCvGsONQwEOkhfoAl3ER7yTY2748o3j55GADAHujR7EOrq7oEdFe%2FFsY9"], "x-moose": ["majestic"], "x-ua-compatible": ["IE=edge"], "vary": ["accept-encoding"], "pragma": ["no-cache"], "x-sup-id": ["http://www.reddit.com/sup.json#e4356386a7"], "x-ratelimit-used": ["2"], "x-frame-options": ["SAMEORIGIN"], "connection": ["keep-alive"], "content-encoding": ["gzip"], "x-ratelimit-remaining": ["298"], "cf-ray": ["1ffcab124bf608b1-FRA"]}}, "request": {"body": {"encoding": "utf-8", "string": ""}, "uri": "https://api.reddit.com/user/PyAPITestUser2/comments.json?t=all&sort=new", "method": "GET", "headers": {"Cookie": ["__cfduid=dea6ea5a6ed306c9a2fbe4aea3094d7ad1435864409; reddit_session=7302867%2C2015-07-02T12%3A13%3A29%2C21d559485f58693dfc5004b7f142610d81005445"], "Connection": ["keep-alive"], "User-Agent": ["PRAW_test_suite PRAW/3.0.0 Python/2.7.8 Linux-3.16.0-41-generic-x86_64-with-Ubuntu-14.10-utopic"], "Accept": ["*/*"], "Accept-Encoding": ["gzip, deflate"]}}, "recorded_at": "2015-07-02T19:13:30"}]}
\ No newline at end of file
diff --git a/tests/cassettes/test_pickling_v2.json b/tests/cassettes/test_pickling_v2.json
new file mode 100644
index 00000000..3a4f3110
--- /dev/null
+++ b/tests/cassettes/test_pickling_v2.json
@@ -0,0 +1,1 @@
+{"recorded_with": "betamax/0.4.2", "http_interactions": [{"response": {"body": {"base64_string": "H4sIAAAAAAAAAxzLy2rEMAxA0V8xWnvAkuL48R3dlVJkWyHz9OBkMwz59zLd3sN9w2XrD8jmDTpGHxtk8/1jDTTZ5T8/VNvvuu/PDy1y29QauPe2yrZCNvB6Tc9RxjpuhThh1EQ6YcEkpRL5ElRRQ5uLF6FSp+bBGqi9X8/6+QM7inOw5NCfXDg5+kLKyJnJcuJCsixLQsZJWqzOFU01xsTE4sIslZuPcBzHHwAAAP//AwAKbaoxygAAAA==", "encoding": "UTF-8"}, "status": {"message": "OK", "code": 200}, "url": "https://api.reddit.com/api/login/.json", "headers": {"x-xss-protection": ["1; mode=block"], "set-cookie": ["__cfduid=d49ca6cca210c0b0c94548e0d7457f5e81435864411; expires=Fri, 01-Jul-16 19:13:31 GMT; path=/; domain=.reddit.com; HttpOnly", "secure_session=; Domain=reddit.com; Max-Age=-1435864412; Path=/; expires=Thu, 01-Jan-1970 00:00:01 GMT; HttpOnly", "reddit_session=7302867%2C2015-07-02T12%3A13%3A32%2C393b2afff91314ad8c00be9c889323a076ac3d58; Domain=reddit.com; Path=/; HttpOnly"], "server": ["cloudflare-nginx"], "date": ["Thu, 02 Jul 2015 19:13:32 GMT"], "x-content-type-options": ["nosniff"], "cache-control": ["private, no-cache", "no-cache"], "content-type": ["application/json; charset=UTF-8"], "x-moose": ["majestic"], "x-ua-compatible": ["IE=edge"], "pragma": ["no-cache"], "transfer-encoding": ["chunked"], "x-frame-options": ["SAMEORIGIN"], "connection": ["keep-alive"], "content-encoding": ["gzip"], "cf-ray": ["1ffcab1d4ce40467-FRA"]}}, "request": {"body": {"encoding": "utf-8", "string": "user=PyAPITestUser2&api_type=json&passwd=1111"}, "uri": "https://api.reddit.com/api/login/.json", "method": "POST", "headers": {"Content-Length": ["45"], "User-Agent": ["PRAW_test_suite PRAW/3.0.0 Python/2.7.8 Linux-3.16.0-41-generic-x86_64-with-Ubuntu-14.10-utopic"], "Content-Type": ["application/x-www-form-urlencoded"], "Accept": ["*/*"], "Connection": ["keep-alive"], "Accept-Encoding": ["gzip, deflate"]}}, "recorded_at": "2015-07-02T19:13:32"}, {"response": {"body": {"base64_string": "H4sIAF2NlVUC/+2cW2/juBmG/4qRi0WLDic8H2axKIpigRboxV7sohc7hcHjWBPHdiw5mWSw/70kJXtkO83YsSw7aW5ykBTxJb/vffSRYvz14qqYuIsPg4t/FWVVTD5dvBtcOF3peOjrxfXUjXQ5SqevvpTVLUPlohJYOyMcQwZrLoRBKmiDscJeUuo0kp4z5LhId7KjYuzmfhLv8PvXVVMVWmulXJi5d66ohkV9mg1xxaY8XTQuJlfDqqjGPp351ZfV4O/ajvyHgYYI3jrN5w8IWioZV9xJAS1nUjDhjIVcexWwsxxzE6LGdD+jJxPvhuY+3m6yGI/jobm/nt7q8XDudTlNSpvjuelGERkSQ/XnaiVJL6rRdJ7O/XL/t1/+mYT9Vvo5ri+48mU8Vc0XPt9/Ni7ygYt0dhEvi23NpvMqHfv9P/FYqW99aijocZn+pG7VlsUMT136o09xGPMVMP6i53FY1/+gvl/ThdVtnxI50zEsqxFv96+003kabZTuMJvNp7cbA2ankyodnZeFHhdVOpNkmalLP178I3ZmUE6v/WAxKezUxVj96eMCQhcvyt/dn1MzPgZ8rQ+12mEY62I+tGU5tGNdpr40zbrpXe7asq3hqLoepwZ/GFc/uuJ2kK//6ePFtft48cOn6sd0fJZ+2EFRuvYyX/xxkn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Ix1hhEcaKogUER7hHA8o/KHmh1CD3V13z89WNEHPepUNaNZF/jY2ORAEOSUegC1UYBKZIHWVAIJMbeGYYvxiVY99xDYAybqQG9jgvaCiZjbbUws7ZTclMyUvNS20hOYaPSeJyZebZEB8xuLY2OiyyJjs9bnBlOpUQBaokhw5B0wSguQPrmVGyihsSfarbWXxB5IUcd6mxSkl+lIdwVFo/c8SfFaCwore9oU/q1/h5Jihzr/u9MRSvDbdKQV/016EI57oUdXdcZK73nSgxiGmFAylpMRHJRhAqQOIS12GxuQt84dvOzJ54ve6WHueqkzcqqKo3yuliGWchNB7piDgAprgQwUgVi4GsNYfHjRXAH2X2bsIfD4mGgCvY0J1Mt0JOZ2GxNLOyU3JTMlL7Wt9AQmGr3niYnXWmQ0CwnHxkSXRcZmrQ998EYRBBA3keA8QGCsVMBoHCBHGCKcFfXPib0k9kCKOtZbpGDq+P/N3mVBsdR7nqR4pQWF+Iyye3shRdO/Q0mxQ53/3ekIYY99JEyntNhB5umnI8v4b9IDU/TI+HRPj67qjJXeTuiRcztUPqf2+kAZH+rsra/8L3S6MKwVaQAA", "encoding": "UTF-8"}, "status": {"message": "OK", "code": 200}, "url": "https://api.reddit.com/user/PyAPITestUser2/comments.json?t=all&sort=new", "headers": {"x-xss-protection": ["1; mode=block"], "cache-control": ["private, no-cache", "no-cache"], "content-length": ["2607"], "server": ["cloudflare-nginx"], "date": ["Thu, 02 Jul 2015 19:13:33 GMT"], "x-content-type-options": ["nosniff"], "x-ratelimit-reset": ["387"], "content-type": ["application/json; charset=UTF-8"], "x-reddit-tracking": ["https://pixel.redditmedia.com/pixel/of_destiny.png?v=NI%2FS0Vy8geEeJ%2BBL7Qy5J2Q26m47mKxDD5uB2y%2B851CRfxV7GGUC7FAOqmbXqrgmuzZ%2BjeU5o6AO95wvK098lEadH8PZql7p"], "x-moose": ["majestic"], "x-ua-compatible": ["IE=edge"], "vary": ["accept-encoding"], "pragma": ["no-cache"], "x-sup-id": ["http://www.reddit.com/sup.json#e4356386a7"], "x-ratelimit-used": ["3"], "x-frame-options": ["SAMEORIGIN"], "connection": ["keep-alive"], "content-encoding": ["gzip"], "x-ratelimit-remaining": ["297"], "cf-ray": ["1ffcab26cdfa0467-FRA"]}}, "request": {"body": {"encoding": "utf-8", "string": ""}, "uri": "https://api.reddit.com/user/PyAPITestUser2/comments.json?t=all&sort=new", "method": "GET", "headers": {"Cookie": ["__cfduid=d49ca6cca210c0b0c94548e0d7457f5e81435864411; reddit_session=7302867%2C2015-07-02T12%3A13%3A32%2C393b2afff91314ad8c00be9c889323a076ac3d58"], "Connection": ["keep-alive"], "User-Agent": ["PRAW_test_suite PRAW/3.0.0 Python/2.7.8 Linux-3.16.0-41-generic-x86_64-with-Ubuntu-14.10-utopic"], "Accept": ["*/*"], "Accept-Encoding": ["gzip, deflate"]}}, "recorded_at": "2015-07-02T19:13:33"}]}
\ No newline at end of file
diff --git a/tests/cassettes/test_unpickle_comment.json b/tests/cassettes/test_unpickle_comment.json
deleted file mode 100644
index ce5e4d79..00000000
--- a/tests/cassettes/test_unpickle_comment.json
+++ /dev/null
@@ -1,1 +0,0 @@
-{"recorded_with": "betamax/0.4.2", "http_interactions": [{"recorded_at": "2015-06-15T13:50:36", "response": {"status": {"code": 200, "message": "OK"}, "headers": {"transfer-encoding": ["chunked"], "cache-control": ["private, no-cache", "no-cache"], "server": ["cloudflare-nginx"], "set-cookie": ["__cfduid=d28895e21c18fe156bbe302205f9b22ac1434376236; expires=Tue, 14-Jun-16 13:50:36 GMT; path=/; domain=.reddit.com; HttpOnly", "secure_session=; Domain=reddit.com; Max-Age=-1434376237; Path=/; expires=Thu, 01-Jan-1970 00:00:01 GMT; HttpOnly", "reddit_session=7302867%2C2015-06-15T06%3A50%3A37%2Cc0e114b1f45a1bc763984b34c83d31df49a92fed; Domain=reddit.com; Path=/; HttpOnly"], "x-moose": ["majestic"], "x-xss-protection": ["1; mode=block"], "connection": ["keep-alive"], "content-encoding": ["gzip"], "pragma": ["no-cache"], "x-ua-compatible": ["IE=edge"], "x-frame-options": ["SAMEORIGIN"], "cf-ray": ["1f6ebeb510a504a3-CDG"], "date": ["Mon, 15 Jun 2015 13:50:37 GMT"], "content-type": ["application/json; charset=UTF-8"], "x-content-type-options": ["nosniff"]}, "body": {"encoding": "UTF-8", "base64_string": "H4sIAAAAAAAAAxzLTWrDMBBA4auIWSug0c+MpXNkV0oZWaM6TRMV26GL4LuXdPs+3hO+tnGHYp6g6zrWDYp5e7cGmuzyn++q7WPZ958Xdfne1Bq4jbbItkAxcPt8CD+uv3zBPElGVidEnZPXWmtLVSmRsnOkVTwqR7AG5jGuF339HJyfiK13mE6OTpjOjkpyJbCdnSLGij0mwTozhTzFGuI8hRaw9Zgl+64NjuP4AwAA//8DABH3aj7KAAAA"}, "url": "https://api.reddit.com/api/login/.json"}, "request": {"headers": {"Accept-Encoding": ["gzip, deflate"], "Connection": ["keep-alive"], "Accept": ["*/*"], "Content-Length": ["45"], "User-Agent": ["PRAW_test_suite PRAW/3.0a1 Python/2.7.8 Linux-3.16.0-37-generic-x86_64-with-Ubuntu-14.10-utopic"], "Content-Type": ["application/x-www-form-urlencoded"]}, "body": {"encoding": "utf-8", "string": "passwd=1111&api_type=json&user=PyAPITestUser2"}, "uri": "https://api.reddit.com/api/login/.json", "method": "POST"}}, {"recorded_at": "2015-06-15T13:50:37", "response": {"status": {"code": 200, "message": "OK"}, "headers": {"x-ratelimit-remaining": ["299"], "content-type": ["application/json; charset=UTF-8"], "cache-control": ["private, no-cache", "no-cache"], "content-length": ["2574"], "server": ["cloudflare-nginx"], "x-content-type-options": ["nosniff"], "x-moose": ["majestic"], "x-ratelimit-used": ["1"], "x-frame-options": ["SAMEORIGIN"], "x-sup-id": ["http://www.reddit.com/sup.json#e4356386a7"], "x-xss-protection": ["1; mode=block"], "connection": ["keep-alive"], "content-encoding": ["gzip"], "pragma": ["no-cache"], "x-ua-compatible": ["IE=edge"], "x-reddit-tracking": ["https://pixel.redditmedia.com/pixel/of_destiny.png?v=HcLLGdCwZSCTj%2BYMBgG8Ln0%2FKHA5a%2FIoJVNJ%2Fv%2FXrv6TSUaosRpQ67%2Fyfcg6Z7i5Diz8FZevtuCHzUmagS6TUQ7G47Go4bcv"], "cf-ray": ["1f6ebeb9f0cd04a3-CDG"], "date": ["Mon, 15 Jun 2015 13:50:37 GMT"], "x-ratelimit-reset": ["563"], "vary": ["accept-encoding"]}, "body": {"encoding": "UTF-8", "base64_string": "H4sIAC3YflUC/+2cW2/bRhqG/4rgi6KLzcRzPqQoFotFgV1gL3rRYi/qhTAnRox1ikT5FPS/d2ZIKpTkOpJFUrLrG8cmafKd+b734Ts0oy8X1/nUXXwYXPw3Xxb59OPFu8GF04UOm75cTGZupJejuNsvVlO4yPESeWSVdAR7yz3VAmVQQwup4BZxCWVmtDeCIB7PZEf52C38NJzhty/rSxVo4yrLlVl45/JimJe72RAXbJZOMM6n18MiL8Y+7vlffp0PfpoWi/vBbDq4WkFoSfyqbDzW6OnUu6G5D4dOV+Nx2LTwk9mNHg8XXi9nUUW1PZ22uhoZEirvaLG+nF4Vo9ki7vv5/p8//+cXvyx+XfoFLg+49suwq1isfDr/fJynDRdx7yocFq41ny2KuO23/4dtS33j44UyPV7GXymvaj8vPc4f4i99DFOUjoDhB70IU7b5C+X5qiGsT/uUyLkOU76eTTQMF3P5tY67lna2iFOJ4inm88XsZmvG7CxMb9i6WOZ6nBdxT9RlZi5+e/HrNP+88oM47vsPA7mYf75Wo5vra2g4xYwb5KEWkmkBCUYs9IOiOOPcWcKQIDpp8KHUGyMsxzLMxjpfDO1yObRjvUyTeneXOmV2mwZeCxmOisk47v5uXPzg8ptBOv7Hq4uJu7r47mPxQ9w+j98cKzee6DKd6Wqavg9Xiz+lqazbNiqpGljP82ERSrGe6uEody71fz3YqZ6kXi7rUjeBDeUtJwVRArEikKP3qSGac1P4u3i1ZhOvFmkmRkUx/3B56afvb4NH5mGK9fvZ4uNl0yP/yN2PeHFLb8yDcvcCU5tB7Aj3yhAPkUD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vUMJprr9H+ltBola63lS4pUGCfEJJef2QolqfMdSYo9s/80lCGGPfZxLq6TYQ+bplyB1/bfJgSl6ZH7aJUdb+WKt9TzJoUmGHQ/RAmGO438k40BRG3IklJo5IS1l6XWfI8hx9zC77Z0c+bwXcsQ2LW5uJmmOjkXHZsJXFCsBRRbyHnKAYiKAMpkHmBlnEDImY6f9jO59BHaPiKrQO4ggnYeL2NdNRNRWik6KRoo+atrozxFRaz1PRLzWcNHbp2i2Fy528j0nRGhPASc4viOnGVDCGwCxDs5kmUblZzH2z4iDJPZAid1PzKyc93KCRK31PCnxOoNEuLcX6Zp9UKIe37GU2CPbf3MJEu7mfNcZrZJiD5knX4Ks679JDi4JedancB9CjpbyRUNrK+RIfZ0VPrX15iQZn5WdWx75B7y/uSWyaAAA"}, "url": "https://api.reddit.com/user/PyAPITestUser2/comments.json?sort=new&t=all"}, "request": {"headers": {"Connection": ["keep-alive"], "User-Agent": ["PRAW_test_suite PRAW/3.0a1 Python/2.7.8 Linux-3.16.0-37-generic-x86_64-with-Ubuntu-14.10-utopic"], "Accept": ["*/*"], "Accept-Encoding": ["gzip, deflate"], "Cookie": ["reddit_session=7302867%2C2015-06-15T06%3A50%3A37%2Cc0e114b1f45a1bc763984b34c83d31df49a92fed; __cfduid=d28895e21c18fe156bbe302205f9b22ac1434376236"]}, "body": {"encoding": "utf-8", "string": ""}, "uri": "https://api.reddit.com/user/PyAPITestUser2/comments.json?sort=new&t=all", "method": "GET"}}, {"recorded_at": "2015-06-15T13:50:38", "response": {"status": {"code": 200, "message": "OK"}, "headers": {"x-ratelimit-remaining": ["298"], "transfer-encoding": ["chunked"], "cache-control": ["private, no-cache", "no-cache"], "x-moose": ["majestic"], "server": ["cloudflare-nginx"], "x-ratelimit-used": ["2"], "x-frame-options": ["SAMEORIGIN"], "x-xss-protection": ["1; mode=block"], "connection": ["keep-alive"], "content-encoding": ["gzip"], "pragma": ["no-cache"], "x-ua-compatible": ["IE=edge"], "x-reddit-tracking": ["https://pixel.redditmedia.com/pixel/of_destiny.png?v=6qsn21tVL7go5HvVpotLbf0tnpT2hujgxe4105fEz7G1t0%2BHh25pl%2FSGghZNuAZaGB%2FJKaxz67I%3D"], "cf-ray": ["1f6ebebe912c04a3-CDG"], "date": ["Mon, 15 Jun 2015 13:50:38 GMT"], "x-ratelimit-reset": ["562"], "content-type": ["application/json; charset=UTF-8"], "x-content-type-options": ["nosniff"]}, "body": {"encoding": "UTF-8", "base64_string": "H4sIAAAAAAAAA1yRwW7DIBBEfwVxtqrYxgn2rcfecmjPaANLvYqBCnCUNsq/V6AkjXodzQ5vhgs/kjd8Yjx3vGHcQAY+sQufISkHtPCJWVgSNox7cFic++/X/ds7pvyRMNYrSspGwhp0d+uIkLEobSfFth02cnjZNIzPZFDZGJyK4RByerr5DItROqIxVPVid8HMkOby8LYVLq1j+Nl1BzNYsYGulwjCgu7sCOM49LtejhalMJ0WW7krcDcQtWb9gGnFHabUDOZ/1YX8UR0hujJG25WU4Bz6/BDHhvFwwqhaySeW41rOKKlS4SmIavyfozbE8xdFyBQ8n5hfl+UGcsJIltAovOHcY+sHCU1nW9f2h3BWOqw+l42u118AAAD//wMAKxRkF8UBAAA="}, "url": "https://api.reddit.com/user/PyAPITestUser2/about/.json"}, "request": {"headers": {"Connection": ["keep-alive"], "User-Agent": ["PRAW_test_suite PRAW/3.0a1 Python/2.7.8 Linux-3.16.0-37-generic-x86_64-with-Ubuntu-14.10-utopic"], "Accept": ["*/*"], "Accept-Encoding": ["gzip, deflate"], "Cookie": ["reddit_session=7302867%2C2015-06-15T06%3A50%3A37%2Cc0e114b1f45a1bc763984b34c83d31df49a92fed; __cfduid=d28895e21c18fe156bbe302205f9b22ac1434376236"]}, "body": {"encoding": "utf-8", "string": ""}, "uri": "https://api.reddit.com/user/PyAPITestUser2/about/.json", "method": "GET"}}, {"recorded_at": "2015-06-15T13:50:38", "response": {"status": {"code": 200, "message": "OK"}, "headers": {"x-ratelimit-remaining": ["297"], "content-type": ["application/json; charset=UTF-8"], "cache-control": ["private, no-cache", "no-cache"], "content-length": ["682"], "server": ["cloudflare-nginx"], "x-content-type-options": ["nosniff"], "x-moose": ["majestic"], "x-ratelimit-used": ["3"], "x-frame-options": ["SAMEORIGIN"], "x-xss-protection": ["1; mode=block"], "connection": ["keep-alive"], "content-encoding": ["gzip"], "pragma": ["no-cache"], "x-ua-compatible": ["IE=edge"], "x-reddit-tracking": ["https://pixel.redditmedia.com/pixel/of_destiny.png?v=AqxVkrSRF3bN55ymSSdkwfD%2FLdA4QMcYwodHHwNYU4Pccch5s1XTILSk9LACd6ER3FcO3MQmUDmhY5Rn5rzZjrp3D2F%2F%2BvsO"], "cf-ray": ["1f6ebec1714204a3-CDG"], "date": ["Mon, 15 Jun 2015 13:50:38 GMT"], "x-ratelimit-reset": ["562"], "vary": ["accept-encoding"]}, "body": {"encoding": "UTF-8", "base64_string": "H4sIAC7YflUC/61UyU7cQBD9FccHTsx4XwaUAyIimgOLICdC1OqlPNOZ9kJ3e2BA/Hu6G5sxHJCQcrHsqvKrV/Wq6tnf8Ib5R56vM//Q8xnW2Hw9+wQ3DUjE65V1WpfqSc010vCo0VrXwtibXgjj6ZWNVMj9Y8EqLBQYB3fIsc7a3CKMcbRttOSk1600fi17GzuBHzMyrjqBd6jBNVibBMZMCO64CVPahqwBsz3NtdbdURCQuV73NVHz1x9qYBzPaVsH0c/0PF5dIX41u87l7cU5e7g0hPqL5RKj/vIpOl1GJ7ebEHV0/rdbOQ6gqOSd5m0zVu0fCH38bTbzbk7R5dmZN5sdrPSxNTK+9ajASn2/82t254/2zr782CN5BS3ytHpI6D0UjEZZXpQQVqQK0yIvUhpnxYLQjMa0giTJwoyFFiZwOHeNeze5RviRy8VAxfLWXAvXtGvXA+/kaun9Mk3z0oeUb7aPOfRJRXLDglR5SnHF4qLMU8DVgkAZFSRMynBB8pDFFo62QuBOAWIgQAMzGtY1NFpN1O56IjhFk47Z/NOyxT3Uuo8SuSuyKCxTVuRltFiYSqO8jG3hizJb4CysGKQljUqXu92CjMpPE/1Hab7O8avScDP/SPEnK8+wQc402bVhrEcRh6hPOvv1gZqstODNBglMYLLTmNK2N/oiTDXfWhLRvvNa4qridCLJQHio6ncShoeeefx5TWJ5EpB2WOJ4n9edkg95x13XGXq7G1QC1u6wREkcZ1lYFNncJPB76UQPZPDhNASuiZwBwmw6ogMS6rUl/wFtOHnvlRlvVt2a+vC7i+Vcyqi0hhoQNJgIR3JwDxuCFG0lIEem5o1lY5OZFgyc9a5zFb/29k0Wpexcj07c7KYXdN/TsbiXl38Stiz/ywUAAA=="}, "url": "https://api.reddit.com/r/reddit_api_test/about/.json"}, "request": {"headers": {"Connection": ["keep-alive"], "User-Agent": ["PRAW_test_suite PRAW/3.0a1 Python/2.7.8 Linux-3.16.0-37-generic-x86_64-with-Ubuntu-14.10-utopic"], "Accept": ["*/*"], "Accept-Encoding": ["gzip, deflate"], "Cookie": ["reddit_session=7302867%2C2015-06-15T06%3A50%3A37%2Cc0e114b1f45a1bc763984b34c83d31df49a92fed; __cfduid=d28895e21c18fe156bbe302205f9b22ac1434376236"]}, "body": {"encoding": "utf-8", "string": ""}, "uri": "https://api.reddit.com/r/reddit_api_test/about/.json", "method": "GET"}}]}
\ No newline at end of file
diff --git a/tests/test_comments.py b/tests/test_comments.py
index e3c3aa27..2253f27e 100644
--- a/tests/test_comments.py
+++ b/tests/test_comments.py
@@ -2,6 +2,7 @@
from __future__ import print_function, unicode_literals
import pickle
+import mock
from praw import helpers
from praw.objects import Comment, MoreComments
from .helper import PRAWTest, betamax
@@ -98,10 +99,24 @@ class CommentTest(PRAWTest):
lambda item: isinstance(item, Comment))
self.assertEqual(comment._replies, None)
+ def _test_pickling(self, protocol):
+ comment = next(self.r.user.get_comments())
+ with mock.patch('praw.BaseReddit.request_json') as request_json_func:
+ unpickled_comment = pickle.loads(pickle.dumps(comment, protocol))
+ self.assertEqual(comment, unpickled_comment)
+ self.assertEqual(request_json_func.called, 0)
+
@betamax()
- def test_unpickle_comment(self):
- item = next(self.r.user.get_comments())
- self.assertEqual(item, pickle.loads(pickle.dumps(item)))
+ def test_pickling_v0(self):
+ self._test_pickling(0)
+
+ @betamax()
+ def test_pickling_v1(self):
+ self._test_pickling(1)
+
+ @betamax()
+ def test_pickling_v2(self):
+ self._test_pickling(2)
class MoreCommentsTest(PRAWTest):
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_hyperlinks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 1,
"issue_text_score": 1,
"test_score": 1
},
"num_modified_files": 1
} | 3.0 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "pytest",
"pip_packages": [
"betamax>=0.4.2",
"betamax-matchers>=0.2.0",
"flake8",
"mock>=1.0.0",
"pytest",
"pytest-cov",
"pytest-xdist",
"pytest-mock",
"pytest-asyncio"
],
"pre_install": null,
"python": "3.9",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | betamax==0.9.0
betamax-matchers==0.4.0
certifi==2025.1.31
charset-normalizer==3.4.1
coverage==7.8.0
exceptiongroup @ file:///croot/exceptiongroup_1706031385326/work
execnet==2.1.1
flake8==7.2.0
idna==3.10
iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work
mccabe==0.7.0
mock==5.2.0
packaging @ file:///croot/packaging_1734472117206/work
pluggy @ file:///croot/pluggy_1733169602837/work
-e git+https://github.com/praw-dev/praw.git@c64e3f71841e8f0c996d42eb5dc9a91fc0c25dcb#egg=praw
pycodestyle==2.13.0
pyflakes==3.3.1
pytest @ file:///croot/pytest_1738938843180/work
pytest-asyncio==0.26.0
pytest-cov==6.0.0
pytest-mock==3.14.0
pytest-xdist==3.6.1
requests==2.32.3
requests-toolbelt==1.0.0
six==1.17.0
tomli @ file:///opt/conda/conda-bld/tomli_1657175507142/work
typing_extensions==4.13.0
update-checker==0.18.0
urllib3==2.3.0
| name: praw
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- exceptiongroup=1.2.0=py39h06a4308_0
- iniconfig=1.1.1=pyhd3eb1b0_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=3.0.16=h5eee18b_0
- packaging=24.2=py39h06a4308_0
- pip=25.0=py39h06a4308_0
- pluggy=1.5.0=py39h06a4308_0
- pytest=8.3.4=py39h06a4308_0
- python=3.9.21=he870216_1
- readline=8.2=h5eee18b_0
- setuptools=75.8.0=py39h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- tomli=2.0.1=py39h06a4308_0
- tzdata=2025a=h04d1e81_0
- wheel=0.45.1=py39h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- betamax==0.9.0
- betamax-matchers==0.4.0
- certifi==2025.1.31
- charset-normalizer==3.4.1
- coverage==7.8.0
- execnet==2.1.1
- flake8==7.2.0
- idna==3.10
- mccabe==0.7.0
- mock==5.2.0
- pycodestyle==2.13.0
- pyflakes==3.3.1
- pytest-asyncio==0.26.0
- pytest-cov==6.0.0
- pytest-mock==3.14.0
- pytest-xdist==3.6.1
- requests==2.32.3
- requests-toolbelt==1.0.0
- six==1.17.0
- typing-extensions==4.13.0
- update-checker==0.18.0
- urllib3==2.3.0
prefix: /opt/conda/envs/praw
| [
"tests/test_comments.py::CommentTest::test_pickling_v0",
"tests/test_comments.py::CommentTest::test_pickling_v1",
"tests/test_comments.py::CommentTest::test_pickling_v2"
] | [] | [
"tests/test_comments.py::CommentTest::test_add_comment",
"tests/test_comments.py::CommentTest::test_add_reply",
"tests/test_comments.py::CommentTest::test_edit",
"tests/test_comments.py::CommentTest::test_front_page_comment_replies_are_none",
"tests/test_comments.py::CommentTest::test_get_comments_permalink",
"tests/test_comments.py::CommentTest::test_inbox_comment_permalink",
"tests/test_comments.py::CommentTest::test_inbox_comment_replies_are_none",
"tests/test_comments.py::CommentTest::test_save_comment",
"tests/test_comments.py::CommentTest::test_spambox_comments_replies_are_none",
"tests/test_comments.py::CommentTest::test_unicode_comment",
"tests/test_comments.py::CommentTest::test_user_comment_permalink",
"tests/test_comments.py::CommentTest::test_user_comment_replies_are_none",
"tests/test_comments.py::MoreCommentsTest::test_all_comments",
"tests/test_comments.py::MoreCommentsTest::test_comments_method"
] | [] | BSD 2-Clause "Simplified" License | 180 |
|
mattboyer__git-guilt-34 | 58f92d3e37a115596a890ad3e2fe674636c682ee | 2015-07-02 20:15:01 | 58f92d3e37a115596a890ad3e2fe674636c682ee | diff --git a/git_guilt/guilt.py b/git_guilt/guilt.py
index 23a748a..3b400c5 100644
--- a/git_guilt/guilt.py
+++ b/git_guilt/guilt.py
@@ -78,13 +78,14 @@ class GitRunner(object):
raise GitError("Malformed Git version")
raw_version = self.run_git(GitRunner._version_args)
- if not (raw_version and
- 1 == len(raw_version) and
- raw_version[0].startswith('git version')
- ):
- raise GitError("Couldn't determine Git version %s" % raw_version)
+ version_re = re.compile(r'^git version (\d+.\d+.\d+)')
- return version_string_to_tuple(raw_version[0].split()[-1])
+ if raw_version and 1 == len(raw_version):
+ match = version_re.match(raw_version[0])
+ if match:
+ return version_string_to_tuple(match.group(1))
+
+ raise GitError("Couldn't determine Git version %s" % raw_version)
def _get_git_root(self):
# We should probably go beyond just finding the root dir for the Git
| Git version detection fails on MacOS
Here's what a friendly user had to report:
> my MACBOOK running latest 10.10.3 comes preinstalled with
```
Laurences-MacBook-Pro:security Laurence$ git version
git version 2.3.2 (Apple Git-55)
```
The parsing code that consumes the output of `git version` should be made more robust. | mattboyer/git-guilt | diff --git a/test/test_guilt.py b/test/test_guilt.py
index 1433e33..3abda65 100644
--- a/test/test_guilt.py
+++ b/test/test_guilt.py
@@ -306,6 +306,27 @@ class GitRunnerTestCase(TestCase):
)
mock_process.reset_mock()
+ @patch('git_guilt.guilt.subprocess.Popen')
+ def test_mac_version(self, mock_process):
+ mock_process.return_value.communicate = Mock(
+ return_value=(b'git version 2.3.2 (Apple Git-55)', None)
+ )
+ mock_process.return_value.returncode = 0
+ mock_process.return_value.wait = \
+ Mock(return_value=None)
+
+ version_tuple = self.runner._get_git_version()
+
+ mock_process.assert_called_once_with(
+ ['nosuchgit', '--version'],
+ cwd='/my/arbitrary/path',
+ stderr=-1,
+ stdout=-1
+ )
+ mock_process.reset_mock()
+
+ self.assertEquals((2,3,2), version_tuple)
+
def test_version_comparison(self):
self.assertEquals((1, 0, 0), self.runner.version)
| {
"commit_name": "head_commit",
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true,
"llm_score": {
"difficulty_score": 1,
"issue_text_score": 0,
"test_score": 0
},
"num_modified_files": 1
} | 0.30 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[dev]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest",
"pytest-cov"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.4",
"reqs_path": [
"requirements-3.4.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | alabaster==0.7.13
astroid==2.11.7
attrs==22.2.0
Babel==2.11.0
certifi==2021.5.30
charset-normalizer==2.0.12
coverage==6.2
coveralls==3.3.1
dill==0.3.4
docopt==0.6.2
docutils==0.18.1
-e git+https://github.com/mattboyer/git-guilt.git@58f92d3e37a115596a890ad3e2fe674636c682ee#egg=git_guilt
idna==3.10
imagesize==1.4.1
importlib-metadata==4.8.3
iniconfig==1.1.1
isort==5.10.1
Jinja2==3.0.3
lazy-object-proxy==1.7.1
MarkupSafe==2.0.1
mccabe==0.7.0
mock==5.2.0
nose==1.3.7
packaging==21.3
pep8==1.7.1
platformdirs==2.4.0
pluggy==1.0.0
py==1.11.0
Pygments==2.14.0
pylint==2.13.9
pyparsing==3.1.4
pytest==7.0.1
pytest-cov==4.0.0
pytz==2025.2
requests==2.27.1
snowballstemmer==2.2.0
Sphinx==5.3.0
sphinx-argparse==0.3.2
sphinxcontrib-applehelp==1.0.2
sphinxcontrib-devhelp==1.0.2
sphinxcontrib-htmlhelp==2.0.0
sphinxcontrib-jsmath==1.0.1
sphinxcontrib-qthelp==1.0.3
sphinxcontrib-serializinghtml==1.1.5
tomli==1.2.3
typed-ast==1.5.5
typing_extensions==4.1.1
urllib3==1.26.20
wrapt==1.16.0
zipp==3.6.0
| name: git-guilt
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- pip=21.2.2=py36h06a4308_0
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_0
- setuptools=58.0.4=py36h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- alabaster==0.7.13
- argparse==1.4.0
- astroid==2.11.7
- attrs==22.2.0
- babel==2.11.0
- charset-normalizer==2.0.12
- coverage==6.2
- coveralls==3.3.1
- dill==0.3.4
- docopt==0.6.2
- docutils==0.18.1
- idna==3.10
- imagesize==1.4.1
- importlib-metadata==4.8.3
- iniconfig==1.1.1
- isort==5.10.1
- jinja2==3.0.3
- lazy-object-proxy==1.7.1
- markupsafe==2.0.1
- mccabe==0.7.0
- mock==5.2.0
- nose==1.3.7
- packaging==21.3
- pep8==1.7.1
- platformdirs==2.4.0
- pluggy==1.0.0
- py==1.11.0
- pygments==2.14.0
- pylint==2.13.9
- pyparsing==3.1.4
- pytest==7.0.1
- pytest-cov==4.0.0
- pytz==2025.2
- requests==2.27.1
- snowballstemmer==2.2.0
- sphinx==5.3.0
- sphinx-argparse==0.3.2
- sphinxcontrib-applehelp==1.0.2
- sphinxcontrib-devhelp==1.0.2
- sphinxcontrib-htmlhelp==2.0.0
- sphinxcontrib-jsmath==1.0.1
- sphinxcontrib-qthelp==1.0.3
- sphinxcontrib-serializinghtml==1.1.5
- tomli==1.2.3
- typed-ast==1.5.5
- typing-extensions==4.1.1
- urllib3==1.26.20
- wrapt==1.16.0
- zipp==3.6.0
prefix: /opt/conda/envs/git-guilt
| [
"test/test_guilt.py::GitRunnerTestCase::test_mac_version"
] | [] | [
"test/test_guilt.py::DeltaTestCase::test_comparison",
"test/test_guilt.py::DeltaTestCase::test_eq",
"test/test_guilt.py::DeltaTestCase::test_repr",
"test/test_guilt.py::BinaryDeltaTestCase::test_comparison",
"test/test_guilt.py::BinaryDeltaTestCase::test_eq",
"test/test_guilt.py::BinaryDeltaTestCase::test_repr",
"test/test_guilt.py::ArgTestCase::test_bad_args",
"test/test_guilt.py::ArgTestCase::test_help",
"test/test_guilt.py::GitRunnerTestCase::test_get_delta_files",
"test/test_guilt.py::GitRunnerTestCase::test_get_delta_no_files",
"test/test_guilt.py::GitRunnerTestCase::test_get_git_root_exception",
"test/test_guilt.py::GitRunnerTestCase::test_populate_rev_tree",
"test/test_guilt.py::GitRunnerTestCase::test_run_git",
"test/test_guilt.py::GitRunnerTestCase::test_run_git_cwd",
"test/test_guilt.py::GitRunnerTestCase::test_run_git_exception",
"test/test_guilt.py::GitRunnerTestCase::test_run_git_no_output_error",
"test/test_guilt.py::GitRunnerTestCase::test_run_git_no_output_no_error",
"test/test_guilt.py::GitRunnerTestCase::test_run_git_non_zerp",
"test/test_guilt.py::GitRunnerTestCase::test_run_git_stderr",
"test/test_guilt.py::GitRunnerTestCase::test_version_comparison",
"test/test_guilt.py::GitRunnerTestCase::test_version_retrieval",
"test/test_guilt.py::TextBlameTests::test_blame_locs",
"test/test_guilt.py::TextBlameTests::test_blame_locs_bad_encoding",
"test/test_guilt.py::TextBlameTests::test_blame_locs_empty_file",
"test/test_guilt.py::TextBlameTests::test_blame_locs_exception",
"test/test_guilt.py::TextBlameTests::test_blame_locs_file_missing",
"test/test_guilt.py::TextBlameTests::test_text_blame_repr",
"test/test_guilt.py::BinaryBlameTests::test_bin_blame_repr",
"test/test_guilt.py::BinaryBlameTests::test_blame_bytes",
"test/test_guilt.py::BinaryBlameTests::test_blame_bytes_empty_file",
"test/test_guilt.py::BinaryBlameTests::test_blame_bytes_file_missing",
"test/test_guilt.py::BinaryBlameTests::test_blame_bytes_locs_exception",
"test/test_guilt.py::GuiltTestCase::test_file_not_in_since_rev",
"test/test_guilt.py::GuiltTestCase::test_file_not_in_until_rev",
"test/test_guilt.py::GuiltTestCase::test_map_binary_blames",
"test/test_guilt.py::GuiltTestCase::test_map_text_blames",
"test/test_guilt.py::GuiltTestCase::test_populate_trees",
"test/test_guilt.py::GuiltTestCase::test_reduce_locs",
"test/test_guilt.py::GuiltTestCase::test_show_run",
"test/test_guilt.py::FormatterTestCase::test_get_width_not_tty",
"test/test_guilt.py::FormatterTestCase::test_get_width_tty",
"test/test_guilt.py::FormatterTestCase::test_green",
"test/test_guilt.py::FormatterTestCase::test_red",
"test/test_guilt.py::FormatterTestCase::test_show_binary_guilt",
"test/test_guilt.py::FormatterTestCase::test_show_text_guilt"
] | [] | null | 181 |
|
kevin1024__vcrpy-167 | 5f8407a8a1a2ebe11aa386c7a4f13816956c419b | 2015-07-04 12:30:53 | 1660cc3a9fee71f1ef98b338609a7ae23eed90ca | Diaoul: No unit test because dict order is not deterministic.
Diaoul: More details in the commit message. | diff --git a/README.rst b/README.rst
index a5dcd90..0b85862 100644
--- a/README.rst
+++ b/README.rst
@@ -5,7 +5,6 @@ VCR.py
:alt: vcr.py
vcr.py
-
This is a Python version of `Ruby's VCR
library <https://github.com/vcr/vcr>`__.
@@ -145,7 +144,9 @@ The following options are available :
- port (the port of the server receiving the request)
- path (the path of the request)
- query (the query string of the request)
-- body (the entire request body)
+- raw\_body (the entire request body as is)
+- body (the entire request body unmarshalled by content-type
+ i.e. xmlrpc, json, form-urlencoded, falling back on raw\_body)
- headers (the headers of the request)
Backwards compatible matchers:
diff --git a/setup.py b/setup.py
index 4b8c549..eaf20c3 100644
--- a/setup.py
+++ b/setup.py
@@ -3,7 +3,6 @@
import sys
from setuptools import setup, find_packages
from setuptools.command.test import test as TestCommand
-import pkg_resources
long_description = open('README.rst', 'r').read()
@@ -21,21 +20,6 @@ class PyTest(TestCommand):
sys.exit(errno)
-install_requires=['PyYAML', 'wrapt', 'six>=1.5']
-
-
-extras_require = {
- ':python_version in "2.4, 2.5, 2.6"':
- ['contextlib2', 'backport_collections', 'mock'],
- ':python_version in "2.7, 3.1, 3.2"': ['contextlib2', 'mock'],
-}
-
-
-if 'bdist_wheel' not in sys.argv:
- for key, value in extras_require.items():
- if key.startswith(':') and pkg_resources.evaluate_marker(key[1:]):
- install_requires.extend(value)
-
setup(
name='vcrpy',
version='1.6.0',
@@ -48,8 +32,12 @@ setup(
author_email='[email protected]',
url='https://github.com/kevin1024/vcrpy',
packages=find_packages(exclude=("tests*",)),
- install_requires=install_requires,
- extras_require=extras_require,
+ install_requires=['PyYAML', 'wrapt', 'six>=1.5'],
+ extras_require = {
+ ':python_version in "2.4, 2.5, 2.6"':
+ ['contextlib2', 'backport_collections', 'mock'],
+ ':python_version in "2.7, 3.1, 3.2"': ['contextlib2', 'mock'],
+ },
license='MIT',
tests_require=['pytest', 'mock', 'pytest-localserver'],
cmdclass={'test': PyTest},
diff --git a/vcr/config.py b/vcr/config.py
index 1faef3b..7655a3a 100644
--- a/vcr/config.py
+++ b/vcr/config.py
@@ -47,6 +47,7 @@ class VCR(object):
'path': matchers.path,
'query': matchers.query,
'headers': matchers.headers,
+ 'raw_body': matchers.raw_body,
'body': matchers.body,
}
self.record_mode = record_mode
diff --git a/vcr/matchers.py b/vcr/matchers.py
index 91bce11..39c5949 100644
--- a/vcr/matchers.py
+++ b/vcr/matchers.py
@@ -1,3 +1,6 @@
+import json
+from six.moves import urllib, xmlrpc_client
+from .util import CaseInsensitiveDict, read_body
import logging
log = logging.getLogger(__name__)
@@ -30,10 +33,23 @@ def query(r1, r2):
return r1.query == r2.query
+def raw_body(r1, r2):
+ return read_body(r1) == read_body(r2)
+
+
def body(r1, r2):
- if hasattr(r1.body, 'read') and hasattr(r2.body, 'read'):
- return r1.body.read() == r2.body.read()
- return r1.body == r2.body
+ r1_body = read_body(r1)
+ r2_body = read_body(r2)
+ r1_headers = CaseInsensitiveDict(r1.headers)
+ r2_headers = CaseInsensitiveDict(r2.headers)
+ if r1_headers.get('Content-Type') == r2_headers.get('Content-Type') == 'application/x-www-form-urlencoded':
+ return urllib.parse.parse_qs(r1_body) == urllib.parse.parse_qs(r2_body)
+ if r1_headers.get('Content-Type') == r2_headers.get('Content-Type') == 'application/json':
+ return json.loads(r1_body) == json.loads(r2_body)
+ if ('xmlrpc' in r1_headers.get('User-Agent', '') and 'xmlrpc' in r2_headers.get('User-Agent', '') and
+ r1_headers.get('Content-Type') == r2_headers.get('Content-Type') == 'text/xml'):
+ return xmlrpc_client.loads(r1_body) == xmlrpc_client.loads(r2_body)
+ return r1_body == r2_body
def headers(r1, r2):
diff --git a/vcr/util.py b/vcr/util.py
index 57f72b1..8c5bd94 100644
--- a/vcr/util.py
+++ b/vcr/util.py
@@ -1,3 +1,74 @@
+import collections
+
+# Shamelessly stolen from https://github.com/kennethreitz/requests/blob/master/requests/structures.py
+class CaseInsensitiveDict(collections.MutableMapping):
+ """
+ A case-insensitive ``dict``-like object.
+ Implements all methods and operations of
+ ``collections.MutableMapping`` as well as dict's ``copy``. Also
+ provides ``lower_items``.
+ All keys are expected to be strings. The structure remembers the
+ case of the last key to be set, and ``iter(instance)``,
+ ``keys()``, ``items()``, ``iterkeys()``, and ``iteritems()``
+ will contain case-sensitive keys. However, querying and contains
+ testing is case insensitive::
+ cid = CaseInsensitiveDict()
+ cid['Accept'] = 'application/json'
+ cid['aCCEPT'] == 'application/json' # True
+ list(cid) == ['Accept'] # True
+ For example, ``headers['content-encoding']`` will return the
+ value of a ``'Content-Encoding'`` response header, regardless
+ of how the header name was originally stored.
+ If the constructor, ``.update``, or equality comparison
+ operations are given keys that have equal ``.lower()``s, the
+ behavior is undefined.
+ """
+ def __init__(self, data=None, **kwargs):
+ self._store = dict()
+ if data is None:
+ data = {}
+ self.update(data, **kwargs)
+
+ def __setitem__(self, key, value):
+ # Use the lowercased key for lookups, but store the actual
+ # key alongside the value.
+ self._store[key.lower()] = (key, value)
+
+ def __getitem__(self, key):
+ return self._store[key.lower()][1]
+
+ def __delitem__(self, key):
+ del self._store[key.lower()]
+
+ def __iter__(self):
+ return (casedkey for casedkey, mappedvalue in self._store.values())
+
+ def __len__(self):
+ return len(self._store)
+
+ def lower_items(self):
+ """Like iteritems(), but with all lowercase keys."""
+ return (
+ (lowerkey, keyval[1])
+ for (lowerkey, keyval)
+ in self._store.items()
+ )
+
+ def __eq__(self, other):
+ if isinstance(other, collections.Mapping):
+ other = CaseInsensitiveDict(other)
+ else:
+ return NotImplemented
+ # Compare insensitively
+ return dict(self.lower_items()) == dict(other.lower_items())
+
+ # Copy is required
+ def copy(self):
+ return CaseInsensitiveDict(self._store.values())
+
+ def __repr__(self):
+ return str(dict(self.items()))
+
def partition_dict(predicate, dictionary):
true_dict = {}
false_dict = {}
@@ -14,3 +85,8 @@ def compose(*functions):
res = function(res)
return res
return composed
+
+def read_body(request):
+ if hasattr(request.body, 'read'):
+ return request.body.read()
+ return request.body
| Error with body matcher for json, xmlrpc and form urlencoded
This is a tricky issue I encountered when using the body matcher on xmlrpc requests.
Symptoms: Sometimes the request won't match, sometimes it will, and this only affects certain requests. This occurs on Python 3.4 and I believe other python 3 versions but not on 2.7
Cause: An XMLRPC request has a body with XML inside which is generated from the parameters passed to the function call. Some parameters can be of dict type. xmlrpclib (or xmlrpc.client) will loop over items of the dict and generate the appropriate XML which will be the body of our POST request. Now items order is not guaranteed in dict and the behavior changed in python 3 such that the order of the same dict *can change anytime* and is not *more or less constant on the same computer* as in python 2. So the generated XML won't be necessarily the same as the one you recorded.
Fix suggestion: A custom xmlrpc body matcher that takes that into account and will compare the `struct` XML elements in the correct order.
The gzip compression didn't help me debuging this as I couldn't even read directly the cassettes... | kevin1024/vcrpy | diff --git a/tests/unit/test_matchers.py b/tests/unit/test_matchers.py
index f942bd2..d4b32de 100644
--- a/tests/unit/test_matchers.py
+++ b/tests/unit/test_matchers.py
@@ -35,6 +35,38 @@ def test_uri_matcher():
assert matched
+def test_body_matcher():
+ # raw
+ req1 = request.Request('POST', 'http://host.com/', '123', {})
+ req2 = request.Request('POST', 'http://another-host.com/', '123', {'Some-Header': 'value'})
+ assert matchers.body(req1, req2)
+
+ # application/x-www-form-urlencoded
+ req1 = request.Request('POST', 'http://host.com/', 'a=1&b=2', {'Content-Type': 'application/x-www-form-urlencoded'})
+ req2 = request.Request('POST', 'http://host.com/', 'b=2&a=1', {'Content-Type': 'application/x-www-form-urlencoded'})
+ assert matchers.body(req1, req2)
+
+ # application/json
+ req1 = request.Request('POST', 'http://host.com/', '{"a": 1, "b": 2}', {'Content-Type': 'application/json'})
+ req2 = request.Request('POST', 'http://host.com/', '{"b": 2, "a": 1}', {'content-type': 'application/json'})
+ assert matchers.body(req1, req2)
+
+ # xmlrpc
+ req1_body = (b"<?xml version='1.0'?><methodCall><methodName>test</methodName>"
+ b"<params><param><value><array><data><value><struct>"
+ b"<member><name>a</name><value><string>1</string></value></member>"
+ b"<member><name>b</name><value><string>2</string></value></member>"
+ b"</struct></value></data></array></value></param></params></methodCall>")
+ req2_body = (b"<?xml version='1.0'?><methodCall><methodName>test</methodName>"
+ b"<params><param><value><array><data><value><struct>"
+ b"<member><name>b</name><value><string>2</string></value></member>"
+ b"<member><name>a</name><value><string>1</string></value></member>"
+ b"</struct></value></data></array></value></param></params></methodCall>")
+ req1 = request.Request('POST', 'http://host.com/', req1_body, {'User-Agent': 'xmlrpclib', 'Content-Type': 'text/xml'})
+ req2 = request.Request('POST', 'http://host.com/', req2_body, {'user-agent': 'somexmlrpc', 'content-type': 'text/xml'})
+ assert matchers.body(req1, req2)
+
+
def test_query_matcher():
req1 = request.Request('GET', 'http://host.com/?a=b&c=d', '', {})
req2 = request.Request('GET', 'http://host.com/?c=d&a=b', '', {})
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 2,
"issue_text_score": 1,
"test_score": 2
},
"num_modified_files": 5
} | 1.6 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "pytest",
"pip_packages": [
"pytest",
"pytest-localserver",
"mock"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.7",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | attrs @ file:///croot/attrs_1668696182826/work
certifi @ file:///croot/certifi_1671487769961/work/certifi
flit_core @ file:///opt/conda/conda-bld/flit-core_1644941570762/work/source/flit_core
importlib-metadata @ file:///tmp/build/80754af9/importlib-metadata_1648562407465/work
iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work
MarkupSafe==2.1.5
mock==5.2.0
packaging @ file:///croot/packaging_1671697413597/work
pluggy @ file:///tmp/build/80754af9/pluggy_1648042572264/work
py @ file:///opt/conda/conda-bld/py_1644396412707/work
pytest==7.1.2
pytest-localserver==0.9.0.post0
PyYAML==6.0.1
six==1.17.0
tomli @ file:///opt/conda/conda-bld/tomli_1657175507142/work
typing_extensions @ file:///croot/typing_extensions_1669924550328/work
-e git+https://github.com/kevin1024/vcrpy.git@5f8407a8a1a2ebe11aa386c7a4f13816956c419b#egg=vcrpy
Werkzeug==2.2.3
wrapt==1.16.0
zipp @ file:///croot/zipp_1672387121353/work
| name: vcrpy
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- attrs=22.1.0=py37h06a4308_0
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2022.12.7=py37h06a4308_0
- flit-core=3.6.0=pyhd3eb1b0_0
- importlib-metadata=4.11.3=py37h06a4308_0
- importlib_metadata=4.11.3=hd3eb1b0_0
- iniconfig=1.1.1=pyhd3eb1b0_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- packaging=22.0=py37h06a4308_0
- pip=22.3.1=py37h06a4308_0
- pluggy=1.0.0=py37h06a4308_1
- py=1.11.0=pyhd3eb1b0_0
- pytest=7.1.2=py37h06a4308_0
- python=3.7.16=h7a1cb2a_0
- readline=8.2=h5eee18b_0
- setuptools=65.6.3=py37h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- tomli=2.0.1=py37h06a4308_0
- typing_extensions=4.4.0=py37h06a4308_0
- wheel=0.38.4=py37h06a4308_0
- xz=5.6.4=h5eee18b_1
- zipp=3.11.0=py37h06a4308_0
- zlib=1.2.13=h5eee18b_1
- pip:
- markupsafe==2.1.5
- mock==5.2.0
- pytest-localserver==0.9.0.post0
- pyyaml==6.0.1
- six==1.17.0
- werkzeug==2.2.3
- wrapt==1.16.0
prefix: /opt/conda/envs/vcrpy
| [
"tests/unit/test_matchers.py::test_body_matcher"
] | [] | [
"tests/unit/test_matchers.py::test_uri_matcher",
"tests/unit/test_matchers.py::test_query_matcher",
"tests/unit/test_matchers.py::test_metchers"
] | [] | MIT License | 182 |
imageio__imageio-98 | d99d9a25cd8db0920d42cf5d3f372471776865fe | 2015-07-04 20:48:09 | 1f53bf2d5794079c9300a3bb46a1adbc5889de59 | diff --git a/imageio/plugins/__init__.py b/imageio/plugins/__init__.py
index 4e0074c..4ee8062 100644
--- a/imageio/plugins/__init__.py
+++ b/imageio/plugins/__init__.py
@@ -78,6 +78,7 @@ For the Format.Writer class:
"""
+from . import tifffile # noqa
from . import freeimage # noqa
from . import freeimagemulti # noqa
from . import example # noqa
diff --git a/imageio/plugins/_tifffile.py b/imageio/plugins/_tifffile.py
new file mode 100644
index 0000000..9ccacbe
--- /dev/null
+++ b/imageio/plugins/_tifffile.py
@@ -0,0 +1,4808 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+# tifffile.py
+
+# Copyright (c) 2008-2014, Christoph Gohlke
+# Copyright (c) 2008-2014, The Regents of the University of California
+# Produced at the Laboratory for Fluorescence Dynamics
+# All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions are met:
+#
+# * Redistributions of source code must retain the above copyright
+# notice, this list of conditions and the following disclaimer.
+# * Redistributions in binary form must reproduce the above copyright
+# notice, this list of conditions and the following disclaimer in the
+# documentation and/or other materials provided with the distribution.
+# * Neither the name of the copyright holders nor the names of any
+# contributors may be used to endorse or promote products derived
+# from this software without specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
+# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+# POSSIBILITY OF SUCH DAMAGE.
+
+"""Read and write image data from and to TIFF files.
+
+Image and metadata can be read from TIFF, BigTIFF, OME-TIFF, STK, LSM, NIH,
+SGI, ImageJ, MicroManager, FluoView, SEQ and GEL files.
+Only a subset of the TIFF specification is supported, mainly uncompressed
+and losslessly compressed 2**(0 to 6) bit integer, 16, 32 and 64-bit float,
+grayscale and RGB(A) images, which are commonly used in bio-scientific imaging.
+Specifically, reading JPEG and CCITT compressed image data or EXIF, IPTC, GPS,
+and XMP metadata is not implemented.
+Only primary info records are read for STK, FluoView, MicroManager, and
+NIH image formats.
+
+TIFF, the Tagged Image File Format, is under the control of Adobe Systems.
+BigTIFF allows for files greater than 4 GB. STK, LSM, FluoView, SGI, SEQ, GEL,
+and OME-TIFF, are custom extensions defined by Molecular Devices (Universal
+Imaging Corporation), Carl Zeiss MicroImaging, Olympus, Silicon Graphics
+International, Media Cybernetics, Molecular Dynamics, and the Open Microscopy
+Environment consortium respectively.
+
+For command line usage run ``python tifffile.py --help``
+
+:Author:
+ `Christoph Gohlke <http://www.lfd.uci.edu/~gohlke/>`_
+
+:Organization:
+ Laboratory for Fluorescence Dynamics, University of California, Irvine
+
+:Version: 2014.08.24
+
+Requirements
+------------
+* `CPython 2.7 or 3.4 <http://www.python.org>`_
+* `Numpy 1.8.2 <http://www.numpy.org>`_
+* `Matplotlib 1.4 <http://www.matplotlib.org>`_ (optional for plotting)
+* `Tifffile.c 2013.11.05 <http://www.lfd.uci.edu/~gohlke/>`_
+ (recommended for faster decoding of PackBits and LZW encoded strings)
+
+Notes
+-----
+The API is not stable yet and might change between revisions.
+
+Tested on little-endian platforms only.
+
+Other Python packages and modules for reading bio-scientific TIFF files:
+
+* `Imread <http://luispedro.org/software/imread>`_
+* `PyLibTiff <http://code.google.com/p/pylibtiff>`_
+* `SimpleITK <http://www.simpleitk.org>`_
+* `PyLSM <https://launchpad.net/pylsm>`_
+* `PyMca.TiffIO.py <http://pymca.sourceforge.net/>`_ (same as fabio.TiffIO)
+* `BioImageXD.Readers <http://www.bioimagexd.net/>`_
+* `Cellcognition.io <http://cellcognition.org/>`_
+* `CellProfiler.bioformats
+ <https://github.com/CellProfiler/python-bioformats>`_
+
+Acknowledgements
+----------------
+* Egor Zindy, University of Manchester, for cz_lsm_scan_info specifics.
+* Wim Lewis for a bug fix and some read_cz_lsm functions.
+* Hadrien Mary for help on reading MicroManager files.
+
+References
+----------
+(1) TIFF 6.0 Specification and Supplements. Adobe Systems Incorporated.
+ http://partners.adobe.com/public/developer/tiff/
+(2) TIFF File Format FAQ. http://www.awaresystems.be/imaging/tiff/faq.html
+(3) MetaMorph Stack (STK) Image File Format.
+ http://support.meta.moleculardevices.com/docs/t10243.pdf
+(4) Image File Format Description LSM 5/7 Release 6.0 (ZEN 2010).
+ Carl Zeiss MicroImaging GmbH. BioSciences. May 10, 2011
+(5) File Format Description - LSM 5xx Release 2.0.
+ http://ibb.gsf.de/homepage/karsten.rodenacker/IDL/Lsmfile.doc
+(6) The OME-TIFF format.
+ http://www.openmicroscopy.org/site/support/file-formats/ome-tiff
+(7) UltraQuant(r) Version 6.0 for Windows Start-Up Guide.
+ http://www.ultralum.com/images%20ultralum/pdf/UQStart%20Up%20Guide.pdf
+(8) Micro-Manager File Formats.
+ http://www.micro-manager.org/wiki/Micro-Manager_File_Formats
+(9) Tags for TIFF and Related Specifications. Digital Preservation.
+ http://www.digitalpreservation.gov/formats/content/tiff_tags.shtml
+
+Examples
+--------
+>>> data = numpy.random.rand(5, 301, 219)
+>>> imsave('temp.tif', data)
+
+>>> image = imread('temp.tif')
+>>> numpy.testing.assert_array_equal(image, data)
+
+>>> with TiffFile('temp.tif') as tif:
+... images = tif.asarray()
+... for page in tif:
+... for tag in page.tags.values():
+... t = tag.name, tag.value
+... image = page.asarray()
+
+"""
+
+from __future__ import division, print_function
+
+import sys
+import os
+import re
+import glob
+import math
+import zlib
+import time
+import json
+import struct
+import warnings
+import tempfile
+import datetime
+import collections
+from fractions import Fraction
+from xml.etree import cElementTree as etree
+
+import numpy
+
+__version__ = '2014.08.24'
+__docformat__ = 'restructuredtext en'
+__all__ = ('imsave', 'imread', 'imshow', 'TiffFile', 'TiffWriter',
+ 'TiffSequence')
+
+
+def imsave(filename, data, **kwargs):
+ """Write image data to TIFF file.
+
+ Refer to the TiffWriter class and member functions for documentation.
+
+ Parameters
+ ----------
+ filename : str
+ Name of file to write.
+ data : array_like
+ Input image. The last dimensions are assumed to be image depth,
+ height, width, and samples.
+ kwargs : dict
+ Parameters 'byteorder', 'bigtiff', and 'software' are passed to
+ the TiffWriter class.
+ Parameters 'photometric', 'planarconfig', 'resolution',
+ 'description', 'compress', 'volume', and 'extratags' are passed to
+ the TiffWriter.save function.
+
+ Examples
+ --------
+ >>> data = numpy.random.rand(2, 5, 3, 301, 219)
+ >>> description = u'{"shape": %s}' % str(list(data.shape))
+ >>> imsave('temp.tif', data, compress=6,
+ ... extratags=[(270, 's', 0, description, True)])
+
+ """
+ tifargs = {}
+ for key in ('byteorder', 'bigtiff', 'software', 'writeshape'):
+ if key in kwargs:
+ tifargs[key] = kwargs[key]
+ del kwargs[key]
+
+ if 'writeshape' not in kwargs:
+ kwargs['writeshape'] = True
+ if 'bigtiff' not in tifargs and data.size*data.dtype.itemsize > 2000*2**20:
+ tifargs['bigtiff'] = True
+
+ with TiffWriter(filename, **tifargs) as tif:
+ tif.save(data, **kwargs)
+
+
+class TiffWriter(object):
+ """Write image data to TIFF file.
+
+ TiffWriter instances must be closed using the close method, which is
+ automatically called when using the 'with' statement.
+
+ Examples
+ --------
+ >>> data = numpy.random.rand(2, 5, 3, 301, 219)
+ >>> with TiffWriter('temp.tif', bigtiff=True) as tif:
+ ... for i in range(data.shape[0]):
+ ... tif.save(data[i], compress=6)
+
+ """
+ TYPES = {'B': 1, 's': 2, 'H': 3, 'I': 4, '2I': 5, 'b': 6,
+ 'h': 8, 'i': 9, 'f': 11, 'd': 12, 'Q': 16, 'q': 17}
+ TAGS = {
+ 'new_subfile_type': 254, 'subfile_type': 255,
+ 'image_width': 256, 'image_length': 257, 'bits_per_sample': 258,
+ 'compression': 259, 'photometric': 262, 'fill_order': 266,
+ 'document_name': 269, 'image_description': 270, 'strip_offsets': 273,
+ 'orientation': 274, 'samples_per_pixel': 277, 'rows_per_strip': 278,
+ 'strip_byte_counts': 279, 'x_resolution': 282, 'y_resolution': 283,
+ 'planar_configuration': 284, 'page_name': 285, 'resolution_unit': 296,
+ 'software': 305, 'datetime': 306, 'predictor': 317, 'color_map': 320,
+ 'tile_width': 322, 'tile_length': 323, 'tile_offsets': 324,
+ 'tile_byte_counts': 325, 'extra_samples': 338, 'sample_format': 339,
+ 'image_depth': 32997, 'tile_depth': 32998}
+
+ def __init__(self, filename, bigtiff=False, byteorder=None,
+ software='tifffile.py'):
+ """Create a new TIFF file for writing.
+
+ Use bigtiff=True when creating files greater than 2 GB.
+
+ Parameters
+ ----------
+ filename : str
+ Name of file to write.
+ bigtiff : bool
+ If True, the BigTIFF format is used.
+ byteorder : {'<', '>'}
+ The endianness of the data in the file.
+ By default this is the system's native byte order.
+ software : str
+ Name of the software used to create the image.
+ Saved with the first page only.
+
+ """
+ if byteorder not in (None, '<', '>'):
+ raise ValueError("invalid byteorder %s" % byteorder)
+ if byteorder is None:
+ byteorder = '<' if sys.byteorder == 'little' else '>'
+
+ self._byteorder = byteorder
+ self._software = software
+
+ self._fh = open(filename, 'wb')
+ self._fh.write({'<': b'II', '>': b'MM'}[byteorder])
+
+ if bigtiff:
+ self._bigtiff = True
+ self._offset_size = 8
+ self._tag_size = 20
+ self._numtag_format = 'Q'
+ self._offset_format = 'Q'
+ self._val_format = '8s'
+ self._fh.write(struct.pack(byteorder+'HHH', 43, 8, 0))
+ else:
+ self._bigtiff = False
+ self._offset_size = 4
+ self._tag_size = 12
+ self._numtag_format = 'H'
+ self._offset_format = 'I'
+ self._val_format = '4s'
+ self._fh.write(struct.pack(byteorder+'H', 42))
+
+ # first IFD
+ self._ifd_offset = self._fh.tell()
+ self._fh.write(struct.pack(byteorder+self._offset_format, 0))
+
+ def save(self, data, photometric=None, planarconfig=None, resolution=None,
+ description=None, volume=False, writeshape=False, compress=0,
+ extratags=()):
+ """Write image data to TIFF file.
+
+ Image data are written in one stripe per plane.
+ Dimensions larger than 2 to 4 (depending on photometric mode, planar
+ configuration, and SGI mode) are flattened and saved as separate pages.
+ The 'sample_format' and 'bits_per_sample' TIFF tags are derived from
+ the data type.
+
+ Parameters
+ ----------
+ data : array_like
+ Input image. The last dimensions are assumed to be image depth,
+ height, width, and samples.
+ photometric : {'minisblack', 'miniswhite', 'rgb'}
+ The color space of the image data.
+ By default this setting is inferred from the data shape.
+ planarconfig : {'contig', 'planar'}
+ Specifies if samples are stored contiguous or in separate planes.
+ By default this setting is inferred from the data shape.
+ 'contig': last dimension contains samples.
+ 'planar': third last dimension contains samples.
+ resolution : (float, float) or ((int, int), (int, int))
+ X and Y resolution in dots per inch as float or rational numbers.
+ description : str
+ The subject of the image. Saved with the first page only.
+ compress : int
+ Values from 0 to 9 controlling the level of zlib compression.
+ If 0, data are written uncompressed (default).
+ volume : bool
+ If True, volume data are stored in one tile (if applicable) using
+ the SGI image_depth and tile_depth tags.
+ Image width and depth must be multiple of 16.
+ Few software can read this format, e.g. MeVisLab.
+ writeshape : bool
+ If True, write the data shape to the image_description tag
+ if necessary and no other description is given.
+ extratags: sequence of tuples
+ Additional tags as [(code, dtype, count, value, writeonce)].
+
+ code : int
+ The TIFF tag Id.
+ dtype : str
+ Data type of items in 'value' in Python struct format.
+ One of B, s, H, I, 2I, b, h, i, f, d, Q, or q.
+ count : int
+ Number of data values. Not used for string values.
+ value : sequence
+ 'Count' values compatible with 'dtype'.
+ writeonce : bool
+ If True, the tag is written to the first page only.
+
+ """
+ if photometric not in (None, 'minisblack', 'miniswhite', 'rgb'):
+ raise ValueError("invalid photometric %s" % photometric)
+ if planarconfig not in (None, 'contig', 'planar'):
+ raise ValueError("invalid planarconfig %s" % planarconfig)
+ if not 0 <= compress <= 9:
+ raise ValueError("invalid compression level %s" % compress)
+
+ fh = self._fh
+ byteorder = self._byteorder
+ numtag_format = self._numtag_format
+ val_format = self._val_format
+ offset_format = self._offset_format
+ offset_size = self._offset_size
+ tag_size = self._tag_size
+
+ data = numpy.asarray(data, dtype=byteorder+data.dtype.char, order='C')
+ data_shape = shape = data.shape
+ data = numpy.atleast_2d(data)
+
+ # normalize shape of data
+ samplesperpixel = 1
+ extrasamples = 0
+ if volume and data.ndim < 3:
+ volume = False
+ if photometric is None:
+ if planarconfig:
+ photometric = 'rgb'
+ elif data.ndim > 2 and shape[-1] in (3, 4):
+ photometric = 'rgb'
+ elif volume and data.ndim > 3 and shape[-4] in (3, 4):
+ photometric = 'rgb'
+ elif data.ndim > 2 and shape[-3] in (3, 4):
+ photometric = 'rgb'
+ else:
+ photometric = 'minisblack'
+ if planarconfig and len(shape) <= (3 if volume else 2):
+ planarconfig = None
+ photometric = 'minisblack'
+ if photometric == 'rgb':
+ if len(shape) < 3:
+ raise ValueError("not a RGB(A) image")
+ if len(shape) < 4:
+ volume = False
+ if planarconfig is None:
+ if shape[-1] in (3, 4):
+ planarconfig = 'contig'
+ elif shape[-4 if volume else -3] in (3, 4):
+ planarconfig = 'planar'
+ elif shape[-1] > shape[-4 if volume else -3]:
+ planarconfig = 'planar'
+ else:
+ planarconfig = 'contig'
+ if planarconfig == 'contig':
+ data = data.reshape((-1, 1) + shape[(-4 if volume else -3):])
+ samplesperpixel = data.shape[-1]
+ else:
+ data = data.reshape(
+ (-1,) + shape[(-4 if volume else -3):] + (1,))
+ samplesperpixel = data.shape[1]
+ if samplesperpixel > 3:
+ extrasamples = samplesperpixel - 3
+ elif planarconfig and len(shape) > (3 if volume else 2):
+ if planarconfig == 'contig':
+ data = data.reshape((-1, 1) + shape[(-4 if volume else -3):])
+ samplesperpixel = data.shape[-1]
+ else:
+ data = data.reshape(
+ (-1,) + shape[(-4 if volume else -3):] + (1,))
+ samplesperpixel = data.shape[1]
+ extrasamples = samplesperpixel - 1
+ else:
+ planarconfig = None
+ # remove trailing 1s
+ while len(shape) > 2 and shape[-1] == 1:
+ shape = shape[:-1]
+ if len(shape) < 3:
+ volume = False
+ if False and (
+ len(shape) > (3 if volume else 2) and shape[-1] < 5 and
+ all(shape[-1] < i
+ for i in shape[(-4 if volume else -3):-1])):
+ # DISABLED: non-standard TIFF, e.g. (220, 320, 2)
+ planarconfig = 'contig'
+ samplesperpixel = shape[-1]
+ data = data.reshape((-1, 1) + shape[(-4 if volume else -3):])
+ else:
+ data = data.reshape(
+ (-1, 1) + shape[(-3 if volume else -2):] + (1,))
+
+ if samplesperpixel == 2:
+ warnings.warn("writing non-standard TIFF (samplesperpixel 2)")
+
+ if volume and (data.shape[-2] % 16 or data.shape[-3] % 16):
+ warnings.warn("volume width or length are not multiple of 16")
+ volume = False
+ data = numpy.swapaxes(data, 1, 2)
+ data = data.reshape(
+ (data.shape[0] * data.shape[1],) + data.shape[2:])
+
+ # data.shape is now normalized 5D or 6D, depending on volume
+ # (pages, planar_samples, (depth,) height, width, contig_samples)
+ assert len(data.shape) in (5, 6)
+ shape = data.shape
+
+ bytestr = bytes if sys.version[0] == '2' else (
+ lambda x: bytes(x, 'utf-8') if isinstance(x, str) else x)
+ tags = [] # list of (code, ifdentry, ifdvalue, writeonce)
+
+ if volume:
+ # use tiles to save volume data
+ tag_byte_counts = TiffWriter.TAGS['tile_byte_counts']
+ tag_offsets = TiffWriter.TAGS['tile_offsets']
+ else:
+ # else use strips
+ tag_byte_counts = TiffWriter.TAGS['strip_byte_counts']
+ tag_offsets = TiffWriter.TAGS['strip_offsets']
+
+ def pack(fmt, *val):
+ return struct.pack(byteorder+fmt, *val)
+
+ def addtag(code, dtype, count, value, writeonce=False):
+ # Compute ifdentry & ifdvalue bytes from code, dtype, count, value.
+ # Append (code, ifdentry, ifdvalue, writeonce) to tags list.
+ code = int(TiffWriter.TAGS.get(code, code))
+ try:
+ tifftype = TiffWriter.TYPES[dtype]
+ except KeyError:
+ raise ValueError("unknown dtype %s" % dtype)
+ rawcount = count
+ if dtype == 's':
+ value = bytestr(value) + b'\0'
+ count = rawcount = len(value)
+ value = (value, )
+ if len(dtype) > 1:
+ count *= int(dtype[:-1])
+ dtype = dtype[-1]
+ ifdentry = [pack('HH', code, tifftype),
+ pack(offset_format, rawcount)]
+ ifdvalue = None
+ if count == 1:
+ if isinstance(value, (tuple, list)):
+ value = value[0]
+ ifdentry.append(pack(val_format, pack(dtype, value)))
+ elif struct.calcsize(dtype) * count <= offset_size:
+ ifdentry.append(pack(val_format,
+ pack(str(count)+dtype, *value)))
+ else:
+ ifdentry.append(pack(offset_format, 0))
+ ifdvalue = pack(str(count)+dtype, *value)
+ tags.append((code, b''.join(ifdentry), ifdvalue, writeonce))
+
+ def rational(arg, max_denominator=1000000):
+ # return nominator and denominator from float or two integers
+ try:
+ f = Fraction.from_float(arg)
+ except TypeError:
+ f = Fraction(arg[0], arg[1])
+ f = f.limit_denominator(max_denominator)
+ return f.numerator, f.denominator
+
+ if self._software:
+ addtag('software', 's', 0, self._software, writeonce=True)
+ self._software = None # only save to first page
+ if description:
+ addtag('image_description', 's', 0, description, writeonce=True)
+ elif writeshape and shape[0] > 1 and shape != data_shape:
+ addtag('image_description', 's', 0,
+ "shape=(%s)" % (",".join('%i' % i for i in data_shape)),
+ writeonce=True)
+ addtag('datetime', 's', 0,
+ datetime.datetime.now().strftime("%Y:%m:%d %H:%M:%S"),
+ writeonce=True)
+ addtag('compression', 'H', 1, 32946 if compress else 1)
+ addtag('orientation', 'H', 1, 1)
+ addtag('image_width', 'I', 1, shape[-2])
+ addtag('image_length', 'I', 1, shape[-3])
+ if volume:
+ addtag('image_depth', 'I', 1, shape[-4])
+ addtag('tile_depth', 'I', 1, shape[-4])
+ addtag('tile_width', 'I', 1, shape[-2])
+ addtag('tile_length', 'I', 1, shape[-3])
+ addtag('new_subfile_type', 'I', 1, 0 if shape[0] == 1 else 2)
+ addtag('sample_format', 'H', 1,
+ {'u': 1, 'i': 2, 'f': 3, 'c': 6}[data.dtype.kind])
+ addtag('photometric', 'H', 1,
+ {'miniswhite': 0, 'minisblack': 1, 'rgb': 2}[photometric])
+ addtag('samples_per_pixel', 'H', 1, samplesperpixel)
+ if planarconfig and samplesperpixel > 1:
+ addtag('planar_configuration', 'H', 1, 1
+ if planarconfig == 'contig' else 2)
+ addtag('bits_per_sample', 'H', samplesperpixel,
+ (data.dtype.itemsize * 8, ) * samplesperpixel)
+ else:
+ addtag('bits_per_sample', 'H', 1, data.dtype.itemsize * 8)
+ if extrasamples:
+ if photometric == 'rgb' and extrasamples == 1:
+ addtag('extra_samples', 'H', 1, 1) # associated alpha channel
+ else:
+ addtag('extra_samples', 'H', extrasamples, (0,) * extrasamples)
+ if resolution:
+ addtag('x_resolution', '2I', 1, rational(resolution[0]))
+ addtag('y_resolution', '2I', 1, rational(resolution[1]))
+ addtag('resolution_unit', 'H', 1, 2)
+ addtag('rows_per_strip', 'I', 1,
+ shape[-3] * (shape[-4] if volume else 1))
+
+ # use one strip or tile per plane
+ strip_byte_counts = (data[0, 0].size * data.dtype.itemsize,) * shape[1]
+ addtag(tag_byte_counts, offset_format, shape[1], strip_byte_counts)
+ addtag(tag_offsets, offset_format, shape[1], (0, ) * shape[1])
+
+ # add extra tags from users
+ for t in extratags:
+ addtag(*t)
+ # the entries in an IFD must be sorted in ascending order by tag code
+ tags = sorted(tags, key=lambda x: x[0])
+
+ if not self._bigtiff and (fh.tell() + data.size*data.dtype.itemsize
+ > 2**31-1):
+ raise ValueError("data too large for non-bigtiff file")
+
+ for pageindex in range(shape[0]):
+ # update pointer at ifd_offset
+ pos = fh.tell()
+ fh.seek(self._ifd_offset)
+ fh.write(pack(offset_format, pos))
+ fh.seek(pos)
+
+ # write ifdentries
+ fh.write(pack(numtag_format, len(tags)))
+ tag_offset = fh.tell()
+ fh.write(b''.join(t[1] for t in tags))
+ self._ifd_offset = fh.tell()
+ fh.write(pack(offset_format, 0)) # offset to next IFD
+
+ # write tag values and patch offsets in ifdentries, if necessary
+ for tagindex, tag in enumerate(tags):
+ if tag[2]:
+ pos = fh.tell()
+ fh.seek(tag_offset + tagindex*tag_size + offset_size + 4)
+ fh.write(pack(offset_format, pos))
+ fh.seek(pos)
+ if tag[0] == tag_offsets:
+ strip_offsets_offset = pos
+ elif tag[0] == tag_byte_counts:
+ strip_byte_counts_offset = pos
+ fh.write(tag[2])
+
+ # write image data
+ data_offset = fh.tell()
+ if compress:
+ strip_byte_counts = []
+ for plane in data[pageindex]:
+ plane = zlib.compress(plane, compress)
+ strip_byte_counts.append(len(plane))
+ fh.write(plane)
+ else:
+ # if this fails try update Python/numpy
+ data[pageindex].tofile(fh)
+ fh.flush()
+
+ # update strip and tile offsets and byte_counts if necessary
+ pos = fh.tell()
+ for tagindex, tag in enumerate(tags):
+ if tag[0] == tag_offsets: # strip or tile offsets
+ if tag[2]:
+ fh.seek(strip_offsets_offset)
+ strip_offset = data_offset
+ for size in strip_byte_counts:
+ fh.write(pack(offset_format, strip_offset))
+ strip_offset += size
+ else:
+ fh.seek(tag_offset + tagindex*tag_size +
+ offset_size + 4)
+ fh.write(pack(offset_format, data_offset))
+ elif tag[0] == tag_byte_counts: # strip or tile byte_counts
+ if compress:
+ if tag[2]:
+ fh.seek(strip_byte_counts_offset)
+ for size in strip_byte_counts:
+ fh.write(pack(offset_format, size))
+ else:
+ fh.seek(tag_offset + tagindex*tag_size +
+ offset_size + 4)
+ fh.write(pack(offset_format, strip_byte_counts[0]))
+ break
+ fh.seek(pos)
+ fh.flush()
+ # remove tags that should be written only once
+ if pageindex == 0:
+ tags = [t for t in tags if not t[-1]]
+
+ def close(self):
+ self._fh.close()
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, exc_type, exc_value, traceback):
+ self.close()
+
+
+def imread(files, **kwargs):
+ """Return image data from TIFF file(s) as numpy array.
+
+ The first image series is returned if no arguments are provided.
+
+ Parameters
+ ----------
+ files : str or list
+ File name, glob pattern, or list of file names.
+ key : int, slice, or sequence of page indices
+ Defines which pages to return as array.
+ series : int
+ Defines which series of pages in file to return as array.
+ multifile : bool
+ If True (default), OME-TIFF data may include pages from multiple files.
+ pattern : str
+ Regular expression pattern that matches axes names and indices in
+ file names.
+ kwargs : dict
+ Additional parameters passed to the TiffFile or TiffSequence asarray
+ function.
+
+ Examples
+ --------
+ >>> im = imread('test.tif', key=0) # doctest: +SKIP
+ >>> im.shape # doctest: +SKIP
+ (256, 256, 4)
+ >>> ims = imread(['test.tif', 'test.tif']) # doctest: +SKIP
+ >>> ims.shape # doctest: +SKIP
+ (2, 256, 256, 4)
+
+ """
+ kwargs_file = {}
+ if 'multifile' in kwargs:
+ kwargs_file['multifile'] = kwargs['multifile']
+ del kwargs['multifile']
+ else:
+ kwargs_file['multifile'] = True
+ kwargs_seq = {}
+ if 'pattern' in kwargs:
+ kwargs_seq['pattern'] = kwargs['pattern']
+ del kwargs['pattern']
+
+ if isinstance(files, basestring) and any(i in files for i in '?*'):
+ files = glob.glob(files)
+ if not files:
+ raise ValueError('no files found')
+ if len(files) == 1:
+ files = files[0]
+
+ if isinstance(files, basestring):
+ with TiffFile(files, **kwargs_file) as tif:
+ return tif.asarray(**kwargs)
+ else:
+ with TiffSequence(files, **kwargs_seq) as imseq:
+ return imseq.asarray(**kwargs)
+
+
+class lazyattr(object):
+ """Lazy object attribute whose value is computed on first access."""
+ __slots__ = ('func', )
+
+ def __init__(self, func):
+ self.func = func
+
+ def __get__(self, instance, owner):
+ if instance is None:
+ return self
+ value = self.func(instance)
+ if value is NotImplemented:
+ return getattr(super(owner, instance), self.func.__name__)
+ setattr(instance, self.func.__name__, value)
+ return value
+
+
+class TiffFile(object):
+ """Read image and metadata from TIFF, STK, LSM, and FluoView files.
+
+ TiffFile instances must be closed using the close method, which is
+ automatically called when using the 'with' statement.
+
+ Attributes
+ ----------
+ pages : list
+ All TIFF pages in file.
+ series : list of Records(shape, dtype, axes, TiffPages)
+ TIFF pages with compatible shapes and types.
+ micromanager_metadata: dict
+ Extra MicroManager non-TIFF metadata in the file, if exists.
+
+ All attributes are read-only.
+
+ Examples
+ --------
+ >>> with TiffFile('test.tif') as tif: # doctest: +SKIP
+ ... data = tif.asarray()
+ ... data.shape
+ (256, 256, 4)
+
+ """
+ def __init__(self, arg, name=None, offset=None, size=None,
+ multifile=True, multifile_close=True):
+ """Initialize instance from file.
+
+ Parameters
+ ----------
+ arg : str or open file
+ Name of file or open file object.
+ The file objects are closed in TiffFile.close().
+ name : str
+ Optional name of file in case 'arg' is a file handle.
+ offset : int
+ Optional start position of embedded file. By default this is
+ the current file position.
+ size : int
+ Optional size of embedded file. By default this is the number
+ of bytes from the 'offset' to the end of the file.
+ multifile : bool
+ If True (default), series may include pages from multiple files.
+ Currently applies to OME-TIFF only.
+ multifile_close : bool
+ If True (default), keep the handles of other files in multifile
+ series closed. This is inefficient when few files refer to
+ many pages. If False, the C runtime may run out of resources.
+
+ """
+ self._fh = FileHandle(arg, name=name, offset=offset, size=size)
+ self.offset_size = None
+ self.pages = []
+ self._multifile = bool(multifile)
+ self._multifile_close = bool(multifile_close)
+ self._files = {self._fh.name: self} # cache of TiffFiles
+ try:
+ self._fromfile()
+ except Exception:
+ self._fh.close()
+ raise
+
+ @property
+ def filehandle(self):
+ """Return file handle."""
+ return self._fh
+
+ @property
+ def filename(self):
+ """Return name of file handle."""
+ return self._fh.name
+
+ def close(self):
+ """Close open file handle(s)."""
+ for tif in self._files.values():
+ tif._fh.close()
+ self._files = {}
+
+ def _fromfile(self):
+ """Read TIFF header and all page records from file."""
+ self._fh.seek(0)
+ try:
+ self.byteorder = {b'II': '<', b'MM': '>'}[self._fh.read(2)]
+ except KeyError:
+ raise ValueError("not a valid TIFF file")
+ version = struct.unpack(self.byteorder+'H', self._fh.read(2))[0]
+ if version == 43: # BigTiff
+ self.offset_size, zero = struct.unpack(self.byteorder+'HH',
+ self._fh.read(4))
+ if zero or self.offset_size != 8:
+ raise ValueError("not a valid BigTIFF file")
+ elif version == 42:
+ self.offset_size = 4
+ else:
+ raise ValueError("not a TIFF file")
+ self.pages = []
+ while True:
+ try:
+ page = TiffPage(self)
+ self.pages.append(page)
+ except StopIteration:
+ break
+ if not self.pages:
+ raise ValueError("empty TIFF file")
+
+ if self.is_micromanager:
+ # MicroManager files contain metadata not stored in TIFF tags.
+ self.micromanager_metadata = read_micromanager_metadata(self._fh)
+
+ if self.is_lsm:
+ self._fix_lsm_strip_offsets()
+ self._fix_lsm_strip_byte_counts()
+
+ def _fix_lsm_strip_offsets(self):
+ """Unwrap strip offsets for LSM files greater than 4 GB."""
+ for series in self.series:
+ wrap = 0
+ previous_offset = 0
+ for page in series.pages:
+ strip_offsets = []
+ for current_offset in page.strip_offsets:
+ if current_offset < previous_offset:
+ wrap += 2**32
+ strip_offsets.append(current_offset + wrap)
+ previous_offset = current_offset
+ page.strip_offsets = tuple(strip_offsets)
+
+ def _fix_lsm_strip_byte_counts(self):
+ """Set strip_byte_counts to size of compressed data.
+
+ The strip_byte_counts tag in LSM files contains the number of bytes
+ for the uncompressed data.
+
+ """
+ if not self.pages:
+ return
+ strips = {}
+ for page in self.pages:
+ assert len(page.strip_offsets) == len(page.strip_byte_counts)
+ for offset, bytecount in zip(page.strip_offsets,
+ page.strip_byte_counts):
+ strips[offset] = bytecount
+ offsets = sorted(strips.keys())
+ offsets.append(min(offsets[-1] + strips[offsets[-1]], self._fh.size))
+ for i, offset in enumerate(offsets[:-1]):
+ strips[offset] = min(strips[offset], offsets[i+1] - offset)
+ for page in self.pages:
+ if page.compression:
+ page.strip_byte_counts = tuple(
+ strips[offset] for offset in page.strip_offsets)
+
+ @lazyattr
+ def series(self):
+ """Return series of TiffPage with compatible shape and properties."""
+ if not self.pages:
+ return []
+
+ series = []
+ page0 = self.pages[0]
+
+ if self.is_ome:
+ series = self._omeseries()
+ elif self.is_fluoview:
+ dims = {b'X': 'X', b'Y': 'Y', b'Z': 'Z', b'T': 'T',
+ b'WAVELENGTH': 'C', b'TIME': 'T', b'XY': 'R',
+ b'EVENT': 'V', b'EXPOSURE': 'L'}
+ mmhd = list(reversed(page0.mm_header.dimensions))
+ series = [Record(
+ axes=''.join(dims.get(i[0].strip().upper(), 'Q')
+ for i in mmhd if i[1] > 1),
+ shape=tuple(int(i[1]) for i in mmhd if i[1] > 1),
+ pages=self.pages, dtype=numpy.dtype(page0.dtype))]
+ elif self.is_lsm:
+ lsmi = page0.cz_lsm_info
+ axes = CZ_SCAN_TYPES[lsmi.scan_type]
+ if page0.is_rgb:
+ axes = axes.replace('C', '').replace('XY', 'XYC')
+ axes = axes[::-1]
+ shape = tuple(getattr(lsmi, CZ_DIMENSIONS[i]) for i in axes)
+ pages = [p for p in self.pages if not p.is_reduced]
+ series = [Record(axes=axes, shape=shape, pages=pages,
+ dtype=numpy.dtype(pages[0].dtype))]
+ if len(pages) != len(self.pages): # reduced RGB pages
+ pages = [p for p in self.pages if p.is_reduced]
+ cp = 1
+ i = 0
+ while cp < len(pages) and i < len(shape)-2:
+ cp *= shape[i]
+ i += 1
+ shape = shape[:i] + pages[0].shape
+ axes = axes[:i] + 'CYX'
+ series.append(Record(axes=axes, shape=shape, pages=pages,
+ dtype=numpy.dtype(pages[0].dtype)))
+ elif self.is_imagej:
+ shape = []
+ axes = []
+ ij = page0.imagej_tags
+ if 'frames' in ij:
+ shape.append(ij['frames'])
+ axes.append('T')
+ if 'slices' in ij:
+ shape.append(ij['slices'])
+ axes.append('Z')
+ if 'channels' in ij and not self.is_rgb:
+ shape.append(ij['channels'])
+ axes.append('C')
+ remain = len(self.pages) // (product(shape) if shape else 1)
+ if remain > 1:
+ shape.append(remain)
+ axes.append('I')
+ shape.extend(page0.shape)
+ axes.extend(page0.axes)
+ axes = ''.join(axes)
+ series = [Record(pages=self.pages, shape=tuple(shape), axes=axes,
+ dtype=numpy.dtype(page0.dtype))]
+ elif self.is_nih:
+ if len(self.pages) == 1:
+ shape = page0.shape
+ axes = page0.axes
+ else:
+ shape = (len(self.pages),) + page0.shape
+ axes = 'I' + page0.axes
+ series = [Record(pages=self.pages, shape=shape, axes=axes,
+ dtype=numpy.dtype(page0.dtype))]
+ elif page0.is_shaped:
+ # TODO: shaped files can contain multiple series
+ shape = page0.tags['image_description'].value[7:-1]
+ shape = tuple(int(i) for i in shape.split(b','))
+ series = [Record(pages=self.pages, shape=shape,
+ axes='Q' * len(shape),
+ dtype=numpy.dtype(page0.dtype))]
+
+ # generic detection of series
+ if not series:
+ shapes = []
+ pages = {}
+ for page in self.pages:
+ if not page.shape:
+ continue
+ shape = page.shape + (page.axes,
+ page.compression in TIFF_DECOMPESSORS)
+ if shape not in pages:
+ shapes.append(shape)
+ pages[shape] = [page]
+ else:
+ pages[shape].append(page)
+ series = [Record(pages=pages[s],
+ axes=(('I' + s[-2])
+ if len(pages[s]) > 1 else s[-2]),
+ dtype=numpy.dtype(pages[s][0].dtype),
+ shape=((len(pages[s]), ) + s[:-2]
+ if len(pages[s]) > 1 else s[:-2]))
+ for s in shapes]
+
+ # remove empty series, e.g. in MD Gel files
+ series = [s for s in series if sum(s.shape) > 0]
+
+ return series
+
+ def asarray(self, key=None, series=None, memmap=False):
+ """Return image data from multiple TIFF pages as numpy array.
+
+ By default the first image series is returned.
+
+ Parameters
+ ----------
+ key : int, slice, or sequence of page indices
+ Defines which pages to return as array.
+ series : int
+ Defines which series of pages to return as array.
+ memmap : bool
+ If True, return an array stored in a binary file on disk
+ if possible.
+
+ """
+ if key is None and series is None:
+ series = 0
+ if series is not None:
+ pages = self.series[series].pages
+ else:
+ pages = self.pages
+
+ if key is None:
+ pass
+ elif isinstance(key, int):
+ pages = [pages[key]]
+ elif isinstance(key, slice):
+ pages = pages[key]
+ elif isinstance(key, collections.Iterable):
+ pages = [pages[k] for k in key]
+ else:
+ raise TypeError("key must be an int, slice, or sequence")
+
+ if not len(pages):
+ raise ValueError("no pages selected")
+
+ if self.is_nih:
+ if pages[0].is_palette:
+ result = stack_pages(pages, colormapped=False, squeeze=False)
+ result = numpy.take(pages[0].color_map, result, axis=1)
+ result = numpy.swapaxes(result, 0, 1)
+ else:
+ result = stack_pages(pages, memmap=memmap,
+ colormapped=False, squeeze=False)
+ elif len(pages) == 1:
+ return pages[0].asarray(memmap=memmap)
+ elif self.is_ome:
+ assert not self.is_palette, "color mapping disabled for ome-tiff"
+ if any(p is None for p in pages):
+ # zero out missing pages
+ firstpage = next(p for p in pages if p)
+ nopage = numpy.zeros_like(
+ firstpage.asarray(memmap=False))
+ s = self.series[series]
+ if memmap:
+ with tempfile.NamedTemporaryFile() as fh:
+ result = numpy.memmap(fh, dtype=s.dtype, shape=s.shape)
+ result = result.reshape(-1)
+ else:
+ result = numpy.empty(s.shape, s.dtype).reshape(-1)
+ index = 0
+
+ class KeepOpen:
+ # keep Tiff files open between consecutive pages
+ def __init__(self, parent, close):
+ self.master = parent
+ self.parent = parent
+ self._close = close
+
+ def open(self, page):
+ if self._close and page and page.parent != self.parent:
+ if self.parent != self.master:
+ self.parent.filehandle.close()
+ self.parent = page.parent
+ self.parent.filehandle.open()
+
+ def close(self):
+ if self._close and self.parent != self.master:
+ self.parent.filehandle.close()
+
+ keep = KeepOpen(self, self._multifile_close)
+ for page in pages:
+ keep.open(page)
+ if page:
+ a = page.asarray(memmap=False, colormapped=False,
+ reopen=False)
+ else:
+ a = nopage
+ try:
+ result[index:index + a.size] = a.reshape(-1)
+ except ValueError as e:
+ warnings.warn("ome-tiff: %s" % e)
+ break
+ index += a.size
+ keep.close()
+ else:
+ result = stack_pages(pages, memmap=memmap)
+
+ if key is None:
+ try:
+ result.shape = self.series[series].shape
+ except ValueError:
+ try:
+ warnings.warn("failed to reshape %s to %s" % (
+ result.shape, self.series[series].shape))
+ # try series of expected shapes
+ result.shape = (-1,) + self.series[series].shape
+ except ValueError:
+ # revert to generic shape
+ result.shape = (-1,) + pages[0].shape
+ else:
+ result.shape = (-1,) + pages[0].shape
+ return result
+
+ def _omeseries(self):
+ """Return image series in OME-TIFF file(s)."""
+ root = etree.fromstring(self.pages[0].tags['image_description'].value)
+ uuid = root.attrib.get('UUID', None)
+ self._files = {uuid: self}
+ dirname = self._fh.dirname
+ modulo = {}
+ result = []
+ for element in root:
+ if element.tag.endswith('BinaryOnly'):
+ warnings.warn("ome-xml: not an ome-tiff master file")
+ break
+ if element.tag.endswith('StructuredAnnotations'):
+ for annot in element:
+ if not annot.attrib.get('Namespace',
+ '').endswith('modulo'):
+ continue
+ for value in annot:
+ for modul in value:
+ for along in modul:
+ if not along.tag[:-1].endswith('Along'):
+ continue
+ axis = along.tag[-1]
+ newaxis = along.attrib.get('Type', 'other')
+ newaxis = AXES_LABELS[newaxis]
+ if 'Start' in along.attrib:
+ labels = range(
+ int(along.attrib['Start']),
+ int(along.attrib['End']) + 1,
+ int(along.attrib.get('Step', 1)))
+ else:
+ labels = [label.text for label in along
+ if label.tag.endswith('Label')]
+ modulo[axis] = (newaxis, labels)
+ if not element.tag.endswith('Image'):
+ continue
+ for pixels in element:
+ if not pixels.tag.endswith('Pixels'):
+ continue
+ atr = pixels.attrib
+ dtype = atr.get('Type', None)
+ axes = ''.join(reversed(atr['DimensionOrder']))
+ shape = list(int(atr['Size'+ax]) for ax in axes)
+ size = product(shape[:-2])
+ ifds = [None] * size
+ for data in pixels:
+ if not data.tag.endswith('TiffData'):
+ continue
+ atr = data.attrib
+ ifd = int(atr.get('IFD', 0))
+ num = int(atr.get('NumPlanes', 1 if 'IFD' in atr else 0))
+ num = int(atr.get('PlaneCount', num))
+ idx = [int(atr.get('First'+ax, 0)) for ax in axes[:-2]]
+ try:
+ idx = numpy.ravel_multi_index(idx, shape[:-2])
+ except ValueError:
+ # ImageJ produces invalid ome-xml when cropping
+ warnings.warn("ome-xml: invalid TiffData index")
+ continue
+ for uuid in data:
+ if not uuid.tag.endswith('UUID'):
+ continue
+ if uuid.text not in self._files:
+ if not self._multifile:
+ # abort reading multifile OME series
+ # and fall back to generic series
+ return []
+ fname = uuid.attrib['FileName']
+ try:
+ tif = TiffFile(os.path.join(dirname, fname))
+ except (IOError, ValueError):
+ tif.close()
+ warnings.warn(
+ "ome-xml: failed to read '%s'" % fname)
+ break
+ self._files[uuid.text] = tif
+ if self._multifile_close:
+ tif.close()
+ pages = self._files[uuid.text].pages
+ try:
+ for i in range(num if num else len(pages)):
+ ifds[idx + i] = pages[ifd + i]
+ except IndexError:
+ warnings.warn("ome-xml: index out of range")
+ # only process first uuid
+ break
+ else:
+ pages = self.pages
+ try:
+ for i in range(num if num else len(pages)):
+ ifds[idx + i] = pages[ifd + i]
+ except IndexError:
+ warnings.warn("ome-xml: index out of range")
+ if all(i is None for i in ifds):
+ # skip images without data
+ continue
+ dtype = next(i for i in ifds if i).dtype
+ result.append(Record(axes=axes, shape=shape, pages=ifds,
+ dtype=numpy.dtype(dtype)))
+
+ for record in result:
+ for axis, (newaxis, labels) in modulo.items():
+ i = record.axes.index(axis)
+ size = len(labels)
+ if record.shape[i] == size:
+ record.axes = record.axes.replace(axis, newaxis, 1)
+ else:
+ record.shape[i] //= size
+ record.shape.insert(i+1, size)
+ record.axes = record.axes.replace(axis, axis+newaxis, 1)
+ record.shape = tuple(record.shape)
+
+ # squeeze dimensions
+ for record in result:
+ record.shape, record.axes = squeeze_axes(record.shape, record.axes)
+
+ return result
+
+ def __len__(self):
+ """Return number of image pages in file."""
+ return len(self.pages)
+
+ def __getitem__(self, key):
+ """Return specified page."""
+ return self.pages[key]
+
+ def __iter__(self):
+ """Return iterator over pages."""
+ return iter(self.pages)
+
+ def __str__(self):
+ """Return string containing information about file."""
+ result = [
+ self._fh.name.capitalize(),
+ format_size(self._fh.size),
+ {'<': 'little endian', '>': 'big endian'}[self.byteorder]]
+ if self.is_bigtiff:
+ result.append("bigtiff")
+ if len(self.pages) > 1:
+ result.append("%i pages" % len(self.pages))
+ if len(self.series) > 1:
+ result.append("%i series" % len(self.series))
+ if len(self._files) > 1:
+ result.append("%i files" % (len(self._files)))
+ return ", ".join(result)
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, exc_type, exc_value, traceback):
+ self.close()
+
+ @lazyattr
+ def fstat(self):
+ try:
+ return os.fstat(self._fh.fileno())
+ except Exception: # io.UnsupportedOperation
+ return None
+
+ @lazyattr
+ def is_bigtiff(self):
+ return self.offset_size != 4
+
+ @lazyattr
+ def is_rgb(self):
+ return all(p.is_rgb for p in self.pages)
+
+ @lazyattr
+ def is_palette(self):
+ return all(p.is_palette for p in self.pages)
+
+ @lazyattr
+ def is_mdgel(self):
+ return any(p.is_mdgel for p in self.pages)
+
+ @lazyattr
+ def is_mediacy(self):
+ return any(p.is_mediacy for p in self.pages)
+
+ @lazyattr
+ def is_stk(self):
+ return all(p.is_stk for p in self.pages)
+
+ @lazyattr
+ def is_lsm(self):
+ return self.pages[0].is_lsm
+
+ @lazyattr
+ def is_imagej(self):
+ return self.pages[0].is_imagej
+
+ @lazyattr
+ def is_micromanager(self):
+ return self.pages[0].is_micromanager
+
+ @lazyattr
+ def is_nih(self):
+ return self.pages[0].is_nih
+
+ @lazyattr
+ def is_fluoview(self):
+ return self.pages[0].is_fluoview
+
+ @lazyattr
+ def is_ome(self):
+ return self.pages[0].is_ome
+
+
+class TiffPage(object):
+ """A TIFF image file directory (IFD).
+
+ Attributes
+ ----------
+ index : int
+ Index of page in file.
+ dtype : str {TIFF_SAMPLE_DTYPES}
+ Data type of image, colormapped if applicable.
+ shape : tuple
+ Dimensions of the image array in TIFF page,
+ colormapped and with one alpha channel if applicable.
+ axes : str
+ Axes label codes:
+ 'X' width, 'Y' height, 'S' sample, 'I' image series|page|plane,
+ 'Z' depth, 'C' color|em-wavelength|channel, 'E' ex-wavelength|lambda,
+ 'T' time, 'R' region|tile, 'A' angle, 'P' phase, 'H' lifetime,
+ 'L' exposure, 'V' event, 'Q' unknown, '_' missing
+ tags : TiffTags
+ Dictionary of tags in page.
+ Tag values are also directly accessible as attributes.
+ color_map : numpy array
+ Color look up table, if exists.
+ cz_lsm_scan_info: Record(dict)
+ LSM scan info attributes, if exists.
+ imagej_tags: Record(dict)
+ Consolidated ImageJ description and metadata tags, if exists.
+ uic_tags: Record(dict)
+ Consolidated MetaMorph STK/UIC tags, if exists.
+
+ All attributes are read-only.
+
+ Notes
+ -----
+ The internal, normalized '_shape' attribute is 6 dimensional:
+
+ 0. number planes (stk)
+ 1. planar samples_per_pixel
+ 2. image_depth Z (sgi)
+ 3. image_length Y
+ 4. image_width X
+ 5. contig samples_per_pixel
+
+ """
+ def __init__(self, parent):
+ """Initialize instance from file."""
+ self.parent = parent
+ self.index = len(parent.pages)
+ self.shape = self._shape = ()
+ self.dtype = self._dtype = None
+ self.axes = ""
+ self.tags = TiffTags()
+
+ self._fromfile()
+ self._process_tags()
+
+ def _fromfile(self):
+ """Read TIFF IFD structure and its tags from file.
+
+ File cursor must be at storage position of IFD offset and is left at
+ offset to next IFD.
+
+ Raises StopIteration if offset (first bytes read) is 0.
+
+ """
+ fh = self.parent.filehandle
+ byteorder = self.parent.byteorder
+ offset_size = self.parent.offset_size
+
+ fmt = {4: 'I', 8: 'Q'}[offset_size]
+ offset = struct.unpack(byteorder + fmt, fh.read(offset_size))[0]
+ if not offset:
+ raise StopIteration()
+
+ # read standard tags
+ tags = self.tags
+ fh.seek(offset)
+ fmt, size = {4: ('H', 2), 8: ('Q', 8)}[offset_size]
+ try:
+ numtags = struct.unpack(byteorder + fmt, fh.read(size))[0]
+ except Exception:
+ warnings.warn("corrupted page list")
+ raise StopIteration()
+
+ tagcode = 0
+ for _ in range(numtags):
+ try:
+ tag = TiffTag(self.parent)
+ # print(tag)
+ except TiffTag.Error as e:
+ warnings.warn(str(e))
+ continue
+ if tagcode > tag.code:
+ # expected for early LSM and tifffile versions
+ warnings.warn("tags are not ordered by code")
+ tagcode = tag.code
+ if tag.name not in tags:
+ tags[tag.name] = tag
+ else:
+ # some files contain multiple IFD with same code
+ # e.g. MicroManager files contain two image_description
+ i = 1
+ while True:
+ name = "%s_%i" % (tag.name, i)
+ if name not in tags:
+ tags[name] = tag
+ break
+
+ pos = fh.tell()
+
+ if self.is_lsm or (self.index and self.parent.is_lsm):
+ # correct non standard LSM bitspersample tags
+ self.tags['bits_per_sample']._correct_lsm_bitspersample(self)
+
+ if self.is_lsm:
+ # read LSM info subrecords
+ for name, reader in CZ_LSM_INFO_READERS.items():
+ try:
+ offset = self.cz_lsm_info['offset_'+name]
+ except KeyError:
+ continue
+ if offset < 8:
+ # older LSM revision
+ continue
+ fh.seek(offset)
+ try:
+ setattr(self, 'cz_lsm_'+name, reader(fh))
+ except ValueError:
+ pass
+
+ elif self.is_stk and 'uic1tag' in tags and not tags['uic1tag'].value:
+ # read uic1tag now that plane count is known
+ uic1tag = tags['uic1tag']
+ fh.seek(uic1tag.value_offset)
+ tags['uic1tag'].value = Record(
+ read_uic1tag(fh, byteorder, uic1tag.dtype, uic1tag.count,
+ tags['uic2tag'].count))
+ fh.seek(pos)
+
+ def _process_tags(self):
+ """Validate standard tags and initialize attributes.
+
+ Raise ValueError if tag values are not supported.
+
+ """
+ tags = self.tags
+ for code, (name, default, dtype, count, validate) in TIFF_TAGS.items():
+ if not (name in tags or default is None):
+ tags[name] = TiffTag(code, dtype=dtype, count=count,
+ value=default, name=name)
+ if name in tags and validate:
+ try:
+ if tags[name].count == 1:
+ setattr(self, name, validate[tags[name].value])
+ else:
+ setattr(self, name, tuple(
+ validate[value] for value in tags[name].value))
+ except KeyError:
+ raise ValueError("%s.value (%s) not supported" %
+ (name, tags[name].value))
+
+ tag = tags['bits_per_sample']
+ if tag.count == 1:
+ self.bits_per_sample = tag.value
+ else:
+ # LSM might list more items than samples_per_pixel
+ value = tag.value[:self.samples_per_pixel]
+ if any((v-value[0] for v in value)):
+ self.bits_per_sample = value
+ else:
+ self.bits_per_sample = value[0]
+
+ tag = tags['sample_format']
+ if tag.count == 1:
+ self.sample_format = TIFF_SAMPLE_FORMATS[tag.value]
+ else:
+ value = tag.value[:self.samples_per_pixel]
+ if any((v-value[0] for v in value)):
+ self.sample_format = [TIFF_SAMPLE_FORMATS[v] for v in value]
+ else:
+ self.sample_format = TIFF_SAMPLE_FORMATS[value[0]]
+
+ if 'photometric' not in tags:
+ self.photometric = None
+
+ if 'image_depth' not in tags:
+ self.image_depth = 1
+
+ if 'image_length' in tags:
+ self.strips_per_image = int(math.floor(
+ float(self.image_length + self.rows_per_strip - 1) /
+ self.rows_per_strip))
+ else:
+ self.strips_per_image = 0
+
+ key = (self.sample_format, self.bits_per_sample)
+ self.dtype = self._dtype = TIFF_SAMPLE_DTYPES.get(key, None)
+
+ if 'image_length' not in self.tags or 'image_width' not in self.tags:
+ # some GEL file pages are missing image data
+ self.image_length = 0
+ self.image_width = 0
+ self.image_depth = 0
+ self.strip_offsets = 0
+ self._shape = ()
+ self.shape = ()
+ self.axes = ''
+
+ if self.is_palette:
+ self.dtype = self.tags['color_map'].dtype[1]
+ self.color_map = numpy.array(self.color_map, self.dtype)
+ dmax = self.color_map.max()
+ if dmax < 256:
+ self.dtype = numpy.uint8
+ self.color_map = self.color_map.astype(self.dtype)
+ #else:
+ # self.dtype = numpy.uint8
+ # self.color_map >>= 8
+ # self.color_map = self.color_map.astype(self.dtype)
+ self.color_map.shape = (3, -1)
+
+ # determine shape of data
+ image_length = self.image_length
+ image_width = self.image_width
+ image_depth = self.image_depth
+ samples_per_pixel = self.samples_per_pixel
+
+ if self.is_stk:
+ assert self.image_depth == 1
+ planes = self.tags['uic2tag'].count
+ if self.is_contig:
+ self._shape = (planes, 1, 1, image_length, image_width,
+ samples_per_pixel)
+ if samples_per_pixel == 1:
+ self.shape = (planes, image_length, image_width)
+ self.axes = 'YX'
+ else:
+ self.shape = (planes, image_length, image_width,
+ samples_per_pixel)
+ self.axes = 'YXS'
+ else:
+ self._shape = (planes, samples_per_pixel, 1, image_length,
+ image_width, 1)
+ if samples_per_pixel == 1:
+ self.shape = (planes, image_length, image_width)
+ self.axes = 'YX'
+ else:
+ self.shape = (planes, samples_per_pixel, image_length,
+ image_width)
+ self.axes = 'SYX'
+ # detect type of series
+ if planes == 1:
+ self.shape = self.shape[1:]
+ elif numpy.all(self.uic2tag.z_distance != 0):
+ self.axes = 'Z' + self.axes
+ elif numpy.all(numpy.diff(self.uic2tag.time_created) != 0):
+ self.axes = 'T' + self.axes
+ else:
+ self.axes = 'I' + self.axes
+ # DISABLED
+ if self.is_palette:
+ assert False, "color mapping disabled for stk"
+ if self.color_map.shape[1] >= 2**self.bits_per_sample:
+ if image_depth == 1:
+ self.shape = (3, planes, image_length, image_width)
+ else:
+ self.shape = (3, planes, image_depth, image_length,
+ image_width)
+ self.axes = 'C' + self.axes
+ else:
+ warnings.warn("palette cannot be applied")
+ self.is_palette = False
+ elif self.is_palette:
+ samples = 1
+ if 'extra_samples' in self.tags:
+ samples += len(self.extra_samples)
+ if self.is_contig:
+ self._shape = (1, 1, image_depth, image_length, image_width,
+ samples)
+ else:
+ self._shape = (1, samples, image_depth, image_length,
+ image_width, 1)
+ if self.color_map.shape[1] >= 2**self.bits_per_sample:
+ if image_depth == 1:
+ self.shape = (3, image_length, image_width)
+ self.axes = 'CYX'
+ else:
+ self.shape = (3, image_depth, image_length, image_width)
+ self.axes = 'CZYX'
+ else:
+ warnings.warn("palette cannot be applied")
+ self.is_palette = False
+ if image_depth == 1:
+ self.shape = (image_length, image_width)
+ self.axes = 'YX'
+ else:
+ self.shape = (image_depth, image_length, image_width)
+ self.axes = 'ZYX'
+ elif self.is_rgb or samples_per_pixel > 1:
+ if self.is_contig:
+ self._shape = (1, 1, image_depth, image_length, image_width,
+ samples_per_pixel)
+ if image_depth == 1:
+ self.shape = (image_length, image_width, samples_per_pixel)
+ self.axes = 'YXS'
+ else:
+ self.shape = (image_depth, image_length, image_width,
+ samples_per_pixel)
+ self.axes = 'ZYXS'
+ else:
+ self._shape = (1, samples_per_pixel, image_depth,
+ image_length, image_width, 1)
+ if image_depth == 1:
+ self.shape = (samples_per_pixel, image_length, image_width)
+ self.axes = 'SYX'
+ else:
+ self.shape = (samples_per_pixel, image_depth,
+ image_length, image_width)
+ self.axes = 'SZYX'
+ if False and self.is_rgb and 'extra_samples' in self.tags:
+ # DISABLED: only use RGB and first alpha channel if exists
+ extra_samples = self.extra_samples
+ if self.tags['extra_samples'].count == 1:
+ extra_samples = (extra_samples, )
+ for exs in extra_samples:
+ if exs in ('unassalpha', 'assocalpha', 'unspecified'):
+ if self.is_contig:
+ self.shape = self.shape[:-1] + (4,)
+ else:
+ self.shape = (4,) + self.shape[1:]
+ break
+ else:
+ self._shape = (1, 1, image_depth, image_length, image_width, 1)
+ if image_depth == 1:
+ self.shape = (image_length, image_width)
+ self.axes = 'YX'
+ else:
+ self.shape = (image_depth, image_length, image_width)
+ self.axes = 'ZYX'
+ if not self.compression and 'strip_byte_counts' not in tags:
+ self.strip_byte_counts = (
+ product(self.shape) * (self.bits_per_sample // 8), )
+
+ assert len(self.shape) == len(self.axes)
+
+ def asarray(self, squeeze=True, colormapped=True, rgbonly=False,
+ scale_mdgel=False, memmap=False, reopen=True):
+ """Read image data from file and return as numpy array.
+
+ Raise ValueError if format is unsupported.
+ If any of 'squeeze', 'colormapped', or 'rgbonly' are not the default,
+ the shape of the returned array might be different from the page shape.
+
+ Parameters
+ ----------
+ squeeze : bool
+ If True, all length-1 dimensions (except X and Y) are
+ squeezed out from result.
+ colormapped : bool
+ If True, color mapping is applied for palette-indexed images.
+ rgbonly : bool
+ If True, return RGB(A) image without additional extra samples.
+ memmap : bool
+ If True, use numpy.memmap to read arrays from file if possible.
+ For use on 64 bit systems and files with few huge contiguous data.
+ reopen : bool
+ If True and the parent file handle is closed, the file is
+ temporarily re-opened (and closed if no exception occurs).
+ scale_mdgel : bool
+ If True, MD Gel data will be scaled according to the private
+ metadata in the second TIFF page. The dtype will be float32.
+
+ """
+ if not self._shape:
+ return
+
+ if self.dtype is None:
+ raise ValueError("data type not supported: %s%i" % (
+ self.sample_format, self.bits_per_sample))
+ if self.compression not in TIFF_DECOMPESSORS:
+ raise ValueError("cannot decompress %s" % self.compression)
+ tag = self.tags['sample_format']
+ if tag.count != 1 and any((i-tag.value[0] for i in tag.value)):
+ raise ValueError("sample formats don't match %s" % str(tag.value))
+
+ fh = self.parent.filehandle
+ closed = fh.closed
+ if closed:
+ if reopen:
+ fh.open()
+ else:
+ raise IOError("file handle is closed")
+
+ dtype = self._dtype
+ shape = self._shape
+ image_width = self.image_width
+ image_length = self.image_length
+ image_depth = self.image_depth
+ typecode = self.parent.byteorder + dtype
+ bits_per_sample = self.bits_per_sample
+
+ if self.is_tiled:
+ if 'tile_offsets' in self.tags:
+ byte_counts = self.tile_byte_counts
+ offsets = self.tile_offsets
+ else:
+ byte_counts = self.strip_byte_counts
+ offsets = self.strip_offsets
+ tile_width = self.tile_width
+ tile_length = self.tile_length
+ tile_depth = self.tile_depth if 'tile_depth' in self.tags else 1
+ tw = (image_width + tile_width - 1) // tile_width
+ tl = (image_length + tile_length - 1) // tile_length
+ td = (image_depth + tile_depth - 1) // tile_depth
+ shape = (shape[0], shape[1],
+ td*tile_depth, tl*tile_length, tw*tile_width, shape[-1])
+ tile_shape = (tile_depth, tile_length, tile_width, shape[-1])
+ runlen = tile_width
+ else:
+ byte_counts = self.strip_byte_counts
+ offsets = self.strip_offsets
+ runlen = image_width
+
+ if any(o < 2 for o in offsets):
+ raise ValueError("corrupted page")
+
+ if memmap and self._is_memmappable(rgbonly, colormapped):
+ result = fh.memmap_array(typecode, shape, offset=offsets[0])
+ elif self.is_contiguous:
+ fh.seek(offsets[0])
+ result = fh.read_array(typecode, product(shape))
+ result = result.astype('=' + dtype)
+ else:
+ if self.is_contig:
+ runlen *= self.samples_per_pixel
+ if bits_per_sample in (8, 16, 32, 64, 128):
+ if (bits_per_sample * runlen) % 8:
+ raise ValueError("data and sample size mismatch")
+
+ def unpack(x):
+ try:
+ return numpy.fromstring(x, typecode)
+ except ValueError as e:
+ # strips may be missing EOI
+ warnings.warn("unpack: %s" % e)
+ xlen = ((len(x) // (bits_per_sample // 8))
+ * (bits_per_sample // 8))
+ return numpy.fromstring(x[:xlen], typecode)
+
+ elif isinstance(bits_per_sample, tuple):
+ def unpack(x):
+ return unpackrgb(x, typecode, bits_per_sample)
+ else:
+ def unpack(x):
+ return unpackints(x, typecode, bits_per_sample, runlen)
+
+ decompress = TIFF_DECOMPESSORS[self.compression]
+ if self.compression == 'jpeg':
+ table = self.jpeg_tables if 'jpeg_tables' in self.tags else b''
+ decompress = lambda x: decodejpg(x, table, self.photometric)
+
+ if self.is_tiled:
+ result = numpy.empty(shape, dtype)
+ tw, tl, td, pl = 0, 0, 0, 0
+ for offset, bytecount in zip(offsets, byte_counts):
+ fh.seek(offset)
+ tile = unpack(decompress(fh.read(bytecount)))
+ tile.shape = tile_shape
+ if self.predictor == 'horizontal':
+ numpy.cumsum(tile, axis=-2, dtype=dtype, out=tile)
+ result[0, pl, td:td+tile_depth,
+ tl:tl+tile_length, tw:tw+tile_width, :] = tile
+ del tile
+ tw += tile_width
+ if tw >= shape[4]:
+ tw, tl = 0, tl + tile_length
+ if tl >= shape[3]:
+ tl, td = 0, td + tile_depth
+ if td >= shape[2]:
+ td, pl = 0, pl + 1
+ result = result[...,
+ :image_depth, :image_length, :image_width, :]
+ else:
+ strip_size = (self.rows_per_strip * self.image_width *
+ self.samples_per_pixel)
+ result = numpy.empty(shape, dtype).reshape(-1)
+ index = 0
+ for offset, bytecount in zip(offsets, byte_counts):
+ fh.seek(offset)
+ strip = fh.read(bytecount)
+ strip = decompress(strip)
+ strip = unpack(strip)
+ size = min(result.size, strip.size, strip_size,
+ result.size - index)
+ result[index:index+size] = strip[:size]
+ del strip
+ index += size
+
+ result.shape = self._shape
+
+ if self.predictor == 'horizontal' and not (self.is_tiled and not
+ self.is_contiguous):
+ # work around bug in LSM510 software
+ if not (self.parent.is_lsm and not self.compression):
+ numpy.cumsum(result, axis=-2, dtype=dtype, out=result)
+
+ if colormapped and self.is_palette:
+ if self.color_map.shape[1] >= 2**bits_per_sample:
+ # FluoView and LSM might fail here
+ result = numpy.take(self.color_map,
+ result[:, 0, :, :, :, 0], axis=1)
+ elif rgbonly and self.is_rgb and 'extra_samples' in self.tags:
+ # return only RGB and first alpha channel if exists
+ extra_samples = self.extra_samples
+ if self.tags['extra_samples'].count == 1:
+ extra_samples = (extra_samples, )
+ for i, exs in enumerate(extra_samples):
+ if exs in ('unassalpha', 'assocalpha', 'unspecified'):
+ if self.is_contig:
+ result = result[..., [0, 1, 2, 3+i]]
+ else:
+ result = result[:, [0, 1, 2, 3+i]]
+ break
+ else:
+ if self.is_contig:
+ result = result[..., :3]
+ else:
+ result = result[:, :3]
+
+ if squeeze:
+ try:
+ result.shape = self.shape
+ except ValueError:
+ warnings.warn("failed to reshape from %s to %s" % (
+ str(result.shape), str(self.shape)))
+
+ if scale_mdgel and self.parent.is_mdgel:
+ # MD Gel stores private metadata in the second page
+ tags = self.parent.pages[1]
+ if tags.md_file_tag in (2, 128):
+ scale = tags.md_scale_pixel
+ scale = scale[0] / scale[1] # rational
+ result = result.astype('float32')
+ if tags.md_file_tag == 2:
+ result **= 2 # squary root data format
+ result *= scale
+
+ if closed:
+ # TODO: file remains open if an exception occurred above
+ fh.close()
+ return result
+
+ def _is_memmappable(self, rgbonly, colormapped):
+ """Return if image data in file can be memory mapped."""
+ if not self.parent.filehandle.is_file or not self.is_contiguous:
+ return False
+ return not (self.predictor or
+ (rgbonly and 'extra_samples' in self.tags) or
+ (colormapped and self.is_palette) or
+ ({'big': '>', 'little': '<'}[sys.byteorder] !=
+ self.parent.byteorder))
+
+ @lazyattr
+ def is_contiguous(self):
+ """Return offset and size of contiguous data, else None.
+
+ Excludes prediction and colormapping.
+
+ """
+ if self.compression or self.bits_per_sample not in (8, 16, 32, 64):
+ return
+ if self.is_tiled:
+ if (self.image_width != self.tile_width or
+ self.image_length % self.tile_length or
+ self.tile_width % 16 or self.tile_length % 16):
+ return
+ if ('image_depth' in self.tags and 'tile_depth' in self.tags and
+ (self.image_length != self.tile_length or
+ self.image_depth % self.tile_depth)):
+ return
+ offsets = self.tile_offsets
+ byte_counts = self.tile_byte_counts
+ else:
+ offsets = self.strip_offsets
+ byte_counts = self.strip_byte_counts
+ if len(offsets) == 1:
+ return offsets[0], byte_counts[0]
+ if self.is_stk or all(offsets[i] + byte_counts[i] == offsets[i+1]
+ or byte_counts[i+1] == 0 # no data/ignore offset
+ for i in range(len(offsets)-1)):
+ return offsets[0], sum(byte_counts)
+
+ def __str__(self):
+ """Return string containing information about page."""
+ s = ', '.join(s for s in (
+ ' x '.join(str(i) for i in self.shape),
+ str(numpy.dtype(self.dtype)),
+ '%s bit' % str(self.bits_per_sample),
+ self.photometric if 'photometric' in self.tags else '',
+ self.compression if self.compression else 'raw',
+ '|'.join(t[3:] for t in (
+ 'is_stk', 'is_lsm', 'is_nih', 'is_ome', 'is_imagej',
+ 'is_micromanager', 'is_fluoview', 'is_mdgel', 'is_mediacy',
+ 'is_sgi', 'is_reduced', 'is_tiled',
+ 'is_contiguous') if getattr(self, t))) if s)
+ return "Page %i: %s" % (self.index, s)
+
+ def __getattr__(self, name):
+ """Return tag value."""
+ if name in self.tags:
+ value = self.tags[name].value
+ setattr(self, name, value)
+ return value
+ raise AttributeError(name)
+
+ @lazyattr
+ def uic_tags(self):
+ """Consolidate UIC tags."""
+ if not self.is_stk:
+ raise AttributeError("uic_tags")
+ tags = self.tags
+ result = Record()
+ result.number_planes = tags['uic2tag'].count
+ if 'image_description' in tags:
+ result.plane_descriptions = self.image_description.split(b'\x00')
+ if 'uic1tag' in tags:
+ result.update(tags['uic1tag'].value)
+ if 'uic3tag' in tags:
+ result.update(tags['uic3tag'].value) # wavelengths
+ if 'uic4tag' in tags:
+ result.update(tags['uic4tag'].value) # override uic1 tags
+ uic2tag = tags['uic2tag'].value
+ result.z_distance = uic2tag.z_distance
+ result.time_created = uic2tag.time_created
+ result.time_modified = uic2tag.time_modified
+ try:
+ result.datetime_created = [
+ julian_datetime(*dt) for dt in
+ zip(uic2tag.date_created, uic2tag.time_created)]
+ result.datetime_modified = [
+ julian_datetime(*dt) for dt in
+ zip(uic2tag.date_modified, uic2tag.time_modified)]
+ except ValueError as e:
+ warnings.warn("uic_tags: %s" % e)
+ return result
+
+ @lazyattr
+ def imagej_tags(self):
+ """Consolidate ImageJ metadata."""
+ if not self.is_imagej:
+ raise AttributeError("imagej_tags")
+ tags = self.tags
+ if 'image_description_1' in tags:
+ # MicroManager
+ result = imagej_description(tags['image_description_1'].value)
+ else:
+ result = imagej_description(tags['image_description'].value)
+ if 'imagej_metadata' in tags:
+ try:
+ result.update(imagej_metadata(
+ tags['imagej_metadata'].value,
+ tags['imagej_byte_counts'].value,
+ self.parent.byteorder))
+ except Exception as e:
+ warnings.warn(str(e))
+ return Record(result)
+
+ @lazyattr
+ def is_rgb(self):
+ """True if page contains a RGB image."""
+ return ('photometric' in self.tags and
+ self.tags['photometric'].value == 2)
+
+ @lazyattr
+ def is_contig(self):
+ """True if page contains a contiguous image."""
+ return ('planar_configuration' in self.tags and
+ self.tags['planar_configuration'].value == 1)
+
+ @lazyattr
+ def is_palette(self):
+ """True if page contains a palette-colored image and not OME or STK."""
+ try:
+ # turn off color mapping for OME-TIFF and STK
+ if self.is_stk or self.is_ome or self.parent.is_ome:
+ return False
+ except IndexError:
+ pass # OME-XML not found in first page
+ return ('photometric' in self.tags and
+ self.tags['photometric'].value == 3)
+
+ @lazyattr
+ def is_tiled(self):
+ """True if page contains tiled image."""
+ return 'tile_width' in self.tags
+
+ @lazyattr
+ def is_reduced(self):
+ """True if page is a reduced image of another image."""
+ return bool(self.tags['new_subfile_type'].value & 1)
+
+ @lazyattr
+ def is_mdgel(self):
+ """True if page contains md_file_tag tag."""
+ return 'md_file_tag' in self.tags
+
+ @lazyattr
+ def is_mediacy(self):
+ """True if page contains Media Cybernetics Id tag."""
+ return ('mc_id' in self.tags and
+ self.tags['mc_id'].value.startswith(b'MC TIFF'))
+
+ @lazyattr
+ def is_stk(self):
+ """True if page contains UIC2Tag tag."""
+ return 'uic2tag' in self.tags
+
+ @lazyattr
+ def is_lsm(self):
+ """True if page contains LSM CZ_LSM_INFO tag."""
+ return 'cz_lsm_info' in self.tags
+
+ @lazyattr
+ def is_fluoview(self):
+ """True if page contains FluoView MM_STAMP tag."""
+ return 'mm_stamp' in self.tags
+
+ @lazyattr
+ def is_nih(self):
+ """True if page contains NIH image header."""
+ return 'nih_image_header' in self.tags
+
+ @lazyattr
+ def is_sgi(self):
+ """True if page contains SGI image and tile depth tags."""
+ return 'image_depth' in self.tags and 'tile_depth' in self.tags
+
+ @lazyattr
+ def is_ome(self):
+ """True if page contains OME-XML in image_description tag."""
+ return ('image_description' in self.tags and self.tags[
+ 'image_description'].value.startswith(b'<?xml version='))
+
+ @lazyattr
+ def is_shaped(self):
+ """True if page contains shape in image_description tag."""
+ return ('image_description' in self.tags and self.tags[
+ 'image_description'].value.startswith(b'shape=('))
+
+ @lazyattr
+ def is_imagej(self):
+ """True if page contains ImageJ description."""
+ return (
+ ('image_description' in self.tags and
+ self.tags['image_description'].value.startswith(b'ImageJ=')) or
+ ('image_description_1' in self.tags and # Micromanager
+ self.tags['image_description_1'].value.startswith(b'ImageJ=')))
+
+ @lazyattr
+ def is_micromanager(self):
+ """True if page contains Micro-Manager metadata."""
+ return 'micromanager_metadata' in self.tags
+
+
+class TiffTag(object):
+ """A TIFF tag structure.
+
+ Attributes
+ ----------
+ name : string
+ Attribute name of tag.
+ code : int
+ Decimal code of tag.
+ dtype : str
+ Datatype of tag data. One of TIFF_DATA_TYPES.
+ count : int
+ Number of values.
+ value : various types
+ Tag data as Python object.
+ value_offset : int
+ Location of value in file, if any.
+
+ All attributes are read-only.
+
+ """
+ __slots__ = ('code', 'name', 'count', 'dtype', 'value', 'value_offset',
+ '_offset', '_value', '_type')
+
+ class Error(Exception):
+ pass
+
+ def __init__(self, arg, **kwargs):
+ """Initialize instance from file or arguments."""
+ self._offset = None
+ if hasattr(arg, '_fh'):
+ self._fromfile(arg, **kwargs)
+ else:
+ self._fromdata(arg, **kwargs)
+
+ def _fromdata(self, code, dtype, count, value, name=None):
+ """Initialize instance from arguments."""
+ self.code = int(code)
+ self.name = name if name else str(code)
+ self.dtype = TIFF_DATA_TYPES[dtype]
+ self.count = int(count)
+ self.value = value
+ self._value = value
+ self._type = dtype
+
+ def _fromfile(self, parent):
+ """Read tag structure from open file. Advance file cursor."""
+ fh = parent.filehandle
+ byteorder = parent.byteorder
+ self._offset = fh.tell()
+ self.value_offset = self._offset + parent.offset_size + 4
+
+ fmt, size = {4: ('HHI4s', 12), 8: ('HHQ8s', 20)}[parent.offset_size]
+ data = fh.read(size)
+ code, dtype = struct.unpack(byteorder + fmt[:2], data[:4])
+ count, value = struct.unpack(byteorder + fmt[2:], data[4:])
+ self._value = value
+ self._type = dtype
+
+ if code in TIFF_TAGS:
+ name = TIFF_TAGS[code][0]
+ elif code in CUSTOM_TAGS:
+ name = CUSTOM_TAGS[code][0]
+ else:
+ name = str(code)
+
+ try:
+ dtype = TIFF_DATA_TYPES[self._type]
+ except KeyError:
+ raise TiffTag.Error("unknown tag data type %i" % self._type)
+
+ fmt = '%s%i%s' % (byteorder, count*int(dtype[0]), dtype[1])
+ size = struct.calcsize(fmt)
+ if size > parent.offset_size or code in CUSTOM_TAGS:
+ pos = fh.tell()
+ tof = {4: 'I', 8: 'Q'}[parent.offset_size]
+ self.value_offset = offset = struct.unpack(byteorder+tof, value)[0]
+ if offset < 0 or offset > parent.filehandle.size:
+ raise TiffTag.Error("corrupt file - invalid tag value offset")
+ elif offset < 4:
+ raise TiffTag.Error("corrupt value offset for tag %i" % code)
+ fh.seek(offset)
+ if code in CUSTOM_TAGS:
+ readfunc = CUSTOM_TAGS[code][1]
+ value = readfunc(fh, byteorder, dtype, count)
+ if isinstance(value, dict): # numpy.core.records.record
+ value = Record(value)
+ elif code in TIFF_TAGS or dtype[-1] == 's':
+ value = struct.unpack(fmt, fh.read(size))
+ else:
+ value = read_numpy(fh, byteorder, dtype, count)
+ fh.seek(pos)
+ else:
+ value = struct.unpack(fmt, value[:size])
+
+ if code not in CUSTOM_TAGS and code not in (273, 279, 324, 325):
+ # scalar value if not strip/tile offsets/byte_counts
+ if len(value) == 1:
+ value = value[0]
+
+ if (dtype.endswith('s') and isinstance(value, bytes)
+ and self._type != 7):
+ # TIFF ASCII fields can contain multiple strings,
+ # each terminated with a NUL
+ value = stripascii(value)
+
+ self.code = code
+ self.name = name
+ self.dtype = dtype
+ self.count = count
+ self.value = value
+
+ def _correct_lsm_bitspersample(self, parent):
+ """Correct LSM bitspersample tag.
+
+ Old LSM writers may use a separate region for two 16-bit values,
+ although they fit into the tag value element of the tag.
+
+ """
+ if self.code == 258 and self.count == 2:
+ # TODO: test this. Need example file.
+ warnings.warn("correcting LSM bitspersample tag")
+ fh = parent.filehandle
+ tof = {4: '<I', 8: '<Q'}[parent.offset_size]
+ self.value_offset = struct.unpack(tof, self._value)[0]
+ fh.seek(self.value_offset)
+ self.value = struct.unpack("<HH", fh.read(4))
+
+ def as_str(self):
+ """Return value as human readable string."""
+ return ((str(self.value).split('\n', 1)[0]) if (self._type != 7)
+ else '<undefined>')
+
+ def __str__(self):
+ """Return string containing information about tag."""
+ return ' '.join(str(getattr(self, s)) for s in self.__slots__)
+
+
+class TiffSequence(object):
+ """Sequence of image files.
+
+ The data shape and dtype of all files must match.
+
+ Properties
+ ----------
+ files : list
+ List of file names.
+ shape : tuple
+ Shape of image sequence.
+ axes : str
+ Labels of axes in shape.
+
+ Examples
+ --------
+ >>> tifs = TiffSequence("test.oif.files/*.tif") # doctest: +SKIP
+ >>> tifs.shape, tifs.axes # doctest: +SKIP
+ ((2, 100), 'CT')
+ >>> data = tifs.asarray() # doctest: +SKIP
+ >>> data.shape # doctest: +SKIP
+ (2, 100, 256, 256)
+
+ """
+ _patterns = {
+ 'axes': r"""
+ # matches Olympus OIF and Leica TIFF series
+ _?(?:(q|l|p|a|c|t|x|y|z|ch|tp)(\d{1,4}))
+ _?(?:(q|l|p|a|c|t|x|y|z|ch|tp)(\d{1,4}))?
+ _?(?:(q|l|p|a|c|t|x|y|z|ch|tp)(\d{1,4}))?
+ _?(?:(q|l|p|a|c|t|x|y|z|ch|tp)(\d{1,4}))?
+ _?(?:(q|l|p|a|c|t|x|y|z|ch|tp)(\d{1,4}))?
+ _?(?:(q|l|p|a|c|t|x|y|z|ch|tp)(\d{1,4}))?
+ _?(?:(q|l|p|a|c|t|x|y|z|ch|tp)(\d{1,4}))?
+ """}
+
+ class ParseError(Exception):
+ pass
+
+ def __init__(self, files, imread=TiffFile, pattern='axes',
+ *args, **kwargs):
+ """Initialize instance from multiple files.
+
+ Parameters
+ ----------
+ files : str, or sequence of str
+ Glob pattern or sequence of file names.
+ imread : function or class
+ Image read function or class with asarray function returning numpy
+ array from single file.
+ pattern : str
+ Regular expression pattern that matches axes names and sequence
+ indices in file names.
+ By default this matches Olympus OIF and Leica TIFF series.
+
+ """
+ if isinstance(files, basestring):
+ files = natural_sorted(glob.glob(files))
+ files = list(files)
+ if not files:
+ raise ValueError("no files found")
+ #if not os.path.isfile(files[0]):
+ # raise ValueError("file not found")
+ self.files = files
+
+ if hasattr(imread, 'asarray'):
+ # redefine imread
+ _imread = imread
+
+ def imread(fname, *args, **kwargs):
+ with _imread(fname) as im:
+ return im.asarray(*args, **kwargs)
+
+ self.imread = imread
+
+ self.pattern = self._patterns.get(pattern, pattern)
+ try:
+ self._parse()
+ if not self.axes:
+ self.axes = 'I'
+ except self.ParseError:
+ self.axes = 'I'
+ self.shape = (len(files),)
+ self._start_index = (0,)
+ self._indices = tuple((i,) for i in range(len(files)))
+
+ def __str__(self):
+ """Return string with information about image sequence."""
+ return "\n".join([
+ self.files[0],
+ '* files: %i' % len(self.files),
+ '* axes: %s' % self.axes,
+ '* shape: %s' % str(self.shape)])
+
+ def __len__(self):
+ return len(self.files)
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, exc_type, exc_value, traceback):
+ self.close()
+
+ def close(self):
+ pass
+
+ def asarray(self, memmap=False, *args, **kwargs):
+ """Read image data from all files and return as single numpy array.
+
+ If memmap is True, return an array stored in a binary file on disk.
+ The args and kwargs parameters are passed to the imread function.
+
+ Raise IndexError or ValueError if image shapes don't match.
+
+ """
+ im = self.imread(self.files[0], *args, **kwargs)
+ shape = self.shape + im.shape
+ if memmap:
+ with tempfile.NamedTemporaryFile() as fh:
+ result = numpy.memmap(fh, dtype=im.dtype, shape=shape)
+ else:
+ result = numpy.zeros(shape, dtype=im.dtype)
+ result = result.reshape(-1, *im.shape)
+ for index, fname in zip(self._indices, self.files):
+ index = [i-j for i, j in zip(index, self._start_index)]
+ index = numpy.ravel_multi_index(index, self.shape)
+ im = self.imread(fname, *args, **kwargs)
+ result[index] = im
+ result.shape = shape
+ return result
+
+ def _parse(self):
+ """Get axes and shape from file names."""
+ if not self.pattern:
+ raise self.ParseError("invalid pattern")
+ pattern = re.compile(self.pattern, re.IGNORECASE | re.VERBOSE)
+ matches = pattern.findall(self.files[0])
+ if not matches:
+ raise self.ParseError("pattern doesn't match file names")
+ matches = matches[-1]
+ if len(matches) % 2:
+ raise self.ParseError("pattern doesn't match axis name and index")
+ axes = ''.join(m for m in matches[::2] if m)
+ if not axes:
+ raise self.ParseError("pattern doesn't match file names")
+
+ indices = []
+ for fname in self.files:
+ matches = pattern.findall(fname)[-1]
+ if axes != ''.join(m for m in matches[::2] if m):
+ raise ValueError("axes don't match within the image sequence")
+ indices.append([int(m) for m in matches[1::2] if m])
+ shape = tuple(numpy.max(indices, axis=0))
+ start_index = tuple(numpy.min(indices, axis=0))
+ shape = tuple(i-j+1 for i, j in zip(shape, start_index))
+ if product(shape) != len(self.files):
+ warnings.warn("files are missing. Missing data are zeroed")
+
+ self.axes = axes.upper()
+ self.shape = shape
+ self._indices = indices
+ self._start_index = start_index
+
+
+class Record(dict):
+ """Dictionary with attribute access.
+
+ Can also be initialized with numpy.core.records.record.
+
+ """
+ __slots__ = ()
+
+ def __init__(self, arg=None, **kwargs):
+ if kwargs:
+ arg = kwargs
+ elif arg is None:
+ arg = {}
+ try:
+ dict.__init__(self, arg)
+ except (TypeError, ValueError):
+ for i, name in enumerate(arg.dtype.names):
+ v = arg[i]
+ self[name] = v if v.dtype.char != 'S' else stripnull(v)
+
+ def __getattr__(self, name):
+ return self[name]
+
+ def __setattr__(self, name, value):
+ self.__setitem__(name, value)
+
+ def __str__(self):
+ """Pretty print Record."""
+ s = []
+ lists = []
+ for k in sorted(self):
+ try:
+ if k.startswith('_'): # does not work with byte
+ continue
+ except AttributeError:
+ pass
+ v = self[k]
+ if isinstance(v, (list, tuple)) and len(v):
+ if isinstance(v[0], Record):
+ lists.append((k, v))
+ continue
+ elif isinstance(v[0], TiffPage):
+ v = [i.index for i in v if i]
+ s.append(
+ ("* %s: %s" % (k, str(v))).split("\n", 1)[0]
+ [:PRINT_LINE_LEN].rstrip())
+ for k, v in lists:
+ l = []
+ for i, w in enumerate(v):
+ l.append("* %s[%i]\n %s" % (k, i,
+ str(w).replace("\n", "\n ")))
+ s.append('\n'.join(l))
+ return '\n'.join(s)
+
+
+class TiffTags(Record):
+ """Dictionary of TiffTag with attribute access."""
+
+ def __str__(self):
+ """Return string with information about all tags."""
+ s = []
+ for tag in sorted(self.values(), key=lambda x: x.code):
+ typecode = "%i%s" % (tag.count * int(tag.dtype[0]), tag.dtype[1])
+ line = "* %i %s (%s) %s" % (
+ tag.code, tag.name, typecode, tag.as_str())
+ s.append(line[:PRINT_LINE_LEN].lstrip())
+ return '\n'.join(s)
+
+
+class FileHandle(object):
+ """Binary file handle.
+
+ * Handle embedded files (for CZI within CZI files).
+ * Allow to re-open closed files (for multi file formats such as OME-TIFF).
+ * Read numpy arrays and records from file like objects.
+
+ Only binary read, seek, tell, and close are supported on embedded files.
+ When initialized from another file handle, do not use it unless this
+ FileHandle is closed.
+
+ Attributes
+ ----------
+ name : str
+ Name of the file.
+ path : str
+ Absolute path to file.
+ size : int
+ Size of file in bytes.
+ is_file : bool
+ If True, file has a filno and can be memory mapped.
+
+ All attributes are read-only.
+
+ """
+ __slots__ = ('_fh', '_arg', '_mode', '_name', '_dir',
+ '_offset', '_size', '_close', 'is_file')
+
+ def __init__(self, arg, mode='rb', name=None, offset=None, size=None):
+ """Initialize file handle from file name or another file handle.
+
+ Parameters
+ ----------
+ arg : str, File, or FileHandle
+ File name or open file handle.
+ mode : str
+ File open mode in case 'arg' is a file name.
+ name : str
+ Optional name of file in case 'arg' is a file handle.
+ offset : int
+ Optional start position of embedded file. By default this is
+ the current file position.
+ size : int
+ Optional size of embedded file. By default this is the number
+ of bytes from the 'offset' to the end of the file.
+
+ """
+ self._fh = None
+ self._arg = arg
+ self._mode = mode
+ self._name = name
+ self._dir = ''
+ self._offset = offset
+ self._size = size
+ self._close = True
+ self.is_file = False
+ self.open()
+
+ def open(self):
+ """Open or re-open file."""
+ if self._fh:
+ return # file is open
+
+ if isinstance(self._arg, basestring):
+ # file name
+ self._arg = os.path.abspath(self._arg)
+ self._dir, self._name = os.path.split(self._arg)
+ self._fh = open(self._arg, self._mode)
+ self._close = True
+ if self._offset is None:
+ self._offset = 0
+ elif isinstance(self._arg, FileHandle):
+ # FileHandle
+ self._fh = self._arg._fh
+ if self._offset is None:
+ self._offset = 0
+ self._offset += self._arg._offset
+ self._close = False
+ if not self._name:
+ if self._offset:
+ name, ext = os.path.splitext(self._arg._name)
+ self._name = "%s@%i%s" % (name, self._offset, ext)
+ else:
+ self._name = self._arg._name
+ self._dir = self._arg._dir
+ else:
+ # open file object
+ self._fh = self._arg
+ if self._offset is None:
+ self._offset = self._arg.tell()
+ self._close = False
+ if not self._name:
+ try:
+ self._dir, self._name = os.path.split(self._fh.name)
+ except AttributeError:
+ self._name = "Unnamed stream"
+
+ if self._offset:
+ self._fh.seek(self._offset)
+
+ if self._size is None:
+ pos = self._fh.tell()
+ self._fh.seek(self._offset, 2)
+ self._size = self._fh.tell()
+ self._fh.seek(pos)
+
+ try:
+ self._fh.fileno()
+ self.is_file = True
+ except Exception:
+ self.is_file = False
+
+ def read(self, size=-1):
+ """Read 'size' bytes from file, or until EOF is reached."""
+ if size < 0 and self._offset:
+ size = self._size
+ return self._fh.read(size)
+
+ def memmap_array(self, dtype, shape, offset=0, mode='r', order='C'):
+ """Return numpy.memmap of data stored in file."""
+ if not self.is_file:
+ raise ValueError("Can not memory map file without fileno.")
+ return numpy.memmap(self._fh, dtype=dtype, mode=mode,
+ offset=self._offset + offset,
+ shape=shape, order=order)
+
+ def read_array(self, dtype, count=-1, sep=""):
+ """Return numpy array from file.
+
+ Work around numpy issue #2230, "numpy.fromfile does not accept
+ StringIO object" https://github.com/numpy/numpy/issues/2230.
+
+ """
+ try:
+ return numpy.fromfile(self._fh, dtype, count, sep)
+ except IOError:
+ if count < 0:
+ size = self._size
+ else:
+ size = count * numpy.dtype(dtype).itemsize
+ data = self._fh.read(size)
+ return numpy.fromstring(data, dtype, count, sep)
+
+ def read_record(self, dtype, shape=1, byteorder=None):
+ """Return numpy record from file."""
+ try:
+ rec = numpy.rec.fromfile(self._fh, dtype, shape,
+ byteorder=byteorder)
+ except Exception:
+ dtype = numpy.dtype(dtype)
+ if shape is None:
+ shape = self._size // dtype.itemsize
+ size = product(sequence(shape)) * dtype.itemsize
+ data = self._fh.read(size)
+ return numpy.rec.fromstring(data, dtype, shape,
+ byteorder=byteorder)
+ return rec[0] if shape == 1 else rec
+
+ def tell(self):
+ """Return file's current position."""
+ return self._fh.tell() - self._offset
+
+ def seek(self, offset, whence=0):
+ """Set file's current position."""
+ if self._offset:
+ if whence == 0:
+ self._fh.seek(self._offset + offset, whence)
+ return
+ elif whence == 2:
+ self._fh.seek(self._offset + self._size + offset, 0)
+ return
+ self._fh.seek(offset, whence)
+
+ def close(self):
+ """Close file."""
+ if self._close and self._fh:
+ self._fh.close()
+ self._fh = None
+ self.is_file = False
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, exc_type, exc_value, traceback):
+ self.close()
+
+ def __getattr__(self, name):
+ """Return attribute from underlying file object."""
+ if self._offset:
+ warnings.warn(
+ "FileHandle: '%s' not implemented for embedded files" % name)
+ return getattr(self._fh, name)
+
+ @property
+ def name(self):
+ return self._name
+
+ @property
+ def dirname(self):
+ return self._dir
+
+ @property
+ def path(self):
+ return os.path.join(self._dir, self._name)
+
+ @property
+ def size(self):
+ return self._size
+
+ @property
+ def closed(self):
+ return self._fh is None
+
+
+def read_bytes(fh, byteorder, dtype, count):
+ """Read tag data from file and return as byte string."""
+ dtype = 'b' if dtype[-1] == 's' else byteorder+dtype[-1]
+ return fh.read_array(dtype, count).tostring()
+
+
+def read_numpy(fh, byteorder, dtype, count):
+ """Read tag data from file and return as numpy array."""
+ dtype = 'b' if dtype[-1] == 's' else byteorder+dtype[-1]
+ return fh.read_array(dtype, count)
+
+
+def read_json(fh, byteorder, dtype, count):
+ """Read JSON tag data from file and return as object."""
+ data = fh.read(count)
+ try:
+ return json.loads(unicode(stripnull(data), 'utf-8'))
+ except ValueError:
+ warnings.warn("invalid JSON `%s`" % data)
+
+
+def read_mm_header(fh, byteorder, dtype, count):
+ """Read MM_HEADER tag from file and return as numpy.rec.array."""
+ return fh.read_record(MM_HEADER, byteorder=byteorder)
+
+
+def read_mm_stamp(fh, byteorder, dtype, count):
+ """Read MM_STAMP tag from file and return as numpy.array."""
+ return fh.read_array(byteorder+'f8', 8)
+
+
+def read_uic1tag(fh, byteorder, dtype, count, plane_count=None):
+ """Read MetaMorph STK UIC1Tag from file and return as dictionary.
+
+ Return empty dictionary if plane_count is unknown.
+
+ """
+ assert dtype in ('2I', '1I') and byteorder == '<'
+ result = {}
+ if dtype == '2I':
+ # pre MetaMorph 2.5 (not tested)
+ values = fh.read_array('<u4', 2*count).reshape(count, 2)
+ result = {'z_distance': values[:, 0] / values[:, 1]}
+ elif plane_count:
+ for i in range(count):
+ tagid = struct.unpack('<I', fh.read(4))[0]
+ if tagid in (28, 29, 37, 40, 41):
+ # silently skip unexpected tags
+ fh.read(4)
+ continue
+ name, value = read_uic_tag(fh, tagid, plane_count, offset=True)
+ result[name] = value
+ return result
+
+
+def read_uic2tag(fh, byteorder, dtype, plane_count):
+ """Read MetaMorph STK UIC2Tag from file and return as dictionary."""
+ assert dtype == '2I' and byteorder == '<'
+ values = fh.read_array('<u4', 6*plane_count).reshape(plane_count, 6)
+ return {
+ 'z_distance': values[:, 0] / values[:, 1],
+ 'date_created': values[:, 2], # julian days
+ 'time_created': values[:, 3], # milliseconds
+ 'date_modified': values[:, 4], # julian days
+ 'time_modified': values[:, 5], # milliseconds
+ }
+
+
+def read_uic3tag(fh, byteorder, dtype, plane_count):
+ """Read MetaMorph STK UIC3Tag from file and return as dictionary."""
+ assert dtype == '2I' and byteorder == '<'
+ values = fh.read_array('<u4', 2*plane_count).reshape(plane_count, 2)
+ return {'wavelengths': values[:, 0] / values[:, 1]}
+
+
+def read_uic4tag(fh, byteorder, dtype, plane_count):
+ """Read MetaMorph STK UIC4Tag from file and return as dictionary."""
+ assert dtype == '1I' and byteorder == '<'
+ result = {}
+ while True:
+ tagid = struct.unpack('<H', fh.read(2))[0]
+ if tagid == 0:
+ break
+ name, value = read_uic_tag(fh, tagid, plane_count, offset=False)
+ result[name] = value
+ return result
+
+
+def read_uic_tag(fh, tagid, plane_count, offset):
+ """Read a single UIC tag value from file and return tag name and value.
+
+ UIC1Tags use an offset.
+
+ """
+ def read_int(count=1):
+ value = struct.unpack('<%iI' % count, fh.read(4*count))
+ return value[0] if count == 1 else value
+
+ try:
+ name, dtype = UIC_TAGS[tagid]
+ except KeyError:
+ # unknown tag
+ return '_tagid_%i' % tagid, read_int()
+
+ if offset:
+ pos = fh.tell()
+ if dtype not in (int, None):
+ off = read_int()
+ if off < 8:
+ warnings.warn("invalid offset for uic tag '%s': %i"
+ % (name, off))
+ return name, off
+ fh.seek(off)
+
+ if dtype is None:
+ # skip
+ name = '_' + name
+ value = read_int()
+ elif dtype is int:
+ # int
+ value = read_int()
+ elif dtype is Fraction:
+ # fraction
+ value = read_int(2)
+ value = value[0] / value[1]
+ elif dtype is julian_datetime:
+ # datetime
+ value = julian_datetime(*read_int(2))
+ elif dtype is read_uic_image_property:
+ # ImagePropertyEx
+ value = read_uic_image_property(fh)
+ elif dtype is str:
+ # pascal string
+ size = read_int()
+ if 0 <= size < 2**10:
+ value = struct.unpack('%is' % size, fh.read(size))[0][:-1]
+ value = stripnull(value)
+ elif offset:
+ value = ''
+ warnings.warn("corrupt string in uic tag '%s'" % name)
+ else:
+ raise ValueError("invalid string size %i" % size)
+ elif dtype == '%ip':
+ # sequence of pascal strings
+ value = []
+ for i in range(plane_count):
+ size = read_int()
+ if 0 <= size < 2**10:
+ string = struct.unpack('%is' % size, fh.read(size))[0][:-1]
+ string = stripnull(string)
+ value.append(string)
+ elif offset:
+ warnings.warn("corrupt string in uic tag '%s'" % name)
+ else:
+ raise ValueError("invalid string size %i" % size)
+ else:
+ # struct or numpy type
+ dtype = '<' + dtype
+ if '%i' in dtype:
+ dtype = dtype % plane_count
+ if '(' in dtype:
+ # numpy type
+ value = fh.read_array(dtype, 1)[0]
+ if value.shape[-1] == 2:
+ # assume fractions
+ value = value[..., 0] / value[..., 1]
+ else:
+ # struct format
+ value = struct.unpack(dtype, fh.read(struct.calcsize(dtype)))
+ if len(value) == 1:
+ value = value[0]
+
+ if offset:
+ fh.seek(pos + 4)
+
+ return name, value
+
+
+def read_uic_image_property(fh):
+ """Read UIC ImagePropertyEx tag from file and return as dict."""
+ # TODO: test this
+ size = struct.unpack('B', fh.read(1))[0]
+ name = struct.unpack('%is' % size, fh.read(size))[0][:-1]
+ flags, prop = struct.unpack('<IB', fh.read(5))
+ if prop == 1:
+ value = struct.unpack('II', fh.read(8))
+ value = value[0] / value[1]
+ else:
+ size = struct.unpack('B', fh.read(1))[0]
+ value = struct.unpack('%is' % size, fh.read(size))[0]
+ return dict(name=name, flags=flags, value=value)
+
+
+def read_cz_lsm_info(fh, byteorder, dtype, count):
+ """Read CS_LSM_INFO tag from file and return as numpy.rec.array."""
+ assert byteorder == '<'
+ magic_number, structure_size = struct.unpack('<II', fh.read(8))
+ if magic_number not in (50350412, 67127628):
+ raise ValueError("not a valid CS_LSM_INFO structure")
+ fh.seek(-8, 1)
+
+ if structure_size < numpy.dtype(CZ_LSM_INFO).itemsize:
+ # adjust structure according to structure_size
+ cz_lsm_info = []
+ size = 0
+ for name, dtype in CZ_LSM_INFO:
+ size += numpy.dtype(dtype).itemsize
+ if size > structure_size:
+ break
+ cz_lsm_info.append((name, dtype))
+ else:
+ cz_lsm_info = CZ_LSM_INFO
+
+ return fh.read_record(cz_lsm_info, byteorder=byteorder)
+
+
+def read_cz_lsm_floatpairs(fh):
+ """Read LSM sequence of float pairs from file and return as list."""
+ size = struct.unpack('<i', fh.read(4))[0]
+ return fh.read_array('<2f8', count=size)
+
+
+def read_cz_lsm_positions(fh):
+ """Read LSM positions from file and return as list."""
+ size = struct.unpack('<I', fh.read(4))[0]
+ return fh.read_array('<2f8', count=size)
+
+
+def read_cz_lsm_time_stamps(fh):
+ """Read LSM time stamps from file and return as list."""
+ size, count = struct.unpack('<ii', fh.read(8))
+ if size != (8 + 8 * count):
+ raise ValueError("lsm_time_stamps block is too short")
+ # return struct.unpack('<%dd' % count, fh.read(8*count))
+ return fh.read_array('<f8', count=count)
+
+
+def read_cz_lsm_event_list(fh):
+ """Read LSM events from file and return as list of (time, type, text)."""
+ count = struct.unpack('<II', fh.read(8))[1]
+ events = []
+ while count > 0:
+ esize, etime, etype = struct.unpack('<IdI', fh.read(16))
+ etext = stripnull(fh.read(esize - 16))
+ events.append((etime, etype, etext))
+ count -= 1
+ return events
+
+
+def read_cz_lsm_scan_info(fh):
+ """Read LSM scan information from file and return as Record."""
+ block = Record()
+ blocks = [block]
+ unpack = struct.unpack
+ if 0x10000000 != struct.unpack('<I', fh.read(4))[0]:
+ # not a Recording sub block
+ raise ValueError("not a lsm_scan_info structure")
+ fh.read(8)
+ while True:
+ entry, dtype, size = unpack('<III', fh.read(12))
+ if dtype == 2:
+ # ascii
+ value = stripnull(fh.read(size))
+ elif dtype == 4:
+ # long
+ value = unpack('<i', fh.read(4))[0]
+ elif dtype == 5:
+ # rational
+ value = unpack('<d', fh.read(8))[0]
+ else:
+ value = 0
+ if entry in CZ_LSM_SCAN_INFO_ARRAYS:
+ blocks.append(block)
+ name = CZ_LSM_SCAN_INFO_ARRAYS[entry]
+ newobj = []
+ setattr(block, name, newobj)
+ block = newobj
+ elif entry in CZ_LSM_SCAN_INFO_STRUCTS:
+ blocks.append(block)
+ newobj = Record()
+ block.append(newobj)
+ block = newobj
+ elif entry in CZ_LSM_SCAN_INFO_ATTRIBUTES:
+ name = CZ_LSM_SCAN_INFO_ATTRIBUTES[entry]
+ setattr(block, name, value)
+ elif entry == 0xffffffff:
+ # end sub block
+ block = blocks.pop()
+ else:
+ # unknown entry
+ setattr(block, "entry_0x%x" % entry, value)
+ if not blocks:
+ break
+ return block
+
+
+def read_nih_image_header(fh, byteorder, dtype, count):
+ """Read NIH_IMAGE_HEADER tag from file and return as numpy.rec.array."""
+ a = fh.read_record(NIH_IMAGE_HEADER, byteorder=byteorder)
+ a = a.newbyteorder(byteorder)
+ a.xunit = a.xunit[:a._xunit_len]
+ a.um = a.um[:a._um_len]
+ return a
+
+
+def read_micromanager_metadata(fh):
+ """Read MicroManager non-TIFF settings from open file and return as dict.
+
+ The settings can be used to read image data without parsing the TIFF file.
+
+ Raise ValueError if file does not contain valid MicroManager metadata.
+
+ """
+ fh.seek(0)
+ try:
+ byteorder = {b'II': '<', b'MM': '>'}[fh.read(2)]
+ except IndexError:
+ raise ValueError("not a MicroManager TIFF file")
+
+ results = {}
+ fh.seek(8)
+ (index_header, index_offset, display_header, display_offset,
+ comments_header, comments_offset, summary_header, summary_length
+ ) = struct.unpack(byteorder + "IIIIIIII", fh.read(32))
+
+ if summary_header != 2355492:
+ raise ValueError("invalid MicroManager summary_header")
+ results['summary'] = read_json(fh, byteorder, None, summary_length)
+
+ if index_header != 54773648:
+ raise ValueError("invalid MicroManager index_header")
+ fh.seek(index_offset)
+ header, count = struct.unpack(byteorder + "II", fh.read(8))
+ if header != 3453623:
+ raise ValueError("invalid MicroManager index_header")
+ data = struct.unpack(byteorder + "IIIII"*count, fh.read(20*count))
+ results['index_map'] = {
+ 'channel': data[::5], 'slice': data[1::5], 'frame': data[2::5],
+ 'position': data[3::5], 'offset': data[4::5]}
+
+ if display_header != 483765892:
+ raise ValueError("invalid MicroManager display_header")
+ fh.seek(display_offset)
+ header, count = struct.unpack(byteorder + "II", fh.read(8))
+ if header != 347834724:
+ raise ValueError("invalid MicroManager display_header")
+ results['display_settings'] = read_json(fh, byteorder, None, count)
+
+ if comments_header != 99384722:
+ raise ValueError("invalid MicroManager comments_header")
+ fh.seek(comments_offset)
+ header, count = struct.unpack(byteorder + "II", fh.read(8))
+ if header != 84720485:
+ raise ValueError("invalid MicroManager comments_header")
+ results['comments'] = read_json(fh, byteorder, None, count)
+
+ return results
+
+
+def imagej_metadata(data, bytecounts, byteorder):
+ """Return dict from ImageJ metadata tag value."""
+ _str = str if sys.version_info[0] < 3 else lambda x: str(x, 'cp1252')
+
+ def read_string(data, byteorder):
+ return _str(stripnull(data[0 if byteorder == '<' else 1::2]))
+
+ def read_double(data, byteorder):
+ return struct.unpack(byteorder+('d' * (len(data) // 8)), data)
+
+ def read_bytes(data, byteorder):
+ #return struct.unpack('b' * len(data), data)
+ return numpy.fromstring(data, 'uint8')
+
+ metadata_types = { # big endian
+ b'info': ('info', read_string),
+ b'labl': ('labels', read_string),
+ b'rang': ('ranges', read_double),
+ b'luts': ('luts', read_bytes),
+ b'roi ': ('roi', read_bytes),
+ b'over': ('overlays', read_bytes)}
+ metadata_types.update( # little endian
+ dict((k[::-1], v) for k, v in metadata_types.items()))
+
+ if not bytecounts:
+ raise ValueError("no ImageJ metadata")
+
+ if not data[:4] in (b'IJIJ', b'JIJI'):
+ raise ValueError("invalid ImageJ metadata")
+
+ header_size = bytecounts[0]
+ if header_size < 12 or header_size > 804:
+ raise ValueError("invalid ImageJ metadata header size")
+
+ ntypes = (header_size - 4) // 8
+ header = struct.unpack(byteorder+'4sI'*ntypes, data[4:4+ntypes*8])
+ pos = 4 + ntypes * 8
+ counter = 0
+ result = {}
+ for mtype, count in zip(header[::2], header[1::2]):
+ values = []
+ name, func = metadata_types.get(mtype, (_str(mtype), read_bytes))
+ for _ in range(count):
+ counter += 1
+ pos1 = pos + bytecounts[counter]
+ values.append(func(data[pos:pos1], byteorder))
+ pos = pos1
+ result[name.strip()] = values[0] if count == 1 else values
+ return result
+
+
+def imagej_description(description):
+ """Return dict from ImageJ image_description tag."""
+ def _bool(val):
+ return {b'true': True, b'false': False}[val.lower()]
+
+ _str = str if sys.version_info[0] < 3 else lambda x: str(x, 'cp1252')
+ result = {}
+ for line in description.splitlines():
+ try:
+ key, val = line.split(b'=')
+ except Exception:
+ continue
+ key = key.strip()
+ val = val.strip()
+ for dtype in (int, float, _bool, _str):
+ try:
+ val = dtype(val)
+ break
+ except Exception:
+ pass
+ result[_str(key)] = val
+ return result
+
+
+def decodejpg(encoded, tables=b'', photometric=None,
+ ycbcr_subsampling=None, ycbcr_positioning=None):
+ """Decode JPEG encoded byte string (using _czifile extension module)."""
+ import _czifile
+ image = _czifile.decodejpg(encoded, tables)
+ if photometric == 'rgb' and ycbcr_subsampling and ycbcr_positioning:
+ # TODO: convert YCbCr to RGB
+ pass
+ return image.tostring()
+
+
+def decodepackbits(encoded):
+ """Decompress PackBits encoded byte string.
+
+ PackBits is a simple byte-oriented run-length compression scheme.
+
+ """
+ func = ord if sys.version[0] == '2' else lambda x: x
+ result = []
+ result_extend = result.extend
+ i = 0
+ try:
+ while True:
+ n = func(encoded[i]) + 1
+ i += 1
+ if n < 129:
+ result_extend(encoded[i:i+n])
+ i += n
+ elif n > 129:
+ result_extend(encoded[i:i+1] * (258-n))
+ i += 1
+ except IndexError:
+ pass
+ return b''.join(result) if sys.version[0] == '2' else bytes(result)
+
+
+def decodelzw(encoded):
+ """Decompress LZW (Lempel-Ziv-Welch) encoded TIFF strip (byte string).
+
+ The strip must begin with a CLEAR code and end with an EOI code.
+
+ This is an implementation of the LZW decoding algorithm described in (1).
+ It is not compatible with old style LZW compressed files like quad-lzw.tif.
+
+ """
+ len_encoded = len(encoded)
+ bitcount_max = len_encoded * 8
+ unpack = struct.unpack
+
+ if sys.version[0] == '2':
+ newtable = [chr(i) for i in range(256)]
+ else:
+ newtable = [bytes([i]) for i in range(256)]
+ newtable.extend((0, 0))
+
+ def next_code():
+ """Return integer of `bitw` bits at `bitcount` position in encoded."""
+ start = bitcount // 8
+ s = encoded[start:start+4]
+ try:
+ code = unpack('>I', s)[0]
+ except Exception:
+ code = unpack('>I', s + b'\x00'*(4-len(s)))[0]
+ code <<= bitcount % 8
+ code &= mask
+ return code >> shr
+
+ switchbitch = { # code: bit-width, shr-bits, bit-mask
+ 255: (9, 23, int(9*'1'+'0'*23, 2)),
+ 511: (10, 22, int(10*'1'+'0'*22, 2)),
+ 1023: (11, 21, int(11*'1'+'0'*21, 2)),
+ 2047: (12, 20, int(12*'1'+'0'*20, 2)), }
+ bitw, shr, mask = switchbitch[255]
+ bitcount = 0
+
+ if len_encoded < 4:
+ raise ValueError("strip must be at least 4 characters long")
+
+ if next_code() != 256:
+ raise ValueError("strip must begin with CLEAR code")
+
+ code = 0
+ oldcode = 0
+ result = []
+ result_append = result.append
+ while True:
+ code = next_code() # ~5% faster when inlining this function
+ bitcount += bitw
+ if code == 257 or bitcount >= bitcount_max: # EOI
+ break
+ if code == 256: # CLEAR
+ table = newtable[:]
+ table_append = table.append
+ lentable = 258
+ bitw, shr, mask = switchbitch[255]
+ code = next_code()
+ bitcount += bitw
+ if code == 257: # EOI
+ break
+ result_append(table[code])
+ else:
+ if code < lentable:
+ decoded = table[code]
+ newcode = table[oldcode] + decoded[:1]
+ else:
+ newcode = table[oldcode]
+ newcode += newcode[:1]
+ decoded = newcode
+ result_append(decoded)
+ table_append(newcode)
+ lentable += 1
+ oldcode = code
+ if lentable in switchbitch:
+ bitw, shr, mask = switchbitch[lentable]
+
+ if code != 257:
+ warnings.warn("unexpected end of lzw stream (code %i)" % code)
+
+ return b''.join(result)
+
+
+def unpackints(data, dtype, itemsize, runlen=0):
+ """Decompress byte string to array of integers of any bit size <= 32.
+
+ Parameters
+ ----------
+ data : byte str
+ Data to decompress.
+ dtype : numpy.dtype or str
+ A numpy boolean or integer type.
+ itemsize : int
+ Number of bits per integer.
+ runlen : int
+ Number of consecutive integers, after which to start at next byte.
+
+ """
+ if itemsize == 1: # bitarray
+ data = numpy.fromstring(data, '|B')
+ data = numpy.unpackbits(data)
+ if runlen % 8:
+ data = data.reshape(-1, runlen + (8 - runlen % 8))
+ data = data[:, :runlen].reshape(-1)
+ return data.astype(dtype)
+
+ dtype = numpy.dtype(dtype)
+ if itemsize in (8, 16, 32, 64):
+ return numpy.fromstring(data, dtype)
+ if itemsize < 1 or itemsize > 32:
+ raise ValueError("itemsize out of range: %i" % itemsize)
+ if dtype.kind not in "biu":
+ raise ValueError("invalid dtype")
+
+ itembytes = next(i for i in (1, 2, 4, 8) if 8 * i >= itemsize)
+ if itembytes != dtype.itemsize:
+ raise ValueError("dtype.itemsize too small")
+ if runlen == 0:
+ runlen = len(data) // itembytes
+ skipbits = runlen*itemsize % 8
+ if skipbits:
+ skipbits = 8 - skipbits
+ shrbits = itembytes*8 - itemsize
+ bitmask = int(itemsize*'1'+'0'*shrbits, 2)
+ dtypestr = '>' + dtype.char # dtype always big endian?
+
+ unpack = struct.unpack
+ l = runlen * (len(data)*8 // (runlen*itemsize + skipbits))
+ result = numpy.empty((l, ), dtype)
+ bitcount = 0
+ for i in range(len(result)):
+ start = bitcount // 8
+ s = data[start:start+itembytes]
+ try:
+ code = unpack(dtypestr, s)[0]
+ except Exception:
+ code = unpack(dtypestr, s + b'\x00'*(itembytes-len(s)))[0]
+ code <<= bitcount % 8
+ code &= bitmask
+ result[i] = code >> shrbits
+ bitcount += itemsize
+ if (i+1) % runlen == 0:
+ bitcount += skipbits
+ return result
+
+
+def unpackrgb(data, dtype='<B', bitspersample=(5, 6, 5), rescale=True):
+ """Return array from byte string containing packed samples.
+
+ Use to unpack RGB565 or RGB555 to RGB888 format.
+
+ Parameters
+ ----------
+ data : byte str
+ The data to be decoded. Samples in each pixel are stored consecutively.
+ Pixels are aligned to 8, 16, or 32 bit boundaries.
+ dtype : numpy.dtype
+ The sample data type. The byteorder applies also to the data stream.
+ bitspersample : tuple
+ Number of bits for each sample in a pixel.
+ rescale : bool
+ Upscale samples to the number of bits in dtype.
+
+ Returns
+ -------
+ result : ndarray
+ Flattened array of unpacked samples of native dtype.
+
+ Examples
+ --------
+ >>> data = struct.pack('BBBB', 0x21, 0x08, 0xff, 0xff)
+ >>> print(unpackrgb(data, '<B', (5, 6, 5), False))
+ [ 1 1 1 31 63 31]
+ >>> print(unpackrgb(data, '<B', (5, 6, 5)))
+ [ 8 4 8 255 255 255]
+ >>> print(unpackrgb(data, '<B', (5, 5, 5)))
+ [ 16 8 8 255 255 255]
+
+ """
+ dtype = numpy.dtype(dtype)
+ bits = int(numpy.sum(bitspersample))
+ if not (bits <= 32 and all(i <= dtype.itemsize*8 for i in bitspersample)):
+ raise ValueError("sample size not supported %s" % str(bitspersample))
+ dt = next(i for i in 'BHI' if numpy.dtype(i).itemsize*8 >= bits)
+ data = numpy.fromstring(data, dtype.byteorder+dt)
+ result = numpy.empty((data.size, len(bitspersample)), dtype.char)
+ for i, bps in enumerate(bitspersample):
+ t = data >> int(numpy.sum(bitspersample[i+1:]))
+ t &= int('0b'+'1'*bps, 2)
+ if rescale:
+ o = ((dtype.itemsize * 8) // bps + 1) * bps
+ if o > data.dtype.itemsize * 8:
+ t = t.astype('I')
+ t *= (2**o - 1) // (2**bps - 1)
+ t //= 2**(o - (dtype.itemsize * 8))
+ result[:, i] = t
+ return result.reshape(-1)
+
+
+def reorient(image, orientation):
+ """Return reoriented view of image array.
+
+ Parameters
+ ----------
+ image : numpy array
+ Non-squeezed output of asarray() functions.
+ Axes -3 and -2 must be image length and width respectively.
+ orientation : int or str
+ One of TIFF_ORIENTATIONS keys or values.
+
+ """
+ o = TIFF_ORIENTATIONS.get(orientation, orientation)
+ if o == 'top_left':
+ return image
+ elif o == 'top_right':
+ return image[..., ::-1, :]
+ elif o == 'bottom_left':
+ return image[..., ::-1, :, :]
+ elif o == 'bottom_right':
+ return image[..., ::-1, ::-1, :]
+ elif o == 'left_top':
+ return numpy.swapaxes(image, -3, -2)
+ elif o == 'right_top':
+ return numpy.swapaxes(image, -3, -2)[..., ::-1, :]
+ elif o == 'left_bottom':
+ return numpy.swapaxes(image, -3, -2)[..., ::-1, :, :]
+ elif o == 'right_bottom':
+ return numpy.swapaxes(image, -3, -2)[..., ::-1, ::-1, :]
+
+
+def squeeze_axes(shape, axes, skip='XY'):
+ """Return shape and axes with single-dimensional entries removed.
+
+ Remove unused dimensions unless their axes are listed in 'skip'.
+
+ >>> squeeze_axes((5, 1, 2, 1, 1), 'TZYXC')
+ ((5, 2, 1), 'TYX')
+
+ """
+ if len(shape) != len(axes):
+ raise ValueError("dimensions of axes and shape don't match")
+ shape, axes = zip(*(i for i in zip(shape, axes)
+ if i[0] > 1 or i[1] in skip))
+ return shape, ''.join(axes)
+
+
+def transpose_axes(data, axes, asaxes='CTZYX'):
+ """Return data with its axes permuted to match specified axes.
+
+ A view is returned if possible.
+
+ >>> transpose_axes(numpy.zeros((2, 3, 4, 5)), 'TYXC', asaxes='CTZYX').shape
+ (5, 2, 1, 3, 4)
+
+ """
+ for ax in axes:
+ if ax not in asaxes:
+ raise ValueError("unknown axis %s" % ax)
+ # add missing axes to data
+ shape = data.shape
+ for ax in reversed(asaxes):
+ if ax not in axes:
+ axes = ax + axes
+ shape = (1,) + shape
+ data = data.reshape(shape)
+ # transpose axes
+ data = data.transpose([axes.index(ax) for ax in asaxes])
+ return data
+
+
+def stack_pages(pages, memmap=False, *args, **kwargs):
+ """Read data from sequence of TiffPage and stack them vertically.
+
+ If memmap is True, return an array stored in a binary file on disk.
+ Additional parameters are passsed to the page asarray function.
+
+ """
+ if len(pages) == 0:
+ raise ValueError("no pages")
+
+ if len(pages) == 1:
+ return pages[0].asarray(memmap=memmap, *args, **kwargs)
+
+ result = pages[0].asarray(*args, **kwargs)
+ shape = (len(pages),) + result.shape
+ if memmap:
+ with tempfile.NamedTemporaryFile() as fh:
+ result = numpy.memmap(fh, dtype=result.dtype, shape=shape)
+ else:
+ result = numpy.empty(shape, dtype=result.dtype)
+
+ for i, page in enumerate(pages):
+ result[i] = page.asarray(*args, **kwargs)
+
+ return result
+
+
+def stripnull(string):
+ """Return string truncated at first null character.
+
+ Clean NULL terminated C strings.
+
+ >>> stripnull(b'string\\x00') # doctest: +SKIP
+ b'string'
+
+ """
+ i = string.find(b'\x00')
+ return string if (i < 0) else string[:i]
+
+
+def stripascii(string):
+ """Return string truncated at last byte that is 7bit ASCII.
+
+ Clean NULL separated and terminated TIFF strings.
+
+ >>> stripascii(b'string\\x00string\\n\\x01\\x00') # doctest: +SKIP
+ b'string\\x00string\\n'
+ >>> stripascii(b'\\x00') # doctest: +SKIP
+ b''
+
+ """
+ # TODO: pythonize this
+ ord_ = ord if sys.version_info[0] < 3 else lambda x: x
+ i = len(string)
+ while i:
+ i -= 1
+ if 8 < ord_(string[i]) < 127:
+ break
+ else:
+ i = -1
+ return string[:i+1]
+
+
+def format_size(size):
+ """Return file size as string from byte size."""
+ for unit in ('B', 'KB', 'MB', 'GB', 'TB'):
+ if size < 2048:
+ return "%.f %s" % (size, unit)
+ size /= 1024.0
+
+
+def sequence(value):
+ """Return tuple containing value if value is not a sequence.
+
+ >>> sequence(1)
+ (1,)
+ >>> sequence([1])
+ [1]
+
+ """
+ try:
+ len(value)
+ return value
+ except TypeError:
+ return (value, )
+
+
+def product(iterable):
+ """Return product of sequence of numbers.
+
+ Equivalent of functools.reduce(operator.mul, iterable, 1).
+
+ >>> product([2**8, 2**30])
+ 274877906944
+ >>> product([])
+ 1
+
+ """
+ prod = 1
+ for i in iterable:
+ prod *= i
+ return prod
+
+
+def natural_sorted(iterable):
+ """Return human sorted list of strings.
+
+ E.g. for sorting file names.
+
+ >>> natural_sorted(['f1', 'f2', 'f10'])
+ ['f1', 'f2', 'f10']
+
+ """
+ def sortkey(x):
+ return [(int(c) if c.isdigit() else c) for c in re.split(numbers, x)]
+ numbers = re.compile(r'(\d+)')
+ return sorted(iterable, key=sortkey)
+
+
+def excel_datetime(timestamp, epoch=datetime.datetime.fromordinal(693594)):
+ """Return datetime object from timestamp in Excel serial format.
+
+ Convert LSM time stamps.
+
+ >>> excel_datetime(40237.029999999795)
+ datetime.datetime(2010, 2, 28, 0, 43, 11, 999982)
+
+ """
+ return epoch + datetime.timedelta(timestamp)
+
+
+def julian_datetime(julianday, milisecond=0):
+ """Return datetime from days since 1/1/4713 BC and ms since midnight.
+
+ Convert Julian dates according to MetaMorph.
+
+ >>> julian_datetime(2451576, 54362783)
+ datetime.datetime(2000, 2, 2, 15, 6, 2, 783)
+
+ """
+ if julianday <= 1721423:
+ # no datetime before year 1
+ return None
+
+ a = julianday + 1
+ if a > 2299160:
+ alpha = math.trunc((a - 1867216.25) / 36524.25)
+ a += 1 + alpha - alpha // 4
+ b = a + (1524 if a > 1721423 else 1158)
+ c = math.trunc((b - 122.1) / 365.25)
+ d = math.trunc(365.25 * c)
+ e = math.trunc((b - d) / 30.6001)
+
+ day = b - d - math.trunc(30.6001 * e)
+ month = e - (1 if e < 13.5 else 13)
+ year = c - (4716 if month > 2.5 else 4715)
+
+ hour, milisecond = divmod(milisecond, 1000 * 60 * 60)
+ minute, milisecond = divmod(milisecond, 1000 * 60)
+ second, milisecond = divmod(milisecond, 1000)
+
+ return datetime.datetime(year, month, day,
+ hour, minute, second, milisecond)
+
+
+def test_tifffile(directory='testimages', verbose=True):
+ """Read all images in directory.
+
+ Print error message on failure.
+
+ >>> test_tifffile(verbose=False)
+
+ """
+ successful = 0
+ failed = 0
+ start = time.time()
+ for f in glob.glob(os.path.join(directory, '*.*')):
+ if verbose:
+ print("\n%s>\n" % f.lower(), end='')
+ t0 = time.time()
+ try:
+ tif = TiffFile(f, multifile=True)
+ except Exception as e:
+ if not verbose:
+ print(f, end=' ')
+ print("ERROR:", e)
+ failed += 1
+ continue
+ try:
+ img = tif.asarray()
+ except ValueError:
+ try:
+ img = tif[0].asarray()
+ except Exception as e:
+ if not verbose:
+ print(f, end=' ')
+ print("ERROR:", e)
+ failed += 1
+ continue
+ finally:
+ tif.close()
+ successful += 1
+ if verbose:
+ print("%s, %s %s, %s, %.0f ms" % (
+ str(tif), str(img.shape), img.dtype, tif[0].compression,
+ (time.time()-t0) * 1e3))
+ if verbose:
+ print("\nSuccessfully read %i of %i files in %.3f s\n" % (
+ successful, successful+failed, time.time()-start))
+
+
+class TIFF_SUBFILE_TYPES(object):
+ def __getitem__(self, key):
+ result = []
+ if key & 1:
+ result.append('reduced_image')
+ if key & 2:
+ result.append('page')
+ if key & 4:
+ result.append('mask')
+ return tuple(result)
+
+
+TIFF_PHOTOMETRICS = {
+ 0: 'miniswhite',
+ 1: 'minisblack',
+ 2: 'rgb',
+ 3: 'palette',
+ 4: 'mask',
+ 5: 'separated', # CMYK
+ 6: 'ycbcr',
+ 8: 'cielab',
+ 9: 'icclab',
+ 10: 'itulab',
+ 32803: 'cfa', # Color Filter Array
+ 32844: 'logl',
+ 32845: 'logluv',
+ 34892: 'linear_raw'
+}
+
+TIFF_COMPESSIONS = {
+ 1: None,
+ 2: 'ccittrle',
+ 3: 'ccittfax3',
+ 4: 'ccittfax4',
+ 5: 'lzw',
+ 6: 'ojpeg',
+ 7: 'jpeg',
+ 8: 'adobe_deflate',
+ 9: 't85',
+ 10: 't43',
+ 32766: 'next',
+ 32771: 'ccittrlew',
+ 32773: 'packbits',
+ 32809: 'thunderscan',
+ 32895: 'it8ctpad',
+ 32896: 'it8lw',
+ 32897: 'it8mp',
+ 32898: 'it8bl',
+ 32908: 'pixarfilm',
+ 32909: 'pixarlog',
+ 32946: 'deflate',
+ 32947: 'dcs',
+ 34661: 'jbig',
+ 34676: 'sgilog',
+ 34677: 'sgilog24',
+ 34712: 'jp2000',
+ 34713: 'nef',
+}
+
+TIFF_DECOMPESSORS = {
+ None: lambda x: x,
+ 'adobe_deflate': zlib.decompress,
+ 'deflate': zlib.decompress,
+ 'packbits': decodepackbits,
+ 'lzw': decodelzw,
+ # 'jpeg': decodejpg
+}
+
+TIFF_DATA_TYPES = {
+ 1: '1B', # BYTE 8-bit unsigned integer.
+ 2: '1s', # ASCII 8-bit byte that contains a 7-bit ASCII code;
+ # the last byte must be NULL (binary zero).
+ 3: '1H', # SHORT 16-bit (2-byte) unsigned integer
+ 4: '1I', # LONG 32-bit (4-byte) unsigned integer.
+ 5: '2I', # RATIONAL Two LONGs: the first represents the numerator of
+ # a fraction; the second, the denominator.
+ 6: '1b', # SBYTE An 8-bit signed (twos-complement) integer.
+ 7: '1s', # UNDEFINED An 8-bit byte that may contain anything,
+ # depending on the definition of the field.
+ 8: '1h', # SSHORT A 16-bit (2-byte) signed (twos-complement) integer.
+ 9: '1i', # SLONG A 32-bit (4-byte) signed (twos-complement) integer.
+ 10: '2i', # SRATIONAL Two SLONGs: the first represents the numerator
+ # of a fraction, the second the denominator.
+ 11: '1f', # FLOAT Single precision (4-byte) IEEE format.
+ 12: '1d', # DOUBLE Double precision (8-byte) IEEE format.
+ 13: '1I', # IFD unsigned 4 byte IFD offset.
+ #14: '', # UNICODE
+ #15: '', # COMPLEX
+ 16: '1Q', # LONG8 unsigned 8 byte integer (BigTiff)
+ 17: '1q', # SLONG8 signed 8 byte integer (BigTiff)
+ 18: '1Q', # IFD8 unsigned 8 byte IFD offset (BigTiff)
+}
+
+TIFF_SAMPLE_FORMATS = {
+ 1: 'uint',
+ 2: 'int',
+ 3: 'float',
+ #4: 'void',
+ #5: 'complex_int',
+ 6: 'complex',
+}
+
+TIFF_SAMPLE_DTYPES = {
+ ('uint', 1): '?', # bitmap
+ ('uint', 2): 'B',
+ ('uint', 3): 'B',
+ ('uint', 4): 'B',
+ ('uint', 5): 'B',
+ ('uint', 6): 'B',
+ ('uint', 7): 'B',
+ ('uint', 8): 'B',
+ ('uint', 9): 'H',
+ ('uint', 10): 'H',
+ ('uint', 11): 'H',
+ ('uint', 12): 'H',
+ ('uint', 13): 'H',
+ ('uint', 14): 'H',
+ ('uint', 15): 'H',
+ ('uint', 16): 'H',
+ ('uint', 17): 'I',
+ ('uint', 18): 'I',
+ ('uint', 19): 'I',
+ ('uint', 20): 'I',
+ ('uint', 21): 'I',
+ ('uint', 22): 'I',
+ ('uint', 23): 'I',
+ ('uint', 24): 'I',
+ ('uint', 25): 'I',
+ ('uint', 26): 'I',
+ ('uint', 27): 'I',
+ ('uint', 28): 'I',
+ ('uint', 29): 'I',
+ ('uint', 30): 'I',
+ ('uint', 31): 'I',
+ ('uint', 32): 'I',
+ ('uint', 64): 'Q',
+ ('int', 8): 'b',
+ ('int', 16): 'h',
+ ('int', 32): 'i',
+ ('int', 64): 'q',
+ ('float', 16): 'e',
+ ('float', 32): 'f',
+ ('float', 64): 'd',
+ ('complex', 64): 'F',
+ ('complex', 128): 'D',
+ ('uint', (5, 6, 5)): 'B',
+}
+
+TIFF_ORIENTATIONS = {
+ 1: 'top_left',
+ 2: 'top_right',
+ 3: 'bottom_right',
+ 4: 'bottom_left',
+ 5: 'left_top',
+ 6: 'right_top',
+ 7: 'right_bottom',
+ 8: 'left_bottom',
+}
+
+# TODO: is there a standard for character axes labels?
+AXES_LABELS = {
+ 'X': 'width',
+ 'Y': 'height',
+ 'Z': 'depth',
+ 'S': 'sample', # rgb(a)
+ 'I': 'series', # general sequence, plane, page, IFD
+ 'T': 'time',
+ 'C': 'channel', # color, emission wavelength
+ 'A': 'angle',
+ 'P': 'phase', # formerly F # P is Position in LSM!
+ 'R': 'tile', # region, point, mosaic
+ 'H': 'lifetime', # histogram
+ 'E': 'lambda', # excitation wavelength
+ 'L': 'exposure', # lux
+ 'V': 'event',
+ 'Q': 'other',
+ #'M': 'mosaic', # LSM 6
+}
+
+AXES_LABELS.update(dict((v, k) for k, v in AXES_LABELS.items()))
+
+# Map OME pixel types to numpy dtype
+OME_PIXEL_TYPES = {
+ 'int8': 'i1',
+ 'int16': 'i2',
+ 'int32': 'i4',
+ 'uint8': 'u1',
+ 'uint16': 'u2',
+ 'uint32': 'u4',
+ 'float': 'f4',
+ # 'bit': 'bit',
+ 'double': 'f8',
+ 'complex': 'c8',
+ 'double-complex': 'c16',
+}
+
+# NIH Image PicHeader v1.63
+NIH_IMAGE_HEADER = [
+ ('fileid', 'a8'),
+ ('nlines', 'i2'),
+ ('pixelsperline', 'i2'),
+ ('version', 'i2'),
+ ('oldlutmode', 'i2'),
+ ('oldncolors', 'i2'),
+ ('colors', 'u1', (3, 32)),
+ ('oldcolorstart', 'i2'),
+ ('colorwidth', 'i2'),
+ ('extracolors', 'u2', (6, 3)),
+ ('nextracolors', 'i2'),
+ ('foregroundindex', 'i2'),
+ ('backgroundindex', 'i2'),
+ ('xscale', 'f8'),
+ ('_x0', 'i2'),
+ ('_x1', 'i2'),
+ ('units_t', 'i2'), # NIH_UNITS_TYPE
+ ('p1', [('x', 'i2'), ('y', 'i2')]),
+ ('p2', [('x', 'i2'), ('y', 'i2')]),
+ ('curvefit_t', 'i2'), # NIH_CURVEFIT_TYPE
+ ('ncoefficients', 'i2'),
+ ('coeff', 'f8', 6),
+ ('_um_len', 'u1'),
+ ('um', 'a15'),
+ ('_x2', 'u1'),
+ ('binarypic', 'b1'),
+ ('slicestart', 'i2'),
+ ('sliceend', 'i2'),
+ ('scalemagnification', 'f4'),
+ ('nslices', 'i2'),
+ ('slicespacing', 'f4'),
+ ('currentslice', 'i2'),
+ ('frameinterval', 'f4'),
+ ('pixelaspectratio', 'f4'),
+ ('colorstart', 'i2'),
+ ('colorend', 'i2'),
+ ('ncolors', 'i2'),
+ ('fill1', '3u2'),
+ ('fill2', '3u2'),
+ ('colortable_t', 'u1'), # NIH_COLORTABLE_TYPE
+ ('lutmode_t', 'u1'), # NIH_LUTMODE_TYPE
+ ('invertedtable', 'b1'),
+ ('zeroclip', 'b1'),
+ ('_xunit_len', 'u1'),
+ ('xunit', 'a11'),
+ ('stacktype_t', 'i2'), # NIH_STACKTYPE_TYPE
+]
+
+NIH_COLORTABLE_TYPE = (
+ 'CustomTable', 'AppleDefault', 'Pseudo20', 'Pseudo32', 'Rainbow',
+ 'Fire1', 'Fire2', 'Ice', 'Grays', 'Spectrum')
+
+NIH_LUTMODE_TYPE = (
+ 'PseudoColor', 'OldAppleDefault', 'OldSpectrum', 'GrayScale',
+ 'ColorLut', 'CustomGrayscale')
+
+NIH_CURVEFIT_TYPE = (
+ 'StraightLine', 'Poly2', 'Poly3', 'Poly4', 'Poly5', 'ExpoFit',
+ 'PowerFit', 'LogFit', 'RodbardFit', 'SpareFit1', 'Uncalibrated',
+ 'UncalibratedOD')
+
+NIH_UNITS_TYPE = (
+ 'Nanometers', 'Micrometers', 'Millimeters', 'Centimeters', 'Meters',
+ 'Kilometers', 'Inches', 'Feet', 'Miles', 'Pixels', 'OtherUnits')
+
+NIH_STACKTYPE_TYPE = (
+ 'VolumeStack', 'RGBStack', 'MovieStack', 'HSVStack')
+
+# Map Universal Imaging Corporation MetaMorph internal tag ids to name and type
+UIC_TAGS = {
+ 0: ('auto_scale', int),
+ 1: ('min_scale', int),
+ 2: ('max_scale', int),
+ 3: ('spatial_calibration', int),
+ 4: ('x_calibration', Fraction),
+ 5: ('y_calibration', Fraction),
+ 6: ('calibration_units', str),
+ 7: ('name', str),
+ 8: ('thresh_state', int),
+ 9: ('thresh_state_red', int),
+ 10: ('tagid_10', None), # undefined
+ 11: ('thresh_state_green', int),
+ 12: ('thresh_state_blue', int),
+ 13: ('thresh_state_lo', int),
+ 14: ('thresh_state_hi', int),
+ 15: ('zoom', int),
+ 16: ('create_time', julian_datetime),
+ 17: ('last_saved_time', julian_datetime),
+ 18: ('current_buffer', int),
+ 19: ('gray_fit', None),
+ 20: ('gray_point_count', None),
+ 21: ('gray_x', Fraction),
+ 22: ('gray_y', Fraction),
+ 23: ('gray_min', Fraction),
+ 24: ('gray_max', Fraction),
+ 25: ('gray_unit_name', str),
+ 26: ('standard_lut', int),
+ 27: ('wavelength', int),
+ 28: ('stage_position', '(%i,2,2)u4'), # N xy positions as fractions
+ 29: ('camera_chip_offset', '(%i,2,2)u4'), # N xy offsets as fractions
+ 30: ('overlay_mask', None),
+ 31: ('overlay_compress', None),
+ 32: ('overlay', None),
+ 33: ('special_overlay_mask', None),
+ 34: ('special_overlay_compress', None),
+ 35: ('special_overlay', None),
+ 36: ('image_property', read_uic_image_property),
+ 37: ('stage_label', '%ip'), # N str
+ 38: ('autoscale_lo_info', Fraction),
+ 39: ('autoscale_hi_info', Fraction),
+ 40: ('absolute_z', '(%i,2)u4'), # N fractions
+ 41: ('absolute_z_valid', '(%i,)u4'), # N long
+ 42: ('gamma', int),
+ 43: ('gamma_red', int),
+ 44: ('gamma_green', int),
+ 45: ('gamma_blue', int),
+ 46: ('camera_bin', int),
+ 47: ('new_lut', int),
+ 48: ('image_property_ex', None),
+ 49: ('plane_property', int),
+ 50: ('user_lut_table', '(256,3)u1'),
+ 51: ('red_autoscale_info', int),
+ 52: ('red_autoscale_lo_info', Fraction),
+ 53: ('red_autoscale_hi_info', Fraction),
+ 54: ('red_minscale_info', int),
+ 55: ('red_maxscale_info', int),
+ 56: ('green_autoscale_info', int),
+ 57: ('green_autoscale_lo_info', Fraction),
+ 58: ('green_autoscale_hi_info', Fraction),
+ 59: ('green_minscale_info', int),
+ 60: ('green_maxscale_info', int),
+ 61: ('blue_autoscale_info', int),
+ 62: ('blue_autoscale_lo_info', Fraction),
+ 63: ('blue_autoscale_hi_info', Fraction),
+ 64: ('blue_min_scale_info', int),
+ 65: ('blue_max_scale_info', int),
+ #66: ('overlay_plane_color', read_uic_overlay_plane_color),
+}
+
+
+# Olympus FluoView
+MM_DIMENSION = [
+ ('name', 'a16'),
+ ('size', 'i4'),
+ ('origin', 'f8'),
+ ('resolution', 'f8'),
+ ('unit', 'a64'),
+]
+
+MM_HEADER = [
+ ('header_flag', 'i2'),
+ ('image_type', 'u1'),
+ ('image_name', 'a257'),
+ ('offset_data', 'u4'),
+ ('palette_size', 'i4'),
+ ('offset_palette0', 'u4'),
+ ('offset_palette1', 'u4'),
+ ('comment_size', 'i4'),
+ ('offset_comment', 'u4'),
+ ('dimensions', MM_DIMENSION, 10),
+ ('offset_position', 'u4'),
+ ('map_type', 'i2'),
+ ('map_min', 'f8'),
+ ('map_max', 'f8'),
+ ('min_value', 'f8'),
+ ('max_value', 'f8'),
+ ('offset_map', 'u4'),
+ ('gamma', 'f8'),
+ ('offset', 'f8'),
+ ('gray_channel', MM_DIMENSION),
+ ('offset_thumbnail', 'u4'),
+ ('voice_field', 'i4'),
+ ('offset_voice_field', 'u4'),
+]
+
+# Carl Zeiss LSM
+CZ_LSM_INFO = [
+ ('magic_number', 'u4'),
+ ('structure_size', 'i4'),
+ ('dimension_x', 'i4'),
+ ('dimension_y', 'i4'),
+ ('dimension_z', 'i4'),
+ ('dimension_channels', 'i4'),
+ ('dimension_time', 'i4'),
+ ('data_type', 'i4'), # CZ_DATA_TYPES
+ ('thumbnail_x', 'i4'),
+ ('thumbnail_y', 'i4'),
+ ('voxel_size_x', 'f8'),
+ ('voxel_size_y', 'f8'),
+ ('voxel_size_z', 'f8'),
+ ('origin_x', 'f8'),
+ ('origin_y', 'f8'),
+ ('origin_z', 'f8'),
+ ('scan_type', 'u2'),
+ ('spectral_scan', 'u2'),
+ ('type_of_data', 'u4'), # CZ_TYPE_OF_DATA
+ ('offset_vector_overlay', 'u4'),
+ ('offset_input_lut', 'u4'),
+ ('offset_output_lut', 'u4'),
+ ('offset_channel_colors', 'u4'),
+ ('time_interval', 'f8'),
+ ('offset_channel_data_types', 'u4'),
+ ('offset_scan_info', 'u4'), # CZ_LSM_SCAN_INFO
+ ('offset_ks_data', 'u4'),
+ ('offset_time_stamps', 'u4'),
+ ('offset_event_list', 'u4'),
+ ('offset_roi', 'u4'),
+ ('offset_bleach_roi', 'u4'),
+ ('offset_next_recording', 'u4'),
+ # LSM 2.0 ends here
+ ('display_aspect_x', 'f8'),
+ ('display_aspect_y', 'f8'),
+ ('display_aspect_z', 'f8'),
+ ('display_aspect_time', 'f8'),
+ ('offset_mean_of_roi_overlay', 'u4'),
+ ('offset_topo_isoline_overlay', 'u4'),
+ ('offset_topo_profile_overlay', 'u4'),
+ ('offset_linescan_overlay', 'u4'),
+ ('offset_toolbar_flags', 'u4'),
+ ('offset_channel_wavelength', 'u4'),
+ ('offset_channel_factors', 'u4'),
+ ('objective_sphere_correction', 'f8'),
+ ('offset_unmix_parameters', 'u4'),
+ # LSM 3.2, 4.0 end here
+ ('offset_acquisition_parameters', 'u4'),
+ ('offset_characteristics', 'u4'),
+ ('offset_palette', 'u4'),
+ ('time_difference_x', 'f8'),
+ ('time_difference_y', 'f8'),
+ ('time_difference_z', 'f8'),
+ ('internal_use_1', 'u4'),
+ ('dimension_p', 'i4'),
+ ('dimension_m', 'i4'),
+ ('dimensions_reserved', '16i4'),
+ ('offset_tile_positions', 'u4'),
+ ('reserved_1', '9u4'),
+ ('offset_positions', 'u4'),
+ ('reserved_2', '21u4'), # must be 0
+]
+
+# Import functions for LSM_INFO sub-records
+CZ_LSM_INFO_READERS = {
+ 'scan_info': read_cz_lsm_scan_info,
+ 'time_stamps': read_cz_lsm_time_stamps,
+ 'event_list': read_cz_lsm_event_list,
+ 'channel_colors': read_cz_lsm_floatpairs,
+ 'positions': read_cz_lsm_floatpairs,
+ 'tile_positions': read_cz_lsm_floatpairs,
+}
+
+# Map cz_lsm_info.scan_type to dimension order
+CZ_SCAN_TYPES = {
+ 0: 'XYZCT', # x-y-z scan
+ 1: 'XYZCT', # z scan (x-z plane)
+ 2: 'XYZCT', # line scan
+ 3: 'XYTCZ', # time series x-y
+ 4: 'XYZTC', # time series x-z
+ 5: 'XYTCZ', # time series 'Mean of ROIs'
+ 6: 'XYZTC', # time series x-y-z
+ 7: 'XYCTZ', # spline scan
+ 8: 'XYCZT', # spline scan x-z
+ 9: 'XYTCZ', # time series spline plane x-z
+ 10: 'XYZCT', # point mode
+}
+
+# Map dimension codes to cz_lsm_info attribute
+CZ_DIMENSIONS = {
+ 'X': 'dimension_x',
+ 'Y': 'dimension_y',
+ 'Z': 'dimension_z',
+ 'C': 'dimension_channels',
+ 'T': 'dimension_time',
+}
+
+# Description of cz_lsm_info.data_type
+CZ_DATA_TYPES = {
+ 0: 'varying data types',
+ 1: '8 bit unsigned integer',
+ 2: '12 bit unsigned integer',
+ 5: '32 bit float',
+}
+
+# Description of cz_lsm_info.type_of_data
+CZ_TYPE_OF_DATA = {
+ 0: 'Original scan data',
+ 1: 'Calculated data',
+ 2: '3D reconstruction',
+ 3: 'Topography height map',
+}
+
+CZ_LSM_SCAN_INFO_ARRAYS = {
+ 0x20000000: "tracks",
+ 0x30000000: "lasers",
+ 0x60000000: "detection_channels",
+ 0x80000000: "illumination_channels",
+ 0xa0000000: "beam_splitters",
+ 0xc0000000: "data_channels",
+ 0x11000000: "timers",
+ 0x13000000: "markers",
+}
+
+CZ_LSM_SCAN_INFO_STRUCTS = {
+ # 0x10000000: "recording",
+ 0x40000000: "track",
+ 0x50000000: "laser",
+ 0x70000000: "detection_channel",
+ 0x90000000: "illumination_channel",
+ 0xb0000000: "beam_splitter",
+ 0xd0000000: "data_channel",
+ 0x12000000: "timer",
+ 0x14000000: "marker",
+}
+
+CZ_LSM_SCAN_INFO_ATTRIBUTES = {
+ # recording
+ 0x10000001: "name",
+ 0x10000002: "description",
+ 0x10000003: "notes",
+ 0x10000004: "objective",
+ 0x10000005: "processing_summary",
+ 0x10000006: "special_scan_mode",
+ 0x10000007: "scan_type",
+ 0x10000008: "scan_mode",
+ 0x10000009: "number_of_stacks",
+ 0x1000000a: "lines_per_plane",
+ 0x1000000b: "samples_per_line",
+ 0x1000000c: "planes_per_volume",
+ 0x1000000d: "images_width",
+ 0x1000000e: "images_height",
+ 0x1000000f: "images_number_planes",
+ 0x10000010: "images_number_stacks",
+ 0x10000011: "images_number_channels",
+ 0x10000012: "linscan_xy_size",
+ 0x10000013: "scan_direction",
+ 0x10000014: "time_series",
+ 0x10000015: "original_scan_data",
+ 0x10000016: "zoom_x",
+ 0x10000017: "zoom_y",
+ 0x10000018: "zoom_z",
+ 0x10000019: "sample_0x",
+ 0x1000001a: "sample_0y",
+ 0x1000001b: "sample_0z",
+ 0x1000001c: "sample_spacing",
+ 0x1000001d: "line_spacing",
+ 0x1000001e: "plane_spacing",
+ 0x1000001f: "plane_width",
+ 0x10000020: "plane_height",
+ 0x10000021: "volume_depth",
+ 0x10000023: "nutation",
+ 0x10000034: "rotation",
+ 0x10000035: "precession",
+ 0x10000036: "sample_0time",
+ 0x10000037: "start_scan_trigger_in",
+ 0x10000038: "start_scan_trigger_out",
+ 0x10000039: "start_scan_event",
+ 0x10000040: "start_scan_time",
+ 0x10000041: "stop_scan_trigger_in",
+ 0x10000042: "stop_scan_trigger_out",
+ 0x10000043: "stop_scan_event",
+ 0x10000044: "stop_scan_time",
+ 0x10000045: "use_rois",
+ 0x10000046: "use_reduced_memory_rois",
+ 0x10000047: "user",
+ 0x10000048: "use_bc_correction",
+ 0x10000049: "position_bc_correction1",
+ 0x10000050: "position_bc_correction2",
+ 0x10000051: "interpolation_y",
+ 0x10000052: "camera_binning",
+ 0x10000053: "camera_supersampling",
+ 0x10000054: "camera_frame_width",
+ 0x10000055: "camera_frame_height",
+ 0x10000056: "camera_offset_x",
+ 0x10000057: "camera_offset_y",
+ 0x10000059: "rt_binning",
+ 0x1000005a: "rt_frame_width",
+ 0x1000005b: "rt_frame_height",
+ 0x1000005c: "rt_region_width",
+ 0x1000005d: "rt_region_height",
+ 0x1000005e: "rt_offset_x",
+ 0x1000005f: "rt_offset_y",
+ 0x10000060: "rt_zoom",
+ 0x10000061: "rt_line_period",
+ 0x10000062: "prescan",
+ 0x10000063: "scan_direction_z",
+ # track
+ 0x40000001: "multiplex_type", # 0 after line; 1 after frame
+ 0x40000002: "multiplex_order",
+ 0x40000003: "sampling_mode", # 0 sample; 1 line average; 2 frame average
+ 0x40000004: "sampling_method", # 1 mean; 2 sum
+ 0x40000005: "sampling_number",
+ 0x40000006: "acquire",
+ 0x40000007: "sample_observation_time",
+ 0x4000000b: "time_between_stacks",
+ 0x4000000c: "name",
+ 0x4000000d: "collimator1_name",
+ 0x4000000e: "collimator1_position",
+ 0x4000000f: "collimator2_name",
+ 0x40000010: "collimator2_position",
+ 0x40000011: "is_bleach_track",
+ 0x40000012: "is_bleach_after_scan_number",
+ 0x40000013: "bleach_scan_number",
+ 0x40000014: "trigger_in",
+ 0x40000015: "trigger_out",
+ 0x40000016: "is_ratio_track",
+ 0x40000017: "bleach_count",
+ 0x40000018: "spi_center_wavelength",
+ 0x40000019: "pixel_time",
+ 0x40000021: "condensor_frontlens",
+ 0x40000023: "field_stop_value",
+ 0x40000024: "id_condensor_aperture",
+ 0x40000025: "condensor_aperture",
+ 0x40000026: "id_condensor_revolver",
+ 0x40000027: "condensor_filter",
+ 0x40000028: "id_transmission_filter1",
+ 0x40000029: "id_transmission1",
+ 0x40000030: "id_transmission_filter2",
+ 0x40000031: "id_transmission2",
+ 0x40000032: "repeat_bleach",
+ 0x40000033: "enable_spot_bleach_pos",
+ 0x40000034: "spot_bleach_posx",
+ 0x40000035: "spot_bleach_posy",
+ 0x40000036: "spot_bleach_posz",
+ 0x40000037: "id_tubelens",
+ 0x40000038: "id_tubelens_position",
+ 0x40000039: "transmitted_light",
+ 0x4000003a: "reflected_light",
+ 0x4000003b: "simultan_grab_and_bleach",
+ 0x4000003c: "bleach_pixel_time",
+ # laser
+ 0x50000001: "name",
+ 0x50000002: "acquire",
+ 0x50000003: "power",
+ # detection_channel
+ 0x70000001: "integration_mode",
+ 0x70000002: "special_mode",
+ 0x70000003: "detector_gain_first",
+ 0x70000004: "detector_gain_last",
+ 0x70000005: "amplifier_gain_first",
+ 0x70000006: "amplifier_gain_last",
+ 0x70000007: "amplifier_offs_first",
+ 0x70000008: "amplifier_offs_last",
+ 0x70000009: "pinhole_diameter",
+ 0x7000000a: "counting_trigger",
+ 0x7000000b: "acquire",
+ 0x7000000c: "point_detector_name",
+ 0x7000000d: "amplifier_name",
+ 0x7000000e: "pinhole_name",
+ 0x7000000f: "filter_set_name",
+ 0x70000010: "filter_name",
+ 0x70000013: "integrator_name",
+ 0x70000014: "channel_name",
+ 0x70000015: "detector_gain_bc1",
+ 0x70000016: "detector_gain_bc2",
+ 0x70000017: "amplifier_gain_bc1",
+ 0x70000018: "amplifier_gain_bc2",
+ 0x70000019: "amplifier_offset_bc1",
+ 0x70000020: "amplifier_offset_bc2",
+ 0x70000021: "spectral_scan_channels",
+ 0x70000022: "spi_wavelength_start",
+ 0x70000023: "spi_wavelength_stop",
+ 0x70000026: "dye_name",
+ 0x70000027: "dye_folder",
+ # illumination_channel
+ 0x90000001: "name",
+ 0x90000002: "power",
+ 0x90000003: "wavelength",
+ 0x90000004: "aquire",
+ 0x90000005: "detchannel_name",
+ 0x90000006: "power_bc1",
+ 0x90000007: "power_bc2",
+ # beam_splitter
+ 0xb0000001: "filter_set",
+ 0xb0000002: "filter",
+ 0xb0000003: "name",
+ # data_channel
+ 0xd0000001: "name",
+ 0xd0000003: "acquire",
+ 0xd0000004: "color",
+ 0xd0000005: "sample_type",
+ 0xd0000006: "bits_per_sample",
+ 0xd0000007: "ratio_type",
+ 0xd0000008: "ratio_track1",
+ 0xd0000009: "ratio_track2",
+ 0xd000000a: "ratio_channel1",
+ 0xd000000b: "ratio_channel2",
+ 0xd000000c: "ratio_const1",
+ 0xd000000d: "ratio_const2",
+ 0xd000000e: "ratio_const3",
+ 0xd000000f: "ratio_const4",
+ 0xd0000010: "ratio_const5",
+ 0xd0000011: "ratio_const6",
+ 0xd0000012: "ratio_first_images1",
+ 0xd0000013: "ratio_first_images2",
+ 0xd0000014: "dye_name",
+ 0xd0000015: "dye_folder",
+ 0xd0000016: "spectrum",
+ 0xd0000017: "acquire",
+ # timer
+ 0x12000001: "name",
+ 0x12000002: "description",
+ 0x12000003: "interval",
+ 0x12000004: "trigger_in",
+ 0x12000005: "trigger_out",
+ 0x12000006: "activation_time",
+ 0x12000007: "activation_number",
+ # marker
+ 0x14000001: "name",
+ 0x14000002: "description",
+ 0x14000003: "trigger_in",
+ 0x14000004: "trigger_out",
+}
+
+# Map TIFF tag code to attribute name, default value, type, count, validator
+TIFF_TAGS = {
+ 254: ('new_subfile_type', 0, 4, 1, TIFF_SUBFILE_TYPES()),
+ 255: ('subfile_type', None, 3, 1,
+ {0: 'undefined', 1: 'image', 2: 'reduced_image', 3: 'page'}),
+ 256: ('image_width', None, 4, 1, None),
+ 257: ('image_length', None, 4, 1, None),
+ 258: ('bits_per_sample', 1, 3, 1, None),
+ 259: ('compression', 1, 3, 1, TIFF_COMPESSIONS),
+ 262: ('photometric', None, 3, 1, TIFF_PHOTOMETRICS),
+ 266: ('fill_order', 1, 3, 1, {1: 'msb2lsb', 2: 'lsb2msb'}),
+ 269: ('document_name', None, 2, None, None),
+ 270: ('image_description', None, 2, None, None),
+ 271: ('make', None, 2, None, None),
+ 272: ('model', None, 2, None, None),
+ 273: ('strip_offsets', None, 4, None, None),
+ 274: ('orientation', 1, 3, 1, TIFF_ORIENTATIONS),
+ 277: ('samples_per_pixel', 1, 3, 1, None),
+ 278: ('rows_per_strip', 2**32-1, 4, 1, None),
+ 279: ('strip_byte_counts', None, 4, None, None),
+ 280: ('min_sample_value', None, 3, None, None),
+ 281: ('max_sample_value', None, 3, None, None), # 2**bits_per_sample
+ 282: ('x_resolution', None, 5, 1, None),
+ 283: ('y_resolution', None, 5, 1, None),
+ 284: ('planar_configuration', 1, 3, 1, {1: 'contig', 2: 'separate'}),
+ 285: ('page_name', None, 2, None, None),
+ 286: ('x_position', None, 5, 1, None),
+ 287: ('y_position', None, 5, 1, None),
+ 296: ('resolution_unit', 2, 4, 1, {1: 'none', 2: 'inch', 3: 'centimeter'}),
+ 297: ('page_number', None, 3, 2, None),
+ 305: ('software', None, 2, None, None),
+ 306: ('datetime', None, 2, None, None),
+ 315: ('artist', None, 2, None, None),
+ 316: ('host_computer', None, 2, None, None),
+ 317: ('predictor', 1, 3, 1, {1: None, 2: 'horizontal'}),
+ 318: ('white_point', None, 5, 2, None),
+ 319: ('primary_chromaticities', None, 5, 6, None),
+ 320: ('color_map', None, 3, None, None),
+ 322: ('tile_width', None, 4, 1, None),
+ 323: ('tile_length', None, 4, 1, None),
+ 324: ('tile_offsets', None, 4, None, None),
+ 325: ('tile_byte_counts', None, 4, None, None),
+ 338: ('extra_samples', None, 3, None,
+ {0: 'unspecified', 1: 'assocalpha', 2: 'unassalpha'}),
+ 339: ('sample_format', 1, 3, 1, TIFF_SAMPLE_FORMATS),
+ 340: ('smin_sample_value', None, None, None, None),
+ 341: ('smax_sample_value', None, None, None, None),
+ 347: ('jpeg_tables', None, 7, None, None),
+ 530: ('ycbcr_subsampling', 1, 3, 2, None),
+ 531: ('ycbcr_positioning', 1, 3, 1, None),
+ 32996: ('sgi_matteing', None, None, 1, None), # use extra_samples
+ 32996: ('sgi_datatype', None, None, 1, None), # use sample_format
+ 32997: ('image_depth', None, 4, 1, None),
+ 32998: ('tile_depth', None, 4, 1, None),
+ 33432: ('copyright', None, 1, None, None),
+ 33445: ('md_file_tag', None, 4, 1, None),
+ 33446: ('md_scale_pixel', None, 5, 1, None),
+ 33447: ('md_color_table', None, 3, None, None),
+ 33448: ('md_lab_name', None, 2, None, None),
+ 33449: ('md_sample_info', None, 2, None, None),
+ 33450: ('md_prep_date', None, 2, None, None),
+ 33451: ('md_prep_time', None, 2, None, None),
+ 33452: ('md_file_units', None, 2, None, None),
+ 33550: ('model_pixel_scale', None, 12, 3, None),
+ 33922: ('model_tie_point', None, 12, None, None),
+ 34665: ('exif_ifd', None, None, 1, None),
+ 34735: ('geo_key_directory', None, 3, None, None),
+ 34736: ('geo_double_params', None, 12, None, None),
+ 34737: ('geo_ascii_params', None, 2, None, None),
+ 34853: ('gps_ifd', None, None, 1, None),
+ 37510: ('user_comment', None, None, None, None),
+ 42112: ('gdal_metadata', None, 2, None, None),
+ 42113: ('gdal_nodata', None, 2, None, None),
+ 50289: ('mc_xy_position', None, 12, 2, None),
+ 50290: ('mc_z_position', None, 12, 1, None),
+ 50291: ('mc_xy_calibration', None, 12, 3, None),
+ 50292: ('mc_lens_lem_na_n', None, 12, 3, None),
+ 50293: ('mc_channel_name', None, 1, None, None),
+ 50294: ('mc_ex_wavelength', None, 12, 1, None),
+ 50295: ('mc_time_stamp', None, 12, 1, None),
+ 50838: ('imagej_byte_counts', None, None, None, None),
+ 65200: ('flex_xml', None, 2, None, None),
+ # code: (attribute name, default value, type, count, validator)
+}
+
+# Map custom TIFF tag codes to attribute names and import functions
+CUSTOM_TAGS = {
+ 700: ('xmp', read_bytes),
+ 34377: ('photoshop', read_numpy),
+ 33723: ('iptc', read_bytes),
+ 34675: ('icc_profile', read_bytes),
+ 33628: ('uic1tag', read_uic1tag), # Universal Imaging Corporation STK
+ 33629: ('uic2tag', read_uic2tag),
+ 33630: ('uic3tag', read_uic3tag),
+ 33631: ('uic4tag', read_uic4tag),
+ 34361: ('mm_header', read_mm_header), # Olympus FluoView
+ 34362: ('mm_stamp', read_mm_stamp),
+ 34386: ('mm_user_block', read_bytes),
+ 34412: ('cz_lsm_info', read_cz_lsm_info), # Carl Zeiss LSM
+ 43314: ('nih_image_header', read_nih_image_header),
+ # 40001: ('mc_ipwinscal', read_bytes),
+ 40100: ('mc_id_old', read_bytes),
+ 50288: ('mc_id', read_bytes),
+ 50296: ('mc_frame_properties', read_bytes),
+ 50839: ('imagej_metadata', read_bytes),
+ 51123: ('micromanager_metadata', read_json),
+}
+
+# Max line length of printed output
+PRINT_LINE_LEN = 79
+
+
+def imshow(data, title=None, vmin=0, vmax=None, cmap=None,
+ bitspersample=None, photometric='rgb', interpolation='nearest',
+ dpi=96, figure=None, subplot=111, maxdim=8192, **kwargs):
+ """Plot n-dimensional images using matplotlib.pyplot.
+
+ Return figure, subplot and plot axis.
+ Requires pyplot already imported ``from matplotlib import pyplot``.
+
+ Parameters
+ ----------
+ bitspersample : int or None
+ Number of bits per channel in integer RGB images.
+ photometric : {'miniswhite', 'minisblack', 'rgb', or 'palette'}
+ The color space of the image data.
+ title : str
+ Window and subplot title.
+ figure : matplotlib.figure.Figure (optional).
+ Matplotlib to use for plotting.
+ subplot : int
+ A matplotlib.pyplot.subplot axis.
+ maxdim : int
+ maximum image size in any dimension.
+ kwargs : optional
+ Arguments for matplotlib.pyplot.imshow.
+
+ """
+ #if photometric not in ('miniswhite', 'minisblack', 'rgb', 'palette'):
+ # raise ValueError("Can't handle %s photometrics" % photometric)
+ # TODO: handle photometric == 'separated' (CMYK)
+ isrgb = photometric in ('rgb', 'palette')
+ data = numpy.atleast_2d(data.squeeze())
+ data = data[(slice(0, maxdim), ) * len(data.shape)]
+
+ dims = data.ndim
+ if dims < 2:
+ raise ValueError("not an image")
+ elif dims == 2:
+ dims = 0
+ isrgb = False
+ else:
+ if isrgb and data.shape[-3] in (3, 4):
+ data = numpy.swapaxes(data, -3, -2)
+ data = numpy.swapaxes(data, -2, -1)
+ elif not isrgb and (data.shape[-1] < data.shape[-2] // 16 and
+ data.shape[-1] < data.shape[-3] // 16 and
+ data.shape[-1] < 5):
+ data = numpy.swapaxes(data, -3, -1)
+ data = numpy.swapaxes(data, -2, -1)
+ isrgb = isrgb and data.shape[-1] in (3, 4)
+ dims -= 3 if isrgb else 2
+
+ if photometric == 'palette' and isrgb:
+ datamax = data.max()
+ if datamax > 255:
+ data >>= 8 # possible precision loss
+ data = data.astype('B')
+ elif data.dtype.kind in 'ui':
+ if not (isrgb and data.dtype.itemsize <= 1) or bitspersample is None:
+ try:
+ bitspersample = int(math.ceil(math.log(data.max(), 2)))
+ except Exception:
+ bitspersample = data.dtype.itemsize * 8
+ elif not isinstance(bitspersample, int):
+ # bitspersample can be tuple, e.g. (5, 6, 5)
+ bitspersample = data.dtype.itemsize * 8
+ datamax = 2**bitspersample
+ if isrgb:
+ if bitspersample < 8:
+ data <<= 8 - bitspersample
+ elif bitspersample > 8:
+ data >>= bitspersample - 8 # precision loss
+ data = data.astype('B')
+ elif data.dtype.kind == 'f':
+ datamax = data.max()
+ if isrgb and datamax > 1.0:
+ if data.dtype.char == 'd':
+ data = data.astype('f')
+ data /= datamax
+ elif data.dtype.kind == 'b':
+ datamax = 1
+ elif data.dtype.kind == 'c':
+ raise NotImplementedError("complex type") # TODO: handle complex types
+
+ if not isrgb:
+ if vmax is None:
+ vmax = datamax
+ if vmin is None:
+ if data.dtype.kind == 'i':
+ dtmin = numpy.iinfo(data.dtype).min
+ vmin = numpy.min(data)
+ if vmin == dtmin:
+ vmin = numpy.min(data > dtmin)
+ if data.dtype.kind == 'f':
+ dtmin = numpy.finfo(data.dtype).min
+ vmin = numpy.min(data)
+ if vmin == dtmin:
+ vmin = numpy.min(data > dtmin)
+ else:
+ vmin = 0
+
+ pyplot = sys.modules['matplotlib.pyplot']
+
+ if figure is None:
+ pyplot.rc('font', family='sans-serif', weight='normal', size=8)
+ figure = pyplot.figure(dpi=dpi, figsize=(10.3, 6.3), frameon=True,
+ facecolor='1.0', edgecolor='w')
+ try:
+ figure.canvas.manager.window.title(title)
+ except Exception:
+ pass
+ pyplot.subplots_adjust(bottom=0.03*(dims+2), top=0.9,
+ left=0.1, right=0.95, hspace=0.05, wspace=0.0)
+ subplot = pyplot.subplot(subplot)
+
+ if title:
+ try:
+ title = unicode(title, 'Windows-1252')
+ except TypeError:
+ pass
+ pyplot.title(title, size=11)
+
+ if cmap is None:
+ if data.dtype.kind in 'ubf' or vmin == 0:
+ cmap = 'cubehelix'
+ else:
+ cmap = 'coolwarm'
+ if photometric == 'miniswhite':
+ cmap += '_r'
+
+ image = pyplot.imshow(data[(0, ) * dims].squeeze(), vmin=vmin, vmax=vmax,
+ cmap=cmap, interpolation=interpolation, **kwargs)
+
+ if not isrgb:
+ pyplot.colorbar() # panchor=(0.55, 0.5), fraction=0.05
+
+ def format_coord(x, y):
+ # callback function to format coordinate display in toolbar
+ x = int(x + 0.5)
+ y = int(y + 0.5)
+ try:
+ if dims:
+ return "%s @ %s [%4i, %4i]" % (cur_ax_dat[1][y, x],
+ current, x, y)
+ else:
+ return "%s @ [%4i, %4i]" % (data[y, x], x, y)
+ except IndexError:
+ return ""
+
+ pyplot.gca().format_coord = format_coord
+
+ if dims:
+ current = list((0, ) * dims)
+ cur_ax_dat = [0, data[tuple(current)].squeeze()]
+ sliders = [pyplot.Slider(
+ pyplot.axes([0.125, 0.03*(axis+1), 0.725, 0.025]),
+ 'Dimension %i' % axis, 0, data.shape[axis]-1, 0, facecolor='0.5',
+ valfmt='%%.0f [%i]' % data.shape[axis]) for axis in range(dims)]
+ for slider in sliders:
+ slider.drawon = False
+
+ def set_image(current, sliders=sliders, data=data):
+ # change image and redraw canvas
+ cur_ax_dat[1] = data[tuple(current)].squeeze()
+ image.set_data(cur_ax_dat[1])
+ for ctrl, index in zip(sliders, current):
+ ctrl.eventson = False
+ ctrl.set_val(index)
+ ctrl.eventson = True
+ figure.canvas.draw()
+
+ def on_changed(index, axis, data=data, current=current):
+ # callback function for slider change event
+ index = int(round(index))
+ cur_ax_dat[0] = axis
+ if index == current[axis]:
+ return
+ if index >= data.shape[axis]:
+ index = 0
+ elif index < 0:
+ index = data.shape[axis] - 1
+ current[axis] = index
+ set_image(current)
+
+ def on_keypressed(event, data=data, current=current):
+ # callback function for key press event
+ key = event.key
+ axis = cur_ax_dat[0]
+ if str(key) in '0123456789':
+ on_changed(key, axis)
+ elif key == 'right':
+ on_changed(current[axis] + 1, axis)
+ elif key == 'left':
+ on_changed(current[axis] - 1, axis)
+ elif key == 'up':
+ cur_ax_dat[0] = 0 if axis == len(data.shape)-1 else axis + 1
+ elif key == 'down':
+ cur_ax_dat[0] = len(data.shape)-1 if axis == 0 else axis - 1
+ elif key == 'end':
+ on_changed(data.shape[axis] - 1, axis)
+ elif key == 'home':
+ on_changed(0, axis)
+
+ figure.canvas.mpl_connect('key_press_event', on_keypressed)
+ for axis, ctrl in enumerate(sliders):
+ ctrl.on_changed(lambda k, a=axis: on_changed(k, a))
+
+ return figure, subplot, image
+
+
+def _app_show():
+ """Block the GUI. For use as skimage plugin."""
+ pyplot = sys.modules['matplotlib.pyplot']
+ pyplot.show()
+
+
+def main(argv=None):
+ """Command line usage main function."""
+ if float(sys.version[0:3]) < 2.6:
+ print("This script requires Python version 2.6 or better.")
+ print("This is Python version %s" % sys.version)
+ return 0
+ if argv is None:
+ argv = sys.argv
+
+ import optparse
+
+ parser = optparse.OptionParser(
+ usage="usage: %prog [options] path",
+ description="Display image data in TIFF files.",
+ version="%%prog %s" % __version__)
+ opt = parser.add_option
+ opt('-p', '--page', dest='page', type='int', default=-1,
+ help="display single page")
+ opt('-s', '--series', dest='series', type='int', default=-1,
+ help="display series of pages of same shape")
+ opt('--nomultifile', dest='nomultifile', action='store_true',
+ default=False, help="don't read OME series from multiple files")
+ opt('--noplot', dest='noplot', action='store_true', default=False,
+ help="don't display images")
+ opt('--interpol', dest='interpol', metavar='INTERPOL', default='bilinear',
+ help="image interpolation method")
+ opt('--dpi', dest='dpi', type='int', default=96,
+ help="set plot resolution")
+ opt('--debug', dest='debug', action='store_true', default=False,
+ help="raise exception on failures")
+ opt('--test', dest='test', action='store_true', default=False,
+ help="try read all images in path")
+ opt('--doctest', dest='doctest', action='store_true', default=False,
+ help="runs the docstring examples")
+ opt('-v', '--verbose', dest='verbose', action='store_true', default=True)
+ opt('-q', '--quiet', dest='verbose', action='store_false')
+
+ settings, path = parser.parse_args()
+ path = ' '.join(path)
+
+ if settings.doctest:
+ import doctest
+ doctest.testmod()
+ return 0
+ if not path:
+ parser.error("No file specified")
+ if settings.test:
+ test_tifffile(path, settings.verbose)
+ return 0
+
+ if any(i in path for i in '?*'):
+ path = glob.glob(path)
+ if not path:
+ print('no files match the pattern')
+ return 0
+ # TODO: handle image sequences
+ #if len(path) == 1:
+ path = path[0]
+
+ print("Reading file structure...", end=' ')
+ start = time.time()
+ try:
+ tif = TiffFile(path, multifile=not settings.nomultifile)
+ except Exception as e:
+ if settings.debug:
+ raise
+ else:
+ print("\n", e)
+ sys.exit(0)
+ print("%.3f ms" % ((time.time()-start) * 1e3))
+
+ if tif.is_ome:
+ settings.norgb = True
+
+ images = [(None, tif[0 if settings.page < 0 else settings.page])]
+ if not settings.noplot:
+ print("Reading image data... ", end=' ')
+
+ def notnone(x):
+ return next(i for i in x if i is not None)
+ start = time.time()
+ try:
+ if settings.page >= 0:
+ images = [(tif.asarray(key=settings.page),
+ tif[settings.page])]
+ elif settings.series >= 0:
+ images = [(tif.asarray(series=settings.series),
+ notnone(tif.series[settings.series].pages))]
+ else:
+ images = []
+ for i, s in enumerate(tif.series):
+ try:
+ images.append(
+ (tif.asarray(series=i), notnone(s.pages)))
+ except ValueError as e:
+ images.append((None, notnone(s.pages)))
+ if settings.debug:
+ raise
+ else:
+ print("\n* series %i failed: %s... " % (i, e),
+ end='')
+ print("%.3f ms" % ((time.time()-start) * 1e3))
+ except Exception as e:
+ if settings.debug:
+ raise
+ else:
+ print(e)
+
+ tif.close()
+
+ print("\nTIFF file:", tif)
+ print()
+ for i, s in enumerate(tif.series):
+ print("Series %i" % i)
+ print(s)
+ print()
+ for i, page in images:
+ print(page)
+ print(page.tags)
+ if page.is_palette:
+ print("\nColor Map:", page.color_map.shape, page.color_map.dtype)
+ for attr in ('cz_lsm_info', 'cz_lsm_scan_info', 'uic_tags',
+ 'mm_header', 'imagej_tags', 'micromanager_metadata',
+ 'nih_image_header'):
+ if hasattr(page, attr):
+ print("", attr.upper(), Record(getattr(page, attr)), sep="\n")
+ print()
+ if page.is_micromanager:
+ print('MICROMANAGER_FILE_METADATA')
+ print(Record(tif.micromanager_metadata))
+
+ if images and not settings.noplot:
+ try:
+ import matplotlib
+ matplotlib.use('TkAgg')
+ from matplotlib import pyplot
+ except ImportError as e:
+ warnings.warn("failed to import matplotlib.\n%s" % e)
+ else:
+ for img, page in images:
+ if img is None:
+ continue
+ vmin, vmax = None, None
+ if 'gdal_nodata' in page.tags:
+ try:
+ vmin = numpy.min(img[img > float(page.gdal_nodata)])
+ except ValueError:
+ pass
+ if page.is_stk:
+ try:
+ vmin = page.uic_tags['min_scale']
+ vmax = page.uic_tags['max_scale']
+ except KeyError:
+ pass
+ else:
+ if vmax <= vmin:
+ vmin, vmax = None, None
+ title = "%s\n %s" % (str(tif), str(page))
+ imshow(img, title=title, vmin=vmin, vmax=vmax,
+ bitspersample=page.bits_per_sample,
+ photometric=page.photometric,
+ interpolation=settings.interpol,
+ dpi=settings.dpi)
+ pyplot.show()
+
+
+TIFFfile = TiffFile # backwards compatibility
+
+if sys.version_info[0] > 2:
+ basestring = str, bytes
+ unicode = str
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/imageio/plugins/tifffile.py b/imageio/plugins/tifffile.py
new file mode 100644
index 0000000..6e4eba0
--- /dev/null
+++ b/imageio/plugins/tifffile.py
@@ -0,0 +1,229 @@
+# -*- coding: utf-8 -*-
+# Copyright (c) 2015, imageio contributors
+# imageio is distributed under the terms of the (new) BSD License.
+
+""" Storage of image data in tiff format.
+"""
+
+from __future__ import absolute_import, print_function, division
+
+from .. import formats
+from ..core import Format
+
+import numpy as np
+
+_tifffile = None # Defer loading to lib() function.
+
+
+def load_lib():
+ global _tifffile
+ try:
+ import tifffile as _tifffile
+ except ImportError:
+ from . import _tifffile
+ return _tifffile
+
+
+TIFF_FORMATS = ('.tif', '.tiff', '.stk', '.lsm')
+WRITE_METADATA_KEYS = ('photometric', 'planarconfig', 'resolution',
+ 'description', 'compress', 'volume', 'writeshape',
+ 'extratags')
+READ_METADATA_KEYS = ('planar_configuration', 'is_fluoview', 'is_nih',
+ 'is_contig', 'is_micromanager', 'is_ome', 'is_lsm'
+ 'is_palette', 'is_reduced', 'is_rgb', 'is_sgi',
+ 'is_shaped', 'is_stk', 'is_tiled', 'is_mdgel'
+ 'resolution_unit', 'compression', 'is_mediacy',
+ 'orientation')
+
+
+class TiffFormat(Format):
+
+ """ Provides support for a wide range of Tiff images.
+
+ Parameters for reading
+ ----------------------
+ offset : int
+ Optional start position of embedded file. By default this is
+ the current file position.
+ size : int
+ Optional size of embedded file. By default this is the number
+ of bytes from the 'offset' to the end of the file.
+ multifile : bool
+ If True (default), series may include pages from multiple files.
+ Currently applies to OME-TIFF only.
+ multifile_close : bool
+ If True (default), keep the handles of other files in multifile
+ series closed. This is inefficient when few files refer to
+ many pages. If False, the C runtime may run out of resources.
+
+ Parameters for saving
+ ---------------------
+ bigtiff : bool
+ If True, the BigTIFF format is used.
+ byteorder : {'<', '>'}
+ The endianness of the data in the file.
+ By default this is the system's native byte order.
+ software : str
+ Name of the software used to create the image.
+ Saved with the first page only.
+
+ Metadata for reading
+ --------------------
+ planar_configuration : {'contig', 'planar'}
+ Specifies if samples are stored contiguous or in separate planes.
+ By default this setting is inferred from the data shape.
+ 'contig': last dimension contains samples.
+ 'planar': third last dimension contains samples.
+ resolution_unit : (float, float) or ((int, int), (int, int))
+ X and Y resolution in dots per inch as float or rational numbers.
+ compression : int
+ Values from 0 to 9 indicating the level of zlib compression.
+ If 0, data is uncompressed.
+ orientation : {'top_left', 'bottom_right', ...}
+ Oriented of image array.
+ is_rgb : bool
+ True if page contains a RGB image.
+ is_contig : bool
+ True if page contains a contiguous image.
+ is_tiled : bool
+ True if page contains tiled image.
+ is_palette : bool
+ True if page contains a palette-colored image and not OME or STK.
+ is_reduced : bool
+ True if page is a reduced image of another image.
+ is_shaped : bool
+ True if page contains shape in image_description tag.
+ is_fluoview : bool
+ True if page contains FluoView MM_STAMP tag.
+ is_nih : bool
+ True if page contains NIH image header.
+ is_micromanager : bool
+ True if page contains Micro-Manager metadata.
+ is_ome : bool
+ True if page contains OME-XML in image_description tag.
+ is_sgi : bool
+ True if page contains SGI image and tile depth tags.
+ is_stk : bool
+ True if page contains UIC2Tag tag.
+ is_mdgel : bool
+ True if page contains md_file_tag tag.
+ is_mediacy : bool
+ True if page contains Media Cybernetics Id tag.
+ is_stk : bool
+ True if page contains UIC2Tag tag.
+ is_lsm : bool
+ True if page contains LSM CZ_LSM_INFO tag.
+
+ Metadata for writing
+ --------------------
+ photometric : {'minisblack', 'miniswhite', 'rgb'}
+ The color space of the image data.
+ By default this setting is inferred from the data shape.
+ planarconfig : {'contig', 'planar'}
+ Specifies if samples are stored contiguous or in separate planes.
+ By default this setting is inferred from the data shape.
+ 'contig': last dimension contains samples.
+ 'planar': third last dimension contains samples.
+ resolution : (float, float) or ((int, int), (int, int))
+ X and Y resolution in dots per inch as float or rational numbers.
+ description : str
+ The subject of the image. Saved with the first page only.
+ compress : int
+ Values from 0 to 9 controlling the level of zlib compression.
+ If 0, data are written uncompressed (default).
+ volume : bool
+ If True, volume data are stored in one tile (if applicable) using
+ the SGI image_depth and tile_depth tags.
+ Image width and depth must be multiple of 16.
+ Few software can read this format, e.g. MeVisLab.
+ writeshape : bool
+ If True, write the data shape to the image_description tag
+ if necessary and no other description is given.
+ extratags: sequence of tuples
+ Additional tags as [(code, dtype, count, value, writeonce)].
+
+ code : int
+ The TIFF tag Id.
+ dtype : str
+ Data type of items in 'value' in Python struct format.
+ One of B, s, H, I, 2I, b, h, i, f, d, Q, or q.
+ count : int
+ Number of data values. Not used for string values.
+ value : sequence
+ 'Count' values compatible with 'dtype'.
+ writeonce : bool
+ If True, the tag is written to the first page only.
+ """
+
+ def _can_read(self, request):
+ # We support any kind of image data
+ return request.filename.lower().endswith(TIFF_FORMATS)
+
+ def _can_write(self, request):
+ # We support any kind of image data
+ return request.filename.lower().endswith(TIFF_FORMATS)
+
+ # -- reader
+
+ class Reader(Format.Reader):
+
+ def _open(self, **kwargs):
+ if not _tifffile:
+ load_lib()
+ self._tf = _tifffile.TiffFile(self.request.get_file(), **kwargs)
+
+ # metadata is the same for all images
+ self._meta = {}
+
+ def _close(self):
+ self._tf.close()
+
+ def _get_length(self):
+ return len(self._tf)
+
+ def _get_data(self, index):
+ # Get data
+ if index < 0 or index >= len(self._tf):
+ raise IndexError(
+ 'Index out of range while reading from tiff file')
+ im = self._tf[index].asarray()
+ meta = self._meta or self._get_meta_data(index)
+ # Return array and empty meta data
+ return im, meta
+
+ def _get_meta_data(self, index):
+ page = self._tf[index or 0]
+ for key in READ_METADATA_KEYS:
+ try:
+ self._meta[key] = getattr(page, key)
+ except Exception:
+ pass
+ return self._meta
+
+ # -- writer
+ class Writer(Format.Writer):
+
+ def _open(self, bigtiff=None, byteorder=None, software=None):
+ if not _tifffile:
+ load_lib()
+ self._tf = _tifffile.TiffWriter(self.request.get_local_filename(),
+ bigtiff, byteorder, software)
+ self._meta = {}
+
+ def _close(self):
+ self._tf.close()
+
+ def _append_data(self, im, meta):
+ meta = meta or self._meta
+ print(meta)
+ self._tf.save(np.asanyarray(im), **meta)
+
+ def set_meta_data(self, meta):
+ self._meta = {}
+ for (key, value) in meta.items():
+ if key in WRITE_METADATA_KEYS:
+ self._meta[key] = value
+
+# Register
+format = TiffFormat('tiff', "TIFF format", 'tif tiff stk lsm', 'iIvV')
+formats.add_format(format)
| Plugin: scientific TIFF files
In some fields a variant of the TIFF format is heavily used, e.g. for multiplanar microscopic images. Like OME-TIFF (https://www.openmicroscopy.org/site/support/ome-model/ome-tiff/).
The freeimage TIFF reader only deals with basic TIFF.
This is not really my field, so could use some input on what is needed.
One implementation that we could potentially use is: http://www.lfd.uci.edu/~gohlke/code/tifffile.py.html
I believe there was another, but I cannot remember. | imageio/imageio | diff --git a/tests/test_meta.py b/tests/test_meta.py
index d8bcf21..2d08a82 100644
--- a/tests/test_meta.py
+++ b/tests/test_meta.py
@@ -122,7 +122,8 @@ def test_import_dependencies():
# Get the difference; what do we import extra?
extra_modules = modnames_new.difference(modnames_ref)
- known_modules = ['zipfile', 'importlib'] # discard these
+ known_modules = ['zipfile', 'importlib', 'json', 'decimal',
+ 'fractions'] # discard these
# Remove modules in standard library
stdloc = os.path.dirname(os.__file__)
diff --git a/tests/test_tifffile.py b/tests/test_tifffile.py
new file mode 100644
index 0000000..67fb089
--- /dev/null
+++ b/tests/test_tifffile.py
@@ -0,0 +1,61 @@
+""" Test tifffile plugin functionality.
+"""
+
+import os
+
+import numpy as np
+
+from pytest import raises
+from imageio.testing import run_tests_if_main, get_test_dir
+
+import imageio
+
+test_dir = get_test_dir()
+
+
+def test_tifffile_format():
+ # Test selection
+ for name in ['tiff', '.tif']:
+ format = imageio.formats['tiff']
+ assert format.name == 'TIFF'
+
+
+def test_tifffile_reading_writing():
+ """ Test reading and saveing tiff """
+ im2 = np.ones((10, 10, 3), np.uint8) * 2
+
+ filename1 = os.path.join(test_dir, 'test_tiff.tiff')
+
+ # One image
+ imageio.imsave(filename1, im2)
+ im = imageio.imread(filename1)
+ ims = imageio.mimread(filename1)
+ assert (im == im2).all()
+ assert len(ims) == 1
+
+ # Multiple images
+ imageio.mimsave(filename1, [im2, im2, im2])
+ im = imageio.imread(filename1)
+ ims = imageio.mimread(filename1)
+ assert (im == im2).all()
+ assert len(ims) == 3, ims[0].shape
+
+ # Mixed
+ W = imageio.save(filename1)
+ W.set_meta_data({'planarconfig': 'planar'})
+ assert W.format.name == 'TIFF'
+ W.append_data(im2)
+ W.append_data(im2)
+ W.close()
+ #
+ R = imageio.read(filename1)
+ assert R.format.name == 'TIFF'
+ ims = list(R) # == [im for im in R]
+ assert (ims[0] == im2).all()
+ meta = R.get_meta_data()
+ assert meta['is_rgb']
+ # Fail
+ raises(IndexError, R.get_data, -1)
+ raises(IndexError, R.get_data, 3)
+
+run_tests_if_main()
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_hyperlinks",
"has_added_files"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 3,
"issue_text_score": 2,
"test_score": 3
},
"num_modified_files": 1
} | 1.3 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[dev]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "numpy>=1.16.0",
"pip_packages": [
"pytest",
"pytest-cov"
],
"pre_install": [
"apt-get update",
"apt-get install -y libfreeimage3"
],
"python": "3.9",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | coverage==7.8.0
exceptiongroup==1.2.2
-e git+https://github.com/imageio/imageio.git@d99d9a25cd8db0920d42cf5d3f372471776865fe#egg=imageio
iniconfig==2.1.0
numpy @ file:///croot/numpy_and_numpy_base_1736283260865/work/dist/numpy-2.0.2-cp39-cp39-linux_x86_64.whl#sha256=3387e3e62932fa288bc18e8f445ce19e998b418a65ed2064dd40a054f976a6c7
packaging==24.2
pluggy==1.5.0
pytest==8.3.5
pytest-cov==6.0.0
tomli==2.2.1
| name: imageio
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- blas=1.0=openblas
- ca-certificates=2025.2.25=h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgfortran-ng=11.2.0=h00389a5_1
- libgfortran5=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libopenblas=0.3.21=h043d6bf_0
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- numpy=2.0.2=py39heeff2f4_0
- numpy-base=2.0.2=py39h8a23956_0
- openssl=3.0.16=h5eee18b_0
- pip=25.0=py39h06a4308_0
- python=3.9.21=he870216_1
- readline=8.2=h5eee18b_0
- setuptools=72.1.0=py39h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- tzdata=2025a=h04d1e81_0
- wheel=0.45.1=py39h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- coverage==7.8.0
- exceptiongroup==1.2.2
- iniconfig==2.1.0
- packaging==24.2
- pluggy==1.5.0
- pytest==8.3.5
- pytest-cov==6.0.0
- tomli==2.2.1
prefix: /opt/conda/envs/imageio
| [
"tests/test_tifffile.py::test_tifffile_reading_writing"
] | [] | [
"tests/test_meta.py::test_namespace",
"tests/test_meta.py::test_import_nothing",
"tests/test_meta.py::test_import_modules",
"tests/test_meta.py::test_import_dependencies",
"tests/test_tifffile.py::test_tifffile_format"
] | [] | BSD 2-Clause "Simplified" License | 183 |
|
sympy__sympy-9622 | 3ae27d8c8d8b2d792b193855093cd9dc3f06d116 | 2015-07-06 07:30:35 | 0241b35cae5f2adc04dc37b25f7dc9c5f00bd746 | leosartaj: Polys interface of diff is different from that of sympy's. Therefore unevaluated Derivative creation can fail. eg.
```
>>> p = Poly(x**2 + x, x)
>>> diff(p, (x, 1))
Poly(3*x**2, x, domain='ZZ') # works
>>> diff(p, (x, 1), evaluate=False)
AttributeError
```
This is beacause ``Derivative`` doesn't recognize this interface.
By removing [L-2204](https://github.com/sympy/sympy/pull/9622/files#diff-c96d00473bda7f403c25a06fc5814515R2204) and [L-2205](https://github.com/sympy/sympy/pull/9622/files#diff-c96d00473bda7f403c25a06fc5814515R2205), ``diff`` will always try to evaluate and never return unevaluated ``Derivative``.
These are my thoughts. Suggestions?
leosartaj: Ping @jksuom @aktech
aktech: This looks fine to me, except for the minor [comment](https://github.com/sympy/sympy/pull/9622#discussion_r33917493). | diff --git a/sympy/polys/polytools.py b/sympy/polys/polytools.py
index 1a119855c1..60b1cae841 100644
--- a/sympy/polys/polytools.py
+++ b/sympy/polys/polytools.py
@@ -12,6 +12,7 @@
from sympy.core.relational import Relational
from sympy.core.sympify import sympify
from sympy.core.decorators import _sympifyit
+from sympy.core.function import Derivative
from sympy.logic.boolalg import BooleanAtom
@@ -2183,7 +2184,7 @@ def integrate(self, *specs, **args):
else: # pragma: no cover
raise OperationNotSupported(f, 'integrate')
- def diff(f, *specs):
+ def diff(f, *specs, **kwargs):
"""
Computes partial derivative of ``f``.
@@ -2200,6 +2201,9 @@ def diff(f, *specs):
Poly(2*x*y, x, y, domain='ZZ')
"""
+ if not kwargs.get('evaluate', True):
+ return Derivative(f, *specs, **kwargs)
+
if hasattr(f.rep, 'diff'):
if not specs:
return f.per(f.rep.diff(m=1))
@@ -2218,6 +2222,9 @@ def diff(f, *specs):
else: # pragma: no cover
raise OperationNotSupported(f, 'diff')
+ _eval_derivative = diff
+ _eval_diff = diff
+
def eval(self, x, a=None, auto=True):
"""
Evaluate ``f`` at ``a`` in the given variable.
| inconsistent diff on polynomials
From this stackoverflow question: http://stackoverflow.com/questions/31120436/why-does-sympy-diff-not-differentiate-sympy-polynomials-as-expected
``` python
In [1]: from sympy import *
In [2]: from sympy.abc import x
In [3]: p = Poly(x+1, x, domain='QQ')
In [4]: p.diff(x)
Out[4]: Poly(1, x, domain='QQ')
In [5]: diff(p, x)
Out[5]: Derivative(Poly(x + 1, x, domain='QQ'), x)
In [6]: diff(p, x).doit()
Out[6]: Derivative(Poly(x + 1, x, domain='ZZ'), x)
```
Seems like the toplevel `diff` is following a different code path compared to the `diff` method on Poly.
| sympy/sympy | diff --git a/sympy/polys/tests/test_polytools.py b/sympy/polys/tests/test_polytools.py
index 38deab20d5..2f6310e59b 100644
--- a/sympy/polys/tests/test_polytools.py
+++ b/sympy/polys/tests/test_polytools.py
@@ -51,8 +51,8 @@
from sympy.polys.orderings import lex, grlex, grevlex
from sympy import (
- S, Integer, Rational, Float, Mul, Symbol, sqrt, Piecewise,
- exp, sin, tanh, expand, oo, I, pi, re, im, RootOf, Eq, Tuple, Expr)
+ S, Integer, Rational, Float, Mul, Symbol, sqrt, Piecewise, Derivative,
+ exp, sin, tanh, expand, oo, I, pi, re, im, RootOf, Eq, Tuple, Expr, diff)
from sympy.core.basic import _aresame
from sympy.core.compatibility import iterable
@@ -1423,6 +1423,13 @@ def test_Poly_diff():
assert Poly(x**2*y**2 + x*y).diff(y, x) == Poly(4*x*y + 1)
+def test_issue_9585():
+ assert diff(Poly(x**2 + x)) == Poly(2*x + 1)
+ assert diff(Poly(x**2 + x), x, evaluate=False) == \
+ Derivative(Poly(x**2 + x), x)
+ assert Derivative(Poly(x**2 + x), x).doit() == Poly(2*x + 1)
+
+
def test_Poly_eval():
assert Poly(0, x).eval(7) == 0
assert Poly(1, x).eval(7) == 1
diff --git a/sympy/solvers/tests/test_solveset.py b/sympy/solvers/tests/test_solveset.py
index 3883120704..d1106efcf5 100644
--- a/sympy/solvers/tests/test_solveset.py
+++ b/sympy/solvers/tests/test_solveset.py
@@ -40,6 +40,7 @@
def test_invert_real():
x = Dummy(real=True)
n = Symbol('n')
+ d = Dummy()
assert solveset(abs(x) - n, x) == Intersection(S.Reals, FiniteSet(-n, n))
n = Symbol('n', real=True)
@@ -587,6 +588,7 @@ def test_solveset_complex_polynomial():
def test_sol_zero_complex():
+ # This should return the complex set after it is implemented
assert solveset_complex(0, x) == S.Complex
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_hyperlinks",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 1,
"issue_text_score": 2,
"test_score": 1
},
"num_modified_files": 1
} | 0.7 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "pytest",
"pip_packages": [
"pytest"
],
"pre_install": null,
"python": "3.4",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | attrs @ file:///opt/conda/conda-bld/attrs_1642510447205/work
certifi==2021.5.30
importlib-metadata @ file:///tmp/build/80754af9/importlib-metadata_1631916693255/work
iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work
more-itertools @ file:///tmp/build/80754af9/more-itertools_1637733554872/work
mpmath==1.3.0
packaging @ file:///tmp/build/80754af9/packaging_1637314298585/work
pluggy @ file:///tmp/build/80754af9/pluggy_1615976315926/work
py @ file:///opt/conda/conda-bld/py_1644396412707/work
pyparsing @ file:///tmp/build/80754af9/pyparsing_1635766073266/work
pytest==6.2.4
-e git+https://github.com/sympy/sympy.git@3ae27d8c8d8b2d792b193855093cd9dc3f06d116#egg=sympy
toml @ file:///tmp/build/80754af9/toml_1616166611790/work
typing_extensions @ file:///opt/conda/conda-bld/typing_extensions_1647553014482/work
zipp @ file:///tmp/build/80754af9/zipp_1633618647012/work
| name: sympy
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- attrs=21.4.0=pyhd3eb1b0_0
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- importlib-metadata=4.8.1=py36h06a4308_0
- importlib_metadata=4.8.1=hd3eb1b0_0
- iniconfig=1.1.1=pyhd3eb1b0_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- more-itertools=8.12.0=pyhd3eb1b0_0
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- packaging=21.3=pyhd3eb1b0_0
- pip=21.2.2=py36h06a4308_0
- pluggy=0.13.1=py36h06a4308_0
- py=1.11.0=pyhd3eb1b0_0
- pyparsing=3.0.4=pyhd3eb1b0_0
- pytest=6.2.4=py36h06a4308_2
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_0
- setuptools=58.0.4=py36h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- toml=0.10.2=pyhd3eb1b0_0
- typing_extensions=4.1.1=pyh06a4308_0
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- zipp=3.6.0=pyhd3eb1b0_0
- zlib=1.2.13=h5eee18b_1
- pip:
- mpmath==1.3.0
prefix: /opt/conda/envs/sympy
| [
"sympy/polys/tests/test_polytools.py::test_issue_9585"
] | [] | [
"sympy/polys/tests/test_polytools.py::test_Poly_from_dict",
"sympy/polys/tests/test_polytools.py::test_Poly_from_list",
"sympy/polys/tests/test_polytools.py::test_Poly_from_poly",
"sympy/polys/tests/test_polytools.py::test_Poly_from_expr",
"sympy/polys/tests/test_polytools.py::test_Poly__new__",
"sympy/polys/tests/test_polytools.py::test_Poly__args",
"sympy/polys/tests/test_polytools.py::test_Poly__gens",
"sympy/polys/tests/test_polytools.py::test_Poly_zero",
"sympy/polys/tests/test_polytools.py::test_Poly_one",
"sympy/polys/tests/test_polytools.py::test_Poly__unify",
"sympy/polys/tests/test_polytools.py::test_Poly_free_symbols",
"sympy/polys/tests/test_polytools.py::test_PurePoly_free_symbols",
"sympy/polys/tests/test_polytools.py::test_Poly__eq__",
"sympy/polys/tests/test_polytools.py::test_PurePoly__eq__",
"sympy/polys/tests/test_polytools.py::test_PurePoly_Poly",
"sympy/polys/tests/test_polytools.py::test_Poly_get_domain",
"sympy/polys/tests/test_polytools.py::test_Poly_set_domain",
"sympy/polys/tests/test_polytools.py::test_Poly_get_modulus",
"sympy/polys/tests/test_polytools.py::test_Poly_set_modulus",
"sympy/polys/tests/test_polytools.py::test_Poly_add_ground",
"sympy/polys/tests/test_polytools.py::test_Poly_sub_ground",
"sympy/polys/tests/test_polytools.py::test_Poly_mul_ground",
"sympy/polys/tests/test_polytools.py::test_Poly_quo_ground",
"sympy/polys/tests/test_polytools.py::test_Poly_exquo_ground",
"sympy/polys/tests/test_polytools.py::test_Poly_abs",
"sympy/polys/tests/test_polytools.py::test_Poly_neg",
"sympy/polys/tests/test_polytools.py::test_Poly_add",
"sympy/polys/tests/test_polytools.py::test_Poly_sub",
"sympy/polys/tests/test_polytools.py::test_Poly_mul",
"sympy/polys/tests/test_polytools.py::test_Poly_sqr",
"sympy/polys/tests/test_polytools.py::test_Poly_pow",
"sympy/polys/tests/test_polytools.py::test_Poly_divmod",
"sympy/polys/tests/test_polytools.py::test_Poly_eq_ne",
"sympy/polys/tests/test_polytools.py::test_Poly_nonzero",
"sympy/polys/tests/test_polytools.py::test_Poly_properties",
"sympy/polys/tests/test_polytools.py::test_Poly_is_irreducible",
"sympy/polys/tests/test_polytools.py::test_Poly_subs",
"sympy/polys/tests/test_polytools.py::test_Poly_replace",
"sympy/polys/tests/test_polytools.py::test_Poly_reorder",
"sympy/polys/tests/test_polytools.py::test_Poly_ltrim",
"sympy/polys/tests/test_polytools.py::test_Poly_has_only_gens",
"sympy/polys/tests/test_polytools.py::test_Poly_to_ring",
"sympy/polys/tests/test_polytools.py::test_Poly_to_field",
"sympy/polys/tests/test_polytools.py::test_Poly_to_exact",
"sympy/polys/tests/test_polytools.py::test_Poly_retract",
"sympy/polys/tests/test_polytools.py::test_Poly_slice",
"sympy/polys/tests/test_polytools.py::test_Poly_coeffs",
"sympy/polys/tests/test_polytools.py::test_Poly_monoms",
"sympy/polys/tests/test_polytools.py::test_Poly_terms",
"sympy/polys/tests/test_polytools.py::test_Poly_all_coeffs",
"sympy/polys/tests/test_polytools.py::test_Poly_all_monoms",
"sympy/polys/tests/test_polytools.py::test_Poly_all_terms",
"sympy/polys/tests/test_polytools.py::test_Poly_termwise",
"sympy/polys/tests/test_polytools.py::test_Poly_length",
"sympy/polys/tests/test_polytools.py::test_Poly_as_dict",
"sympy/polys/tests/test_polytools.py::test_Poly_as_expr",
"sympy/polys/tests/test_polytools.py::test_Poly_lift",
"sympy/polys/tests/test_polytools.py::test_Poly_deflate",
"sympy/polys/tests/test_polytools.py::test_Poly_inject",
"sympy/polys/tests/test_polytools.py::test_Poly_eject",
"sympy/polys/tests/test_polytools.py::test_Poly_exclude",
"sympy/polys/tests/test_polytools.py::test_Poly__gen_to_level",
"sympy/polys/tests/test_polytools.py::test_Poly_degree",
"sympy/polys/tests/test_polytools.py::test_Poly_degree_list",
"sympy/polys/tests/test_polytools.py::test_Poly_total_degree",
"sympy/polys/tests/test_polytools.py::test_Poly_homogenize",
"sympy/polys/tests/test_polytools.py::test_Poly_homogeneous_order",
"sympy/polys/tests/test_polytools.py::test_Poly_LC",
"sympy/polys/tests/test_polytools.py::test_Poly_TC",
"sympy/polys/tests/test_polytools.py::test_Poly_EC",
"sympy/polys/tests/test_polytools.py::test_Poly_coeff",
"sympy/polys/tests/test_polytools.py::test_Poly_nth",
"sympy/polys/tests/test_polytools.py::test_Poly_LM",
"sympy/polys/tests/test_polytools.py::test_Poly_LM_custom_order",
"sympy/polys/tests/test_polytools.py::test_Poly_EM",
"sympy/polys/tests/test_polytools.py::test_Poly_LT",
"sympy/polys/tests/test_polytools.py::test_Poly_ET",
"sympy/polys/tests/test_polytools.py::test_Poly_max_norm",
"sympy/polys/tests/test_polytools.py::test_Poly_l1_norm",
"sympy/polys/tests/test_polytools.py::test_Poly_clear_denoms",
"sympy/polys/tests/test_polytools.py::test_Poly_rat_clear_denoms",
"sympy/polys/tests/test_polytools.py::test_Poly_integrate",
"sympy/polys/tests/test_polytools.py::test_Poly_diff",
"sympy/polys/tests/test_polytools.py::test_Poly_eval",
"sympy/polys/tests/test_polytools.py::test_Poly___call__",
"sympy/polys/tests/test_polytools.py::test_parallel_poly_from_expr",
"sympy/polys/tests/test_polytools.py::test_pdiv",
"sympy/polys/tests/test_polytools.py::test_div",
"sympy/polys/tests/test_polytools.py::test_gcdex",
"sympy/polys/tests/test_polytools.py::test_revert",
"sympy/polys/tests/test_polytools.py::test_subresultants",
"sympy/polys/tests/test_polytools.py::test_resultant",
"sympy/polys/tests/test_polytools.py::test_discriminant",
"sympy/polys/tests/test_polytools.py::test_dispersion",
"sympy/polys/tests/test_polytools.py::test_gcd_list",
"sympy/polys/tests/test_polytools.py::test_lcm_list",
"sympy/polys/tests/test_polytools.py::test_gcd",
"sympy/polys/tests/test_polytools.py::test_gcd_numbers_vs_polys",
"sympy/polys/tests/test_polytools.py::test_terms_gcd",
"sympy/polys/tests/test_polytools.py::test_trunc",
"sympy/polys/tests/test_polytools.py::test_monic",
"sympy/polys/tests/test_polytools.py::test_content",
"sympy/polys/tests/test_polytools.py::test_primitive",
"sympy/polys/tests/test_polytools.py::test_compose",
"sympy/polys/tests/test_polytools.py::test_shift",
"sympy/polys/tests/test_polytools.py::test_sturm",
"sympy/polys/tests/test_polytools.py::test_gff",
"sympy/polys/tests/test_polytools.py::test_sqf_norm",
"sympy/polys/tests/test_polytools.py::test_sqf",
"sympy/polys/tests/test_polytools.py::test_factor",
"sympy/polys/tests/test_polytools.py::test_factor_large",
"sympy/polys/tests/test_polytools.py::test_intervals",
"sympy/polys/tests/test_polytools.py::test_refine_root",
"sympy/polys/tests/test_polytools.py::test_count_roots",
"sympy/polys/tests/test_polytools.py::test_Poly_root",
"sympy/polys/tests/test_polytools.py::test_real_roots",
"sympy/polys/tests/test_polytools.py::test_all_roots",
"sympy/polys/tests/test_polytools.py::test_nroots",
"sympy/polys/tests/test_polytools.py::test_ground_roots",
"sympy/polys/tests/test_polytools.py::test_nth_power_roots_poly",
"sympy/polys/tests/test_polytools.py::test_torational_factor_list",
"sympy/polys/tests/test_polytools.py::test_cancel",
"sympy/polys/tests/test_polytools.py::test_reduced",
"sympy/polys/tests/test_polytools.py::test_groebner",
"sympy/polys/tests/test_polytools.py::test_fglm",
"sympy/polys/tests/test_polytools.py::test_is_zero_dimensional",
"sympy/polys/tests/test_polytools.py::test_GroebnerBasis",
"sympy/polys/tests/test_polytools.py::test_poly",
"sympy/polys/tests/test_polytools.py::test_keep_coeff",
"sympy/polys/tests/test_polytools.py::test_noncommutative",
"sympy/polys/tests/test_polytools.py::test_to_rational_coeffs",
"sympy/solvers/tests/test_solveset.py::test_invert_real",
"sympy/solvers/tests/test_solveset.py::test_invert_complex",
"sympy/solvers/tests/test_solveset.py::test_domain_check",
"sympy/solvers/tests/test_solveset.py::test_is_function_class_equation",
"sympy/solvers/tests/test_solveset.py::test_garbage_input",
"sympy/solvers/tests/test_solveset.py::test_solve_mul",
"sympy/solvers/tests/test_solveset.py::test_solve_invert",
"sympy/solvers/tests/test_solveset.py::test_errorinverses",
"sympy/solvers/tests/test_solveset.py::test_solve_polynomial",
"sympy/solvers/tests/test_solveset.py::test_return_root_of",
"sympy/solvers/tests/test_solveset.py::test__has_rational_power",
"sympy/solvers/tests/test_solveset.py::test_solveset_sqrt_1",
"sympy/solvers/tests/test_solveset.py::test_solveset_sqrt_2",
"sympy/solvers/tests/test_solveset.py::test_solve_sqrt_3",
"sympy/solvers/tests/test_solveset.py::test_solve_polynomial_symbolic_param",
"sympy/solvers/tests/test_solveset.py::test_solve_rational",
"sympy/solvers/tests/test_solveset.py::test_solveset_real_gen_is_pow",
"sympy/solvers/tests/test_solveset.py::test_no_sol",
"sympy/solvers/tests/test_solveset.py::test_sol_zero_real",
"sympy/solvers/tests/test_solveset.py::test_no_sol_rational_extragenous",
"sympy/solvers/tests/test_solveset.py::test_solve_polynomial_cv_1a",
"sympy/solvers/tests/test_solveset.py::test_solveset_real_rational",
"sympy/solvers/tests/test_solveset.py::test_solveset_real_log",
"sympy/solvers/tests/test_solveset.py::test_poly_gens",
"sympy/solvers/tests/test_solveset.py::test_solve_abs",
"sympy/solvers/tests/test_solveset.py::test_real_imag_splitting",
"sympy/solvers/tests/test_solveset.py::test_units",
"sympy/solvers/tests/test_solveset.py::test_solve_only_exp_1",
"sympy/solvers/tests/test_solveset.py::test_atan2",
"sympy/solvers/tests/test_solveset.py::test_piecewise",
"sympy/solvers/tests/test_solveset.py::test_solveset_complex_polynomial",
"sympy/solvers/tests/test_solveset.py::test_sol_zero_complex",
"sympy/solvers/tests/test_solveset.py::test_solveset_complex_rational",
"sympy/solvers/tests/test_solveset.py::test_solveset_complex_exp",
"sympy/solvers/tests/test_solveset.py::test_solve_complex_log",
"sympy/solvers/tests/test_solveset.py::test_solve_complex_sqrt",
"sympy/solvers/tests/test_solveset.py::test_solveset_complex_tan",
"sympy/solvers/tests/test_solveset.py::test_solve_trig",
"sympy/solvers/tests/test_solveset.py::test_solve_invalid_sol",
"sympy/solvers/tests/test_solveset.py::test_solve_complex_unsolvable",
"sympy/solvers/tests/test_solveset.py::test_solveset",
"sympy/solvers/tests/test_solveset.py::test_improve_coverage",
"sympy/solvers/tests/test_solveset.py::test_issue_9522",
"sympy/solvers/tests/test_solveset.py::test_linear_eq_to_matrix",
"sympy/solvers/tests/test_solveset.py::test_linsolve",
"sympy/solvers/tests/test_solveset.py::test_issue_9556",
"sympy/solvers/tests/test_solveset.py::test_issue_9611"
] | [] | BSD | 184 |
sympy__sympy-9625 | 3ae27d8c8d8b2d792b193855093cd9dc3f06d116 | 2015-07-06 08:33:56 | 0241b35cae5f2adc04dc37b25f7dc9c5f00bd746 | diff --git a/sympy/sets/fancysets.py b/sympy/sets/fancysets.py
index 4bc2da4297..14bac1ab51 100644
--- a/sympy/sets/fancysets.py
+++ b/sympy/sets/fancysets.py
@@ -177,6 +177,13 @@ class Reals(with_metaclass(Singleton, Interval)):
def __new__(cls):
return Interval.__new__(cls, -S.Infinity, S.Infinity)
+ def __eq__(self, other):
+ if other == Interval(-S.Infinity, S.Infinity):
+ return True
+
+ def __hash__(self):
+ return hash(Interval(-S.Infinity, S.Infinity))
+
class ImageSet(Set):
"""
| S.Reals == Interval(-oo, oo) should return True
As of now:
```python
In [3]: S.Reals == Interval(-oo, oo)
Out[3]: False
```
The reason is:
```python
In [4]: type(S.Reals)
Out[4]: sympy.sets.fancysets.Reals
In [5]: type(Interval(-oo, oo))
Out[5]: sympy.sets.sets.Interval
```
Note: S.Reals derives from Interval Class constructor. | sympy/sympy | diff --git a/sympy/sets/tests/test_fancysets.py b/sympy/sets/tests/test_fancysets.py
index 5d79caa871..3b5db24334 100644
--- a/sympy/sets/tests/test_fancysets.py
+++ b/sympy/sets/tests/test_fancysets.py
@@ -185,6 +185,7 @@ def test_Reals():
assert -sqrt(2) in S.Reals
assert (2, 5) not in S.Reals
assert sqrt(-1) not in S.Reals
+ assert S.Reals == Interval(-oo, oo)
def test_Complex():
| {
"commit_name": "head_commit",
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true,
"llm_score": {
"difficulty_score": 1,
"issue_text_score": 0,
"test_score": 2
},
"num_modified_files": 1
} | 0.7 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "pytest",
"pip_packages": [
"pytest"
],
"pre_install": null,
"python": "3.4",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | attrs @ file:///opt/conda/conda-bld/attrs_1642510447205/work
certifi==2021.5.30
importlib-metadata @ file:///tmp/build/80754af9/importlib-metadata_1631916693255/work
iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work
more-itertools @ file:///tmp/build/80754af9/more-itertools_1637733554872/work
mpmath==1.3.0
packaging @ file:///tmp/build/80754af9/packaging_1637314298585/work
pluggy @ file:///tmp/build/80754af9/pluggy_1615976315926/work
py @ file:///opt/conda/conda-bld/py_1644396412707/work
pyparsing @ file:///tmp/build/80754af9/pyparsing_1635766073266/work
pytest==6.2.4
-e git+https://github.com/sympy/sympy.git@3ae27d8c8d8b2d792b193855093cd9dc3f06d116#egg=sympy
toml @ file:///tmp/build/80754af9/toml_1616166611790/work
typing_extensions @ file:///opt/conda/conda-bld/typing_extensions_1647553014482/work
zipp @ file:///tmp/build/80754af9/zipp_1633618647012/work
| name: sympy
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- attrs=21.4.0=pyhd3eb1b0_0
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- importlib-metadata=4.8.1=py36h06a4308_0
- importlib_metadata=4.8.1=hd3eb1b0_0
- iniconfig=1.1.1=pyhd3eb1b0_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- more-itertools=8.12.0=pyhd3eb1b0_0
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- packaging=21.3=pyhd3eb1b0_0
- pip=21.2.2=py36h06a4308_0
- pluggy=0.13.1=py36h06a4308_0
- py=1.11.0=pyhd3eb1b0_0
- pyparsing=3.0.4=pyhd3eb1b0_0
- pytest=6.2.4=py36h06a4308_2
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_0
- setuptools=58.0.4=py36h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- toml=0.10.2=pyhd3eb1b0_0
- typing_extensions=4.1.1=pyh06a4308_0
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- zipp=3.6.0=pyhd3eb1b0_0
- zlib=1.2.13=h5eee18b_1
- pip:
- mpmath==1.3.0
prefix: /opt/conda/envs/sympy
| [
"sympy/sets/tests/test_fancysets.py::test_Reals"
] | [] | [
"sympy/sets/tests/test_fancysets.py::test_naturals",
"sympy/sets/tests/test_fancysets.py::test_naturals0",
"sympy/sets/tests/test_fancysets.py::test_integers",
"sympy/sets/tests/test_fancysets.py::test_ImageSet",
"sympy/sets/tests/test_fancysets.py::test_image_is_ImageSet",
"sympy/sets/tests/test_fancysets.py::test_ImageSet_iterator_not_injetive",
"sympy/sets/tests/test_fancysets.py::test_Range",
"sympy/sets/tests/test_fancysets.py::test_range_interval_intersection",
"sympy/sets/tests/test_fancysets.py::test_fun",
"sympy/sets/tests/test_fancysets.py::test_Complex",
"sympy/sets/tests/test_fancysets.py::test_intersections",
"sympy/sets/tests/test_fancysets.py::test_infinitely_indexed_set_1",
"sympy/sets/tests/test_fancysets.py::test_infinitely_indexed_set_2",
"sympy/sets/tests/test_fancysets.py::test_imageset_intersect_real",
"sympy/sets/tests/test_fancysets.py::test_ImageSet_simplification",
"sympy/sets/tests/test_fancysets.py::test_ComplexPlane_contains",
"sympy/sets/tests/test_fancysets.py::test_ComplexPlane_intersect",
"sympy/sets/tests/test_fancysets.py::test_ComplexPlane_union",
"sympy/sets/tests/test_fancysets.py::test_ComplexPlane_measure",
"sympy/sets/tests/test_fancysets.py::test_normalize_theta_set"
] | [] | BSD | 185 |
|
softlayer__softlayer-python-571 | 7d3772b40ea8cb46065ecb4756d4746d02bfbf61 | 2015-07-06 19:24:20 | 1195b2020ef6efc40462d59eb079f26e5f39a6d8 | diff --git a/CHANGELOG b/CHANGELOG
index e5e1b8ad..3397760f 100644
--- a/CHANGELOG
+++ b/CHANGELOG
@@ -1,9 +1,3 @@
-4.0.4
-
- * Fixes bug with pulling the userData property for the virtual server detail
-
- * Fixes a class of bugs invloving unicode from the API
-
4.0.3
* Fixes bug with `slcli vs ready` command
diff --git a/SoftLayer/CLI/formatting.py b/SoftLayer/CLI/formatting.py
index 6f35a985..4f10980d 100644
--- a/SoftLayer/CLI/formatting.py
+++ b/SoftLayer/CLI/formatting.py
@@ -50,7 +50,7 @@ def format_output(data, fmt='table'): # pylint: disable=R0911,R0912
# responds to .formatted
if hasattr(data, 'formatted'):
if fmt == 'table':
- return data.formatted
+ return str(data.formatted)
# responds to .separator
if hasattr(data, 'separator'):
diff --git a/SoftLayer/CLI/server/detail.py b/SoftLayer/CLI/server/detail.py
index 943b694b..9fc76c5d 100644
--- a/SoftLayer/CLI/server/detail.py
+++ b/SoftLayer/CLI/server/detail.py
@@ -96,8 +96,10 @@ def cli(env, identifier, passwords, price):
table.add_row(['remote users', pass_table])
tag_row = []
- for tag in result['tagReferences']:
- tag_row.append(tag['tag']['name'])
+ for tag_detail in result['tagReferences']:
+ tag = utils.lookup(tag_detail, 'tag', 'name')
+ if tag is not None:
+ tag_row.append(tag)
if tag_row:
table.add_row(['tags', formatting.listing(tag_row, separator=',')])
diff --git a/SoftLayer/CLI/virt/detail.py b/SoftLayer/CLI/virt/detail.py
index 3afe151e..4fc115ce 100644
--- a/SoftLayer/CLI/virt/detail.py
+++ b/SoftLayer/CLI/virt/detail.py
@@ -93,8 +93,10 @@ def cli(self, identifier, passwords=False, price=False):
table.add_row(['users', pass_table])
tag_row = []
- for tag in result['tagReferences']:
- tag_row.append(tag['tag']['name'])
+ for tag_detail in result['tagReferences']:
+ tag = utils.lookup(tag_detail, 'tag', 'name')
+ if tag is not None:
+ tag_row.append(tag)
if tag_row:
table.add_row(['tags', formatting.listing(tag_row, separator=', ')])
diff --git a/SoftLayer/consts.py b/SoftLayer/consts.py
index 0279225c..674f0460 100644
--- a/SoftLayer/consts.py
+++ b/SoftLayer/consts.py
@@ -5,7 +5,7 @@
:license: MIT, see LICENSE for more details.
"""
-VERSION = 'v4.0.4'
+VERSION = 'v4.0.3'
API_PUBLIC_ENDPOINT = 'https://api.softlayer.com/xmlrpc/v3.1/'
API_PRIVATE_ENDPOINT = 'https://api.service.softlayer.com/xmlrpc/v3.1/'
API_PUBLIC_ENDPOINT_REST = 'https://api.softlayer.com/rest/v3.1/'
diff --git a/SoftLayer/managers/vs.py b/SoftLayer/managers/vs.py
index 30de90b3..ebd523f4 100644
--- a/SoftLayer/managers/vs.py
+++ b/SoftLayer/managers/vs.py
@@ -191,6 +191,7 @@ def get_instance(self, instance_id, **kwargs):
'blockDevices',
'blockDeviceTemplateGroup[id, name, globalIdentifier]',
'postInstallScriptUri',
+ 'userData',
'''operatingSystem[passwords[username,password],
softwareLicense.softwareDescription[
manufacturer,name,version,
diff --git a/docs/conf.py b/docs/conf.py
index 8f480496..0472001b 100644
--- a/docs/conf.py
+++ b/docs/conf.py
@@ -55,9 +55,9 @@
# built documents.
#
# The short X.Y version.
-version = '4.0.4'
+version = '4.0.3'
# The full version, including alpha/beta/rc tags.
-release = '4.0.4'
+release = '4.0.3'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
diff --git a/setup.py b/setup.py
index 3f329b77..88132dbe 100644
--- a/setup.py
+++ b/setup.py
@@ -36,7 +36,7 @@
setup(
name='SoftLayer',
- version='4.0.4',
+ version='4.0.3',
description=DESCRIPTION,
long_description=LONG_DESCRIPTION,
author='SoftLayer Technologies, Inc.',
| slcli server detail example01 (KeyError: 'tag')
Hello
I am running
slcli server detail hostname
against our entire SLR inventory (200 servers) for most of them I get expected output but for 4 out of the 100 I get this:
```
➜ ~ slcli server detail example01
An unexpected error has occured:
Traceback (most recent call last):
File "/usr/local/lib/python2.7/site-packages/SoftLayer-4.0.2-py2.7.egg/SoftLayer/CLI/core.py", line 181, in main
cli.main()
File "/usr/local/lib/python2.7/site-packages/click-4.0-py2.7.egg/click/core.py", line 644, in main
rv = self.invoke(ctx)
File "/usr/local/lib/python2.7/site-packages/click-4.0-py2.7.egg/click/core.py", line 991, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "/usr/local/lib/python2.7/site-packages/click-4.0-py2.7.egg/click/core.py", line 991, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "/usr/local/lib/python2.7/site-packages/click-4.0-py2.7.egg/click/core.py", line 837, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "/usr/local/lib/python2.7/site-packages/click-4.0-py2.7.egg/click/core.py", line 464, in invoke
return callback(*args, **kwargs)
File "/usr/local/lib/python2.7/site-packages/click-4.0-py2.7.egg/click/decorators.py", line 64, in new_func
return ctx.invoke(f, obj, *args[1:], **kwargs)
File "/usr/local/lib/python2.7/site-packages/click-4.0-py2.7.egg/click/core.py", line 464, in invoke
return callback(*args, **kwargs)
File "/usr/local/lib/python2.7/site-packages/SoftLayer-4.0.2-py2.7.egg/SoftLayer/CLI/server/detail.py", line 100, in cli
tag_row.append(tag['tag']['name'])
KeyError: 'tag'
Feel free to report this error as it is likely a bug:
https://github.com/softlayer/softlayer-python/issues
```
I tried it under
```
➜ ~ python -V
Python 2.7.10
```
and
```
(softlayer)➜ ~ python -V
Python 3.4.3
``` | softlayer/softlayer-python | diff --git a/SoftLayer/tests/CLI/helper_tests.py b/SoftLayer/tests/CLI/helper_tests.py
index 873d58a8..7862ef00 100644
--- a/SoftLayer/tests/CLI/helper_tests.py
+++ b/SoftLayer/tests/CLI/helper_tests.py
@@ -1,4 +1,3 @@
-# -*- coding: utf-8 -*-
"""
SoftLayer.tests.CLI.helper_tests
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@@ -358,17 +357,6 @@ def test_format_output_python_keyvaluetable(self):
ret = formatting.format_output(t, 'python')
self.assertEqual({'nothing': None}, ret)
- def test_format_output_unicode(self):
- t = formatting.format_output('☃', 'raw')
- self.assertEqual('☃', t)
-
- item = formatting.FormattedItem('raw ☃', '☃')
- t = formatting.format_output(item)
- self.assertEqual('☃', t)
-
- t = formatting.format_output(item, 'raw')
- self.assertEqual('raw ☃', t)
-
class TestTemplateArgs(testing.TestCase):
diff --git a/SoftLayer/tests/CLI/modules/server_tests.py b/SoftLayer/tests/CLI/modules/server_tests.py
index 85df2f42..e41e49cd 100644
--- a/SoftLayer/tests/CLI/modules/server_tests.py
+++ b/SoftLayer/tests/CLI/modules/server_tests.py
@@ -57,6 +57,25 @@ def test_server_details(self):
self.assertEqual(result.exit_code, 0)
self.assertEqual(json.loads(result.output), expected)
+ def test_detail_vs_empty_tag(self):
+ mock = self.set_mock('SoftLayer_Hardware_Server', 'getObject')
+ mock.return_value = {
+ 'id': 100,
+ 'processorPhysicalCoreAmount': 2,
+ 'memoryCapacity': 2,
+ 'tagReferences': [
+ {'tag': {'name': 'example-tag'}},
+ {},
+ ],
+ }
+ result = self.run_command(['server', 'detail', '100'])
+
+ self.assertEqual(result.exit_code, 0)
+ self.assertEqual(
+ json.loads(result.output)['tags'],
+ ['example-tag'],
+ )
+
def test_list_servers(self):
result = self.run_command(['server', 'list', '--tag=openstack'])
diff --git a/SoftLayer/tests/CLI/modules/vs_tests.py b/SoftLayer/tests/CLI/modules/vs_tests.py
index 9c1064bd..76dd75e5 100644
--- a/SoftLayer/tests/CLI/modules/vs_tests.py
+++ b/SoftLayer/tests/CLI/modules/vs_tests.py
@@ -66,6 +66,25 @@ def test_detail_vs(self):
'id': 1}],
'owner': 'chechu'})
+ def test_detail_vs_empty_tag(self):
+ mock = self.set_mock('SoftLayer_Virtual_Guest', 'getObject')
+ mock.return_value = {
+ 'id': 100,
+ 'maxCpu': 2,
+ 'maxMemory': 1024,
+ 'tagReferences': [
+ {'tag': {'name': 'example-tag'}},
+ {},
+ ],
+ }
+ result = self.run_command(['vs', 'detail', '100'])
+
+ self.assertEqual(result.exit_code, 0)
+ self.assertEqual(
+ json.loads(result.output)['tags'],
+ ['example-tag'],
+ )
+
def test_create_options(self):
result = self.run_command(['vs', 'create-options'])
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 0,
"issue_text_score": 0,
"test_score": 0
},
"num_modified_files": 8
} | 4.0 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[dev]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.6",
"reqs_path": [
"tools/test-requirements.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | alabaster==0.7.13
attrs==22.2.0
Babel==2.11.0
certifi==2021.5.30
charset-normalizer==2.0.12
click==8.0.4
coverage==6.2
distlib==0.3.9
docutils==0.18.1
filelock==3.4.1
fixtures==4.0.1
idna==3.10
imagesize==1.4.1
importlib-metadata==4.8.3
importlib-resources==5.4.0
iniconfig==1.1.1
Jinja2==3.0.3
MarkupSafe==2.0.1
mock==5.2.0
nose==1.3.7
packaging==21.3
pbr==6.1.1
platformdirs==2.4.0
pluggy==1.0.0
prettytable==2.5.0
py==1.11.0
Pygments==2.14.0
pyparsing==3.1.4
pytest==7.0.1
pytz==2025.2
requests==2.27.1
six==1.17.0
snowballstemmer==2.2.0
-e git+https://github.com/softlayer/softlayer-python.git@7d3772b40ea8cb46065ecb4756d4746d02bfbf61#egg=SoftLayer
Sphinx==5.3.0
sphinxcontrib-applehelp==1.0.2
sphinxcontrib-devhelp==1.0.2
sphinxcontrib-htmlhelp==2.0.0
sphinxcontrib-jsmath==1.0.1
sphinxcontrib-qthelp==1.0.3
sphinxcontrib-serializinghtml==1.1.5
testtools==2.6.0
toml==0.10.2
tomli==1.2.3
tox==3.28.0
typing_extensions==4.1.1
urllib3==1.26.20
virtualenv==20.17.1
wcwidth==0.2.13
zipp==3.6.0
| name: softlayer-python
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- pip=21.2.2=py36h06a4308_0
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_0
- setuptools=58.0.4=py36h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- alabaster==0.7.13
- attrs==22.2.0
- babel==2.11.0
- charset-normalizer==2.0.12
- click==8.0.4
- coverage==6.2
- distlib==0.3.9
- docutils==0.18.1
- filelock==3.4.1
- fixtures==4.0.1
- idna==3.10
- imagesize==1.4.1
- importlib-metadata==4.8.3
- importlib-resources==5.4.0
- iniconfig==1.1.1
- jinja2==3.0.3
- markupsafe==2.0.1
- mock==5.2.0
- nose==1.3.7
- packaging==21.3
- pbr==6.1.1
- platformdirs==2.4.0
- pluggy==1.0.0
- prettytable==2.5.0
- py==1.11.0
- pygments==2.14.0
- pyparsing==3.1.4
- pytest==7.0.1
- pytz==2025.2
- requests==2.27.1
- six==1.17.0
- snowballstemmer==2.2.0
- sphinx==5.3.0
- sphinxcontrib-applehelp==1.0.2
- sphinxcontrib-devhelp==1.0.2
- sphinxcontrib-htmlhelp==2.0.0
- sphinxcontrib-jsmath==1.0.1
- sphinxcontrib-qthelp==1.0.3
- sphinxcontrib-serializinghtml==1.1.5
- testtools==2.6.0
- toml==0.10.2
- tomli==1.2.3
- tox==3.28.0
- typing-extensions==4.1.1
- urllib3==1.26.20
- virtualenv==20.17.1
- wcwidth==0.2.13
- zipp==3.6.0
prefix: /opt/conda/envs/softlayer-python
| [
"SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_detail_vs_empty_tag",
"SoftLayer/tests/CLI/modules/vs_tests.py::DnsTests::test_detail_vs_empty_tag"
] | [] | [
"SoftLayer/tests/CLI/helper_tests.py::CLIJSONEncoderTest::test_default",
"SoftLayer/tests/CLI/helper_tests.py::CLIJSONEncoderTest::test_fail",
"SoftLayer/tests/CLI/helper_tests.py::PromptTests::test_confirmation",
"SoftLayer/tests/CLI/helper_tests.py::PromptTests::test_do_or_die",
"SoftLayer/tests/CLI/helper_tests.py::FormattedItemTests::test_blank",
"SoftLayer/tests/CLI/helper_tests.py::FormattedItemTests::test_gb",
"SoftLayer/tests/CLI/helper_tests.py::FormattedItemTests::test_init",
"SoftLayer/tests/CLI/helper_tests.py::FormattedItemTests::test_mb_to_gb",
"SoftLayer/tests/CLI/helper_tests.py::FormattedItemTests::test_sort",
"SoftLayer/tests/CLI/helper_tests.py::FormattedItemTests::test_sort_mixed",
"SoftLayer/tests/CLI/helper_tests.py::FormattedListTests::test_init",
"SoftLayer/tests/CLI/helper_tests.py::FormattedListTests::test_str",
"SoftLayer/tests/CLI/helper_tests.py::FormattedListTests::test_to_python",
"SoftLayer/tests/CLI/helper_tests.py::FormattedTxnTests::test_active_txn",
"SoftLayer/tests/CLI/helper_tests.py::FormattedTxnTests::test_active_txn_empty",
"SoftLayer/tests/CLI/helper_tests.py::FormattedTxnTests::test_active_txn_missing",
"SoftLayer/tests/CLI/helper_tests.py::FormattedTxnTests::test_transaction_status",
"SoftLayer/tests/CLI/helper_tests.py::FormattedTxnTests::test_transaction_status_missing",
"SoftLayer/tests/CLI/helper_tests.py::CLIAbortTests::test_init",
"SoftLayer/tests/CLI/helper_tests.py::ResolveIdTests::test_resolve_id_multiple",
"SoftLayer/tests/CLI/helper_tests.py::ResolveIdTests::test_resolve_id_none",
"SoftLayer/tests/CLI/helper_tests.py::ResolveIdTests::test_resolve_id_one",
"SoftLayer/tests/CLI/helper_tests.py::TestFormatOutput::test_format_output_formatted_item",
"SoftLayer/tests/CLI/helper_tests.py::TestFormatOutput::test_format_output_json",
"SoftLayer/tests/CLI/helper_tests.py::TestFormatOutput::test_format_output_json_keyvaluetable",
"SoftLayer/tests/CLI/helper_tests.py::TestFormatOutput::test_format_output_list",
"SoftLayer/tests/CLI/helper_tests.py::TestFormatOutput::test_format_output_python",
"SoftLayer/tests/CLI/helper_tests.py::TestFormatOutput::test_format_output_python_keyvaluetable",
"SoftLayer/tests/CLI/helper_tests.py::TestFormatOutput::test_format_output_raw",
"SoftLayer/tests/CLI/helper_tests.py::TestFormatOutput::test_format_output_string",
"SoftLayer/tests/CLI/helper_tests.py::TestFormatOutput::test_format_output_table",
"SoftLayer/tests/CLI/helper_tests.py::TestFormatOutput::test_sequentialoutput",
"SoftLayer/tests/CLI/helper_tests.py::TestFormatOutput::test_unknown",
"SoftLayer/tests/CLI/helper_tests.py::TestTemplateArgs::test_no_template_option",
"SoftLayer/tests/CLI/helper_tests.py::TestTemplateArgs::test_template_options",
"SoftLayer/tests/CLI/helper_tests.py::TestExportToTemplate::test_export_to_template",
"SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_cancel_server",
"SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_create_options",
"SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_create_server",
"SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_create_server_missing_required",
"SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_create_server_test_flag",
"SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_create_server_with_export",
"SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_edit_server_failed",
"SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_edit_server_userdata",
"SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_edit_server_userdata_and_file",
"SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_edit_server_userfile",
"SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_list_servers",
"SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_nic_edit_server",
"SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_server_cancel_reasons",
"SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_server_details",
"SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_server_power_cycle",
"SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_server_power_cycle_negative",
"SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_server_power_off",
"SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_server_power_on",
"SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_server_reboot_default",
"SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_server_reboot_hard",
"SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_server_reboot_negative",
"SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_server_reboot_soft",
"SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_server_reload",
"SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_update_firmware",
"SoftLayer/tests/CLI/modules/vs_tests.py::DnsTests::test_create",
"SoftLayer/tests/CLI/modules/vs_tests.py::DnsTests::test_create_options",
"SoftLayer/tests/CLI/modules/vs_tests.py::DnsTests::test_detail_vs",
"SoftLayer/tests/CLI/modules/vs_tests.py::DnsTests::test_list_vs"
] | [] | MIT License | 186 |
|
sympy__sympy-9627 | 0aeefdf5d0acb38a22718bd517c90b2d3100ea2f | 2015-07-06 21:26:25 | 0241b35cae5f2adc04dc37b25f7dc9c5f00bd746 | aktech: @hargup @flacjacket
leosartaj: This maybe done by implementing ``_intersect`` in ``Reals`` just like other sets?
gxyd: I am not sure if my comments matter, but I think the problem is not with the `S.Reals` for ex.
```
>>> Intersction(Interval(1,2), Interval(3,4), FiniteSet(n))
# returned as it is instead of EmptySet
```
As I see the code you are only apllying it to `S.Reals` so I guess my example would not be taken care of.
I think problem is in line no 1442 on sets.py, since if it finds any FiniteSet containing an element which is `None` for its containment. We should also make the `Intersection(star_here other_args)` there (I cannot find star on.my keypad) . This code may work on line 1442.
```
other_args = list([intersection(star_here other_args)])
If s.emptyset in other_args:
return s.emptyset
```
Please bare with me if you find anything wrong here.
aktech: @leosartaj
> This maybe done by implementing _intersect in Reals just like other sets?
These are Global rules & all global rules should reside at one [place](https://github.com/sympy/sympy/blob/master/sympy/sets/sets.py#L1427).
aktech: @gxyd Thanks for the review.
> I am not sure if my comments matter, but I think the problem is not with the S.Reals for ex.
Every comment matters, feel free to comment.
> As I see the code you are only apllying it to S.Reals so I guess my example would not be taken care of.
I see I am only fixing the subset of the problem you are talking about, So my fix isn't general, which is not apt. +1 for your code, it looks good.
> (I cannot find star on.my keypad)
Press Shift + 8
| diff --git a/sympy/polys/domains/pythonrational.py b/sympy/polys/domains/pythonrational.py
index fb455d829a..d3c6a39f55 100644
--- a/sympy/polys/domains/pythonrational.py
+++ b/sympy/polys/domains/pythonrational.py
@@ -8,8 +8,6 @@
from sympy.polys.domains.domainelement import DomainElement
from sympy.core.compatibility import integer_types
-from sympy.core.sympify import converter
-from sympy.core.numbers import Rational
from sympy.printing.defaults import DefaultPrinting
from sympy.utilities import public
@@ -246,8 +244,3 @@ def denom(self):
numerator = numer
denominator = denom
-
-
-def sympify_pythonrational(arg):
- return Rational(arg.p, arg.q)
-converter[PythonRational] = sympify_pythonrational
diff --git a/sympy/polys/ring_series.py b/sympy/polys/ring_series.py
index bd93775834..74a6331df3 100644
--- a/sympy/polys/ring_series.py
+++ b/sympy/polys/ring_series.py
@@ -1,12 +1,10 @@
-from sympy.polys.domains import QQ, EX, ExpressionDomain
+from sympy.polys.domains import QQ
from sympy.polys.rings import PolyElement, ring
from sympy.polys.monomials import monomial_min, monomial_mul, monomial_div
-from sympy.polys.polyerrors import DomainError
from mpmath.libmp.libintmath import ifac
from sympy.core.numbers import Rational
from sympy.core.compatibility import as_int, range
-from sympy.core import S, evaluate
-from sympy.functions import sin, cos, tan, atan, exp, atanh, tanh, log
+from sympy.core import S
from mpmath.libmp.libintmath import giant_steps
import math
@@ -34,8 +32,8 @@ def _invert_monoms(p1):
terms = list(p1.items())
terms.sort()
deg = p1.degree()
- R = p1.ring
- p = R.zero
+ ring = p1.ring
+ p = ring.zero
cv = p1.listcoeffs()
mv = p1.listmonoms()
for i in range(len(mv)):
@@ -70,9 +68,9 @@ def rs_trunc(p1, x, prec):
>>> rs_trunc(p, x, 10)
x**5 + x + 1
"""
- R = p1.ring
- p = R.zero
- i = R.gens.index(x)
+ ring = p1.ring
+ p = ring.zero
+ i = ring.gens.index(x)
for exp1 in p1:
if exp1[i] >= prec:
continue
@@ -97,18 +95,18 @@ def rs_mul(p1, p2, x, prec):
>>> rs_mul(p1, p2, x, 3)
3*x**2 + 3*x + 1
"""
- R = p1.ring
- p = R.zero
- if R.__class__ != p2.ring.__class__ or R != p2.ring:
+ ring = p1.ring
+ p = ring.zero
+ if ring.__class__ != p2.ring.__class__ or ring != p2.ring:
raise ValueError('p1 and p2 must have the same ring')
- iv = R.gens.index(x)
+ iv = ring.gens.index(x)
if not isinstance(p2, PolyElement):
raise ValueError('p1 and p2 must have the same ring')
- if R == p2.ring:
+ if ring == p2.ring:
get = p.get
items2 = list(p2.items())
items2.sort(key=lambda e: e[0][iv])
- if R.ngens == 1:
+ if ring.ngens == 1:
for exp1, v1 in p1.items():
for exp2, v2 in items2:
exp = exp1[0] + exp2[0]
@@ -118,7 +116,7 @@ def rs_mul(p1, p2, x, prec):
else:
break
else:
- monomial_mul = R.monomial_mul
+ monomial_mul = ring.monomial_mul
for exp1, v1 in p1.items():
for exp2, v2 in items2:
if exp1[iv] + exp2[iv] < prec:
@@ -145,13 +143,13 @@ def rs_square(p1, x, prec):
>>> rs_square(p, x, 3)
6*x**2 + 4*x + 1
"""
- R = p1.ring
- p = R.zero
- iv = R.gens.index(x)
+ ring = p1.ring
+ p = ring.zero
+ iv = ring.gens.index(x)
get = p.get
items = list(p1.items())
items.sort(key=lambda e: e[0][iv])
- monomial_mul = R.monomial_mul
+ monomial_mul = ring.monomial_mul
for i in range(len(items)):
exp1, v1 = items[i]
for j in range(i):
@@ -232,10 +230,10 @@ def _has_constant_term(p, x):
>>> _has_constant_term(p, x)
True
"""
- R = p.ring
- iv = R.gens.index(x)
- zm = R.zero_monom
- a = [0]*R.ngens
+ ring = p.ring
+ iv = ring.gens.index(x)
+ zm = ring.zero_monom
+ a = [0]*ring.ngens
a[iv] = 1
miv = tuple(a)
for expv in p:
@@ -261,22 +259,17 @@ def _series_inversion1(p, x, prec):
-x**3 + x**2 - x + 1
"""
- R = p.ring
- zm = R.zero_monom
- c = p[zm]
+ ring = p.ring
+ zm = ring.zero_monom
if zm not in p:
raise ValueError('no constant term in series')
- if _has_constant_term(p - c, x):
- raise ValueError('p cannot contain a constant term depending on '
- 'parameters')
- one = R(1)
- if R.domain is EX:
- one = 1
- if c != one:
+ if _has_constant_term(p - p[zm], x):
+ raise ValueError('p cannot contain a constant term depending on parameters')
+ if p[zm] != ring(1):
# TODO add check that it is a unit
- p1 = R(1)/c
+ p1 = ring(1)/p[zm]
else:
- p1 = R(1)
+ p1 = ring(1)
for precx in _giant_steps(prec):
tmp = p1.square()
tmp = rs_mul(tmp, p, x, precx)
@@ -299,9 +292,9 @@ def rs_series_inversion(p, x, prec):
>>> rs_series_inversion(1 + x*y**2, y, 4)
-x*y**2 + 1
"""
- R = p.ring
- zm = R.zero_monom
- ii = R.gens.index(x)
+ ring = p.ring
+ zm = ring.zero_monom
+ ii = ring.gens.index(x)
m = min(p, key=lambda k: k[ii])[ii]
if m:
raise NotImplementedError('no constant term in series')
@@ -424,10 +417,10 @@ def rs_series_from_list(p, c, x, prec, concur=1):
sympy.polys.ring.compose
"""
- R = p.ring
+ ring = p.ring
n = len(c)
if not concur:
- q = R(1)
+ q = ring(1)
s = c[0]*q
for i in range(1, n):
q = rs_mul(q, p, x, prec)
@@ -437,9 +430,9 @@ def rs_series_from_list(p, c, x, prec, concur=1):
K, r = divmod(n, J)
if r:
K += 1
- ax = [R(1)]
+ ax = [ring(1)]
b = 1
- q = R(1)
+ q = ring(1)
if len(p) < 20:
for i in range(1, J):
q = rs_mul(q, p, x, prec)
@@ -453,8 +446,8 @@ def rs_series_from_list(p, c, x, prec, concur=1):
ax.append(q)
# optimize using rs_square
pj = rs_mul(ax[-1], p, x, prec)
- b = R(1)
- s = R(0)
+ b = ring(1)
+ s = ring(0)
for k in range(K - 1):
r = J*k
s1 = c[r]
@@ -468,7 +461,7 @@ def rs_series_from_list(p, c, x, prec, concur=1):
k = K - 1
r = J*k
if r < n:
- s1 = c[r]*R(1)
+ s1 = c[r]*ring(1)
for j in range(1, J):
if r + j >= n:
break
@@ -494,10 +487,10 @@ def rs_diff(p, x):
>>> rs_diff(p, x)
2*x*y**3 + 1
"""
- R = p.ring
- n = R.gens.index(x)
- p1 = R.zero
- mn = [0]*R.ngens
+ ring = p.ring
+ n = ring.gens.index(x)
+ p1 = ring.zero
+ mn = [0]*ring.ngens
mn[n] = 1
mn = tuple(mn)
for expv in p:
@@ -521,10 +514,10 @@ def rs_integrate(p, x):
>>> rs_integrate(p, x)
1/3*x**3*y**3 + 1/2*x**2
"""
- R = p.ring
- p1 = R.zero
- n = R.gens.index(x)
- mn = [0]*R.ngens
+ ring = p.ring
+ p1 = ring.zero
+ n = ring.gens.index(x)
+ mn = [0]*ring.ngens
mn[n] = 1
mn = tuple(mn)
@@ -543,7 +536,7 @@ def fun(p, f, *args):
args[-2] = iv: names of the series variables
args[-1] = prec: list of the precisions of the series variables
- The case with f method name is used to compute rs_tan and rs_nth_root
+ The case with f method name is used to compute tan and nth_root
of a multivariate series:
fun(p, tan, iv, prec)
@@ -562,11 +555,11 @@ def fun(p, f, *args):
1/3*x**3*y**3 + 2*x**3*y**2 + x**3*y + 1/3*x**3 + x**2*y + x*y + x
"""
- _R = p.ring
- R1, _x = ring('_x', _R.domain)
+ _ring = p.ring
+ ring1, _x = ring('_x', _ring)
h = int(args[-1])
args1 = args[:-2] + (_x, h)
- zm = _R.zero_monom
+ zm = _ring.zero_monom
# separate the constant term of the series
# compute the univariate series f(_x, .., 'x', sum(nv))
# or _x.f(..., 'x', sum(nv)
@@ -594,8 +587,8 @@ def mul_xin(p, i, n):
x_i is the ith variable in p
"""
n = as_int(n)
- R = p.ring
- q = R(0)
+ ring = p.ring
+ q = ring(0)
for k, v in p.items():
k1 = list(k)
k1[i] += n
@@ -621,34 +614,14 @@ def rs_log(p, x, prec):
>>> rs_log(1 + x, x, 8)
1/7*x**7 - 1/6*x**6 + 1/5*x**5 - 1/4*x**4 + 1/3*x**3 - 1/2*x**2 + x
"""
- R = p.ring
+ ring = p.ring
if p == 1:
return 0
- if _has_constant_term(p, x):
- const = 0
- zm = R.zero_monom
- c = p[zm]
- if c == 1:
- pass
- else:
- c_expr = c.as_expr()
- if R.domain is EX:
- const = log(c_expr)
- elif isinstance(c, PolyElement):
- try:
- const = R(log(c_expr))
- except ValueError:
- raise DomainError("The given series can't be expanded in this "
- "domain.")
- else:
- raise DomainError("The given series can't be expanded in this "
- "domain")
-
- dlog = p.diff(x)
- dlog = rs_mul(dlog, _series_inversion1(p, x, prec), x, prec - 1)
- return rs_integrate(dlog, x) + const
- else:
- raise NotImplementedError
+ if _has_constant_term(p - 1, x):
+ raise NotImplementedError('p - 1 must not have a constant term in the series variables')
+ dlog = p.diff(x)
+ dlog = rs_mul(dlog, _series_inversion1(p, x, prec), x, prec - 1)
+ return rs_integrate(dlog, x)
def rs_LambertW(p, iv, prec):
"""
@@ -670,12 +643,12 @@ def rs_LambertW(p, iv, prec):
LambertW
"""
- R = p.ring
- p1 = R(0)
+ ring = p.ring
+ p1 = ring(0)
if _has_constant_term(p, iv):
raise NotImplementedError('Polynomial must not have constant term in \
the series variables')
- if iv in R.gens:
+ if iv in ring.gens:
for precx in _giant_steps(prec):
e = rs_exp(p1, iv, precx)
p2 = rs_mul(e, p1, iv, precx) - p
@@ -691,8 +664,8 @@ def _exp1(p, x, prec):
"""
Helper function for ``rs_exp``
"""
- R = p.ring
- p1 = R(1)
+ ring = p.ring
+ p1 = ring(1)
for precx in _giant_steps(prec):
pt = p - rs_log(p1, x, precx)
tmp = rs_mul(pt, p1, x, precx)
@@ -713,31 +686,12 @@ def rs_exp(p, x, prec):
>>> rs_exp(x**2, x, 7)
1/6*x**6 + 1/2*x**4 + x**2 + 1
"""
- R = p.ring
+ ring = p.ring
if _has_constant_term(p, x):
- zm = R.zero_monom
- c = p[zm]
- c_expr = c.as_expr()
- if R.domain is EX:
- const = exp(c_expr)
- elif isinstance(c, PolyElement):
- try:
- const = R(exp(c_expr))
- except ValueError:
- raise DomainError("The given series can't be expanded in this "
- "domain.")
- else:
- raise DomainError("The given series can't be expanded in this "
- "domain")
- p1 = p - c
-
- # Makes use of sympy fuctions to evaluate the values of the cos/sin
- # of the constant term.
- return const*rs_exp(p1, x, prec)
-
+ raise NotImplementedError
if len(p) > 20:
return _exp1(p, x, prec)
- one = R(1)
+ one = ring(1)
n = 1
k = 1
c = []
@@ -752,8 +706,8 @@ def rs_exp(p, x, prec):
# TODO
# Needs to be benchmarked before use in rs_atan
def _atan_series(p, iv, prec):
- R = p.ring
- mo = R(-1)
+ ring = p.ring
+ mo = ring(-1)
c = [-mo]
p2 = rs_square(p, iv, prec)
for k in range(1, prec):
@@ -783,32 +737,19 @@ def rs_atan(p, x, prec):
atan
"""
- R = p.ring
- const = 0
if _has_constant_term(p, x):
- zm = R.zero_monom
- c = p[zm]
- c_expr = c.as_expr()
- if R.domain is EX:
- const = atan(c_expr)
- elif isinstance(c, PolyElement):
- try:
- const = R(atan(c_expr))
- except ValueError:
- raise DomainError("The given series can't be expanded in this "
- "domain.")
- else:
- raise DomainError("The given series can't be expanded in this "
- "domain")
+ raise NotImplementedError('Polynomial must not have constant term in \
+ the series variables')
+ ring = p.ring
# Instead of using a closed form formula, we differentiate atan(p) to get
# `1/(1+p**2) * dp`, whose series expansion is much easier to calculate.
# Finally we integrate to get back atan
dp = p.diff(x)
- p1 = rs_square(p, x, prec) + R(1)
+ p1 = rs_square(p, x, prec) + ring(1)
p1 = rs_series_inversion(p1, x, prec - 1)
p1 = rs_mul(dp, p1, x, prec - 1)
- return rs_integrate(p1, x) + const
+ return rs_integrate(p1, x)
def _tan1(p, x, prec):
"""
@@ -823,8 +764,8 @@ def _tan1(p, x, prec):
Then `f(r) = 0`
Or `y = atan(x)` where `x = tan(y)` as required.
"""
- R = p.ring
- p1 = R(0)
+ ring = p.ring
+ p1 = ring(0)
for precx in _giant_steps(prec):
tmp = p - rs_atan(p1, x, precx)
tmp = rs_mul(tmp, 1 + p1.square(), x, precx)
@@ -852,36 +793,13 @@ def rs_tan(p, x, prec):
tan
"""
- R = p.ring
- const = 0
+ ring = p.ring
if _has_constant_term(p, x):
- zm = R.zero_monom
- c = p[zm]
- c_expr = c.as_expr()
- if R.domain is EX:
- const = tan(c_expr)
- elif isinstance(c, PolyElement):
- try:
- const = R(tan(c_expr))
- except ValueError:
- raise DomainError("The given series can't be expanded in this "
- "domain.")
- else:
- raise DomainError("The given series can't be expanded in this "
- "domain")
- raise NotImplementedError
- p1 = p - c
-
- # Makes use of sympy fuctions to evaluate the values of the cos/sin
- # of the constant term.
- t2 = rs_tan(p1, x, prec)
- t = rs_series_inversion(1 - const*t2, x, prec)
- return rs_mul(const + t2, t, x, prec)
-
- if R.ngens == 1:
+ raise NotImplementedError('Polynomial must not have constant term in \
+ series variables')
+ if ring.ngens == 1:
return _tan1(p, x, prec)
- else:
- return fun(p, _tan1, x, prec)
+ return fun(p, rs_tan, x, prec)
def rs_sin(p, x, prec):
"""
@@ -904,38 +822,19 @@ def rs_sin(p, x, prec):
sin
"""
- R = x.ring
+ ring = x.ring
if not p:
- return R(0)
+ return ring(0)
+ # Support for constant term can be extended on the lines of rs_cos
if _has_constant_term(p, x):
- zm = R.zero_monom
- c = p[zm]
- c_expr = c.as_expr()
- if R.domain is EX:
- t1, t2 = sin(c_expr), cos(c_expr)
- elif isinstance(c, PolyElement):
- try:
- t1, t2 = R(sin(c_expr)), R(cos(c_expr))
- except ValueError:
- raise DomainError("The given series can't be expanded in this "
- "domain.")
- else:
- raise DomainError("The given series can't be expanded in this "
- "domain")
- raise NotImplementedError
- p1 = p - c
-
- # Makes use of sympy cos, sin fuctions to evaluate the values of the cos/sin
- # of the constant term.
- return rs_sin(p1, x, prec)*t2 + rs_cos(p1, x, prec)*t1
-
- # Series is calculated in terms of tan as its evaluation is fast.
+ raise NotImplementedError
+ # Series is calcualed in terms of tan as its evaluation is fast.
if len(p) > 20 and p.ngens == 1:
t = rs_tan(p/2, x, prec)
t2 = rs_square(t, x, prec)
p1 = rs_series_inversion(1 + t2, x, prec)
return rs_mul(p1, 2*t, x, prec)
- one = R(1)
+ one = ring(1)
n = 1
c = [0]
for k in range(2, prec + 2, 2):
@@ -965,36 +864,26 @@ def rs_cos(p, iv, prec):
cos
"""
- R = p.ring
+ ring = p.ring
if _has_constant_term(p, iv):
- zm = R.zero_monom
- c = p[zm]
- c_expr = c.as_expr()
- if R.domain is EX:
- t1, t2 = sin(c_expr), cos(c_expr)
- elif isinstance(c, PolyElement):
- try:
- t1, t2 = R(sin(c_expr)), R(cos(c_expr))
- except ValueError:
- raise DomainError("The given series can't be expanded in this "
- "domain.")
- else:
- raise DomainError("The given series can't be expanded in this "
- "domain")
+ zm = ring.zero_monom
+ c = S(p[zm])
+ if not c.is_real:
raise NotImplementedError
p1 = p - c
# Makes use of sympy cos, sin fuctions to evaluate the values of the cos/sin
- # of the constant term.
- return rs_cos(p1, iv, prec)*t2 - rs_sin(p1, iv, prec)*t1
+ # of the constant term. Should it be left unevaluated?
+ from sympy.functions import cos, sin
+ return cos(c)*rs_cos(p1, iv, prec) - sin(c)*rs_sin(p1, iv, prec)
# Series is calculated in terms of tan as its evaluation is fast.
- if len(p) > 20 and R.ngens == 1:
+ if len(p) > 20 and ring.ngens == 1:
t = rs_tan(p/2, iv, prec)
t2 = rs_square(t, iv, prec)
p1 = rs_series_inversion(1+t2, iv, prec)
return rs_mul(p1 ,1 - t2, iv, prec)
- one = R(1)
+ one = ring(1)
n = 1
c = []
for k in range(2, prec + 2, 2):
@@ -1021,8 +910,8 @@ def check_series_var(p, iv):
# TODO
# Needs to be benchmarked before use in rs_atanh
def _atanh(p, iv, prec):
- R = p.ring
- one = R(1)
+ ring = p.ring
+ one = ring(1)
c = [one]
p2 = rs_square(p, iv, prec)
for k in range(1, prec):
@@ -1031,7 +920,7 @@ def _atanh(p, iv, prec):
s = rs_mul(s, p, iv, prec)
return s
-def rs_atanh(p, x, prec):
+def rs_atanh(p, iv, prec):
"""
Hyperbolic arctangent of a series
@@ -1052,32 +941,19 @@ def rs_atanh(p, x, prec):
atanh
"""
- R = p.ring
- const = 0
- if _has_constant_term(p, x):
- zm = R.zero_monom
- c = p[zm]
- c_expr = c.as_expr()
- if R.domain is EX:
- const = atanh(c_expr)
- elif isinstance(c, PolyElement):
- try:
- const = R(atanh(c_expr))
- except ValueError:
- raise DomainError("The given series can't be expanded in this "
- "domain.")
- else:
- raise DomainError("The given series can't be expanded in this "
- "domain")
+ if _has_constant_term(p, iv):
+ raise NotImplementedError('Polynomial must not have constant term in \
+ the series variables')
+ ring = p.ring
# Instead of using a closed form formula, we differentiate atanh(p) to get
# `1/(1-p**2) * dp`, whose series expansion is much easier to calculate.
# Finally we integrate to get back atanh
- dp = rs_diff(p, x)
- p1 = - rs_square(p, x, prec) + 1
- p1 = rs_series_inversion(p1, x, prec - 1)
- p1 = rs_mul(dp, p1, x, prec - 1)
- return rs_integrate(p1, x) + const
+ dp = rs_diff(p, iv)
+ p1 = - rs_square(p, iv, prec) + 1
+ p1 = rs_series_inversion(p1, iv, prec - 1)
+ p1 = rs_mul(dp, p1, iv, prec - 1)
+ return rs_integrate(p1, iv)
def rs_sinh(p, iv, prec):
"""
@@ -1144,15 +1020,15 @@ def _tanh(p, iv, prec):
_tanh
"""
- R = p.ring
- p1 = R(0)
+ ring = p.ring
+ p1 = ring(0)
for precx in _giant_steps(prec):
tmp = p - rs_atanh(p1, iv, precx)
tmp = rs_mul(tmp, 1 - p1.square(), iv, precx)
p1 += tmp
return p1
-def rs_tanh(p, x, prec):
+def rs_tanh(p, iv, prec):
"""
Hyperbolic tangent of a series
@@ -1173,33 +1049,13 @@ def rs_tanh(p, x, prec):
tanh
"""
- R = p.ring
- const = 0
- if _has_constant_term(p, x):
- zm = R.zero_monom
- c = p[zm]
- c_expr = c.as_expr()
- if R.domain is EX:
- const = tanh(c_expr)
- elif isinstance(c, PolyElement):
- try:
- const = R(tanh(c_expr))
- except ValueError:
- raise DomainError("The given series can't be expanded in this "
- "domain.")
- else:
- raise DomainError("The given series can't be expanded in this "
- "domain")
- raise NotImplementedError
- p1 = p - c
- t1 = rs_tanh(p1, x, prec)
- t = rs_series_inversion(1 + const*t1, x, prec)
- return rs_mul(const + t1, t, x, prec)
-
- if R.ngens == 1:
- return _tanh(p, x, prec)
- else:
- return fun(p, _tanh, x, prec)
+ ring = p.ring
+ if _has_constant_term(p, iv):
+ raise NotImplementedError('Polynomial must not have constant term in \
+ the series variables')
+ if ring.ngens == 1:
+ return _tanh(p, iv, prec)
+ return fun(p, _tanh, iv, prec)
def rs_newton(p, x, prec):
"""
diff --git a/sympy/sets/sets.py b/sympy/sets/sets.py
index cdbee1f317..1f4b4690ae 100644
--- a/sympy/sets/sets.py
+++ b/sympy/sets/sets.py
@@ -1439,7 +1439,10 @@ def reduce(args):
unk = [x for x in s
if any(other.contains(x) not in (True, False) for other in other_args)]
if unk:
- res += Intersection(*([s.func(*unk)] + other_args), evaluate=False)
+ other_sets = Intersection(*other_args)
+ if other_sets.is_EmptySet:
+ return EmptySet()
+ res += Intersection(s.func(*unk), other_sets, evaluate=False)
return res
# If any of the sets are unions, return a Union of Intersections
| Intersection(S.Reals, Interval(0, oo), FiniteSet(n)) is not simplified
```python
In [10]: Intersection(S.Reals, Interval(0, oo), FiniteSet(n))
Out[10]: Intersection((-oo, oo), [0, oo), {n})
```
It should simplify to the following:
```python
In [10]: Intersection(S.Reals, Interval(0, oo), FiniteSet(n))
Out[10]: Intersection([0, oo), {n})
``` | sympy/sympy | diff --git a/sympy/polys/tests/test_ring_series.py b/sympy/polys/tests/test_ring_series.py
index e0c1b2e87c..0af6732caa 100644
--- a/sympy/polys/tests/test_ring_series.py
+++ b/sympy/polys/tests/test_ring_series.py
@@ -1,4 +1,4 @@
-from sympy.polys.domains import QQ, EX
+from sympy.polys.domains import QQ
from sympy.polys.rings import ring
from sympy.polys.ring_series import (_invert_monoms, rs_integrate,
rs_trunc, rs_mul, rs_square, rs_pow, _has_constant_term, rs_series_inversion,
@@ -7,8 +7,6 @@
rs_sinh, rs_cosh, rs_tanh, _tan1, fun, rs_series_reversion)
from sympy.utilities.pytest import raises
from sympy.core.compatibility import range
-from sympy.core.symbol import symbols
-from sympy.functions import sin, cos, exp, tan, atan, atanh, tanh, log
def test_ring_series1():
R, x = ring('x', QQ)
@@ -153,18 +151,6 @@ def test_log():
assert p1 == (4*x**5*y**2 - 2*x**5*y - 2*x**4*y**2 + x**5/5 + 2*x**4*y -
x**4/4 - 2*x**3*y + x**3/3 + 2*x**2*y - x**2/2 + x)
- # Constant term in series
- a = symbols('a')
- R, x, y = ring('x, y', EX)
- assert rs_log(x + a, x, 5) == -EX(1/(4*a**4))*x**4 + EX(1/(3*a**3))*x**3 \
- - EX(1/(2*a**2))*x**2 + EX(1/a)*x + EX(log(a))
- assert rs_log(x + x**2*y + a, x, 4) == -EX(a**(-2))*x**3*y + \
- EX(1/(3*a**3))*x**3 + EX(1/a)*x**2*y - EX(1/(2*a**2))*x**2 + \
- EX(1/a)*x + EX(log(a))
-
- p = x + x**2 + 3
- assert rs_log(p, x, 10).compose(x, 5) == EX(log(3) + 19281291595/9920232)
-
def test_exp():
R, x = ring('x', QQ)
p = x + x**4
@@ -180,23 +166,6 @@ def test_exp():
p1 = rs_exp(p, x, prec)
assert p1 == x + 1
- # Constant term in series
- a = symbols('a')
- R, x, y = ring('x, y', QQ[exp(a), a])
- assert rs_exp(x + a, x, 5) == exp(a)*x**4/24 + exp(a)*x**3/6 + \
- exp(a)*x**2/2 + exp(a)*x + exp(a)
- assert rs_exp(x + x**2*y + a, x, 5) == exp(a)*x**4*y**2/2 + \
- exp(a)*x**4*y/2 + exp(a)*x**4/24 + exp(a)*x**3*y + \
- exp(a)*x**3/6 + exp(a)*x**2*y + exp(a)*x**2/2 + exp(a)*x + exp(a)
-
- R, x, y = ring('x, y', EX)
- assert rs_exp(x + a, x, 5) == EX(exp(a)/24)*x**4 + EX(exp(a)/6)*x**3 + \
- EX(exp(a)/2)*x**2 + EX(exp(a))*x + EX(exp(a))
- assert rs_exp(x + x**2*y + a, x, 5) == EX(exp(a)/2)*x**4*y**2 + \
- EX(exp(a)/2)*x**4*y + EX(exp(a)/24)*x**4 + EX(exp(a))*x**3*y + \
- EX(exp(a)/6)*x**3 + EX(exp(a))*x**2*y + EX(exp(a)/2)*x**2 + \
- EX(exp(a))*x + EX(exp(a))
-
def test_newton():
R, x = ring('x', QQ)
p = x**2 - 2
@@ -223,19 +192,6 @@ def test_atan():
2*x**7*y**9 - 1/7*x**7*y**7 - 1/3*x**6*y**9 + x**6*y**7 - x**5*y**7 + \
1/5*x**5*y**5 - x**4*y**5 - 1/3*x**3*y**3 + x**2*y**3 + x*y
- # Constant term in series
- a = symbols('a')
- R, x, y = ring('x, y', EX)
- assert rs_atan(x + a, x, 5) == -EX((a**3 - a)/(a**8 + 4*a**6 + 6*a**4 + \
- 4*a**2 + 1))*x**4 + EX((3*a**2 - 1)/(3*a**6 + 9*a**4 + \
- 9*a**2 + 3))*x**3 - EX(a/(a**4 + 2*a**2 + 1))*x**2 + \
- EX(1/(a**2 + 1))*x + EX(atan(a))
- assert rs_atan(x + x**2*y + a, x, 4) == -EX(2*a/(a**4 + 2*a**2 + 1)) \
- *x**3*y + EX((3*a**2 - 1)/(3*a**6 + 9*a**4 + 9*a**2 + 3))*x**3 + \
- EX(1/(a**2 + 1))*x**2*y - EX(a/(a**4 + 2*a**2 + 1))*x**2 + EX(1/(a**2 \
- + 1))*x + EX(atan(a))
-
-
def test_tan():
R, x, y = ring('x, y', QQ)
assert rs_tan(x, x, 9) == \
@@ -244,29 +200,6 @@ def test_tan():
4/3*x**7*y**9 + 17/315*x**7*y**7 + 1/3*x**6*y**9 + 2/3*x**6*y**7 + \
x**5*y**7 + 2/15*x**5*y**5 + x**4*y**5 + 1/3*x**3*y**3 + x**2*y**3 + x*y
- # Constant term in series
- a = symbols('a')
- R, x, y = ring('x, y', QQ[tan(a), a])
- assert rs_tan(x + a, x, 5) == (tan(a)**5 + 5*tan(a)**3/3 + \
- 2*tan(a)/3)*x**4 + (tan(a)**4 + 4*tan(a)**2/3 + 1/3)*x**3 + \
- (tan(a)**3 + tan(a))*x**2 + (tan(a)**2 + 1)*x + tan(a)
- assert rs_tan(x + x**2*y + a, x, 4) == (2*tan(a)**3 + 2*tan(a))*x**3*y + \
- (tan(a)**4 + 4/3*tan(a)**2 + 1/3)*x**3 + (tan(a)**2 + 1)*x**2*y + \
- (tan(a)**3 + tan(a))*x**2 + (tan(a)**2 + 1)*x + tan(a)
-
- R, x, y = ring('x, y', EX)
- assert rs_tan(x + a, x, 5) == EX(tan(a)**5 + 5*tan(a)**3/3 + \
- 2*tan(a)/3)*x**4 + EX(tan(a)**4 + 4*tan(a)**2/3 + EX(1)/3)*x**3 + \
- EX(tan(a)**3 + tan(a))*x**2 + EX(tan(a)**2 + 1)*x + EX(tan(a))
- assert rs_tan(x + x**2*y + a, x, 4) == EX(2*tan(a)**3 + \
- 2*tan(a))*x**3*y + EX(tan(a)**4 + 4*tan(a)**2/3 + EX(1)/3)*x**3 + \
- EX(tan(a)**2 + 1)*x**2*y + EX(tan(a)**3 + tan(a))*x**2 + \
- EX(tan(a)**2 + 1)*x + EX(tan(a))
-
- p = x + x**2 + 5
- assert rs_atan(p, x, 10).compose(x, 10) == EX(atan(5) + 67701870330562640/ \
- 668083460499)
-
def test_sin():
R, x, y = ring('x, y', QQ)
assert rs_sin(x, x, 9) == \
@@ -276,23 +209,6 @@ def test_sin():
+ 1/24*x**6*y**7 - 1/2*x**5*y**7 + 1/120*x**5*y**5 - 1/2*x**4*y**5 \
- 1/6*x**3*y**3 + x**2*y**3 + x*y
- # Constant term in series
- a = symbols('a')
- R, x, y = ring('x, y', QQ[sin(a), cos(a), a])
- assert rs_sin(x + a, x, 5) == sin(a)*x**4/24 - cos(a)*x**3/6 - \
- sin(a)*x**2/2 + cos(a)*x + sin(a)
- assert rs_sin(x + x**2*y + a, x, 5) == -sin(a)*x**4*y**2/2 - \
- cos(a)*x**4*y/2 + sin(a)*x**4/24 - sin(a)*x**3*y - cos(a)*x**3/6 + \
- cos(a)*x**2*y - sin(a)*x**2/2 + cos(a)*x + sin(a)
-
- R, x, y = ring('x, y', EX)
- assert rs_sin(x + a, x, 5) == EX(sin(a)/24)*x**4 - EX(cos(a)/6)*x**3 - \
- EX(sin(a)/2)*x**2 + EX(cos(a))*x + EX(sin(a))
- assert rs_sin(x + x**2*y + a, x, 5) == -EX(sin(a)/2)*x**4*y**2 - \
- EX(cos(a)/2)*x**4*y + EX(sin(a)/24)*x**4 - EX(sin(a))*x**3*y - \
- EX(cos(a)/6)*x**3 + EX(cos(a))*x**2*y - EX(sin(a)/2)*x**2 + \
- EX(cos(a))*x + EX(sin(a))
-
def test_cos():
R, x, y = ring('x, y', QQ)
assert rs_cos(x, x, 9) == \
@@ -302,23 +218,6 @@ def test_cos():
1/120*x**7*y**8 + 1/4*x**6*y**8 - 1/720*x**6*y**6 + 1/6*x**5*y**6 \
- 1/2*x**4*y**6 + 1/24*x**4*y**4 - x**3*y**4 - 1/2*x**2*y**2 + 1
- # Constant term in series
- a = symbols('a')
- R, x, y = ring('x, y', QQ[sin(a), cos(a), a])
- assert rs_cos(x + a, x, 5) == cos(a)*x**4/24 + sin(a)*x**3/6 - \
- cos(a)*x**2/2 - sin(a)*x + cos(a)
- assert rs_cos(x + x**2*y + a, x, 5) == -cos(a)*x**4*y**2/2 + \
- sin(a)*x**4*y/2 + cos(a)*x**4/24 - cos(a)*x**3*y + sin(a)*x**3/6 - \
- sin(a)*x**2*y - cos(a)*x**2/2 - sin(a)*x + cos(a)
-
- R, x, y = ring('x, y', EX)
- assert rs_cos(x + a, x, 5) == EX(cos(a)/24)*x**4 + EX(sin(a)/6)*x**3 - \
- EX(cos(a)/2)*x**2 - EX(sin(a))*x + EX(cos(a))
- assert rs_cos(x + x**2*y + a, x, 5) == -EX(cos(a)/2)*x**4*y**2 + \
- EX(sin(a)/2)*x**4*y + EX(cos(a)/24)*x**4 - EX(cos(a))*x**3*y + \
- EX(sin(a)/6)*x**3 - EX(sin(a))*x**2*y - EX(cos(a)/2)*x**2 - \
- EX(sin(a))*x + EX(cos(a))
-
def test_cos_sin():
R, x, y = ring('x, y', QQ)
cos, sin = rs_cos_sin(x, x, 9)
@@ -335,22 +234,6 @@ def test_atanh():
2*x**7*y**9 + 1/7*x**7*y**7 + 1/3*x**6*y**9 + x**6*y**7 + x**5*y**7 + \
1/5*x**5*y**5 + x**4*y**5 + 1/3*x**3*y**3 + x**2*y**3 + x*y
- # Constant term in series
- a = symbols('a')
- R, x, y = ring('x, y', EX)
- assert rs_atanh(x + a, x, 5) == EX((a**3 + a)/(a**8 - 4*a**6 + 6*a**4 - \
- 4*a**2 + 1))*x**4 - EX((3*a**2 + 1)/(3*a**6 - 9*a**4 + \
- 9*a**2 - 3))*x**3 + EX(a/(a**4 - 2*a**2 + 1))*x**2 - EX(1/(a**2 - \
- 1))*x + EX(atanh(a))
- assert rs_atanh(x + x**2*y + a, x, 4) == EX(2*a/(a**4 - 2*a**2 + \
- 1))*x**3*y - EX((3*a**2 + 1)/(3*a**6 - 9*a**4 + 9*a**2 - 3))*x**3 - \
- EX(1/(a**2 - 1))*x**2*y + EX(a/(a**4 - 2*a**2 + 1))*x**2 - \
- EX(1/(a**2 - 1))*x + EX(atanh(a))
-
- p = x + x**2 + 5
- assert rs_atanh(p, x, 10).compose(x, 10) == EX(-733442653682135/5079158784 \
- + atanh(5))
-
def test_sinh():
R, x, y = ring('x, y', QQ)
assert rs_sinh(x, x, 9) == 1/5040*x**7 + 1/120*x**5 + 1/6*x**3 + x
@@ -375,14 +258,3 @@ def test_tanh():
17/45*x**8*y**9 + 4/3*x**7*y**9 - 17/315*x**7*y**7 - 1/3*x**6*y**9 + \
2/3*x**6*y**7 - x**5*y**7 + 2/15*x**5*y**5 - x**4*y**5 - \
1/3*x**3*y**3 + x**2*y**3 + x*y
-
- # Constant term in series
- a = symbols('a')
- R, x, y = ring('x, y', EX)
- assert rs_tanh(x + a, x, 5) == EX(tanh(a)**5 - 5*tanh(a)**3/3 + \
- 2*tanh(a)/3)*x**4 + EX(-tanh(a)**4 + 4*tanh(a)**2/3 - QQ(1, 3))*x**3 + \
- EX(tanh(a)**3 - tanh(a))*x**2 + EX(-tanh(a)**2 + 1)*x + EX(tanh(a))
-
- p = rs_tanh(x + x**2*y + a, x, 4)
- assert (p.compose(x, 10)).compose(y, 5) == EX(-1000*tanh(a)**4 + \
- 10100*tanh(a)**3 + 2470*tanh(a)**2/3 - 10099*tanh(a) + QQ(530, 3))
diff --git a/sympy/sets/tests/test_sets.py b/sympy/sets/tests/test_sets.py
index 1ea8b30b37..fd8bc62c21 100644
--- a/sympy/sets/tests/test_sets.py
+++ b/sympy/sets/tests/test_sets.py
@@ -253,6 +253,7 @@ def test_intersect():
assert Union(Interval(0, 1), Interval(2, 3)).intersection(Interval(1, 2)) == \
Union(Interval(1, 1), Interval(2, 2))
+
def test_intersection():
# iterable
i = Intersection(FiniteSet(1, 2, 3), Interval(2, 5), evaluate=False)
@@ -281,6 +282,16 @@ def test_intersection():
Intersection(S.Integers, S.Naturals, S.Reals, evaluate=False)
+def test_issue_9623():
+ n = Symbol('n')
+
+ a = S.Reals
+ b = Interval(0, oo)
+ c = FiniteSet(n)
+
+ assert Intersection(a, b, c) == Intersection(b, c)
+ assert Intersection(Interval(1, 2), Interval(3, 4), FiniteSet(n)) == EmptySet()
+
def test_is_disjoint():
assert Interval(0, 2).is_disjoint(Interval(1, 2)) == False
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 2,
"issue_text_score": 1,
"test_score": 0
},
"num_modified_files": 3
} | 0.7 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "pytest",
"pip_packages": [
"mpmath>=0.19",
"pytest"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.6",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | attrs @ file:///opt/conda/conda-bld/attrs_1642510447205/work
certifi==2021.5.30
importlib-metadata @ file:///tmp/build/80754af9/importlib-metadata_1631916693255/work
iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work
more-itertools @ file:///tmp/build/80754af9/more-itertools_1637733554872/work
mpmath==1.3.0
packaging @ file:///tmp/build/80754af9/packaging_1637314298585/work
pluggy @ file:///tmp/build/80754af9/pluggy_1615976315926/work
py @ file:///opt/conda/conda-bld/py_1644396412707/work
pyparsing @ file:///tmp/build/80754af9/pyparsing_1635766073266/work
pytest==6.2.4
-e git+https://github.com/sympy/sympy.git@0aeefdf5d0acb38a22718bd517c90b2d3100ea2f#egg=sympy
toml @ file:///tmp/build/80754af9/toml_1616166611790/work
typing_extensions @ file:///opt/conda/conda-bld/typing_extensions_1647553014482/work
zipp @ file:///tmp/build/80754af9/zipp_1633618647012/work
| name: sympy
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- attrs=21.4.0=pyhd3eb1b0_0
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- importlib-metadata=4.8.1=py36h06a4308_0
- importlib_metadata=4.8.1=hd3eb1b0_0
- iniconfig=1.1.1=pyhd3eb1b0_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- more-itertools=8.12.0=pyhd3eb1b0_0
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- packaging=21.3=pyhd3eb1b0_0
- pip=21.2.2=py36h06a4308_0
- pluggy=0.13.1=py36h06a4308_0
- py=1.11.0=pyhd3eb1b0_0
- pyparsing=3.0.4=pyhd3eb1b0_0
- pytest=6.2.4=py36h06a4308_2
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_0
- setuptools=58.0.4=py36h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- toml=0.10.2=pyhd3eb1b0_0
- typing_extensions=4.1.1=pyh06a4308_0
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- zipp=3.6.0=pyhd3eb1b0_0
- zlib=1.2.13=h5eee18b_1
- pip:
- mpmath==1.3.0
prefix: /opt/conda/envs/sympy
| [
"sympy/sets/tests/test_sets.py::test_issue_9623"
] | [] | [
"sympy/polys/tests/test_ring_series.py::test_ring_series1",
"sympy/polys/tests/test_ring_series.py::test_trunc",
"sympy/polys/tests/test_ring_series.py::test_mul_trunc",
"sympy/polys/tests/test_ring_series.py::test_square_trunc",
"sympy/polys/tests/test_ring_series.py::test_pow_trunc",
"sympy/polys/tests/test_ring_series.py::test_has_constant_term",
"sympy/polys/tests/test_ring_series.py::test_inversion",
"sympy/polys/tests/test_ring_series.py::test_series_reversion",
"sympy/polys/tests/test_ring_series.py::test_series_from_list",
"sympy/polys/tests/test_ring_series.py::test_log",
"sympy/polys/tests/test_ring_series.py::test_exp",
"sympy/polys/tests/test_ring_series.py::test_newton",
"sympy/polys/tests/test_ring_series.py::test_compose_add",
"sympy/polys/tests/test_ring_series.py::test_fun",
"sympy/polys/tests/test_ring_series.py::test_atan",
"sympy/polys/tests/test_ring_series.py::test_tan",
"sympy/polys/tests/test_ring_series.py::test_sin",
"sympy/polys/tests/test_ring_series.py::test_cos",
"sympy/polys/tests/test_ring_series.py::test_cos_sin",
"sympy/polys/tests/test_ring_series.py::test_atanh",
"sympy/polys/tests/test_ring_series.py::test_sinh",
"sympy/polys/tests/test_ring_series.py::test_cosh",
"sympy/polys/tests/test_ring_series.py::test_tanh",
"sympy/sets/tests/test_sets.py::test_interval_arguments",
"sympy/sets/tests/test_sets.py::test_interval_symbolic_end_points",
"sympy/sets/tests/test_sets.py::test_union",
"sympy/sets/tests/test_sets.py::test_difference",
"sympy/sets/tests/test_sets.py::test_Complement",
"sympy/sets/tests/test_sets.py::test_complement",
"sympy/sets/tests/test_sets.py::test_intersect",
"sympy/sets/tests/test_sets.py::test_intersection",
"sympy/sets/tests/test_sets.py::test_is_disjoint",
"sympy/sets/tests/test_sets.py::test_ProductSet_of_single_arg_is_arg",
"sympy/sets/tests/test_sets.py::test_interval_subs",
"sympy/sets/tests/test_sets.py::test_interval_to_mpi",
"sympy/sets/tests/test_sets.py::test_measure",
"sympy/sets/tests/test_sets.py::test_is_subset",
"sympy/sets/tests/test_sets.py::test_is_proper_subset",
"sympy/sets/tests/test_sets.py::test_is_superset",
"sympy/sets/tests/test_sets.py::test_is_proper_superset",
"sympy/sets/tests/test_sets.py::test_contains",
"sympy/sets/tests/test_sets.py::test_interval_symbolic",
"sympy/sets/tests/test_sets.py::test_union_contains",
"sympy/sets/tests/test_sets.py::test_is_number",
"sympy/sets/tests/test_sets.py::test_Interval_is_left_unbounded",
"sympy/sets/tests/test_sets.py::test_Interval_is_right_unbounded",
"sympy/sets/tests/test_sets.py::test_Interval_as_relational",
"sympy/sets/tests/test_sets.py::test_Finite_as_relational",
"sympy/sets/tests/test_sets.py::test_Union_as_relational",
"sympy/sets/tests/test_sets.py::test_Intersection_as_relational",
"sympy/sets/tests/test_sets.py::test_EmptySet",
"sympy/sets/tests/test_sets.py::test_finite_basic",
"sympy/sets/tests/test_sets.py::test_powerset",
"sympy/sets/tests/test_sets.py::test_product_basic",
"sympy/sets/tests/test_sets.py::test_real",
"sympy/sets/tests/test_sets.py::test_supinf",
"sympy/sets/tests/test_sets.py::test_universalset",
"sympy/sets/tests/test_sets.py::test_Union_of_ProductSets_shares",
"sympy/sets/tests/test_sets.py::test_Interval_free_symbols",
"sympy/sets/tests/test_sets.py::test_image_interval",
"sympy/sets/tests/test_sets.py::test_image_FiniteSet",
"sympy/sets/tests/test_sets.py::test_image_Union",
"sympy/sets/tests/test_sets.py::test_image_EmptySet",
"sympy/sets/tests/test_sets.py::test_issue_5724_7680",
"sympy/sets/tests/test_sets.py::test_boundary",
"sympy/sets/tests/test_sets.py::test_boundary_Union",
"sympy/sets/tests/test_sets.py::test_boundary_ProductSet",
"sympy/sets/tests/test_sets.py::test_boundary_ProductSet_line",
"sympy/sets/tests/test_sets.py::test_is_open",
"sympy/sets/tests/test_sets.py::test_is_closed",
"sympy/sets/tests/test_sets.py::test_closure",
"sympy/sets/tests/test_sets.py::test_interior",
"sympy/sets/tests/test_sets.py::test_issue_7841",
"sympy/sets/tests/test_sets.py::test_Eq",
"sympy/sets/tests/test_sets.py::test_SymmetricDifference",
"sympy/sets/tests/test_sets.py::test_issue_9536"
] | [] | BSD | 187 |
sigmavirus24__github3.py-407 | 48adfa8a0a3884fd9e2600b90b37e27efd61eee2 | 2015-07-06 22:37:54 | 05ed0c6a02cffc6ddd0e82ce840c464e1c5fd8c4 | diff --git a/AUTHORS.rst b/AUTHORS.rst
index 49e1c5b7..117a8194 100644
--- a/AUTHORS.rst
+++ b/AUTHORS.rst
@@ -94,3 +94,5 @@ Contributors
- Antoine Giraudmaillet (@antoine-g)
- Paulus Schoutsen (@balloob)
+
+- Nolan Bruabker (@nrb)
diff --git a/github3/issues/milestone.py b/github3/issues/milestone.py
index 9c2726e6..96114ddb 100644
--- a/github3/issues/milestone.py
+++ b/github3/issues/milestone.py
@@ -38,6 +38,8 @@ class Milestone(GitHubCore):
self.due_on = self._strptime(mile.get('due_on'))
#: datetime object representing when the milestone was updated.
self.updated_at = self._strptime(mile.get('updated_at'))
+ #: string representing the milestone's ID.
+ self.id = str(mile.get('id'))
def _repr(self):
return '<Milestone [{0}]>'.format(self)
| Milestone objects don't have id attributes
```py
>>> r = g.repository('rcbops', 'rpc-openstack')
>>> milestones = list(r.milestones())
>>> milestones
[<Milestone [kilo 11.0.0]>, <Milestone [next]>, <Milestone [icehouse 9.0.10]>, <Milestone [juno 10.1.10]>, <Milestone [Kilo 11.1.0]>, <Milestone [Kilo 11.2.0]>]
>>> milestones[0].id
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'Milestone' object has no attribute 'id'
``` | sigmavirus24/github3.py | diff --git a/tests/test_issues.py b/tests/test_issues.py
index e85aa48c..c58275c4 100644
--- a/tests/test_issues.py
+++ b/tests/test_issues.py
@@ -77,6 +77,9 @@ class TestMilestone(BaseCase):
def test_str(self):
assert str(self.m) == 'v1.0.0'
+ def test_id(self):
+ assert self.m.id== '219754'
+
def test_delete(self):
self.response('', 204)
self.delete(self.api)
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 0,
"issue_text_score": 1,
"test_score": 1
},
"num_modified_files": 2
} | 1.0 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[test]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest",
"pytest-cov",
"pytest-xdist",
"pytest-mock",
"pytest-asyncio"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.9",
"reqs_path": [
"requirements.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | betamax==0.9.0
betamax-matchers==0.4.0
certifi==2025.1.31
charset-normalizer==3.4.1
coverage==7.8.0
exceptiongroup==1.2.2
execnet==2.1.1
-e git+https://github.com/sigmavirus24/github3.py.git@48adfa8a0a3884fd9e2600b90b37e27efd61eee2#egg=github3.py
idna==3.10
iniconfig==2.1.0
packaging==24.2
pluggy==1.5.0
pytest==8.3.5
pytest-asyncio==0.26.0
pytest-cov==6.0.0
pytest-mock==3.14.0
pytest-xdist==3.6.1
requests==2.32.3
requests-toolbelt==1.0.0
tomli==2.2.1
typing_extensions==4.13.0
uritemplate==4.1.1
uritemplate.py==3.0.2
urllib3==2.3.0
| name: github3.py
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=3.0.16=h5eee18b_0
- pip=25.0=py39h06a4308_0
- python=3.9.21=he870216_1
- readline=8.2=h5eee18b_0
- setuptools=75.8.0=py39h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- tzdata=2025a=h04d1e81_0
- wheel=0.45.1=py39h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- betamax==0.9.0
- betamax-matchers==0.4.0
- certifi==2025.1.31
- charset-normalizer==3.4.1
- coverage==7.8.0
- exceptiongroup==1.2.2
- execnet==2.1.1
- idna==3.10
- iniconfig==2.1.0
- packaging==24.2
- pluggy==1.5.0
- pytest==8.3.5
- pytest-asyncio==0.26.0
- pytest-cov==6.0.0
- pytest-mock==3.14.0
- pytest-xdist==3.6.1
- requests==2.32.3
- requests-toolbelt==1.0.0
- tomli==2.2.1
- typing-extensions==4.13.0
- uritemplate==4.1.1
- uritemplate-py==3.0.2
- urllib3==2.3.0
prefix: /opt/conda/envs/github3.py
| [
"tests/test_issues.py::TestMilestone::test_id"
] | [] | [
"tests/test_issues.py::TestLabel::test_delete",
"tests/test_issues.py::TestLabel::test_equality",
"tests/test_issues.py::TestLabel::test_repr",
"tests/test_issues.py::TestLabel::test_str",
"tests/test_issues.py::TestLabel::test_update",
"tests/test_issues.py::TestMilestone::test_delete",
"tests/test_issues.py::TestMilestone::test_due_on",
"tests/test_issues.py::TestMilestone::test_repr",
"tests/test_issues.py::TestMilestone::test_str",
"tests/test_issues.py::TestMilestone::test_update",
"tests/test_issues.py::TestIssue::test_add_labels",
"tests/test_issues.py::TestIssue::test_assign",
"tests/test_issues.py::TestIssue::test_close",
"tests/test_issues.py::TestIssue::test_comment",
"tests/test_issues.py::TestIssue::test_create_comment",
"tests/test_issues.py::TestIssue::test_edit",
"tests/test_issues.py::TestIssue::test_enterprise",
"tests/test_issues.py::TestIssue::test_equality",
"tests/test_issues.py::TestIssue::test_is_closed",
"tests/test_issues.py::TestIssue::test_issue_137",
"tests/test_issues.py::TestIssue::test_remove_all_labels",
"tests/test_issues.py::TestIssue::test_remove_label",
"tests/test_issues.py::TestIssue::test_reopen",
"tests/test_issues.py::TestIssue::test_replace_labels",
"tests/test_issues.py::TestIssue::test_repr",
"tests/test_issues.py::TestIssueEvent::test_equality",
"tests/test_issues.py::TestIssueEvent::test_repr"
] | [] | BSD 3-Clause "New" or "Revised" License | 188 |
|
marshmallow-code__marshmallow-234 | 4e922445601219dc6bfe014d36b3c61d9528e2ad | 2015-07-07 10:29:53 | b8ad05b5342914e857c442d75e8abe9ea8f867fb | diff --git a/marshmallow/schema.py b/marshmallow/schema.py
index 4de0a123..7fe1289f 100644
--- a/marshmallow/schema.py
+++ b/marshmallow/schema.py
@@ -699,8 +699,8 @@ class BaseSchema(base.SchemaABC):
"""
if obj and many:
try: # Homogeneous collection
- obj_prototype = obj[0]
- except IndexError: # Nothing to serialize
+ obj_prototype = next(iter(obj))
+ except StopIteration: # Nothing to serialize
return self.declared_fields
obj = obj_prototype
ret = self.dict_class()
| fields.Nested does not support sets
Currently `fields.Nested` assumes that the value of the field is a list - https://github.com/marshmallow-code/marshmallow/blob/dev/marshmallow/schema.py#L702 - and fails for `set` during serialization | marshmallow-code/marshmallow | diff --git a/tests/test_schema.py b/tests/test_schema.py
index 29dada19..5d0dbbdf 100644
--- a/tests/test_schema.py
+++ b/tests/test_schema.py
@@ -3,6 +3,7 @@
import json
import random
+from collections import namedtuple
import pytest
@@ -687,6 +688,21 @@ def test_nested_only_and_exclude():
assert 'bar' not in result.data['inner']
+def test_nested_with_sets():
+ class Inner(Schema):
+ foo = fields.Field()
+
+ class Outer(Schema):
+ inners = fields.Nested(Inner, many=True)
+
+ sch = Outer()
+
+ DataClass = namedtuple('DataClass', ['foo'])
+ data = dict(inners=set([DataClass(42), DataClass(2)]))
+ result = sch.dump(data)
+ assert len(result.data['inners']) == 2
+
+
def test_meta_serializer_fields():
u = User("John", age=42.3, email="[email protected]",
homepage="http://john.com")
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_short_problem_statement"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 1,
"issue_text_score": 1,
"test_score": 0
},
"num_modified_files": 1
} | 2.0 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[dev]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest"
],
"pre_install": null,
"python": "3.9",
"reqs_path": [
"dev-requirements.txt",
"docs/requirements.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | alabaster @ git+https://github.com/sloria/alabaster.git@667b1b676c6bf7226db057f098ec826d84d3ae40
babel==2.17.0
cachetools==5.5.2
certifi==2025.1.31
chardet==5.2.0
charset-normalizer==3.4.1
colorama==0.4.6
distlib==0.3.9
docutils==0.20.1
exceptiongroup==1.2.2
filelock==3.18.0
flake8==2.4.0
idna==3.10
imagesize==1.4.1
importlib_metadata==8.6.1
iniconfig==2.1.0
invoke==2.2.0
Jinja2==3.1.6
MarkupSafe==3.0.2
-e git+https://github.com/marshmallow-code/marshmallow.git@4e922445601219dc6bfe014d36b3c61d9528e2ad#egg=marshmallow
mccabe==0.3.1
packaging==24.2
pep8==1.5.7
platformdirs==4.3.7
pluggy==1.5.0
pyflakes==0.8.1
Pygments==2.19.1
pyproject-api==1.9.0
pytest==8.3.5
python-dateutil==2.9.0.post0
pytz==2025.2
requests==2.32.3
six==1.17.0
snowballstemmer==2.2.0
Sphinx==7.2.6
sphinx-issues==0.2.0
sphinxcontrib-applehelp==2.0.0
sphinxcontrib-devhelp==2.0.0
sphinxcontrib-htmlhelp==2.1.0
sphinxcontrib-jsmath==1.0.1
sphinxcontrib-qthelp==2.0.0
sphinxcontrib-serializinghtml==2.0.0
tomli==2.2.1
tox==4.25.0
typing_extensions==4.13.0
urllib3==2.3.0
virtualenv==20.29.3
zipp==3.21.0
| name: marshmallow
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=3.0.16=h5eee18b_0
- pip=25.0=py39h06a4308_0
- python=3.9.21=he870216_1
- readline=8.2=h5eee18b_0
- setuptools=75.8.0=py39h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- tzdata=2025a=h04d1e81_0
- wheel=0.45.1=py39h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- alabaster==0.7.11+sloria0
- babel==2.17.0
- cachetools==5.5.2
- certifi==2025.1.31
- chardet==5.2.0
- charset-normalizer==3.4.1
- colorama==0.4.6
- distlib==0.3.9
- docutils==0.20.1
- exceptiongroup==1.2.2
- filelock==3.18.0
- flake8==2.4.0
- idna==3.10
- imagesize==1.4.1
- importlib-metadata==8.6.1
- iniconfig==2.1.0
- invoke==2.2.0
- jinja2==3.1.6
- markupsafe==3.0.2
- mccabe==0.3.1
- packaging==24.2
- pep8==1.5.7
- platformdirs==4.3.7
- pluggy==1.5.0
- pyflakes==0.8.1
- pygments==2.19.1
- pyproject-api==1.9.0
- pytest==8.3.5
- python-dateutil==2.9.0.post0
- pytz==2025.2
- requests==2.32.3
- six==1.17.0
- snowballstemmer==2.2.0
- sphinx==7.2.6
- sphinx-issues==0.2.0
- sphinxcontrib-applehelp==2.0.0
- sphinxcontrib-devhelp==2.0.0
- sphinxcontrib-htmlhelp==2.1.0
- sphinxcontrib-jsmath==1.0.1
- sphinxcontrib-qthelp==2.0.0
- sphinxcontrib-serializinghtml==2.0.0
- tomli==2.2.1
- tox==4.25.0
- typing-extensions==4.13.0
- urllib3==2.3.0
- virtualenv==20.29.3
- zipp==3.21.0
prefix: /opt/conda/envs/marshmallow
| [
"tests/test_schema.py::test_nested_with_sets"
] | [] | [
"tests/test_schema.py::test_serializing_basic_object[UserSchema]",
"tests/test_schema.py::test_serializing_basic_object[UserMetaSchema]",
"tests/test_schema.py::test_serializer_dump",
"tests/test_schema.py::test_dump_returns_dict_of_errors",
"tests/test_schema.py::test_dump_with_strict_mode_raises_error[UserSchema]",
"tests/test_schema.py::test_dump_with_strict_mode_raises_error[UserMetaSchema]",
"tests/test_schema.py::test_dump_resets_errors",
"tests/test_schema.py::test_load_resets_errors",
"tests/test_schema.py::test_dump_resets_error_fields",
"tests/test_schema.py::test_load_resets_error_fields",
"tests/test_schema.py::test_errored_fields_do_not_appear_in_output",
"tests/test_schema.py::test_load_many_stores_error_indices",
"tests/test_schema.py::test_dump_many",
"tests/test_schema.py::test_multiple_errors_can_be_stored_for_a_given_index",
"tests/test_schema.py::test_dump_many_stores_error_indices",
"tests/test_schema.py::test_dump_many_doesnt_stores_error_indices_when_index_errors_is_false",
"tests/test_schema.py::test_dump_returns_a_marshalresult",
"tests/test_schema.py::test_dumps_returns_a_marshalresult",
"tests/test_schema.py::test_dumping_single_object_with_collection_schema",
"tests/test_schema.py::test_loading_single_object_with_collection_schema",
"tests/test_schema.py::test_dumps_many",
"tests/test_schema.py::test_load_returns_an_unmarshalresult",
"tests/test_schema.py::test_load_many",
"tests/test_schema.py::test_loads_returns_an_unmarshalresult",
"tests/test_schema.py::test_loads_many",
"tests/test_schema.py::test_loads_deserializes_from_json",
"tests/test_schema.py::test_serializing_none",
"tests/test_schema.py::test_default_many_symmetry",
"tests/test_schema.py::TestValidate::test_validate_returns_errors_dict",
"tests/test_schema.py::TestValidate::test_validate_many",
"tests/test_schema.py::TestValidate::test_validate_many_doesnt_store_index_if_index_errors_option_is_false",
"tests/test_schema.py::TestValidate::test_validate_strict",
"tests/test_schema.py::TestValidate::test_validate_required",
"tests/test_schema.py::test_fields_are_not_copies[UserSchema]",
"tests/test_schema.py::test_fields_are_not_copies[UserMetaSchema]",
"tests/test_schema.py::test_dumps_returns_json",
"tests/test_schema.py::test_naive_datetime_field",
"tests/test_schema.py::test_datetime_formatted_field",
"tests/test_schema.py::test_datetime_iso_field",
"tests/test_schema.py::test_tz_datetime_field",
"tests/test_schema.py::test_local_datetime_field",
"tests/test_schema.py::test_class_variable",
"tests/test_schema.py::test_serialize_many[UserSchema]",
"tests/test_schema.py::test_serialize_many[UserMetaSchema]",
"tests/test_schema.py::test_inheriting_schema",
"tests/test_schema.py::test_custom_field",
"tests/test_schema.py::test_url_field",
"tests/test_schema.py::test_relative_url_field",
"tests/test_schema.py::test_stores_invalid_url_error[UserSchema]",
"tests/test_schema.py::test_stores_invalid_url_error[UserMetaSchema]",
"tests/test_schema.py::test_email_field[UserSchema]",
"tests/test_schema.py::test_email_field[UserMetaSchema]",
"tests/test_schema.py::test_stored_invalid_email",
"tests/test_schema.py::test_integer_field",
"tests/test_schema.py::test_fixed_field",
"tests/test_schema.py::test_as_string",
"tests/test_schema.py::test_decimal_field",
"tests/test_schema.py::test_price_field",
"tests/test_schema.py::test_extra",
"tests/test_schema.py::test_extra_many",
"tests/test_schema.py::test_method_field[UserSchema]",
"tests/test_schema.py::test_method_field[UserMetaSchema]",
"tests/test_schema.py::test_function_field",
"tests/test_schema.py::test_prefix[UserSchema]",
"tests/test_schema.py::test_prefix[UserMetaSchema]",
"tests/test_schema.py::test_fields_must_be_declared_as_instances",
"tests/test_schema.py::test_serializing_generator[UserSchema]",
"tests/test_schema.py::test_serializing_generator[UserMetaSchema]",
"tests/test_schema.py::test_serializing_empty_list_returns_empty_list",
"tests/test_schema.py::test_serializing_dict",
"tests/test_schema.py::test_serializing_dict_with_meta_fields",
"tests/test_schema.py::test_exclude_in_init[UserSchema]",
"tests/test_schema.py::test_exclude_in_init[UserMetaSchema]",
"tests/test_schema.py::test_only_in_init[UserSchema]",
"tests/test_schema.py::test_only_in_init[UserMetaSchema]",
"tests/test_schema.py::test_invalid_only_param",
"tests/test_schema.py::test_can_serialize_uuid",
"tests/test_schema.py::test_can_serialize_time",
"tests/test_schema.py::test_invalid_time",
"tests/test_schema.py::test_invalid_date",
"tests/test_schema.py::test_invalid_email",
"tests/test_schema.py::test_invalid_url",
"tests/test_schema.py::test_invalid_selection",
"tests/test_schema.py::test_custom_json",
"tests/test_schema.py::test_custom_error_message",
"tests/test_schema.py::test_load_errors_with_many",
"tests/test_schema.py::test_error_raised_if_fields_option_is_not_list",
"tests/test_schema.py::test_error_raised_if_additional_option_is_not_list",
"tests/test_schema.py::test_only_and_exclude",
"tests/test_schema.py::test_only_with_invalid_attribute",
"tests/test_schema.py::test_nested_only_and_exclude",
"tests/test_schema.py::test_meta_serializer_fields",
"tests/test_schema.py::test_meta_fields_mapping",
"tests/test_schema.py::test_meta_field_not_on_obj_raises_attribute_error",
"tests/test_schema.py::test_exclude_fields",
"tests/test_schema.py::test_fields_option_must_be_list_or_tuple",
"tests/test_schema.py::test_exclude_option_must_be_list_or_tuple",
"tests/test_schema.py::test_dateformat_option",
"tests/test_schema.py::test_default_dateformat",
"tests/test_schema.py::test_inherit_meta",
"tests/test_schema.py::test_inherit_meta_override",
"tests/test_schema.py::test_additional",
"tests/test_schema.py::test_cant_set_both_additional_and_fields",
"tests/test_schema.py::test_serializing_none_meta",
"tests/test_schema.py::TestErrorHandler::test_dump_with_custom_error_handler",
"tests/test_schema.py::TestErrorHandler::test_load_with_custom_error_handler",
"tests/test_schema.py::TestErrorHandler::test_validate_with_custom_error_handler",
"tests/test_schema.py::TestErrorHandler::test_multiple_serializers_with_same_error_handler",
"tests/test_schema.py::TestErrorHandler::test_setting_error_handler_class_attribute",
"tests/test_schema.py::TestSchemaValidator::test_validator_decorator_is_deprecated",
"tests/test_schema.py::TestSchemaValidator::test_validator_defined_on_class",
"tests/test_schema.py::TestSchemaValidator::test_validator_that_raises_error_with_dict",
"tests/test_schema.py::TestSchemaValidator::test_validator_that_raises_error_with_list",
"tests/test_schema.py::TestSchemaValidator::test_mixed_schema_validators",
"tests/test_schema.py::TestSchemaValidator::test_registered_validators_are_not_shared_with_ancestors",
"tests/test_schema.py::TestSchemaValidator::test_registered_validators_are_not_shared_with_children",
"tests/test_schema.py::TestSchemaValidator::test_inheriting_then_registering_validator",
"tests/test_schema.py::TestSchemaValidator::test_multiple_schema_errors_can_be_stored",
"tests/test_schema.py::TestSchemaValidator::test_schema_validation_error_with_stict_stores_correct_field_name",
"tests/test_schema.py::TestSchemaValidator::test_schema_validation_error_with_strict_when_field_is_specified",
"tests/test_schema.py::TestSchemaValidator::test_schema_validation_error_stored_on_multiple_fields",
"tests/test_schema.py::TestSchemaValidator::test_validator_with_strict",
"tests/test_schema.py::TestSchemaValidator::test_validator_defined_by_decorator",
"tests/test_schema.py::TestSchemaValidator::test_validators_are_inherited",
"tests/test_schema.py::TestSchemaValidator::test_uncaught_validation_errors_are_stored",
"tests/test_schema.py::TestSchemaValidator::test_validation_error_with_error_parameter",
"tests/test_schema.py::TestSchemaValidator::test_store_schema_validation_errors_on_specified_field",
"tests/test_schema.py::TestSchemaValidator::test_errors_are_cleared_on_load",
"tests/test_schema.py::TestSchemaValidator::test_errors_are_cleared_after_loading_collection",
"tests/test_schema.py::TestSchemaValidator::test_raises_error_with_list",
"tests/test_schema.py::TestSchemaValidator::test_raises_error_with_dict",
"tests/test_schema.py::TestSchemaValidator::test_nested_schema_validators",
"tests/test_schema.py::TestPreprocessors::test_preprocessor_decorator_is_deprecated",
"tests/test_schema.py::TestPreprocessors::test_preprocessors_defined_on_class",
"tests/test_schema.py::TestPreprocessors::test_registered_preprocessors_are_not_shared_with_ancestors",
"tests/test_schema.py::TestPreprocessors::test_registered_preprocessors_are_not_shared_with_children",
"tests/test_schema.py::TestPreprocessors::test_preprocessors_defined_by_decorator",
"tests/test_schema.py::TestDataHandler::test_data_handler_is_deprecated",
"tests/test_schema.py::TestDataHandler::test_schema_with_custom_data_handler",
"tests/test_schema.py::TestDataHandler::test_registered_data_handlers_are_not_shared_with_ancestors",
"tests/test_schema.py::TestDataHandler::test_registered_data_handlers_are_not_shared_with_children",
"tests/test_schema.py::TestDataHandler::test_serializer_with_multiple_data_handlers",
"tests/test_schema.py::TestDataHandler::test_setting_data_handlers_class_attribute",
"tests/test_schema.py::TestDataHandler::test_root_data_handler",
"tests/test_schema.py::test_schema_repr",
"tests/test_schema.py::TestNestedSchema::test_flat_nested",
"tests/test_schema.py::TestNestedSchema::test_nested_many_with_missing_attribute",
"tests/test_schema.py::TestNestedSchema::test_nested_with_attribute_none",
"tests/test_schema.py::TestNestedSchema::test_flat_nested2",
"tests/test_schema.py::TestNestedSchema::test_nested_field_does_not_validate_required",
"tests/test_schema.py::TestNestedSchema::test_nested_none",
"tests/test_schema.py::TestNestedSchema::test_nested",
"tests/test_schema.py::TestNestedSchema::test_nested_many_fields",
"tests/test_schema.py::TestNestedSchema::test_nested_meta_many",
"tests/test_schema.py::TestNestedSchema::test_nested_only",
"tests/test_schema.py::TestNestedSchema::test_exclude",
"tests/test_schema.py::TestNestedSchema::test_list_field",
"tests/test_schema.py::TestNestedSchema::test_list_field_parent",
"tests/test_schema.py::TestNestedSchema::test_nested_load_many",
"tests/test_schema.py::TestNestedSchema::test_nested_errors",
"tests/test_schema.py::TestNestedSchema::test_nested_strict",
"tests/test_schema.py::TestNestedSchema::test_nested_method_field",
"tests/test_schema.py::TestNestedSchema::test_nested_function_field",
"tests/test_schema.py::TestNestedSchema::test_nested_prefixed_field",
"tests/test_schema.py::TestNestedSchema::test_nested_prefixed_many_field",
"tests/test_schema.py::TestNestedSchema::test_invalid_float_field",
"tests/test_schema.py::TestNestedSchema::test_serializer_meta_with_nested_fields",
"tests/test_schema.py::TestNestedSchema::test_serializer_with_nested_meta_fields",
"tests/test_schema.py::TestNestedSchema::test_nested_fields_must_be_passed_a_serializer",
"tests/test_schema.py::TestNestedSchema::test_invalid_type_passed_to_nested_many_field",
"tests/test_schema.py::TestSelfReference::test_nesting_schema_within_itself",
"tests/test_schema.py::TestSelfReference::test_nesting_schema_by_passing_class_name",
"tests/test_schema.py::TestSelfReference::test_nesting_within_itself_meta",
"tests/test_schema.py::TestSelfReference::test_nested_self_with_only_param",
"tests/test_schema.py::TestSelfReference::test_multiple_nested_self_fields",
"tests/test_schema.py::TestSelfReference::test_nested_many",
"tests/test_schema.py::test_serialization_with_required_field",
"tests/test_schema.py::test_deserialization_with_required_field",
"tests/test_schema.py::test_deserialization_with_required_field_and_custom_validator",
"tests/test_schema.py::TestContext::test_context_method",
"tests/test_schema.py::TestContext::test_context_method_function",
"tests/test_schema.py::TestContext::test_function_field_raises_error_when_context_not_available",
"tests/test_schema.py::TestContext::test_fields_context",
"tests/test_schema.py::TestContext::test_nested_fields_inherit_context",
"tests/test_schema.py::test_serializer_can_specify_nested_object_as_attribute",
"tests/test_schema.py::TestFieldInheritance::test_inherit_fields_from_schema_subclass",
"tests/test_schema.py::TestFieldInheritance::test_inherit_fields_from_non_schema_subclass",
"tests/test_schema.py::TestFieldInheritance::test_inheritance_follows_mro",
"tests/test_schema.py::TestAccessor::test_accessor_is_used",
"tests/test_schema.py::TestAccessor::test_accessor_with_many",
"tests/test_schema.py::TestAccessor::test_accessor_decorator",
"tests/test_schema.py::TestRequiredFields::test_required_string_field_missing",
"tests/test_schema.py::TestRequiredFields::test_required_string_field_failure",
"tests/test_schema.py::TestRequiredFields::test_allow_none_param",
"tests/test_schema.py::TestRequiredFields::test_allow_none_custom_message",
"tests/test_schema.py::TestDefaults::test_missing_inputs_are_excluded_from_dump_output",
"tests/test_schema.py::TestDefaults::test_none_is_serialized_to_none",
"tests/test_schema.py::TestDefaults::test_default_and_value_missing",
"tests/test_schema.py::TestDefaults::test_loading_none",
"tests/test_schema.py::TestDefaults::test_missing_inputs_are_excluded_from_load_output"
] | [] | MIT License | 189 |
|
sympy__sympy-9662 | 81603ffb24fb022fe941cda2fa59cd2fe849cd53 | 2015-07-12 11:54:54 | 0241b35cae5f2adc04dc37b25f7dc9c5f00bd746 | diff --git a/sympy/printing/latex.py b/sympy/printing/latex.py
index 7232a38d92..41a29beec6 100644
--- a/sympy/printing/latex.py
+++ b/sympy/printing/latex.py
@@ -1393,7 +1393,7 @@ def _print_MatPow(self, expr):
return "%s^{%s}" % (self._print(base), self._print(exp))
def _print_ZeroMatrix(self, Z):
- return r"\bold{0}"
+ return r"\mathbb{0}"
def _print_Identity(self, I):
return r"\mathbb{I}"
| Null MatrixSymbol printing using init_priting(use_unicode=True) for A*B*C-(A*B)*C produces '\bold0'
using `init_printing(use_unicode=True)` is necessary
```
In [1]: from sympy import *
In [2]: init_printing(use_unicode=True) # this is necessary
In [3]: A = MatrixSymbol('A', 3, 2)
In [4]: B = MatrixSymbol('B', 2, 4)
In [5]: C = MatrixSymbol('C', 4, 3)
In [6]: A*B*C - (A*B)*C
Out [6]: \bold0
```
It is working fine on command line .Python 3.4.0 [GCC 4.8.2] on linux
This error is produced using IPython Notebook on Linux machine. Sympy 0.7.6, Python 3.4
Zero matrix notebook display
A `ZeroMatrix` object has MathJax-incompatible LaTeX representation:
>>> sympy.printing.latex(ZeroMatrix(n, n))
'\\bold{0}'
Which results in the following in IPython notebook:

A fix should probably replace `bold` with `mathbb`.
| sympy/sympy | diff --git a/sympy/printing/tests/test_latex.py b/sympy/printing/tests/test_latex.py
index 2739a1ac74..13c4c87fbd 100644
--- a/sympy/printing/tests/test_latex.py
+++ b/sympy/printing/tests/test_latex.py
@@ -1146,6 +1146,11 @@ def test_Hadamard():
assert latex(HadamardProduct(X, Y)*Y) == r'\left(X \circ Y\right) Y'
+def test_ZeroMatrix():
+ from sympy import ZeroMatrix
+ assert latex(ZeroMatrix(1, 1)) == r"\mathbb{0}"
+
+
def test_boolean_args_order():
syms = symbols('a:f')
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_hyperlinks",
"has_media"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 1,
"issue_text_score": 0,
"test_score": 2
},
"num_modified_files": 1
} | 0.7 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "pytest",
"pip_packages": [
"mpmath>=0.19",
"pytest"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.4",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | attrs @ file:///opt/conda/conda-bld/attrs_1642510447205/work
certifi==2021.5.30
importlib-metadata @ file:///tmp/build/80754af9/importlib-metadata_1631916693255/work
iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work
more-itertools @ file:///tmp/build/80754af9/more-itertools_1637733554872/work
mpmath==1.3.0
packaging @ file:///tmp/build/80754af9/packaging_1637314298585/work
pluggy @ file:///tmp/build/80754af9/pluggy_1615976315926/work
py @ file:///opt/conda/conda-bld/py_1644396412707/work
pyparsing @ file:///tmp/build/80754af9/pyparsing_1635766073266/work
pytest==6.2.4
-e git+https://github.com/sympy/sympy.git@81603ffb24fb022fe941cda2fa59cd2fe849cd53#egg=sympy
toml @ file:///tmp/build/80754af9/toml_1616166611790/work
typing_extensions @ file:///opt/conda/conda-bld/typing_extensions_1647553014482/work
zipp @ file:///tmp/build/80754af9/zipp_1633618647012/work
| name: sympy
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- attrs=21.4.0=pyhd3eb1b0_0
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- importlib-metadata=4.8.1=py36h06a4308_0
- importlib_metadata=4.8.1=hd3eb1b0_0
- iniconfig=1.1.1=pyhd3eb1b0_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- more-itertools=8.12.0=pyhd3eb1b0_0
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- packaging=21.3=pyhd3eb1b0_0
- pip=21.2.2=py36h06a4308_0
- pluggy=0.13.1=py36h06a4308_0
- py=1.11.0=pyhd3eb1b0_0
- pyparsing=3.0.4=pyhd3eb1b0_0
- pytest=6.2.4=py36h06a4308_2
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_0
- setuptools=58.0.4=py36h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- toml=0.10.2=pyhd3eb1b0_0
- typing_extensions=4.1.1=pyh06a4308_0
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- zipp=3.6.0=pyhd3eb1b0_0
- zlib=1.2.13=h5eee18b_1
- pip:
- mpmath==1.3.0
prefix: /opt/conda/envs/sympy
| [
"sympy/printing/tests/test_latex.py::test_ZeroMatrix"
] | [] | [
"sympy/printing/tests/test_latex.py::test_printmethod",
"sympy/printing/tests/test_latex.py::test_latex_basic",
"sympy/printing/tests/test_latex.py::test_latex_builtins",
"sympy/printing/tests/test_latex.py::test_latex_Float",
"sympy/printing/tests/test_latex.py::test_latex_symbols",
"sympy/printing/tests/test_latex.py::test_latex_functions",
"sympy/printing/tests/test_latex.py::test_hyper_printing",
"sympy/printing/tests/test_latex.py::test_latex_bessel",
"sympy/printing/tests/test_latex.py::test_latex_fresnel",
"sympy/printing/tests/test_latex.py::test_latex_brackets",
"sympy/printing/tests/test_latex.py::test_latex_indexed",
"sympy/printing/tests/test_latex.py::test_latex_derivatives",
"sympy/printing/tests/test_latex.py::test_latex_subs",
"sympy/printing/tests/test_latex.py::test_latex_integrals",
"sympy/printing/tests/test_latex.py::test_latex_sets",
"sympy/printing/tests/test_latex.py::test_latex_Range",
"sympy/printing/tests/test_latex.py::test_latex_sequences",
"sympy/printing/tests/test_latex.py::test_latex_FourierSeries",
"sympy/printing/tests/test_latex.py::test_latex_intervals",
"sympy/printing/tests/test_latex.py::test_latex_emptyset",
"sympy/printing/tests/test_latex.py::test_latex_union",
"sympy/printing/tests/test_latex.py::test_latex_symmetric_difference",
"sympy/printing/tests/test_latex.py::test_latex_Complement",
"sympy/printing/tests/test_latex.py::test_latex_Complex",
"sympy/printing/tests/test_latex.py::test_latex_productset",
"sympy/printing/tests/test_latex.py::test_latex_Naturals",
"sympy/printing/tests/test_latex.py::test_latex_ImageSet",
"sympy/printing/tests/test_latex.py::test_latex_Contains",
"sympy/printing/tests/test_latex.py::test_latex_sum",
"sympy/printing/tests/test_latex.py::test_latex_product",
"sympy/printing/tests/test_latex.py::test_latex_limits",
"sympy/printing/tests/test_latex.py::test_issue_3568",
"sympy/printing/tests/test_latex.py::test_latex",
"sympy/printing/tests/test_latex.py::test_latex_dict",
"sympy/printing/tests/test_latex.py::test_latex_list",
"sympy/printing/tests/test_latex.py::test_latex_rational",
"sympy/printing/tests/test_latex.py::test_latex_inverse",
"sympy/printing/tests/test_latex.py::test_latex_DiracDelta",
"sympy/printing/tests/test_latex.py::test_latex_Heaviside",
"sympy/printing/tests/test_latex.py::test_latex_KroneckerDelta",
"sympy/printing/tests/test_latex.py::test_latex_LeviCivita",
"sympy/printing/tests/test_latex.py::test_mode",
"sympy/printing/tests/test_latex.py::test_latex_Piecewise",
"sympy/printing/tests/test_latex.py::test_latex_Matrix",
"sympy/printing/tests/test_latex.py::test_latex_matrix_with_functions",
"sympy/printing/tests/test_latex.py::test_latex_mul_symbol",
"sympy/printing/tests/test_latex.py::test_latex_issue_4381",
"sympy/printing/tests/test_latex.py::test_latex_issue_4576",
"sympy/printing/tests/test_latex.py::test_latex_pow_fraction",
"sympy/printing/tests/test_latex.py::test_noncommutative",
"sympy/printing/tests/test_latex.py::test_latex_order",
"sympy/printing/tests/test_latex.py::test_latex_Lambda",
"sympy/printing/tests/test_latex.py::test_latex_PolyElement",
"sympy/printing/tests/test_latex.py::test_latex_FracElement",
"sympy/printing/tests/test_latex.py::test_latex_Poly",
"sympy/printing/tests/test_latex.py::test_latex_RootOf",
"sympy/printing/tests/test_latex.py::test_latex_RootSum",
"sympy/printing/tests/test_latex.py::test_settings",
"sympy/printing/tests/test_latex.py::test_latex_numbers",
"sympy/printing/tests/test_latex.py::test_lamda",
"sympy/printing/tests/test_latex.py::test_custom_symbol_names",
"sympy/printing/tests/test_latex.py::test_matAdd",
"sympy/printing/tests/test_latex.py::test_matMul",
"sympy/printing/tests/test_latex.py::test_latex_MatrixSlice",
"sympy/printing/tests/test_latex.py::test_latex_RandomDomain",
"sympy/printing/tests/test_latex.py::test_PrettyPoly",
"sympy/printing/tests/test_latex.py::test_integral_transforms",
"sympy/printing/tests/test_latex.py::test_PolynomialRingBase",
"sympy/printing/tests/test_latex.py::test_categories",
"sympy/printing/tests/test_latex.py::test_Modules",
"sympy/printing/tests/test_latex.py::test_QuotientRing",
"sympy/printing/tests/test_latex.py::test_Tr",
"sympy/printing/tests/test_latex.py::test_Adjoint",
"sympy/printing/tests/test_latex.py::test_Hadamard",
"sympy/printing/tests/test_latex.py::test_boolean_args_order",
"sympy/printing/tests/test_latex.py::test_imaginary",
"sympy/printing/tests/test_latex.py::test_builtins_without_args",
"sympy/printing/tests/test_latex.py::test_latex_greek_functions",
"sympy/printing/tests/test_latex.py::test_translate",
"sympy/printing/tests/test_latex.py::test_other_symbols",
"sympy/printing/tests/test_latex.py::test_modifiers",
"sympy/printing/tests/test_latex.py::test_greek_symbols",
"sympy/printing/tests/test_latex.py::test_builtin_no_args",
"sympy/printing/tests/test_latex.py::test_issue_6853",
"sympy/printing/tests/test_latex.py::test_Mul",
"sympy/printing/tests/test_latex.py::test_Pow",
"sympy/printing/tests/test_latex.py::test_issue_7180",
"sympy/printing/tests/test_latex.py::test_issue_8409",
"sympy/printing/tests/test_latex.py::test_issue_8470",
"sympy/printing/tests/test_latex.py::test_issue_7117",
"sympy/printing/tests/test_latex.py::test_issue_2934"
] | [] | BSD | 190 |
|
sympy__sympy-9670 | 7b750b32b3c39e7f9e0140d0141323b11f71b295 | 2015-07-13 12:50:51 | 0241b35cae5f2adc04dc37b25f7dc9c5f00bd746 | diff --git a/sympy/assumptions/ask.py b/sympy/assumptions/ask.py
index 91a15ab5d2..8b4c671748 100644
--- a/sympy/assumptions/ask.py
+++ b/sympy/assumptions/ask.py
@@ -218,8 +218,8 @@ class inheriting from AskHandler::
... # Mersenne numbers are in the form 2**n + 1, n integer
... @staticmethod
... def Integer(expr, assumptions):
- ... import math
- ... return ask(Q.integer(math.log(expr + 1, 2)))
+ ... from sympy import log
+ ... return ask(Q.integer(log(expr + 1, 2)))
>>> register_handler('mersenne', MersenneHandler)
>>> ask(Q.mersenne(7))
True
diff --git a/sympy/assumptions/handlers/ntheory.py b/sympy/assumptions/handlers/ntheory.py
index b7a7955966..8bfba1970e 100644
--- a/sympy/assumptions/handlers/ntheory.py
+++ b/sympy/assumptions/handlers/ntheory.py
@@ -6,7 +6,7 @@
from sympy.assumptions import Q, ask
from sympy.assumptions.handlers import CommonHandler
from sympy.ntheory import isprime
-from sympy.core import S
+from sympy.core import S, Float
class AskPrimeHandler(CommonHandler):
@@ -30,7 +30,7 @@ def _number(expr, assumptions):
raise TypeError
except TypeError:
return False
- return isprime(i)
+ return isprime(expr)
@staticmethod
def Basic(expr, assumptions):
@@ -120,6 +120,8 @@ def _number(expr, assumptions):
raise TypeError
except TypeError:
return False
+ if isinstance(expr, (float, Float)):
+ return False
return i % 2 == 0
@staticmethod
@@ -207,10 +209,6 @@ def Integer(expr, assumptions):
Rational, Infinity, NegativeInfinity, ImaginaryUnit = [staticmethod(CommonHandler.AlwaysFalse)]*4
- @staticmethod
- def Float(expr, assumptions):
- return expr % 2 == 0
-
@staticmethod
def NumberSymbol(expr, assumptions):
return AskEvenHandler._number(expr, assumptions)
diff --git a/sympy/assumptions/handlers/sets.py b/sympy/assumptions/handlers/sets.py
index 770dc210a1..f03a9ebdc6 100644
--- a/sympy/assumptions/handlers/sets.py
+++ b/sympy/assumptions/handlers/sets.py
@@ -83,10 +83,6 @@ def Rational(expr, assumptions):
# evaluated to Integers
return False
- @staticmethod
- def Float(expr, assumptions):
- return int(expr) == expr
-
@staticmethod
def Abs(expr, assumptions):
return ask(Q.integer(expr.args[0]), assumptions)
| Floats shouldn't be even, odd or prime in new assumptions
```
In [1]: from sympy import *
In [2]: a = S(1.0)
In [3]: a.is_odd
Out[3]: False
In [4]: ask(Q.odd(a))
Out[4]: True
```
Same goes for even and prime. Composite works fine.
| sympy/sympy | diff --git a/sympy/assumptions/tests/test_query.py b/sympy/assumptions/tests/test_query.py
index 9dd5e0e5bf..87a0b5526c 100644
--- a/sympy/assumptions/tests/test_query.py
+++ b/sympy/assumptions/tests/test_query.py
@@ -87,7 +87,7 @@ def test_int_12():
def test_float_1():
z = 1.0
assert ask(Q.commutative(z)) is True
- assert ask(Q.integer(z)) is True
+ assert ask(Q.integer(z)) is False
assert ask(Q.rational(z)) is True
assert ask(Q.real(z)) is True
assert ask(Q.complex(z)) is True
@@ -96,7 +96,7 @@ def test_float_1():
assert ask(Q.positive(z)) is True
assert ask(Q.negative(z)) is False
assert ask(Q.even(z)) is False
- assert ask(Q.odd(z)) is True
+ assert ask(Q.odd(z)) is False
assert ask(Q.finite(z)) is True
assert ask(Q.infinitesimal(z)) is False
assert ask(Q.prime(z)) is False
@@ -2218,3 +2218,11 @@ def test_check_old_assumption():
x = symbols('x', irrational=True)
assert ask(Q.irrational(x)) is True
assert ask(Q.rational(x)) is False
+
+
+def test_issue_9636():
+ assert ask(Q.integer(1.0)) is False
+ assert ask(Q.prime(3.0)) is False
+ assert ask(Q.composite(4.0)) is False
+ assert ask(Q.even(2.0)) is False
+ assert ask(Q.odd(3.0)) is False
diff --git a/sympy/ntheory/primetest.py b/sympy/ntheory/primetest.py
index f6805a98d9..60da1a3c95 100644
--- a/sympy/ntheory/primetest.py
+++ b/sympy/ntheory/primetest.py
@@ -204,6 +204,9 @@ def isprime(n):
sympy.ntheory.generate.prime : Return the nth prime
"""
+ from sympy.core.numbers import Float
+ if isinstance(n, (Float, float)):
+ return False
n = int(n)
if n < 2:
return False
diff --git a/sympy/ntheory/tests/test_ntheory.py b/sympy/ntheory/tests/test_ntheory.py
index a9b681790c..cf3652a384 100644
--- a/sympy/ntheory/tests/test_ntheory.py
+++ b/sympy/ntheory/tests/test_ntheory.py
@@ -141,6 +141,7 @@ def test_isprime():
assert _mr_safe_helper(
"if n < 3474749660383: return mr(n, [2, 3, 5, 7, 11, 13])") == \
' # [2, 3, 5, 7, 11, 13] stot = 7 clear == bases'
+ assert isprime(5.0) is False
def test_prime():
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 3,
"issue_text_score": 1,
"test_score": 0
},
"num_modified_files": 3
} | 0.7 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"mpmath>=0.19",
"pytest",
"pytest-cov"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.4",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | attrs==22.2.0
certifi==2021.5.30
coverage==6.2
importlib-metadata==4.8.3
iniconfig==1.1.1
mpmath==1.3.0
packaging==21.3
pluggy==1.0.0
py==1.11.0
pyparsing==3.1.4
pytest==7.0.1
pytest-cov==4.0.0
-e git+https://github.com/sympy/sympy.git@7b750b32b3c39e7f9e0140d0141323b11f71b295#egg=sympy
tomli==1.2.3
typing_extensions==4.1.1
zipp==3.6.0
| name: sympy
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- pip=21.2.2=py36h06a4308_0
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_0
- setuptools=58.0.4=py36h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- attrs==22.2.0
- coverage==6.2
- importlib-metadata==4.8.3
- iniconfig==1.1.1
- mpmath==1.3.0
- packaging==21.3
- pluggy==1.0.0
- py==1.11.0
- pyparsing==3.1.4
- pytest==7.0.1
- pytest-cov==4.0.0
- tomli==1.2.3
- typing-extensions==4.1.1
- zipp==3.6.0
prefix: /opt/conda/envs/sympy
| [
"sympy/assumptions/tests/test_query.py::test_float_1",
"sympy/assumptions/tests/test_query.py::test_issue_9636"
] | [
"sympy/assumptions/tests/test_query.py::test_deprecated_Q_bounded",
"sympy/assumptions/tests/test_query.py::test_deprecated_Q_infinity"
] | [
"sympy/assumptions/tests/test_query.py::test_int_1",
"sympy/assumptions/tests/test_query.py::test_int_11",
"sympy/assumptions/tests/test_query.py::test_int_12",
"sympy/assumptions/tests/test_query.py::test_zero_0",
"sympy/assumptions/tests/test_query.py::test_negativeone",
"sympy/assumptions/tests/test_query.py::test_infinity",
"sympy/assumptions/tests/test_query.py::test_neg_infinity",
"sympy/assumptions/tests/test_query.py::test_nan",
"sympy/assumptions/tests/test_query.py::test_Rational_number",
"sympy/assumptions/tests/test_query.py::test_sqrt_2",
"sympy/assumptions/tests/test_query.py::test_pi",
"sympy/assumptions/tests/test_query.py::test_E",
"sympy/assumptions/tests/test_query.py::test_GoldenRatio",
"sympy/assumptions/tests/test_query.py::test_I",
"sympy/assumptions/tests/test_query.py::test_bounded",
"sympy/assumptions/tests/test_query.py::test_commutative",
"sympy/assumptions/tests/test_query.py::test_complex",
"sympy/assumptions/tests/test_query.py::test_even",
"sympy/assumptions/tests/test_query.py::test_evenness_in_ternary_integer_product_with_even",
"sympy/assumptions/tests/test_query.py::test_extended_real",
"sympy/assumptions/tests/test_query.py::test_rational",
"sympy/assumptions/tests/test_query.py::test_hermitian",
"sympy/assumptions/tests/test_query.py::test_imaginary",
"sympy/assumptions/tests/test_query.py::test_infinitesimal",
"sympy/assumptions/tests/test_query.py::test_integer",
"sympy/assumptions/tests/test_query.py::test_negative",
"sympy/assumptions/tests/test_query.py::test_nonzero",
"sympy/assumptions/tests/test_query.py::test_zero",
"sympy/assumptions/tests/test_query.py::test_odd",
"sympy/assumptions/tests/test_query.py::test_oddness_in_ternary_integer_product_with_even",
"sympy/assumptions/tests/test_query.py::test_prime",
"sympy/assumptions/tests/test_query.py::test_positive",
"sympy/assumptions/tests/test_query.py::test_nonpositive",
"sympy/assumptions/tests/test_query.py::test_nonnegative",
"sympy/assumptions/tests/test_query.py::test_real",
"sympy/assumptions/tests/test_query.py::test_algebraic",
"sympy/assumptions/tests/test_query.py::test_global",
"sympy/assumptions/tests/test_query.py::test_custom_context",
"sympy/assumptions/tests/test_query.py::test_functions_in_assumptions",
"sympy/assumptions/tests/test_query.py::test_composite_ask",
"sympy/assumptions/tests/test_query.py::test_composite_proposition",
"sympy/assumptions/tests/test_query.py::test_tautology",
"sympy/assumptions/tests/test_query.py::test_composite_assumptions",
"sympy/assumptions/tests/test_query.py::test_incompatible_resolutors",
"sympy/assumptions/tests/test_query.py::test_key_extensibility",
"sympy/assumptions/tests/test_query.py::test_type_extensibility",
"sympy/assumptions/tests/test_query.py::test_single_fact_lookup",
"sympy/assumptions/tests/test_query.py::test_compute_known_facts",
"sympy/assumptions/tests/test_query.py::test_known_facts_consistent",
"sympy/assumptions/tests/test_query.py::test_Add_queries",
"sympy/assumptions/tests/test_query.py::test_positive_assuming",
"sympy/assumptions/tests/test_query.py::test_issue_5421",
"sympy/assumptions/tests/test_query.py::test_issue_3906",
"sympy/assumptions/tests/test_query.py::test_issue_5833",
"sympy/assumptions/tests/test_query.py::test_issue_6732",
"sympy/assumptions/tests/test_query.py::test_issue_7246",
"sympy/assumptions/tests/test_query.py::test_check_old_assumption",
"sympy/ntheory/tests/test_ntheory.py::test_trailing",
"sympy/ntheory/tests/test_ntheory.py::test_multiplicity",
"sympy/ntheory/tests/test_ntheory.py::test_perfect_power",
"sympy/ntheory/tests/test_ntheory.py::test_isprime",
"sympy/ntheory/tests/test_ntheory.py::test_prime",
"sympy/ntheory/tests/test_ntheory.py::test_primepi",
"sympy/ntheory/tests/test_ntheory.py::test_generate",
"sympy/ntheory/tests/test_ntheory.py::test_randprime",
"sympy/ntheory/tests/test_ntheory.py::test_factorint",
"sympy/ntheory/tests/test_ntheory.py::test_divisors_and_divisor_count",
"sympy/ntheory/tests/test_ntheory.py::test_udivisors_and_udivisor_count",
"sympy/ntheory/tests/test_ntheory.py::test_issue_6981",
"sympy/ntheory/tests/test_ntheory.py::test_totient",
"sympy/ntheory/tests/test_ntheory.py::test_divisor_sigma",
"sympy/ntheory/tests/test_ntheory.py::test_udivisor_sigma",
"sympy/ntheory/tests/test_ntheory.py::test_partitions",
"sympy/ntheory/tests/test_ntheory.py::test_residue",
"sympy/ntheory/tests/test_ntheory.py::test_hex_pi_nth_digits",
"sympy/ntheory/tests/test_ntheory.py::test_crt",
"sympy/ntheory/tests/test_ntheory.py::test_binomial_coefficients_list",
"sympy/ntheory/tests/test_ntheory.py::test_binomial_coefficients",
"sympy/ntheory/tests/test_ntheory.py::test_multinomial_coefficients",
"sympy/ntheory/tests/test_ntheory.py::test_issue_4356",
"sympy/ntheory/tests/test_ntheory.py::test_divisors",
"sympy/ntheory/tests/test_ntheory.py::test_divisor_count",
"sympy/ntheory/tests/test_ntheory.py::test_antidivisors",
"sympy/ntheory/tests/test_ntheory.py::test_antidivisor_count",
"sympy/ntheory/tests/test_ntheory.py::test_primorial",
"sympy/ntheory/tests/test_ntheory.py::test_smoothness_and_smoothness_p",
"sympy/ntheory/tests/test_ntheory.py::test_visual_factorint",
"sympy/ntheory/tests/test_ntheory.py::test_visual_io",
"sympy/ntheory/tests/test_ntheory.py::test_modular",
"sympy/ntheory/tests/test_ntheory.py::test_search",
"sympy/ntheory/tests/test_ntheory.py::test_sieve_slice",
"sympy/ntheory/tests/test_ntheory.py::test_continued_fraction",
"sympy/ntheory/tests/test_ntheory.py::test_egyptian_fraction",
"sympy/ntheory/tests/test_ntheory.py::test_core",
"sympy/ntheory/tests/test_ntheory.py::test_digits"
] | [] | BSD | 191 |
|
colour-science__colour-194 | 3cc1e58379b92f8254f655ee108b721fd1342713 | 2015-07-14 09:01:43 | 3cd6ab8d4c3483bcdeb2d7ef33967160808c0bb2 | diff --git a/colour/volume/__init__.py b/colour/volume/__init__.py
index 58c0f7e4b..72f6c7b1e 100644
--- a/colour/volume/__init__.py
+++ b/colour/volume/__init__.py
@@ -6,16 +6,24 @@ from __future__ import absolute_import
from .dataset import * # noqa
from . import dataset
from .macadam_limits import is_within_macadam_limits
+from .mesh import is_within_mesh_volume
from .pointer_gamut import is_within_pointer_gamut
+from .spectrum import is_within_visible_spectrum
from .rgb import (
RGB_colourspace_limits,
RGB_colourspace_volume_MonteCarlo,
- RGB_colourspace_pointer_gamut_coverage_MonteCarlo)
+ RGB_colourspace_volume_coverage_MonteCarlo,
+ RGB_colourspace_pointer_gamut_coverage_MonteCarlo,
+ RGB_colourspace_visible_spectrum_coverage_MonteCarlo)
__all__ = []
__all__ += dataset.__all__
__all__ += ['is_within_macadam_limits']
+__all__ += ['is_within_mesh_volume']
__all__ += ['is_within_pointer_gamut']
+__all__ += ['is_within_visible_spectrum']
__all__ += ['RGB_colourspace_limits',
'RGB_colourspace_volume_MonteCarlo',
- 'RGB_colourspace_pointer_gamut_coverage_MonteCarlo']
+ 'RGB_colourspace_volume_coverage_MonteCarlo',
+ 'RGB_colourspace_pointer_gamut_coverage_MonteCarlo',
+ 'RGB_colourspace_visible_spectrum_coverage_MonteCarlo']
diff --git a/colour/volume/mesh.py b/colour/volume/mesh.py
new file mode 100644
index 000000000..e90f458a3
--- /dev/null
+++ b/colour/volume/mesh.py
@@ -0,0 +1,73 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
+"""
+Mesh Volume Computations Helpers
+================================
+
+Defines helpers objects related to volume computations.
+"""
+
+from __future__ import division, unicode_literals
+
+import numpy as np
+
+from colour.utilities import is_scipy_installed
+
+__author__ = 'Colour Developers'
+__copyright__ = 'Copyright (C) 2013 - 2015 - Colour Developers'
+__license__ = 'New BSD License - http://opensource.org/licenses/BSD-3-Clause'
+__maintainer__ = 'Colour Developers'
+__email__ = '[email protected]'
+__status__ = 'Production'
+
+__all__ = ['is_within_mesh_volume']
+
+
+def is_within_mesh_volume(points, mesh, tolerance=None):
+ """
+ Returns if given points are within given mesh volume using Delaunay
+ triangulation.
+
+ Parameters
+ ----------
+ points : array_like
+ Points to check if they are within `mesh` volume.
+ mesh : array_like
+ Points of the volume used to generate the Delaunay triangulation.
+ tolerance : numeric, optional
+ Tolerance allowed in the inside-triangle check.
+
+ Returns
+ -------
+ bool
+ Is within mesh volume.
+
+ Notes
+ -----
+ - This definition requires *scipy* to be installed.
+
+ Examples
+ --------
+ >>> mesh = np.array([[-1.0, -1.0, 1.0],
+ ... [1.0, -1.0, 1.0],
+ ... [1.0, -1.0, -1.0],
+ ... [-1.0, -1.0, -1.0],
+ ... [0.0, 1.0, 0.0]])
+ >>> is_within_mesh_volume(np.array([0.0005, 0.0031, 0.0010]), mesh)
+ array(True, dtype=bool)
+ >>> a = np.array([[0.0005, 0.0031, 0.0010],
+ ... [0.3205, 0.4131, 0.5100]])
+ >>> is_within_mesh_volume(a, mesh)
+ array([ True, False], dtype=bool)
+ """
+
+ if is_scipy_installed(raise_exception=True):
+ from scipy.spatial import Delaunay
+
+ triangulation = Delaunay(mesh)
+
+ simplex = triangulation.find_simplex(points, tol=tolerance)
+ simplex = np.where(simplex >= 0, True, False)
+
+ return simplex
diff --git a/colour/volume/pointer_gamut.py b/colour/volume/pointer_gamut.py
index 57415b898..860cbd0f0 100644
--- a/colour/volume/pointer_gamut.py
+++ b/colour/volume/pointer_gamut.py
@@ -5,7 +5,7 @@
Pointer's Gamut Volume Computations
===================================
-Defines objects related to Pointer's Gamut volume computations
+Defines objects related to Pointer's Gamut volume computations.
See Also
--------
@@ -15,14 +15,12 @@ See Also
from __future__ import division, unicode_literals
-import numpy as np
-
from colour.models import (
Lab_to_XYZ,
LCHab_to_Lab,
POINTER_GAMUT_DATA,
POINTER_GAMUT_ILLUMINANT)
-from colour.utilities import is_scipy_installed
+from colour.volume import is_within_mesh_volume
__author__ = 'Colour Developers'
__copyright__ = 'Copyright (C) 2013 - 2015 - Colour Developers'
@@ -33,8 +31,6 @@ __status__ = 'Production'
__all__ = ['is_within_pointer_gamut']
-_XYZ_POINTER_GAMUT_TRIANGULATION_CACHE = None
-
def is_within_pointer_gamut(XYZ, tolerance=None):
"""
@@ -60,26 +56,16 @@ def is_within_pointer_gamut(XYZ, tolerance=None):
Examples
--------
- >>> is_within_pointer_gamut(np.array([0.3205, 0.4131, 0.51]))
+ >>> import numpy as np
+ >>> is_within_pointer_gamut(np.array([0.3205, 0.4131, 0.5100]))
array(True, dtype=bool)
- >>> a = np.array([[0.3205, 0.4131, 0.51],
- ... [0.0005, 0.0031, 0.001]])
+ >>> a = np.array([[0.3205, 0.4131, 0.5100],
+ ... [0.0005, 0.0031, 0.0010]])
>>> is_within_pointer_gamut(a)
array([ True, False], dtype=bool)
"""
- if is_scipy_installed(raise_exception=True):
- from scipy.spatial import Delaunay
-
- global _XYZ_POINTER_GAMUT_TRIANGULATION_CACHE
-
- triangulation = _XYZ_POINTER_GAMUT_TRIANGULATION_CACHE
- if triangulation is None:
- _XYZ_POINTER_GAMUT_TRIANGULATION_CACHE = triangulation = (
- Delaunay(Lab_to_XYZ(LCHab_to_Lab(POINTER_GAMUT_DATA),
- POINTER_GAMUT_ILLUMINANT)))
-
- simplex = triangulation.find_simplex(XYZ, tol=tolerance)
- simplex = np.where(simplex >= 0, True, False)
+ XYZ_p = Lab_to_XYZ(LCHab_to_Lab(POINTER_GAMUT_DATA),
+ POINTER_GAMUT_ILLUMINANT)
- return simplex
+ return is_within_mesh_volume(XYZ, XYZ_p, tolerance)
diff --git a/colour/volume/rgb.py b/colour/volume/rgb.py
index a09b41490..0096119e8 100644
--- a/colour/volume/rgb.py
+++ b/colour/volume/rgb.py
@@ -10,6 +10,7 @@ Defines various RGB colourspace volume computation objects:
- :func:`RGB_colourspace_limits`
- :func:`RGB_colourspace_volume_MonteCarlo`
- :func:`RGB_colourspace_pointer_gamut_coverage_MonteCarlo`
+- :func:`RGB_colourspace_visible_spectrum_coverage_MonteCarlo`
See Also
--------
@@ -25,9 +26,13 @@ import numpy as np
from colour.algebra import random_triplet_generator
from colour.colorimetry import ILLUMINANTS
-from colour.models import Lab_to_XYZ, RGB_to_XYZ, XYZ_to_Lab, XYZ_to_RGB
+from colour.models import (
+ Lab_to_XYZ,
+ RGB_to_XYZ,
+ XYZ_to_Lab,
+ XYZ_to_RGB)
from colour.utilities import is_scipy_installed
-from colour.volume import is_within_pointer_gamut
+from colour.volume import is_within_pointer_gamut, is_within_visible_spectrum
__author__ = 'Colour Developers'
__copyright__ = 'Copyright (C) 2013 - 2014 - Colour Developers'
@@ -39,7 +44,8 @@ __status__ = 'Production'
__all__ = ['sample_RGB_colourspace_volume_MonteCarlo',
'RGB_colourspace_limits',
'RGB_colourspace_volume_MonteCarlo',
- 'RGB_colourspace_pointer_gamut_coverage_MonteCarlo']
+ 'RGB_colourspace_pointer_gamut_coverage_MonteCarlo',
+ 'RGB_colourspace_visible_spectrum_coverage_MonteCarlo']
def _wrapper_RGB_colourspace_volume_MonteCarlo(args):
@@ -262,24 +268,25 @@ def RGB_colourspace_volume_MonteCarlo(
return Lab_volume * np.sum(results) / (process_samples * cpu_count)
-def RGB_colourspace_pointer_gamut_coverage_MonteCarlo(
+def RGB_colourspace_volume_coverage_MonteCarlo(
colourspace,
+ coverage_sampler,
samples=10e6,
random_generator=random_triplet_generator,
random_state=None):
"""
- Returns given *RGB* colourspace percentage coverage of Pointer's Gamut
- volume using *Monte Carlo* method.
+ Returns given *RGB* colourspace percentage coverage of an arbitrary volume.
Parameters
----------
colourspace : RGB_Colourspace
- *RGB* colourspace to compute the Pointer's Gamut coverage percentage.
+ *RGB* colourspace to compute the volume coverage percentage.
+ coverage_sampler : object
+ Python object responsible for checking the volume coverage.
samples : numeric, optional
Samples count.
random_generator : generator, optional
- Random triplet generator providing the random samples within the *Lab*
- colourspace volume.
+ Random triplet generator providing the random samples.
random_state : RandomState, optional
Mersenne Twister pseudo-random number generator to use in the random
number generator.
@@ -287,7 +294,7 @@ def RGB_colourspace_pointer_gamut_coverage_MonteCarlo(
Returns
-------
float
- Percentage coverage of Pointer's Gamut volume.
+ Percentage coverage of volume.
Notes
-----
@@ -297,7 +304,11 @@ def RGB_colourspace_pointer_gamut_coverage_MonteCarlo(
--------
>>> from colour import sRGB_COLOURSPACE as sRGB
>>> prng = np.random.RandomState(2)
- >>> RGB_colourspace_pointer_gamut_coverage_MonteCarlo(sRGB, 10e3, random_state=prng) # noqa # doctest: +ELLIPSIS
+ >>> RGB_colourspace_volume_coverage_MonteCarlo(
+ ... sRGB,
+ ... is_within_pointer_gamut,
+ ... 10e3,
+ ... random_state=prng) # doctest: +ELLIPSIS
83...
"""
@@ -306,11 +317,12 @@ def RGB_colourspace_pointer_gamut_coverage_MonteCarlo(
if random_state is not None else
np.random.RandomState())
+ # TODO: Investigate for generator yielding directly a ndarray.
XYZ = np.asarray(list(random_generator(
samples, random_state=random_state)))
- XYZ_p = XYZ[is_within_pointer_gamut(XYZ)]
+ XYZ_vs = XYZ[coverage_sampler(XYZ)]
- RGB = XYZ_to_RGB(XYZ_p,
+ RGB = XYZ_to_RGB(XYZ_vs,
colourspace.whitepoint,
colourspace.whitepoint,
colourspace.XYZ_to_RGB_matrix)
@@ -318,4 +330,102 @@ def RGB_colourspace_pointer_gamut_coverage_MonteCarlo(
RGB_c = RGB[np.logical_and(np.min(RGB, axis=-1) >= 0,
np.max(RGB, axis=-1) <= 1)]
- return 100 * RGB_c.size / XYZ_p.size
+ return 100 * RGB_c.size / XYZ_vs.size
+
+
+def RGB_colourspace_pointer_gamut_coverage_MonteCarlo(
+ colourspace,
+ samples=10e6,
+ random_generator=random_triplet_generator,
+ random_state=None):
+ """
+ Returns given *RGB* colourspace percentage coverage of Pointer's Gamut
+ volume using *Monte Carlo* method.
+
+ Parameters
+ ----------
+ colourspace : RGB_Colourspace
+ *RGB* colourspace to compute the Pointer's Gamut coverage percentage.
+ samples : numeric, optional
+ Samples count.
+ random_generator : generator, optional
+ Random triplet generator providing the random samples.
+ random_state : RandomState, optional
+ Mersenne Twister pseudo-random number generator to use in the random
+ number generator.
+
+ Returns
+ -------
+ float
+ Percentage coverage of Pointer's Gamut volume.
+
+ Notes
+ -----
+ - This definition requires *scipy* to be installed.
+
+ Examples
+ --------
+ >>> from colour import sRGB_COLOURSPACE as sRGB
+ >>> prng = np.random.RandomState(2)
+ >>> RGB_colourspace_pointer_gamut_coverage_MonteCarlo(
+ ... sRGB,
+ ... 10e3,
+ ... random_state=prng) # doctest: +ELLIPSIS
+ 83...
+ """
+
+ return RGB_colourspace_volume_coverage_MonteCarlo(
+ colourspace,
+ is_within_pointer_gamut,
+ samples,
+ random_generator,
+ random_state)
+
+
+def RGB_colourspace_visible_spectrum_coverage_MonteCarlo(
+ colourspace,
+ samples=10e6,
+ random_generator=random_triplet_generator,
+ random_state=None):
+ """
+ Returns given *RGB* colourspace percentage coverage of visible spectrum
+ volume using *Monte Carlo* method.
+
+ Parameters
+ ----------
+ colourspace : RGB_Colourspace
+ *RGB* colourspace to compute the visible spectrum coverage percentage.
+ samples : numeric, optional
+ Samples count.
+ random_generator : generator, optional
+ Random triplet generator providing the random samples.
+ random_state : RandomState, optional
+ Mersenne Twister pseudo-random number generator to use in the random
+ number generator.
+
+ Returns
+ -------
+ float
+ Percentage coverage of visible spectrum volume.
+
+ Notes
+ -----
+ - This definition requires *scipy* to be installed.
+
+ Examples
+ --------
+ >>> from colour import sRGB_COLOURSPACE as sRGB
+ >>> prng = np.random.RandomState(2)
+ >>> RGB_colourspace_visible_spectrum_coverage_MonteCarlo(
+ ... sRGB,
+ ... 10e3,
+ ... random_state=prng) # doctest: +ELLIPSIS
+ 36...
+ """
+
+ return RGB_colourspace_volume_coverage_MonteCarlo(
+ colourspace,
+ is_within_visible_spectrum,
+ samples,
+ random_generator,
+ random_state)
diff --git a/colour/volume/spectrum.py b/colour/volume/spectrum.py
new file mode 100644
index 000000000..5e4e64241
--- /dev/null
+++ b/colour/volume/spectrum.py
@@ -0,0 +1,69 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
+"""
+Visible Spectrum Volume Computations
+====================================
+
+Defines objects related to visible spectrum volume computations.
+
+See Also
+--------
+`Spectrum IPython Notebook
+<http://nbviewer.ipython.org/github/colour-science/colour-ipython/blob/master/notebooks/colorimetry/spectrum.ipynb>`_ # noqa
+"""
+
+from __future__ import division, unicode_literals
+
+from colour.colorimetry import STANDARD_OBSERVERS_CMFS
+from colour.volume import is_within_mesh_volume
+
+__author__ = 'Colour Developers'
+__copyright__ = 'Copyright (C) 2013 - 2015 - Colour Developers'
+__license__ = 'New BSD License - http://opensource.org/licenses/BSD-3-Clause'
+__maintainer__ = 'Colour Developers'
+__email__ = '[email protected]'
+__status__ = 'Production'
+
+__all__ = ['is_within_visible_spectrum']
+
+
+def is_within_visible_spectrum(XYZ,
+ cmfs=STANDARD_OBSERVERS_CMFS.get(
+ 'CIE 1931 2 Degree Standard Observer'),
+ tolerance=None):
+ """
+ Returns if given *CIE XYZ* tristimulus values are within visible spectrum
+ volume / given colour matching functions volume.
+
+ Parameters
+ ----------
+ XYZ : array_like
+ *CIE XYZ* tristimulus values.
+ cmfs : XYZ_ColourMatchingFunctions
+ Standard observer colour matching functions.
+ tolerance : numeric, optional
+ Tolerance allowed in the inside-triangle check.
+
+ Returns
+ -------
+ bool
+ Is within visible spectrum.
+
+ Notes
+ -----
+ - Input *CIE XYZ* tristimulus values are in domain [0, 1].
+ - This definition requires *scipy* to be installed.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> is_within_visible_spectrum(np.array([0.3205, 0.4131, 0.51]))
+ array(True, dtype=bool)
+ >>> a = np.array([[0.3205, 0.4131, 0.51],
+ ... [-0.0005, 0.0031, 0.001]])
+ >>> is_within_visible_spectrum(a)
+ array([ True, False], dtype=bool)
+ """
+
+ return is_within_mesh_volume(XYZ, cmfs.values, tolerance)
| Implement support for "Visible Spectrum" coverage computation.
Similar needs than #190. | colour-science/colour | diff --git a/colour/volume/tests/tests_mesh.py b/colour/volume/tests/tests_mesh.py
new file mode 100644
index 000000000..2ab1296d9
--- /dev/null
+++ b/colour/volume/tests/tests_mesh.py
@@ -0,0 +1,108 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
+"""
+Defines unit tests for :mod:`colour.volume.mesh` module.
+"""
+
+from __future__ import division, unicode_literals
+
+import numpy as np
+import sys
+
+if sys.version_info[:2] <= (2, 6):
+ import unittest2 as unittest
+else:
+ import unittest
+from itertools import permutations
+
+from colour.volume import is_within_mesh_volume
+from colour.utilities import ignore_numpy_errors
+
+__author__ = 'Colour Developers'
+__copyright__ = 'Copyright (C) 2013 - 2015 - Colour Developers'
+__license__ = 'New BSD License - http://opensource.org/licenses/BSD-3-Clause'
+__maintainer__ = 'Colour Developers'
+__email__ = '[email protected]'
+__status__ = 'Production'
+
+__all__ = ['TestIsWithinMeshVolume']
+
+
+class TestIsWithinMeshVolume(unittest.TestCase):
+ """
+ Defines :func:`colour.volume.mesh.is_within_mesh_volume` definition unit
+ tests methods.
+ """
+
+ def setUp(self):
+ """
+ Initialises common tests attributes.
+ """
+
+ self.__mesh = np.array([[-1.0, -1.0, 1.0],
+ [1.0, -1.0, 1.0],
+ [1.0, -1.0, -1.0],
+ [-1.0, -1.0, -1.0],
+ [0.0, 1.0, 0.0]])
+
+ def test_is_within_mesh_volume(self):
+ """
+ Tests :func:`colour.volume.mesh.is_within_mesh_volume` definition.
+ """
+
+ self.assertTrue(
+ is_within_mesh_volume(np.array([0.0005, 0.0031, 0.0010]),
+ self.__mesh))
+
+ self.assertFalse(
+ is_within_mesh_volume(np.array([0.3205, 0.4131, 0.5100]),
+ self.__mesh))
+
+ self.assertTrue(
+ is_within_mesh_volume(np.array([0.0025, 0.0088, 0.0340]),
+ self.__mesh))
+
+ self.assertFalse(
+ is_within_mesh_volume(np.array([0.4325, 0.3788, 0.1034]),
+ self.__mesh))
+
+ def test_n_dimensional_is_within_mesh_volume(self):
+ """
+ Tests :func:`colour.volume.mesh.is_within_mesh_volume` definition
+ n-dimensional arrays support.
+ """
+
+ a = np.array([0.0005, 0.0031, 0.0010])
+ b = np.array([True])
+ np.testing.assert_almost_equal(
+ is_within_mesh_volume(a, self.__mesh),
+ b)
+
+ a = np.tile(a, (6, 1))
+ b = np.tile(b, 6)
+ np.testing.assert_almost_equal(
+ is_within_mesh_volume(a, self.__mesh),
+ b)
+
+ a = np.reshape(a, (2, 3, 3))
+ b = np.reshape(b, (2, 3))
+ np.testing.assert_almost_equal(
+ is_within_mesh_volume(a, self.__mesh),
+ b)
+
+ @ignore_numpy_errors
+ def test_nan_is_within_mesh_volume(self):
+ """
+ Tests :func:`colour.volume.mesh.is_within_mesh_volume` definition nan
+ support.
+ """
+
+ cases = [-1.0, 0.0, 1.0, -np.inf, np.inf, np.nan]
+ cases = set(permutations(cases * 3, r=3))
+ for case in cases:
+ is_within_mesh_volume(case, self.__mesh)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/colour/volume/tests/tests_rgb.py b/colour/volume/tests/tests_rgb.py
index 04e7509f7..04d5b636d 100644
--- a/colour/volume/tests/tests_rgb.py
+++ b/colour/volume/tests/tests_rgb.py
@@ -3,6 +3,18 @@
"""
Defines unit tests for :mod:`colour.volume.rgb` module.
+
+Notes
+-----
+The MonteCarlo sampling based unit tests are assuming that
+:func:`np.random.RandomState` definition will return the same sequence no
+matter which *OS* or *Python* version is used. There is however no formal
+promise about the *prng* sequence reproducibility of either *Python or *Numpy*
+implementations:
+
+Laurent. (2012). Reproducibility of python pseudo-random numbers across systems
+and versions? Retrieved January 20, 2015, from
+http://stackoverflow.com/questions/8786084/reproducibility-of-python-pseudo-random-numbers-across-systems-and-versions # noqa
"""
from __future__ import division, unicode_literals
@@ -22,7 +34,10 @@ from colour.models import (
from colour.volume import (
RGB_colourspace_limits,
RGB_colourspace_volume_MonteCarlo,
- RGB_colourspace_pointer_gamut_coverage_MonteCarlo)
+ RGB_colourspace_volume_coverage_MonteCarlo,
+ RGB_colourspace_pointer_gamut_coverage_MonteCarlo,
+ RGB_colourspace_visible_spectrum_coverage_MonteCarlo,
+ is_within_pointer_gamut)
__author__ = 'Colour Developers'
__copyright__ = 'Copyright (C) 2013 - 2014 - Colour Developers'
@@ -33,7 +48,9 @@ __status__ = 'Production'
__all__ = ['TestRGB_colourspaceLimits',
'TestRGB_colourspaceVolumeMonteCarlo',
- 'TestRGB_colourspacePointerGamutCoverageMonteCarlo']
+ 'TestRGB_colourspace_volume_coverage_MonteCarlo',
+ 'TestRGB_colourspacePointerGamutCoverageMonteCarlo',
+ 'TestRGB_colourspaceVisibleSpectrumCoverageMonteCarlo']
class TestRGB_colourspaceLimits(unittest.TestCase):
@@ -79,16 +96,6 @@ class TestRGB_colourspaceVolumeMonteCarlo(unittest.TestCase):
"""
Tests :func:`colour.volume.rgb.RGB_colourspace_volume_MonteCarlo`
definition.
-
- Notes
- -----
- The test is assuming that :func:`np.random.RandomState` definition will
- return the same sequence no matter which *OS* or *Python* version is
- used. There is however no formal promise about the *prng* sequence
- reproducibility of either *Python or *Numpy* implementations: Laurent.
- (2012). Reproducibility of python pseudo-random numbers across systems
- and versions? Retrieved January 20, 2015, from
- http://stackoverflow.com/questions/8786084/reproducibility-of-python-pseudo-random-numbers-across-systems-and-versions # noqa
"""
self.assertEquals(
@@ -100,6 +107,30 @@ class TestRGB_colourspaceVolumeMonteCarlo(unittest.TestCase):
859500.0)
+class TestRGB_colourspace_volume_coverage_MonteCarlo(unittest.TestCase):
+ """
+ Defines
+ :func:`colour.volume.rgb.RGB_colourspace_volume_coverage_MonteCarlo`
+ definition unit tests methods.
+ """
+
+ def test_RGB_colourspace_volume_coverage_MonteCarlo(self):
+ """
+ Tests
+ :func:`colour.volume.rgb.RGB_colourspace_volume_coverage_MonteCarlo` # noqa
+ definition.
+ """
+
+ np.testing.assert_almost_equal(
+ RGB_colourspace_volume_coverage_MonteCarlo(
+ REC_709_COLOURSPACE,
+ is_within_pointer_gamut,
+ 10e3,
+ random_state=np.random.RandomState(2)),
+ 83.02013422818791,
+ decimal=7)
+
+
class TestRGB_colourspacePointerGamutCoverageMonteCarlo(unittest.TestCase):
"""
Defines
@@ -112,16 +143,6 @@ class TestRGB_colourspacePointerGamutCoverageMonteCarlo(unittest.TestCase):
Tests
:func:`colour.volume.rgb.RGB_colourspace_pointer_gamut_coverage_MonteCarlo` # noqa
definition.
-
- Notes
- -----
- The test is assuming that :func:`np.random.RandomState` definition will
- return the same sequence no matter which *OS* or *Python* version is
- used. There is however no formal promise about the *prng* sequence
- reproducibility of either *Python or *Numpy* implementations: Laurent.
- (2012). Reproducibility of python pseudo-random numbers across systems
- and versions? Retrieved January 20, 2015, from
- http://stackoverflow.com/questions/8786084/reproducibility-of-python-pseudo-random-numbers-across-systems-and-versions # noqa
"""
np.testing.assert_almost_equal(
@@ -133,5 +154,28 @@ class TestRGB_colourspacePointerGamutCoverageMonteCarlo(unittest.TestCase):
decimal=7)
+class TestRGB_colourspaceVisibleSpectrumCoverageMonteCarlo(unittest.TestCase):
+ """
+ Defines
+ :func:`colour.volume.rgb.RGB_colourspace_visible_spectrum_coverage_MonteCarlo` # noqa
+ definition unit tests methods.
+ """
+
+ def test_RGB_colourspace_visible_spectrum_coverage_MonteCarlo(self):
+ """
+ Tests
+ :func:`colour.volume.rgb.RGB_colourspace_visible_spectrum_coverage_MonteCarlo` # noqa
+ definition.
+ """
+
+ np.testing.assert_almost_equal(
+ RGB_colourspace_visible_spectrum_coverage_MonteCarlo(
+ REC_709_COLOURSPACE,
+ 10e3,
+ random_state=np.random.RandomState(2)),
+ 36.48383937316356,
+ decimal=7)
+
+
if __name__ == '__main__':
unittest.main()
diff --git a/colour/volume/tests/tests_spectrum.py b/colour/volume/tests/tests_spectrum.py
new file mode 100644
index 000000000..8e90ceda6
--- /dev/null
+++ b/colour/volume/tests/tests_spectrum.py
@@ -0,0 +1,94 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
+"""
+Defines unit tests for :mod:`colour.volume.spectrum` module.
+"""
+
+from __future__ import division, unicode_literals
+
+import numpy as np
+import sys
+
+if sys.version_info[:2] <= (2, 6):
+ import unittest2 as unittest
+else:
+ import unittest
+from itertools import permutations
+
+from colour.volume import is_within_visible_spectrum
+from colour.utilities import ignore_numpy_errors
+
+__author__ = 'Colour Developers'
+__copyright__ = 'Copyright (C) 2013 - 2015 - Colour Developers'
+__license__ = 'New BSD License - http://opensource.org/licenses/BSD-3-Clause'
+__maintainer__ = 'Colour Developers'
+__email__ = '[email protected]'
+__status__ = 'Production'
+
+__all__ = ['TestIsWithinVisibleSpectrum']
+
+
+class TestIsWithinVisibleSpectrum(unittest.TestCase):
+ """
+ Defines :func:`colour.volume.spectrum.is_within_visible_spectrum`
+ definition unit tests methods.
+ """
+
+ def test_is_within_visible_spectrum(self):
+ """
+ Tests :func:`colour.volume.spectrum.is_within_visible_spectrum`
+ definition.
+ """
+
+ self.assertTrue(
+ is_within_visible_spectrum(np.array([0.3205, 0.4131, 0.5100])))
+
+ self.assertFalse(
+ is_within_visible_spectrum(np.array([-0.0005, 0.0031, 0.0010])))
+
+ self.assertTrue(
+ is_within_visible_spectrum(np.array([0.4325, 0.3788, 0.1034])))
+
+ self.assertFalse(
+ is_within_visible_spectrum(np.array([0.0025, 0.0088, 0.0340])))
+
+ def test_n_dimensional_is_within_visible_spectrum(self):
+ """
+ Tests :func:`colour.volume.spectrum.is_within_visible_spectrum`
+ definition n-dimensional arrays support.
+ """
+
+ a = np.array([0.3205, 0.4131, 0.5100])
+ b = np.array([True])
+ np.testing.assert_almost_equal(
+ is_within_visible_spectrum(a),
+ b)
+
+ a = np.tile(a, (6, 1))
+ b = np.tile(b, 6)
+ np.testing.assert_almost_equal(
+ is_within_visible_spectrum(a),
+ b)
+
+ a = np.reshape(a, (2, 3, 3))
+ b = np.reshape(b, (2, 3))
+ np.testing.assert_almost_equal(
+ is_within_visible_spectrum(a),
+ b)
+
+ @ignore_numpy_errors
+ def test_nan_is_within_visible_spectrum(self):
+ """
+ Tests :func:`colour.volume.spectrum.is_within_visible_spectrum`
+ definition nan support.
+ """
+
+ cases = [-1.0, 0.0, 1.0, -np.inf, np.inf, np.nan]
+ cases = set(permutations(cases * 3, r=3))
+ for case in cases:
+ is_within_visible_spectrum(case)
+
+
+if __name__ == '__main__':
+ unittest.main()
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_short_problem_statement",
"has_added_files",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 2,
"issue_text_score": 3,
"test_score": 2
},
"num_modified_files": 3
} | 0.3 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[tests]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"nose",
"flake8",
"coverage",
"pytest"
],
"pre_install": [],
"python": "3.4",
"reqs_path": [
"requirements/base.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | attrs==22.2.0
certifi==2021.5.30
-e git+https://github.com/colour-science/colour.git@3cc1e58379b92f8254f655ee108b721fd1342713#egg=colour_science
coverage==6.2
flake8==5.0.4
importlib-metadata==4.2.0
iniconfig==1.1.1
mccabe==0.7.0
nose==1.3.7
numpy==1.19.5
packaging==21.3
pluggy==1.0.0
py==1.11.0
pycodestyle==2.9.1
pyflakes==2.5.0
pyparsing==3.1.4
pytest==7.0.1
tomli==1.2.3
typing_extensions==4.1.1
zipp==3.6.0
| name: colour
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- pip=21.2.2=py36h06a4308_0
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_0
- setuptools=58.0.4=py36h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- attrs==22.2.0
- coverage==6.2
- flake8==5.0.4
- importlib-metadata==4.2.0
- iniconfig==1.1.1
- mccabe==0.7.0
- nose==1.3.7
- numpy==1.19.5
- packaging==21.3
- pluggy==1.0.0
- py==1.11.0
- pycodestyle==2.9.1
- pyflakes==2.5.0
- pyparsing==3.1.4
- pytest==7.0.1
- tomli==1.2.3
- typing-extensions==4.1.1
- zipp==3.6.0
prefix: /opt/conda/envs/colour
| [
"colour/volume/tests/tests_rgb.py::TestRGB_colourspaceLimits::test_RGB_colourspace_limits",
"colour/volume/tests/tests_rgb.py::TestRGB_colourspaceVolumeMonteCarlo::test_RGB_colourspace_volume_MonteCarlo"
] | [
"colour/volume/tests/tests_mesh.py::TestIsWithinMeshVolume::test_is_within_mesh_volume",
"colour/volume/tests/tests_mesh.py::TestIsWithinMeshVolume::test_n_dimensional_is_within_mesh_volume",
"colour/volume/tests/tests_mesh.py::TestIsWithinMeshVolume::test_nan_is_within_mesh_volume",
"colour/volume/tests/tests_rgb.py::TestRGB_colourspace_volume_coverage_MonteCarlo::test_RGB_colourspace_volume_coverage_MonteCarlo",
"colour/volume/tests/tests_rgb.py::TestRGB_colourspacePointerGamutCoverageMonteCarlo::test_RGB_colourspace_pointer_gamut_coverage_MonteCarlo",
"colour/volume/tests/tests_rgb.py::TestRGB_colourspaceVisibleSpectrumCoverageMonteCarlo::test_RGB_colourspace_visible_spectrum_coverage_MonteCarlo",
"colour/volume/tests/tests_spectrum.py::TestIsWithinVisibleSpectrum::test_is_within_visible_spectrum",
"colour/volume/tests/tests_spectrum.py::TestIsWithinVisibleSpectrum::test_n_dimensional_is_within_visible_spectrum",
"colour/volume/tests/tests_spectrum.py::TestIsWithinVisibleSpectrum::test_nan_is_within_visible_spectrum"
] | [] | [] | BSD 3-Clause "New" or "Revised" License | 192 |
|
sympy__sympy-9682 | 36badf22076027367f13fb8825319f07ff2e86fc | 2015-07-15 12:39:36 | 0241b35cae5f2adc04dc37b25f7dc9c5f00bd746 | diff --git a/sympy/sets/sets.py b/sympy/sets/sets.py
index 1f4b4690ae..c18a2567db 100644
--- a/sympy/sets/sets.py
+++ b/sympy/sets/sets.py
@@ -910,12 +910,17 @@ def _intersect(self, other):
def _complement(self, other):
- if other is S.Reals:
+ if other == S.Reals:
a = Interval(S.NegativeInfinity, self.start,
True, not self.left_open)
b = Interval(self.end, S.Infinity, not self.right_open, True)
return Union(a, b)
+ if isinstance(other, FiniteSet):
+ nums = [m for m in other.args if m.is_number]
+ if nums == []:
+ return None
+
return Set._complement(self, other)
@@ -1738,23 +1743,25 @@ def _intersect(self, other):
return self.__class__(el for el in self if el in other)
def _complement(self, other):
- if other is S.Reals:
+ if isinstance(other, Interval):
nums = sorted(m for m in self.args if m.is_number)
- syms = [m for m in self.args if m.is_Symbol]
- # Reals cannot contain elements other than numbers and symbols.
+ if other == S.Reals and nums != []:
+ syms = [m for m in self.args if m.is_Symbol]
+ # Reals cannot contain elements other than numbers and symbols.
- intervals = [] # Build up a list of intervals between the elements
- if nums != []:
+ intervals = [] # Build up a list of intervals between the elements
intervals += [Interval(S.NegativeInfinity, nums[0], True, True)]
for a, b in zip(nums[:-1], nums[1:]):
intervals.append(Interval(a, b, True, True)) # both open
intervals.append(Interval(nums[-1], S.Infinity, True, True))
- if syms != []:
- return Complement(Union(intervals, evaluate=False),
- FiniteSet(*syms), evaluate=False)
- else:
- return Union(intervals, evaluate=False)
+ if syms != []:
+ return Complement(Union(intervals, evaluate=False),
+ FiniteSet(*syms), evaluate=False)
+ else:
+ return Union(intervals, evaluate=False)
+ elif nums == []:
+ return None
return Set._complement(self, other)
| `S.Reals - FiniteSet(n)` returns `EmptySet - FiniteSet(n)`
Since
```
>>> Intersection(S.Reals, FiniteSet(n))
# returned unevaluated
```
Hence, I think above should also be returned unevaluated.
The similar though happens with
```
>>> Interval(1,4) - FiniteSet(n)
EmptySet()
```
I am not having latest commits though. | sympy/sympy | diff --git a/sympy/sets/tests/test_sets.py b/sympy/sets/tests/test_sets.py
index fd8bc62c21..b08ef0ad5d 100644
--- a/sympy/sets/tests/test_sets.py
+++ b/sympy/sets/tests/test_sets.py
@@ -869,3 +869,15 @@ def test_issue_9536():
from sympy.functions.elementary.exponential import log
a = Symbol('a', real=True)
assert FiniteSet(log(a)).intersect(S.Reals) == Intersection(S.Reals, FiniteSet(log(a)))
+
+
+def test_issue_9637():
+ n = Symbol('n')
+ a = FiniteSet(n)
+ b = FiniteSet(2, n)
+ assert Complement(S.Reals, a) == Complement(S.Reals, a, evaluate=False)
+ assert Complement(Interval(1, 3), a) == Complement(Interval(1, 3), a, evaluate=False)
+ assert Complement(Interval(1, 3), b) == \
+ Complement(Union(Interval(1, 2, False, True), Interval(2, 3, True, False)), a)
+ assert Complement(a, S.Reals) == Complement(a, S.Reals, evaluate=False)
+ assert Complement(a, Interval(1, 3)) == Complement(a, Interval(1, 3), evaluate=False)
| {
"commit_name": "head_commit",
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true,
"llm_score": {
"difficulty_score": 1,
"issue_text_score": 2,
"test_score": 2
},
"num_modified_files": 1
} | 0.7 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "pytest",
"pip_packages": [
"mpmath>=0.19",
"pytest"
],
"pre_install": null,
"python": "3.6",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | attrs @ file:///opt/conda/conda-bld/attrs_1642510447205/work
certifi==2021.5.30
importlib-metadata @ file:///tmp/build/80754af9/importlib-metadata_1631916693255/work
iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work
more-itertools @ file:///tmp/build/80754af9/more-itertools_1637733554872/work
mpmath==1.3.0
packaging @ file:///tmp/build/80754af9/packaging_1637314298585/work
pluggy @ file:///tmp/build/80754af9/pluggy_1615976315926/work
py @ file:///opt/conda/conda-bld/py_1644396412707/work
pyparsing @ file:///tmp/build/80754af9/pyparsing_1635766073266/work
pytest==6.2.4
-e git+https://github.com/sympy/sympy.git@36badf22076027367f13fb8825319f07ff2e86fc#egg=sympy
toml @ file:///tmp/build/80754af9/toml_1616166611790/work
typing_extensions @ file:///opt/conda/conda-bld/typing_extensions_1647553014482/work
zipp @ file:///tmp/build/80754af9/zipp_1633618647012/work
| name: sympy
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- attrs=21.4.0=pyhd3eb1b0_0
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- importlib-metadata=4.8.1=py36h06a4308_0
- importlib_metadata=4.8.1=hd3eb1b0_0
- iniconfig=1.1.1=pyhd3eb1b0_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- more-itertools=8.12.0=pyhd3eb1b0_0
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- packaging=21.3=pyhd3eb1b0_0
- pip=21.2.2=py36h06a4308_0
- pluggy=0.13.1=py36h06a4308_0
- py=1.11.0=pyhd3eb1b0_0
- pyparsing=3.0.4=pyhd3eb1b0_0
- pytest=6.2.4=py36h06a4308_2
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_0
- setuptools=58.0.4=py36h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- toml=0.10.2=pyhd3eb1b0_0
- typing_extensions=4.1.1=pyh06a4308_0
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- zipp=3.6.0=pyhd3eb1b0_0
- zlib=1.2.13=h5eee18b_1
- pip:
- mpmath==1.3.0
prefix: /opt/conda/envs/sympy
| [
"sympy/sets/tests/test_sets.py::test_issue_9637"
] | [] | [
"sympy/sets/tests/test_sets.py::test_interval_arguments",
"sympy/sets/tests/test_sets.py::test_interval_symbolic_end_points",
"sympy/sets/tests/test_sets.py::test_union",
"sympy/sets/tests/test_sets.py::test_difference",
"sympy/sets/tests/test_sets.py::test_Complement",
"sympy/sets/tests/test_sets.py::test_complement",
"sympy/sets/tests/test_sets.py::test_intersect",
"sympy/sets/tests/test_sets.py::test_intersection",
"sympy/sets/tests/test_sets.py::test_issue_9623",
"sympy/sets/tests/test_sets.py::test_is_disjoint",
"sympy/sets/tests/test_sets.py::test_ProductSet_of_single_arg_is_arg",
"sympy/sets/tests/test_sets.py::test_interval_subs",
"sympy/sets/tests/test_sets.py::test_interval_to_mpi",
"sympy/sets/tests/test_sets.py::test_measure",
"sympy/sets/tests/test_sets.py::test_is_subset",
"sympy/sets/tests/test_sets.py::test_is_proper_subset",
"sympy/sets/tests/test_sets.py::test_is_superset",
"sympy/sets/tests/test_sets.py::test_is_proper_superset",
"sympy/sets/tests/test_sets.py::test_contains",
"sympy/sets/tests/test_sets.py::test_interval_symbolic",
"sympy/sets/tests/test_sets.py::test_union_contains",
"sympy/sets/tests/test_sets.py::test_is_number",
"sympy/sets/tests/test_sets.py::test_Interval_is_left_unbounded",
"sympy/sets/tests/test_sets.py::test_Interval_is_right_unbounded",
"sympy/sets/tests/test_sets.py::test_Interval_as_relational",
"sympy/sets/tests/test_sets.py::test_Finite_as_relational",
"sympy/sets/tests/test_sets.py::test_Union_as_relational",
"sympy/sets/tests/test_sets.py::test_Intersection_as_relational",
"sympy/sets/tests/test_sets.py::test_EmptySet",
"sympy/sets/tests/test_sets.py::test_finite_basic",
"sympy/sets/tests/test_sets.py::test_powerset",
"sympy/sets/tests/test_sets.py::test_product_basic",
"sympy/sets/tests/test_sets.py::test_real",
"sympy/sets/tests/test_sets.py::test_supinf",
"sympy/sets/tests/test_sets.py::test_universalset",
"sympy/sets/tests/test_sets.py::test_Union_of_ProductSets_shares",
"sympy/sets/tests/test_sets.py::test_Interval_free_symbols",
"sympy/sets/tests/test_sets.py::test_image_interval",
"sympy/sets/tests/test_sets.py::test_image_FiniteSet",
"sympy/sets/tests/test_sets.py::test_image_Union",
"sympy/sets/tests/test_sets.py::test_image_EmptySet",
"sympy/sets/tests/test_sets.py::test_issue_5724_7680",
"sympy/sets/tests/test_sets.py::test_boundary",
"sympy/sets/tests/test_sets.py::test_boundary_Union",
"sympy/sets/tests/test_sets.py::test_boundary_ProductSet",
"sympy/sets/tests/test_sets.py::test_boundary_ProductSet_line",
"sympy/sets/tests/test_sets.py::test_is_open",
"sympy/sets/tests/test_sets.py::test_is_closed",
"sympy/sets/tests/test_sets.py::test_closure",
"sympy/sets/tests/test_sets.py::test_interior",
"sympy/sets/tests/test_sets.py::test_issue_7841",
"sympy/sets/tests/test_sets.py::test_Eq",
"sympy/sets/tests/test_sets.py::test_SymmetricDifference",
"sympy/sets/tests/test_sets.py::test_issue_9536"
] | [] | BSD | 193 |
|
cdent__gabbi-56 | f2a32ad31bc205580834f009f05586a533f390f7 | 2015-07-16 05:25:12 | 081a75f5f0ddfdc31c4bab62db2f084a50c9ee99 | diff --git a/gabbi/handlers.py b/gabbi/handlers.py
index f754d94..d39a987 100644
--- a/gabbi/handlers.py
+++ b/gabbi/handlers.py
@@ -120,6 +120,8 @@ class HeadersResponseHandler(ResponseHandler):
test_key_value = {}
def action(self, test, header, value):
+ header = header.lower() # case-insensitive comparison
+
response = test.response
header_value = test.replace_template(value)
| case-insensitive headers
As far as I can tell, gabbi enforces lowercase headers:
```yaml
response_headers:
content-type: text/html; charset=utf-8
```
```
... ✓ front page returns HTML
```
vs.
```yaml
response_headers:
Content-Type: text/html; charset=utf-8
```
```
... E front page returns HTML
ERROR: front page returns HTML
"'Content-Type' header not available in response keys: dict_keys(['server', 'content-type', 'access-control-allow-origin', 'date', 'access-control-allow-credentials', 'connection', 'content-location', 'content-length', 'status'])"
```
From my perspective, the second version is more readable - so it would be nice if header name comparisons were case-insensitive.
| cdent/gabbi | diff --git a/gabbi/tests/test_handlers.py b/gabbi/tests/test_handlers.py
index b18e8ec..b647e80 100644
--- a/gabbi/tests/test_handlers.py
+++ b/gabbi/tests/test_handlers.py
@@ -94,10 +94,16 @@ class HandlersTest(unittest.TestCase):
def test_response_headers(self):
handler = handlers.HeadersResponseHandler(self.test_class)
+ self.test.response = {'content-type': 'text/plain'}
+
self.test.test_data = {'response_headers': {
'content-type': 'text/plain',
}}
- self.test.response = {'content-type': 'text/plain'}
+ self._assert_handler(handler)
+
+ self.test.test_data = {'response_headers': {
+ 'Content-Type': 'text/plain',
+ }}
self._assert_handler(handler)
def test_response_headers_regex(self):
| {
"commit_name": "head_commit",
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true,
"llm_score": {
"difficulty_score": 1,
"issue_text_score": 0,
"test_score": 0
},
"num_modified_files": 1
} | 1.1 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"tox",
"pytest"
],
"pre_install": [
"pip install tox"
],
"python": "3.4",
"reqs_path": [
"requirements.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | attrs==22.2.0
certifi==2021.5.30
decorator==5.1.1
distlib==0.3.9
filelock==3.4.1
fixtures==4.0.1
-e git+https://github.com/cdent/gabbi.git@f2a32ad31bc205580834f009f05586a533f390f7#egg=gabbi
httplib2==0.22.0
importlib-metadata==4.8.3
importlib-resources==5.4.0
iniconfig==1.1.1
jsonpath-rw==1.4.0
packaging==21.3
pbr==6.1.1
platformdirs==2.4.0
pluggy==1.0.0
ply==3.11
py==1.11.0
pyparsing==3.1.4
pytest==7.0.1
PyYAML==6.0.1
six==1.17.0
testtools==2.6.0
toml==0.10.2
tomli==1.2.3
tox==3.28.0
typing_extensions==4.1.1
virtualenv==20.17.1
wsgi_intercept==1.13.1
zipp==3.6.0
| name: gabbi
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- pip=21.2.2=py36h06a4308_0
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_0
- setuptools=58.0.4=py36h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- attrs==22.2.0
- decorator==5.1.1
- distlib==0.3.9
- filelock==3.4.1
- fixtures==4.0.1
- httplib2==0.22.0
- importlib-metadata==4.8.3
- importlib-resources==5.4.0
- iniconfig==1.1.1
- jsonpath-rw==1.4.0
- packaging==21.3
- pbr==6.1.1
- platformdirs==2.4.0
- pluggy==1.0.0
- ply==3.11
- py==1.11.0
- pyparsing==3.1.4
- pytest==7.0.1
- pyyaml==6.0.1
- six==1.17.0
- testtools==2.6.0
- toml==0.10.2
- tomli==1.2.3
- tox==3.28.0
- typing-extensions==4.1.1
- virtualenv==20.17.1
- wsgi-intercept==1.13.1
- zipp==3.6.0
prefix: /opt/conda/envs/gabbi
| [
"gabbi/tests/test_handlers.py::HandlersTest::test_response_headers"
] | [] | [
"gabbi/tests/test_handlers.py::HandlersTest::test_response_headers_fail_data",
"gabbi/tests/test_handlers.py::HandlersTest::test_response_headers_fail_header",
"gabbi/tests/test_handlers.py::HandlersTest::test_response_headers_regex",
"gabbi/tests/test_handlers.py::HandlersTest::test_response_json_paths",
"gabbi/tests/test_handlers.py::HandlersTest::test_response_json_paths_fail_data",
"gabbi/tests/test_handlers.py::HandlersTest::test_response_json_paths_fail_path",
"gabbi/tests/test_handlers.py::HandlersTest::test_response_strings",
"gabbi/tests/test_handlers.py::HandlersTest::test_response_strings_fail"
] | [] | Apache License 2.0 | 194 |
|
cdent__gabbi-59 | ad9c7d1743576979ae96a74469937afcb980b5af | 2015-07-16 09:15:44 | 081a75f5f0ddfdc31c4bab62db2f084a50c9ee99 | diff --git a/gabbi/case.py b/gabbi/case.py
index 50b8815..2be6949 100644
--- a/gabbi/case.py
+++ b/gabbi/case.py
@@ -153,7 +153,7 @@ class HTTPTestCase(testcase.TestCase):
def _environ_replace(self, message):
"""Replace an indicator in a message with the environment value."""
- value = re.sub(r"\$ENVIRON\['([^']+)'\]",
+ value = re.sub(self._replacer_regex('ENVIRON'),
self._environ_replacer, message)
if value == "False":
return False
@@ -167,7 +167,7 @@ class HTTPTestCase(testcase.TestCase):
Let KeyError raise if variable not present.
"""
- environ_name = match.group(1)
+ environ_name = match.group('arg')
return os.environ[environ_name]
@staticmethod
@@ -188,17 +188,17 @@ class HTTPTestCase(testcase.TestCase):
"""Replace a header indicator in a message with that headers value from
the prior request.
"""
- return re.sub(r"\$HEADERS\['([^']+)'\]",
+ return re.sub(self._replacer_regex('HEADERS'),
self._header_replacer, message)
def _header_replacer(self, match):
"""Replace a regex match with the value of a prior header."""
- header_key = match.group(1)
+ header_key = match.group('arg')
return self.prior.response[header_key.lower()]
def _json_replacer(self, match):
"""Replace a regex match with the value of a JSON Path."""
- path = match.group(1)
+ path = match.group('arg')
return str(self.extract_json_path_value(self.prior.json_data, path))
def _location_replace(self, message):
@@ -253,9 +253,14 @@ class HTTPTestCase(testcase.TestCase):
return full_url
+ @staticmethod
+ def _replacer_regex(key):
+ message = r"\$%s\[(?P<quote>['\"])(?P<arg>.+?)(?P=quote)\]" % key
+ return message
+
def _response_replace(self, message):
"""Replace a JSON Path from the prior request with a value."""
- return re.sub(r"\$RESPONSE\['([^']+)'\]",
+ return re.sub(self._replacer_regex('RESPONSE'),
self._json_replacer, message)
def _run_request(self, url, method, headers, body):
diff --git a/gabbi/gabbits_intercept/backref.yaml b/gabbi/gabbits_intercept/backref.yaml
index 4ae1168..e0cec5b 100644
--- a/gabbi/gabbits_intercept/backref.yaml
+++ b/gabbi/gabbits_intercept/backref.yaml
@@ -16,7 +16,7 @@ tests:
location: $SCHEME://$NETLOC/posterchild
- name: post some more json
- url: $RESPONSE['link']
+ url: $RESPONSE["link"]
request_headers:
content-type: application/json
method: POST
@@ -26,7 +26,7 @@ tests:
d:
z: $RESPONSE['b']
response_json_paths:
- a: $RESPONSE['a']
+ a: $RESPONSE["a"]
c: /v2
d:
z: $RESPONSE['b']
@@ -48,3 +48,19 @@ tests:
location: $SCHEME://$NETLOC$RESPONSE['c']
x-gabbi-url: $SCHEME://$NETLOC/v2
content-type: $HEADERS['content-type']
+
+- name: post even more json quote different
+ url: $RESPONSE["c"]
+ request_headers:
+ content-type: application/json
+ method: POST
+ data: |
+ {"a": "$RESPONSE["a"]",
+ "c": "$RESPONSE["c"]"}
+ response_strings:
+ - '"a": "$RESPONSE["a"]"'
+ - '"c": "/v2"'
+ response_headers:
+ location: $SCHEME://$NETLOC$RESPONSE['c']
+ x-gabbi-url: $SCHEME://$NETLOC/v2
+ content-type: $HEADERS['content-type']
diff --git a/gabbi/handlers.py b/gabbi/handlers.py
index d39a987..f754d94 100644
--- a/gabbi/handlers.py
+++ b/gabbi/handlers.py
@@ -120,8 +120,6 @@ class HeadersResponseHandler(ResponseHandler):
test_key_value = {}
def action(self, test, header, value):
- header = header.lower() # case-insensitive comparison
-
response = test.response
header_value = test.replace_template(value)
diff --git a/gabbi/reporter.py b/gabbi/reporter.py
index 9776b80..0479588 100644
--- a/gabbi/reporter.py
+++ b/gabbi/reporter.py
@@ -81,7 +81,7 @@ class ConciseTestResult(TextTestResult):
details = details.strip().splitlines()[-1] # traceback's last line
if ':' in details:
details = details.split(':', 1)[1] # discard exception name
- self.stream.writeln('\t%s' % details.strip())
+ self.stream.writeln('\t%s' % details)
class ConciseTestRunner(TextTestRunner):
| magical variables enforce single quotes
One of my tests contained the following line:
```yaml
url: $RESPONSE["$._links.next"]
```
That refused to work - it took me quite a while to figure out that's because gabbi seems to only accept single quotes there, as this worked just fine.
```yaml
url: $RESPONSE['$._links.next']
```
I would argue that users' expectation is that single and double quotes are equivalent.
| cdent/gabbi | diff --git a/gabbi/tests/test_handlers.py b/gabbi/tests/test_handlers.py
index b647e80..b18e8ec 100644
--- a/gabbi/tests/test_handlers.py
+++ b/gabbi/tests/test_handlers.py
@@ -94,16 +94,10 @@ class HandlersTest(unittest.TestCase):
def test_response_headers(self):
handler = handlers.HeadersResponseHandler(self.test_class)
- self.test.response = {'content-type': 'text/plain'}
-
self.test.test_data = {'response_headers': {
'content-type': 'text/plain',
}}
- self._assert_handler(handler)
-
- self.test.test_data = {'response_headers': {
- 'Content-Type': 'text/plain',
- }}
+ self.test.response = {'content-type': 'text/plain'}
self._assert_handler(handler)
def test_response_headers_regex(self):
diff --git a/gabbi/tests/test_replacers.py b/gabbi/tests/test_replacers.py
index f32fe01..11628c1 100644
--- a/gabbi/tests/test_replacers.py
+++ b/gabbi/tests/test_replacers.py
@@ -44,3 +44,8 @@ class EnvironReplaceTest(testtools.TestCase):
os.environ['moo'] = "cow"
self.assertEqual("cow", http_case._environ_replace(message))
+
+ message = '$ENVIRON["moo"]'
+
+ os.environ['moo'] = "True"
+ self.assertEqual(True, http_case._environ_replace(message))
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 0,
"issue_text_score": 2,
"test_score": 2
},
"num_modified_files": 4
} | 1.1 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[dev]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest",
"pytest-cov",
"pytest-xdist",
"pytest-mock",
"pytest-asyncio",
"subunit"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.9",
"reqs_path": [
"requirements/base.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | coverage==7.8.0
decorator==5.2.1
exceptiongroup==1.2.2
execnet==2.1.1
extras==1.0.0
-e git+https://github.com/cdent/gabbi.git@ad9c7d1743576979ae96a74469937afcb980b5af#egg=gabbi
httplib2==0.22.0
iniconfig==2.1.0
jsonpath-rw==1.4.0
packaging==24.2
pbr==6.1.1
pluggy==1.5.0
ply==3.11
pyparsing==3.2.3
pytest==8.3.5
pytest-asyncio==0.26.0
pytest-cov==6.0.0
pytest-mock==3.14.0
pytest-xdist==3.6.1
PyYAML==6.0.2
six==1.17.0
subunit==0.0.0a0
testtools==2.7.2
tomli==2.2.1
typing_extensions==4.13.0
wsgi_intercept==1.13.1
| name: gabbi
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=3.0.16=h5eee18b_0
- pip=25.0=py39h06a4308_0
- python=3.9.21=he870216_1
- readline=8.2=h5eee18b_0
- setuptools=75.8.0=py39h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- tzdata=2025a=h04d1e81_0
- wheel=0.45.1=py39h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- coverage==7.8.0
- decorator==5.2.1
- exceptiongroup==1.2.2
- execnet==2.1.1
- extras==1.0.0
- httplib2==0.22.0
- iniconfig==2.1.0
- jsonpath-rw==1.4.0
- packaging==24.2
- pbr==6.1.1
- pluggy==1.5.0
- ply==3.11
- pyparsing==3.2.3
- pytest==8.3.5
- pytest-asyncio==0.26.0
- pytest-cov==6.0.0
- pytest-mock==3.14.0
- pytest-xdist==3.6.1
- pyyaml==6.0.2
- six==1.17.0
- subunit==0.0.0a0
- testtools==2.7.2
- tomli==2.2.1
- typing-extensions==4.13.0
- wsgi-intercept==1.13.1
prefix: /opt/conda/envs/gabbi
| [
"gabbi/tests/test_replacers.py::EnvironReplaceTest::test_environ_boolean"
] | [] | [
"gabbi/tests/test_handlers.py::HandlersTest::test_response_headers",
"gabbi/tests/test_handlers.py::HandlersTest::test_response_headers_fail_data",
"gabbi/tests/test_handlers.py::HandlersTest::test_response_headers_fail_header",
"gabbi/tests/test_handlers.py::HandlersTest::test_response_headers_regex",
"gabbi/tests/test_handlers.py::HandlersTest::test_response_json_paths",
"gabbi/tests/test_handlers.py::HandlersTest::test_response_json_paths_fail_data",
"gabbi/tests/test_handlers.py::HandlersTest::test_response_json_paths_fail_path",
"gabbi/tests/test_handlers.py::HandlersTest::test_response_strings",
"gabbi/tests/test_handlers.py::HandlersTest::test_response_strings_fail"
] | [] | Apache License 2.0 | 195 |
|
tailhook__injections-6 | 680d3403f0086e0a94d69604bba0bfcbd9596014 | 2015-07-16 17:37:03 | 680d3403f0086e0a94d69604bba0bfcbd9596014 | diff --git a/injections/__init__.py b/injections/__init__.py
index 47bdc0d..dce8a9e 100644
--- a/injections/__init__.py
+++ b/injections/__init__.py
@@ -1,6 +1,7 @@
from .core import (
Container,
Dependency,
+ MissingDependencyError,
has,
depends,
propagate,
@@ -11,6 +12,7 @@ from .core import (
__all__ = [
'Container',
'Dependency',
+ 'MissingDependencyError',
'has',
'depends',
'propagate',
diff --git a/injections/core.py b/injections/core.py
index a4dccae..edff1db 100644
--- a/injections/core.py
+++ b/injections/core.py
@@ -76,6 +76,13 @@ class Dependency:
depends = Dependency # nicer declarative name
+class MissingDependencyError(KeyError):
+ """Required dependency is missed in container"""
+
+ def __str__(self):
+ return "Dependency {!r} is missed in container".format(self.args[0])
+
+
class Container(object):
"""Container for things that will be dependency-injected
@@ -104,7 +111,10 @@ class Container(object):
deps = getattr(inst, '__injections__', None)
if deps:
for attr, dep in deps.items():
- val = pro[dep.name]
+ val = pro.get(dep.name)
+ if val is None:
+ raise MissingDependencyError(dep.name)
+
if not isinstance(val, dep.type):
raise TypeError("Wrong provider for {!r}".format(val))
setattr(inst, attr, val)
diff --git a/setup.py b/setup.py
index 41cf797..c1e7d04 100644
--- a/setup.py
+++ b/setup.py
@@ -16,4 +16,5 @@ setup(name='injections',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 2',
],
+ license='MIT',
)
| Use custom exception for injecting container into object with unknown dependencies
I have a class
```
@has
class A:
redis = depends(Redis)
loop = depends(AbstractLoop)
```
When I try to initialize it from container with missing dependencies I have a `KeyError`.
```
inj = Container()
inj['redis'] = create_redis()
inj.inject(A()) # raises KeyError
```
Exception on injection stage is pretty cool but I suggest using custom exception class. Not `KeyError` but derived from it. Exception text also should be more informative than just `KeyError: 'loop'`. | tailhook/injections | diff --git a/injections/test_core.py b/injections/test_core.py
index 2e9aabe..06006cd 100644
--- a/injections/test_core.py
+++ b/injections/test_core.py
@@ -126,3 +126,21 @@ class TestCore(TestCase):
c['name'] = 1
with self.assertRaises(TypeError):
c.inject(self.Consumer())
+
+ def test_missing_dependency(self):
+ c = di.Container()
+ c['a'] = 1
+
+ @di.has
+ class Consumer:
+ a = di.depends(int)
+ b = di.depends(int)
+
+ if hasattr(self, 'assertRaisesRegex'):
+ checker = self.assertRaisesRegex
+ else:
+ checker = self.assertRaisesRegexp
+
+ with checker(di.MissingDependencyError,
+ "Dependency 'b' is missed in container"):
+ c.inject(Consumer())
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 1,
"issue_text_score": 1,
"test_score": 3
},
"num_modified_files": 3
} | 0.2 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "pytest",
"pip_packages": [
"nose",
"pytest"
],
"pre_install": null,
"python": "3.4",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | attrs @ file:///opt/conda/conda-bld/attrs_1642510447205/work
certifi==2021.5.30
importlib-metadata @ file:///tmp/build/80754af9/importlib-metadata_1631916693255/work
iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work
-e git+https://github.com/tailhook/injections.git@680d3403f0086e0a94d69604bba0bfcbd9596014#egg=injections
more-itertools @ file:///tmp/build/80754af9/more-itertools_1637733554872/work
nose==1.3.7
packaging @ file:///tmp/build/80754af9/packaging_1637314298585/work
pluggy @ file:///tmp/build/80754af9/pluggy_1615976315926/work
py @ file:///opt/conda/conda-bld/py_1644396412707/work
pyparsing @ file:///tmp/build/80754af9/pyparsing_1635766073266/work
pytest==6.2.4
toml @ file:///tmp/build/80754af9/toml_1616166611790/work
typing_extensions @ file:///opt/conda/conda-bld/typing_extensions_1647553014482/work
zipp @ file:///tmp/build/80754af9/zipp_1633618647012/work
| name: injections
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- attrs=21.4.0=pyhd3eb1b0_0
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- importlib-metadata=4.8.1=py36h06a4308_0
- importlib_metadata=4.8.1=hd3eb1b0_0
- iniconfig=1.1.1=pyhd3eb1b0_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- more-itertools=8.12.0=pyhd3eb1b0_0
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- packaging=21.3=pyhd3eb1b0_0
- pip=21.2.2=py36h06a4308_0
- pluggy=0.13.1=py36h06a4308_0
- py=1.11.0=pyhd3eb1b0_0
- pyparsing=3.0.4=pyhd3eb1b0_0
- pytest=6.2.4=py36h06a4308_2
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_0
- setuptools=58.0.4=py36h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- toml=0.10.2=pyhd3eb1b0_0
- typing_extensions=4.1.1=pyh06a4308_0
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- zipp=3.6.0=pyhd3eb1b0_0
- zlib=1.2.13=h5eee18b_1
- pip:
- nose==1.3.7
prefix: /opt/conda/envs/injections
| [
"injections/test_core.py::TestCore::test_missing_dependency"
] | [] | [
"injections/test_core.py::TestCore::test_clone",
"injections/test_core.py::TestCore::test_cyclic",
"injections/test_core.py::TestCore::test_interconnect",
"injections/test_core.py::TestCore::test_larger_cycle",
"injections/test_core.py::TestCore::test_ok",
"injections/test_core.py::TestCore::test_wrong_type"
] | [] | MIT License | 196 |
|
sympy__sympy-9688 | 36badf22076027367f13fb8825319f07ff2e86fc | 2015-07-16 19:56:05 | 0241b35cae5f2adc04dc37b25f7dc9c5f00bd746 | diff --git a/sympy/solvers/solveset.py b/sympy/solvers/solveset.py
index f1914a6a15..05dd5fef19 100644
--- a/sympy/solvers/solveset.py
+++ b/sympy/solvers/solveset.py
@@ -393,6 +393,16 @@ def solveset_real(f, symbol):
raise ValueError(" %s is not a symbol" % (symbol))
f = sympify(f)
+ if isinstance(f, Eq):
+ from sympy.core import Add
+ f = Add(f.lhs, - f.rhs, evaluate=False)
+
+ if f is S.true:
+ return S.Reals
+
+ if f is S.false:
+ return EmptySet()
+
if not isinstance(f, (Expr, Number)):
raise ValueError(" %s is not a valid sympy expression" % (f))
| solveset_real(Eq(x, 1), x) gives NotImplementedError
```python
In [2]: solveset_real(Eq(x, 1), x)
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-2-ea6b87ce2d43> in <module>()
----> 1 solveset_real(Eq(x, 1), x)
NameError: name 'solveset_real' is not defined
In [3]: from sympy.solvers.solveset import *
In [4]: x, y, z, a, b, c = symbols('x y z a b c')
In [5]: solveset_real(Eq(x, 1), x)
---------------------------------------------------------------------------
NotImplementedError Traceback (most recent call last)
<ipython-input-5-ea6b87ce2d43> in <module>()
----> 1 solveset_real(Eq(x, 1), x)
/home/amit/Desktop/myrepo/sympy/sympy/solvers/solveset.pyc in solveset_real(f, symbol)
443 result += _solve_as_rational(equation, symbol,
444 solveset_solver=solveset_real,
--> 445 as_poly_solver=_solve_as_poly_real)
446 else:
447 result += solveset_real(equation, symbol)
/home/amit/Desktop/myrepo/sympy/sympy/solvers/solveset.pyc in _solve_as_rational(f, symbol, solveset_solver, as_poly_solver)
463 g, h = fraction(f)
464 if not h.has(symbol):
--> 465 return as_poly_solver(g, symbol)
466 else:
467 valid_solns = solveset_solver(g, symbol)
/home/amit/Desktop/myrepo/sympy/sympy/solvers/solveset.pyc in _solve_as_poly_real(f, symbol)
566 return _solve_as_poly(f, symbol,
567 solveset_solver=solveset_real,
--> 568 invert_func=invert_real)
569
570
/home/amit/Desktop/myrepo/sympy/sympy/solvers/solveset.pyc in _solve_as_poly(f, symbol, solveset_solver, invert_func)
556 return result
557 else:
--> 558 raise NotImplementedError
559
560
NotImplementedError:
``` | sympy/sympy | diff --git a/sympy/solvers/tests/test_solveset.py b/sympy/solvers/tests/test_solveset.py
index 55a298f26e..5e04e3e863 100644
--- a/sympy/solvers/tests/test_solveset.py
+++ b/sympy/solvers/tests/test_solveset.py
@@ -898,3 +898,10 @@ def test_issue_9557():
assert solveset(x**2 + a, x) == Intersection(S.Reals,
FiniteSet(-sqrt(-a), sqrt(-a)))
+
+
+def test_issue_9686():
+ x = Symbol('x')
+ assert solveset_real(Eq(x, 1), x) == FiniteSet(1)
+ assert solveset_real(Eq(1, 1), x) == S.Reals
+ assert solveset_real(Eq(2, 1), x) == S.EmptySet
| {
"commit_name": "head_commit",
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true,
"llm_score": {
"difficulty_score": 0,
"issue_text_score": 2,
"test_score": 0
},
"num_modified_files": 1
} | 0.7 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "mpmath>=0.19",
"pip_packages": [
"pytest"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.6",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | attrs==22.2.0
certifi==2021.5.30
importlib-metadata==4.8.3
iniconfig==1.1.1
mpmath==1.2.1
packaging==21.3
pluggy==1.0.0
py==1.11.0
pyparsing==3.1.4
pytest==7.0.1
-e git+https://github.com/sympy/sympy.git@36badf22076027367f13fb8825319f07ff2e86fc#egg=sympy
tomli==1.2.3
typing_extensions==4.1.1
zipp==3.6.0
| name: sympy
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- mpmath=1.2.1=py36h06a4308_0
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- pip=21.2.2=py36h06a4308_0
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_0
- setuptools=58.0.4=py36h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- attrs==22.2.0
- importlib-metadata==4.8.3
- iniconfig==1.1.1
- packaging==21.3
- pluggy==1.0.0
- py==1.11.0
- pyparsing==3.1.4
- pytest==7.0.1
- tomli==1.2.3
- typing-extensions==4.1.1
- zipp==3.6.0
prefix: /opt/conda/envs/sympy
| [
"sympy/solvers/tests/test_solveset.py::test_issue_9686"
] | [] | [
"sympy/solvers/tests/test_solveset.py::test_invert_real",
"sympy/solvers/tests/test_solveset.py::test_invert_complex",
"sympy/solvers/tests/test_solveset.py::test_domain_check",
"sympy/solvers/tests/test_solveset.py::test_is_function_class_equation",
"sympy/solvers/tests/test_solveset.py::test_garbage_input",
"sympy/solvers/tests/test_solveset.py::test_solve_mul",
"sympy/solvers/tests/test_solveset.py::test_solve_invert",
"sympy/solvers/tests/test_solveset.py::test_errorinverses",
"sympy/solvers/tests/test_solveset.py::test_solve_polynomial",
"sympy/solvers/tests/test_solveset.py::test_return_root_of",
"sympy/solvers/tests/test_solveset.py::test__has_rational_power",
"sympy/solvers/tests/test_solveset.py::test_solveset_sqrt_1",
"sympy/solvers/tests/test_solveset.py::test_solveset_sqrt_2",
"sympy/solvers/tests/test_solveset.py::test_solve_sqrt_3",
"sympy/solvers/tests/test_solveset.py::test_solve_polynomial_symbolic_param",
"sympy/solvers/tests/test_solveset.py::test_solve_rational",
"sympy/solvers/tests/test_solveset.py::test_solveset_real_gen_is_pow",
"sympy/solvers/tests/test_solveset.py::test_no_sol",
"sympy/solvers/tests/test_solveset.py::test_sol_zero_real",
"sympy/solvers/tests/test_solveset.py::test_no_sol_rational_extragenous",
"sympy/solvers/tests/test_solveset.py::test_solve_polynomial_cv_1a",
"sympy/solvers/tests/test_solveset.py::test_solveset_real_rational",
"sympy/solvers/tests/test_solveset.py::test_solveset_real_log",
"sympy/solvers/tests/test_solveset.py::test_poly_gens",
"sympy/solvers/tests/test_solveset.py::test_solve_abs",
"sympy/solvers/tests/test_solveset.py::test_real_imag_splitting",
"sympy/solvers/tests/test_solveset.py::test_units",
"sympy/solvers/tests/test_solveset.py::test_solve_only_exp_1",
"sympy/solvers/tests/test_solveset.py::test_atan2",
"sympy/solvers/tests/test_solveset.py::test_piecewise",
"sympy/solvers/tests/test_solveset.py::test_solveset_complex_polynomial",
"sympy/solvers/tests/test_solveset.py::test_sol_zero_complex",
"sympy/solvers/tests/test_solveset.py::test_solveset_complex_rational",
"sympy/solvers/tests/test_solveset.py::test_solveset_complex_exp",
"sympy/solvers/tests/test_solveset.py::test_solve_complex_log",
"sympy/solvers/tests/test_solveset.py::test_solve_complex_sqrt",
"sympy/solvers/tests/test_solveset.py::test_solveset_complex_tan",
"sympy/solvers/tests/test_solveset.py::test_solve_trig",
"sympy/solvers/tests/test_solveset.py::test_solve_invalid_sol",
"sympy/solvers/tests/test_solveset.py::test_solve_complex_unsolvable",
"sympy/solvers/tests/test_solveset.py::test_solveset",
"sympy/solvers/tests/test_solveset.py::test_improve_coverage",
"sympy/solvers/tests/test_solveset.py::test_issue_9522",
"sympy/solvers/tests/test_solveset.py::test_linear_eq_to_matrix",
"sympy/solvers/tests/test_solveset.py::test_linsolve",
"sympy/solvers/tests/test_solveset.py::test_issue_9556",
"sympy/solvers/tests/test_solveset.py::test_issue_9611",
"sympy/solvers/tests/test_solveset.py::test_issue_9557"
] | [] | BSD | 197 |
|
toejough__ugetch-24 | 2616fe2bbe55feb0048e3e973966f83d7f5f9710 | 2015-07-18 12:50:40 | 2616fe2bbe55feb0048e3e973966f83d7f5f9710 | diff --git a/.travis.yml b/.travis.yml
index 0386a42..4d40821 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -1,5 +1,11 @@
+# basic config
language: python
python: 3.4
install:
- pip install tox
script: tox
+
+# whitelist
+branches:
+ only:
+ - master
diff --git a/README.rst b/README.rst
index 91ee28f..ae7af94 100644
--- a/README.rst
+++ b/README.rst
@@ -24,17 +24,21 @@ API
getkey
------
-Gets a "key" from the ``infile`` and returns it to the user, where "key" is a character or glyph.
-Currently supports parsing ASCII and UTF-8.
+Gets a "key" from the ``infile`` and returns it to the user, where "key" is a character, glyph, or string describing a control key.
+
+Currently supports parsing ASCII, UTF-8, and tab.
Any other keys entered (such as arrow keys, UTF-16, etc) will result in returning individual bytes, one at a time.
+The tab key is represented as a string: 'TAB'. This is not a "character", but it *is* a "key". The implementation
+of keys may change in the future, but for now this seems to be simple and clear.
+
Parameters:
* ``infile`` - defaults to the ``sys.stdin`` file, as it is set at call time.
Returns:
-* ``key`` - a string value corresponding to the key read in from the TTY ('a', 'B', '-', etc).
+* ``key`` - a string value corresponding to the key read in from the TTY ('a', 'B', '-', '☢', 'TAB', etc).
contribution
============
diff --git a/ugetch/__init__.py b/ugetch/__init__.py
index 2c7bd98..b615ca3 100644
--- a/ugetch/__init__.py
+++ b/ugetch/__init__.py
@@ -14,40 +14,62 @@ import termios
def ascii_parser(infile):
'''Parse ascii bytes to ascii keys'''
byte = _get_byte(infile)
+ key = None
if byte < 128:
- return chr(byte)
+ key = chr(byte)
else:
_put_byte(byte)
+ return key
def utf8_parser(infile):
'''Parse utf-8 bytes to a string'''
first_byte = _get_byte(infile)
+ key = None
+ utf8_bytes = [first_byte]
# get byte string in py 2 and 3
- if sys.version_info.major == 3:
- string = chr(first_byte)
+ try:
+ if sys.version_info.major == 3:
+ key = chr(first_byte)
+ else:
+ if 194 <= first_byte <= 223:
+ # 2 bytes
+ utf8_bytes.append(_get_byte(infile))
+ elif 224 <= first_byte <= 239:
+ # 3 bytes
+ utf8_bytes.append(_get_byte(infile))
+ utf8_bytes.append(_get_byte(infile))
+ elif 240 <= first_byte <= 244:
+ # 4 bytes
+ utf8_bytes.append(_get_byte(infile))
+ utf8_bytes.append(_get_byte(infile))
+ utf8_bytes.append(_get_byte(infile))
+ byte_string = ''.join([chr(b) for b in utf8_bytes])
+ key = byte_string.decode('utf-8')
+ except:
+ # couldn't parse utf-8 out. not a failure, just not a success.
+ for b in utf8_bytes:
+ _put_byte(b)
+ return key
+
+
+def tab_parser(infile):
+ '''Parse a tab key out'''
+ first_byte = _get_byte(infile)
+ key = None
+ if first_byte == 9:
+ # Tab key
+ key = 'TAB'
else:
- utf8_bytes = [first_byte]
- if 194 <= first_byte <= 223:
- # 2 bytes
- utf8_bytes.append(_get_byte(infile))
- elif 224 <= first_byte <= 239:
- # 3 bytes
- utf8_bytes.append(_get_byte(infile))
- utf8_bytes.append(_get_byte(infile))
- elif 240 <= first_byte <= 244:
- # 4 bytes
- utf8_bytes.append(_get_byte(infile))
- utf8_bytes.append(_get_byte(infile))
- utf8_bytes.append(_get_byte(infile))
- byte_string = ''.join([chr(b) for b in utf8_bytes])
- string = byte_string.decode('utf-8')
- return string
+ _put_byte(first_byte)
+ return key
# [ Global ]
_DEFAULT=object() # enable dynamic defaults
-_KEY_PARSERS=[ascii_parser, utf8_parser] # ways to parse keys from byte lists
+# Tab needs to go before the ASCII parser, because it is technically in the ASCII range,
+# and would be sucked in raw by the ASCII parser.
+_KEY_PARSERS=[tab_parser, ascii_parser, utf8_parser] # ways to parse keys from byte lists
_BYTES=[] # byte buffer from the input file
| implement tab key support | toejough/ugetch | diff --git a/test_ugetch.py b/test_ugetch.py
index 52f60b7..072b7bf 100644
--- a/test_ugetch.py
+++ b/test_ugetch.py
@@ -19,8 +19,7 @@ import ugetch
# [ Helpers ]
-def in_vs_out(input_values):
- '''supply ascii chars, use getch, and validate ascii returned'''
+def start_cli_shim():
# choose the correct spawn
spawn = pexpect.spawn
if sys.version_info.major == 3:
@@ -28,23 +27,35 @@ def in_vs_out(input_values):
# spawn the subproc
p = spawn("python ugetch-cli.py", timeout=0.5)
p.expect_exact("hit ctrl-c to exit.")
+ return p
+
+
+def assert_expected(p, expected):
+ '''Assert that we get the expected value'''
+ index = p.expect_exact([expected, pexpect.EOF, pexpect.TIMEOUT])
+ assert index == 0, "did not find expected ({}) in output ({})".format(
+ value, p.before
+ )
+
+
+def in_vs_out(input_values):
+ '''supply ascii chars, use getch, and validate ascii returned'''
+ # get shim
+ p = start_cli_shim()
# test each char
for value in input_values:
p.expect_exact("hit a key to print its representation: ")
p.send(value)
- index = p.expect_exact([value, pexpect.EOF, pexpect.TIMEOUT])
- assert index == 0, "did not find expected ({}) in output ({})".format(
- value, p.before
- )
+ assert_expected(p, value)
# [ Unit tests ]
def test_getch_ascii():
'''supply ascii chars, use getch, and validate ascii returned'''
- in_vs_out(" \n\t")
all_printable_acii = [chr(n) for n in range(32, 127)] # not including 127
in_vs_out(all_printable_acii)
+
def test_getch_utf8():
'''supply utf-8 glyphs, use getch, and validate the keys returned'''
in_vs_out(['☢'])
@@ -52,6 +63,17 @@ def test_getch_utf8():
in_vs_out(['༰','༱','༲','༳','༴',' ༵','༶','༸',' ༹','༺',' ','༻',' ','༼','༽',' ༾',' ༿',' ','ཀ','ཁ','ག','གྷ','ང','ཅ','ཆ']) # tibetan
+def test_getch_tab():
+ # get shim
+ p = start_cli_shim()
+ # test each char
+ p.expect_exact("hit a key to print its representation: ")
+ p.send('\t')
+ assert_expected(p, 'TAB')
+ p.sendcontrol('i')
+ assert_expected(p, 'TAB')
+
+
if __name__ == '__main__':
import cProfile
cProfile.run("test_getch_ascii()")
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 3,
"issue_text_score": 3,
"test_score": 2
},
"num_modified_files": 3
} | unknown | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "pytest",
"pip_packages": [
"pytest",
"pexpect",
"pytest-cache"
],
"pre_install": null,
"python": "3.9",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | exceptiongroup @ file:///croot/exceptiongroup_1706031385326/work
execnet==2.1.1
iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work
packaging @ file:///croot/packaging_1734472117206/work
pexpect==4.9.0
pluggy @ file:///croot/pluggy_1733169602837/work
ptyprocess==0.7.0
pytest @ file:///croot/pytest_1738938843180/work
pytest-cache==1.0
tomli @ file:///opt/conda/conda-bld/tomli_1657175507142/work
-e git+https://github.com/toejough/ugetch.git@2616fe2bbe55feb0048e3e973966f83d7f5f9710#egg=ugetch
| name: ugetch
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- exceptiongroup=1.2.0=py39h06a4308_0
- iniconfig=1.1.1=pyhd3eb1b0_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=3.0.16=h5eee18b_0
- packaging=24.2=py39h06a4308_0
- pip=25.0=py39h06a4308_0
- pluggy=1.5.0=py39h06a4308_0
- pytest=8.3.4=py39h06a4308_0
- python=3.9.21=he870216_1
- readline=8.2=h5eee18b_0
- setuptools=75.8.0=py39h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- tomli=2.0.1=py39h06a4308_0
- tzdata=2025a=h04d1e81_0
- wheel=0.45.1=py39h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- execnet==2.1.1
- pexpect==4.9.0
- ptyprocess==0.7.0
- pytest-cache==1.0
prefix: /opt/conda/envs/ugetch
| [
"test_ugetch.py::test_getch_tab"
] | [] | [
"test_ugetch.py::test_getch_ascii",
"test_ugetch.py::test_getch_utf8"
] | [] | MIT License | 198 |
|
toejough__ugetch-26 | ddf84a5577fa1b7341dd404bdf5b5e9b9a43cf72 | 2015-07-18 13:52:44 | ddf84a5577fa1b7341dd404bdf5b5e9b9a43cf72 | diff --git a/README.rst b/README.rst
index ae7af94..3b949a3 100644
--- a/README.rst
+++ b/README.rst
@@ -26,11 +26,9 @@ getkey
Gets a "key" from the ``infile`` and returns it to the user, where "key" is a character, glyph, or string describing a control key.
-Currently supports parsing ASCII, UTF-8, and tab.
-Any other keys entered (such as arrow keys, UTF-16, etc) will result in returning individual bytes, one at a time.
-
-The tab key is represented as a string: 'TAB'. This is not a "character", but it *is* a "key". The implementation
-of keys may change in the future, but for now this seems to be simple and clear.
+Currently supports parsing ASCII, UTF-8, and some `special characters`_ as listed below.
+Any other keys entered will result in returning individual bytes, one at a time.
+*Pull requests adding special key support are welcome*
Parameters:
@@ -40,6 +38,21 @@ Returns:
* ``key`` - a string value corresponding to the key read in from the TTY ('a', 'B', '-', '☢', 'TAB', etc).
+Special Characters
+==================
+The following special characters are supported for VT220-like terminals. This is all I personally have to test on,
+but pull reqeusts with additional support are welcome. Issue #14 will make integration of new keys easier.
+
+Currently, special keys are supported by returning their name as a string, instead of a single character or glyph, as ASCII and UTF-8 do.
+This is not a "character", but it *is* a "key". The implementation
+of keys may change in the future, but for now this seems to be simple and clear.
+
+* TAB
+* UP
+* DOWN
+* LEFT
+* RIGHT
+
contribution
============
diff --git a/ugetch/__init__.py b/ugetch/__init__.py
index b615ca3..8d714da 100644
--- a/ugetch/__init__.py
+++ b/ugetch/__init__.py
@@ -65,11 +65,42 @@ def tab_parser(infile):
return key
+def arrow_parser(infile):
+ '''Parse arrow keys'''
+ first_byte = _get_byte(infile)
+ key = None
+ if first_byte == 27:
+ # escape. Check for bracket
+ second_byte = _get_byte(infile)
+ if second_byte == 91:
+ # final byte
+ final_byte = _get_byte(infile)
+ if final_byte == 65:
+ key = 'UP'
+ elif final_byte == 66:
+ key = 'DOWN'
+ elif final_byte == 67:
+ key = 'RIGHT'
+ elif final_byte == 68:
+ key = 'LEFT'
+ else:
+ _put_byte(first_byte)
+ _put_byte(second_byte)
+ _put_byte(final_byte)
+ else:
+ _put_byte(first_byte)
+ _put_byte(second_byte)
+ else:
+ _put_byte(first_byte)
+ return key
+
+
# [ Global ]
_DEFAULT=object() # enable dynamic defaults
-# Tab needs to go before the ASCII parser, because it is technically in the ASCII range,
-# and would be sucked in raw by the ASCII parser.
-_KEY_PARSERS=[tab_parser, ascii_parser, utf8_parser] # ways to parse keys from byte lists
+# Special key parsers need to go before the ASCII parser, because
+# their first byte is generally in the ASCII range,
+# and would be sucked in raw by the ASCII parser.
+_KEY_PARSERS=[tab_parser, arrow_parser, ascii_parser, utf8_parser] # ways to parse keys from byte lists
_BYTES=[] # byte buffer from the input file
| implement arrow key support | toejough/ugetch | diff --git a/test_ugetch.py b/test_ugetch.py
index 072b7bf..498adbd 100644
--- a/test_ugetch.py
+++ b/test_ugetch.py
@@ -34,7 +34,7 @@ def assert_expected(p, expected):
'''Assert that we get the expected value'''
index = p.expect_exact([expected, pexpect.EOF, pexpect.TIMEOUT])
assert index == 0, "did not find expected ({}) in output ({})".format(
- value, p.before
+ expected, p.before
)
@@ -44,7 +44,7 @@ def in_vs_out(input_values):
p = start_cli_shim()
# test each char
for value in input_values:
- p.expect_exact("hit a key to print its representation: ")
+ assert_expected(p, "hit a key to print its representation: ")
p.send(value)
assert_expected(p, value)
@@ -74,6 +74,24 @@ def test_getch_tab():
assert_expected(p, 'TAB')
+def test_getch_arrows():
+ # get shim
+ p = start_cli_shim()
+ # test each arrow
+ KEY_UP = '\x1b[A'
+ KEY_DOWN = '\x1b[B'
+ KEY_RIGHT = '\x1b[C'
+ KEY_LEFT = '\x1b[D'
+ p.send(KEY_UP)
+ assert_expected(p, 'UP')
+ p.send(KEY_DOWN)
+ assert_expected(p, 'DOWN')
+ p.send(KEY_LEFT)
+ assert_expected(p, 'LEFT')
+ p.send(KEY_RIGHT)
+ assert_expected(p, 'RIGHT')
+
+
if __name__ == '__main__':
import cProfile
cProfile.run("test_getch_ascii()")
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 2,
"issue_text_score": 3,
"test_score": 2
},
"num_modified_files": 2
} | unknown | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "pytest",
"pip_packages": [
"pytest",
"pexpect",
"pytest-cache"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.9",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | exceptiongroup @ file:///croot/exceptiongroup_1706031385326/work
execnet==2.1.1
iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work
packaging @ file:///croot/packaging_1734472117206/work
pexpect==4.9.0
pluggy @ file:///croot/pluggy_1733169602837/work
ptyprocess==0.7.0
pytest @ file:///croot/pytest_1738938843180/work
pytest-cache==1.0
tomli @ file:///opt/conda/conda-bld/tomli_1657175507142/work
-e git+https://github.com/toejough/ugetch.git@ddf84a5577fa1b7341dd404bdf5b5e9b9a43cf72#egg=ugetch
| name: ugetch
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- exceptiongroup=1.2.0=py39h06a4308_0
- iniconfig=1.1.1=pyhd3eb1b0_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=3.0.16=h5eee18b_0
- packaging=24.2=py39h06a4308_0
- pip=25.0=py39h06a4308_0
- pluggy=1.5.0=py39h06a4308_0
- pytest=8.3.4=py39h06a4308_0
- python=3.9.21=he870216_1
- readline=8.2=h5eee18b_0
- setuptools=75.8.0=py39h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- tomli=2.0.1=py39h06a4308_0
- tzdata=2025a=h04d1e81_0
- wheel=0.45.1=py39h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- execnet==2.1.1
- pexpect==4.9.0
- ptyprocess==0.7.0
- pytest-cache==1.0
prefix: /opt/conda/envs/ugetch
| [
"test_ugetch.py::test_getch_arrows"
] | [] | [
"test_ugetch.py::test_getch_ascii",
"test_ugetch.py::test_getch_utf8",
"test_ugetch.py::test_getch_tab"
] | [] | MIT License | 199 |
Subsets and Splits