Dataset Viewer
problem_id
stringlengths 18
22
| source
stringclasses 1
value | task_type
stringclasses 1
value | in_source_id
stringlengths 13
58
| prompt
stringlengths 1.1k
10.2k
| golden_diff
stringlengths 151
4.94k
| verification_info
stringlengths 582
21k
| num_tokens
int64 271
2.05k
| num_tokens_diff
int64 47
1.02k
|
---|---|---|---|---|---|---|---|---|
gh_patches_debug_32737 | rasdani/github-patches | git_diff | dask__dask-586 | We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Additional improvement for da.image.imread
I think following 2 improvements make the function better.
#### 1. Allow custom `imread` function.
Some prefer `opencv` which reads color in BGR order, otherwise `skimage` reads in RGB order. Adding `dialect` option (like `dialect='skimage'` or `dialect='cv'`) or accept different file read function may better.
#### 2. Allow custom preprocessing function.
In image processing, input images may have different sizes. In these case, preprocessing is needed between image read and array creation. This preprocessing function must return the same size of array on user's responsibility.
--- END ISSUE ---
Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `dask/array/image.py`
Content:
```
1 from glob import glob
2 import os
3
4 try:
5 from skimage.io import imread as sk_imread
6 except ImportError:
7 pass
8
9 from .core import Array
10 from ..base import tokenize
11
12 def add_leading_dimension(x):
13 return x[None, ...]
14
15
16 def imread(filename):
17 """ Read a stack of images into a dask array
18
19 Parameters
20 ----------
21
22 filename: string
23 A globstring like 'myfile.*.png'
24
25 Example
26 -------
27
28 >>> from dask.array.image import imread
29 >>> im = imread('2015-*-*.png') # doctest: +SKIP
30 >>> im.shape # doctest: +SKIP
31 (365, 1000, 1000, 3)
32
33 Returns
34 -------
35
36 Dask array of all images stacked along the first dimension. All images
37 will be treated as individual chunks
38 """
39 filenames = sorted(glob(filename))
40 if not filenames:
41 raise ValueError("No files found under name %s" % filename)
42
43 name = 'imread-%s' % tokenize(filenames, map(os.path.getmtime, filenames))
44
45 sample = sk_imread(filenames[0])
46
47 dsk = dict(((name, i) + (0,) * len(sample.shape),
48 (add_leading_dimension, (sk_imread, filename)))
49 for i, filename in enumerate(filenames))
50
51 chunks = ((1,) * len(filenames),) + tuple((d,) for d in sample.shape)
52
53 return Array(dsk, name, chunks, sample.dtype)
54
```
--- END FILES ---
Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.
Here is an example:
```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
if __name__ == "__main__":
- asyncio.run(run_async_server("."), debug=True)
+ asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
if __name__ == "__main__":
- server = run_sync_server(".")
+ server = run_sync_server()
server.shutdown()
```
| diff --git a/dask/array/image.py b/dask/array/image.py
--- a/dask/array/image.py
+++ b/dask/array/image.py
@@ -13,7 +13,7 @@
return x[None, ...]
-def imread(filename):
+def imread(filename, imread=None, preprocess=None):
""" Read a stack of images into a dask array
Parameters
@@ -21,6 +21,13 @@
filename: string
A globstring like 'myfile.*.png'
+ imread: function (optional)
+ Optionally provide custom imread function.
+ Function should expect a filename and produce a numpy array.
+ Defaults to ``skimage.io.imread``.
+ preprocess: function (optional)
+ Optionally provide custom function to preprocess the image.
+ Function should expect a numpy array for a single image.
Example
-------
@@ -36,17 +43,25 @@
Dask array of all images stacked along the first dimension. All images
will be treated as individual chunks
"""
+ imread = imread or sk_imread
filenames = sorted(glob(filename))
if not filenames:
raise ValueError("No files found under name %s" % filename)
name = 'imread-%s' % tokenize(filenames, map(os.path.getmtime, filenames))
- sample = sk_imread(filenames[0])
-
- dsk = dict(((name, i) + (0,) * len(sample.shape),
- (add_leading_dimension, (sk_imread, filename)))
- for i, filename in enumerate(filenames))
+ sample = imread(filenames[0])
+ if preprocess:
+ sample = preprocess(sample)
+
+ keys = [(name, i) + (0,) * len(sample.shape) for i in range(len(filenames))]
+ if preprocess:
+ values = [(add_leading_dimension, (preprocess, (imread, filename)))
+ for filename in filenames]
+ else:
+ values = [(add_leading_dimension, (imread, filename))
+ for filename in filenames]
+ dsk = dict(zip(keys, values))
chunks = ((1,) * len(filenames),) + tuple((d,) for d in sample.shape)
| {"golden_diff": "diff --git a/dask/array/image.py b/dask/array/image.py\n--- a/dask/array/image.py\n+++ b/dask/array/image.py\n@@ -13,7 +13,7 @@\n return x[None, ...]\n \n \n-def imread(filename):\n+def imread(filename, imread=None, preprocess=None):\n \"\"\" Read a stack of images into a dask array\n \n Parameters\n@@ -21,6 +21,13 @@\n \n filename: string\n A globstring like 'myfile.*.png'\n+ imread: function (optional)\n+ Optionally provide custom imread function.\n+ Function should expect a filename and produce a numpy array.\n+ Defaults to ``skimage.io.imread``.\n+ preprocess: function (optional)\n+ Optionally provide custom function to preprocess the image.\n+ Function should expect a numpy array for a single image.\n \n Example\n -------\n@@ -36,17 +43,25 @@\n Dask array of all images stacked along the first dimension. All images\n will be treated as individual chunks\n \"\"\"\n+ imread = imread or sk_imread\n filenames = sorted(glob(filename))\n if not filenames:\n raise ValueError(\"No files found under name %s\" % filename)\n \n name = 'imread-%s' % tokenize(filenames, map(os.path.getmtime, filenames))\n \n- sample = sk_imread(filenames[0])\n-\n- dsk = dict(((name, i) + (0,) * len(sample.shape),\n- (add_leading_dimension, (sk_imread, filename)))\n- for i, filename in enumerate(filenames))\n+ sample = imread(filenames[0])\n+ if preprocess:\n+ sample = preprocess(sample)\n+\n+ keys = [(name, i) + (0,) * len(sample.shape) for i in range(len(filenames))]\n+ if preprocess:\n+ values = [(add_leading_dimension, (preprocess, (imread, filename)))\n+ for filename in filenames]\n+ else:\n+ values = [(add_leading_dimension, (imread, filename))\n+ for filename in filenames]\n+ dsk = dict(zip(keys, values))\n \n chunks = ((1,) * len(filenames),) + tuple((d,) for d in sample.shape)\n", "issue": "Additional improvement for da.image.imread\nI think following 2 improvements make the function better.\n#### 1. Allow custom `imread` function.\n\nSome prefer `opencv` which reads color in BGR order, otherwise `skimage` reads in RGB order. Adding `dialect` option (like `dialect='skimage'` or `dialect='cv'`) or accept different file read function may better.\n#### 2. Allow custom preprocessing function.\n\nIn image processing, input images may have different sizes. In these case, preprocessing is needed between image read and array creation. This preprocessing function must return the same size of array on user's responsibility.\n\n", "before_files": [{"content": "from glob import glob\nimport os\n\ntry:\n from skimage.io import imread as sk_imread\nexcept ImportError:\n pass\n\nfrom .core import Array\nfrom ..base import tokenize\n\ndef add_leading_dimension(x):\n return x[None, ...]\n\n\ndef imread(filename):\n \"\"\" Read a stack of images into a dask array\n\n Parameters\n ----------\n\n filename: string\n A globstring like 'myfile.*.png'\n\n Example\n -------\n\n >>> from dask.array.image import imread\n >>> im = imread('2015-*-*.png') # doctest: +SKIP\n >>> im.shape # doctest: +SKIP\n (365, 1000, 1000, 3)\n\n Returns\n -------\n\n Dask array of all images stacked along the first dimension. All images\n will be treated as individual chunks\n \"\"\"\n filenames = sorted(glob(filename))\n if not filenames:\n raise ValueError(\"No files found under name %s\" % filename)\n\n name = 'imread-%s' % tokenize(filenames, map(os.path.getmtime, filenames))\n\n sample = sk_imread(filenames[0])\n\n dsk = dict(((name, i) + (0,) * len(sample.shape),\n (add_leading_dimension, (sk_imread, filename)))\n for i, filename in enumerate(filenames))\n\n chunks = ((1,) * len(filenames),) + tuple((d,) for d in sample.shape)\n\n return Array(dsk, name, chunks, sample.dtype)\n", "path": "dask/array/image.py"}], "after_files": [{"content": "from glob import glob\nimport os\n\ntry:\n from skimage.io import imread as sk_imread\nexcept ImportError:\n pass\n\nfrom .core import Array\nfrom ..base import tokenize\n\ndef add_leading_dimension(x):\n return x[None, ...]\n\n\ndef imread(filename, imread=None, preprocess=None):\n \"\"\" Read a stack of images into a dask array\n\n Parameters\n ----------\n\n filename: string\n A globstring like 'myfile.*.png'\n imread: function (optional)\n Optionally provide custom imread function.\n Function should expect a filename and produce a numpy array.\n Defaults to ``skimage.io.imread``.\n preprocess: function (optional)\n Optionally provide custom function to preprocess the image.\n Function should expect a numpy array for a single image.\n\n Example\n -------\n\n >>> from dask.array.image import imread\n >>> im = imread('2015-*-*.png') # doctest: +SKIP\n >>> im.shape # doctest: +SKIP\n (365, 1000, 1000, 3)\n\n Returns\n -------\n\n Dask array of all images stacked along the first dimension. All images\n will be treated as individual chunks\n \"\"\"\n imread = imread or sk_imread\n filenames = sorted(glob(filename))\n if not filenames:\n raise ValueError(\"No files found under name %s\" % filename)\n\n name = 'imread-%s' % tokenize(filenames, map(os.path.getmtime, filenames))\n\n sample = imread(filenames[0])\n if preprocess:\n sample = preprocess(sample)\n\n keys = [(name, i) + (0,) * len(sample.shape) for i in range(len(filenames))]\n if preprocess:\n values = [(add_leading_dimension, (preprocess, (imread, filename)))\n for filename in filenames]\n else:\n values = [(add_leading_dimension, (imread, filename))\n for filename in filenames]\n dsk = dict(zip(keys, values))\n\n chunks = ((1,) * len(filenames),) + tuple((d,) for d in sample.shape)\n\n return Array(dsk, name, chunks, sample.dtype)\n", "path": "dask/array/image.py"}]} | 843 | 497 |
gh_patches_debug_3876 | rasdani/github-patches | git_diff | xorbitsai__inference-299 | We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
FEAT: Disable Gradio Telemetry
Pull requests are disabled but see here:
https://github.com/arch-btw/inference/pull/1
--- END ISSUE ---
Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `examples/gradio_chatinterface.py`
Content:
```
1 from typing import Dict, List
2
3 import gradio as gr
4
5 from xinference.client import Client
6
7 if __name__ == "__main__":
8 import argparse
9 import textwrap
10
11 parser = argparse.ArgumentParser(
12 formatter_class=argparse.RawDescriptionHelpFormatter,
13 epilog=textwrap.dedent(
14 """\
15 instructions to run:
16 1. Install Xinference and Llama-cpp-python
17 2. Run 'xinference --host "localhost" --port 9997' in terminal
18 3. Run this python file in new terminal window
19
20 e.g. (feel free to copy)
21 python gradio_chatinterface.py \\
22 --endpoint http://localhost:9997 \\
23 --model_name vicuna-v1.3 \\
24 --model_size_in_billions 7 \\
25 --model_format ggmlv3 \\
26 --quantization q2_K
27
28 If you decide to change the port number in step 2,
29 please also change the endpoint in the arguments
30 """
31 ),
32 )
33
34 parser.add_argument(
35 "--endpoint", type=str, required=True, help="Xinference endpoint, required"
36 )
37 parser.add_argument(
38 "--model_name", type=str, required=True, help="Name of the model, required"
39 )
40 parser.add_argument(
41 "--model_size_in_billions",
42 type=int,
43 required=False,
44 help="Size of the model in billions",
45 )
46 parser.add_argument(
47 "--model_format",
48 type=str,
49 required=False,
50 help="Format of the model",
51 )
52 parser.add_argument(
53 "--quantization", type=str, required=False, help="Quantization of the model"
54 )
55
56 args = parser.parse_args()
57
58 endpoint = args.endpoint
59 model_name = args.model_name
60 model_size_in_billions = args.model_size_in_billions
61 model_format = args.model_format
62 quantization = args.quantization
63
64 print(f"Xinference endpoint: {endpoint}")
65 print(f"Model Name: {model_name}")
66 print(f"Model Size (in billions): {model_size_in_billions}")
67 print(f"Model Format: {model_format}")
68 print(f"Quantization: {quantization}")
69
70 client = Client(endpoint)
71 model_uid = client.launch_model(
72 model_name,
73 model_size_in_billions=model_size_in_billions,
74 model_format=model_format,
75 quantization=quantization,
76 n_ctx=2048,
77 )
78 model = client.get_model(model_uid)
79
80 def flatten(matrix: List[List[str]]) -> List[str]:
81 flat_list = []
82 for row in matrix:
83 flat_list += row
84 return flat_list
85
86 def to_chat(lst: List[str]) -> List[Dict[str, str]]:
87 res = []
88 for i in range(len(lst)):
89 role = "assistant" if i % 2 == 1 else "user"
90 res.append(
91 {
92 "role": role,
93 "content": lst[i],
94 }
95 )
96 return res
97
98 def generate_wrapper(message: str, history: List[List[str]]) -> str:
99 output = model.chat(
100 prompt=message,
101 chat_history=to_chat(flatten(history)),
102 generate_config={"max_tokens": 512, "stream": False},
103 )
104 return output["choices"][0]["message"]["content"]
105
106 demo = gr.ChatInterface(
107 fn=generate_wrapper,
108 examples=[
109 "Show me a two sentence horror story with a plot twist",
110 "Generate a Haiku poem using trignometry as the central theme",
111 "Write three sentences of scholarly description regarding a supernatural beast",
112 "Prove there does not exist a largest integer",
113 ],
114 title="Xinference Chat Bot",
115 )
116 demo.launch()
117
```
--- END FILES ---
Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.
Here is an example:
```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
if __name__ == "__main__":
- asyncio.run(run_async_server("."), debug=True)
+ asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
if __name__ == "__main__":
- server = run_sync_server(".")
+ server = run_sync_server()
server.shutdown()
```
| diff --git a/examples/gradio_chatinterface.py b/examples/gradio_chatinterface.py
--- a/examples/gradio_chatinterface.py
+++ b/examples/gradio_chatinterface.py
@@ -105,6 +105,7 @@
demo = gr.ChatInterface(
fn=generate_wrapper,
+ analytics_enabled=False,
examples=[
"Show me a two sentence horror story with a plot twist",
"Generate a Haiku poem using trignometry as the central theme",
| {"golden_diff": "diff --git a/examples/gradio_chatinterface.py b/examples/gradio_chatinterface.py\n--- a/examples/gradio_chatinterface.py\n+++ b/examples/gradio_chatinterface.py\n@@ -105,6 +105,7 @@\n \n demo = gr.ChatInterface(\n fn=generate_wrapper,\n+ analytics_enabled=False,\n examples=[\n \"Show me a two sentence horror story with a plot twist\",\n \"Generate a Haiku poem using trignometry as the central theme\",\n", "issue": "FEAT: Disable Gradio Telemetry\nPull requests are disabled but see here:\r\n\r\nhttps://github.com/arch-btw/inference/pull/1\n", "before_files": [{"content": "from typing import Dict, List\n\nimport gradio as gr\n\nfrom xinference.client import Client\n\nif __name__ == \"__main__\":\n import argparse\n import textwrap\n\n parser = argparse.ArgumentParser(\n formatter_class=argparse.RawDescriptionHelpFormatter,\n epilog=textwrap.dedent(\n \"\"\"\\\n instructions to run:\n 1. Install Xinference and Llama-cpp-python\n 2. Run 'xinference --host \"localhost\" --port 9997' in terminal\n 3. Run this python file in new terminal window\n\n e.g. (feel free to copy)\n python gradio_chatinterface.py \\\\\n --endpoint http://localhost:9997 \\\\\n --model_name vicuna-v1.3 \\\\\n --model_size_in_billions 7 \\\\\n --model_format ggmlv3 \\\\\n --quantization q2_K\n\n If you decide to change the port number in step 2,\n please also change the endpoint in the arguments\n \"\"\"\n ),\n )\n\n parser.add_argument(\n \"--endpoint\", type=str, required=True, help=\"Xinference endpoint, required\"\n )\n parser.add_argument(\n \"--model_name\", type=str, required=True, help=\"Name of the model, required\"\n )\n parser.add_argument(\n \"--model_size_in_billions\",\n type=int,\n required=False,\n help=\"Size of the model in billions\",\n )\n parser.add_argument(\n \"--model_format\",\n type=str,\n required=False,\n help=\"Format of the model\",\n )\n parser.add_argument(\n \"--quantization\", type=str, required=False, help=\"Quantization of the model\"\n )\n\n args = parser.parse_args()\n\n endpoint = args.endpoint\n model_name = args.model_name\n model_size_in_billions = args.model_size_in_billions\n model_format = args.model_format\n quantization = args.quantization\n\n print(f\"Xinference endpoint: {endpoint}\")\n print(f\"Model Name: {model_name}\")\n print(f\"Model Size (in billions): {model_size_in_billions}\")\n print(f\"Model Format: {model_format}\")\n print(f\"Quantization: {quantization}\")\n\n client = Client(endpoint)\n model_uid = client.launch_model(\n model_name,\n model_size_in_billions=model_size_in_billions,\n model_format=model_format,\n quantization=quantization,\n n_ctx=2048,\n )\n model = client.get_model(model_uid)\n\n def flatten(matrix: List[List[str]]) -> List[str]:\n flat_list = []\n for row in matrix:\n flat_list += row\n return flat_list\n\n def to_chat(lst: List[str]) -> List[Dict[str, str]]:\n res = []\n for i in range(len(lst)):\n role = \"assistant\" if i % 2 == 1 else \"user\"\n res.append(\n {\n \"role\": role,\n \"content\": lst[i],\n }\n )\n return res\n\n def generate_wrapper(message: str, history: List[List[str]]) -> str:\n output = model.chat(\n prompt=message,\n chat_history=to_chat(flatten(history)),\n generate_config={\"max_tokens\": 512, \"stream\": False},\n )\n return output[\"choices\"][0][\"message\"][\"content\"]\n\n demo = gr.ChatInterface(\n fn=generate_wrapper,\n examples=[\n \"Show me a two sentence horror story with a plot twist\",\n \"Generate a Haiku poem using trignometry as the central theme\",\n \"Write three sentences of scholarly description regarding a supernatural beast\",\n \"Prove there does not exist a largest integer\",\n ],\n title=\"Xinference Chat Bot\",\n )\n demo.launch()\n", "path": "examples/gradio_chatinterface.py"}], "after_files": [{"content": "from typing import Dict, List\n\nimport gradio as gr\n\nfrom xinference.client import Client\n\nif __name__ == \"__main__\":\n import argparse\n import textwrap\n\n parser = argparse.ArgumentParser(\n formatter_class=argparse.RawDescriptionHelpFormatter,\n epilog=textwrap.dedent(\n \"\"\"\\\n instructions to run:\n 1. Install Xinference and Llama-cpp-python\n 2. Run 'xinference --host \"localhost\" --port 9997' in terminal\n 3. Run this python file in new terminal window\n\n e.g. (feel free to copy)\n python gradio_chatinterface.py \\\\\n --endpoint http://localhost:9997 \\\\\n --model_name vicuna-v1.3 \\\\\n --model_size_in_billions 7 \\\\\n --model_format ggmlv3 \\\\\n --quantization q2_K\n\n If you decide to change the port number in step 2,\n please also change the endpoint in the arguments\n \"\"\"\n ),\n )\n\n parser.add_argument(\n \"--endpoint\", type=str, required=True, help=\"Xinference endpoint, required\"\n )\n parser.add_argument(\n \"--model_name\", type=str, required=True, help=\"Name of the model, required\"\n )\n parser.add_argument(\n \"--model_size_in_billions\",\n type=int,\n required=False,\n help=\"Size of the model in billions\",\n )\n parser.add_argument(\n \"--model_format\",\n type=str,\n required=False,\n help=\"Format of the model\",\n )\n parser.add_argument(\n \"--quantization\", type=str, required=False, help=\"Quantization of the model\"\n )\n\n args = parser.parse_args()\n\n endpoint = args.endpoint\n model_name = args.model_name\n model_size_in_billions = args.model_size_in_billions\n model_format = args.model_format\n quantization = args.quantization\n\n print(f\"Xinference endpoint: {endpoint}\")\n print(f\"Model Name: {model_name}\")\n print(f\"Model Size (in billions): {model_size_in_billions}\")\n print(f\"Model Format: {model_format}\")\n print(f\"Quantization: {quantization}\")\n\n client = Client(endpoint)\n model_uid = client.launch_model(\n model_name,\n model_size_in_billions=model_size_in_billions,\n model_format=model_format,\n quantization=quantization,\n n_ctx=2048,\n )\n model = client.get_model(model_uid)\n\n def flatten(matrix: List[List[str]]) -> List[str]:\n flat_list = []\n for row in matrix:\n flat_list += row\n return flat_list\n\n def to_chat(lst: List[str]) -> List[Dict[str, str]]:\n res = []\n for i in range(len(lst)):\n role = \"assistant\" if i % 2 == 1 else \"user\"\n res.append(\n {\n \"role\": role,\n \"content\": lst[i],\n }\n )\n return res\n\n def generate_wrapper(message: str, history: List[List[str]]) -> str:\n output = model.chat(\n prompt=message,\n chat_history=to_chat(flatten(history)),\n generate_config={\"max_tokens\": 512, \"stream\": False},\n )\n return output[\"choices\"][0][\"message\"][\"content\"]\n\n demo = gr.ChatInterface(\n fn=generate_wrapper,\n analytics_enabled=False,\n examples=[\n \"Show me a two sentence horror story with a plot twist\",\n \"Generate a Haiku poem using trignometry as the central theme\",\n \"Write three sentences of scholarly description regarding a supernatural beast\",\n \"Prove there does not exist a largest integer\",\n ],\n title=\"Xinference Chat Bot\",\n )\n demo.launch()\n", "path": "examples/gradio_chatinterface.py"}]} | 1,351 | 103 |
gh_patches_debug_4863 | rasdani/github-patches | git_diff | digitalfabrik__integreat-cms-1210 | We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
PDF Export URL pattern
### Describe the Bug
The web app calls `/REGION/LANG/wp-json/ig-mpdf/v1/pdf` to export a PDF which returns a 404. Our API currently uses `REGION/LANG/pdf`.
The normal mapping does not work, as we
### Steps to Reproduce
```shell
curl 'https://malte-test.tuerantuer.org/joerdenstorf/de/wp-json/ig-mpdf/v1/pdf'
```
### Expected Behavior
Map old URL pattern to new endpoint.
### Actual Behavior
404
--- END ISSUE ---
Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `integreat_cms/api/urls.py`
Content:
```
1 """
2 Expansion of API-Endpoints for the CMS
3 """
4 from django.urls import include, path, re_path
5
6 from .v3.events import events
7 from .v3.feedback import (
8 page_feedback,
9 search_result_feedback,
10 region_feedback,
11 offer_feedback,
12 offer_list_feedback,
13 event_list_feedback,
14 event_feedback,
15 poi_feedback,
16 map_feedback,
17 imprint_page_feedback,
18 legacy_feedback_endpoint,
19 )
20 from .v3.imprint import imprint
21 from .v3.languages import languages
22 from .v3.locations import locations
23 from .v3.pages import pages, children, parents, single_page
24 from .v3.pdf_export import pdf_export
25 from .v3.push_notifications import sent_push_notifications
26 from .v3.regions import regions, liveregions, hiddenregions
27 from .v3.offers import offers
28
29
30 #: The namespace for this URL config (see :attr:`django.urls.ResolverMatch.app_name`)
31 app_name = "api"
32
33 content_api_urlpatterns = [
34 path("pages/", pages, name="pages"),
35 path("locations/", locations, name="locations"),
36 path("events/", events, name="events"),
37 path("page/", single_page, name="single_page"),
38 path("post/", single_page, name="single_page"),
39 path("children/", children, name="children"),
40 path("parents/", parents, name="parents"),
41 path("pdf/", pdf_export, name="pdf_export"),
42 path(
43 "sent_push_notifications/",
44 sent_push_notifications,
45 name="sent_push_notifications",
46 ),
47 path("imprint/", imprint, name="imprint"),
48 path("disclaimer/", imprint, name="imprint"),
49 path("offers/", offers, name="offers"),
50 path("extras/", offers, name="offers"),
51 re_path(
52 r"^feedback/?$",
53 legacy_feedback_endpoint.legacy_feedback_endpoint,
54 name="legacy_feedback_endpoint",
55 ),
56 path(
57 "feedback/",
58 include(
59 [
60 re_path(
61 r"^categories/?$",
62 region_feedback.region_feedback,
63 name="region_feedback",
64 ),
65 re_path(r"^page/?$", page_feedback.page_feedback, name="page_feedback"),
66 re_path(r"^poi/?$", poi_feedback.poi_feedback, name="poi_feedback"),
67 re_path(
68 r"^event/?$", event_feedback.event_feedback, name="event_feedback"
69 ),
70 re_path(
71 r"^events/?$",
72 event_list_feedback.event_list_feedback,
73 name="event_list_feedback",
74 ),
75 re_path(
76 r"^imprint-page/?$",
77 imprint_page_feedback.imprint_page_feedback,
78 name="imprint_page_feedbacks",
79 ),
80 re_path(r"^map/?$", map_feedback.map_feedback, name="map_feedback"),
81 re_path(
82 r"^search/?$",
83 search_result_feedback.search_result_feedback,
84 name="search_result_feedback",
85 ),
86 re_path(
87 r"^offers/?$",
88 offer_list_feedback.offer_list_feedback,
89 name="offer_list_feedback",
90 ),
91 re_path(
92 r"^extras/?$",
93 offer_list_feedback.offer_list_feedback,
94 name="offer_list_feedback",
95 ),
96 re_path(
97 r"^offer/?$", offer_feedback.offer_feedback, name="offer_feedback"
98 ),
99 re_path(
100 r"^extra/?$", offer_feedback.offer_feedback, name="offer_feedback"
101 ),
102 ]
103 ),
104 ),
105 ]
106
107 region_api_urlpatterns = [
108 path("", regions, name="regions"),
109 path("live/", liveregions, name="regions_live"),
110 path("hidden/", hiddenregions, name="regions_hidden"),
111 ]
112
113 #: The url patterns of this module (see :doc:`topics/http/urls`)
114 urlpatterns = [
115 path("api/regions/", include(region_api_urlpatterns)),
116 path("wp-json/extensions/v3/sites/", include(region_api_urlpatterns)),
117 path(
118 "api/<slug:region_slug>/",
119 include(
120 [
121 path("languages/", languages, name="languages"),
122 path("offers/", offers, name="offers"),
123 path("extras/", offers, name="offers"),
124 path("<slug:language_slug>/", include(content_api_urlpatterns)),
125 ]
126 ),
127 ),
128 path(
129 "<slug:region_slug>/",
130 include(
131 [
132 path(
133 "de/wp-json/extensions/v3/languages/", languages, name="languages"
134 ),
135 path(
136 "<slug:language_slug>/wp-json/extensions/v3/",
137 include(content_api_urlpatterns),
138 ),
139 ]
140 ),
141 ),
142 ]
143
```
--- END FILES ---
Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.
Here is an example:
```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
if __name__ == "__main__":
- asyncio.run(run_async_server("."), debug=True)
+ asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
if __name__ == "__main__":
- server = run_sync_server(".")
+ server = run_sync_server()
server.shutdown()
```
| diff --git a/integreat_cms/api/urls.py b/integreat_cms/api/urls.py
--- a/integreat_cms/api/urls.py
+++ b/integreat_cms/api/urls.py
@@ -136,6 +136,11 @@
"<slug:language_slug>/wp-json/extensions/v3/",
include(content_api_urlpatterns),
),
+ path(
+ "<slug:language_slug>/wp-json/ig-mpdf/v1/pdf/",
+ pdf_export,
+ name="pdf_export",
+ ),
]
),
),
| {"golden_diff": "diff --git a/integreat_cms/api/urls.py b/integreat_cms/api/urls.py\n--- a/integreat_cms/api/urls.py\n+++ b/integreat_cms/api/urls.py\n@@ -136,6 +136,11 @@\n \"<slug:language_slug>/wp-json/extensions/v3/\",\n include(content_api_urlpatterns),\n ),\n+ path(\n+ \"<slug:language_slug>/wp-json/ig-mpdf/v1/pdf/\",\n+ pdf_export,\n+ name=\"pdf_export\",\n+ ),\n ]\n ),\n ),\n", "issue": "PDF Export URL pattern\n### Describe the Bug\r\nThe web app calls `/REGION/LANG/wp-json/ig-mpdf/v1/pdf` to export a PDF which returns a 404. Our API currently uses `REGION/LANG/pdf`.\r\n\r\nThe normal mapping does not work, as we\r\n\r\n### Steps to Reproduce\r\n\r\n```shell\r\ncurl 'https://malte-test.tuerantuer.org/joerdenstorf/de/wp-json/ig-mpdf/v1/pdf'\r\n```\r\n\r\n### Expected Behavior\r\nMap old URL pattern to new endpoint.\r\n\r\n\r\n### Actual Behavior\r\n404\n", "before_files": [{"content": "\"\"\"\nExpansion of API-Endpoints for the CMS\n\"\"\"\nfrom django.urls import include, path, re_path\n\nfrom .v3.events import events\nfrom .v3.feedback import (\n page_feedback,\n search_result_feedback,\n region_feedback,\n offer_feedback,\n offer_list_feedback,\n event_list_feedback,\n event_feedback,\n poi_feedback,\n map_feedback,\n imprint_page_feedback,\n legacy_feedback_endpoint,\n)\nfrom .v3.imprint import imprint\nfrom .v3.languages import languages\nfrom .v3.locations import locations\nfrom .v3.pages import pages, children, parents, single_page\nfrom .v3.pdf_export import pdf_export\nfrom .v3.push_notifications import sent_push_notifications\nfrom .v3.regions import regions, liveregions, hiddenregions\nfrom .v3.offers import offers\n\n\n#: The namespace for this URL config (see :attr:`django.urls.ResolverMatch.app_name`)\napp_name = \"api\"\n\ncontent_api_urlpatterns = [\n path(\"pages/\", pages, name=\"pages\"),\n path(\"locations/\", locations, name=\"locations\"),\n path(\"events/\", events, name=\"events\"),\n path(\"page/\", single_page, name=\"single_page\"),\n path(\"post/\", single_page, name=\"single_page\"),\n path(\"children/\", children, name=\"children\"),\n path(\"parents/\", parents, name=\"parents\"),\n path(\"pdf/\", pdf_export, name=\"pdf_export\"),\n path(\n \"sent_push_notifications/\",\n sent_push_notifications,\n name=\"sent_push_notifications\",\n ),\n path(\"imprint/\", imprint, name=\"imprint\"),\n path(\"disclaimer/\", imprint, name=\"imprint\"),\n path(\"offers/\", offers, name=\"offers\"),\n path(\"extras/\", offers, name=\"offers\"),\n re_path(\n r\"^feedback/?$\",\n legacy_feedback_endpoint.legacy_feedback_endpoint,\n name=\"legacy_feedback_endpoint\",\n ),\n path(\n \"feedback/\",\n include(\n [\n re_path(\n r\"^categories/?$\",\n region_feedback.region_feedback,\n name=\"region_feedback\",\n ),\n re_path(r\"^page/?$\", page_feedback.page_feedback, name=\"page_feedback\"),\n re_path(r\"^poi/?$\", poi_feedback.poi_feedback, name=\"poi_feedback\"),\n re_path(\n r\"^event/?$\", event_feedback.event_feedback, name=\"event_feedback\"\n ),\n re_path(\n r\"^events/?$\",\n event_list_feedback.event_list_feedback,\n name=\"event_list_feedback\",\n ),\n re_path(\n r\"^imprint-page/?$\",\n imprint_page_feedback.imprint_page_feedback,\n name=\"imprint_page_feedbacks\",\n ),\n re_path(r\"^map/?$\", map_feedback.map_feedback, name=\"map_feedback\"),\n re_path(\n r\"^search/?$\",\n search_result_feedback.search_result_feedback,\n name=\"search_result_feedback\",\n ),\n re_path(\n r\"^offers/?$\",\n offer_list_feedback.offer_list_feedback,\n name=\"offer_list_feedback\",\n ),\n re_path(\n r\"^extras/?$\",\n offer_list_feedback.offer_list_feedback,\n name=\"offer_list_feedback\",\n ),\n re_path(\n r\"^offer/?$\", offer_feedback.offer_feedback, name=\"offer_feedback\"\n ),\n re_path(\n r\"^extra/?$\", offer_feedback.offer_feedback, name=\"offer_feedback\"\n ),\n ]\n ),\n ),\n]\n\nregion_api_urlpatterns = [\n path(\"\", regions, name=\"regions\"),\n path(\"live/\", liveregions, name=\"regions_live\"),\n path(\"hidden/\", hiddenregions, name=\"regions_hidden\"),\n]\n\n#: The url patterns of this module (see :doc:`topics/http/urls`)\nurlpatterns = [\n path(\"api/regions/\", include(region_api_urlpatterns)),\n path(\"wp-json/extensions/v3/sites/\", include(region_api_urlpatterns)),\n path(\n \"api/<slug:region_slug>/\",\n include(\n [\n path(\"languages/\", languages, name=\"languages\"),\n path(\"offers/\", offers, name=\"offers\"),\n path(\"extras/\", offers, name=\"offers\"),\n path(\"<slug:language_slug>/\", include(content_api_urlpatterns)),\n ]\n ),\n ),\n path(\n \"<slug:region_slug>/\",\n include(\n [\n path(\n \"de/wp-json/extensions/v3/languages/\", languages, name=\"languages\"\n ),\n path(\n \"<slug:language_slug>/wp-json/extensions/v3/\",\n include(content_api_urlpatterns),\n ),\n ]\n ),\n ),\n]\n", "path": "integreat_cms/api/urls.py"}], "after_files": [{"content": "\"\"\"\nExpansion of API-Endpoints for the CMS\n\"\"\"\nfrom django.urls import include, path, re_path\n\nfrom .v3.events import events\nfrom .v3.feedback import (\n page_feedback,\n search_result_feedback,\n region_feedback,\n offer_feedback,\n offer_list_feedback,\n event_list_feedback,\n event_feedback,\n poi_feedback,\n map_feedback,\n imprint_page_feedback,\n legacy_feedback_endpoint,\n)\nfrom .v3.imprint import imprint\nfrom .v3.languages import languages\nfrom .v3.locations import locations\nfrom .v3.pages import pages, children, parents, single_page\nfrom .v3.pdf_export import pdf_export\nfrom .v3.push_notifications import sent_push_notifications\nfrom .v3.regions import regions, liveregions, hiddenregions\nfrom .v3.offers import offers\n\n\n#: The namespace for this URL config (see :attr:`django.urls.ResolverMatch.app_name`)\napp_name = \"api\"\n\ncontent_api_urlpatterns = [\n path(\"pages/\", pages, name=\"pages\"),\n path(\"locations/\", locations, name=\"locations\"),\n path(\"events/\", events, name=\"events\"),\n path(\"page/\", single_page, name=\"single_page\"),\n path(\"post/\", single_page, name=\"single_page\"),\n path(\"children/\", children, name=\"children\"),\n path(\"parents/\", parents, name=\"parents\"),\n path(\"pdf/\", pdf_export, name=\"pdf_export\"),\n path(\n \"sent_push_notifications/\",\n sent_push_notifications,\n name=\"sent_push_notifications\",\n ),\n path(\"imprint/\", imprint, name=\"imprint\"),\n path(\"disclaimer/\", imprint, name=\"imprint\"),\n path(\"offers/\", offers, name=\"offers\"),\n path(\"extras/\", offers, name=\"offers\"),\n re_path(\n r\"^feedback/?$\",\n legacy_feedback_endpoint.legacy_feedback_endpoint,\n name=\"legacy_feedback_endpoint\",\n ),\n path(\n \"feedback/\",\n include(\n [\n re_path(\n r\"^categories/?$\",\n region_feedback.region_feedback,\n name=\"region_feedback\",\n ),\n re_path(r\"^page/?$\", page_feedback.page_feedback, name=\"page_feedback\"),\n re_path(r\"^poi/?$\", poi_feedback.poi_feedback, name=\"poi_feedback\"),\n re_path(\n r\"^event/?$\", event_feedback.event_feedback, name=\"event_feedback\"\n ),\n re_path(\n r\"^events/?$\",\n event_list_feedback.event_list_feedback,\n name=\"event_list_feedback\",\n ),\n re_path(\n r\"^imprint-page/?$\",\n imprint_page_feedback.imprint_page_feedback,\n name=\"imprint_page_feedbacks\",\n ),\n re_path(r\"^map/?$\", map_feedback.map_feedback, name=\"map_feedback\"),\n re_path(\n r\"^search/?$\",\n search_result_feedback.search_result_feedback,\n name=\"search_result_feedback\",\n ),\n re_path(\n r\"^offers/?$\",\n offer_list_feedback.offer_list_feedback,\n name=\"offer_list_feedback\",\n ),\n re_path(\n r\"^extras/?$\",\n offer_list_feedback.offer_list_feedback,\n name=\"offer_list_feedback\",\n ),\n re_path(\n r\"^offer/?$\", offer_feedback.offer_feedback, name=\"offer_feedback\"\n ),\n re_path(\n r\"^extra/?$\", offer_feedback.offer_feedback, name=\"offer_feedback\"\n ),\n ]\n ),\n ),\n]\n\nregion_api_urlpatterns = [\n path(\"\", regions, name=\"regions\"),\n path(\"live/\", liveregions, name=\"regions_live\"),\n path(\"hidden/\", hiddenregions, name=\"regions_hidden\"),\n]\n\n#: The url patterns of this module (see :doc:`topics/http/urls`)\nurlpatterns = [\n path(\"api/regions/\", include(region_api_urlpatterns)),\n path(\"wp-json/extensions/v3/sites/\", include(region_api_urlpatterns)),\n path(\n \"api/<slug:region_slug>/\",\n include(\n [\n path(\"languages/\", languages, name=\"languages\"),\n path(\"offers/\", offers, name=\"offers\"),\n path(\"extras/\", offers, name=\"offers\"),\n path(\"<slug:language_slug>/\", include(content_api_urlpatterns)),\n ]\n ),\n ),\n path(\n \"<slug:region_slug>/\",\n include(\n [\n path(\n \"de/wp-json/extensions/v3/languages/\", languages, name=\"languages\"\n ),\n path(\n \"<slug:language_slug>/wp-json/extensions/v3/\",\n include(content_api_urlpatterns),\n ),\n path(\n \"<slug:language_slug>/wp-json/ig-mpdf/v1/pdf/\",\n pdf_export,\n name=\"pdf_export\",\n ),\n ]\n ),\n ),\n]\n", "path": "integreat_cms/api/urls.py"}]} | 1,656 | 129 |
gh_patches_debug_29434 | rasdani/github-patches | git_diff | plone__Products.CMFPlone-1515 | We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Resources from third party add-ons are not being included in compiled plone-legacy bundle
Seems JS resources registered in Plone 5 using old approach (`jsregistry.xml`) are not included in the final compilation: I installed an add-on and, even as I can see the JS resources listed in `default.js`, the source code is not present.
If I enable development mode, then I can see the source code included in `plone-legacy-compiled.js` and it's executed normally.
--- END ISSUE ---
Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `Products/CMFPlone/resources/browser/combine.py`
Content:
```
1 from zExceptions import NotFound
2 from Acquisition import aq_base
3 from datetime import datetime
4 from plone.registry.interfaces import IRegistry
5 from plone.resource.file import FilesystemFile
6 from plone.resource.interfaces import IResourceDirectory
7 from Products.CMFPlone.interfaces import IBundleRegistry
8 from Products.CMFPlone.interfaces.resources import (
9 OVERRIDE_RESOURCE_DIRECTORY_NAME,
10 )
11 from StringIO import StringIO
12 from zope.component import getUtility
13 from zope.component import queryUtility
14
15 PRODUCTION_RESOURCE_DIRECTORY = "production"
16
17
18 def get_production_resource_directory():
19 persistent_directory = queryUtility(IResourceDirectory, name="persistent")
20 if persistent_directory is None:
21 return ''
22 container = persistent_directory[OVERRIDE_RESOURCE_DIRECTORY_NAME]
23 try:
24 production_folder = container[PRODUCTION_RESOURCE_DIRECTORY]
25 except NotFound:
26 return "%s/++unique++1" % PRODUCTION_RESOURCE_DIRECTORY
27 timestamp = production_folder.readFile('timestamp.txt')
28 return "%s/++unique++%s" % (
29 PRODUCTION_RESOURCE_DIRECTORY, timestamp)
30
31
32 def get_resource(context, path):
33 resource = context.unrestrictedTraverse(path)
34 if isinstance(resource, FilesystemFile):
35 (directory, sep, filename) = path.rpartition('/')
36 return context.unrestrictedTraverse(directory).readFile(filename)
37 else:
38 if hasattr(aq_base(resource), 'GET'):
39 # for FileResource
40 return resource.GET()
41 else:
42 # any BrowserView
43 return resource()
44
45
46 def write_js(context, folder, meta_bundle):
47 registry = getUtility(IRegistry)
48 resources = []
49
50 # default resources
51 if meta_bundle == 'default' and registry.records.get(
52 'plone.resources/jquery.js'
53 ):
54 resources.append(get_resource(context,
55 registry.records['plone.resources/jquery.js'].value))
56 resources.append(get_resource(context,
57 registry.records['plone.resources.requirejs'].value))
58 resources.append(get_resource(context,
59 registry.records['plone.resources.configjs'].value))
60
61 # bundles
62 bundles = registry.collectionOfInterface(
63 IBundleRegistry, prefix="plone.bundles", check=False)
64 for bundle in bundles.values():
65 if bundle.merge_with == meta_bundle:
66 resources.append(get_resource(context, bundle.jscompilation))
67
68 fi = StringIO()
69 for script in resources:
70 fi.write(script + '\n')
71 folder.writeFile(meta_bundle + ".js", fi)
72
73
74 def write_css(context, folder, meta_bundle):
75 registry = getUtility(IRegistry)
76 resources = []
77
78 bundles = registry.collectionOfInterface(
79 IBundleRegistry, prefix="plone.bundles", check=False)
80 for bundle in bundles.values():
81 if bundle.merge_with == meta_bundle:
82 resources.append(get_resource(context, bundle.csscompilation))
83
84 fi = StringIO()
85 for script in resources:
86 fi.write(script + '\n')
87 folder.writeFile(meta_bundle + ".css", fi)
88
89
90 def combine_bundles(context):
91 persistent_directory = queryUtility(IResourceDirectory, name="persistent")
92 if persistent_directory is None:
93 return
94 if OVERRIDE_RESOURCE_DIRECTORY_NAME not in persistent_directory:
95 persistent_directory.makeDirectory(OVERRIDE_RESOURCE_DIRECTORY_NAME)
96 container = persistent_directory[OVERRIDE_RESOURCE_DIRECTORY_NAME]
97 if PRODUCTION_RESOURCE_DIRECTORY not in container:
98 container.makeDirectory(PRODUCTION_RESOURCE_DIRECTORY)
99 production_folder = container[PRODUCTION_RESOURCE_DIRECTORY]
100
101 # store timestamp
102 fi = StringIO()
103 fi.write(datetime.now().isoformat())
104 production_folder.writeFile("timestamp.txt", fi)
105
106 # generate new combined bundles
107 write_js(context, production_folder, 'default')
108 write_js(context, production_folder, 'logged-in')
109 write_css(context, production_folder, 'default')
110 write_css(context, production_folder, 'logged-in')
111
```
--- END FILES ---
Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.
Here is an example:
```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
if __name__ == "__main__":
- asyncio.run(run_async_server("."), debug=True)
+ asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
if __name__ == "__main__":
- server = run_sync_server(".")
+ server = run_sync_server()
server.shutdown()
```
| diff --git a/Products/CMFPlone/resources/browser/combine.py b/Products/CMFPlone/resources/browser/combine.py
--- a/Products/CMFPlone/resources/browser/combine.py
+++ b/Products/CMFPlone/resources/browser/combine.py
@@ -30,6 +30,14 @@
def get_resource(context, path):
+ if path.startswith('++plone++'):
+ # ++plone++ resources can be customized, we return their override
+ # value if any
+ overrides = get_override_directory(context)
+ filepath = path[9:]
+ if overrides.isFile(filepath):
+ return overrides.readFile(filepath)
+
resource = context.unrestrictedTraverse(path)
if isinstance(resource, FilesystemFile):
(directory, sep, filename) = path.rpartition('/')
@@ -87,13 +95,17 @@
folder.writeFile(meta_bundle + ".css", fi)
-def combine_bundles(context):
+def get_override_directory(context):
persistent_directory = queryUtility(IResourceDirectory, name="persistent")
if persistent_directory is None:
return
if OVERRIDE_RESOURCE_DIRECTORY_NAME not in persistent_directory:
persistent_directory.makeDirectory(OVERRIDE_RESOURCE_DIRECTORY_NAME)
- container = persistent_directory[OVERRIDE_RESOURCE_DIRECTORY_NAME]
+ return persistent_directory[OVERRIDE_RESOURCE_DIRECTORY_NAME]
+
+
+def combine_bundles(context):
+ container = get_override_directory(context)
if PRODUCTION_RESOURCE_DIRECTORY not in container:
container.makeDirectory(PRODUCTION_RESOURCE_DIRECTORY)
production_folder = container[PRODUCTION_RESOURCE_DIRECTORY]
| {"golden_diff": "diff --git a/Products/CMFPlone/resources/browser/combine.py b/Products/CMFPlone/resources/browser/combine.py\n--- a/Products/CMFPlone/resources/browser/combine.py\n+++ b/Products/CMFPlone/resources/browser/combine.py\n@@ -30,6 +30,14 @@\n \n \n def get_resource(context, path):\n+ if path.startswith('++plone++'):\n+ # ++plone++ resources can be customized, we return their override\n+ # value if any\n+ overrides = get_override_directory(context)\n+ filepath = path[9:]\n+ if overrides.isFile(filepath):\n+ return overrides.readFile(filepath)\n+\n resource = context.unrestrictedTraverse(path)\n if isinstance(resource, FilesystemFile):\n (directory, sep, filename) = path.rpartition('/')\n@@ -87,13 +95,17 @@\n folder.writeFile(meta_bundle + \".css\", fi)\n \n \n-def combine_bundles(context):\n+def get_override_directory(context):\n persistent_directory = queryUtility(IResourceDirectory, name=\"persistent\")\n if persistent_directory is None:\n return\n if OVERRIDE_RESOURCE_DIRECTORY_NAME not in persistent_directory:\n persistent_directory.makeDirectory(OVERRIDE_RESOURCE_DIRECTORY_NAME)\n- container = persistent_directory[OVERRIDE_RESOURCE_DIRECTORY_NAME]\n+ return persistent_directory[OVERRIDE_RESOURCE_DIRECTORY_NAME]\n+\n+\n+def combine_bundles(context):\n+ container = get_override_directory(context)\n if PRODUCTION_RESOURCE_DIRECTORY not in container:\n container.makeDirectory(PRODUCTION_RESOURCE_DIRECTORY)\n production_folder = container[PRODUCTION_RESOURCE_DIRECTORY]\n", "issue": "Resources from third party add-ons are not being included in compiled plone-legacy bundle\nSeems JS resources registered in Plone 5 using old approach (`jsregistry.xml`) are not included in the final compilation: I installed an add-on and, even as I can see the JS resources listed in `default.js`, the source code is not present.\n\nIf I enable development mode, then I can see the source code included in `plone-legacy-compiled.js` and it's executed normally.\n\n", "before_files": [{"content": "from zExceptions import NotFound\nfrom Acquisition import aq_base\nfrom datetime import datetime\nfrom plone.registry.interfaces import IRegistry\nfrom plone.resource.file import FilesystemFile\nfrom plone.resource.interfaces import IResourceDirectory\nfrom Products.CMFPlone.interfaces import IBundleRegistry\nfrom Products.CMFPlone.interfaces.resources import (\n OVERRIDE_RESOURCE_DIRECTORY_NAME,\n)\nfrom StringIO import StringIO\nfrom zope.component import getUtility\nfrom zope.component import queryUtility\n\nPRODUCTION_RESOURCE_DIRECTORY = \"production\"\n\n\ndef get_production_resource_directory():\n persistent_directory = queryUtility(IResourceDirectory, name=\"persistent\")\n if persistent_directory is None:\n return ''\n container = persistent_directory[OVERRIDE_RESOURCE_DIRECTORY_NAME]\n try:\n production_folder = container[PRODUCTION_RESOURCE_DIRECTORY]\n except NotFound:\n return \"%s/++unique++1\" % PRODUCTION_RESOURCE_DIRECTORY\n timestamp = production_folder.readFile('timestamp.txt')\n return \"%s/++unique++%s\" % (\n PRODUCTION_RESOURCE_DIRECTORY, timestamp)\n\n\ndef get_resource(context, path):\n resource = context.unrestrictedTraverse(path)\n if isinstance(resource, FilesystemFile):\n (directory, sep, filename) = path.rpartition('/')\n return context.unrestrictedTraverse(directory).readFile(filename)\n else:\n if hasattr(aq_base(resource), 'GET'):\n # for FileResource\n return resource.GET()\n else:\n # any BrowserView\n return resource()\n\n\ndef write_js(context, folder, meta_bundle):\n registry = getUtility(IRegistry)\n resources = []\n\n # default resources\n if meta_bundle == 'default' and registry.records.get(\n 'plone.resources/jquery.js'\n ):\n resources.append(get_resource(context,\n registry.records['plone.resources/jquery.js'].value))\n resources.append(get_resource(context,\n registry.records['plone.resources.requirejs'].value))\n resources.append(get_resource(context,\n registry.records['plone.resources.configjs'].value))\n\n # bundles\n bundles = registry.collectionOfInterface(\n IBundleRegistry, prefix=\"plone.bundles\", check=False)\n for bundle in bundles.values():\n if bundle.merge_with == meta_bundle:\n resources.append(get_resource(context, bundle.jscompilation))\n\n fi = StringIO()\n for script in resources:\n fi.write(script + '\\n')\n folder.writeFile(meta_bundle + \".js\", fi)\n\n\ndef write_css(context, folder, meta_bundle):\n registry = getUtility(IRegistry)\n resources = []\n\n bundles = registry.collectionOfInterface(\n IBundleRegistry, prefix=\"plone.bundles\", check=False)\n for bundle in bundles.values():\n if bundle.merge_with == meta_bundle:\n resources.append(get_resource(context, bundle.csscompilation))\n\n fi = StringIO()\n for script in resources:\n fi.write(script + '\\n')\n folder.writeFile(meta_bundle + \".css\", fi)\n\n\ndef combine_bundles(context):\n persistent_directory = queryUtility(IResourceDirectory, name=\"persistent\")\n if persistent_directory is None:\n return\n if OVERRIDE_RESOURCE_DIRECTORY_NAME not in persistent_directory:\n persistent_directory.makeDirectory(OVERRIDE_RESOURCE_DIRECTORY_NAME)\n container = persistent_directory[OVERRIDE_RESOURCE_DIRECTORY_NAME]\n if PRODUCTION_RESOURCE_DIRECTORY not in container:\n container.makeDirectory(PRODUCTION_RESOURCE_DIRECTORY)\n production_folder = container[PRODUCTION_RESOURCE_DIRECTORY]\n\n # store timestamp\n fi = StringIO()\n fi.write(datetime.now().isoformat())\n production_folder.writeFile(\"timestamp.txt\", fi)\n\n # generate new combined bundles\n write_js(context, production_folder, 'default')\n write_js(context, production_folder, 'logged-in')\n write_css(context, production_folder, 'default')\n write_css(context, production_folder, 'logged-in')\n", "path": "Products/CMFPlone/resources/browser/combine.py"}], "after_files": [{"content": "from zExceptions import NotFound\nfrom Acquisition import aq_base\nfrom datetime import datetime\nfrom plone.registry.interfaces import IRegistry\nfrom plone.resource.file import FilesystemFile\nfrom plone.resource.interfaces import IResourceDirectory\nfrom Products.CMFPlone.interfaces import IBundleRegistry\nfrom Products.CMFPlone.interfaces.resources import (\n OVERRIDE_RESOURCE_DIRECTORY_NAME,\n)\nfrom StringIO import StringIO\nfrom zope.component import getUtility\nfrom zope.component import queryUtility\n\nPRODUCTION_RESOURCE_DIRECTORY = \"production\"\n\n\ndef get_production_resource_directory():\n persistent_directory = queryUtility(IResourceDirectory, name=\"persistent\")\n if persistent_directory is None:\n return ''\n container = persistent_directory[OVERRIDE_RESOURCE_DIRECTORY_NAME]\n try:\n production_folder = container[PRODUCTION_RESOURCE_DIRECTORY]\n except NotFound:\n return \"%s/++unique++1\" % PRODUCTION_RESOURCE_DIRECTORY\n timestamp = production_folder.readFile('timestamp.txt')\n return \"%s/++unique++%s\" % (\n PRODUCTION_RESOURCE_DIRECTORY, timestamp)\n\n\ndef get_resource(context, path):\n if path.startswith('++plone++'):\n # ++plone++ resources can be customized, we return their override\n # value if any\n overrides = get_override_directory(context)\n filepath = path[9:]\n if overrides.isFile(filepath):\n return overrides.readFile(filepath)\n\n resource = context.unrestrictedTraverse(path)\n if isinstance(resource, FilesystemFile):\n (directory, sep, filename) = path.rpartition('/')\n return context.unrestrictedTraverse(directory).readFile(filename)\n else:\n if hasattr(aq_base(resource), 'GET'):\n # for FileResource\n return resource.GET()\n else:\n # any BrowserView\n return resource()\n\n\ndef write_js(context, folder, meta_bundle):\n registry = getUtility(IRegistry)\n resources = []\n\n # default resources\n if meta_bundle == 'default' and registry.records.get(\n 'plone.resources/jquery.js'\n ):\n resources.append(get_resource(context,\n registry.records['plone.resources/jquery.js'].value))\n resources.append(get_resource(context,\n registry.records['plone.resources.requirejs'].value))\n resources.append(get_resource(context,\n registry.records['plone.resources.configjs'].value))\n\n # bundles\n bundles = registry.collectionOfInterface(\n IBundleRegistry, prefix=\"plone.bundles\", check=False)\n for bundle in bundles.values():\n if bundle.merge_with == meta_bundle:\n resources.append(get_resource(context, bundle.jscompilation))\n\n fi = StringIO()\n for script in resources:\n fi.write(script + '\\n')\n folder.writeFile(meta_bundle + \".js\", fi)\n\n\ndef write_css(context, folder, meta_bundle):\n registry = getUtility(IRegistry)\n resources = []\n\n bundles = registry.collectionOfInterface(\n IBundleRegistry, prefix=\"plone.bundles\", check=False)\n for bundle in bundles.values():\n if bundle.merge_with == meta_bundle:\n resources.append(get_resource(context, bundle.csscompilation))\n\n fi = StringIO()\n for script in resources:\n fi.write(script + '\\n')\n folder.writeFile(meta_bundle + \".css\", fi)\n\n\ndef get_override_directory(context):\n persistent_directory = queryUtility(IResourceDirectory, name=\"persistent\")\n if persistent_directory is None:\n return\n if OVERRIDE_RESOURCE_DIRECTORY_NAME not in persistent_directory:\n persistent_directory.makeDirectory(OVERRIDE_RESOURCE_DIRECTORY_NAME)\n return persistent_directory[OVERRIDE_RESOURCE_DIRECTORY_NAME]\n\n\ndef combine_bundles(context):\n container = get_override_directory(context)\n if PRODUCTION_RESOURCE_DIRECTORY not in container:\n container.makeDirectory(PRODUCTION_RESOURCE_DIRECTORY)\n production_folder = container[PRODUCTION_RESOURCE_DIRECTORY]\n\n # store timestamp\n fi = StringIO()\n fi.write(datetime.now().isoformat())\n production_folder.writeFile(\"timestamp.txt\", fi)\n\n # generate new combined bundles\n write_js(context, production_folder, 'default')\n write_js(context, production_folder, 'logged-in')\n write_css(context, production_folder, 'default')\n write_css(context, production_folder, 'logged-in')\n", "path": "Products/CMFPlone/resources/browser/combine.py"}]} | 1,383 | 338 |
gh_patches_debug_22011 | rasdani/github-patches | git_diff | docker__docker-py-1330 | We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Add docker network IPAM options parameter
IPAM driver missing options
supports an options field in the IPAM config
It introduced in API v1.22.
```
POST /networks/create Now supports an options field in the IPAM config that provides options for custom IPAM plugins.
```
--- END ISSUE ---
Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `docker/types/networks.py`
Content:
```
1 from .. import errors
2 from ..utils import normalize_links, version_lt
3
4
5 class EndpointConfig(dict):
6 def __init__(self, version, aliases=None, links=None, ipv4_address=None,
7 ipv6_address=None, link_local_ips=None):
8 if version_lt(version, '1.22'):
9 raise errors.InvalidVersion(
10 'Endpoint config is not supported for API version < 1.22'
11 )
12
13 if aliases:
14 self["Aliases"] = aliases
15
16 if links:
17 self["Links"] = normalize_links(links)
18
19 ipam_config = {}
20 if ipv4_address:
21 ipam_config['IPv4Address'] = ipv4_address
22
23 if ipv6_address:
24 ipam_config['IPv6Address'] = ipv6_address
25
26 if link_local_ips is not None:
27 if version_lt(version, '1.24'):
28 raise errors.InvalidVersion(
29 'link_local_ips is not supported for API version < 1.24'
30 )
31 ipam_config['LinkLocalIPs'] = link_local_ips
32
33 if ipam_config:
34 self['IPAMConfig'] = ipam_config
35
36
37 class NetworkingConfig(dict):
38 def __init__(self, endpoints_config=None):
39 if endpoints_config:
40 self["EndpointsConfig"] = endpoints_config
41
42
43 class IPAMConfig(dict):
44 """
45 Create an IPAM (IP Address Management) config dictionary to be used with
46 :py:meth:`~docker.api.network.NetworkApiMixin.create_network`.
47
48 Args:
49
50 driver (str): The IPAM driver to use. Defaults to ``default``.
51 pool_configs (list): A list of pool configurations
52 (:py:class:`~docker.types.IPAMPool`). Defaults to empty list.
53
54 Example:
55
56 >>> ipam_config = docker.types.IPAMConfig(driver='default')
57 >>> network = client.create_network('network1', ipam=ipam_config)
58
59 """
60 def __init__(self, driver='default', pool_configs=None):
61 self.update({
62 'Driver': driver,
63 'Config': pool_configs or []
64 })
65
66
67 class IPAMPool(dict):
68 """
69 Create an IPAM pool config dictionary to be added to the
70 ``pool_configs`` parameter of
71 :py:class:`~docker.types.IPAMConfig`.
72
73 Args:
74
75 subnet (str): Custom subnet for this IPAM pool using the CIDR
76 notation. Defaults to ``None``.
77 iprange (str): Custom IP range for endpoints in this IPAM pool using
78 the CIDR notation. Defaults to ``None``.
79 gateway (str): Custom IP address for the pool's gateway.
80 aux_addresses (dict): A dictionary of ``key -> ip_address``
81 relationships specifying auxiliary addresses that need to be
82 allocated by the IPAM driver.
83
84 Example:
85
86 >>> ipam_pool = docker.types.IPAMPool(
87 subnet='124.42.0.0/16',
88 iprange='124.42.0.0/24',
89 gateway='124.42.0.254',
90 aux_addresses={
91 'reserved1': '124.42.1.1'
92 }
93 )
94 >>> ipam_config = docker.types.IPAMConfig(
95 pool_configs=[ipam_pool])
96 """
97 def __init__(self, subnet=None, iprange=None, gateway=None,
98 aux_addresses=None):
99 self.update({
100 'Subnet': subnet,
101 'IPRange': iprange,
102 'Gateway': gateway,
103 'AuxiliaryAddresses': aux_addresses
104 })
105
```
--- END FILES ---
Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.
Here is an example:
```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
if __name__ == "__main__":
- asyncio.run(run_async_server("."), debug=True)
+ asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
if __name__ == "__main__":
- server = run_sync_server(".")
+ server = run_sync_server()
server.shutdown()
```
| diff --git a/docker/types/networks.py b/docker/types/networks.py
--- a/docker/types/networks.py
+++ b/docker/types/networks.py
@@ -50,6 +50,8 @@
driver (str): The IPAM driver to use. Defaults to ``default``.
pool_configs (list): A list of pool configurations
(:py:class:`~docker.types.IPAMPool`). Defaults to empty list.
+ options (dict): Driver options as a key-value dictionary.
+ Defaults to `None`.
Example:
@@ -57,12 +59,17 @@
>>> network = client.create_network('network1', ipam=ipam_config)
"""
- def __init__(self, driver='default', pool_configs=None):
+ def __init__(self, driver='default', pool_configs=None, options=None):
self.update({
'Driver': driver,
'Config': pool_configs or []
})
+ if options:
+ if not isinstance(options, dict):
+ raise TypeError('IPAMConfig options must be a dictionary')
+ self['Options'] = options
+
class IPAMPool(dict):
"""
| {"golden_diff": "diff --git a/docker/types/networks.py b/docker/types/networks.py\n--- a/docker/types/networks.py\n+++ b/docker/types/networks.py\n@@ -50,6 +50,8 @@\n driver (str): The IPAM driver to use. Defaults to ``default``.\n pool_configs (list): A list of pool configurations\n (:py:class:`~docker.types.IPAMPool`). Defaults to empty list.\n+ options (dict): Driver options as a key-value dictionary.\n+ Defaults to `None`.\n \n Example:\n \n@@ -57,12 +59,17 @@\n >>> network = client.create_network('network1', ipam=ipam_config)\n \n \"\"\"\n- def __init__(self, driver='default', pool_configs=None):\n+ def __init__(self, driver='default', pool_configs=None, options=None):\n self.update({\n 'Driver': driver,\n 'Config': pool_configs or []\n })\n \n+ if options:\n+ if not isinstance(options, dict):\n+ raise TypeError('IPAMConfig options must be a dictionary')\n+ self['Options'] = options\n+\n \n class IPAMPool(dict):\n \"\"\"\n", "issue": "Add docker network IPAM options parameter\nIPAM driver missing options\n\nsupports an options field in the IPAM config \nIt introduced in API v1.22.\n\n```\nPOST /networks/create Now supports an options field in the IPAM config that provides options for custom IPAM plugins.\n```\n\n", "before_files": [{"content": "from .. import errors\nfrom ..utils import normalize_links, version_lt\n\n\nclass EndpointConfig(dict):\n def __init__(self, version, aliases=None, links=None, ipv4_address=None,\n ipv6_address=None, link_local_ips=None):\n if version_lt(version, '1.22'):\n raise errors.InvalidVersion(\n 'Endpoint config is not supported for API version < 1.22'\n )\n\n if aliases:\n self[\"Aliases\"] = aliases\n\n if links:\n self[\"Links\"] = normalize_links(links)\n\n ipam_config = {}\n if ipv4_address:\n ipam_config['IPv4Address'] = ipv4_address\n\n if ipv6_address:\n ipam_config['IPv6Address'] = ipv6_address\n\n if link_local_ips is not None:\n if version_lt(version, '1.24'):\n raise errors.InvalidVersion(\n 'link_local_ips is not supported for API version < 1.24'\n )\n ipam_config['LinkLocalIPs'] = link_local_ips\n\n if ipam_config:\n self['IPAMConfig'] = ipam_config\n\n\nclass NetworkingConfig(dict):\n def __init__(self, endpoints_config=None):\n if endpoints_config:\n self[\"EndpointsConfig\"] = endpoints_config\n\n\nclass IPAMConfig(dict):\n \"\"\"\n Create an IPAM (IP Address Management) config dictionary to be used with\n :py:meth:`~docker.api.network.NetworkApiMixin.create_network`.\n\n Args:\n\n driver (str): The IPAM driver to use. Defaults to ``default``.\n pool_configs (list): A list of pool configurations\n (:py:class:`~docker.types.IPAMPool`). Defaults to empty list.\n\n Example:\n\n >>> ipam_config = docker.types.IPAMConfig(driver='default')\n >>> network = client.create_network('network1', ipam=ipam_config)\n\n \"\"\"\n def __init__(self, driver='default', pool_configs=None):\n self.update({\n 'Driver': driver,\n 'Config': pool_configs or []\n })\n\n\nclass IPAMPool(dict):\n \"\"\"\n Create an IPAM pool config dictionary to be added to the\n ``pool_configs`` parameter of\n :py:class:`~docker.types.IPAMConfig`.\n\n Args:\n\n subnet (str): Custom subnet for this IPAM pool using the CIDR\n notation. Defaults to ``None``.\n iprange (str): Custom IP range for endpoints in this IPAM pool using\n the CIDR notation. Defaults to ``None``.\n gateway (str): Custom IP address for the pool's gateway.\n aux_addresses (dict): A dictionary of ``key -> ip_address``\n relationships specifying auxiliary addresses that need to be\n allocated by the IPAM driver.\n\n Example:\n\n >>> ipam_pool = docker.types.IPAMPool(\n subnet='124.42.0.0/16',\n iprange='124.42.0.0/24',\n gateway='124.42.0.254',\n aux_addresses={\n 'reserved1': '124.42.1.1'\n }\n )\n >>> ipam_config = docker.types.IPAMConfig(\n pool_configs=[ipam_pool])\n \"\"\"\n def __init__(self, subnet=None, iprange=None, gateway=None,\n aux_addresses=None):\n self.update({\n 'Subnet': subnet,\n 'IPRange': iprange,\n 'Gateway': gateway,\n 'AuxiliaryAddresses': aux_addresses\n })\n", "path": "docker/types/networks.py"}], "after_files": [{"content": "from .. import errors\nfrom ..utils import normalize_links, version_lt\n\n\nclass EndpointConfig(dict):\n def __init__(self, version, aliases=None, links=None, ipv4_address=None,\n ipv6_address=None, link_local_ips=None):\n if version_lt(version, '1.22'):\n raise errors.InvalidVersion(\n 'Endpoint config is not supported for API version < 1.22'\n )\n\n if aliases:\n self[\"Aliases\"] = aliases\n\n if links:\n self[\"Links\"] = normalize_links(links)\n\n ipam_config = {}\n if ipv4_address:\n ipam_config['IPv4Address'] = ipv4_address\n\n if ipv6_address:\n ipam_config['IPv6Address'] = ipv6_address\n\n if link_local_ips is not None:\n if version_lt(version, '1.24'):\n raise errors.InvalidVersion(\n 'link_local_ips is not supported for API version < 1.24'\n )\n ipam_config['LinkLocalIPs'] = link_local_ips\n\n if ipam_config:\n self['IPAMConfig'] = ipam_config\n\n\nclass NetworkingConfig(dict):\n def __init__(self, endpoints_config=None):\n if endpoints_config:\n self[\"EndpointsConfig\"] = endpoints_config\n\n\nclass IPAMConfig(dict):\n \"\"\"\n Create an IPAM (IP Address Management) config dictionary to be used with\n :py:meth:`~docker.api.network.NetworkApiMixin.create_network`.\n\n Args:\n\n driver (str): The IPAM driver to use. Defaults to ``default``.\n pool_configs (list): A list of pool configurations\n (:py:class:`~docker.types.IPAMPool`). Defaults to empty list.\n options (dict): Driver options as a key-value dictionary.\n Defaults to `None`.\n\n Example:\n\n >>> ipam_config = docker.types.IPAMConfig(driver='default')\n >>> network = client.create_network('network1', ipam=ipam_config)\n\n \"\"\"\n def __init__(self, driver='default', pool_configs=None, options=None):\n self.update({\n 'Driver': driver,\n 'Config': pool_configs or []\n })\n\n if options:\n if not isinstance(options, dict):\n raise TypeError('IPAMConfig options must be a dictionary')\n self['Options'] = options\n\n\nclass IPAMPool(dict):\n \"\"\"\n Create an IPAM pool config dictionary to be added to the\n ``pool_configs`` parameter of\n :py:class:`~docker.types.IPAMConfig`.\n\n Args:\n\n subnet (str): Custom subnet for this IPAM pool using the CIDR\n notation. Defaults to ``None``.\n iprange (str): Custom IP range for endpoints in this IPAM pool using\n the CIDR notation. Defaults to ``None``.\n gateway (str): Custom IP address for the pool's gateway.\n aux_addresses (dict): A dictionary of ``key -> ip_address``\n relationships specifying auxiliary addresses that need to be\n allocated by the IPAM driver.\n\n Example:\n\n >>> ipam_pool = docker.types.IPAMPool(\n subnet='124.42.0.0/16',\n iprange='124.42.0.0/24',\n gateway='124.42.0.254',\n aux_addresses={\n 'reserved1': '124.42.1.1'\n }\n )\n >>> ipam_config = docker.types.IPAMConfig(\n pool_configs=[ipam_pool])\n \"\"\"\n def __init__(self, subnet=None, iprange=None, gateway=None,\n aux_addresses=None):\n self.update({\n 'Subnet': subnet,\n 'IPRange': iprange,\n 'Gateway': gateway,\n 'AuxiliaryAddresses': aux_addresses\n })\n", "path": "docker/types/networks.py"}]} | 1,302 | 254 |
gh_patches_debug_2452 | rasdani/github-patches | git_diff | pyinstaller__pyinstaller-2225 | We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
missing hidden import for skimage
When packaging an application that imports skimage.feature (and nothing else), the app would not run due to an ImportError on the "transform" module. This can be fixed by adding one item to the hiddenimports in hook-skimage.transform.py file (bolded below):
> hiddenimports = ['skimage.draw.draw',
> 'skimage._shared.geometry',
> 'skimage.filters.rank.core_cy',
> **'skimage._shared.transform'**]
>
> datas = collect_data_files('skimage')
PyInstaller 3.2, Windows 7 64 bit, Python 2.7.12, Anaconda 4.1.1 distribution.
--- END ISSUE ---
Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `PyInstaller/hooks/hook-skimage.transform.py`
Content:
```
1 #-----------------------------------------------------------------------------
2 # Copyright (c) 2014-2016, PyInstaller Development Team.
3 #
4 # Distributed under the terms of the GNU General Public License with exception
5 # for distributing bootloader.
6 #
7 # The full license is in the file COPYING.txt, distributed with this software.
8 #-----------------------------------------------------------------------------
9 from PyInstaller.utils.hooks import collect_data_files
10
11 # Hook tested with scikit-image (skimage) 0.9.3 on Mac OS 10.9 and Windows 7
12 # 64-bit
13 hiddenimports = ['skimage.draw.draw',
14 'skimage._shared.geometry',
15 'skimage.filters.rank.core_cy']
16
17 datas = collect_data_files('skimage')
18
```
--- END FILES ---
Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.
Here is an example:
```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
if __name__ == "__main__":
- asyncio.run(run_async_server("."), debug=True)
+ asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
if __name__ == "__main__":
- server = run_sync_server(".")
+ server = run_sync_server()
server.shutdown()
```
| diff --git a/PyInstaller/hooks/hook-skimage.transform.py b/PyInstaller/hooks/hook-skimage.transform.py
--- a/PyInstaller/hooks/hook-skimage.transform.py
+++ b/PyInstaller/hooks/hook-skimage.transform.py
@@ -12,6 +12,7 @@
# 64-bit
hiddenimports = ['skimage.draw.draw',
'skimage._shared.geometry',
+ 'skimage._shared.transform',
'skimage.filters.rank.core_cy']
datas = collect_data_files('skimage')
| {"golden_diff": "diff --git a/PyInstaller/hooks/hook-skimage.transform.py b/PyInstaller/hooks/hook-skimage.transform.py\n--- a/PyInstaller/hooks/hook-skimage.transform.py\n+++ b/PyInstaller/hooks/hook-skimage.transform.py\n@@ -12,6 +12,7 @@\n # 64-bit\n hiddenimports = ['skimage.draw.draw',\n 'skimage._shared.geometry',\n+ 'skimage._shared.transform',\n 'skimage.filters.rank.core_cy']\n \n datas = collect_data_files('skimage')\n", "issue": "missing hidden import for skimage\nWhen packaging an application that imports skimage.feature (and nothing else), the app would not run due to an ImportError on the \"transform\" module. This can be fixed by adding one item to the hiddenimports in hook-skimage.transform.py file (bolded below):\n\n> hiddenimports = ['skimage.draw.draw',\n> 'skimage._shared.geometry',\n> 'skimage.filters.rank.core_cy',\n> **'skimage._shared.transform'**] \n> \n> datas = collect_data_files('skimage')\n\nPyInstaller 3.2, Windows 7 64 bit, Python 2.7.12, Anaconda 4.1.1 distribution.\n\n", "before_files": [{"content": "#-----------------------------------------------------------------------------\n# Copyright (c) 2014-2016, PyInstaller Development Team.\n#\n# Distributed under the terms of the GNU General Public License with exception\n# for distributing bootloader.\n#\n# The full license is in the file COPYING.txt, distributed with this software.\n#-----------------------------------------------------------------------------\nfrom PyInstaller.utils.hooks import collect_data_files\n\n# Hook tested with scikit-image (skimage) 0.9.3 on Mac OS 10.9 and Windows 7\n# 64-bit\nhiddenimports = ['skimage.draw.draw',\n 'skimage._shared.geometry',\n 'skimage.filters.rank.core_cy']\n\ndatas = collect_data_files('skimage')\n", "path": "PyInstaller/hooks/hook-skimage.transform.py"}], "after_files": [{"content": "#-----------------------------------------------------------------------------\n# Copyright (c) 2014-2016, PyInstaller Development Team.\n#\n# Distributed under the terms of the GNU General Public License with exception\n# for distributing bootloader.\n#\n# The full license is in the file COPYING.txt, distributed with this software.\n#-----------------------------------------------------------------------------\nfrom PyInstaller.utils.hooks import collect_data_files\n\n# Hook tested with scikit-image (skimage) 0.9.3 on Mac OS 10.9 and Windows 7\n# 64-bit\nhiddenimports = ['skimage.draw.draw',\n 'skimage._shared.geometry',\n 'skimage._shared.transform',\n 'skimage.filters.rank.core_cy']\n\ndatas = collect_data_files('skimage')\n", "path": "PyInstaller/hooks/hook-skimage.transform.py"}]} | 588 | 116 |
gh_patches_debug_7034 | rasdani/github-patches | git_diff | aws__aws-cli-5019 | We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Add support for PyYAML 5.3
Closes: https://github.com/aws/aws-cli/issues/4828
Signed-off-by: Igor Raits <[email protected]>
*Issue #, if available:*
*Description of changes:*
By submitting this pull request, I confirm that you can use, modify, copy, and redistribute this contribution, under the terms of your choice.
--- END ISSUE ---
Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `setup.py`
Content:
```
1 #!/usr/bin/env python
2 import codecs
3 import os.path
4 import re
5 import sys
6
7 from setuptools import setup, find_packages
8
9
10 here = os.path.abspath(os.path.dirname(__file__))
11
12
13 def read(*parts):
14 return codecs.open(os.path.join(here, *parts), 'r').read()
15
16
17 def find_version(*file_paths):
18 version_file = read(*file_paths)
19 version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]",
20 version_file, re.M)
21 if version_match:
22 return version_match.group(1)
23 raise RuntimeError("Unable to find version string.")
24
25
26 install_requires = [
27 'botocore==1.15.10',
28 'docutils>=0.10,<0.16',
29 'rsa>=3.1.2,<=3.5.0',
30 's3transfer>=0.3.0,<0.4.0',
31 'PyYAML>=3.10,<5.3',
32 ]
33
34
35 if sys.version_info[:2] == (3, 4):
36 install_requires.append('colorama>=0.2.5,<0.4.2')
37 else:
38 install_requires.append('colorama>=0.2.5,<0.4.4')
39
40
41 setup_options = dict(
42 name='awscli',
43 version=find_version("awscli", "__init__.py"),
44 description='Universal Command Line Environment for AWS.',
45 long_description=read('README.rst'),
46 author='Amazon Web Services',
47 url='http://aws.amazon.com/cli/',
48 scripts=['bin/aws', 'bin/aws.cmd',
49 'bin/aws_completer', 'bin/aws_zsh_completer.sh',
50 'bin/aws_bash_completer'],
51 packages=find_packages(exclude=['tests*']),
52 package_data={'awscli': ['data/*.json', 'examples/*/*.rst',
53 'examples/*/*.txt', 'examples/*/*/*.txt',
54 'examples/*/*/*.rst', 'topics/*.rst',
55 'topics/*.json']},
56 install_requires=install_requires,
57 extras_require={},
58 license="Apache License 2.0",
59 classifiers=[
60 'Development Status :: 5 - Production/Stable',
61 'Intended Audience :: Developers',
62 'Intended Audience :: System Administrators',
63 'Natural Language :: English',
64 'License :: OSI Approved :: Apache Software License',
65 'Programming Language :: Python',
66 'Programming Language :: Python :: 2',
67 'Programming Language :: Python :: 2.7',
68 'Programming Language :: Python :: 3',
69 'Programming Language :: Python :: 3.4',
70 'Programming Language :: Python :: 3.5',
71 'Programming Language :: Python :: 3.6',
72 'Programming Language :: Python :: 3.7',
73 'Programming Language :: Python :: 3.8',
74 ],
75 )
76
77
78 if 'py2exe' in sys.argv:
79 # This will actually give us a py2exe command.
80 import py2exe
81 # And we have some py2exe specific options.
82 setup_options['options'] = {
83 'py2exe': {
84 'optimize': 0,
85 'skip_archive': True,
86 'dll_excludes': ['crypt32.dll'],
87 'packages': ['docutils', 'urllib', 'httplib', 'HTMLParser',
88 'awscli', 'ConfigParser', 'xml.etree', 'pipes'],
89 }
90 }
91 setup_options['console'] = ['bin/aws']
92
93
94 setup(**setup_options)
95
```
--- END FILES ---
Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.
Here is an example:
```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
if __name__ == "__main__":
- asyncio.run(run_async_server("."), debug=True)
+ asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
if __name__ == "__main__":
- server = run_sync_server(".")
+ server = run_sync_server()
server.shutdown()
```
| diff --git a/setup.py b/setup.py
--- a/setup.py
+++ b/setup.py
@@ -28,13 +28,14 @@
'docutils>=0.10,<0.16',
'rsa>=3.1.2,<=3.5.0',
's3transfer>=0.3.0,<0.4.0',
- 'PyYAML>=3.10,<5.3',
]
if sys.version_info[:2] == (3, 4):
+ install_requires.append('PyYAML>=3.10,<5.3')
install_requires.append('colorama>=0.2.5,<0.4.2')
else:
+ install_requires.append('PyYAML>=3.10,<5.4')
install_requires.append('colorama>=0.2.5,<0.4.4')
| {"golden_diff": "diff --git a/setup.py b/setup.py\n--- a/setup.py\n+++ b/setup.py\n@@ -28,13 +28,14 @@\n 'docutils>=0.10,<0.16',\n 'rsa>=3.1.2,<=3.5.0',\n 's3transfer>=0.3.0,<0.4.0',\n- 'PyYAML>=3.10,<5.3',\n ]\n \n \n if sys.version_info[:2] == (3, 4):\n+ install_requires.append('PyYAML>=3.10,<5.3')\n install_requires.append('colorama>=0.2.5,<0.4.2')\n else:\n+ install_requires.append('PyYAML>=3.10,<5.4')\n install_requires.append('colorama>=0.2.5,<0.4.4')\n", "issue": "Add support for PyYAML 5.3\nCloses: https://github.com/aws/aws-cli/issues/4828\r\nSigned-off-by: Igor Raits <[email protected]>\r\n\r\n*Issue #, if available:*\r\n\r\n*Description of changes:*\r\n\r\n\r\nBy submitting this pull request, I confirm that you can use, modify, copy, and redistribute this contribution, under the terms of your choice.\r\n\n", "before_files": [{"content": "#!/usr/bin/env python\nimport codecs\nimport os.path\nimport re\nimport sys\n\nfrom setuptools import setup, find_packages\n\n\nhere = os.path.abspath(os.path.dirname(__file__))\n\n\ndef read(*parts):\n return codecs.open(os.path.join(here, *parts), 'r').read()\n\n\ndef find_version(*file_paths):\n version_file = read(*file_paths)\n version_match = re.search(r\"^__version__ = ['\\\"]([^'\\\"]*)['\\\"]\",\n version_file, re.M)\n if version_match:\n return version_match.group(1)\n raise RuntimeError(\"Unable to find version string.\")\n\n\ninstall_requires = [\n 'botocore==1.15.10',\n 'docutils>=0.10,<0.16',\n 'rsa>=3.1.2,<=3.5.0',\n 's3transfer>=0.3.0,<0.4.0',\n 'PyYAML>=3.10,<5.3',\n]\n\n\nif sys.version_info[:2] == (3, 4):\n install_requires.append('colorama>=0.2.5,<0.4.2')\nelse:\n install_requires.append('colorama>=0.2.5,<0.4.4')\n\n\nsetup_options = dict(\n name='awscli',\n version=find_version(\"awscli\", \"__init__.py\"),\n description='Universal Command Line Environment for AWS.',\n long_description=read('README.rst'),\n author='Amazon Web Services',\n url='http://aws.amazon.com/cli/',\n scripts=['bin/aws', 'bin/aws.cmd',\n 'bin/aws_completer', 'bin/aws_zsh_completer.sh',\n 'bin/aws_bash_completer'],\n packages=find_packages(exclude=['tests*']),\n package_data={'awscli': ['data/*.json', 'examples/*/*.rst',\n 'examples/*/*.txt', 'examples/*/*/*.txt',\n 'examples/*/*/*.rst', 'topics/*.rst',\n 'topics/*.json']},\n install_requires=install_requires,\n extras_require={},\n license=\"Apache License 2.0\",\n classifiers=[\n 'Development Status :: 5 - Production/Stable',\n 'Intended Audience :: Developers',\n 'Intended Audience :: System Administrators',\n 'Natural Language :: English',\n 'License :: OSI Approved :: Apache Software License',\n 'Programming Language :: Python',\n 'Programming Language :: Python :: 2',\n 'Programming Language :: Python :: 2.7',\n 'Programming Language :: Python :: 3',\n 'Programming Language :: Python :: 3.4',\n 'Programming Language :: Python :: 3.5',\n 'Programming Language :: Python :: 3.6',\n 'Programming Language :: Python :: 3.7',\n 'Programming Language :: Python :: 3.8',\n ],\n)\n\n\nif 'py2exe' in sys.argv:\n # This will actually give us a py2exe command.\n import py2exe\n # And we have some py2exe specific options.\n setup_options['options'] = {\n 'py2exe': {\n 'optimize': 0,\n 'skip_archive': True,\n 'dll_excludes': ['crypt32.dll'],\n 'packages': ['docutils', 'urllib', 'httplib', 'HTMLParser',\n 'awscli', 'ConfigParser', 'xml.etree', 'pipes'],\n }\n }\n setup_options['console'] = ['bin/aws']\n\n\nsetup(**setup_options)\n", "path": "setup.py"}], "after_files": [{"content": "#!/usr/bin/env python\nimport codecs\nimport os.path\nimport re\nimport sys\n\nfrom setuptools import setup, find_packages\n\n\nhere = os.path.abspath(os.path.dirname(__file__))\n\n\ndef read(*parts):\n return codecs.open(os.path.join(here, *parts), 'r').read()\n\n\ndef find_version(*file_paths):\n version_file = read(*file_paths)\n version_match = re.search(r\"^__version__ = ['\\\"]([^'\\\"]*)['\\\"]\",\n version_file, re.M)\n if version_match:\n return version_match.group(1)\n raise RuntimeError(\"Unable to find version string.\")\n\n\ninstall_requires = [\n 'botocore==1.15.10',\n 'docutils>=0.10,<0.16',\n 'rsa>=3.1.2,<=3.5.0',\n 's3transfer>=0.3.0,<0.4.0',\n]\n\n\nif sys.version_info[:2] == (3, 4):\n install_requires.append('PyYAML>=3.10,<5.3')\n install_requires.append('colorama>=0.2.5,<0.4.2')\nelse:\n install_requires.append('PyYAML>=3.10,<5.4')\n install_requires.append('colorama>=0.2.5,<0.4.4')\n\n\nsetup_options = dict(\n name='awscli',\n version=find_version(\"awscli\", \"__init__.py\"),\n description='Universal Command Line Environment for AWS.',\n long_description=read('README.rst'),\n author='Amazon Web Services',\n url='http://aws.amazon.com/cli/',\n scripts=['bin/aws', 'bin/aws.cmd',\n 'bin/aws_completer', 'bin/aws_zsh_completer.sh',\n 'bin/aws_bash_completer'],\n packages=find_packages(exclude=['tests*']),\n package_data={'awscli': ['data/*.json', 'examples/*/*.rst',\n 'examples/*/*.txt', 'examples/*/*/*.txt',\n 'examples/*/*/*.rst', 'topics/*.rst',\n 'topics/*.json']},\n install_requires=install_requires,\n extras_require={},\n license=\"Apache License 2.0\",\n classifiers=[\n 'Development Status :: 5 - Production/Stable',\n 'Intended Audience :: Developers',\n 'Intended Audience :: System Administrators',\n 'Natural Language :: English',\n 'License :: OSI Approved :: Apache Software License',\n 'Programming Language :: Python',\n 'Programming Language :: Python :: 2',\n 'Programming Language :: Python :: 2.7',\n 'Programming Language :: Python :: 3',\n 'Programming Language :: Python :: 3.4',\n 'Programming Language :: Python :: 3.5',\n 'Programming Language :: Python :: 3.6',\n 'Programming Language :: Python :: 3.7',\n 'Programming Language :: Python :: 3.8',\n ],\n)\n\n\nif 'py2exe' in sys.argv:\n # This will actually give us a py2exe command.\n import py2exe\n # And we have some py2exe specific options.\n setup_options['options'] = {\n 'py2exe': {\n 'optimize': 0,\n 'skip_archive': True,\n 'dll_excludes': ['crypt32.dll'],\n 'packages': ['docutils', 'urllib', 'httplib', 'HTMLParser',\n 'awscli', 'ConfigParser', 'xml.etree', 'pipes'],\n }\n }\n setup_options['console'] = ['bin/aws']\n\n\nsetup(**setup_options)\n", "path": "setup.py"}]} | 1,288 | 196 |
gh_patches_debug_14458 | rasdani/github-patches | git_diff | kovidgoyal__kitty-5211 | We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
MacOS: Launch OS Window via Remote Control
**Describe the bug**
Ref: https://github.com/kovidgoyal/kitty/issues/45#issuecomment-915753960
Remote control via socket doesn't work opening a new OS window unless there is an existing window open already.
**To Reproduce**
Steps to reproduce the behavior:
1. Launch kitty without window:
````
kitty --config NONE --listen-on=unix:/tmp/scratch -o allow_remote_control=yes -o macos_quit_when_last_window_closed=no -1 --instance-group scratch false &
````
2. Attempt to open OS Window using remote control:
````
kitty @ --to unix:/tmp/scratch launch --type=os-window --title=test
````
3. No window opens up
4. Right click icon -> Open OS Window
5. Reattempt remote control:
````
kitty @ --to unix:/tmp/scratch launch --type=os-window --title=test
````
6. Window opens up fine with title "test"
**Environment details**
```
kitty 0.25.2 created by Kovid Goyal
Darwin gtd.lan 21.5.0 Darwin Kernel Version 21.5.0: Tue Apr 26 21:08:22 PDT 2022; root:xnu-8020.121.3~4/RELEASE_X86_64 x86_64
ProductName: macOS ProductVersion: 12.4 BuildVersion: 21F79
Frozen: True
Paths:
kitty: /Applications/kitty.app/Contents/MacOS/kitty
base dir: /Applications/kitty.app/Contents/Resources/kitty
extensions dir: /Applications/kitty.app/Contents/Resources/Python/lib/kitty-extensions
system shell: /bin/zsh
Loaded config overrides:
allow_remote_control yes
macos_quit_when_last_window_closed no
Config options different from defaults:
allow_remote_control y
Important environment variables seen by the kitty process:
PATH /usr/local/opt/coreutils/libexec/gnubin:/Users/hars/.config/bin:/Users/hars/.dwm/statusbar:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Library/Apple/usr/bin:/usr/local/opt/coreutils/libexec/gnubin:/Users/hars/.config/bin:/Users/hars/.dwm/statusbar:/Applications/kitty.app/Contents/MacOS:/Users/hars/.local/share/sheldon/repos/github.com/kazhala/dotbare:/usr/local/opt/fzf/bin
LANG en_AU.UTF-8
VISUAL nvim
EDITOR nvim
SHELL /bin/zsh
USER hars
XDG_CONFIG_HOME /Users/hars/.config
XDG_CACHE_HOME /Users/hars/.cache
```
**Additional context**
Also tried ``new-window --window-type=os``
--- END ISSUE ---
Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `kitty/rc/launch.py`
Content:
```
1 #!/usr/bin/env python
2 # License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net>
3
4
5 from typing import TYPE_CHECKING, Optional
6
7 from kitty.cli_stub import LaunchCLIOptions
8 from kitty.launch import (
9 launch as do_launch, options_spec as launch_options_spec,
10 parse_launch_args
11 )
12
13 from .base import (
14 MATCH_TAB_OPTION, ArgsType, Boss, PayloadGetType, PayloadType, RCOptions,
15 RemoteCommand, ResponseType, Window
16 )
17
18 if TYPE_CHECKING:
19 from kitty.cli_stub import LaunchRCOptions as CLIOptions
20
21
22 class Launch(RemoteCommand):
23
24 '''
25 args+: The command line to run in the new window, as a list, use an empty list to run the default shell
26 match: The tab to open the new window in
27 window_title: Title for the new window
28 cwd: Working directory for the new window
29 env: List of environment variables of the form NAME=VALUE
30 tab_title: Title for the new tab
31 type: The type of window to open
32 keep_focus: Boolean indicating whether the current window should retain focus or not
33 copy_colors: Boolean indicating whether to copy the colors from the current window
34 copy_cmdline: Boolean indicating whether to copy the cmdline from the current window
35 copy_env: Boolean indicating whether to copy the environ from the current window
36 hold: Boolean indicating whether to keep window open after cmd exits
37 location: Where in the tab to open the new window
38 allow_remote_control: Boolean indicating whether to allow remote control from the new window
39 stdin_source: Where to get stdin for thew process from
40 stdin_add_formatting: Boolean indicating whether to add formatting codes to stdin
41 stdin_add_line_wrap_markers: Boolean indicating whether to add line wrap markers to stdin
42 no_response: Boolean indicating whether to send back the window id
43 marker: Specification for marker for new window, for example: "text 1 ERROR"
44 logo: Path to window logo
45 logo_position: Window logo position as string or empty string to use default
46 logo_alpha: Window logo alpha or -1 to use default
47 self: Boolean, if True use tab the command was run in
48 '''
49
50 short_desc = 'Run an arbitrary process in a new window/tab'
51 desc = (
52 'Prints out the id of the newly opened window. Any command line arguments'
53 ' are assumed to be the command line used to run in the new window, if none'
54 ' are provided, the default shell is run. For example:'
55 ' :code:`kitty @ launch --title=Email mutt`.'
56 )
57 options_spec = MATCH_TAB_OPTION + '\n\n' + '''\
58 --no-response
59 type=bool-set
60 Do not print out the id of the newly created window.
61
62
63 --self
64 type=bool-set
65 If specified the tab containing the window this command is run in is used
66 instead of the active tab
67 ''' + '\n\n' + launch_options_spec().replace(':option:`launch', ':option:`kitty @ launch')
68 argspec = '[CMD ...]'
69
70 def message_to_kitty(self, global_opts: RCOptions, opts: 'CLIOptions', args: ArgsType) -> PayloadType:
71 ans = {'args': args or []}
72 for attr, val in opts.__dict__.items():
73 ans[attr] = val
74 return ans
75
76 def response_from_kitty(self, boss: Boss, window: Optional[Window], payload_get: PayloadGetType) -> ResponseType:
77 default_opts = parse_launch_args()[0]
78 opts = LaunchCLIOptions()
79 for key, default_value in default_opts.__dict__.items():
80 val = payload_get(key)
81 if val is None:
82 val = default_value
83 setattr(opts, key, val)
84 tabs = self.tabs_for_match_payload(boss, window, payload_get)
85 if tabs and tabs[0]:
86 w = do_launch(boss, opts, payload_get('args') or [], target_tab=tabs[0])
87 return None if payload_get('no_response') else str(getattr(w, 'id', 0))
88 return None
89
90
91 launch = Launch()
92
```
--- END FILES ---
Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.
Here is an example:
```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
if __name__ == "__main__":
- asyncio.run(run_async_server("."), debug=True)
+ asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
if __name__ == "__main__":
- server = run_sync_server(".")
+ server = run_sync_server()
server.shutdown()
```
| diff --git a/kitty/rc/launch.py b/kitty/rc/launch.py
--- a/kitty/rc/launch.py
+++ b/kitty/rc/launch.py
@@ -81,11 +81,14 @@
if val is None:
val = default_value
setattr(opts, key, val)
+ target_tab = None
tabs = self.tabs_for_match_payload(boss, window, payload_get)
if tabs and tabs[0]:
- w = do_launch(boss, opts, payload_get('args') or [], target_tab=tabs[0])
- return None if payload_get('no_response') else str(getattr(w, 'id', 0))
- return None
+ target_tab = tabs[0]
+ elif payload_get('type') not in ('os-window', 'background'):
+ return None
+ w = do_launch(boss, opts, payload_get('args') or [], target_tab=target_tab)
+ return None if payload_get('no_response') else str(getattr(w, 'id', 0))
launch = Launch()
| {"golden_diff": "diff --git a/kitty/rc/launch.py b/kitty/rc/launch.py\n--- a/kitty/rc/launch.py\n+++ b/kitty/rc/launch.py\n@@ -81,11 +81,14 @@\n if val is None:\n val = default_value\n setattr(opts, key, val)\n+ target_tab = None\n tabs = self.tabs_for_match_payload(boss, window, payload_get)\n if tabs and tabs[0]:\n- w = do_launch(boss, opts, payload_get('args') or [], target_tab=tabs[0])\n- return None if payload_get('no_response') else str(getattr(w, 'id', 0))\n- return None\n+ target_tab = tabs[0]\n+ elif payload_get('type') not in ('os-window', 'background'):\n+ return None\n+ w = do_launch(boss, opts, payload_get('args') or [], target_tab=target_tab)\n+ return None if payload_get('no_response') else str(getattr(w, 'id', 0))\n \n \n launch = Launch()\n", "issue": "MacOS: Launch OS Window via Remote Control \n**Describe the bug** \r\n\r\nRef: https://github.com/kovidgoyal/kitty/issues/45#issuecomment-915753960\r\n\r\nRemote control via socket doesn't work opening a new OS window unless there is an existing window open already. \r\n\r\n**To Reproduce** \r\n\r\nSteps to reproduce the behavior:\r\n1. Launch kitty without window:\r\n````\r\nkitty --config NONE --listen-on=unix:/tmp/scratch -o allow_remote_control=yes -o macos_quit_when_last_window_closed=no -1 --instance-group scratch false &\r\n````\r\n2. Attempt to open OS Window using remote control:\r\n````\r\nkitty @ --to unix:/tmp/scratch launch --type=os-window --title=test\r\n````\r\n3. No window opens up\r\n\r\n4. Right click icon -> Open OS Window\r\n\r\n5. Reattempt remote control:\r\n````\r\nkitty @ --to unix:/tmp/scratch launch --type=os-window --title=test\r\n````\r\n6. Window opens up fine with title \"test\"\r\n\r\n**Environment details**\r\n```\r\nkitty 0.25.2 created by Kovid Goyal\r\nDarwin gtd.lan 21.5.0 Darwin Kernel Version 21.5.0: Tue Apr 26 21:08:22 PDT 2022; root:xnu-8020.121.3~4/RELEASE_X86_64 x86_64\r\nProductName:\tmacOS ProductVersion:\t12.4 BuildVersion:\t21F79\r\nFrozen: True\r\nPaths:\r\n kitty: /Applications/kitty.app/Contents/MacOS/kitty\r\n base dir: /Applications/kitty.app/Contents/Resources/kitty\r\n extensions dir: /Applications/kitty.app/Contents/Resources/Python/lib/kitty-extensions\r\n system shell: /bin/zsh\r\nLoaded config overrides:\r\n allow_remote_control yes\r\n macos_quit_when_last_window_closed no\r\n\r\nConfig options different from defaults:\r\nallow_remote_control y\r\n\r\nImportant environment variables seen by the kitty process:\r\n\tPATH /usr/local/opt/coreutils/libexec/gnubin:/Users/hars/.config/bin:/Users/hars/.dwm/statusbar:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Library/Apple/usr/bin:/usr/local/opt/coreutils/libexec/gnubin:/Users/hars/.config/bin:/Users/hars/.dwm/statusbar:/Applications/kitty.app/Contents/MacOS:/Users/hars/.local/share/sheldon/repos/github.com/kazhala/dotbare:/usr/local/opt/fzf/bin\r\n\tLANG en_AU.UTF-8\r\n\tVISUAL nvim\r\n\tEDITOR nvim\r\n\tSHELL /bin/zsh\r\n\tUSER hars\r\n\tXDG_CONFIG_HOME /Users/hars/.config\r\n\tXDG_CACHE_HOME /Users/hars/.cache\r\n\r\n```\r\n**Additional context**\r\n\r\nAlso tried ``new-window --window-type=os``\r\n\r\n\n", "before_files": [{"content": "#!/usr/bin/env python\n# License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net>\n\n\nfrom typing import TYPE_CHECKING, Optional\n\nfrom kitty.cli_stub import LaunchCLIOptions\nfrom kitty.launch import (\n launch as do_launch, options_spec as launch_options_spec,\n parse_launch_args\n)\n\nfrom .base import (\n MATCH_TAB_OPTION, ArgsType, Boss, PayloadGetType, PayloadType, RCOptions,\n RemoteCommand, ResponseType, Window\n)\n\nif TYPE_CHECKING:\n from kitty.cli_stub import LaunchRCOptions as CLIOptions\n\n\nclass Launch(RemoteCommand):\n\n '''\n args+: The command line to run in the new window, as a list, use an empty list to run the default shell\n match: The tab to open the new window in\n window_title: Title for the new window\n cwd: Working directory for the new window\n env: List of environment variables of the form NAME=VALUE\n tab_title: Title for the new tab\n type: The type of window to open\n keep_focus: Boolean indicating whether the current window should retain focus or not\n copy_colors: Boolean indicating whether to copy the colors from the current window\n copy_cmdline: Boolean indicating whether to copy the cmdline from the current window\n copy_env: Boolean indicating whether to copy the environ from the current window\n hold: Boolean indicating whether to keep window open after cmd exits\n location: Where in the tab to open the new window\n allow_remote_control: Boolean indicating whether to allow remote control from the new window\n stdin_source: Where to get stdin for thew process from\n stdin_add_formatting: Boolean indicating whether to add formatting codes to stdin\n stdin_add_line_wrap_markers: Boolean indicating whether to add line wrap markers to stdin\n no_response: Boolean indicating whether to send back the window id\n marker: Specification for marker for new window, for example: \"text 1 ERROR\"\n logo: Path to window logo\n logo_position: Window logo position as string or empty string to use default\n logo_alpha: Window logo alpha or -1 to use default\n self: Boolean, if True use tab the command was run in\n '''\n\n short_desc = 'Run an arbitrary process in a new window/tab'\n desc = (\n 'Prints out the id of the newly opened window. Any command line arguments'\n ' are assumed to be the command line used to run in the new window, if none'\n ' are provided, the default shell is run. For example:'\n ' :code:`kitty @ launch --title=Email mutt`.'\n )\n options_spec = MATCH_TAB_OPTION + '\\n\\n' + '''\\\n--no-response\ntype=bool-set\nDo not print out the id of the newly created window.\n\n\n--self\ntype=bool-set\nIf specified the tab containing the window this command is run in is used\ninstead of the active tab\n ''' + '\\n\\n' + launch_options_spec().replace(':option:`launch', ':option:`kitty @ launch')\n argspec = '[CMD ...]'\n\n def message_to_kitty(self, global_opts: RCOptions, opts: 'CLIOptions', args: ArgsType) -> PayloadType:\n ans = {'args': args or []}\n for attr, val in opts.__dict__.items():\n ans[attr] = val\n return ans\n\n def response_from_kitty(self, boss: Boss, window: Optional[Window], payload_get: PayloadGetType) -> ResponseType:\n default_opts = parse_launch_args()[0]\n opts = LaunchCLIOptions()\n for key, default_value in default_opts.__dict__.items():\n val = payload_get(key)\n if val is None:\n val = default_value\n setattr(opts, key, val)\n tabs = self.tabs_for_match_payload(boss, window, payload_get)\n if tabs and tabs[0]:\n w = do_launch(boss, opts, payload_get('args') or [], target_tab=tabs[0])\n return None if payload_get('no_response') else str(getattr(w, 'id', 0))\n return None\n\n\nlaunch = Launch()\n", "path": "kitty/rc/launch.py"}], "after_files": [{"content": "#!/usr/bin/env python\n# License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net>\n\n\nfrom typing import TYPE_CHECKING, Optional\n\nfrom kitty.cli_stub import LaunchCLIOptions\nfrom kitty.launch import (\n launch as do_launch, options_spec as launch_options_spec,\n parse_launch_args\n)\n\nfrom .base import (\n MATCH_TAB_OPTION, ArgsType, Boss, PayloadGetType, PayloadType, RCOptions,\n RemoteCommand, ResponseType, Window\n)\n\nif TYPE_CHECKING:\n from kitty.cli_stub import LaunchRCOptions as CLIOptions\n\n\nclass Launch(RemoteCommand):\n\n '''\n args+: The command line to run in the new window, as a list, use an empty list to run the default shell\n match: The tab to open the new window in\n window_title: Title for the new window\n cwd: Working directory for the new window\n env: List of environment variables of the form NAME=VALUE\n tab_title: Title for the new tab\n type: The type of window to open\n keep_focus: Boolean indicating whether the current window should retain focus or not\n copy_colors: Boolean indicating whether to copy the colors from the current window\n copy_cmdline: Boolean indicating whether to copy the cmdline from the current window\n copy_env: Boolean indicating whether to copy the environ from the current window\n hold: Boolean indicating whether to keep window open after cmd exits\n location: Where in the tab to open the new window\n allow_remote_control: Boolean indicating whether to allow remote control from the new window\n stdin_source: Where to get stdin for thew process from\n stdin_add_formatting: Boolean indicating whether to add formatting codes to stdin\n stdin_add_line_wrap_markers: Boolean indicating whether to add line wrap markers to stdin\n no_response: Boolean indicating whether to send back the window id\n marker: Specification for marker for new window, for example: \"text 1 ERROR\"\n logo: Path to window logo\n logo_position: Window logo position as string or empty string to use default\n logo_alpha: Window logo alpha or -1 to use default\n self: Boolean, if True use tab the command was run in\n '''\n\n short_desc = 'Run an arbitrary process in a new window/tab'\n desc = (\n 'Prints out the id of the newly opened window. Any command line arguments'\n ' are assumed to be the command line used to run in the new window, if none'\n ' are provided, the default shell is run. For example:'\n ' :code:`kitty @ launch --title=Email mutt`.'\n )\n options_spec = MATCH_TAB_OPTION + '\\n\\n' + '''\\\n--no-response\ntype=bool-set\nDo not print out the id of the newly created window.\n\n\n--self\ntype=bool-set\nIf specified the tab containing the window this command is run in is used\ninstead of the active tab\n ''' + '\\n\\n' + launch_options_spec().replace(':option:`launch', ':option:`kitty @ launch')\n argspec = '[CMD ...]'\n\n def message_to_kitty(self, global_opts: RCOptions, opts: 'CLIOptions', args: ArgsType) -> PayloadType:\n ans = {'args': args or []}\n for attr, val in opts.__dict__.items():\n ans[attr] = val\n return ans\n\n def response_from_kitty(self, boss: Boss, window: Optional[Window], payload_get: PayloadGetType) -> ResponseType:\n default_opts = parse_launch_args()[0]\n opts = LaunchCLIOptions()\n for key, default_value in default_opts.__dict__.items():\n val = payload_get(key)\n if val is None:\n val = default_value\n setattr(opts, key, val)\n target_tab = None\n tabs = self.tabs_for_match_payload(boss, window, payload_get)\n if tabs and tabs[0]:\n target_tab = tabs[0]\n elif payload_get('type') not in ('os-window', 'background'):\n return None\n w = do_launch(boss, opts, payload_get('args') or [], target_tab=target_tab)\n return None if payload_get('no_response') else str(getattr(w, 'id', 0))\n\n\nlaunch = Launch()\n", "path": "kitty/rc/launch.py"}]} | 1,990 | 236 |
gh_patches_debug_23025 | rasdani/github-patches | git_diff | cookiecutter__cookiecutter-862 | We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Empty hook file causes cryptic error
If you have a pre_gen_project.sh or a post_gen_project.sh file with no data in it, cookiecutter fails with an unhelpful traceback.
```
Traceback (most recent call last):
File "/usr/local/bin/cookiecutter", line 11, in <module>
sys.exit(main())
File "/usr/local/lib/python2.7/site-packages/click/core.py", line 716, in __call__
return self.main(*args, **kwargs)
File "/usr/local/lib/python2.7/site-packages/click/core.py", line 696, in main
rv = self.invoke(ctx)
File "/usr/local/lib/python2.7/site-packages/click/core.py", line 889, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "/usr/local/lib/python2.7/site-packages/click/core.py", line 534, in invoke
return callback(*args, **kwargs)
File "/usr/local/lib/python2.7/site-packages/cookiecutter/cli.py", line 100, in main
config_file=user_config
File "/usr/local/lib/python2.7/site-packages/cookiecutter/main.py", line 140, in cookiecutter
output_dir=output_dir
File "/usr/local/lib/python2.7/site-packages/cookiecutter/generate.py", line 273, in generate_files
_run_hook_from_repo_dir(repo_dir, 'pre_gen_project', project_dir, context)
File "/usr/local/lib/python2.7/site-packages/cookiecutter/generate.py", line 232, in _run_hook_from_repo_dir
run_hook(hook_name, project_dir, context)
File "/usr/local/lib/python2.7/site-packages/cookiecutter/hooks.py", line 116, in run_hook
run_script_with_context(script, project_dir, context)
File "/usr/local/lib/python2.7/site-packages/cookiecutter/hooks.py", line 101, in run_script_with_context
run_script(temp.name, cwd)
File "/usr/local/lib/python2.7/site-packages/cookiecutter/hooks.py", line 73, in run_script
cwd=cwd
File "/usr/local/Cellar/python/2.7.10_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 656, in __init__
_cleanup()
File "/usr/local/Cellar/python/2.7.10_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 1335, in _execute_child
raise child_exception
OSError: [Errno 8] Exec format error
```
--- END ISSUE ---
Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `cookiecutter/hooks.py`
Content:
```
1 # -*- coding: utf-8 -*-
2
3 """Functions for discovering and executing various cookiecutter hooks."""
4
5 import io
6 import logging
7 import os
8 import subprocess
9 import sys
10 import tempfile
11
12 from jinja2 import Template
13
14 from cookiecutter import utils
15 from .exceptions import FailedHookException
16
17 logger = logging.getLogger(__name__)
18
19 _HOOKS = [
20 'pre_gen_project',
21 'post_gen_project',
22 ]
23 EXIT_SUCCESS = 0
24
25
26 def valid_hook(hook_file, hook_name):
27 """Determine if a hook file is valid.
28
29 :param hook_file: The hook file to consider for validity
30 :param hook_name: The hook to find
31 :return: The hook file validity
32 """
33 filename = os.path.basename(hook_file)
34 basename = os.path.splitext(filename)[0]
35
36 matching_hook = basename == hook_name
37 supported_hook = basename in _HOOKS
38 backup_file = filename.endswith('~')
39
40 return matching_hook and supported_hook and not backup_file
41
42
43 def find_hook(hook_name, hooks_dir='hooks'):
44 """Return a dict of all hook scripts provided.
45
46 Must be called with the project template as the current working directory.
47 Dict's key will be the hook/script's name, without extension, while values
48 will be the absolute path to the script. Missing scripts will not be
49 included in the returned dict.
50
51 :param hook_name: The hook to find
52 :param hooks_dir: The hook directory in the template
53 :return: The absolute path to the hook script or None
54 """
55 logger.debug('hooks_dir is {}'.format(os.path.abspath(hooks_dir)))
56
57 if not os.path.isdir(hooks_dir):
58 logger.debug('No hooks/ dir in template_dir')
59 return None
60
61 for hook_file in os.listdir(hooks_dir):
62 if valid_hook(hook_file, hook_name):
63 return os.path.abspath(os.path.join(hooks_dir, hook_file))
64
65 return None
66
67
68 def run_script(script_path, cwd='.'):
69 """Execute a script from a working directory.
70
71 :param script_path: Absolute path to the script to run.
72 :param cwd: The directory to run the script from.
73 """
74 run_thru_shell = sys.platform.startswith('win')
75 if script_path.endswith('.py'):
76 script_command = [sys.executable, script_path]
77 else:
78 script_command = [script_path]
79
80 utils.make_executable(script_path)
81
82 proc = subprocess.Popen(
83 script_command,
84 shell=run_thru_shell,
85 cwd=cwd
86 )
87 exit_status = proc.wait()
88 if exit_status != EXIT_SUCCESS:
89 raise FailedHookException(
90 "Hook script failed (exit status: %d)" % exit_status)
91
92
93 def run_script_with_context(script_path, cwd, context):
94 """Execute a script after rendering it with Jinja.
95
96 :param script_path: Absolute path to the script to run.
97 :param cwd: The directory to run the script from.
98 :param context: Cookiecutter project template context.
99 """
100 _, extension = os.path.splitext(script_path)
101
102 contents = io.open(script_path, 'r', encoding='utf-8').read()
103
104 with tempfile.NamedTemporaryFile(
105 delete=False,
106 mode='wb',
107 suffix=extension
108 ) as temp:
109 output = Template(contents).render(**context)
110 temp.write(output.encode('utf-8'))
111
112 run_script(temp.name, cwd)
113
114
115 def run_hook(hook_name, project_dir, context):
116 """
117 Try to find and execute a hook from the specified project directory.
118
119 :param hook_name: The hook to execute.
120 :param project_dir: The directory to execute the script from.
121 :param context: Cookiecutter project context.
122 """
123 script = find_hook(hook_name)
124 if script is None:
125 logger.debug('No hooks found')
126 return
127 logger.debug('Running hook {}'.format(hook_name))
128 run_script_with_context(script, project_dir, context)
129
```
--- END FILES ---
Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.
Here is an example:
```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
if __name__ == "__main__":
- asyncio.run(run_async_server("."), debug=True)
+ asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
if __name__ == "__main__":
- server = run_sync_server(".")
+ server = run_sync_server()
server.shutdown()
```
| diff --git a/cookiecutter/hooks.py b/cookiecutter/hooks.py
--- a/cookiecutter/hooks.py
+++ b/cookiecutter/hooks.py
@@ -2,6 +2,7 @@
"""Functions for discovering and executing various cookiecutter hooks."""
+import errno
import io
import logging
import os
@@ -79,15 +80,26 @@
utils.make_executable(script_path)
- proc = subprocess.Popen(
- script_command,
- shell=run_thru_shell,
- cwd=cwd
- )
- exit_status = proc.wait()
- if exit_status != EXIT_SUCCESS:
+ try:
+ proc = subprocess.Popen(
+ script_command,
+ shell=run_thru_shell,
+ cwd=cwd
+ )
+ exit_status = proc.wait()
+ if exit_status != EXIT_SUCCESS:
+ raise FailedHookException(
+ 'Hook script failed (exit status: {})'.format(exit_status)
+ )
+ except OSError as os_error:
+ if os_error.errno == errno.ENOEXEC:
+ raise FailedHookException(
+ 'Hook script failed, might be an '
+ 'empty file or missing a shebang'
+ )
raise FailedHookException(
- "Hook script failed (exit status: %d)" % exit_status)
+ 'Hook script failed (error: {})'.format(os_error)
+ )
def run_script_with_context(script_path, cwd, context):
| {"golden_diff": "diff --git a/cookiecutter/hooks.py b/cookiecutter/hooks.py\n--- a/cookiecutter/hooks.py\n+++ b/cookiecutter/hooks.py\n@@ -2,6 +2,7 @@\n \n \"\"\"Functions for discovering and executing various cookiecutter hooks.\"\"\"\n \n+import errno\n import io\n import logging\n import os\n@@ -79,15 +80,26 @@\n \n utils.make_executable(script_path)\n \n- proc = subprocess.Popen(\n- script_command,\n- shell=run_thru_shell,\n- cwd=cwd\n- )\n- exit_status = proc.wait()\n- if exit_status != EXIT_SUCCESS:\n+ try:\n+ proc = subprocess.Popen(\n+ script_command,\n+ shell=run_thru_shell,\n+ cwd=cwd\n+ )\n+ exit_status = proc.wait()\n+ if exit_status != EXIT_SUCCESS:\n+ raise FailedHookException(\n+ 'Hook script failed (exit status: {})'.format(exit_status)\n+ )\n+ except OSError as os_error:\n+ if os_error.errno == errno.ENOEXEC:\n+ raise FailedHookException(\n+ 'Hook script failed, might be an '\n+ 'empty file or missing a shebang'\n+ )\n raise FailedHookException(\n- \"Hook script failed (exit status: %d)\" % exit_status)\n+ 'Hook script failed (error: {})'.format(os_error)\n+ )\n \n \n def run_script_with_context(script_path, cwd, context):\n", "issue": "Empty hook file causes cryptic error\nIf you have a pre_gen_project.sh or a post_gen_project.sh file with no data in it, cookiecutter fails with an unhelpful traceback.\n\n```\nTraceback (most recent call last):\n File \"/usr/local/bin/cookiecutter\", line 11, in <module>\n sys.exit(main())\n File \"/usr/local/lib/python2.7/site-packages/click/core.py\", line 716, in __call__\n return self.main(*args, **kwargs)\n File \"/usr/local/lib/python2.7/site-packages/click/core.py\", line 696, in main\n rv = self.invoke(ctx)\n File \"/usr/local/lib/python2.7/site-packages/click/core.py\", line 889, in invoke\n return ctx.invoke(self.callback, **ctx.params)\n File \"/usr/local/lib/python2.7/site-packages/click/core.py\", line 534, in invoke\n return callback(*args, **kwargs)\n File \"/usr/local/lib/python2.7/site-packages/cookiecutter/cli.py\", line 100, in main\n config_file=user_config\n File \"/usr/local/lib/python2.7/site-packages/cookiecutter/main.py\", line 140, in cookiecutter\n output_dir=output_dir\n File \"/usr/local/lib/python2.7/site-packages/cookiecutter/generate.py\", line 273, in generate_files\n _run_hook_from_repo_dir(repo_dir, 'pre_gen_project', project_dir, context)\n File \"/usr/local/lib/python2.7/site-packages/cookiecutter/generate.py\", line 232, in _run_hook_from_repo_dir\n run_hook(hook_name, project_dir, context)\n File \"/usr/local/lib/python2.7/site-packages/cookiecutter/hooks.py\", line 116, in run_hook\n run_script_with_context(script, project_dir, context)\n File \"/usr/local/lib/python2.7/site-packages/cookiecutter/hooks.py\", line 101, in run_script_with_context\n run_script(temp.name, cwd)\n File \"/usr/local/lib/python2.7/site-packages/cookiecutter/hooks.py\", line 73, in run_script\n cwd=cwd\n File \"/usr/local/Cellar/python/2.7.10_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py\", line 656, in __init__\n _cleanup()\n File \"/usr/local/Cellar/python/2.7.10_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py\", line 1335, in _execute_child\n raise child_exception\nOSError: [Errno 8] Exec format error\n```\n\n", "before_files": [{"content": "# -*- coding: utf-8 -*-\n\n\"\"\"Functions for discovering and executing various cookiecutter hooks.\"\"\"\n\nimport io\nimport logging\nimport os\nimport subprocess\nimport sys\nimport tempfile\n\nfrom jinja2 import Template\n\nfrom cookiecutter import utils\nfrom .exceptions import FailedHookException\n\nlogger = logging.getLogger(__name__)\n\n_HOOKS = [\n 'pre_gen_project',\n 'post_gen_project',\n]\nEXIT_SUCCESS = 0\n\n\ndef valid_hook(hook_file, hook_name):\n \"\"\"Determine if a hook file is valid.\n\n :param hook_file: The hook file to consider for validity\n :param hook_name: The hook to find\n :return: The hook file validity\n \"\"\"\n filename = os.path.basename(hook_file)\n basename = os.path.splitext(filename)[0]\n\n matching_hook = basename == hook_name\n supported_hook = basename in _HOOKS\n backup_file = filename.endswith('~')\n\n return matching_hook and supported_hook and not backup_file\n\n\ndef find_hook(hook_name, hooks_dir='hooks'):\n \"\"\"Return a dict of all hook scripts provided.\n\n Must be called with the project template as the current working directory.\n Dict's key will be the hook/script's name, without extension, while values\n will be the absolute path to the script. Missing scripts will not be\n included in the returned dict.\n\n :param hook_name: The hook to find\n :param hooks_dir: The hook directory in the template\n :return: The absolute path to the hook script or None\n \"\"\"\n logger.debug('hooks_dir is {}'.format(os.path.abspath(hooks_dir)))\n\n if not os.path.isdir(hooks_dir):\n logger.debug('No hooks/ dir in template_dir')\n return None\n\n for hook_file in os.listdir(hooks_dir):\n if valid_hook(hook_file, hook_name):\n return os.path.abspath(os.path.join(hooks_dir, hook_file))\n\n return None\n\n\ndef run_script(script_path, cwd='.'):\n \"\"\"Execute a script from a working directory.\n\n :param script_path: Absolute path to the script to run.\n :param cwd: The directory to run the script from.\n \"\"\"\n run_thru_shell = sys.platform.startswith('win')\n if script_path.endswith('.py'):\n script_command = [sys.executable, script_path]\n else:\n script_command = [script_path]\n\n utils.make_executable(script_path)\n\n proc = subprocess.Popen(\n script_command,\n shell=run_thru_shell,\n cwd=cwd\n )\n exit_status = proc.wait()\n if exit_status != EXIT_SUCCESS:\n raise FailedHookException(\n \"Hook script failed (exit status: %d)\" % exit_status)\n\n\ndef run_script_with_context(script_path, cwd, context):\n \"\"\"Execute a script after rendering it with Jinja.\n\n :param script_path: Absolute path to the script to run.\n :param cwd: The directory to run the script from.\n :param context: Cookiecutter project template context.\n \"\"\"\n _, extension = os.path.splitext(script_path)\n\n contents = io.open(script_path, 'r', encoding='utf-8').read()\n\n with tempfile.NamedTemporaryFile(\n delete=False,\n mode='wb',\n suffix=extension\n ) as temp:\n output = Template(contents).render(**context)\n temp.write(output.encode('utf-8'))\n\n run_script(temp.name, cwd)\n\n\ndef run_hook(hook_name, project_dir, context):\n \"\"\"\n Try to find and execute a hook from the specified project directory.\n\n :param hook_name: The hook to execute.\n :param project_dir: The directory to execute the script from.\n :param context: Cookiecutter project context.\n \"\"\"\n script = find_hook(hook_name)\n if script is None:\n logger.debug('No hooks found')\n return\n logger.debug('Running hook {}'.format(hook_name))\n run_script_with_context(script, project_dir, context)\n", "path": "cookiecutter/hooks.py"}], "after_files": [{"content": "# -*- coding: utf-8 -*-\n\n\"\"\"Functions for discovering and executing various cookiecutter hooks.\"\"\"\n\nimport errno\nimport io\nimport logging\nimport os\nimport subprocess\nimport sys\nimport tempfile\n\nfrom jinja2 import Template\n\nfrom cookiecutter import utils\nfrom .exceptions import FailedHookException\n\nlogger = logging.getLogger(__name__)\n\n_HOOKS = [\n 'pre_gen_project',\n 'post_gen_project',\n]\nEXIT_SUCCESS = 0\n\n\ndef valid_hook(hook_file, hook_name):\n \"\"\"Determine if a hook file is valid.\n\n :param hook_file: The hook file to consider for validity\n :param hook_name: The hook to find\n :return: The hook file validity\n \"\"\"\n filename = os.path.basename(hook_file)\n basename = os.path.splitext(filename)[0]\n\n matching_hook = basename == hook_name\n supported_hook = basename in _HOOKS\n backup_file = filename.endswith('~')\n\n return matching_hook and supported_hook and not backup_file\n\n\ndef find_hook(hook_name, hooks_dir='hooks'):\n \"\"\"Return a dict of all hook scripts provided.\n\n Must be called with the project template as the current working directory.\n Dict's key will be the hook/script's name, without extension, while values\n will be the absolute path to the script. Missing scripts will not be\n included in the returned dict.\n\n :param hook_name: The hook to find\n :param hooks_dir: The hook directory in the template\n :return: The absolute path to the hook script or None\n \"\"\"\n logger.debug('hooks_dir is {}'.format(os.path.abspath(hooks_dir)))\n\n if not os.path.isdir(hooks_dir):\n logger.debug('No hooks/ dir in template_dir')\n return None\n\n for hook_file in os.listdir(hooks_dir):\n if valid_hook(hook_file, hook_name):\n return os.path.abspath(os.path.join(hooks_dir, hook_file))\n\n return None\n\n\ndef run_script(script_path, cwd='.'):\n \"\"\"Execute a script from a working directory.\n\n :param script_path: Absolute path to the script to run.\n :param cwd: The directory to run the script from.\n \"\"\"\n run_thru_shell = sys.platform.startswith('win')\n if script_path.endswith('.py'):\n script_command = [sys.executable, script_path]\n else:\n script_command = [script_path]\n\n utils.make_executable(script_path)\n\n try:\n proc = subprocess.Popen(\n script_command,\n shell=run_thru_shell,\n cwd=cwd\n )\n exit_status = proc.wait()\n if exit_status != EXIT_SUCCESS:\n raise FailedHookException(\n 'Hook script failed (exit status: {})'.format(exit_status)\n )\n except OSError as os_error:\n if os_error.errno == errno.ENOEXEC:\n raise FailedHookException(\n 'Hook script failed, might be an '\n 'empty file or missing a shebang'\n )\n raise FailedHookException(\n 'Hook script failed (error: {})'.format(os_error)\n )\n\n\ndef run_script_with_context(script_path, cwd, context):\n \"\"\"Execute a script after rendering it with Jinja.\n\n :param script_path: Absolute path to the script to run.\n :param cwd: The directory to run the script from.\n :param context: Cookiecutter project template context.\n \"\"\"\n _, extension = os.path.splitext(script_path)\n\n contents = io.open(script_path, 'r', encoding='utf-8').read()\n\n with tempfile.NamedTemporaryFile(\n delete=False,\n mode='wb',\n suffix=extension\n ) as temp:\n output = Template(contents).render(**context)\n temp.write(output.encode('utf-8'))\n\n run_script(temp.name, cwd)\n\n\ndef run_hook(hook_name, project_dir, context):\n \"\"\"\n Try to find and execute a hook from the specified project directory.\n\n :param hook_name: The hook to execute.\n :param project_dir: The directory to execute the script from.\n :param context: Cookiecutter project context.\n \"\"\"\n script = find_hook(hook_name)\n if script is None:\n logger.debug('No hooks found')\n return\n logger.debug('Running hook {}'.format(hook_name))\n run_script_with_context(script, project_dir, context)\n", "path": "cookiecutter/hooks.py"}]} | 2,021 | 328 |
gh_patches_debug_6280 | rasdani/github-patches | git_diff | PennyLaneAI__pennylane-2060 | We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Raise exception or warning when `qml.adjoint` is used on operation list instead of function.
The newer `qml.adjoint` function does not have any effect when acting on operation lists like in the following example:
```python
params = list(range(4))
qml.adjoint(qml.templates.AngleEmbedding(params))
```
Users might try this, because it worked like this with `qml.inv` which `qml.adjoint` is replacing. Therefore, we should raise
an exception whenever this is attempted by checking for the input to be `callable`. Alternatively, a warning could be raised, but
the behaviour differs fundamentally from the expected, an exception seems more appropriate.
--- END ISSUE ---
Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `pennylane/transforms/adjoint.py`
Content:
```
1 # Copyright 2018-2021 Xanadu Quantum Technologies Inc.
2
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6
7 # http://www.apache.org/licenses/LICENSE-2.0
8
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14 """Code for the adjoint transform."""
15
16 from functools import wraps
17 from pennylane.tape import QuantumTape, stop_recording
18
19
20 def adjoint(fn):
21 """Create a function that applies the adjoint (inverse) of the provided operation or template.
22
23 This transform can be used to apply the adjoint of an arbitrary sequence of operations.
24
25 Args:
26 fn (function): A quantum function that applies quantum operations.
27
28 Returns:
29 function: A new function that will apply the same operations but adjointed and in reverse order.
30
31 **Example**
32
33 The adjoint transforms can be used within a QNode to apply the adjoint of
34 any quantum function. Consider the following quantum function, that applies two
35 operations:
36
37 .. code-block:: python3
38
39 def my_ops(a, b, wire):
40 qml.RX(a, wires=wire)
41 qml.RY(b, wires=wire)
42
43 We can create a QNode that applies this quantum function,
44 followed by the adjoint of this function:
45
46 .. code-block:: python3
47
48 dev = qml.device('default.qubit', wires=1)
49
50 @qml.qnode(dev)
51 def circuit(a, b):
52 my_ops(a, b, wire=0)
53 qml.adjoint(my_ops)(a, b, wire=0)
54 return qml.expval(qml.PauliZ(0))
55
56 Printing this out, we can see that the inverse quantum
57 function has indeed been applied:
58
59 >>> print(qml.draw(circuit)(0.2, 0.5))
60 0: ──RX(0.2)──RY(0.5)──RY(-0.5)──RX(-0.2)──┤ ⟨Z⟩
61
62 The adjoint function can also be applied directly to templates and operations:
63
64 >>> qml.adjoint(qml.RX)(0.123, wires=0)
65 >>> qml.adjoint(qml.templates.StronglyEntanglingLayers)(weights, wires=[0, 1])
66
67 .. UsageDetails::
68
69 **Adjoint of a function**
70
71 Here, we apply the ``subroutine`` function, and then apply its inverse.
72 Notice that in addition to adjointing all of the operations, they are also
73 applied in reverse construction order.
74
75 .. code-block:: python3
76
77 def subroutine(wire):
78 qml.RX(0.123, wires=wire)
79 qml.RY(0.456, wires=wire)
80
81 dev = qml.device('default.qubit', wires=1)
82 @qml.qnode(dev)
83 def circuit():
84 subroutine(0)
85 qml.adjoint(subroutine)(0)
86 return qml.expval(qml.PauliZ(0))
87
88 This creates the following circuit:
89
90 >>> print(qml.draw(circuit)())
91 0: --RX(0.123)--RY(0.456)--RY(-0.456)--RX(-0.123)--| <Z>
92
93 **Single operation**
94
95 You can also easily adjoint a single operation just by wrapping it with ``adjoint``:
96
97 .. code-block:: python3
98
99 dev = qml.device('default.qubit', wires=1)
100 @qml.qnode(dev)
101 def circuit():
102 qml.RX(0.123, wires=0)
103 qml.adjoint(qml.RX)(0.123, wires=0)
104 return qml.expval(qml.PauliZ(0))
105
106 This creates the following circuit:
107
108 >>> print(qml.draw(circuit)())
109 0: --RX(0.123)--RX(-0.123)--| <Z>
110 """
111
112 @wraps(fn)
113 def wrapper(*args, **kwargs):
114 with stop_recording(), QuantumTape() as tape:
115 fn(*args, **kwargs)
116
117 if not tape.operations:
118 # we called op.expand(): get the outputted tape
119 tape = fn(*args, **kwargs)
120
121 adjoint_ops = []
122 for op in reversed(tape.operations):
123 try:
124 new_op = op.adjoint()
125 adjoint_ops.append(new_op)
126 except NotImplementedError:
127 # Expand the operation and adjoint the result.
128 new_ops = adjoint(op.expand)()
129
130 if isinstance(new_ops, QuantumTape):
131 new_ops = new_ops.operations
132
133 adjoint_ops.extend(new_ops)
134
135 if len(adjoint_ops) == 1:
136 adjoint_ops = adjoint_ops[0]
137
138 return adjoint_ops
139
140 return wrapper
141
```
--- END FILES ---
Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.
Here is an example:
```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
if __name__ == "__main__":
- asyncio.run(run_async_server("."), debug=True)
+ asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
if __name__ == "__main__":
- server = run_sync_server(".")
+ server = run_sync_server()
server.shutdown()
```
| diff --git a/pennylane/transforms/adjoint.py b/pennylane/transforms/adjoint.py
--- a/pennylane/transforms/adjoint.py
+++ b/pennylane/transforms/adjoint.py
@@ -108,6 +108,12 @@
>>> print(qml.draw(circuit)())
0: --RX(0.123)--RX(-0.123)--| <Z>
"""
+ if not callable(fn):
+ raise ValueError(
+ f"The object {fn} of type {type(fn)} is not callable. "
+ "This error might occur if you apply adjoint to a list "
+ "of operations instead of a function or template."
+ )
@wraps(fn)
def wrapper(*args, **kwargs):
| {"golden_diff": "diff --git a/pennylane/transforms/adjoint.py b/pennylane/transforms/adjoint.py\n--- a/pennylane/transforms/adjoint.py\n+++ b/pennylane/transforms/adjoint.py\n@@ -108,6 +108,12 @@\n >>> print(qml.draw(circuit)())\r\n 0: --RX(0.123)--RX(-0.123)--| <Z>\r\n \"\"\"\r\n+ if not callable(fn):\r\n+ raise ValueError(\r\n+ f\"The object {fn} of type {type(fn)} is not callable. \"\r\n+ \"This error might occur if you apply adjoint to a list \"\r\n+ \"of operations instead of a function or template.\"\r\n+ )\r\n \r\n @wraps(fn)\r\n def wrapper(*args, **kwargs):\n", "issue": "Raise exception or warning when `qml.adjoint` is used on operation list instead of function.\nThe newer `qml.adjoint` function does not have any effect when acting on operation lists like in the following example:\r\n```python\r\nparams = list(range(4))\r\nqml.adjoint(qml.templates.AngleEmbedding(params))\r\n```\r\nUsers might try this, because it worked like this with `qml.inv` which `qml.adjoint` is replacing. Therefore, we should raise\r\nan exception whenever this is attempted by checking for the input to be `callable`. Alternatively, a warning could be raised, but \r\nthe behaviour differs fundamentally from the expected, an exception seems more appropriate.\r\n\r\n\n", "before_files": [{"content": "# Copyright 2018-2021 Xanadu Quantum Technologies Inc.\r\n\r\n# Licensed under the Apache License, Version 2.0 (the \"License\");\r\n# you may not use this file except in compliance with the License.\r\n# You may obtain a copy of the License at\r\n\r\n# http://www.apache.org/licenses/LICENSE-2.0\r\n\r\n# Unless required by applicable law or agreed to in writing, software\r\n# distributed under the License is distributed on an \"AS IS\" BASIS,\r\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n# See the License for the specific language governing permissions and\r\n# limitations under the License.\r\n\"\"\"Code for the adjoint transform.\"\"\"\r\n\r\nfrom functools import wraps\r\nfrom pennylane.tape import QuantumTape, stop_recording\r\n\r\n\r\ndef adjoint(fn):\r\n \"\"\"Create a function that applies the adjoint (inverse) of the provided operation or template.\r\n\r\n This transform can be used to apply the adjoint of an arbitrary sequence of operations.\r\n\r\n Args:\r\n fn (function): A quantum function that applies quantum operations.\r\n\r\n Returns:\r\n function: A new function that will apply the same operations but adjointed and in reverse order.\r\n\r\n **Example**\r\n\r\n The adjoint transforms can be used within a QNode to apply the adjoint of\r\n any quantum function. Consider the following quantum function, that applies two\r\n operations:\r\n\r\n .. code-block:: python3\r\n\r\n def my_ops(a, b, wire):\r\n qml.RX(a, wires=wire)\r\n qml.RY(b, wires=wire)\r\n\r\n We can create a QNode that applies this quantum function,\r\n followed by the adjoint of this function:\r\n\r\n .. code-block:: python3\r\n\r\n dev = qml.device('default.qubit', wires=1)\r\n\r\n @qml.qnode(dev)\r\n def circuit(a, b):\r\n my_ops(a, b, wire=0)\r\n qml.adjoint(my_ops)(a, b, wire=0)\r\n return qml.expval(qml.PauliZ(0))\r\n\r\n Printing this out, we can see that the inverse quantum\r\n function has indeed been applied:\r\n\r\n >>> print(qml.draw(circuit)(0.2, 0.5))\r\n 0: \u2500\u2500RX(0.2)\u2500\u2500RY(0.5)\u2500\u2500RY(-0.5)\u2500\u2500RX(-0.2)\u2500\u2500\u2524 \u27e8Z\u27e9\r\n\r\n The adjoint function can also be applied directly to templates and operations:\r\n\r\n >>> qml.adjoint(qml.RX)(0.123, wires=0)\r\n >>> qml.adjoint(qml.templates.StronglyEntanglingLayers)(weights, wires=[0, 1])\r\n\r\n .. UsageDetails::\r\n\r\n **Adjoint of a function**\r\n\r\n Here, we apply the ``subroutine`` function, and then apply its inverse.\r\n Notice that in addition to adjointing all of the operations, they are also\r\n applied in reverse construction order.\r\n\r\n .. code-block:: python3\r\n\r\n def subroutine(wire):\r\n qml.RX(0.123, wires=wire)\r\n qml.RY(0.456, wires=wire)\r\n\r\n dev = qml.device('default.qubit', wires=1)\r\n @qml.qnode(dev)\r\n def circuit():\r\n subroutine(0)\r\n qml.adjoint(subroutine)(0)\r\n return qml.expval(qml.PauliZ(0))\r\n\r\n This creates the following circuit:\r\n\r\n >>> print(qml.draw(circuit)())\r\n 0: --RX(0.123)--RY(0.456)--RY(-0.456)--RX(-0.123)--| <Z>\r\n\r\n **Single operation**\r\n\r\n You can also easily adjoint a single operation just by wrapping it with ``adjoint``:\r\n\r\n .. code-block:: python3\r\n\r\n dev = qml.device('default.qubit', wires=1)\r\n @qml.qnode(dev)\r\n def circuit():\r\n qml.RX(0.123, wires=0)\r\n qml.adjoint(qml.RX)(0.123, wires=0)\r\n return qml.expval(qml.PauliZ(0))\r\n\r\n This creates the following circuit:\r\n\r\n >>> print(qml.draw(circuit)())\r\n 0: --RX(0.123)--RX(-0.123)--| <Z>\r\n \"\"\"\r\n\r\n @wraps(fn)\r\n def wrapper(*args, **kwargs):\r\n with stop_recording(), QuantumTape() as tape:\r\n fn(*args, **kwargs)\r\n\r\n if not tape.operations:\r\n # we called op.expand(): get the outputted tape\r\n tape = fn(*args, **kwargs)\r\n\r\n adjoint_ops = []\r\n for op in reversed(tape.operations):\r\n try:\r\n new_op = op.adjoint()\r\n adjoint_ops.append(new_op)\r\n except NotImplementedError:\r\n # Expand the operation and adjoint the result.\r\n new_ops = adjoint(op.expand)()\r\n\r\n if isinstance(new_ops, QuantumTape):\r\n new_ops = new_ops.operations\r\n\r\n adjoint_ops.extend(new_ops)\r\n\r\n if len(adjoint_ops) == 1:\r\n adjoint_ops = adjoint_ops[0]\r\n\r\n return adjoint_ops\r\n\r\n return wrapper\r\n", "path": "pennylane/transforms/adjoint.py"}], "after_files": [{"content": "# Copyright 2018-2021 Xanadu Quantum Technologies Inc.\r\n\r\n# Licensed under the Apache License, Version 2.0 (the \"License\");\r\n# you may not use this file except in compliance with the License.\r\n# You may obtain a copy of the License at\r\n\r\n# http://www.apache.org/licenses/LICENSE-2.0\r\n\r\n# Unless required by applicable law or agreed to in writing, software\r\n# distributed under the License is distributed on an \"AS IS\" BASIS,\r\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n# See the License for the specific language governing permissions and\r\n# limitations under the License.\r\n\"\"\"Code for the adjoint transform.\"\"\"\r\n\r\nfrom functools import wraps\r\nfrom pennylane.tape import QuantumTape, stop_recording\r\n\r\n\r\ndef adjoint(fn):\r\n \"\"\"Create a function that applies the adjoint (inverse) of the provided operation or template.\r\n\r\n This transform can be used to apply the adjoint of an arbitrary sequence of operations.\r\n\r\n Args:\r\n fn (function): A quantum function that applies quantum operations.\r\n\r\n Returns:\r\n function: A new function that will apply the same operations but adjointed and in reverse order.\r\n\r\n **Example**\r\n\r\n The adjoint transforms can be used within a QNode to apply the adjoint of\r\n any quantum function. Consider the following quantum function, that applies two\r\n operations:\r\n\r\n .. code-block:: python3\r\n\r\n def my_ops(a, b, wire):\r\n qml.RX(a, wires=wire)\r\n qml.RY(b, wires=wire)\r\n\r\n We can create a QNode that applies this quantum function,\r\n followed by the adjoint of this function:\r\n\r\n .. code-block:: python3\r\n\r\n dev = qml.device('default.qubit', wires=1)\r\n\r\n @qml.qnode(dev)\r\n def circuit(a, b):\r\n my_ops(a, b, wire=0)\r\n qml.adjoint(my_ops)(a, b, wire=0)\r\n return qml.expval(qml.PauliZ(0))\r\n\r\n Printing this out, we can see that the inverse quantum\r\n function has indeed been applied:\r\n\r\n >>> print(qml.draw(circuit)(0.2, 0.5))\r\n 0: \u2500\u2500RX(0.2)\u2500\u2500RY(0.5)\u2500\u2500RY(-0.5)\u2500\u2500RX(-0.2)\u2500\u2500\u2524 \u27e8Z\u27e9\r\n\r\n The adjoint function can also be applied directly to templates and operations:\r\n\r\n >>> qml.adjoint(qml.RX)(0.123, wires=0)\r\n >>> qml.adjoint(qml.templates.StronglyEntanglingLayers)(weights, wires=[0, 1])\r\n\r\n .. UsageDetails::\r\n\r\n **Adjoint of a function**\r\n\r\n Here, we apply the ``subroutine`` function, and then apply its inverse.\r\n Notice that in addition to adjointing all of the operations, they are also\r\n applied in reverse construction order.\r\n\r\n .. code-block:: python3\r\n\r\n def subroutine(wire):\r\n qml.RX(0.123, wires=wire)\r\n qml.RY(0.456, wires=wire)\r\n\r\n dev = qml.device('default.qubit', wires=1)\r\n @qml.qnode(dev)\r\n def circuit():\r\n subroutine(0)\r\n qml.adjoint(subroutine)(0)\r\n return qml.expval(qml.PauliZ(0))\r\n\r\n This creates the following circuit:\r\n\r\n >>> print(qml.draw(circuit)())\r\n 0: --RX(0.123)--RY(0.456)--RY(-0.456)--RX(-0.123)--| <Z>\r\n\r\n **Single operation**\r\n\r\n You can also easily adjoint a single operation just by wrapping it with ``adjoint``:\r\n\r\n .. code-block:: python3\r\n\r\n dev = qml.device('default.qubit', wires=1)\r\n @qml.qnode(dev)\r\n def circuit():\r\n qml.RX(0.123, wires=0)\r\n qml.adjoint(qml.RX)(0.123, wires=0)\r\n return qml.expval(qml.PauliZ(0))\r\n\r\n This creates the following circuit:\r\n\r\n >>> print(qml.draw(circuit)())\r\n 0: --RX(0.123)--RX(-0.123)--| <Z>\r\n \"\"\"\r\n if not callable(fn):\r\n raise ValueError(\r\n f\"The object {fn} of type {type(fn)} is not callable. \"\r\n \"This error might occur if you apply adjoint to a list \"\r\n \"of operations instead of a function or template.\"\r\n )\r\n\r\n @wraps(fn)\r\n def wrapper(*args, **kwargs):\r\n with stop_recording(), QuantumTape() as tape:\r\n fn(*args, **kwargs)\r\n\r\n if not tape.operations:\r\n # we called op.expand(): get the outputted tape\r\n tape = fn(*args, **kwargs)\r\n\r\n adjoint_ops = []\r\n for op in reversed(tape.operations):\r\n try:\r\n new_op = op.adjoint()\r\n adjoint_ops.append(new_op)\r\n except NotImplementedError:\r\n # Expand the operation and adjoint the result.\r\n new_ops = adjoint(op.expand)()\r\n\r\n if isinstance(new_ops, QuantumTape):\r\n new_ops = new_ops.operations\r\n\r\n adjoint_ops.extend(new_ops)\r\n\r\n if len(adjoint_ops) == 1:\r\n adjoint_ops = adjoint_ops[0]\r\n\r\n return adjoint_ops\r\n\r\n return wrapper\r\n", "path": "pennylane/transforms/adjoint.py"}]} | 1,883 | 182 |
gh_patches_debug_19776 | rasdani/github-patches | git_diff | azavea__raster-vision-1484 | We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Local runner should write makefile to temporary dir
Instead, it writes it to the `root_uri` which might be an S3 URI, and `make`, which is used by the local runner cannot handle that.
Makefile error when `root_uri` is an S3 path
## 🐛 Bug
When running training command and having `root_uri` set to an S3 folder, this error shows up:
```
make: s3://<random_bucket_name>/predictions/Makefile: No such file or directory
make: *** No rule to make target 's3://<random_bucket_name>/predictions/Makefile'. Stop.
```
This error disappears when `root_uri` is a local path. AWS config is right as it is able to read and write the files.
## To Reproduce
Steps to reproduce the behavior:
1. I ran the following command inside the container:
`python -m rastervision.pipeline.cli run local code/local_exp.py -a raw_uri s3://<random_bucket_name>/datafortesting/data/ -a root_uri s3://<random_bucket_name>/predictions -a test False`
<!-- Please provide the command executed, source of the get_config() function, error messages, and/or full stack traces if at all possible -->
## Expected behavior
It should run normally like it is running when `root_uri` is a local path.
## Environment
Running with docker. **Image**: quay.io/azavea/raster-vision:pytorch-v0.13.1
## Additional context
This might be a relevant issue: #991
--- END ISSUE ---
Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `rastervision_pipeline/rastervision/pipeline/runner/local_runner.py`
Content:
```
1 import sys
2 from os.path import dirname, join
3 from subprocess import Popen
4
5 from rastervision.pipeline.file_system import str_to_file
6 from rastervision.pipeline.runner.runner import Runner
7 from rastervision.pipeline.utils import terminate_at_exit
8
9 LOCAL = 'local'
10
11
12 class LocalRunner(Runner):
13 """Runs each command locally using different processes for each command/split.
14
15 This is implemented by generating a Makefile and then running it using make.
16 """
17
18 def run(self,
19 cfg_json_uri,
20 pipeline,
21 commands,
22 num_splits=1,
23 pipeline_run_name: str = 'raster-vision'):
24 num_commands = 0
25 for command in commands:
26 if command in pipeline.split_commands and num_splits > 1:
27 num_commands += num_splits
28 else:
29 num_commands += 1
30
31 makefile = '.PHONY: '
32 makefile += ' '.join([str(ci) for ci in range(num_commands)])
33 makefile += '\n\n'
34
35 makefile += 'all: '
36 makefile += ' '.join([str(ci) for ci in range(num_commands)])
37 makefile += '\n\n'
38
39 prev_command_inds = []
40 curr_command_ind = 0
41 for command in commands:
42
43 curr_command_inds = []
44 if command in pipeline.split_commands and num_splits > 1:
45 for split_ind in range(num_splits):
46 makefile += '{}: '.format(curr_command_ind)
47 makefile += ' '.join([str(ci) for ci in prev_command_inds])
48 makefile += '\n'
49 invocation = (
50 'python -m rastervision.pipeline.cli run_command '
51 '{} {} --split-ind {} --num-splits {}').format(
52 cfg_json_uri, command, split_ind, num_splits)
53 makefile += '\t{}\n\n'.format(invocation)
54 curr_command_inds.append(curr_command_ind)
55 curr_command_ind += 1
56 else:
57 makefile += '{}: '.format(curr_command_ind)
58 makefile += ' '.join([str(ci) for ci in prev_command_inds])
59 makefile += '\n'
60 invocation = (
61 'python -m rastervision.pipeline.cli run_command '
62 '{} {}'.format(cfg_json_uri, command))
63 makefile += '\t{}\n\n'.format(invocation)
64 curr_command_inds.append(curr_command_ind)
65 curr_command_ind += 1
66
67 prev_command_inds = curr_command_inds
68
69 makefile_path = join(dirname(cfg_json_uri), 'Makefile')
70 str_to_file(makefile, makefile_path)
71 process = Popen(['make', '-j', '-f', makefile_path])
72 terminate_at_exit(process)
73 exitcode = process.wait()
74 if exitcode != 0:
75 sys.exit(exitcode)
76 else:
77 return 0
78
```
--- END FILES ---
Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.
Here is an example:
```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
if __name__ == "__main__":
- asyncio.run(run_async_server("."), debug=True)
+ asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
if __name__ == "__main__":
- server = run_sync_server(".")
+ server = run_sync_server()
server.shutdown()
```
| diff --git a/rastervision_pipeline/rastervision/pipeline/runner/local_runner.py b/rastervision_pipeline/rastervision/pipeline/runner/local_runner.py
--- a/rastervision_pipeline/rastervision/pipeline/runner/local_runner.py
+++ b/rastervision_pipeline/rastervision/pipeline/runner/local_runner.py
@@ -2,7 +2,7 @@
from os.path import dirname, join
from subprocess import Popen
-from rastervision.pipeline.file_system import str_to_file
+from rastervision.pipeline.file_system import str_to_file, download_if_needed
from rastervision.pipeline.runner.runner import Runner
from rastervision.pipeline.utils import terminate_at_exit
@@ -68,7 +68,8 @@
makefile_path = join(dirname(cfg_json_uri), 'Makefile')
str_to_file(makefile, makefile_path)
- process = Popen(['make', '-j', '-f', makefile_path])
+ makefile_path_local = download_if_needed(makefile_path)
+ process = Popen(['make', '-j', '-f', makefile_path_local])
terminate_at_exit(process)
exitcode = process.wait()
if exitcode != 0:
| {"golden_diff": "diff --git a/rastervision_pipeline/rastervision/pipeline/runner/local_runner.py b/rastervision_pipeline/rastervision/pipeline/runner/local_runner.py\n--- a/rastervision_pipeline/rastervision/pipeline/runner/local_runner.py\n+++ b/rastervision_pipeline/rastervision/pipeline/runner/local_runner.py\n@@ -2,7 +2,7 @@\n from os.path import dirname, join\n from subprocess import Popen\n \n-from rastervision.pipeline.file_system import str_to_file\n+from rastervision.pipeline.file_system import str_to_file, download_if_needed\n from rastervision.pipeline.runner.runner import Runner\n from rastervision.pipeline.utils import terminate_at_exit\n \n@@ -68,7 +68,8 @@\n \n makefile_path = join(dirname(cfg_json_uri), 'Makefile')\n str_to_file(makefile, makefile_path)\n- process = Popen(['make', '-j', '-f', makefile_path])\n+ makefile_path_local = download_if_needed(makefile_path)\n+ process = Popen(['make', '-j', '-f', makefile_path_local])\n terminate_at_exit(process)\n exitcode = process.wait()\n if exitcode != 0:\n", "issue": "Local runner should write makefile to temporary dir\nInstead, it writes it to the `root_uri` which might be an S3 URI, and `make`, which is used by the local runner cannot handle that.\nMakefile error when `root_uri` is an S3 path\n## \ud83d\udc1b Bug\r\nWhen running training command and having `root_uri` set to an S3 folder, this error shows up:\r\n```\r\nmake: s3://<random_bucket_name>/predictions/Makefile: No such file or directory\r\nmake: *** No rule to make target 's3://<random_bucket_name>/predictions/Makefile'. Stop.\r\n```\r\n\r\nThis error disappears when `root_uri` is a local path. AWS config is right as it is able to read and write the files.\r\n\r\n## To Reproduce\r\n\r\nSteps to reproduce the behavior:\r\n\r\n1. I ran the following command inside the container:\r\n`python -m rastervision.pipeline.cli run local code/local_exp.py -a raw_uri s3://<random_bucket_name>/datafortesting/data/ -a root_uri s3://<random_bucket_name>/predictions -a test False`\r\n\r\n<!-- Please provide the command executed, source of the get_config() function, error messages, and/or full stack traces if at all possible -->\r\n\r\n## Expected behavior\r\n\r\nIt should run normally like it is running when `root_uri` is a local path.\r\n\r\n## Environment\r\n\r\nRunning with docker. **Image**: quay.io/azavea/raster-vision:pytorch-v0.13.1\r\n\r\n## Additional context\r\n\r\nThis might be a relevant issue: #991 \r\n\n", "before_files": [{"content": "import sys\nfrom os.path import dirname, join\nfrom subprocess import Popen\n\nfrom rastervision.pipeline.file_system import str_to_file\nfrom rastervision.pipeline.runner.runner import Runner\nfrom rastervision.pipeline.utils import terminate_at_exit\n\nLOCAL = 'local'\n\n\nclass LocalRunner(Runner):\n \"\"\"Runs each command locally using different processes for each command/split.\n\n This is implemented by generating a Makefile and then running it using make.\n \"\"\"\n\n def run(self,\n cfg_json_uri,\n pipeline,\n commands,\n num_splits=1,\n pipeline_run_name: str = 'raster-vision'):\n num_commands = 0\n for command in commands:\n if command in pipeline.split_commands and num_splits > 1:\n num_commands += num_splits\n else:\n num_commands += 1\n\n makefile = '.PHONY: '\n makefile += ' '.join([str(ci) for ci in range(num_commands)])\n makefile += '\\n\\n'\n\n makefile += 'all: '\n makefile += ' '.join([str(ci) for ci in range(num_commands)])\n makefile += '\\n\\n'\n\n prev_command_inds = []\n curr_command_ind = 0\n for command in commands:\n\n curr_command_inds = []\n if command in pipeline.split_commands and num_splits > 1:\n for split_ind in range(num_splits):\n makefile += '{}: '.format(curr_command_ind)\n makefile += ' '.join([str(ci) for ci in prev_command_inds])\n makefile += '\\n'\n invocation = (\n 'python -m rastervision.pipeline.cli run_command '\n '{} {} --split-ind {} --num-splits {}').format(\n cfg_json_uri, command, split_ind, num_splits)\n makefile += '\\t{}\\n\\n'.format(invocation)\n curr_command_inds.append(curr_command_ind)\n curr_command_ind += 1\n else:\n makefile += '{}: '.format(curr_command_ind)\n makefile += ' '.join([str(ci) for ci in prev_command_inds])\n makefile += '\\n'\n invocation = (\n 'python -m rastervision.pipeline.cli run_command '\n '{} {}'.format(cfg_json_uri, command))\n makefile += '\\t{}\\n\\n'.format(invocation)\n curr_command_inds.append(curr_command_ind)\n curr_command_ind += 1\n\n prev_command_inds = curr_command_inds\n\n makefile_path = join(dirname(cfg_json_uri), 'Makefile')\n str_to_file(makefile, makefile_path)\n process = Popen(['make', '-j', '-f', makefile_path])\n terminate_at_exit(process)\n exitcode = process.wait()\n if exitcode != 0:\n sys.exit(exitcode)\n else:\n return 0\n", "path": "rastervision_pipeline/rastervision/pipeline/runner/local_runner.py"}], "after_files": [{"content": "import sys\nfrom os.path import dirname, join\nfrom subprocess import Popen\n\nfrom rastervision.pipeline.file_system import str_to_file, download_if_needed\nfrom rastervision.pipeline.runner.runner import Runner\nfrom rastervision.pipeline.utils import terminate_at_exit\n\nLOCAL = 'local'\n\n\nclass LocalRunner(Runner):\n \"\"\"Runs each command locally using different processes for each command/split.\n\n This is implemented by generating a Makefile and then running it using make.\n \"\"\"\n\n def run(self,\n cfg_json_uri,\n pipeline,\n commands,\n num_splits=1,\n pipeline_run_name: str = 'raster-vision'):\n num_commands = 0\n for command in commands:\n if command in pipeline.split_commands and num_splits > 1:\n num_commands += num_splits\n else:\n num_commands += 1\n\n makefile = '.PHONY: '\n makefile += ' '.join([str(ci) for ci in range(num_commands)])\n makefile += '\\n\\n'\n\n makefile += 'all: '\n makefile += ' '.join([str(ci) for ci in range(num_commands)])\n makefile += '\\n\\n'\n\n prev_command_inds = []\n curr_command_ind = 0\n for command in commands:\n\n curr_command_inds = []\n if command in pipeline.split_commands and num_splits > 1:\n for split_ind in range(num_splits):\n makefile += '{}: '.format(curr_command_ind)\n makefile += ' '.join([str(ci) for ci in prev_command_inds])\n makefile += '\\n'\n invocation = (\n 'python -m rastervision.pipeline.cli run_command '\n '{} {} --split-ind {} --num-splits {}').format(\n cfg_json_uri, command, split_ind, num_splits)\n makefile += '\\t{}\\n\\n'.format(invocation)\n curr_command_inds.append(curr_command_ind)\n curr_command_ind += 1\n else:\n makefile += '{}: '.format(curr_command_ind)\n makefile += ' '.join([str(ci) for ci in prev_command_inds])\n makefile += '\\n'\n invocation = (\n 'python -m rastervision.pipeline.cli run_command '\n '{} {}'.format(cfg_json_uri, command))\n makefile += '\\t{}\\n\\n'.format(invocation)\n curr_command_inds.append(curr_command_ind)\n curr_command_ind += 1\n\n prev_command_inds = curr_command_inds\n\n makefile_path = join(dirname(cfg_json_uri), 'Makefile')\n str_to_file(makefile, makefile_path)\n makefile_path_local = download_if_needed(makefile_path)\n process = Popen(['make', '-j', '-f', makefile_path_local])\n terminate_at_exit(process)\n exitcode = process.wait()\n if exitcode != 0:\n sys.exit(exitcode)\n else:\n return 0\n", "path": "rastervision_pipeline/rastervision/pipeline/runner/local_runner.py"}]} | 1,363 | 267 |
End of preview. Expand
in Data Studio
README.md exists but content is empty.
- Downloads last month
- 78