Benchanything commited on
Commit
8247f19
·
verified ·
1 Parent(s): 62cfde8

Add 300 CheckerBench tasks, dataset card, and restoration tools (part 3)

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. tasks/codeql_python_benchmark51_v2/pyvul-1a630dd8f83b2e29740d/pre_context.md +24 -0
  2. tasks/codeql_python_benchmark51_v2/pyvul-1a630dd8f83b2e29740d/task.json +44 -0
  3. tasks/codeql_python_benchmark51_v2/pyvul-1a630dd8f83b2e29740d/task_prompt.md +82 -0
  4. tasks/codeql_python_benchmark51_v2/pyvul-1f5068a3fe5ca0192a07/patch.diff +168 -0
  5. tasks/codeql_python_benchmark51_v2/pyvul-1f5068a3fe5ca0192a07/post_context.md +1823 -0
  6. tasks/codeql_python_benchmark51_v2/pyvul-1f5068a3fe5ca0192a07/pre_context.md +1755 -0
  7. tasks/codeql_python_benchmark51_v2/pyvul-1f5068a3fe5ca0192a07/task.json +71 -0
  8. tasks/codeql_python_benchmark51_v2/pyvul-1f5068a3fe5ca0192a07/task_prompt.md +82 -0
  9. tasks/codeql_python_benchmark51_v2/pyvul-2ab65d62986b80922362/patch.diff +60 -0
  10. tasks/codeql_python_benchmark51_v2/pyvul-2ab65d62986b80922362/post_context.md +64 -0
  11. tasks/codeql_python_benchmark51_v2/pyvul-2ab65d62986b80922362/pre_context.md +59 -0
  12. tasks/codeql_python_benchmark51_v2/pyvul-2ab65d62986b80922362/task.json +46 -0
  13. tasks/codeql_python_benchmark51_v2/pyvul-2ab65d62986b80922362/task_prompt.md +82 -0
  14. tasks/codeql_python_benchmark51_v2/pyvul-3062589ff0b3b95c2ed7/patch.diff +33 -0
  15. tasks/codeql_python_benchmark51_v2/pyvul-3062589ff0b3b95c2ed7/post_context.md +17 -0
  16. tasks/codeql_python_benchmark51_v2/pyvul-3062589ff0b3b95c2ed7/pre_context.md +23 -0
  17. tasks/codeql_python_benchmark51_v2/pyvul-3062589ff0b3b95c2ed7/task.json +47 -0
  18. tasks/codeql_python_benchmark51_v2/pyvul-3062589ff0b3b95c2ed7/task_prompt.md +82 -0
  19. tasks/codeql_python_benchmark51_v2/pyvul-3187445bcbbf39128a26/patch.diff +39 -0
  20. tasks/codeql_python_benchmark51_v2/pyvul-3187445bcbbf39128a26/post_context.md +244 -0
  21. tasks/codeql_python_benchmark51_v2/pyvul-3187445bcbbf39128a26/pre_context.md +244 -0
  22. tasks/codeql_python_benchmark51_v2/pyvul-3187445bcbbf39128a26/task.json +49 -0
  23. tasks/codeql_python_benchmark51_v2/pyvul-3187445bcbbf39128a26/task_prompt.md +82 -0
  24. tasks/codeql_python_benchmark51_v2/pyvul-36a40541d7c74a9a7777/patch.diff +39 -0
  25. tasks/codeql_python_benchmark51_v2/pyvul-36a40541d7c74a9a7777/post_context.md +40 -0
  26. tasks/codeql_python_benchmark51_v2/pyvul-36a40541d7c74a9a7777/pre_context.md +40 -0
  27. tasks/codeql_python_benchmark51_v2/pyvul-36a40541d7c74a9a7777/task.json +46 -0
  28. tasks/codeql_python_benchmark51_v2/pyvul-36a40541d7c74a9a7777/task_prompt.md +82 -0
  29. tasks/codeql_python_benchmark51_v2/pyvul-3819b1a7530257524a75/patch.diff +32 -0
  30. tasks/codeql_python_benchmark51_v2/pyvul-3819b1a7530257524a75/post_context.md +130 -0
  31. tasks/codeql_python_benchmark51_v2/pyvul-3819b1a7530257524a75/pre_context.md +128 -0
  32. tasks/codeql_python_benchmark51_v2/pyvul-3819b1a7530257524a75/task.json +50 -0
  33. tasks/codeql_python_benchmark51_v2/pyvul-3819b1a7530257524a75/task_prompt.md +82 -0
  34. tasks/codeql_python_benchmark51_v2/pyvul-394adf7b067d96b356ca/patch.diff +53 -0
  35. tasks/codeql_python_benchmark51_v2/pyvul-394adf7b067d96b356ca/post_context.md +314 -0
  36. tasks/codeql_python_benchmark51_v2/pyvul-394adf7b067d96b356ca/pre_context.md +280 -0
  37. tasks/codeql_python_benchmark51_v2/pyvul-394adf7b067d96b356ca/task.json +51 -0
  38. tasks/codeql_python_benchmark51_v2/pyvul-394adf7b067d96b356ca/task_prompt.md +82 -0
  39. tasks/codeql_python_benchmark51_v2/pyvul-3994e3622b21c396ef8a/patch.diff +912 -0
  40. tasks/codeql_python_benchmark51_v2/pyvul-3994e3622b21c396ef8a/post_context.md +140 -0
  41. tasks/codeql_python_benchmark51_v2/pyvul-3994e3622b21c396ef8a/pre_context.md +145 -0
  42. tasks/codeql_python_benchmark51_v2/pyvul-3994e3622b21c396ef8a/task.json +57 -0
  43. tasks/codeql_python_benchmark51_v2/pyvul-3994e3622b21c396ef8a/task_prompt.md +82 -0
  44. tasks/codeql_python_benchmark51_v2/pyvul-4954e5890cce23c8b03d/patch.diff +80 -0
  45. tasks/codeql_python_benchmark51_v2/pyvul-4954e5890cce23c8b03d/post_context.md +1683 -0
  46. tasks/codeql_python_benchmark51_v2/pyvul-4954e5890cce23c8b03d/pre_context.md +1668 -0
  47. tasks/codeql_python_benchmark51_v2/pyvul-4954e5890cce23c8b03d/task.json +59 -0
  48. tasks/codeql_python_benchmark51_v2/pyvul-4954e5890cce23c8b03d/task_prompt.md +82 -0
  49. tasks/codeql_python_benchmark51_v2/pyvul-4ac3440b9023e6511a91/patch.diff +184 -0
  50. tasks/codeql_python_benchmark51_v2/pyvul-4ac3440b9023e6511a91/post_context.md +169 -0
tasks/codeql_python_benchmark51_v2/pyvul-1a630dd8f83b2e29740d/pre_context.md ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Patch-overlapping Python context before the fix
2
+
3
+ ## `mlflow/utils/file_utils.py` — `function:make_tarfile` (lines 284-301)
4
+
5
+ ```python
6
+ def make_tarfile(output_filename, source_dir, archive_name, custom_filter=None):
7
+ # Helper for filtering out modification timestamps
8
+ def _filter_timestamps(tar_info):
9
+ tar_info.mtime = 0
10
+ return tar_info if custom_filter is None else custom_filter(tar_info)
11
+
12
+ unzipped_filename = tempfile.mktemp()
13
+ try:
14
+ with tarfile.open(unzipped_filename, "w") as tar:
15
+ tar.add(source_dir, arcname=archive_name, filter=_filter_timestamps)
16
+ # When gzipping the tar, don't include the tar's filename or modification time in the
17
+ # zipped archive (see https://docs.python.org/3/library/gzip.html#gzip.GzipFile)
18
+ with gzip.GzipFile(
19
+ filename="", fileobj=open(output_filename, "wb"), mode="wb", mtime=0
20
+ ) as gzipped_tar, open(unzipped_filename, "rb") as tar:
21
+ gzipped_tar.write(tar.read())
22
+ finally:
23
+ os.remove(unzipped_filename)
24
+ ```
tasks/codeql_python_benchmark51_v2/pyvul-1a630dd8f83b2e29740d/task.json ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "schema_version": "synthesis-task-v1",
3
+ "task": {
4
+ "pair_id": "pyvul-1a630dd8f83b2e29740d",
5
+ "dataset_id": "PyVul",
6
+ "dataset_item_id": "pyvul-1a630dd8f83b2e29740d",
7
+ "project_id": "pyvul__mlflow__mlflow",
8
+ "language": "python",
9
+ "backend": "codeql"
10
+ },
11
+ "changed_python_files": [
12
+ "mlflow/utils/file_utils.py"
13
+ ],
14
+ "patch_units": {
15
+ "before": [
16
+ "function:make_tarfile"
17
+ ],
18
+ "after": [
19
+ "function:make_tarfile"
20
+ ]
21
+ },
22
+ "runtime_assets": {
23
+ "before": {
24
+ "database": "assets/19fa596228b1fb4b86e469be665edd7d7dbeb9b0b3686da07895004356b280c4/database",
25
+ "cache_key": "19fa596228b1fb4b86e469be665edd7d7dbeb9b0b3686da07895004356b280c4",
26
+ "codeql_version": "2.26.4"
27
+ },
28
+ "after": {
29
+ "database": "assets/6542ed4eb6001d9e9ca948df5dfeebb2e57bc60e826ac0604d9041b761dd7fcf/database",
30
+ "cache_key": "6542ed4eb6001d9e9ca948df5dfeebb2e57bc60e826ac0604d9041b761dd7fcf",
31
+ "codeql_version": "2.26.4"
32
+ },
33
+ "refine": {
34
+ "database": "assets/f5ac0d40fec4af9c5fe47b810e939639e7cc56bf5fc589efd3262e3aab0aae88/database",
35
+ "cache_key": "f5ac0d40fec4af9c5fe47b810e939639e7cc56bf5fc589efd3262e3aab0aae88",
36
+ "codeql_version": "2.26.4"
37
+ }
38
+ },
39
+ "benchmark_contract": {
40
+ "agent_visible": true,
41
+ "reference_query_location": "references/pyvul-1a630dd8f83b2e29740d/query/ (do not mount into agent)",
42
+ "evaluator_location": "evaluator/pyvul-1a630dd8f83b2e29740d/ (do not mount into agent)"
43
+ }
44
+ }
tasks/codeql_python_benchmark51_v2/pyvul-1a630dd8f83b2e29740d/task_prompt.md ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Python CodeQL detector synthesis
2
+
3
+ You are cc operating in `/work`. Starting only from the supplied patch,
4
+ before/after Python context, CodeQL references, and validation tools, synthesize a semantic CodeQL
5
+ detector for the vulnerability fixed by the patch. This is one fresh session. You may iterate inside
6
+ this session, but no later framework repair or resume will occur.
7
+
8
+ ## Inputs and owned outputs
9
+
10
+ - Read `patch.diff`, `python_patch.diff`, `pre_context.md`, and `post_context.md`.
11
+ - Read `references/codeql/convergence_protocol.md` and
12
+ `references/codeql/api_navigation.md` before experimenting. Read the remaining
13
+ `references/codeql/` files for the selected mechanism.
14
+ - Use `scripts/search_codeql_api.sh` to inspect the pinned official libraries when an API detail is
15
+ uncertain. Do not guess predicate names or build a large family of inspection queries.
16
+ - Complete the design contract in `state.json` and `scope_statement.md` before final validation.
17
+ - Replace `query/vulnerability.ql`; add only genuinely shared `.qll` helpers when useful. Keep the
18
+ fixed offline dependency in `query/qlpack.yml`.
19
+ - Preserve the exact `expected_query_id` from `config.json` as the query's sole `@id`. This
20
+ task-unique metadata must never be used in a query predicate.
21
+ - Use `scripts/compile_query.sh`, `scripts/run_before.sh`, and `scripts/run_after.sh`.
22
+ - Finish by writing `summary.json` with `status`, `query_path`, `query_kind`, `build_passed`,
23
+ `before_findings`, `after_findings`, `validation_completed`, and a concise `notes` field.
24
+
25
+ ## Required reasoning contract
26
+
27
+ Before coding, record this mapping in `state.json`:
28
+
29
+ ```text
30
+ vulnerable operation / trigger / patch safety condition
31
+ → CodeQL-observable evidence
32
+ → syntax, control-flow, local value-flow, global taint/value-flow, or interprocedural mechanism
33
+ → source, sink/report site, guard/barrier and query predicates
34
+ ```
35
+
36
+ Choose the lowest mechanism that can actually prove the condition. Guard-sensitive patches require
37
+ real path/control-flow semantics; provenance-sensitive patches require value flow. Do not replace
38
+ either with source-text matching or with the mere presence of patch-added syntax.
39
+
40
+ ## Mandatory convergence contract
41
+
42
+ The rollout has a 30-minute hard wall-clock ceiling and must be finalized by minute 27. Minutes
43
+ 27–30 are an emergency shutdown buffer, not exploration time. A sophisticated unfinished query is
44
+ a failure; an early compilable semantic candidate can be improved. Follow the checkpoints in
45
+ `references/codeql/convergence_protocol.md`:
46
+
47
+ 1. Record the mechanism contract, then replace the placeholder in `query/vulnerability.ql`
48
+ immediately. Do not wait until every CodeQL API detail is known.
49
+ 2. Use at most three distinct scratch `.ql` files. Prefer repeatedly editing one
50
+ `query/scratch.ql`. After two failed variants of one API assumption, inspect the exact bundled
51
+ definition with `scripts/search_codeql_api.sh` or simplify the mechanism.
52
+ 3. Obtain a compiling minimal main query before broadening it. Compile the main query after every
53
+ meaningful mechanism change.
54
+ 4. Move in order from compile → relevant before finding → after elimination → final contract. Do
55
+ not continue API exploration after the intended before/after differential is established.
56
+ 5. Run `scripts/check_progress.sh` at each checkpoint. It reports elapsed time, the minute-27
57
+ finalization deadline, and the minute-30 hard timeout. When it prints `finalize_now`, stop all
58
+ exploration, preserve the best compiling query, finish the contract files, and exit.
59
+
60
+ ## Semantic and generalization rules
61
+
62
+ - Report at the vulnerable call, operator, access, or sink.
63
+ - Do not use a patch-local path, line, commit hash, label, or local variable name as the primary
64
+ matching condition. Stable library/framework APIs or public project APIs are allowed only when
65
+ `scope_statement.md` explains why they define the intended vulnerability family.
66
+ - The safety condition introduced by the patch must be represented by the query.
67
+ - A lower after warning count is not enough: inspect SARIF and ensure at least one intended before
68
+ finding is in a patch-overlapping semantic unit and the corresponding finding disappears after.
69
+ - Avoid broad proxy queries that report an enclosing function or unrelated API merely because it
70
+ changed in the patch.
71
+
72
+ ## Final validation protocol
73
+
74
+ 1. Compile the final query.
75
+ 2. Run it on before and inspect `raw/before.sarif` for the intended report location.
76
+ 3. Run the identical query on after and inspect `raw/after.sarif`.
77
+ 4. Recheck query metadata, query kind/select signature, report locality, design-to-code consistency,
78
+ and absence of patch-local hardcoding.
79
+ 5. Update `state.json`, `scope_statement.md`, and write valid `summary.json`.
80
+
81
+ Do not modify the runtime databases, references, patch, context, or validation scripts except for
82
+ normal CodeQL-generated database caches produced by the provided run scripts.
tasks/codeql_python_benchmark51_v2/pyvul-1f5068a3fe5ca0192a07/patch.diff ADDED
@@ -0,0 +1,168 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ diff --git a/DESCRIPTION.md b/DESCRIPTION.md
2
+ index 5e6684a2..0f626e3a 100644
3
+ --- a/DESCRIPTION.md
4
+ +++ b/DESCRIPTION.md
5
+ @@ -11,6 +11,7 @@ Source code is also available at: https://github.com/snowflakedb/snowflake-conne
6
+ - v2.8.2(November 18,2022)
7
+
8
+ - Improved performance of OCSP response caching
9
+ + - Improved performance of regexes used for PUT/GET SQL statement detection
10
+
11
+ - v2.8.1(October 30,2022)
12
+
13
+ diff --git a/src/snowflake/connector/_sql_util.py b/src/snowflake/connector/_sql_util.py
14
+ new file mode 100644
15
+ index 00000000..51a9d090
16
+ --- /dev/null
17
+ +++ b/src/snowflake/connector/_sql_util.py
18
+ @@ -0,0 +1,52 @@
19
+ +#
20
+ +# Copyright (c) 2012-2021 Snowflake Computing Inc. All rights reserved.
21
+ +#
22
+ +
23
+ +from __future__ import annotations
24
+ +
25
+ +import re
26
+ +
27
+ +from .constants import FileTransferType
28
+ +
29
+ +COMMENT_START_SQL_RE = re.compile(
30
+ + r"""
31
+ + ^\s*(?:
32
+ + /\*[\w\W]*?\*/
33
+ + )""",
34
+ + re.VERBOSE,
35
+ +)
36
+ +
37
+ +PUT_SQL_RE = re.compile(r"^\s*put", flags=re.IGNORECASE)
38
+ +GET_SQL_RE = re.compile(r"^\s*get", flags=re.IGNORECASE)
39
+ +
40
+ +
41
+ +def remove_starting_comments(sql: str) -> str:
42
+ + """Remove all comments from the start of a SQL statement."""
43
+ + commentless_sql = sql
44
+ + while True:
45
+ + start_comment = COMMENT_START_SQL_RE.match(commentless_sql)
46
+ + if start_comment is None:
47
+ + break
48
+ + commentless_sql = commentless_sql[start_comment.end() :]
49
+ + return commentless_sql
50
+ +
51
+ +
52
+ +def get_file_transfer_type(sql: str) -> FileTransferType | None:
53
+ + """Decide whether a SQL is a file transfer and return its type.
54
+ +
55
+ + None is returned if the SQL isn't a file transfer so that this function can be
56
+ + used in an if-statement.
57
+ + """
58
+ + commentless_sql = remove_starting_comments(sql)
59
+ + if PUT_SQL_RE.match(commentless_sql):
60
+ + return FileTransferType.PUT
61
+ + elif GET_SQL_RE.match(commentless_sql):
62
+ + return FileTransferType.GET
63
+ +
64
+ +
65
+ +def is_put_statement(sql: str) -> bool:
66
+ + return get_file_transfer_type(sql) == FileTransferType.PUT
67
+ +
68
+ +
69
+ +def is_get_statement(sql: str) -> bool:
70
+ + return get_file_transfer_type(sql) == FileTransferType.GET
71
+ diff --git a/src/snowflake/connector/cursor.py b/src/snowflake/connector/cursor.py
72
+ index 2a8089b0..a367a987 100644
73
+ --- a/src/snowflake/connector/cursor.py
74
+ +++ b/src/snowflake/connector/cursor.py
75
+ @@ -32,6 +32,7 @@ from snowflake.connector.result_batch import create_batches_from_response
76
+ from snowflake.connector.result_set import ResultSet
77
+
78
+ from . import compat
79
+ +from ._sql_util import get_file_transfer_type
80
+ from .bind_upload_agent import BindUploadAgent, BindUploadError
81
+ from .constants import (
82
+ FIELD_NAME_TO_ID,
83
+ @@ -183,8 +184,6 @@ class SnowflakeCursor:
84
+ Calling a function is expensive in Python and most of these getters are unnecessary.
85
+ """
86
+
87
+ - PUT_SQL_RE = re.compile(r"^(?:/\*.*\*/\s*)*put\s+", flags=re.IGNORECASE)
88
+ - GET_SQL_RE = re.compile(r"^(?:/\*.*\*/\s*)*get\s+", flags=re.IGNORECASE)
89
+ INSERT_SQL_RE = re.compile(r"^insert\s+into", flags=re.IGNORECASE)
90
+ COMMENT_SQL_RE = re.compile(r"/\*.*\*/")
91
+ INSERT_SQL_VALUES_RE = re.compile(
92
+ @@ -202,11 +201,7 @@ class SnowflakeCursor:
93
+ None is returned if the SQL isn't a file transfer so that this function can be
94
+ used in an if-statement.
95
+ """
96
+ - if SnowflakeCursor.PUT_SQL_RE.match(sql):
97
+ - return FileTransferType.PUT
98
+ - elif SnowflakeCursor.GET_SQL_RE.match(sql):
99
+ - return FileTransferType.GET
100
+ - return None
101
+ + return get_file_transfer_type(sql)
102
+
103
+ def __init__(
104
+ self,
105
+ @@ -464,9 +459,7 @@ class SnowflakeCursor:
106
+ self._is_file_transfer = _is_put_get
107
+ else:
108
+ # or detect it.
109
+ - self._is_file_transfer = self.PUT_SQL_RE.match(
110
+ - query
111
+ - ) or self.GET_SQL_RE.match(query)
112
+ + self._is_file_transfer = get_file_transfer_type(query) is not None
113
+ logger.debug("is_file_transfer: %s", self._is_file_transfer is not None)
114
+
115
+ real_timeout = (
116
+ diff --git a/src/snowflake/connector/gcs_storage_client.py b/src/snowflake/connector/gcs_storage_client.py
117
+ index b3709be3..e113e459 100644
118
+ --- a/src/snowflake/connector/gcs_storage_client.py
119
+ +++ b/src/snowflake/connector/gcs_storage_client.py
120
+ @@ -10,6 +10,7 @@ import os
121
+ from logging import getLogger
122
+ from typing import TYPE_CHECKING, Any, NamedTuple
123
+
124
+ +from ._sql_util import is_put_statement
125
+ from .compat import quote
126
+ from .constants import (
127
+ FILE_PROTOCOL,
128
+ @@ -269,9 +270,7 @@ class SnowflakeGCSRestClient(SnowflakeStorageClient):
129
+ The local file path.
130
+ """
131
+ command = self._command
132
+ - if FILE_PROTOCOL not in self._command or not self._cursor.PUT_SQL_RE.match(
133
+ - command
134
+ - ):
135
+ + if FILE_PROTOCOL not in self._command or not is_put_statement(command):
136
+ return None
137
+
138
+ file_path_begin_index = command.find(FILE_PROTOCOL)
139
+ diff --git a/test/unit/test_cursor.py b/test/unit/test_cursor.py
140
+ index 37c118c1..bc43a559 100644
141
+ --- a/test/unit/test_cursor.py
142
+ +++ b/test/unit/test_cursor.py
143
+ @@ -27,9 +27,24 @@ class FakeConnection(SnowflakeConnection):
144
+ @pytest.mark.parametrize(
145
+ "sql,_type",
146
+ (
147
+ + ("", None),
148
+ + ("select 1;", None),
149
+ ("PUT file:///tmp/data/mydata.csv @my_int_stage;", FileTransferType.PUT),
150
+ ("GET @%mytable file:///tmp/data/;", FileTransferType.GET),
151
+ - ("select 1;", None),
152
+ + ("/**/PUT file:///tmp/data/mydata.csv @my_int_stage;", FileTransferType.PUT),
153
+ + ("/**/ GET @%mytable file:///tmp/data/;", FileTransferType.GET),
154
+ + pytest.param(
155
+ + "/**/\n"
156
+ + + "\t/*/get\t*/\t/**/\n" * 10000
157
+ + + "\t*/get @~/test.csv file:///tmp\n",
158
+ + None,
159
+ + id="long_incorrect",
160
+ + ),
161
+ + pytest.param(
162
+ + "/**/\n" + "\t/*/put\t*/\t/**/\n" * 10000 + "put file:///tmp/data.csv @~",
163
+ + FileTransferType.PUT,
164
+ + id="long_correct",
165
+ + ),
166
+ ),
167
+ )
168
+ def test_get_filetransfer_type(sql, _type):
tasks/codeql_python_benchmark51_v2/pyvul-1f5068a3fe5ca0192a07/post_context.md ADDED
@@ -0,0 +1,1823 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Patch-overlapping Python context after the fix
2
+
3
+ ## `src/snowflake/connector/_sql_util.py` — `function:remove_starting_comments` (lines 23-31)
4
+
5
+ ```python
6
+ def remove_starting_comments(sql: str) -> str:
7
+ """Remove all comments from the start of a SQL statement."""
8
+ commentless_sql = sql
9
+ while True:
10
+ start_comment = COMMENT_START_SQL_RE.match(commentless_sql)
11
+ if start_comment is None:
12
+ break
13
+ commentless_sql = commentless_sql[start_comment.end() :]
14
+ return commentless_sql
15
+ ```
16
+
17
+ ## `src/snowflake/connector/_sql_util.py` — `function:get_file_transfer_type` (lines 34-44)
18
+
19
+ ```python
20
+ def get_file_transfer_type(sql: str) -> FileTransferType | None:
21
+ """Decide whether a SQL is a file transfer and return its type.
22
+
23
+ None is returned if the SQL isn't a file transfer so that this function can be
24
+ used in an if-statement.
25
+ """
26
+ commentless_sql = remove_starting_comments(sql)
27
+ if PUT_SQL_RE.match(commentless_sql):
28
+ return FileTransferType.PUT
29
+ elif GET_SQL_RE.match(commentless_sql):
30
+ return FileTransferType.GET
31
+ ```
32
+
33
+ ## `src/snowflake/connector/_sql_util.py` — `function:is_put_statement` (lines 47-48)
34
+
35
+ ```python
36
+ def is_put_statement(sql: str) -> bool:
37
+ return get_file_transfer_type(sql) == FileTransferType.PUT
38
+ ```
39
+
40
+ ## `src/snowflake/connector/_sql_util.py` — `function:is_get_statement` (lines 51-52)
41
+
42
+ ```python
43
+ def is_get_statement(sql: str) -> bool:
44
+ return get_file_transfer_type(sql) == FileTransferType.GET
45
+ ```
46
+
47
+ ## `src/snowflake/connector/_sql_util.py` — `module:<module>@5` (lines 5-5)
48
+
49
+ ```python
50
+ from __future__ import annotations
51
+ ```
52
+
53
+ ## `src/snowflake/connector/_sql_util.py` — `module:<module>@7` (lines 7-7)
54
+
55
+ ```python
56
+ import re
57
+ ```
58
+
59
+ ## `src/snowflake/connector/_sql_util.py` — `module:<module>@9` (lines 9-9)
60
+
61
+ ```python
62
+ from .constants import FileTransferType
63
+ ```
64
+
65
+ ## `src/snowflake/connector/_sql_util.py` — `module:<module>@11` (lines 11-17)
66
+
67
+ ```python
68
+ COMMENT_START_SQL_RE = re.compile(
69
+ r"""
70
+ ^\s*(?:
71
+ /\*[\w\W]*?\*/
72
+ )""",
73
+ re.VERBOSE,
74
+ )
75
+ ```
76
+
77
+ ## `src/snowflake/connector/_sql_util.py` — `module:<module>@19` (lines 19-19)
78
+
79
+ ```python
80
+ PUT_SQL_RE = re.compile(r"^\s*put", flags=re.IGNORECASE)
81
+ ```
82
+
83
+ ## `src/snowflake/connector/_sql_util.py` — `module:<module>@20` (lines 20-20)
84
+
85
+ ```python
86
+ GET_SQL_RE = re.compile(r"^\s*get", flags=re.IGNORECASE)
87
+ ```
88
+
89
+ ## `src/snowflake/connector/cursor.py` — `class:SnowflakeCursor` (lines 159-1301)
90
+
91
+ ```python
92
+ class SnowflakeCursor:
93
+ """Implementation of Cursor object that is returned from Connection.cursor() method.
94
+
95
+ Attributes:
96
+ description: A list of namedtuples about metadata for all columns.
97
+ rowcount: The number of records updated or selected. If not clear, -1 is returned.
98
+ rownumber: The current 0-based index of the cursor in the result set or None if the index cannot be
99
+ determined.
100
+ sfqid: Snowflake query id in UUID form. Include this in the problem report to the customer support.
101
+ sqlstate: Snowflake SQL State code.
102
+ timestamp_output_format: Snowflake timestamp_output_format for timestamps.
103
+ timestamp_ltz_output_format: Snowflake output format for LTZ timestamps.
104
+ timestamp_tz_output_format: Snowflake output format for TZ timestamps.
105
+ timestamp_ntz_output_format: Snowflake output format for NTZ timestamps.
106
+ date_output_format: Snowflake output format for dates.
107
+ time_output_format: Snowflake output format for times.
108
+ timezone: Snowflake timezone.
109
+ binary_output_format: Snowflake output format for binary fields.
110
+ arraysize: The default number of rows fetched by fetchmany.
111
+ connection: The connection object by which the cursor was created.
112
+ errorhandle: The class that handles error handling.
113
+ is_file_transfer: Whether, or not the current command is a put, or get.
114
+
115
+ TODO:
116
+ Most of these attributes have no reason to be properties, we could just store them in public variables.
117
+ Calling a function is expensive in Python and most of these getters are unnecessary.
118
+ """
119
+
120
+ INSERT_SQL_RE = re.compile(r"^insert\s+into", flags=re.IGNORECASE)
121
+ COMMENT_SQL_RE = re.compile(r"/\*.*\*/")
122
+ INSERT_SQL_VALUES_RE = re.compile(
123
+ r".*VALUES\s*(\(.*\)).*", re.IGNORECASE | re.MULTILINE | re.DOTALL
124
+ )
125
+ ALTER_SESSION_RE = re.compile(
126
+ r"alter\s+session\s+set\s+(.*)=\'?([^\']+)\'?\s*;",
127
+ flags=re.IGNORECASE | re.MULTILINE | re.DOTALL,
128
+ )
129
+
130
+ @staticmethod
131
+ def get_file_transfer_type(sql: str) -> FileTransferType | None:
132
+ """Decide whether a SQL is a file transfer and return its type.
133
+
134
+ None is returned if the SQL isn't a file transfer so that this function can be
135
+ used in an if-statement.
136
+ """
137
+ return get_file_transfer_type(sql)
138
+
139
+ def __init__(
140
+ self,
141
+ connection: SnowflakeConnection,
142
+ use_dict_result: bool = False,
143
+ ) -> None:
144
+ """Inits a SnowflakeCursor with a connection.
145
+
146
+ Args:
147
+ connection: The connection that created this cursor.
148
+ use_dict_result: Decides whether to use dict result or not.
149
+ """
150
+ self._connection: SnowflakeConnection = connection
151
+
152
+ self._errorhandler: Callable[
153
+ [SnowflakeConnection, SnowflakeCursor, type[Error], dict[str, str]],
154
+ None,
155
+ ] = Error.default_errorhandler
156
+ self.messages: list[
157
+ tuple[type[Error] | type[Exception], dict[str, str | bool]]
158
+ ] = []
159
+ self._timebomb: Timer | None = None # must be here for abort_exit method
160
+ self._description: list[ResultMetadata] | None = None
161
+ self._column_idx_to_name = None
162
+ self._sfqid = None
163
+ self._sqlstate = None
164
+ self._total_rowcount = -1
165
+ self._sequence_counter = -1
166
+ self._request_id = None
167
+ self._is_file_transfer = False
168
+
169
+ self._timestamp_output_format = None
170
+ self._timestamp_ltz_output_format = None
171
+ self._timestamp_ntz_output_format = None
172
+ self._timestamp_tz_output_format = None
173
+ self._date_output_format = None
174
+ self._time_output_format = None
175
+ self._timezone = None
176
+ self._binary_output_format = None
177
+ self._result: Iterator[tuple] | Iterator[dict] | None = None
178
+ self._result_set: ResultSet | None = None
179
+ self._result_state: ResultState = ResultState.DEFAULT
180
+ self._use_dict_result = use_dict_result
181
+ self.query: str | None = None
182
+ # TODO: self._query_result_format could be defined as an enum
183
+ self._query_result_format: str | None = None
184
+
185
+ self._arraysize = 1 # PEP-0249: defaults to 1
186
+
187
+ self._lock_canceling = Lock()
188
+
189
+ self._first_chunk_time = None
190
+
191
+ self._log_max_query_length = connection.log_max_query_length
192
+ self._inner_cursor: SnowflakeCursor | None = None
193
+ self._prefetch_hook = None
194
+ self._rownumber: int | None = None
195
+
196
+ self.reset()
197
+
198
+ def __del__(self) -> None: # pragma: no cover
199
+ try:
200
+ self.close()
201
+ except compat.BASE_EXCEPTION_CLASS as e:
202
+ if logger.getEffectiveLevel() <= logging.INFO:
203
+ logger.info(e)
204
+
205
+ @property
206
+ def description(self) -> list[ResultMetadata]:
207
+ return self._description
208
+
209
+ @property
210
+ def rowcount(self):
211
+ return self._total_rowcount if self._total_rowcount >= 0 else None
212
+
213
+ @property
214
+ def rownumber(self):
215
+ return self._rownumber if self._rownumber >= 0 else None
216
+
217
+ @property
218
+ def sfqid(self):
219
+ return self._sfqid
220
+
221
+ @property
222
+ def sqlstate(self):
223
+ return self._sqlstate
224
+
225
+ @property
226
+ def timestamp_output_format(self):
227
+ return self._timestamp_output_format
228
+
229
+ @property
230
+ def timestamp_ltz_output_format(self):
231
+ return (
232
+ self._timestamp_ltz_output_format
233
+ if self._timestamp_ltz_output_format
234
+ else self._timestamp_output_format
235
+ )
236
+
237
+ @property
238
+ def timestamp_tz_output_format(self):
239
+ return (
240
+ self._timestamp_tz_output_format
241
+ if self._timestamp_tz_output_format
242
+ else self._timestamp_output_format
243
+ )
244
+
245
+ @property
246
+ def timestamp_ntz_output_format(self):
247
+ return (
248
+ self._timestamp_ntz_output_format
249
+ if self._timestamp_ntz_output_format
250
+ else self._timestamp_output_format
251
+ )
252
+
253
+ @property
254
+ def date_output_format(self):
255
+ return self._date_output_format
256
+
257
+ @property
258
+ def time_output_format(self):
259
+ return self._time_output_format
260
+
261
+ @property
262
+ def timezone(self):
263
+ return self._timezone
264
+
265
+ @property
266
+ def binary_output_format(self):
267
+ return self._binary_output_format
268
+
269
+ @property
270
+ def arraysize(self):
271
+ return self._arraysize
272
+
273
+ @arraysize.setter
274
+ def arraysize(self, value):
275
+ self._arraysize = int(value)
276
+
277
+ @property
278
+ def connection(self):
279
+ return self._connection
280
+
281
+ @property
282
+ def errorhandler(self):
283
+ return self._errorhandler
284
+
285
+ @errorhandler.setter
286
+ def errorhandler(self, value):
287
+ logger.debug("setting errorhandler: %s", value)
288
+ if value is None:
289
+ raise ProgrammingError("Invalid errorhandler is specified")
290
+ self._errorhandler = value
291
+
292
+ @property
293
+ def is_file_transfer(self):
294
+ """Whether the command is PUT or GET."""
295
+ return hasattr(self, "_is_file_transfer") and self._is_file_transfer
296
+
297
+ @property
298
+ def lastrowid(self) -> None:
299
+ """Snowflake does not support lastrowid in which case None should be returned as per PEP249."""
300
+ return None
301
+
302
+ def callproc(self, procname: str, args: T = ()) -> T:
303
+ """Call a stored procedure.
304
+
305
+ Args:
306
+ procname: The stored procedure to be called.
307
+ args: Parameters to be passed into the stored procedure.
308
+
309
+ Returns:
310
+ The input parameters.
311
+ """
312
+ marker_format = "%s" if self._connection.is_pyformat else "?"
313
+ command = (
314
+ f"CALL {procname}({', '.join([marker_format for _ in range(len(args))])})"
315
+ )
316
+ self.execute(command, args)
317
+ return args
318
+
319
+ def close(self) -> bool | None:
320
+ """Closes the cursor object.
321
+
322
+ Returns whether the cursor was closed during this call.
323
+ """
324
+ try:
325
+ if self.is_closed():
326
+ return False
327
+
328
+ with self._lock_canceling:
329
+ self.reset(closing=True)
330
+ self._connection = None
331
+ del self.messages[:]
332
+ return True
333
+ except Exception:
334
+ pass
335
+
336
+ def is_closed(self):
337
+ return self._connection is None or self._connection.is_closed()
338
+
339
+ def _execute_helper(
340
+ self,
341
+ query: str,
342
+ timeout: int = 0,
343
+ statement_params: dict[str, str] | None = None,
344
+ binding_params: tuple | dict[str, dict[str, str]] = None,
345
+ binding_stage: str | None = None,
346
+ is_internal: bool = False,
347
+ describe_only: bool = False,
348
+ _no_results: bool = False,
349
+ _is_put_get=None,
350
+ _no_retry: bool = False,
351
+ ):
352
+ del self.messages[:]
353
+
354
+ if statement_params is not None and not isinstance(statement_params, dict):
355
+ Error.errorhandler_wrapper(
356
+ self.connection,
357
+ self,
358
+ ProgrammingError,
359
+ {
360
+ "msg": "The data type of statement params is invalid. It must be dict.",
361
+ "errno": ER_INVALID_VALUE,
362
+ },
363
+ )
364
+
365
+ # check if current installation include arrow extension or not,
366
+ # if not, we set statement level query result format to be JSON
367
+ if not CAN_USE_ARROW_RESULT_FORMAT:
368
+ logger.debug("Cannot use arrow result format, fallback to json format")
369
+ if statement_params is None:
370
+ statement_params = {
371
+ PARAMETER_PYTHON_CONNECTOR_QUERY_RESULT_FORMAT: "JSON"
372
+ }
373
+ else:
374
+ result_format_val = statement_params.get(
375
+ PARAMETER_PYTHON_CONNECTOR_QUERY_RESULT_FORMAT
376
+ )
377
+ if str(result_format_val).upper() == "ARROW":
378
+ self.check_can_use_arrow_resultset()
379
+ elif result_format_val is None:
380
+ statement_params[
381
+ PARAMETER_PYTHON_CONNECTOR_QUERY_RESULT_FORMAT
382
+ ] = "JSON"
383
+
384
+ self._sequence_counter = self._connection._next_sequence_counter()
385
+ self._request_id = uuid.uuid4()
386
+
387
+ logger.debug(f"Request id: {self._request_id}")
388
+
389
+ logger.debug("running query [%s]", self._format_query_for_log(query))
390
+ if _is_put_get is not None:
391
+ # if told the query is PUT or GET, use the information
392
+ self._is_file_transfer = _is_put_get
393
+ else:
394
+ # or detect it.
395
+ self._is_file_transfer = get_file_transfer_type(query) is not None
396
+ logger.debug("is_file_transfer: %s", self._is_file_transfer is not None)
397
+
398
+ real_timeout = (
399
+ timeout if timeout and timeout > 0 else self._connection.network_timeout
400
+ )
401
+
402
+ if real_timeout is not None:
403
+ self._timebomb = Timer(real_timeout, self.__cancel_query, [query])
404
+ self._timebomb.start()
405
+ logger.debug("started timebomb in %ss", real_timeout)
406
+ else:
407
+ self._timebomb = None
408
+
409
+ original_sigint = signal.getsignal(signal.SIGINT)
410
+
411
+ def interrupt_handler(*_): # pragma: no cover
412
+ try:
413
+ signal.signal(signal.SIGINT, exit_handler)
414
+ except (ValueError, TypeError):
415
+ # ignore failures
416
+ pass
417
+ try:
418
+ if self._timebomb is not None:
419
+ self._timebomb.cancel()
420
+ logger.debug("cancelled timebomb in finally")
421
+ self._timebomb = None
422
+ self.__cancel_query(query)
423
+ finally:
424
+ if original_sigint:
425
+ try:
426
+ signal.signal(signal.SIGINT, original_sigint)
427
+ except (ValueError, TypeError):
428
+ # ignore failures
429
+ pass
430
+ raise KeyboardInterrupt
431
+
432
+ try:
433
+ if not original_sigint == exit_handler:
434
+ signal.signal(signal.SIGINT, interrupt_handler)
435
+ except ValueError: # pragma: no cover
436
+ logger.debug(
437
+ "Failed to set SIGINT handler. " "Not in main thread. Ignored..."
438
+ )
439
+ ret = {"data": {}}
440
+ try:
441
+ ret = self._connection.cmd_query(
442
+ query,
443
+ self._sequence_counter,
444
+ self._request_id,
445
+ binding_params=binding_params,
446
+ binding_stage=binding_stage,
447
+ is_file_transfer=bool(self._is_file_transfer),
448
+ statement_params=statement_params,
449
+ is_internal=is_internal,
450
+ describe_only=describe_only,
451
+ _no_results=_no_results,
452
+ _no_retry=_no_retry,
453
+ )
454
+ finally:
455
+ try:
456
+ if original_sigint:
457
+ signal.signal(signal.SIGINT, original_sigint)
458
+ except (ValueError, TypeError): # pragma: no cover
459
+ logger.debug(
460
+ "Failed to reset SIGINT handler. Not in main " "thread. Ignored..."
461
+ )
462
+ if self._timebomb is not None:
463
+ self._timebomb.cancel()
464
+ logger.debug("cancelled timebomb in finally")
465
+
466
+ if "data" in ret and "parameters" in ret["data"]:
467
+ parameters = ret["data"]["parameters"]
468
+ # Set session parameters for cursor object
469
+ for kv in parameters:
470
+ if "TIMESTAMP_OUTPUT_FORMAT" in kv["name"]:
471
+ self._timestamp_output_format = kv["value"]
472
+ if "TIMESTAMP_NTZ_OUTPUT_FORMAT" in kv["name"]:
473
+ self._timestamp_ntz_output_format = kv["value"]
474
+ if "TIMESTAMP_LTZ_OUTPUT_FORMAT" in kv["name"]:
475
+ self._timestamp_ltz_output_format = kv["value"]
476
+ if "TIMESTAMP_TZ_OUTPUT_FORMAT" in kv["name"]:
477
+ self._timestamp_tz_output_format = kv["value"]
478
+ if "DATE_OUTPUT_FORMAT" in kv["name"]:
479
+ self._date_output_format = kv["value"]
480
+ if "TIME_OUTPUT_FORMAT" in kv["name"]:
481
+ self._time_output_format = kv["value"]
482
+ if "TIMEZONE" in kv["name"]:
483
+ self._timezone = kv["value"]
484
+ if "BINARY_OUTPUT_FORMAT" in kv["name"]:
485
+ self._binary_output_format = kv["value"]
486
+ # Set session parameters for connection object
487
+ self._connection._update_parameters(
488
+ {p["name"]: p["value"] for p in parameters}
489
+ )
490
+
491
+ self.query = query
492
+ self._sequence_counter = -1
493
+ return ret
494
+
495
+ def execute(
496
+ self,
497
+ command: str,
498
+ params: Sequence[Any] | dict[Any, Any] | None = None,
499
+ _bind_stage: str | None = None,
500
+ timeout: int | None = None,
501
+ _exec_async: bool = False,
502
+ _no_retry: bool = False,
503
+ _do_reset: bool = True,
504
+ _put_callback: SnowflakeProgressPercentage = None,
505
+ _put_azure_callback: SnowflakeProgressPercentage = None,
506
+ _put_callback_output_stream: IO[str] = sys.stdout,
507
+ _get_callback: SnowflakeProgressPercentage = None,
508
+ _get_azure_callback: SnowflakeProgressPercentage = None,
509
+ _get_callback_output_stream: IO[str] = sys.stdout,
510
+ _show_progress_bar: bool = True,
511
+ _statement_params: dict[str, str] | None = None,
512
+ _is_internal: bool = False,
513
+ _describe_only: bool = False,
514
+ _no_results: bool = False,
515
+ _is_put_get: bool | None = None,
516
+ _raise_put_get_error: bool = True,
517
+ _force_put_overwrite: bool = False,
518
+ file_stream: IO[bytes] | None = None,
519
+ ) -> SnowflakeCursor | None:
520
+ """Executes a command/query.
521
+
522
+ Args:
523
+ command: The SQL command to be executed.
524
+ params: Parameters to be bound into the SQL statement.
525
+ _bind_stage: Path in temporary stage where binding parameters are uploaded as CSV files.
526
+ timeout: Number of seconds after which to abort the query.
527
+ _exec_async: Whether to execute this query asynchronously.
528
+ _no_retry: Whether or not to retry on known errors.
529
+ _do_reset: Whether or not the result set needs to be reset before executing query.
530
+ _put_callback: Function to which GET command should call back to.
531
+ _put_azure_callback: Function to which an Azure GET command should call back to.
532
+ _put_callback_output_stream: The output stream a PUT command's callback should report on.
533
+ _get_callback: Function to which GET command should call back to.
534
+ _get_azure_callback: Function to which an Azure GET command should call back to.
535
+ _get_callback_output_stream: The output stream a GET command's callback should report on.
536
+ _show_progress_bar: Whether or not to show progress bar.
537
+ _statement_params: Extra information that should be sent to Snowflake with query.
538
+ _is_internal: This flag indicates whether the query is issued internally by the connector.
539
+ _describe_only: If true, the query will not be executed but return the schema/description of this query.
540
+ _no_results: This flag tells the back-end to not return the result, just fire the query and return the
541
+ response returned by Snowflake's server.
542
+ _use_ijson: This flag doesn't do anything as ijson support has ended.
543
+ _is_put_get: Force decision of this SQL query being a PUT, or GET command. This is detected otherwise.
544
+ _raise_put_get_error: Whether to raise PUT and GET errors.
545
+ _force_put_overwrite: If the SQL query is a PUT, then this flag can force overwriting of an already
546
+ existing file on stage.
547
+ file_stream: File-like object to be uploaded with PUT
548
+
549
+ Returns:
550
+ The cursor itself, or None if some error happened, or the response returned
551
+ by Snowflake if the _no_results flag is on.
552
+ """
553
+ if _exec_async:
554
+ _no_results = True
555
+ logger.debug("executing SQL/command")
556
+ if self.is_closed():
557
+ Error.errorhandler_wrapper(
558
+ self.connection,
559
+ self,
560
+ InterfaceError,
561
+ {"msg": "Cursor is closed in execute.", "errno": ER_CURSOR_IS_CLOSED},
562
+ )
563
+
564
+ if _do_reset:
565
+ self.reset()
566
+ command = command.strip(" \t\n\r") if command else None
567
+ if not command:
568
+ logger.warning("execute: no query is given to execute")
569
+ return
570
+
571
+ kwargs = {
572
+ "timeout": timeout,
573
+ "statement_params": _statement_params,
574
+ "is_internal": _is_internal,
575
+ "describe_only": _describe_only,
576
+ "_no_results": _no_results,
577
+ "_is_put_get": _is_put_get,
578
+ "_no_retry": _no_retry,
579
+ }
580
+
581
+ if self._connection.is_pyformat:
582
+ # pyformat/format paramstyle
583
+ # client side binding
584
+ processed_params = self._connection._process_params_pyformat(params, self)
585
+ # SNOW-513061 collect telemetry for empty sequence usage before we make the breaking change announcement
586
+ if params is not None and len(params) == 0:
587
+ self._log_telemetry_job_data(
588
+ TelemetryField.EMPTY_SEQ_INTERPOLATION,
589
+ TelemetryData.TRUE
590
+ if self.connection._interpolate_empty_sequences
591
+ else TelemetryData.FALSE,
592
+ )
593
+ if logger.getEffectiveLevel() <= logging.DEBUG:
594
+ logger.debug(
595
+ f"binding: [{self._format_query_for_log(command)}] "
596
+ f"with input=[{params}], "
597
+ f"processed=[{processed_params}]",
598
+ )
599
+ if (
600
+ self.connection._interpolate_empty_sequences
601
+ and processed_params is not None
602
+ ) or (
603
+ not self.connection._interpolate_empty_sequences
604
+ and len(processed_params) > 0
605
+ ):
606
+ query = command % processed_params
607
+ else:
608
+ query = command
609
+ else:
610
+ # qmark and numeric paramstyle
611
+ query = command
612
+ if _bind_stage:
613
+ kwargs["binding_stage"] = _bind_stage
614
+ else:
615
+ if params is not None and not isinstance(params, (list, tuple)):
616
+ errorvalue = {
617
+ "msg": f"Binding parameters must be a list: {params}",
618
+ "errno": ER_FAILED_PROCESSING_PYFORMAT,
619
+ }
620
+ Error.errorhandler_wrapper(
621
+ self.connection, self, ProgrammingError, errorvalue
622
+ )
623
+
624
+ kwargs["binding_params"] = self._connection._process_params_qmarks(
625
+ params, self
626
+ )
627
+
628
+ m = DESC_TABLE_RE.match(query)
629
+ if m:
630
+ query1 = f"describe table {m.group(1)}"
631
+ if logger.getEffectiveLevel() <= logging.WARNING:
632
+ logger.info(
633
+ "query was rewritten: org=%s, new=%s",
634
+ " ".join(line.strip() for line in query.split("\n")),
635
+ query1,
636
+ )
637
+ query = query1
638
+
639
+ if logger.getEffectiveLevel() <= logging.INFO:
640
+ logger.info("query: [%s]", self._format_query_for_log(query))
641
+ ret = self._execute_helper(query, **kwargs)
642
+ self._sfqid = (
643
+ ret["data"]["queryId"]
644
+ if "data" in ret and "queryId" in ret["data"]
645
+ else None
646
+ )
647
+ self._sqlstate = (
648
+ ret["data"]["sqlState"]
649
+ if "data" in ret and "sqlState" in ret["data"]
650
+ else None
651
+ )
652
+ self._first_chunk_time = get_time_millis()
653
+
654
+ # if server gives a send time, log the time it took to arrive
655
+ if "data" in ret and "sendResultTime" in ret["data"]:
656
+ time_consume_first_result = (
657
+ self._first_chunk_time - ret["data"]["sendResultTime"]
658
+ )
659
+ self._log_telemetry_job_data(
660
+ TelemetryField.TIME_CONSUME_FIRST_RESULT, time_consume_first_result
661
+ )
662
+ logger.debug("sfqid: %s", self.sfqid)
663
+
664
+ logger.info("query execution done")
665
+ if ret["success"]:
666
+ logger.debug("SUCCESS")
667
+ data = ret["data"]
668
+
669
+ logger.debug("PUT OR GET: %s", self.is_file_transfer)
670
+ if self.is_file_transfer:
671
+ # Decide whether to use the old, or new code path
672
+ sf_file_transfer_agent = SnowflakeFileTransferAgent(
673
+ self,
674
+ query,
675
+ ret,
676
+ put_callback=_put_callback,
677
+ put_azure_callback=_put_azure_callback,
678
+ put_callback_output_stream=_put_callback_output_stream,
679
+ get_callback=_get_callback,
680
+ get_azure_callback=_get_azure_callback,
681
+ get_callback_output_stream=_get_callback_output_stream,
682
+ show_progress_bar=_show_progress_bar,
683
+ raise_put_get_error=_raise_put_get_error,
684
+ force_put_overwrite=_force_put_overwrite
685
+ or data.get("overwrite", False),
686
+ source_from_stream=file_stream,
687
+ multipart_threshold=data.get("threshold"),
688
+ use_s3_regional_url=self._connection.enable_stage_s3_privatelink_for_us_east_1,
689
+ )
690
+ sf_file_transfer_agent.execute()
691
+ data = sf_file_transfer_agent.result()
692
+ self._total_rowcount = len(data["rowset"]) if "rowset" in data else -1
693
+ m = self.ALTER_SESSION_RE.match(query)
694
+ if m:
695
+ # session parameters
696
+ param = m.group(1).upper()
697
+ value = m.group(2)
698
+ self._connection.converter.set_parameter(param, value)
699
+
700
+ if _exec_async:
701
+ self.connection._async_sfqids[self._sfqid] = None
702
+ if _no_results:
703
+ self._total_rowcount = (
704
+ ret["data"]["total"]
705
+ if "data" in ret and "total" in ret["data"]
706
+ else -1
707
+ )
708
+ return data
709
+ self._init_result_and_meta(data)
710
+ else:
711
+ self._total_rowcount = (
712
+ ret["data"]["total"] if "data" in ret and "total" in ret["data"] else -1
713
+ )
714
+ logger.debug(ret)
715
+ err = ret["message"]
716
+ code = ret.get("code", -1)
717
+ if "data" in ret:
718
+ err += ret["data"].get("errorMessage", "")
719
+ errvalue = {
720
+ "msg": err,
721
+ "errno": int(code),
722
+ "sqlstate": self._sqlstate,
723
+ "sfqid": self._sfqid,
724
+ }
725
+ is_integrity_error = (
726
+ code == "100072"
727
+ ) # NULL result in a non-nullable column
728
+ error_class = IntegrityError if is_integrity_error else ProgrammingError
729
+ Error.errorhandler_wrapper(self.connection, self, error_class, errvalue)
730
+ return self
731
+
732
+ def execute_async(self, *args, **kwargs):
733
+ """Convenience function to execute a query without waiting for results (asynchronously).
734
+
735
+ This function takes the same arguments as execute, please refer to that function
736
+ for documentation.
737
+ """
738
+ kwargs["_exec_async"] = True
739
+ return self.execute(*args, **kwargs)
740
+
741
+ def describe(self, *args, **kwargs) -> list[ResultMetadata]:
742
+ """Obtain the schema of the result without executing the query.
743
+
744
+ This function takes the same arguments as execute, please refer to that function
745
+ for documentation.
746
+
747
+ Returns:
748
+ The schema of the result.
749
+ """
750
+ kwargs["_describe_only"] = kwargs["_is_internal"] = True
751
+ self.execute(*args, **kwargs)
752
+ return self._description
753
+
754
+ def _format_query_for_log(self, query):
755
+ return self._connection._format_query_for_log(query)
756
+
757
+ def _is_dml(self, data):
758
+ return (
759
+ "statementTypeId" in data
760
+ and int(data["statementTypeId"]) in STATEMENT_TYPE_ID_DML_SET
761
+ )
762
+
763
+ def _init_result_and_meta(self, data):
764
+ is_dml = self._is_dml(data)
765
+ self._query_result_format = data.get("queryResultFormat", "json")
766
+ logger.debug("Query result format: %s", self._query_result_format)
767
+
768
+ if self._total_rowcount == -1 and not is_dml and data.get("total") is not None:
769
+ self._total_rowcount = data["total"]
770
+
771
+ self._description: list[ResultMetadata] = [
772
+ ResultMetadata.from_column(col) for col in data["rowtype"]
773
+ ]
774
+
775
+ result_chunks = create_batches_from_response(
776
+ self, self._query_result_format, data, self._description
777
+ )
778
+
779
+ if not (is_dml or self.is_file_transfer):
780
+ logger.info(
781
+ "Number of results in first chunk: %s", result_chunks[0].rowcount
782
+ )
783
+
784
+ self._result_set = ResultSet(
785
+ self,
786
+ result_chunks,
787
+ self._connection.client_prefetch_threads,
788
+ )
789
+ self._rownumber = -1
790
+ self._result_state = ResultState.VALID
791
+
792
+ # don't update the row count when the result is returned from `describe` method
793
+ if is_dml and "rowset" in data and len(data["rowset"]) > 0:
794
+ updated_rows = 0
795
+ for idx, desc in enumerate(self._description):
796
+ if desc[0] in (
797
+ "number of rows updated",
798
+ "number of multi-joined rows updated",
799
+ "number of rows deleted",
800
+ ) or desc[0].startswith("number of rows inserted"):
801
+ updated_rows += int(data["rowset"][0][idx])
802
+ if self._total_rowcount == -1:
803
+ self._total_rowcount = updated_rows
804
+ else:
805
+ self._total_rowcount += updated_rows
806
+
807
+ def check_can_use_arrow_resultset(self):
808
+ global CAN_USE_ARROW_RESULT_FORMAT
809
+
810
+ if not CAN_USE_ARROW_RESULT_FORMAT:
811
+ if self._connection.application == "SnowSQL":
812
+ msg = "Currently SnowSQL doesn't support the result set in Apache Arrow format."
813
+ errno = ER_NO_PYARROW_SNOWSQL
814
+ else:
815
+ msg = "The result set in Apache Arrow format is not supported for the platform."
816
+ errno = ER_NO_ARROW_RESULT
817
+
818
+ Error.errorhandler_wrapper(
819
+ self.connection,
820
+ self,
821
+ ProgrammingError,
822
+ {
823
+ "msg": msg,
824
+ "errno": errno,
825
+ },
826
+ )
827
+
828
+ def check_can_use_pandas(self):
829
+ if not installed_pandas:
830
+ msg = (
831
+ "Optional dependency: 'pandas' is not installed, please see the following link for install "
832
+ "instructions: https://docs.snowflake.com/en/user-guide/python-connector-pandas.html#installation"
833
+ )
834
+ errno = ER_NO_PYARROW
835
+
836
+ Error.errorhandler_wrapper(
837
+ self.connection,
838
+ self,
839
+ ProgrammingError,
840
+ {
841
+ "msg": msg,
842
+ "errno": errno,
843
+ },
844
+ )
845
+
846
+ def query_result(self, qid):
847
+ url = f"/queries/{qid}/result"
848
+ ret = self._connection.rest.request(url=url, method="get")
849
+ self._sfqid = (
850
+ ret["data"]["queryId"]
851
+ if "data" in ret and "queryId" in ret["data"]
852
+ else None
853
+ )
854
+ self._sqlstate = (
855
+ ret["data"]["sqlState"]
856
+ if "data" in ret and "sqlState" in ret["data"]
857
+ else None
858
+ )
859
+ logger.debug("sfqid=%s", self._sfqid)
860
+
861
+ if ret.get("success"):
862
+ data = ret.get("data")
863
+ self._init_result_and_meta(data)
864
+ else:
865
+ logger.info("failed")
866
+ logger.debug(ret)
867
+ err = ret["message"]
868
+ code = ret.get("code", -1)
869
+ if "data" in ret:
870
+ err += ret["data"].get("errorMessage", "")
871
+ errvalue = {
872
+ "msg": err,
873
+ "errno": int(code),
874
+ "sqlstate": self._sqlstate,
875
+ "sfqid": self._sfqid,
876
+ }
877
+ Error.errorhandler_wrapper(
878
+ self.connection, self, ProgrammingError, errvalue
879
+ )
880
+ return self
881
+
882
+ def fetch_arrow_batches(self) -> Iterator[Table]:
883
+ self.check_can_use_arrow_resultset()
884
+ if self._query_result_format != "arrow":
885
+ raise NotSupportedError
886
+ self._log_telemetry_job_data(
887
+ TelemetryField.ARROW_FETCH_BATCHES, TelemetryData.TRUE
888
+ )
889
+ return self._result_set._fetch_arrow_batches()
890
+
891
+ def fetch_arrow_all(self) -> Table | None:
892
+ self.check_can_use_arrow_resultset()
893
+ if self._query_result_format != "arrow":
894
+ raise NotSupportedError
895
+ self._log_telemetry_job_data(TelemetryField.ARROW_FETCH_ALL, TelemetryData.TRUE)
896
+ return self._result_set._fetch_arrow_all()
897
+
898
+ def fetch_pandas_batches(self, **kwargs) -> Iterator[pandas.DataFrame]:
899
+ """Fetches a single Arrow Table."""
900
+ self.check_can_use_pandas()
901
+ if self._prefetch_hook is not None:
902
+ self._prefetch_hook()
903
+ if self._query_result_format != "arrow":
904
+ raise NotSupportedError
905
+ self._log_telemetry_job_data(
906
+ TelemetryField.PANDAS_FETCH_BATCHES, TelemetryData.TRUE
907
+ )
908
+ return self._result_set._fetch_pandas_batches(**kwargs)
909
+
910
+ def fetch_pandas_all(self, **kwargs) -> pandas.DataFrame:
911
+ """Fetch Pandas dataframes in batches, where 'batch' refers to Snowflake Chunk."""
912
+ self.check_can_use_pandas()
913
+ if self._prefetch_hook is not None:
914
+ self._prefetch_hook()
915
+ if self._query_result_format != "arrow":
916
+ raise NotSupportedError
917
+ self._log_telemetry_job_data(
918
+ TelemetryField.PANDAS_FETCH_ALL, TelemetryData.TRUE
919
+ )
920
+ return self._result_set._fetch_pandas_all(**kwargs)
921
+
922
+ def abort_query(self, qid):
923
+ url = f"/queries/{qid}/abort-request"
924
+ ret = self._connection.rest.request(url=url, method="post")
925
+ return ret.get("success")
926
+
927
+ def executemany(
928
+ self,
929
+ command: str,
930
+ seqparams: Sequence[Any] | dict[str, Any],
931
+ **kwargs: dict[str, Any],
932
+ ) -> SnowflakeCursor:
933
+ """Executes a command/query with the given set of parameters sequentially."""
934
+ logger.debug("executing many SQLs/commands")
935
+ command = command.strip(" \t\n\r") if command else None
936
+
937
+ if not seqparams:
938
+ return self
939
+
940
+ if self.INSERT_SQL_RE.match(command):
941
+ if self._connection.is_pyformat:
942
+ logger.debug("rewriting INSERT query")
943
+ command_wo_comments = re.sub(self.COMMENT_SQL_RE, "", command)
944
+ m = self.INSERT_SQL_VALUES_RE.match(command_wo_comments)
945
+ if not m:
946
+ Error.errorhandler_wrapper(
947
+ self.connection,
948
+ self,
949
+ InterfaceError,
950
+ {
951
+ "msg": "Failed to rewrite multi-row insert",
952
+ "errno": ER_FAILED_TO_REWRITE_MULTI_ROW_INSERT,
953
+ },
954
+ )
955
+
956
+ fmt = m.group(1)
957
+ values = []
958
+ for param in seqparams:
959
+ logger.debug(f"parameter: {param}")
960
+ values.append(
961
+ fmt % self._connection._process_params_pyformat(param, self)
962
+ )
963
+ command = command.replace(fmt, ",".join(values), 1)
964
+ self.execute(command, **kwargs)
965
+ return self
966
+ else:
967
+ logger.debug("bulk insert")
968
+ # sanity check
969
+ row_size = len(seqparams[0])
970
+ for row in seqparams:
971
+ if len(row) != row_size:
972
+ error_value = {
973
+ "msg": f"Bulk data size don't match. expected: {row_size}, "
974
+ f"got: {len(row)}, command: {command}",
975
+ "errno": ER_INVALID_VALUE,
976
+ }
977
+ Error.errorhandler_wrapper(
978
+ self.connection, self, InterfaceError, error_value
979
+ )
980
+ return self
981
+ bind_size = len(seqparams) * row_size
982
+ bind_stage = None
983
+ if (
984
+ bind_size
985
+ > self.connection._session_parameters[
986
+ "CLIENT_STAGE_ARRAY_BINDING_THRESHOLD"
987
+ ]
988
+ > 0
989
+ ):
990
+ # bind stage optimization
991
+ try:
992
+ rows = self.connection._write_params_to_byte_rows(seqparams)
993
+ bind_uploader = BindUploadAgent(self, rows)
994
+ bind_uploader.upload()
995
+ bind_stage = bind_uploader.stage_path
996
+ except BindUploadError:
997
+ logger.debug(
998
+ "Failed to upload binds to stage, sending binds to "
999
+ "Snowflake instead."
1000
+ )
1001
+ binding_param = (
1002
+ None if bind_stage else list(map(list, zip(*seqparams)))
1003
+ ) # transpose
1004
+ self.execute(
1005
+ command, params=binding_param, _bind_stage=bind_stage, **kwargs
1006
+ )
1007
+ return self
1008
+
1009
+ self.reset()
1010
+ for param in seqparams:
1011
+ self.execute(command, params=param, _do_reset=False, **kwargs)
1012
+ return self
1013
+
1014
+ def _result_iterator(
1015
+ self,
1016
+ ) -> Generator[dict, None, None] | Generator[tuple, None, None]:
1017
+ """Yields the elements from _result and raises an exception when appropriate."""
1018
+ try:
1019
+ for _next in self._result:
1020
+ if isinstance(_next, Exception):
1021
+ Error.errorhandler_wrapper_from_ready_exception(
1022
+ self._connection,
1023
+ self,
1024
+ _next,
1025
+ )
1026
+ self._rownumber += 1
1027
+ yield _next
1028
+ except TypeError as err:
1029
+ if self._result_state == ResultState.DEFAULT:
1030
+ raise err
1031
+ else:
1032
+ yield None
1033
+
1034
+ def fetchone(self) -> dict | tuple | None:
1035
+ """Fetches one row."""
1036
+ if self._prefetch_hook is not None:
1037
+ self._prefetch_hook()
1038
+ if self._result is None and self._result_set is not None:
1039
+ self._result = iter(self._result_set)
1040
+ self._result_state = ResultState.VALID
1041
+ try:
1042
+ return next(self._result_iterator())
1043
+ except StopIteration:
1044
+ return None
1045
+
1046
+ def fetchmany(self, size=None):
1047
+ """Fetches the number of specified rows."""
1048
+ if size is None:
1049
+ size = self.arraysize
1050
+
1051
+ if size < 0:
1052
+ errorvalue = {
1053
+ "msg": (
1054
+ "The number of rows is not zero or " "positive number: {}"
1055
+ ).format(size),
1056
+ "errno": ER_NOT_POSITIVE_SIZE,
1057
+ }
1058
+ Error.errorhandler_wrapper(
1059
+ self.connection, self, ProgrammingError, errorvalue
1060
+ )
1061
+ ret = []
1062
+ while size > 0:
1063
+ row = self.fetchone()
1064
+ if row is None:
1065
+ break
1066
+ ret.append(row)
1067
+ if size is not None:
1068
+ size -= 1
1069
+
1070
+ return ret
1071
+
1072
+ def fetchall(self) -> list[tuple] | list[dict]:
1073
+ """Fetches all of the results."""
1074
+ ret = []
1075
+ while True:
1076
+ row = self.fetchone()
1077
+ if row is None:
1078
+ break
1079
+ ret.append(row)
1080
+ return ret
1081
+
1082
+ def nextset(self):
1083
+ """Not supported."""
1084
+ logger.debug("nop")
1085
+ return None
1086
+
1087
+ def setinputsizes(self, _):
1088
+ """Not supported."""
1089
+ logger.debug("nop")
1090
+
1091
+ def setoutputsize(self, _, column=None):
1092
+ """Not supported."""
1093
+ del column
1094
+ logger.debug("nop")
1095
+
1096
+ def scroll(self, value, mode="relative"):
1097
+ Error.errorhandler_wrapper(
1098
+ self.connection,
1099
+ self,
1100
+ NotSupportedError,
1101
+ {
1102
+ "msg": "scroll is not supported.",
1103
+ "errno": ER_UNSUPPORTED_METHOD,
1104
+ "sqlstate": SQLSTATE_FEATURE_NOT_SUPPORTED,
1105
+ },
1106
+ )
1107
+
1108
+ def reset(self, closing=False):
1109
+ """Resets the result set."""
1110
+ # SNOW-647539: Do not erase the rowcount
1111
+ # information when closing the cursor
1112
+ if not closing:
1113
+ self._total_rowcount = -1
1114
+ if self._result_state != ResultState.DEFAULT:
1115
+ self._result_state = ResultState.RESET
1116
+ if self._result is not None:
1117
+ self._result = None
1118
+ if self._inner_cursor is not None:
1119
+ self._inner_cursor.reset(closing=closing)
1120
+ self._result = None
1121
+ self._inner_cursor = None
1122
+ self._prefetch_hook = None
1123
+ if not self.connection._reuse_results:
1124
+ self._result_set = None
1125
+
1126
+ def __iter__(self) -> Iterator[dict] | Iterator[tuple]:
1127
+ """Iteration over the result set."""
1128
+ # set _result if _result_set is not None
1129
+ if self._result is None and self._result_set is not None:
1130
+ self._result = iter(self._result_set)
1131
+ self._result_state = ResultState.VALID
1132
+ return self._result_iterator()
1133
+
1134
+ def __cancel_query(self, query):
1135
+ if self._sequence_counter >= 0 and not self.is_closed():
1136
+ logger.debug("canceled. %s, request_id: %s", query, self._request_id)
1137
+ with self._lock_canceling:
1138
+ self._connection._cancel_query(query, self._request_id)
1139
+
1140
+ def _log_telemetry_job_data(
1141
+ self, telemetry_field: TelemetryField, value: Any
1142
+ ) -> None:
1143
+ """Builds an instance of TelemetryData with the given field and logs it."""
1144
+ ts = get_time_millis()
1145
+ try:
1146
+ self._connection._log_telemetry(
1147
+ TelemetryData.from_telemetry_data_dict(
1148
+ from_dict={
1149
+ TelemetryField.KEY_TYPE.value: telemetry_field.value,
1150
+ TelemetryField.KEY_SFQID.value: self._sfqid,
1151
+ TelemetryField.KEY_VALUE.value: value,
1152
+ },
1153
+ timestamp=ts,
1154
+ connection=self._connection,
1155
+ )
1156
+ )
1157
+ except AttributeError:
1158
+ logger.warning(
1159
+ "Cursor failed to log to telemetry. Connection object may be None.",
1160
+ exc_info=True,
1161
+ )
1162
+
1163
+ def __enter__(self):
1164
+ """Context manager."""
1165
+ return self
1166
+
1167
+ def __exit__(self, exc_type, exc_val, exc_tb):
1168
+ """Context manager with commit or rollback."""
1169
+ self.close()
1170
+
1171
+ def get_results_from_sfqid(self, sfqid: str):
1172
+ """Gets the results from previously ran query."""
1173
+
1174
+ def wait_until_ready():
1175
+ """Makes sure query has finished executing and once it has retrieves results."""
1176
+ no_data_counter = 0
1177
+ retry_pattern_pos = 0
1178
+ while True:
1179
+ status = self.connection.get_query_status(sfqid)
1180
+ if not self.connection.is_still_running(status):
1181
+ break
1182
+ if status == QueryStatus.NO_DATA: # pragma: no cover
1183
+ no_data_counter += 1
1184
+ if no_data_counter > ASYNC_NO_DATA_MAX_RETRY:
1185
+ raise DatabaseError(
1186
+ "Cannot retrieve data on the status of this query. No information returned "
1187
+ "from server for query '{}'"
1188
+ )
1189
+ time.sleep(
1190
+ 0.5 * ASYNC_RETRY_PATTERN[retry_pattern_pos]
1191
+ ) # Same wait as JDBC
1192
+ # If we can advance in ASYNC_RETRY_PATTERN then do so
1193
+ if retry_pattern_pos < (len(ASYNC_RETRY_PATTERN) - 1):
1194
+ retry_pattern_pos += 1
1195
+ if status != QueryStatus.SUCCESS:
1196
+ raise DatabaseError(
1197
+ "Status of query '{}' is {}, results are unavailable".format(
1198
+ sfqid, status.name
1199
+ )
1200
+ )
1201
+ self._inner_cursor.execute(f"select * from table(result_scan('{sfqid}'))")
1202
+ self._result = self._inner_cursor._result
1203
+ self._query_result_format = self._inner_cursor._query_result_format
1204
+ self._total_rowcount = self._inner_cursor._total_rowcount
1205
+ self._description = self._inner_cursor._description
1206
+ self._result_set = self._inner_cursor._result_set
1207
+ self._result_state = ResultState.VALID
1208
+ self._rownumber = 0
1209
+ # Unset this function, so that we don't block anymore
1210
+ self._prefetch_hook = None
1211
+
1212
+ self.connection.get_query_status_throw_if_error(
1213
+ sfqid
1214
+ ) # Trigger an exception if query failed
1215
+ klass = self.__class__
1216
+ self._inner_cursor = klass(self.connection)
1217
+ self._sfqid = sfqid
1218
+ self._prefetch_hook = wait_until_ready
1219
+
1220
+ def get_result_batches(self) -> list[ResultBatch] | None:
1221
+ """Get the previously executed query's ``ResultBatch`` s if available.
1222
+
1223
+ If they are unavailable, in case nothing has been executed yet None will
1224
+ be returned.
1225
+
1226
+ For a detailed description of ``ResultBatch`` s please see the docstring of:
1227
+ ``snowflake.connector.result_batches.ResultBatch``
1228
+ """
1229
+ if self._result_set is None:
1230
+ return None
1231
+ self._log_telemetry_job_data(
1232
+ TelemetryField.GET_PARTITIONS_USED, TelemetryData.TRUE
1233
+ )
1234
+ return self._result_set.batches
1235
+ ```
1236
+
1237
+ ## `src/snowflake/connector/cursor.py` — `function:SnowflakeCursor.get_file_transfer_type` (lines 197-204)
1238
+
1239
+ ```python
1240
+ def get_file_transfer_type(sql: str) -> FileTransferType | None:
1241
+ """Decide whether a SQL is a file transfer and return its type.
1242
+
1243
+ None is returned if the SQL isn't a file transfer so that this function can be
1244
+ used in an if-statement.
1245
+ """
1246
+ return get_file_transfer_type(sql)
1247
+ ```
1248
+
1249
+ ## `src/snowflake/connector/cursor.py` — `function:SnowflakeCursor._execute_helper` (lines 406-560)
1250
+
1251
+ ```python
1252
+ def _execute_helper(
1253
+ self,
1254
+ query: str,
1255
+ timeout: int = 0,
1256
+ statement_params: dict[str, str] | None = None,
1257
+ binding_params: tuple | dict[str, dict[str, str]] = None,
1258
+ binding_stage: str | None = None,
1259
+ is_internal: bool = False,
1260
+ describe_only: bool = False,
1261
+ _no_results: bool = False,
1262
+ _is_put_get=None,
1263
+ _no_retry: bool = False,
1264
+ ):
1265
+ del self.messages[:]
1266
+
1267
+ if statement_params is not None and not isinstance(statement_params, dict):
1268
+ Error.errorhandler_wrapper(
1269
+ self.connection,
1270
+ self,
1271
+ ProgrammingError,
1272
+ {
1273
+ "msg": "The data type of statement params is invalid. It must be dict.",
1274
+ "errno": ER_INVALID_VALUE,
1275
+ },
1276
+ )
1277
+
1278
+ # check if current installation include arrow extension or not,
1279
+ # if not, we set statement level query result format to be JSON
1280
+ if not CAN_USE_ARROW_RESULT_FORMAT:
1281
+ logger.debug("Cannot use arrow result format, fallback to json format")
1282
+ if statement_params is None:
1283
+ statement_params = {
1284
+ PARAMETER_PYTHON_CONNECTOR_QUERY_RESULT_FORMAT: "JSON"
1285
+ }
1286
+ else:
1287
+ result_format_val = statement_params.get(
1288
+ PARAMETER_PYTHON_CONNECTOR_QUERY_RESULT_FORMAT
1289
+ )
1290
+ if str(result_format_val).upper() == "ARROW":
1291
+ self.check_can_use_arrow_resultset()
1292
+ elif result_format_val is None:
1293
+ statement_params[
1294
+ PARAMETER_PYTHON_CONNECTOR_QUERY_RESULT_FORMAT
1295
+ ] = "JSON"
1296
+
1297
+ self._sequence_counter = self._connection._next_sequence_counter()
1298
+ self._request_id = uuid.uuid4()
1299
+
1300
+ logger.debug(f"Request id: {self._request_id}")
1301
+
1302
+ logger.debug("running query [%s]", self._format_query_for_log(query))
1303
+ if _is_put_get is not None:
1304
+ # if told the query is PUT or GET, use the information
1305
+ self._is_file_transfer = _is_put_get
1306
+ else:
1307
+ # or detect it.
1308
+ self._is_file_transfer = get_file_transfer_type(query) is not None
1309
+ logger.debug("is_file_transfer: %s", self._is_file_transfer is not None)
1310
+
1311
+ real_timeout = (
1312
+ timeout if timeout and timeout > 0 else self._connection.network_timeout
1313
+ )
1314
+
1315
+ if real_timeout is not None:
1316
+ self._timebomb = Timer(real_timeout, self.__cancel_query, [query])
1317
+ self._timebomb.start()
1318
+ logger.debug("started timebomb in %ss", real_timeout)
1319
+ else:
1320
+ self._timebomb = None
1321
+
1322
+ original_sigint = signal.getsignal(signal.SIGINT)
1323
+
1324
+ def interrupt_handler(*_): # pragma: no cover
1325
+ try:
1326
+ signal.signal(signal.SIGINT, exit_handler)
1327
+ except (ValueError, TypeError):
1328
+ # ignore failures
1329
+ pass
1330
+ try:
1331
+ if self._timebomb is not None:
1332
+ self._timebomb.cancel()
1333
+ logger.debug("cancelled timebomb in finally")
1334
+ self._timebomb = None
1335
+ self.__cancel_query(query)
1336
+ finally:
1337
+ if original_sigint:
1338
+ try:
1339
+ signal.signal(signal.SIGINT, original_sigint)
1340
+ except (ValueError, TypeError):
1341
+ # ignore failures
1342
+ pass
1343
+ raise KeyboardInterrupt
1344
+
1345
+ try:
1346
+ if not original_sigint == exit_handler:
1347
+ signal.signal(signal.SIGINT, interrupt_handler)
1348
+ except ValueError: # pragma: no cover
1349
+ logger.debug(
1350
+ "Failed to set SIGINT handler. " "Not in main thread. Ignored..."
1351
+ )
1352
+ ret = {"data": {}}
1353
+ try:
1354
+ ret = self._connection.cmd_query(
1355
+ query,
1356
+ self._sequence_counter,
1357
+ self._request_id,
1358
+ binding_params=binding_params,
1359
+ binding_stage=binding_stage,
1360
+ is_file_transfer=bool(self._is_file_transfer),
1361
+ statement_params=statement_params,
1362
+ is_internal=is_internal,
1363
+ describe_only=describe_only,
1364
+ _no_results=_no_results,
1365
+ _no_retry=_no_retry,
1366
+ )
1367
+ finally:
1368
+ try:
1369
+ if original_sigint:
1370
+ signal.signal(signal.SIGINT, original_sigint)
1371
+ except (ValueError, TypeError): # pragma: no cover
1372
+ logger.debug(
1373
+ "Failed to reset SIGINT handler. Not in main " "thread. Ignored..."
1374
+ )
1375
+ if self._timebomb is not None:
1376
+ self._timebomb.cancel()
1377
+ logger.debug("cancelled timebomb in finally")
1378
+
1379
+ if "data" in ret and "parameters" in ret["data"]:
1380
+ parameters = ret["data"]["parameters"]
1381
+ # Set session parameters for cursor object
1382
+ for kv in parameters:
1383
+ if "TIMESTAMP_OUTPUT_FORMAT" in kv["name"]:
1384
+ self._timestamp_output_format = kv["value"]
1385
+ if "TIMESTAMP_NTZ_OUTPUT_FORMAT" in kv["name"]:
1386
+ self._timestamp_ntz_output_format = kv["value"]
1387
+ if "TIMESTAMP_LTZ_OUTPUT_FORMAT" in kv["name"]:
1388
+ self._timestamp_ltz_output_format = kv["value"]
1389
+ if "TIMESTAMP_TZ_OUTPUT_FORMAT" in kv["name"]:
1390
+ self._timestamp_tz_output_format = kv["value"]
1391
+ if "DATE_OUTPUT_FORMAT" in kv["name"]:
1392
+ self._date_output_format = kv["value"]
1393
+ if "TIME_OUTPUT_FORMAT" in kv["name"]:
1394
+ self._time_output_format = kv["value"]
1395
+ if "TIMEZONE" in kv["name"]:
1396
+ self._timezone = kv["value"]
1397
+ if "BINARY_OUTPUT_FORMAT" in kv["name"]:
1398
+ self._binary_output_format = kv["value"]
1399
+ # Set session parameters for connection object
1400
+ self._connection._update_parameters(
1401
+ {p["name"]: p["value"] for p in parameters}
1402
+ )
1403
+
1404
+ self.query = query
1405
+ self._sequence_counter = -1
1406
+ return ret
1407
+ ```
1408
+
1409
+ ## `src/snowflake/connector/cursor.py` — `module:<module>@35` (lines 35-35)
1410
+
1411
+ ```python
1412
+ from ._sql_util import get_file_transfer_type
1413
+ ```
1414
+
1415
+ ## `src/snowflake/connector/gcs_storage_client.py` — `class:SnowflakeGCSRestClient` (lines 48-395)
1416
+
1417
+ ```python
1418
+ class SnowflakeGCSRestClient(SnowflakeStorageClient):
1419
+ def __init__(
1420
+ self,
1421
+ meta: SnowflakeFileMeta,
1422
+ credentials: StorageCredential,
1423
+ stage_info: dict[str, Any],
1424
+ cnx: SnowflakeConnection,
1425
+ command: str,
1426
+ use_s3_regional_url=False,
1427
+ ) -> None:
1428
+ """Creates a client object with given stage credentials.
1429
+
1430
+ Args:
1431
+ stage_info: Access credentials and info of a stage.
1432
+
1433
+ Returns:
1434
+ The client to communicate with GCS.
1435
+ """
1436
+ super().__init__(
1437
+ meta, stage_info, -1, credentials=credentials, chunked_transfer=False
1438
+ )
1439
+ self.stage_info = stage_info
1440
+ self._command = command
1441
+ self.meta = meta
1442
+ self._cursor = cnx.cursor()
1443
+ # presigned_url in meta is for downloading
1444
+ self.presigned_url: str = meta.presigned_url or stage_info.get("presignedUrl")
1445
+ self.security_token = credentials.creds.get("GCS_ACCESS_TOKEN")
1446
+
1447
+ if self.security_token:
1448
+ logger.debug(f"len(GCS_ACCESS_TOKEN): {len(self.security_token)}")
1449
+ else:
1450
+ logger.debug("No access token received from GS, requesting presigned url")
1451
+ self._update_presigned_url()
1452
+
1453
+ def _has_expired_token(self, response: requests.Response) -> bool:
1454
+ return self.security_token and response.status_code == 401
1455
+
1456
+ def _has_expired_presigned_url(self, response: requests.Response) -> bool:
1457
+ # Presigned urls can be generated for any xml-api operation
1458
+ # offered by GCS. Hence the error codes expected are similar
1459
+ # to xml api.
1460
+ # https://cloud.google.com/storage/docs/xml-api/reference-status
1461
+
1462
+ presigned_url_expired = (
1463
+ not self.security_token
1464
+ ) and response.status_code == 400
1465
+ if presigned_url_expired and self.last_err_is_presigned_url:
1466
+ logger.debug("Presigned url expiration error two times in a row.")
1467
+ response.raise_for_status()
1468
+ self.last_err_is_presigned_url = presigned_url_expired
1469
+ return presigned_url_expired
1470
+
1471
+ def _upload_chunk(self, chunk_id: int, chunk: bytes) -> None:
1472
+ meta = self.meta
1473
+
1474
+ content_encoding = ""
1475
+ if meta.dst_compression_type is not None:
1476
+ content_encoding = meta.dst_compression_type.name.lower()
1477
+
1478
+ # We set the contentEncoding to blank for GZIP files. We don't
1479
+ # want GCS to think our gzip files are gzips because it makes
1480
+ # them download uncompressed, and none of the other providers do
1481
+ # that. There's essentially no way for us to prevent that
1482
+ # behavior. Bad Google.
1483
+ if content_encoding and content_encoding == "gzip":
1484
+ content_encoding = ""
1485
+
1486
+ gcs_headers = {
1487
+ HTTP_HEADER_CONTENT_ENCODING: content_encoding,
1488
+ GCS_METADATA_SFC_DIGEST: meta.sha256_digest,
1489
+ }
1490
+
1491
+ if self.encryption_metadata:
1492
+ gcs_headers.update(
1493
+ {
1494
+ GCS_METADATA_ENCRYPTIONDATAPROP: json.dumps(
1495
+ {
1496
+ "EncryptionMode": "FullBlob",
1497
+ "WrappedContentKey": {
1498
+ "KeyId": "symmKey1",
1499
+ "EncryptedKey": self.encryption_metadata.key,
1500
+ "Algorithm": "AES_CBC_256",
1501
+ },
1502
+ "EncryptionAgent": {
1503
+ "Protocol": "1.0",
1504
+ "EncryptionAlgorithm": "AES_CBC_256",
1505
+ },
1506
+ "ContentEncryptionIV": self.encryption_metadata.iv,
1507
+ "KeyWrappingMetadata": {"EncryptionLibrary": "Java 5.3.0"},
1508
+ }
1509
+ ),
1510
+ GCS_METADATA_MATDESC_KEY: self.encryption_metadata.matdesc,
1511
+ }
1512
+ )
1513
+
1514
+ def generate_url_and_rest_args() -> tuple[
1515
+ str, dict[str, dict[str | Any, str | None] | bytes]
1516
+ ]:
1517
+ if not self.presigned_url:
1518
+ upload_url = self.generate_file_url(
1519
+ self.stage_info["location"], meta.dst_file_name.lstrip("/")
1520
+ )
1521
+ access_token = self.security_token
1522
+ else:
1523
+ upload_url = self.presigned_url
1524
+ access_token: str | None = None
1525
+ if access_token:
1526
+ gcs_headers.update({"Authorization": f"Bearer {access_token}"})
1527
+ rest_args = {"headers": gcs_headers, "data": chunk}
1528
+ return upload_url, rest_args
1529
+
1530
+ response = self._send_request_with_retry(
1531
+ "PUT", generate_url_and_rest_args, chunk_id
1532
+ )
1533
+ response.raise_for_status()
1534
+ meta.gcs_file_header_digest = gcs_headers[GCS_METADATA_SFC_DIGEST]
1535
+ meta.gcs_file_header_content_length = meta.upload_size
1536
+ meta.gcs_file_header_encryption_metadata = json.loads(
1537
+ gcs_headers.get(GCS_METADATA_ENCRYPTIONDATAPROP, "null")
1538
+ )
1539
+
1540
+ def download_chunk(self, chunk_id: int) -> None:
1541
+ meta = self.meta
1542
+
1543
+ def generate_url_and_rest_args() -> tuple[
1544
+ str, dict[str, dict[str, str] | bool]
1545
+ ]:
1546
+ gcs_headers = {}
1547
+ if not self.presigned_url:
1548
+ download_url = self.generate_file_url(
1549
+ self.stage_info["location"], meta.src_file_name.lstrip("/")
1550
+ )
1551
+ access_token = self.security_token
1552
+ gcs_headers["Authorization"] = f"Bearer {access_token}"
1553
+ else:
1554
+ download_url = self.presigned_url
1555
+ rest_args = {"headers": gcs_headers, "stream": True}
1556
+ return download_url, rest_args
1557
+
1558
+ response = self._send_request_with_retry(
1559
+ "GET", generate_url_and_rest_args, chunk_id
1560
+ )
1561
+ response.raise_for_status()
1562
+
1563
+ self.write_downloaded_chunk(chunk_id, response.content)
1564
+
1565
+ encryption_metadata = None
1566
+
1567
+ if response.headers.get(GCS_METADATA_ENCRYPTIONDATAPROP, None):
1568
+ encryptiondata = json.loads(
1569
+ response.headers[GCS_METADATA_ENCRYPTIONDATAPROP]
1570
+ )
1571
+
1572
+ if encryptiondata:
1573
+ encryption_metadata = EncryptionMetadata(
1574
+ key=encryptiondata["WrappedContentKey"]["EncryptedKey"],
1575
+ iv=encryptiondata["ContentEncryptionIV"],
1576
+ matdesc=response.headers[GCS_METADATA_MATDESC_KEY]
1577
+ if GCS_METADATA_MATDESC_KEY in response.headers
1578
+ else None,
1579
+ )
1580
+
1581
+ meta.gcs_file_header_digest = response.headers.get(GCS_METADATA_SFC_DIGEST)
1582
+ meta.gcs_file_header_content_length = len(response.content)
1583
+ meta.gcs_file_header_encryption_metadata = encryption_metadata
1584
+
1585
+ def finish_download(self) -> None:
1586
+ super().finish_download()
1587
+ # Sadly, we can only determine the src file size after we've
1588
+ # downloaded it, unlike the other cloud providers where the
1589
+ # metadata can be read beforehand.
1590
+ self.meta.src_file_size = os.path.getsize(self.intermediate_dst_path)
1591
+
1592
+ def _update_presigned_url(self) -> None:
1593
+ """Updates the file metas with presigned urls if any.
1594
+
1595
+ Currently only the file metas generated for PUT/GET on a GCP account need the presigned urls.
1596
+ """
1597
+ logger.debug("Updating presigned url")
1598
+
1599
+ # Rewrite the command such that a new PUT call is made for each file
1600
+ # represented by the regex (if present) separately. This is the only
1601
+ # way to get the presigned url for that file.
1602
+ file_path_to_be_replaced = self._get_local_file_path_from_put_command()
1603
+
1604
+ if not file_path_to_be_replaced:
1605
+ # This prevents GET statements to proceed
1606
+ return
1607
+
1608
+ # At this point the connector has already figured out and
1609
+ # validated that the local file exists and has also decided
1610
+ # upon the destination file name and the compression type.
1611
+ # The only thing that's left to do is to get the presigned
1612
+ # url for the destination file. If the command originally
1613
+ # referred to a single file, then the presigned url got in
1614
+ # that case is simply ignore, since the file name is not what
1615
+ # we want.
1616
+
1617
+ # GS only looks at the file name at the end of local file
1618
+ # path to figure out the remote object name. Hence the prefix
1619
+ # for local path is not necessary in the reconstructed command.
1620
+ file_path_to_replace_with = self.meta.dst_file_name
1621
+ command_with_single_file = self._command
1622
+ command_with_single_file = command_with_single_file.replace(
1623
+ file_path_to_be_replaced, file_path_to_replace_with
1624
+ )
1625
+
1626
+ logger.debug("getting presigned url for %s", file_path_to_replace_with)
1627
+ ret = self._cursor._execute_helper(command_with_single_file)
1628
+
1629
+ stage_info = ret.get("data", dict()).get("stageInfo", dict())
1630
+ self.meta.presigned_url = stage_info.get("presignedUrl")
1631
+ self.presigned_url = stage_info.get("presignedUrl")
1632
+
1633
+ def _get_local_file_path_from_put_command(self) -> str | None:
1634
+ """Get the local file path from PUT command (Logic adopted from JDBC, written by Polita).
1635
+
1636
+ Args:
1637
+ command: Command to be parsed and get the local file path out of.
1638
+
1639
+ Returns:
1640
+ The local file path.
1641
+ """
1642
+ command = self._command
1643
+ if FILE_PROTOCOL not in self._command or not is_put_statement(command):
1644
+ return None
1645
+
1646
+ file_path_begin_index = command.find(FILE_PROTOCOL)
1647
+ is_file_path_quoted = command[file_path_begin_index - 1] == "'"
1648
+ file_path_begin_index += len(FILE_PROTOCOL)
1649
+
1650
+ file_path = ""
1651
+
1652
+ if is_file_path_quoted:
1653
+ file_path_end_index = command.find("'", file_path_begin_index)
1654
+
1655
+ if file_path_end_index > file_path_begin_index:
1656
+ file_path = command[file_path_begin_index:file_path_end_index]
1657
+ else:
1658
+ index_list = []
1659
+ for delimiter in [" ", "\n", ";"]:
1660
+ index = command.find(delimiter, file_path_begin_index)
1661
+ if index != -1:
1662
+ index_list += [index]
1663
+
1664
+ file_path_end_index = min(index_list) if index_list else -1
1665
+
1666
+ if file_path_end_index > file_path_begin_index:
1667
+ file_path = command[file_path_begin_index:file_path_end_index]
1668
+ elif file_path_end_index == -1:
1669
+ file_path = command[file_path_begin_index:]
1670
+
1671
+ return file_path
1672
+
1673
+ def get_file_header(self, filename: str) -> FileHeader | None:
1674
+ """Gets the remote file's metadata.
1675
+
1676
+ Args:
1677
+ filename: Not applicable to GCS.
1678
+
1679
+ Returns:
1680
+ The file header, with expected properties populated or None, based on how the request goes with the
1681
+ storage provider.
1682
+
1683
+ Notes:
1684
+ Sometimes this method is called to verify that the file has indeed been uploaded. In cases of presigned
1685
+ url, we have no way of verifying that, except with the http status code of 200 which we have already
1686
+ confirmed and set the meta.result_status = UPLOADED/DOWNLOADED.
1687
+ """
1688
+ meta = self.meta
1689
+ if (
1690
+ meta.result_status == ResultStatus.UPLOADED
1691
+ or meta.result_status == ResultStatus.DOWNLOADED
1692
+ ):
1693
+ return FileHeader(
1694
+ digest=meta.gcs_file_header_digest,
1695
+ content_length=meta.gcs_file_header_content_length,
1696
+ encryption_metadata=meta.gcs_file_header_encryption_metadata,
1697
+ )
1698
+ elif self.presigned_url:
1699
+ meta.result_status = ResultStatus.NOT_FOUND_FILE
1700
+ else:
1701
+
1702
+ def generate_url_and_authenticated_headers():
1703
+ url = self.generate_file_url(
1704
+ self.stage_info["location"], filename.lstrip("/")
1705
+ )
1706
+ gcs_headers = {"Authorization": f"Bearer {self.security_token}"}
1707
+ rest_args = {"headers": gcs_headers}
1708
+ return url, rest_args
1709
+
1710
+ retry_id = "HEAD"
1711
+ self.retry_count[retry_id] = 0
1712
+ response = self._send_request_with_retry(
1713
+ "HEAD", generate_url_and_authenticated_headers, retry_id
1714
+ )
1715
+ if response.status_code == 404:
1716
+ meta.result_status = ResultStatus.NOT_FOUND_FILE
1717
+ return None
1718
+ elif response.status_code == 200:
1719
+ digest = response.headers.get(GCS_METADATA_SFC_DIGEST, None)
1720
+ content_length = int(response.headers.get("content-length", "0"))
1721
+
1722
+ encryption_metadata = EncryptionMetadata("", "", "")
1723
+ if response.headers.get(GCS_METADATA_ENCRYPTIONDATAPROP, None):
1724
+ encryption_data = json.loads(
1725
+ response.headers[GCS_METADATA_ENCRYPTIONDATAPROP]
1726
+ )
1727
+
1728
+ if encryption_data:
1729
+ encryption_metadata = EncryptionMetadata(
1730
+ key=encryption_data["WrappedContentKey"]["EncryptedKey"],
1731
+ iv=encryption_data["ContentEncryptionIV"],
1732
+ matdesc=response.headers[GCS_METADATA_MATDESC_KEY]
1733
+ if GCS_METADATA_MATDESC_KEY in response.headers
1734
+ else None,
1735
+ )
1736
+ meta.result_status = ResultStatus.UPLOADED
1737
+ return FileHeader(
1738
+ digest=digest,
1739
+ content_length=content_length,
1740
+ encryption_metadata=encryption_metadata,
1741
+ )
1742
+ response.raise_for_status()
1743
+ return None
1744
+
1745
+ @staticmethod
1746
+ def extract_bucket_name_and_path(stage_location: str) -> GcsLocation:
1747
+ container_name = stage_location
1748
+ path = ""
1749
+
1750
+ # split stage location as bucket name and path
1751
+ if "/" in stage_location:
1752
+ container_name = stage_location[0 : stage_location.index("/")]
1753
+ path = stage_location[stage_location.index("/") + 1 :]
1754
+ if path and not path.endswith("/"):
1755
+ path += "/"
1756
+
1757
+ return GcsLocation(bucket_name=container_name, path=path)
1758
+
1759
+ @staticmethod
1760
+ def generate_file_url(stage_location: str, filename: str) -> str:
1761
+ gcs_location = SnowflakeGCSRestClient.extract_bucket_name_and_path(
1762
+ stage_location
1763
+ )
1764
+ full_file_path = f"{gcs_location.path}{filename}"
1765
+ return f"https://storage.googleapis.com/{gcs_location.bucket_name}/{quote(full_file_path)}"
1766
+ ```
1767
+
1768
+ ## `src/snowflake/connector/gcs_storage_client.py` — `function:SnowflakeGCSRestClient._get_local_file_path_from_put_command` (lines 263-301)
1769
+
1770
+ ```python
1771
+ def _get_local_file_path_from_put_command(self) -> str | None:
1772
+ """Get the local file path from PUT command (Logic adopted from JDBC, written by Polita).
1773
+
1774
+ Args:
1775
+ command: Command to be parsed and get the local file path out of.
1776
+
1777
+ Returns:
1778
+ The local file path.
1779
+ """
1780
+ command = self._command
1781
+ if FILE_PROTOCOL not in self._command or not is_put_statement(command):
1782
+ return None
1783
+
1784
+ file_path_begin_index = command.find(FILE_PROTOCOL)
1785
+ is_file_path_quoted = command[file_path_begin_index - 1] == "'"
1786
+ file_path_begin_index += len(FILE_PROTOCOL)
1787
+
1788
+ file_path = ""
1789
+
1790
+ if is_file_path_quoted:
1791
+ file_path_end_index = command.find("'", file_path_begin_index)
1792
+
1793
+ if file_path_end_index > file_path_begin_index:
1794
+ file_path = command[file_path_begin_index:file_path_end_index]
1795
+ else:
1796
+ index_list = []
1797
+ for delimiter in [" ", "\n", ";"]:
1798
+ index = command.find(delimiter, file_path_begin_index)
1799
+ if index != -1:
1800
+ index_list += [index]
1801
+
1802
+ file_path_end_index = min(index_list) if index_list else -1
1803
+
1804
+ if file_path_end_index > file_path_begin_index:
1805
+ file_path = command[file_path_begin_index:file_path_end_index]
1806
+ elif file_path_end_index == -1:
1807
+ file_path = command[file_path_begin_index:]
1808
+
1809
+ return file_path
1810
+ ```
1811
+
1812
+ ## `src/snowflake/connector/gcs_storage_client.py` — `module:<module>@13` (lines 13-13)
1813
+
1814
+ ```python
1815
+ from ._sql_util import is_put_statement
1816
+ ```
1817
+
1818
+ ## `test/unit/test_cursor.py` — `function:test_get_filetransfer_type` (lines 27-51)
1819
+
1820
+ ```python
1821
+ def test_get_filetransfer_type(sql, _type):
1822
+ assert SnowflakeCursor.get_file_transfer_type(sql) == _type
1823
+ ```
tasks/codeql_python_benchmark51_v2/pyvul-1f5068a3fe5ca0192a07/pre_context.md ADDED
@@ -0,0 +1,1755 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Patch-overlapping Python context before the fix
2
+
3
+ ## `src/snowflake/connector/cursor.py` — `class:SnowflakeCursor` (lines 158-1308)
4
+
5
+ ```python
6
+ class SnowflakeCursor:
7
+ """Implementation of Cursor object that is returned from Connection.cursor() method.
8
+
9
+ Attributes:
10
+ description: A list of namedtuples about metadata for all columns.
11
+ rowcount: The number of records updated or selected. If not clear, -1 is returned.
12
+ rownumber: The current 0-based index of the cursor in the result set or None if the index cannot be
13
+ determined.
14
+ sfqid: Snowflake query id in UUID form. Include this in the problem report to the customer support.
15
+ sqlstate: Snowflake SQL State code.
16
+ timestamp_output_format: Snowflake timestamp_output_format for timestamps.
17
+ timestamp_ltz_output_format: Snowflake output format for LTZ timestamps.
18
+ timestamp_tz_output_format: Snowflake output format for TZ timestamps.
19
+ timestamp_ntz_output_format: Snowflake output format for NTZ timestamps.
20
+ date_output_format: Snowflake output format for dates.
21
+ time_output_format: Snowflake output format for times.
22
+ timezone: Snowflake timezone.
23
+ binary_output_format: Snowflake output format for binary fields.
24
+ arraysize: The default number of rows fetched by fetchmany.
25
+ connection: The connection object by which the cursor was created.
26
+ errorhandle: The class that handles error handling.
27
+ is_file_transfer: Whether, or not the current command is a put, or get.
28
+
29
+ TODO:
30
+ Most of these attributes have no reason to be properties, we could just store them in public variables.
31
+ Calling a function is expensive in Python and most of these getters are unnecessary.
32
+ """
33
+
34
+ PUT_SQL_RE = re.compile(r"^(?:/\*.*\*/\s*)*put\s+", flags=re.IGNORECASE)
35
+ GET_SQL_RE = re.compile(r"^(?:/\*.*\*/\s*)*get\s+", flags=re.IGNORECASE)
36
+ INSERT_SQL_RE = re.compile(r"^insert\s+into", flags=re.IGNORECASE)
37
+ COMMENT_SQL_RE = re.compile(r"/\*.*\*/")
38
+ INSERT_SQL_VALUES_RE = re.compile(
39
+ r".*VALUES\s*(\(.*\)).*", re.IGNORECASE | re.MULTILINE | re.DOTALL
40
+ )
41
+ ALTER_SESSION_RE = re.compile(
42
+ r"alter\s+session\s+set\s+(.*)=\'?([^\']+)\'?\s*;",
43
+ flags=re.IGNORECASE | re.MULTILINE | re.DOTALL,
44
+ )
45
+
46
+ @staticmethod
47
+ def get_file_transfer_type(sql: str) -> FileTransferType | None:
48
+ """Decide whether a SQL is a file transfer and return its type.
49
+
50
+ None is returned if the SQL isn't a file transfer so that this function can be
51
+ used in an if-statement.
52
+ """
53
+ if SnowflakeCursor.PUT_SQL_RE.match(sql):
54
+ return FileTransferType.PUT
55
+ elif SnowflakeCursor.GET_SQL_RE.match(sql):
56
+ return FileTransferType.GET
57
+ return None
58
+
59
+ def __init__(
60
+ self,
61
+ connection: SnowflakeConnection,
62
+ use_dict_result: bool = False,
63
+ ) -> None:
64
+ """Inits a SnowflakeCursor with a connection.
65
+
66
+ Args:
67
+ connection: The connection that created this cursor.
68
+ use_dict_result: Decides whether to use dict result or not.
69
+ """
70
+ self._connection: SnowflakeConnection = connection
71
+
72
+ self._errorhandler: Callable[
73
+ [SnowflakeConnection, SnowflakeCursor, type[Error], dict[str, str]],
74
+ None,
75
+ ] = Error.default_errorhandler
76
+ self.messages: list[
77
+ tuple[type[Error] | type[Exception], dict[str, str | bool]]
78
+ ] = []
79
+ self._timebomb: Timer | None = None # must be here for abort_exit method
80
+ self._description: list[ResultMetadata] | None = None
81
+ self._column_idx_to_name = None
82
+ self._sfqid = None
83
+ self._sqlstate = None
84
+ self._total_rowcount = -1
85
+ self._sequence_counter = -1
86
+ self._request_id = None
87
+ self._is_file_transfer = False
88
+
89
+ self._timestamp_output_format = None
90
+ self._timestamp_ltz_output_format = None
91
+ self._timestamp_ntz_output_format = None
92
+ self._timestamp_tz_output_format = None
93
+ self._date_output_format = None
94
+ self._time_output_format = None
95
+ self._timezone = None
96
+ self._binary_output_format = None
97
+ self._result: Iterator[tuple] | Iterator[dict] | None = None
98
+ self._result_set: ResultSet | None = None
99
+ self._result_state: ResultState = ResultState.DEFAULT
100
+ self._use_dict_result = use_dict_result
101
+ self.query: str | None = None
102
+ # TODO: self._query_result_format could be defined as an enum
103
+ self._query_result_format: str | None = None
104
+
105
+ self._arraysize = 1 # PEP-0249: defaults to 1
106
+
107
+ self._lock_canceling = Lock()
108
+
109
+ self._first_chunk_time = None
110
+
111
+ self._log_max_query_length = connection.log_max_query_length
112
+ self._inner_cursor: SnowflakeCursor | None = None
113
+ self._prefetch_hook = None
114
+ self._rownumber: int | None = None
115
+
116
+ self.reset()
117
+
118
+ def __del__(self) -> None: # pragma: no cover
119
+ try:
120
+ self.close()
121
+ except compat.BASE_EXCEPTION_CLASS as e:
122
+ if logger.getEffectiveLevel() <= logging.INFO:
123
+ logger.info(e)
124
+
125
+ @property
126
+ def description(self) -> list[ResultMetadata]:
127
+ return self._description
128
+
129
+ @property
130
+ def rowcount(self):
131
+ return self._total_rowcount if self._total_rowcount >= 0 else None
132
+
133
+ @property
134
+ def rownumber(self):
135
+ return self._rownumber if self._rownumber >= 0 else None
136
+
137
+ @property
138
+ def sfqid(self):
139
+ return self._sfqid
140
+
141
+ @property
142
+ def sqlstate(self):
143
+ return self._sqlstate
144
+
145
+ @property
146
+ def timestamp_output_format(self):
147
+ return self._timestamp_output_format
148
+
149
+ @property
150
+ def timestamp_ltz_output_format(self):
151
+ return (
152
+ self._timestamp_ltz_output_format
153
+ if self._timestamp_ltz_output_format
154
+ else self._timestamp_output_format
155
+ )
156
+
157
+ @property
158
+ def timestamp_tz_output_format(self):
159
+ return (
160
+ self._timestamp_tz_output_format
161
+ if self._timestamp_tz_output_format
162
+ else self._timestamp_output_format
163
+ )
164
+
165
+ @property
166
+ def timestamp_ntz_output_format(self):
167
+ return (
168
+ self._timestamp_ntz_output_format
169
+ if self._timestamp_ntz_output_format
170
+ else self._timestamp_output_format
171
+ )
172
+
173
+ @property
174
+ def date_output_format(self):
175
+ return self._date_output_format
176
+
177
+ @property
178
+ def time_output_format(self):
179
+ return self._time_output_format
180
+
181
+ @property
182
+ def timezone(self):
183
+ return self._timezone
184
+
185
+ @property
186
+ def binary_output_format(self):
187
+ return self._binary_output_format
188
+
189
+ @property
190
+ def arraysize(self):
191
+ return self._arraysize
192
+
193
+ @arraysize.setter
194
+ def arraysize(self, value):
195
+ self._arraysize = int(value)
196
+
197
+ @property
198
+ def connection(self):
199
+ return self._connection
200
+
201
+ @property
202
+ def errorhandler(self):
203
+ return self._errorhandler
204
+
205
+ @errorhandler.setter
206
+ def errorhandler(self, value):
207
+ logger.debug("setting errorhandler: %s", value)
208
+ if value is None:
209
+ raise ProgrammingError("Invalid errorhandler is specified")
210
+ self._errorhandler = value
211
+
212
+ @property
213
+ def is_file_transfer(self):
214
+ """Whether the command is PUT or GET."""
215
+ return hasattr(self, "_is_file_transfer") and self._is_file_transfer
216
+
217
+ @property
218
+ def lastrowid(self) -> None:
219
+ """Snowflake does not support lastrowid in which case None should be returned as per PEP249."""
220
+ return None
221
+
222
+ def callproc(self, procname: str, args: T = ()) -> T:
223
+ """Call a stored procedure.
224
+
225
+ Args:
226
+ procname: The stored procedure to be called.
227
+ args: Parameters to be passed into the stored procedure.
228
+
229
+ Returns:
230
+ The input parameters.
231
+ """
232
+ marker_format = "%s" if self._connection.is_pyformat else "?"
233
+ command = (
234
+ f"CALL {procname}({', '.join([marker_format for _ in range(len(args))])})"
235
+ )
236
+ self.execute(command, args)
237
+ return args
238
+
239
+ def close(self) -> bool | None:
240
+ """Closes the cursor object.
241
+
242
+ Returns whether the cursor was closed during this call.
243
+ """
244
+ try:
245
+ if self.is_closed():
246
+ return False
247
+
248
+ with self._lock_canceling:
249
+ self.reset(closing=True)
250
+ self._connection = None
251
+ del self.messages[:]
252
+ return True
253
+ except Exception:
254
+ pass
255
+
256
+ def is_closed(self):
257
+ return self._connection is None or self._connection.is_closed()
258
+
259
+ def _execute_helper(
260
+ self,
261
+ query: str,
262
+ timeout: int = 0,
263
+ statement_params: dict[str, str] | None = None,
264
+ binding_params: tuple | dict[str, dict[str, str]] = None,
265
+ binding_stage: str | None = None,
266
+ is_internal: bool = False,
267
+ describe_only: bool = False,
268
+ _no_results: bool = False,
269
+ _is_put_get=None,
270
+ _no_retry: bool = False,
271
+ ):
272
+ del self.messages[:]
273
+
274
+ if statement_params is not None and not isinstance(statement_params, dict):
275
+ Error.errorhandler_wrapper(
276
+ self.connection,
277
+ self,
278
+ ProgrammingError,
279
+ {
280
+ "msg": "The data type of statement params is invalid. It must be dict.",
281
+ "errno": ER_INVALID_VALUE,
282
+ },
283
+ )
284
+
285
+ # check if current installation include arrow extension or not,
286
+ # if not, we set statement level query result format to be JSON
287
+ if not CAN_USE_ARROW_RESULT_FORMAT:
288
+ logger.debug("Cannot use arrow result format, fallback to json format")
289
+ if statement_params is None:
290
+ statement_params = {
291
+ PARAMETER_PYTHON_CONNECTOR_QUERY_RESULT_FORMAT: "JSON"
292
+ }
293
+ else:
294
+ result_format_val = statement_params.get(
295
+ PARAMETER_PYTHON_CONNECTOR_QUERY_RESULT_FORMAT
296
+ )
297
+ if str(result_format_val).upper() == "ARROW":
298
+ self.check_can_use_arrow_resultset()
299
+ elif result_format_val is None:
300
+ statement_params[
301
+ PARAMETER_PYTHON_CONNECTOR_QUERY_RESULT_FORMAT
302
+ ] = "JSON"
303
+
304
+ self._sequence_counter = self._connection._next_sequence_counter()
305
+ self._request_id = uuid.uuid4()
306
+
307
+ logger.debug(f"Request id: {self._request_id}")
308
+
309
+ logger.debug("running query [%s]", self._format_query_for_log(query))
310
+ if _is_put_get is not None:
311
+ # if told the query is PUT or GET, use the information
312
+ self._is_file_transfer = _is_put_get
313
+ else:
314
+ # or detect it.
315
+ self._is_file_transfer = self.PUT_SQL_RE.match(
316
+ query
317
+ ) or self.GET_SQL_RE.match(query)
318
+ logger.debug("is_file_transfer: %s", self._is_file_transfer is not None)
319
+
320
+ real_timeout = (
321
+ timeout if timeout and timeout > 0 else self._connection.network_timeout
322
+ )
323
+
324
+ if real_timeout is not None:
325
+ self._timebomb = Timer(real_timeout, self.__cancel_query, [query])
326
+ self._timebomb.start()
327
+ logger.debug("started timebomb in %ss", real_timeout)
328
+ else:
329
+ self._timebomb = None
330
+
331
+ original_sigint = signal.getsignal(signal.SIGINT)
332
+
333
+ def interrupt_handler(*_): # pragma: no cover
334
+ try:
335
+ signal.signal(signal.SIGINT, exit_handler)
336
+ except (ValueError, TypeError):
337
+ # ignore failures
338
+ pass
339
+ try:
340
+ if self._timebomb is not None:
341
+ self._timebomb.cancel()
342
+ logger.debug("cancelled timebomb in finally")
343
+ self._timebomb = None
344
+ self.__cancel_query(query)
345
+ finally:
346
+ if original_sigint:
347
+ try:
348
+ signal.signal(signal.SIGINT, original_sigint)
349
+ except (ValueError, TypeError):
350
+ # ignore failures
351
+ pass
352
+ raise KeyboardInterrupt
353
+
354
+ try:
355
+ if not original_sigint == exit_handler:
356
+ signal.signal(signal.SIGINT, interrupt_handler)
357
+ except ValueError: # pragma: no cover
358
+ logger.debug(
359
+ "Failed to set SIGINT handler. " "Not in main thread. Ignored..."
360
+ )
361
+ ret = {"data": {}}
362
+ try:
363
+ ret = self._connection.cmd_query(
364
+ query,
365
+ self._sequence_counter,
366
+ self._request_id,
367
+ binding_params=binding_params,
368
+ binding_stage=binding_stage,
369
+ is_file_transfer=bool(self._is_file_transfer),
370
+ statement_params=statement_params,
371
+ is_internal=is_internal,
372
+ describe_only=describe_only,
373
+ _no_results=_no_results,
374
+ _no_retry=_no_retry,
375
+ )
376
+ finally:
377
+ try:
378
+ if original_sigint:
379
+ signal.signal(signal.SIGINT, original_sigint)
380
+ except (ValueError, TypeError): # pragma: no cover
381
+ logger.debug(
382
+ "Failed to reset SIGINT handler. Not in main " "thread. Ignored..."
383
+ )
384
+ if self._timebomb is not None:
385
+ self._timebomb.cancel()
386
+ logger.debug("cancelled timebomb in finally")
387
+
388
+ if "data" in ret and "parameters" in ret["data"]:
389
+ parameters = ret["data"]["parameters"]
390
+ # Set session parameters for cursor object
391
+ for kv in parameters:
392
+ if "TIMESTAMP_OUTPUT_FORMAT" in kv["name"]:
393
+ self._timestamp_output_format = kv["value"]
394
+ if "TIMESTAMP_NTZ_OUTPUT_FORMAT" in kv["name"]:
395
+ self._timestamp_ntz_output_format = kv["value"]
396
+ if "TIMESTAMP_LTZ_OUTPUT_FORMAT" in kv["name"]:
397
+ self._timestamp_ltz_output_format = kv["value"]
398
+ if "TIMESTAMP_TZ_OUTPUT_FORMAT" in kv["name"]:
399
+ self._timestamp_tz_output_format = kv["value"]
400
+ if "DATE_OUTPUT_FORMAT" in kv["name"]:
401
+ self._date_output_format = kv["value"]
402
+ if "TIME_OUTPUT_FORMAT" in kv["name"]:
403
+ self._time_output_format = kv["value"]
404
+ if "TIMEZONE" in kv["name"]:
405
+ self._timezone = kv["value"]
406
+ if "BINARY_OUTPUT_FORMAT" in kv["name"]:
407
+ self._binary_output_format = kv["value"]
408
+ # Set session parameters for connection object
409
+ self._connection._update_parameters(
410
+ {p["name"]: p["value"] for p in parameters}
411
+ )
412
+
413
+ self.query = query
414
+ self._sequence_counter = -1
415
+ return ret
416
+
417
+ def execute(
418
+ self,
419
+ command: str,
420
+ params: Sequence[Any] | dict[Any, Any] | None = None,
421
+ _bind_stage: str | None = None,
422
+ timeout: int | None = None,
423
+ _exec_async: bool = False,
424
+ _no_retry: bool = False,
425
+ _do_reset: bool = True,
426
+ _put_callback: SnowflakeProgressPercentage = None,
427
+ _put_azure_callback: SnowflakeProgressPercentage = None,
428
+ _put_callback_output_stream: IO[str] = sys.stdout,
429
+ _get_callback: SnowflakeProgressPercentage = None,
430
+ _get_azure_callback: SnowflakeProgressPercentage = None,
431
+ _get_callback_output_stream: IO[str] = sys.stdout,
432
+ _show_progress_bar: bool = True,
433
+ _statement_params: dict[str, str] | None = None,
434
+ _is_internal: bool = False,
435
+ _describe_only: bool = False,
436
+ _no_results: bool = False,
437
+ _is_put_get: bool | None = None,
438
+ _raise_put_get_error: bool = True,
439
+ _force_put_overwrite: bool = False,
440
+ file_stream: IO[bytes] | None = None,
441
+ ) -> SnowflakeCursor | None:
442
+ """Executes a command/query.
443
+
444
+ Args:
445
+ command: The SQL command to be executed.
446
+ params: Parameters to be bound into the SQL statement.
447
+ _bind_stage: Path in temporary stage where binding parameters are uploaded as CSV files.
448
+ timeout: Number of seconds after which to abort the query.
449
+ _exec_async: Whether to execute this query asynchronously.
450
+ _no_retry: Whether or not to retry on known errors.
451
+ _do_reset: Whether or not the result set needs to be reset before executing query.
452
+ _put_callback: Function to which GET command should call back to.
453
+ _put_azure_callback: Function to which an Azure GET command should call back to.
454
+ _put_callback_output_stream: The output stream a PUT command's callback should report on.
455
+ _get_callback: Function to which GET command should call back to.
456
+ _get_azure_callback: Function to which an Azure GET command should call back to.
457
+ _get_callback_output_stream: The output stream a GET command's callback should report on.
458
+ _show_progress_bar: Whether or not to show progress bar.
459
+ _statement_params: Extra information that should be sent to Snowflake with query.
460
+ _is_internal: This flag indicates whether the query is issued internally by the connector.
461
+ _describe_only: If true, the query will not be executed but return the schema/description of this query.
462
+ _no_results: This flag tells the back-end to not return the result, just fire the query and return the
463
+ response returned by Snowflake's server.
464
+ _use_ijson: This flag doesn't do anything as ijson support has ended.
465
+ _is_put_get: Force decision of this SQL query being a PUT, or GET command. This is detected otherwise.
466
+ _raise_put_get_error: Whether to raise PUT and GET errors.
467
+ _force_put_overwrite: If the SQL query is a PUT, then this flag can force overwriting of an already
468
+ existing file on stage.
469
+ file_stream: File-like object to be uploaded with PUT
470
+
471
+ Returns:
472
+ The cursor itself, or None if some error happened, or the response returned
473
+ by Snowflake if the _no_results flag is on.
474
+ """
475
+ if _exec_async:
476
+ _no_results = True
477
+ logger.debug("executing SQL/command")
478
+ if self.is_closed():
479
+ Error.errorhandler_wrapper(
480
+ self.connection,
481
+ self,
482
+ InterfaceError,
483
+ {"msg": "Cursor is closed in execute.", "errno": ER_CURSOR_IS_CLOSED},
484
+ )
485
+
486
+ if _do_reset:
487
+ self.reset()
488
+ command = command.strip(" \t\n\r") if command else None
489
+ if not command:
490
+ logger.warning("execute: no query is given to execute")
491
+ return
492
+
493
+ kwargs = {
494
+ "timeout": timeout,
495
+ "statement_params": _statement_params,
496
+ "is_internal": _is_internal,
497
+ "describe_only": _describe_only,
498
+ "_no_results": _no_results,
499
+ "_is_put_get": _is_put_get,
500
+ "_no_retry": _no_retry,
501
+ }
502
+
503
+ if self._connection.is_pyformat:
504
+ # pyformat/format paramstyle
505
+ # client side binding
506
+ processed_params = self._connection._process_params_pyformat(params, self)
507
+ # SNOW-513061 collect telemetry for empty sequence usage before we make the breaking change announcement
508
+ if params is not None and len(params) == 0:
509
+ self._log_telemetry_job_data(
510
+ TelemetryField.EMPTY_SEQ_INTERPOLATION,
511
+ TelemetryData.TRUE
512
+ if self.connection._interpolate_empty_sequences
513
+ else TelemetryData.FALSE,
514
+ )
515
+ if logger.getEffectiveLevel() <= logging.DEBUG:
516
+ logger.debug(
517
+ f"binding: [{self._format_query_for_log(command)}] "
518
+ f"with input=[{params}], "
519
+ f"processed=[{processed_params}]",
520
+ )
521
+ if (
522
+ self.connection._interpolate_empty_sequences
523
+ and processed_params is not None
524
+ ) or (
525
+ not self.connection._interpolate_empty_sequences
526
+ and len(processed_params) > 0
527
+ ):
528
+ query = command % processed_params
529
+ else:
530
+ query = command
531
+ else:
532
+ # qmark and numeric paramstyle
533
+ query = command
534
+ if _bind_stage:
535
+ kwargs["binding_stage"] = _bind_stage
536
+ else:
537
+ if params is not None and not isinstance(params, (list, tuple)):
538
+ errorvalue = {
539
+ "msg": f"Binding parameters must be a list: {params}",
540
+ "errno": ER_FAILED_PROCESSING_PYFORMAT,
541
+ }
542
+ Error.errorhandler_wrapper(
543
+ self.connection, self, ProgrammingError, errorvalue
544
+ )
545
+
546
+ kwargs["binding_params"] = self._connection._process_params_qmarks(
547
+ params, self
548
+ )
549
+
550
+ m = DESC_TABLE_RE.match(query)
551
+ if m:
552
+ query1 = f"describe table {m.group(1)}"
553
+ if logger.getEffectiveLevel() <= logging.WARNING:
554
+ logger.info(
555
+ "query was rewritten: org=%s, new=%s",
556
+ " ".join(line.strip() for line in query.split("\n")),
557
+ query1,
558
+ )
559
+ query = query1
560
+
561
+ if logger.getEffectiveLevel() <= logging.INFO:
562
+ logger.info("query: [%s]", self._format_query_for_log(query))
563
+ ret = self._execute_helper(query, **kwargs)
564
+ self._sfqid = (
565
+ ret["data"]["queryId"]
566
+ if "data" in ret and "queryId" in ret["data"]
567
+ else None
568
+ )
569
+ self._sqlstate = (
570
+ ret["data"]["sqlState"]
571
+ if "data" in ret and "sqlState" in ret["data"]
572
+ else None
573
+ )
574
+ self._first_chunk_time = get_time_millis()
575
+
576
+ # if server gives a send time, log the time it took to arrive
577
+ if "data" in ret and "sendResultTime" in ret["data"]:
578
+ time_consume_first_result = (
579
+ self._first_chunk_time - ret["data"]["sendResultTime"]
580
+ )
581
+ self._log_telemetry_job_data(
582
+ TelemetryField.TIME_CONSUME_FIRST_RESULT, time_consume_first_result
583
+ )
584
+ logger.debug("sfqid: %s", self.sfqid)
585
+
586
+ logger.info("query execution done")
587
+ if ret["success"]:
588
+ logger.debug("SUCCESS")
589
+ data = ret["data"]
590
+
591
+ logger.debug("PUT OR GET: %s", self.is_file_transfer)
592
+ if self.is_file_transfer:
593
+ # Decide whether to use the old, or new code path
594
+ sf_file_transfer_agent = SnowflakeFileTransferAgent(
595
+ self,
596
+ query,
597
+ ret,
598
+ put_callback=_put_callback,
599
+ put_azure_callback=_put_azure_callback,
600
+ put_callback_output_stream=_put_callback_output_stream,
601
+ get_callback=_get_callback,
602
+ get_azure_callback=_get_azure_callback,
603
+ get_callback_output_stream=_get_callback_output_stream,
604
+ show_progress_bar=_show_progress_bar,
605
+ raise_put_get_error=_raise_put_get_error,
606
+ force_put_overwrite=_force_put_overwrite
607
+ or data.get("overwrite", False),
608
+ source_from_stream=file_stream,
609
+ multipart_threshold=data.get("threshold"),
610
+ use_s3_regional_url=self._connection.enable_stage_s3_privatelink_for_us_east_1,
611
+ )
612
+ sf_file_transfer_agent.execute()
613
+ data = sf_file_transfer_agent.result()
614
+ self._total_rowcount = len(data["rowset"]) if "rowset" in data else -1
615
+ m = self.ALTER_SESSION_RE.match(query)
616
+ if m:
617
+ # session parameters
618
+ param = m.group(1).upper()
619
+ value = m.group(2)
620
+ self._connection.converter.set_parameter(param, value)
621
+
622
+ if _exec_async:
623
+ self.connection._async_sfqids[self._sfqid] = None
624
+ if _no_results:
625
+ self._total_rowcount = (
626
+ ret["data"]["total"]
627
+ if "data" in ret and "total" in ret["data"]
628
+ else -1
629
+ )
630
+ return data
631
+ self._init_result_and_meta(data)
632
+ else:
633
+ self._total_rowcount = (
634
+ ret["data"]["total"] if "data" in ret and "total" in ret["data"] else -1
635
+ )
636
+ logger.debug(ret)
637
+ err = ret["message"]
638
+ code = ret.get("code", -1)
639
+ if "data" in ret:
640
+ err += ret["data"].get("errorMessage", "")
641
+ errvalue = {
642
+ "msg": err,
643
+ "errno": int(code),
644
+ "sqlstate": self._sqlstate,
645
+ "sfqid": self._sfqid,
646
+ }
647
+ is_integrity_error = (
648
+ code == "100072"
649
+ ) # NULL result in a non-nullable column
650
+ error_class = IntegrityError if is_integrity_error else ProgrammingError
651
+ Error.errorhandler_wrapper(self.connection, self, error_class, errvalue)
652
+ return self
653
+
654
+ def execute_async(self, *args, **kwargs):
655
+ """Convenience function to execute a query without waiting for results (asynchronously).
656
+
657
+ This function takes the same arguments as execute, please refer to that function
658
+ for documentation.
659
+ """
660
+ kwargs["_exec_async"] = True
661
+ return self.execute(*args, **kwargs)
662
+
663
+ def describe(self, *args, **kwargs) -> list[ResultMetadata]:
664
+ """Obtain the schema of the result without executing the query.
665
+
666
+ This function takes the same arguments as execute, please refer to that function
667
+ for documentation.
668
+
669
+ Returns:
670
+ The schema of the result.
671
+ """
672
+ kwargs["_describe_only"] = kwargs["_is_internal"] = True
673
+ self.execute(*args, **kwargs)
674
+ return self._description
675
+
676
+ def _format_query_for_log(self, query):
677
+ return self._connection._format_query_for_log(query)
678
+
679
+ def _is_dml(self, data):
680
+ return (
681
+ "statementTypeId" in data
682
+ and int(data["statementTypeId"]) in STATEMENT_TYPE_ID_DML_SET
683
+ )
684
+
685
+ def _init_result_and_meta(self, data):
686
+ is_dml = self._is_dml(data)
687
+ self._query_result_format = data.get("queryResultFormat", "json")
688
+ logger.debug("Query result format: %s", self._query_result_format)
689
+
690
+ if self._total_rowcount == -1 and not is_dml and data.get("total") is not None:
691
+ self._total_rowcount = data["total"]
692
+
693
+ self._description: list[ResultMetadata] = [
694
+ ResultMetadata.from_column(col) for col in data["rowtype"]
695
+ ]
696
+
697
+ result_chunks = create_batches_from_response(
698
+ self, self._query_result_format, data, self._description
699
+ )
700
+
701
+ if not (is_dml or self.is_file_transfer):
702
+ logger.info(
703
+ "Number of results in first chunk: %s", result_chunks[0].rowcount
704
+ )
705
+
706
+ self._result_set = ResultSet(
707
+ self,
708
+ result_chunks,
709
+ self._connection.client_prefetch_threads,
710
+ )
711
+ self._rownumber = -1
712
+ self._result_state = ResultState.VALID
713
+
714
+ # don't update the row count when the result is returned from `describe` method
715
+ if is_dml and "rowset" in data and len(data["rowset"]) > 0:
716
+ updated_rows = 0
717
+ for idx, desc in enumerate(self._description):
718
+ if desc[0] in (
719
+ "number of rows updated",
720
+ "number of multi-joined rows updated",
721
+ "number of rows deleted",
722
+ ) or desc[0].startswith("number of rows inserted"):
723
+ updated_rows += int(data["rowset"][0][idx])
724
+ if self._total_rowcount == -1:
725
+ self._total_rowcount = updated_rows
726
+ else:
727
+ self._total_rowcount += updated_rows
728
+
729
+ def check_can_use_arrow_resultset(self):
730
+ global CAN_USE_ARROW_RESULT_FORMAT
731
+
732
+ if not CAN_USE_ARROW_RESULT_FORMAT:
733
+ if self._connection.application == "SnowSQL":
734
+ msg = "Currently SnowSQL doesn't support the result set in Apache Arrow format."
735
+ errno = ER_NO_PYARROW_SNOWSQL
736
+ else:
737
+ msg = "The result set in Apache Arrow format is not supported for the platform."
738
+ errno = ER_NO_ARROW_RESULT
739
+
740
+ Error.errorhandler_wrapper(
741
+ self.connection,
742
+ self,
743
+ ProgrammingError,
744
+ {
745
+ "msg": msg,
746
+ "errno": errno,
747
+ },
748
+ )
749
+
750
+ def check_can_use_pandas(self):
751
+ if not installed_pandas:
752
+ msg = (
753
+ "Optional dependency: 'pandas' is not installed, please see the following link for install "
754
+ "instructions: https://docs.snowflake.com/en/user-guide/python-connector-pandas.html#installation"
755
+ )
756
+ errno = ER_NO_PYARROW
757
+
758
+ Error.errorhandler_wrapper(
759
+ self.connection,
760
+ self,
761
+ ProgrammingError,
762
+ {
763
+ "msg": msg,
764
+ "errno": errno,
765
+ },
766
+ )
767
+
768
+ def query_result(self, qid):
769
+ url = f"/queries/{qid}/result"
770
+ ret = self._connection.rest.request(url=url, method="get")
771
+ self._sfqid = (
772
+ ret["data"]["queryId"]
773
+ if "data" in ret and "queryId" in ret["data"]
774
+ else None
775
+ )
776
+ self._sqlstate = (
777
+ ret["data"]["sqlState"]
778
+ if "data" in ret and "sqlState" in ret["data"]
779
+ else None
780
+ )
781
+ logger.debug("sfqid=%s", self._sfqid)
782
+
783
+ if ret.get("success"):
784
+ data = ret.get("data")
785
+ self._init_result_and_meta(data)
786
+ else:
787
+ logger.info("failed")
788
+ logger.debug(ret)
789
+ err = ret["message"]
790
+ code = ret.get("code", -1)
791
+ if "data" in ret:
792
+ err += ret["data"].get("errorMessage", "")
793
+ errvalue = {
794
+ "msg": err,
795
+ "errno": int(code),
796
+ "sqlstate": self._sqlstate,
797
+ "sfqid": self._sfqid,
798
+ }
799
+ Error.errorhandler_wrapper(
800
+ self.connection, self, ProgrammingError, errvalue
801
+ )
802
+ return self
803
+
804
+ def fetch_arrow_batches(self) -> Iterator[Table]:
805
+ self.check_can_use_arrow_resultset()
806
+ if self._query_result_format != "arrow":
807
+ raise NotSupportedError
808
+ self._log_telemetry_job_data(
809
+ TelemetryField.ARROW_FETCH_BATCHES, TelemetryData.TRUE
810
+ )
811
+ return self._result_set._fetch_arrow_batches()
812
+
813
+ def fetch_arrow_all(self) -> Table | None:
814
+ self.check_can_use_arrow_resultset()
815
+ if self._query_result_format != "arrow":
816
+ raise NotSupportedError
817
+ self._log_telemetry_job_data(TelemetryField.ARROW_FETCH_ALL, TelemetryData.TRUE)
818
+ return self._result_set._fetch_arrow_all()
819
+
820
+ def fetch_pandas_batches(self, **kwargs) -> Iterator[pandas.DataFrame]:
821
+ """Fetches a single Arrow Table."""
822
+ self.check_can_use_pandas()
823
+ if self._prefetch_hook is not None:
824
+ self._prefetch_hook()
825
+ if self._query_result_format != "arrow":
826
+ raise NotSupportedError
827
+ self._log_telemetry_job_data(
828
+ TelemetryField.PANDAS_FETCH_BATCHES, TelemetryData.TRUE
829
+ )
830
+ return self._result_set._fetch_pandas_batches(**kwargs)
831
+
832
+ def fetch_pandas_all(self, **kwargs) -> pandas.DataFrame:
833
+ """Fetch Pandas dataframes in batches, where 'batch' refers to Snowflake Chunk."""
834
+ self.check_can_use_pandas()
835
+ if self._prefetch_hook is not None:
836
+ self._prefetch_hook()
837
+ if self._query_result_format != "arrow":
838
+ raise NotSupportedError
839
+ self._log_telemetry_job_data(
840
+ TelemetryField.PANDAS_FETCH_ALL, TelemetryData.TRUE
841
+ )
842
+ return self._result_set._fetch_pandas_all(**kwargs)
843
+
844
+ def abort_query(self, qid):
845
+ url = f"/queries/{qid}/abort-request"
846
+ ret = self._connection.rest.request(url=url, method="post")
847
+ return ret.get("success")
848
+
849
+ def executemany(
850
+ self,
851
+ command: str,
852
+ seqparams: Sequence[Any] | dict[str, Any],
853
+ **kwargs: dict[str, Any],
854
+ ) -> SnowflakeCursor:
855
+ """Executes a command/query with the given set of parameters sequentially."""
856
+ logger.debug("executing many SQLs/commands")
857
+ command = command.strip(" \t\n\r") if command else None
858
+
859
+ if not seqparams:
860
+ return self
861
+
862
+ if self.INSERT_SQL_RE.match(command):
863
+ if self._connection.is_pyformat:
864
+ logger.debug("rewriting INSERT query")
865
+ command_wo_comments = re.sub(self.COMMENT_SQL_RE, "", command)
866
+ m = self.INSERT_SQL_VALUES_RE.match(command_wo_comments)
867
+ if not m:
868
+ Error.errorhandler_wrapper(
869
+ self.connection,
870
+ self,
871
+ InterfaceError,
872
+ {
873
+ "msg": "Failed to rewrite multi-row insert",
874
+ "errno": ER_FAILED_TO_REWRITE_MULTI_ROW_INSERT,
875
+ },
876
+ )
877
+
878
+ fmt = m.group(1)
879
+ values = []
880
+ for param in seqparams:
881
+ logger.debug(f"parameter: {param}")
882
+ values.append(
883
+ fmt % self._connection._process_params_pyformat(param, self)
884
+ )
885
+ command = command.replace(fmt, ",".join(values), 1)
886
+ self.execute(command, **kwargs)
887
+ return self
888
+ else:
889
+ logger.debug("bulk insert")
890
+ # sanity check
891
+ row_size = len(seqparams[0])
892
+ for row in seqparams:
893
+ if len(row) != row_size:
894
+ error_value = {
895
+ "msg": f"Bulk data size don't match. expected: {row_size}, "
896
+ f"got: {len(row)}, command: {command}",
897
+ "errno": ER_INVALID_VALUE,
898
+ }
899
+ Error.errorhandler_wrapper(
900
+ self.connection, self, InterfaceError, error_value
901
+ )
902
+ return self
903
+ bind_size = len(seqparams) * row_size
904
+ bind_stage = None
905
+ if (
906
+ bind_size
907
+ > self.connection._session_parameters[
908
+ "CLIENT_STAGE_ARRAY_BINDING_THRESHOLD"
909
+ ]
910
+ > 0
911
+ ):
912
+ # bind stage optimization
913
+ try:
914
+ rows = self.connection._write_params_to_byte_rows(seqparams)
915
+ bind_uploader = BindUploadAgent(self, rows)
916
+ bind_uploader.upload()
917
+ bind_stage = bind_uploader.stage_path
918
+ except BindUploadError:
919
+ logger.debug(
920
+ "Failed to upload binds to stage, sending binds to "
921
+ "Snowflake instead."
922
+ )
923
+ binding_param = (
924
+ None if bind_stage else list(map(list, zip(*seqparams)))
925
+ ) # transpose
926
+ self.execute(
927
+ command, params=binding_param, _bind_stage=bind_stage, **kwargs
928
+ )
929
+ return self
930
+
931
+ self.reset()
932
+ for param in seqparams:
933
+ self.execute(command, params=param, _do_reset=False, **kwargs)
934
+ return self
935
+
936
+ def _result_iterator(
937
+ self,
938
+ ) -> Generator[dict, None, None] | Generator[tuple, None, None]:
939
+ """Yields the elements from _result and raises an exception when appropriate."""
940
+ try:
941
+ for _next in self._result:
942
+ if isinstance(_next, Exception):
943
+ Error.errorhandler_wrapper_from_ready_exception(
944
+ self._connection,
945
+ self,
946
+ _next,
947
+ )
948
+ self._rownumber += 1
949
+ yield _next
950
+ except TypeError as err:
951
+ if self._result_state == ResultState.DEFAULT:
952
+ raise err
953
+ else:
954
+ yield None
955
+
956
+ def fetchone(self) -> dict | tuple | None:
957
+ """Fetches one row."""
958
+ if self._prefetch_hook is not None:
959
+ self._prefetch_hook()
960
+ if self._result is None and self._result_set is not None:
961
+ self._result = iter(self._result_set)
962
+ self._result_state = ResultState.VALID
963
+ try:
964
+ return next(self._result_iterator())
965
+ except StopIteration:
966
+ return None
967
+
968
+ def fetchmany(self, size=None):
969
+ """Fetches the number of specified rows."""
970
+ if size is None:
971
+ size = self.arraysize
972
+
973
+ if size < 0:
974
+ errorvalue = {
975
+ "msg": (
976
+ "The number of rows is not zero or " "positive number: {}"
977
+ ).format(size),
978
+ "errno": ER_NOT_POSITIVE_SIZE,
979
+ }
980
+ Error.errorhandler_wrapper(
981
+ self.connection, self, ProgrammingError, errorvalue
982
+ )
983
+ ret = []
984
+ while size > 0:
985
+ row = self.fetchone()
986
+ if row is None:
987
+ break
988
+ ret.append(row)
989
+ if size is not None:
990
+ size -= 1
991
+
992
+ return ret
993
+
994
+ def fetchall(self) -> list[tuple] | list[dict]:
995
+ """Fetches all of the results."""
996
+ ret = []
997
+ while True:
998
+ row = self.fetchone()
999
+ if row is None:
1000
+ break
1001
+ ret.append(row)
1002
+ return ret
1003
+
1004
+ def nextset(self):
1005
+ """Not supported."""
1006
+ logger.debug("nop")
1007
+ return None
1008
+
1009
+ def setinputsizes(self, _):
1010
+ """Not supported."""
1011
+ logger.debug("nop")
1012
+
1013
+ def setoutputsize(self, _, column=None):
1014
+ """Not supported."""
1015
+ del column
1016
+ logger.debug("nop")
1017
+
1018
+ def scroll(self, value, mode="relative"):
1019
+ Error.errorhandler_wrapper(
1020
+ self.connection,
1021
+ self,
1022
+ NotSupportedError,
1023
+ {
1024
+ "msg": "scroll is not supported.",
1025
+ "errno": ER_UNSUPPORTED_METHOD,
1026
+ "sqlstate": SQLSTATE_FEATURE_NOT_SUPPORTED,
1027
+ },
1028
+ )
1029
+
1030
+ def reset(self, closing=False):
1031
+ """Resets the result set."""
1032
+ # SNOW-647539: Do not erase the rowcount
1033
+ # information when closing the cursor
1034
+ if not closing:
1035
+ self._total_rowcount = -1
1036
+ if self._result_state != ResultState.DEFAULT:
1037
+ self._result_state = ResultState.RESET
1038
+ if self._result is not None:
1039
+ self._result = None
1040
+ if self._inner_cursor is not None:
1041
+ self._inner_cursor.reset(closing=closing)
1042
+ self._result = None
1043
+ self._inner_cursor = None
1044
+ self._prefetch_hook = None
1045
+ if not self.connection._reuse_results:
1046
+ self._result_set = None
1047
+
1048
+ def __iter__(self) -> Iterator[dict] | Iterator[tuple]:
1049
+ """Iteration over the result set."""
1050
+ # set _result if _result_set is not None
1051
+ if self._result is None and self._result_set is not None:
1052
+ self._result = iter(self._result_set)
1053
+ self._result_state = ResultState.VALID
1054
+ return self._result_iterator()
1055
+
1056
+ def __cancel_query(self, query):
1057
+ if self._sequence_counter >= 0 and not self.is_closed():
1058
+ logger.debug("canceled. %s, request_id: %s", query, self._request_id)
1059
+ with self._lock_canceling:
1060
+ self._connection._cancel_query(query, self._request_id)
1061
+
1062
+ def _log_telemetry_job_data(
1063
+ self, telemetry_field: TelemetryField, value: Any
1064
+ ) -> None:
1065
+ """Builds an instance of TelemetryData with the given field and logs it."""
1066
+ ts = get_time_millis()
1067
+ try:
1068
+ self._connection._log_telemetry(
1069
+ TelemetryData.from_telemetry_data_dict(
1070
+ from_dict={
1071
+ TelemetryField.KEY_TYPE.value: telemetry_field.value,
1072
+ TelemetryField.KEY_SFQID.value: self._sfqid,
1073
+ TelemetryField.KEY_VALUE.value: value,
1074
+ },
1075
+ timestamp=ts,
1076
+ connection=self._connection,
1077
+ )
1078
+ )
1079
+ except AttributeError:
1080
+ logger.warning(
1081
+ "Cursor failed to log to telemetry. Connection object may be None.",
1082
+ exc_info=True,
1083
+ )
1084
+
1085
+ def __enter__(self):
1086
+ """Context manager."""
1087
+ return self
1088
+
1089
+ def __exit__(self, exc_type, exc_val, exc_tb):
1090
+ """Context manager with commit or rollback."""
1091
+ self.close()
1092
+
1093
+ def get_results_from_sfqid(self, sfqid: str):
1094
+ """Gets the results from previously ran query."""
1095
+
1096
+ def wait_until_ready():
1097
+ """Makes sure query has finished executing and once it has retrieves results."""
1098
+ no_data_counter = 0
1099
+ retry_pattern_pos = 0
1100
+ while True:
1101
+ status = self.connection.get_query_status(sfqid)
1102
+ if not self.connection.is_still_running(status):
1103
+ break
1104
+ if status == QueryStatus.NO_DATA: # pragma: no cover
1105
+ no_data_counter += 1
1106
+ if no_data_counter > ASYNC_NO_DATA_MAX_RETRY:
1107
+ raise DatabaseError(
1108
+ "Cannot retrieve data on the status of this query. No information returned "
1109
+ "from server for query '{}'"
1110
+ )
1111
+ time.sleep(
1112
+ 0.5 * ASYNC_RETRY_PATTERN[retry_pattern_pos]
1113
+ ) # Same wait as JDBC
1114
+ # If we can advance in ASYNC_RETRY_PATTERN then do so
1115
+ if retry_pattern_pos < (len(ASYNC_RETRY_PATTERN) - 1):
1116
+ retry_pattern_pos += 1
1117
+ if status != QueryStatus.SUCCESS:
1118
+ raise DatabaseError(
1119
+ "Status of query '{}' is {}, results are unavailable".format(
1120
+ sfqid, status.name
1121
+ )
1122
+ )
1123
+ self._inner_cursor.execute(f"select * from table(result_scan('{sfqid}'))")
1124
+ self._result = self._inner_cursor._result
1125
+ self._query_result_format = self._inner_cursor._query_result_format
1126
+ self._total_rowcount = self._inner_cursor._total_rowcount
1127
+ self._description = self._inner_cursor._description
1128
+ self._result_set = self._inner_cursor._result_set
1129
+ self._result_state = ResultState.VALID
1130
+ self._rownumber = 0
1131
+ # Unset this function, so that we don't block anymore
1132
+ self._prefetch_hook = None
1133
+
1134
+ self.connection.get_query_status_throw_if_error(
1135
+ sfqid
1136
+ ) # Trigger an exception if query failed
1137
+ klass = self.__class__
1138
+ self._inner_cursor = klass(self.connection)
1139
+ self._sfqid = sfqid
1140
+ self._prefetch_hook = wait_until_ready
1141
+
1142
+ def get_result_batches(self) -> list[ResultBatch] | None:
1143
+ """Get the previously executed query's ``ResultBatch`` s if available.
1144
+
1145
+ If they are unavailable, in case nothing has been executed yet None will
1146
+ be returned.
1147
+
1148
+ For a detailed description of ``ResultBatch`` s please see the docstring of:
1149
+ ``snowflake.connector.result_batches.ResultBatch``
1150
+ """
1151
+ if self._result_set is None:
1152
+ return None
1153
+ self._log_telemetry_job_data(
1154
+ TelemetryField.GET_PARTITIONS_USED, TelemetryData.TRUE
1155
+ )
1156
+ return self._result_set.batches
1157
+ ```
1158
+
1159
+ ## `src/snowflake/connector/cursor.py` — `function:SnowflakeCursor.get_file_transfer_type` (lines 198-209)
1160
+
1161
+ ```python
1162
+ def get_file_transfer_type(sql: str) -> FileTransferType | None:
1163
+ """Decide whether a SQL is a file transfer and return its type.
1164
+
1165
+ None is returned if the SQL isn't a file transfer so that this function can be
1166
+ used in an if-statement.
1167
+ """
1168
+ if SnowflakeCursor.PUT_SQL_RE.match(sql):
1169
+ return FileTransferType.PUT
1170
+ elif SnowflakeCursor.GET_SQL_RE.match(sql):
1171
+ return FileTransferType.GET
1172
+ return None
1173
+ ```
1174
+
1175
+ ## `src/snowflake/connector/cursor.py` — `function:SnowflakeCursor._execute_helper` (lines 411-567)
1176
+
1177
+ ```python
1178
+ def _execute_helper(
1179
+ self,
1180
+ query: str,
1181
+ timeout: int = 0,
1182
+ statement_params: dict[str, str] | None = None,
1183
+ binding_params: tuple | dict[str, dict[str, str]] = None,
1184
+ binding_stage: str | None = None,
1185
+ is_internal: bool = False,
1186
+ describe_only: bool = False,
1187
+ _no_results: bool = False,
1188
+ _is_put_get=None,
1189
+ _no_retry: bool = False,
1190
+ ):
1191
+ del self.messages[:]
1192
+
1193
+ if statement_params is not None and not isinstance(statement_params, dict):
1194
+ Error.errorhandler_wrapper(
1195
+ self.connection,
1196
+ self,
1197
+ ProgrammingError,
1198
+ {
1199
+ "msg": "The data type of statement params is invalid. It must be dict.",
1200
+ "errno": ER_INVALID_VALUE,
1201
+ },
1202
+ )
1203
+
1204
+ # check if current installation include arrow extension or not,
1205
+ # if not, we set statement level query result format to be JSON
1206
+ if not CAN_USE_ARROW_RESULT_FORMAT:
1207
+ logger.debug("Cannot use arrow result format, fallback to json format")
1208
+ if statement_params is None:
1209
+ statement_params = {
1210
+ PARAMETER_PYTHON_CONNECTOR_QUERY_RESULT_FORMAT: "JSON"
1211
+ }
1212
+ else:
1213
+ result_format_val = statement_params.get(
1214
+ PARAMETER_PYTHON_CONNECTOR_QUERY_RESULT_FORMAT
1215
+ )
1216
+ if str(result_format_val).upper() == "ARROW":
1217
+ self.check_can_use_arrow_resultset()
1218
+ elif result_format_val is None:
1219
+ statement_params[
1220
+ PARAMETER_PYTHON_CONNECTOR_QUERY_RESULT_FORMAT
1221
+ ] = "JSON"
1222
+
1223
+ self._sequence_counter = self._connection._next_sequence_counter()
1224
+ self._request_id = uuid.uuid4()
1225
+
1226
+ logger.debug(f"Request id: {self._request_id}")
1227
+
1228
+ logger.debug("running query [%s]", self._format_query_for_log(query))
1229
+ if _is_put_get is not None:
1230
+ # if told the query is PUT or GET, use the information
1231
+ self._is_file_transfer = _is_put_get
1232
+ else:
1233
+ # or detect it.
1234
+ self._is_file_transfer = self.PUT_SQL_RE.match(
1235
+ query
1236
+ ) or self.GET_SQL_RE.match(query)
1237
+ logger.debug("is_file_transfer: %s", self._is_file_transfer is not None)
1238
+
1239
+ real_timeout = (
1240
+ timeout if timeout and timeout > 0 else self._connection.network_timeout
1241
+ )
1242
+
1243
+ if real_timeout is not None:
1244
+ self._timebomb = Timer(real_timeout, self.__cancel_query, [query])
1245
+ self._timebomb.start()
1246
+ logger.debug("started timebomb in %ss", real_timeout)
1247
+ else:
1248
+ self._timebomb = None
1249
+
1250
+ original_sigint = signal.getsignal(signal.SIGINT)
1251
+
1252
+ def interrupt_handler(*_): # pragma: no cover
1253
+ try:
1254
+ signal.signal(signal.SIGINT, exit_handler)
1255
+ except (ValueError, TypeError):
1256
+ # ignore failures
1257
+ pass
1258
+ try:
1259
+ if self._timebomb is not None:
1260
+ self._timebomb.cancel()
1261
+ logger.debug("cancelled timebomb in finally")
1262
+ self._timebomb = None
1263
+ self.__cancel_query(query)
1264
+ finally:
1265
+ if original_sigint:
1266
+ try:
1267
+ signal.signal(signal.SIGINT, original_sigint)
1268
+ except (ValueError, TypeError):
1269
+ # ignore failures
1270
+ pass
1271
+ raise KeyboardInterrupt
1272
+
1273
+ try:
1274
+ if not original_sigint == exit_handler:
1275
+ signal.signal(signal.SIGINT, interrupt_handler)
1276
+ except ValueError: # pragma: no cover
1277
+ logger.debug(
1278
+ "Failed to set SIGINT handler. " "Not in main thread. Ignored..."
1279
+ )
1280
+ ret = {"data": {}}
1281
+ try:
1282
+ ret = self._connection.cmd_query(
1283
+ query,
1284
+ self._sequence_counter,
1285
+ self._request_id,
1286
+ binding_params=binding_params,
1287
+ binding_stage=binding_stage,
1288
+ is_file_transfer=bool(self._is_file_transfer),
1289
+ statement_params=statement_params,
1290
+ is_internal=is_internal,
1291
+ describe_only=describe_only,
1292
+ _no_results=_no_results,
1293
+ _no_retry=_no_retry,
1294
+ )
1295
+ finally:
1296
+ try:
1297
+ if original_sigint:
1298
+ signal.signal(signal.SIGINT, original_sigint)
1299
+ except (ValueError, TypeError): # pragma: no cover
1300
+ logger.debug(
1301
+ "Failed to reset SIGINT handler. Not in main " "thread. Ignored..."
1302
+ )
1303
+ if self._timebomb is not None:
1304
+ self._timebomb.cancel()
1305
+ logger.debug("cancelled timebomb in finally")
1306
+
1307
+ if "data" in ret and "parameters" in ret["data"]:
1308
+ parameters = ret["data"]["parameters"]
1309
+ # Set session parameters for cursor object
1310
+ for kv in parameters:
1311
+ if "TIMESTAMP_OUTPUT_FORMAT" in kv["name"]:
1312
+ self._timestamp_output_format = kv["value"]
1313
+ if "TIMESTAMP_NTZ_OUTPUT_FORMAT" in kv["name"]:
1314
+ self._timestamp_ntz_output_format = kv["value"]
1315
+ if "TIMESTAMP_LTZ_OUTPUT_FORMAT" in kv["name"]:
1316
+ self._timestamp_ltz_output_format = kv["value"]
1317
+ if "TIMESTAMP_TZ_OUTPUT_FORMAT" in kv["name"]:
1318
+ self._timestamp_tz_output_format = kv["value"]
1319
+ if "DATE_OUTPUT_FORMAT" in kv["name"]:
1320
+ self._date_output_format = kv["value"]
1321
+ if "TIME_OUTPUT_FORMAT" in kv["name"]:
1322
+ self._time_output_format = kv["value"]
1323
+ if "TIMEZONE" in kv["name"]:
1324
+ self._timezone = kv["value"]
1325
+ if "BINARY_OUTPUT_FORMAT" in kv["name"]:
1326
+ self._binary_output_format = kv["value"]
1327
+ # Set session parameters for connection object
1328
+ self._connection._update_parameters(
1329
+ {p["name"]: p["value"] for p in parameters}
1330
+ )
1331
+
1332
+ self.query = query
1333
+ self._sequence_counter = -1
1334
+ return ret
1335
+ ```
1336
+
1337
+ ## `src/snowflake/connector/cursor.py` — `module:<module>@35` (lines 35-35)
1338
+
1339
+ ```python
1340
+ from .bind_upload_agent import BindUploadAgent, BindUploadError
1341
+ ```
1342
+
1343
+ ## `src/snowflake/connector/gcs_storage_client.py` — `class:SnowflakeGCSRestClient` (lines 47-396)
1344
+
1345
+ ```python
1346
+ class SnowflakeGCSRestClient(SnowflakeStorageClient):
1347
+ def __init__(
1348
+ self,
1349
+ meta: SnowflakeFileMeta,
1350
+ credentials: StorageCredential,
1351
+ stage_info: dict[str, Any],
1352
+ cnx: SnowflakeConnection,
1353
+ command: str,
1354
+ use_s3_regional_url=False,
1355
+ ) -> None:
1356
+ """Creates a client object with given stage credentials.
1357
+
1358
+ Args:
1359
+ stage_info: Access credentials and info of a stage.
1360
+
1361
+ Returns:
1362
+ The client to communicate with GCS.
1363
+ """
1364
+ super().__init__(
1365
+ meta, stage_info, -1, credentials=credentials, chunked_transfer=False
1366
+ )
1367
+ self.stage_info = stage_info
1368
+ self._command = command
1369
+ self.meta = meta
1370
+ self._cursor = cnx.cursor()
1371
+ # presigned_url in meta is for downloading
1372
+ self.presigned_url: str = meta.presigned_url or stage_info.get("presignedUrl")
1373
+ self.security_token = credentials.creds.get("GCS_ACCESS_TOKEN")
1374
+
1375
+ if self.security_token:
1376
+ logger.debug(f"len(GCS_ACCESS_TOKEN): {len(self.security_token)}")
1377
+ else:
1378
+ logger.debug("No access token received from GS, requesting presigned url")
1379
+ self._update_presigned_url()
1380
+
1381
+ def _has_expired_token(self, response: requests.Response) -> bool:
1382
+ return self.security_token and response.status_code == 401
1383
+
1384
+ def _has_expired_presigned_url(self, response: requests.Response) -> bool:
1385
+ # Presigned urls can be generated for any xml-api operation
1386
+ # offered by GCS. Hence the error codes expected are similar
1387
+ # to xml api.
1388
+ # https://cloud.google.com/storage/docs/xml-api/reference-status
1389
+
1390
+ presigned_url_expired = (
1391
+ not self.security_token
1392
+ ) and response.status_code == 400
1393
+ if presigned_url_expired and self.last_err_is_presigned_url:
1394
+ logger.debug("Presigned url expiration error two times in a row.")
1395
+ response.raise_for_status()
1396
+ self.last_err_is_presigned_url = presigned_url_expired
1397
+ return presigned_url_expired
1398
+
1399
+ def _upload_chunk(self, chunk_id: int, chunk: bytes) -> None:
1400
+ meta = self.meta
1401
+
1402
+ content_encoding = ""
1403
+ if meta.dst_compression_type is not None:
1404
+ content_encoding = meta.dst_compression_type.name.lower()
1405
+
1406
+ # We set the contentEncoding to blank for GZIP files. We don't
1407
+ # want GCS to think our gzip files are gzips because it makes
1408
+ # them download uncompressed, and none of the other providers do
1409
+ # that. There's essentially no way for us to prevent that
1410
+ # behavior. Bad Google.
1411
+ if content_encoding and content_encoding == "gzip":
1412
+ content_encoding = ""
1413
+
1414
+ gcs_headers = {
1415
+ HTTP_HEADER_CONTENT_ENCODING: content_encoding,
1416
+ GCS_METADATA_SFC_DIGEST: meta.sha256_digest,
1417
+ }
1418
+
1419
+ if self.encryption_metadata:
1420
+ gcs_headers.update(
1421
+ {
1422
+ GCS_METADATA_ENCRYPTIONDATAPROP: json.dumps(
1423
+ {
1424
+ "EncryptionMode": "FullBlob",
1425
+ "WrappedContentKey": {
1426
+ "KeyId": "symmKey1",
1427
+ "EncryptedKey": self.encryption_metadata.key,
1428
+ "Algorithm": "AES_CBC_256",
1429
+ },
1430
+ "EncryptionAgent": {
1431
+ "Protocol": "1.0",
1432
+ "EncryptionAlgorithm": "AES_CBC_256",
1433
+ },
1434
+ "ContentEncryptionIV": self.encryption_metadata.iv,
1435
+ "KeyWrappingMetadata": {"EncryptionLibrary": "Java 5.3.0"},
1436
+ }
1437
+ ),
1438
+ GCS_METADATA_MATDESC_KEY: self.encryption_metadata.matdesc,
1439
+ }
1440
+ )
1441
+
1442
+ def generate_url_and_rest_args() -> tuple[
1443
+ str, dict[str, dict[str | Any, str | None] | bytes]
1444
+ ]:
1445
+ if not self.presigned_url:
1446
+ upload_url = self.generate_file_url(
1447
+ self.stage_info["location"], meta.dst_file_name.lstrip("/")
1448
+ )
1449
+ access_token = self.security_token
1450
+ else:
1451
+ upload_url = self.presigned_url
1452
+ access_token: str | None = None
1453
+ if access_token:
1454
+ gcs_headers.update({"Authorization": f"Bearer {access_token}"})
1455
+ rest_args = {"headers": gcs_headers, "data": chunk}
1456
+ return upload_url, rest_args
1457
+
1458
+ response = self._send_request_with_retry(
1459
+ "PUT", generate_url_and_rest_args, chunk_id
1460
+ )
1461
+ response.raise_for_status()
1462
+ meta.gcs_file_header_digest = gcs_headers[GCS_METADATA_SFC_DIGEST]
1463
+ meta.gcs_file_header_content_length = meta.upload_size
1464
+ meta.gcs_file_header_encryption_metadata = json.loads(
1465
+ gcs_headers.get(GCS_METADATA_ENCRYPTIONDATAPROP, "null")
1466
+ )
1467
+
1468
+ def download_chunk(self, chunk_id: int) -> None:
1469
+ meta = self.meta
1470
+
1471
+ def generate_url_and_rest_args() -> tuple[
1472
+ str, dict[str, dict[str, str] | bool]
1473
+ ]:
1474
+ gcs_headers = {}
1475
+ if not self.presigned_url:
1476
+ download_url = self.generate_file_url(
1477
+ self.stage_info["location"], meta.src_file_name.lstrip("/")
1478
+ )
1479
+ access_token = self.security_token
1480
+ gcs_headers["Authorization"] = f"Bearer {access_token}"
1481
+ else:
1482
+ download_url = self.presigned_url
1483
+ rest_args = {"headers": gcs_headers, "stream": True}
1484
+ return download_url, rest_args
1485
+
1486
+ response = self._send_request_with_retry(
1487
+ "GET", generate_url_and_rest_args, chunk_id
1488
+ )
1489
+ response.raise_for_status()
1490
+
1491
+ self.write_downloaded_chunk(chunk_id, response.content)
1492
+
1493
+ encryption_metadata = None
1494
+
1495
+ if response.headers.get(GCS_METADATA_ENCRYPTIONDATAPROP, None):
1496
+ encryptiondata = json.loads(
1497
+ response.headers[GCS_METADATA_ENCRYPTIONDATAPROP]
1498
+ )
1499
+
1500
+ if encryptiondata:
1501
+ encryption_metadata = EncryptionMetadata(
1502
+ key=encryptiondata["WrappedContentKey"]["EncryptedKey"],
1503
+ iv=encryptiondata["ContentEncryptionIV"],
1504
+ matdesc=response.headers[GCS_METADATA_MATDESC_KEY]
1505
+ if GCS_METADATA_MATDESC_KEY in response.headers
1506
+ else None,
1507
+ )
1508
+
1509
+ meta.gcs_file_header_digest = response.headers.get(GCS_METADATA_SFC_DIGEST)
1510
+ meta.gcs_file_header_content_length = len(response.content)
1511
+ meta.gcs_file_header_encryption_metadata = encryption_metadata
1512
+
1513
+ def finish_download(self) -> None:
1514
+ super().finish_download()
1515
+ # Sadly, we can only determine the src file size after we've
1516
+ # downloaded it, unlike the other cloud providers where the
1517
+ # metadata can be read beforehand.
1518
+ self.meta.src_file_size = os.path.getsize(self.intermediate_dst_path)
1519
+
1520
+ def _update_presigned_url(self) -> None:
1521
+ """Updates the file metas with presigned urls if any.
1522
+
1523
+ Currently only the file metas generated for PUT/GET on a GCP account need the presigned urls.
1524
+ """
1525
+ logger.debug("Updating presigned url")
1526
+
1527
+ # Rewrite the command such that a new PUT call is made for each file
1528
+ # represented by the regex (if present) separately. This is the only
1529
+ # way to get the presigned url for that file.
1530
+ file_path_to_be_replaced = self._get_local_file_path_from_put_command()
1531
+
1532
+ if not file_path_to_be_replaced:
1533
+ # This prevents GET statements to proceed
1534
+ return
1535
+
1536
+ # At this point the connector has already figured out and
1537
+ # validated that the local file exists and has also decided
1538
+ # upon the destination file name and the compression type.
1539
+ # The only thing that's left to do is to get the presigned
1540
+ # url for the destination file. If the command originally
1541
+ # referred to a single file, then the presigned url got in
1542
+ # that case is simply ignore, since the file name is not what
1543
+ # we want.
1544
+
1545
+ # GS only looks at the file name at the end of local file
1546
+ # path to figure out the remote object name. Hence the prefix
1547
+ # for local path is not necessary in the reconstructed command.
1548
+ file_path_to_replace_with = self.meta.dst_file_name
1549
+ command_with_single_file = self._command
1550
+ command_with_single_file = command_with_single_file.replace(
1551
+ file_path_to_be_replaced, file_path_to_replace_with
1552
+ )
1553
+
1554
+ logger.debug("getting presigned url for %s", file_path_to_replace_with)
1555
+ ret = self._cursor._execute_helper(command_with_single_file)
1556
+
1557
+ stage_info = ret.get("data", dict()).get("stageInfo", dict())
1558
+ self.meta.presigned_url = stage_info.get("presignedUrl")
1559
+ self.presigned_url = stage_info.get("presignedUrl")
1560
+
1561
+ def _get_local_file_path_from_put_command(self) -> str | None:
1562
+ """Get the local file path from PUT command (Logic adopted from JDBC, written by Polita).
1563
+
1564
+ Args:
1565
+ command: Command to be parsed and get the local file path out of.
1566
+
1567
+ Returns:
1568
+ The local file path.
1569
+ """
1570
+ command = self._command
1571
+ if FILE_PROTOCOL not in self._command or not self._cursor.PUT_SQL_RE.match(
1572
+ command
1573
+ ):
1574
+ return None
1575
+
1576
+ file_path_begin_index = command.find(FILE_PROTOCOL)
1577
+ is_file_path_quoted = command[file_path_begin_index - 1] == "'"
1578
+ file_path_begin_index += len(FILE_PROTOCOL)
1579
+
1580
+ file_path = ""
1581
+
1582
+ if is_file_path_quoted:
1583
+ file_path_end_index = command.find("'", file_path_begin_index)
1584
+
1585
+ if file_path_end_index > file_path_begin_index:
1586
+ file_path = command[file_path_begin_index:file_path_end_index]
1587
+ else:
1588
+ index_list = []
1589
+ for delimiter in [" ", "\n", ";"]:
1590
+ index = command.find(delimiter, file_path_begin_index)
1591
+ if index != -1:
1592
+ index_list += [index]
1593
+
1594
+ file_path_end_index = min(index_list) if index_list else -1
1595
+
1596
+ if file_path_end_index > file_path_begin_index:
1597
+ file_path = command[file_path_begin_index:file_path_end_index]
1598
+ elif file_path_end_index == -1:
1599
+ file_path = command[file_path_begin_index:]
1600
+
1601
+ return file_path
1602
+
1603
+ def get_file_header(self, filename: str) -> FileHeader | None:
1604
+ """Gets the remote file's metadata.
1605
+
1606
+ Args:
1607
+ filename: Not applicable to GCS.
1608
+
1609
+ Returns:
1610
+ The file header, with expected properties populated or None, based on how the request goes with the
1611
+ storage provider.
1612
+
1613
+ Notes:
1614
+ Sometimes this method is called to verify that the file has indeed been uploaded. In cases of presigned
1615
+ url, we have no way of verifying that, except with the http status code of 200 which we have already
1616
+ confirmed and set the meta.result_status = UPLOADED/DOWNLOADED.
1617
+ """
1618
+ meta = self.meta
1619
+ if (
1620
+ meta.result_status == ResultStatus.UPLOADED
1621
+ or meta.result_status == ResultStatus.DOWNLOADED
1622
+ ):
1623
+ return FileHeader(
1624
+ digest=meta.gcs_file_header_digest,
1625
+ content_length=meta.gcs_file_header_content_length,
1626
+ encryption_metadata=meta.gcs_file_header_encryption_metadata,
1627
+ )
1628
+ elif self.presigned_url:
1629
+ meta.result_status = ResultStatus.NOT_FOUND_FILE
1630
+ else:
1631
+
1632
+ def generate_url_and_authenticated_headers():
1633
+ url = self.generate_file_url(
1634
+ self.stage_info["location"], filename.lstrip("/")
1635
+ )
1636
+ gcs_headers = {"Authorization": f"Bearer {self.security_token}"}
1637
+ rest_args = {"headers": gcs_headers}
1638
+ return url, rest_args
1639
+
1640
+ retry_id = "HEAD"
1641
+ self.retry_count[retry_id] = 0
1642
+ response = self._send_request_with_retry(
1643
+ "HEAD", generate_url_and_authenticated_headers, retry_id
1644
+ )
1645
+ if response.status_code == 404:
1646
+ meta.result_status = ResultStatus.NOT_FOUND_FILE
1647
+ return None
1648
+ elif response.status_code == 200:
1649
+ digest = response.headers.get(GCS_METADATA_SFC_DIGEST, None)
1650
+ content_length = int(response.headers.get("content-length", "0"))
1651
+
1652
+ encryption_metadata = EncryptionMetadata("", "", "")
1653
+ if response.headers.get(GCS_METADATA_ENCRYPTIONDATAPROP, None):
1654
+ encryption_data = json.loads(
1655
+ response.headers[GCS_METADATA_ENCRYPTIONDATAPROP]
1656
+ )
1657
+
1658
+ if encryption_data:
1659
+ encryption_metadata = EncryptionMetadata(
1660
+ key=encryption_data["WrappedContentKey"]["EncryptedKey"],
1661
+ iv=encryption_data["ContentEncryptionIV"],
1662
+ matdesc=response.headers[GCS_METADATA_MATDESC_KEY]
1663
+ if GCS_METADATA_MATDESC_KEY in response.headers
1664
+ else None,
1665
+ )
1666
+ meta.result_status = ResultStatus.UPLOADED
1667
+ return FileHeader(
1668
+ digest=digest,
1669
+ content_length=content_length,
1670
+ encryption_metadata=encryption_metadata,
1671
+ )
1672
+ response.raise_for_status()
1673
+ return None
1674
+
1675
+ @staticmethod
1676
+ def extract_bucket_name_and_path(stage_location: str) -> GcsLocation:
1677
+ container_name = stage_location
1678
+ path = ""
1679
+
1680
+ # split stage location as bucket name and path
1681
+ if "/" in stage_location:
1682
+ container_name = stage_location[0 : stage_location.index("/")]
1683
+ path = stage_location[stage_location.index("/") + 1 :]
1684
+ if path and not path.endswith("/"):
1685
+ path += "/"
1686
+
1687
+ return GcsLocation(bucket_name=container_name, path=path)
1688
+
1689
+ @staticmethod
1690
+ def generate_file_url(stage_location: str, filename: str) -> str:
1691
+ gcs_location = SnowflakeGCSRestClient.extract_bucket_name_and_path(
1692
+ stage_location
1693
+ )
1694
+ full_file_path = f"{gcs_location.path}{filename}"
1695
+ return f"https://storage.googleapis.com/{gcs_location.bucket_name}/{quote(full_file_path)}"
1696
+ ```
1697
+
1698
+ ## `src/snowflake/connector/gcs_storage_client.py` — `function:SnowflakeGCSRestClient._get_local_file_path_from_put_command` (lines 262-302)
1699
+
1700
+ ```python
1701
+ def _get_local_file_path_from_put_command(self) -> str | None:
1702
+ """Get the local file path from PUT command (Logic adopted from JDBC, written by Polita).
1703
+
1704
+ Args:
1705
+ command: Command to be parsed and get the local file path out of.
1706
+
1707
+ Returns:
1708
+ The local file path.
1709
+ """
1710
+ command = self._command
1711
+ if FILE_PROTOCOL not in self._command or not self._cursor.PUT_SQL_RE.match(
1712
+ command
1713
+ ):
1714
+ return None
1715
+
1716
+ file_path_begin_index = command.find(FILE_PROTOCOL)
1717
+ is_file_path_quoted = command[file_path_begin_index - 1] == "'"
1718
+ file_path_begin_index += len(FILE_PROTOCOL)
1719
+
1720
+ file_path = ""
1721
+
1722
+ if is_file_path_quoted:
1723
+ file_path_end_index = command.find("'", file_path_begin_index)
1724
+
1725
+ if file_path_end_index > file_path_begin_index:
1726
+ file_path = command[file_path_begin_index:file_path_end_index]
1727
+ else:
1728
+ index_list = []
1729
+ for delimiter in [" ", "\n", ";"]:
1730
+ index = command.find(delimiter, file_path_begin_index)
1731
+ if index != -1:
1732
+ index_list += [index]
1733
+
1734
+ file_path_end_index = min(index_list) if index_list else -1
1735
+
1736
+ if file_path_end_index > file_path_begin_index:
1737
+ file_path = command[file_path_begin_index:file_path_end_index]
1738
+ elif file_path_end_index == -1:
1739
+ file_path = command[file_path_begin_index:]
1740
+
1741
+ return file_path
1742
+ ```
1743
+
1744
+ ## `src/snowflake/connector/gcs_storage_client.py` — `module:<module>@13` (lines 13-13)
1745
+
1746
+ ```python
1747
+ from .compat import quote
1748
+ ```
1749
+
1750
+ ## `test/unit/test_cursor.py` — `function:test_get_filetransfer_type` (lines 27-36)
1751
+
1752
+ ```python
1753
+ def test_get_filetransfer_type(sql, _type):
1754
+ assert SnowflakeCursor.get_file_transfer_type(sql) == _type
1755
+ ```
tasks/codeql_python_benchmark51_v2/pyvul-1f5068a3fe5ca0192a07/task.json ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "schema_version": "synthesis-task-v1",
3
+ "task": {
4
+ "pair_id": "pyvul-1f5068a3fe5ca0192a07",
5
+ "dataset_id": "PyVul",
6
+ "dataset_item_id": "pyvul-1f5068a3fe5ca0192a07",
7
+ "project_id": "pyvul__snowflakedb__snowflake-connector-python",
8
+ "language": "python",
9
+ "backend": "codeql"
10
+ },
11
+ "changed_python_files": [
12
+ "src/snowflake/connector/_sql_util.py",
13
+ "src/snowflake/connector/cursor.py",
14
+ "src/snowflake/connector/gcs_storage_client.py",
15
+ "test/unit/test_cursor.py"
16
+ ],
17
+ "patch_units": {
18
+ "before": [
19
+ "class:SnowflakeCursor",
20
+ "function:SnowflakeCursor.get_file_transfer_type",
21
+ "function:SnowflakeCursor._execute_helper",
22
+ "module:<module>@35",
23
+ "class:SnowflakeGCSRestClient",
24
+ "function:SnowflakeGCSRestClient._get_local_file_path_from_put_command",
25
+ "module:<module>@13",
26
+ "function:test_get_filetransfer_type"
27
+ ],
28
+ "after": [
29
+ "function:remove_starting_comments",
30
+ "function:get_file_transfer_type",
31
+ "function:is_put_statement",
32
+ "function:is_get_statement",
33
+ "module:<module>@5",
34
+ "module:<module>@7",
35
+ "module:<module>@9",
36
+ "module:<module>@11",
37
+ "module:<module>@19",
38
+ "module:<module>@20",
39
+ "class:SnowflakeCursor",
40
+ "function:SnowflakeCursor.get_file_transfer_type",
41
+ "function:SnowflakeCursor._execute_helper",
42
+ "module:<module>@35",
43
+ "class:SnowflakeGCSRestClient",
44
+ "function:SnowflakeGCSRestClient._get_local_file_path_from_put_command",
45
+ "module:<module>@13",
46
+ "function:test_get_filetransfer_type"
47
+ ]
48
+ },
49
+ "runtime_assets": {
50
+ "before": {
51
+ "database": "assets/51887dcfe7b812bd843f3a90bce6ab7b253e5b2bcb4f7ac848f4c114825a4951/database",
52
+ "cache_key": "51887dcfe7b812bd843f3a90bce6ab7b253e5b2bcb4f7ac848f4c114825a4951",
53
+ "codeql_version": "2.26.4"
54
+ },
55
+ "after": {
56
+ "database": "assets/4fc5588b7743ee66216e918ba584f47435544a3f20dfa638a54387e954e61737/database",
57
+ "cache_key": "4fc5588b7743ee66216e918ba584f47435544a3f20dfa638a54387e954e61737",
58
+ "codeql_version": "2.26.4"
59
+ },
60
+ "refine": {
61
+ "database": "assets/da7a7cda9635f06af5e6e590e9e469862e58d247d08eb71840969ce954b37632/database",
62
+ "cache_key": "da7a7cda9635f06af5e6e590e9e469862e58d247d08eb71840969ce954b37632",
63
+ "codeql_version": "2.26.4"
64
+ }
65
+ },
66
+ "benchmark_contract": {
67
+ "agent_visible": true,
68
+ "reference_query_location": "references/pyvul-1f5068a3fe5ca0192a07/query/ (do not mount into agent)",
69
+ "evaluator_location": "evaluator/pyvul-1f5068a3fe5ca0192a07/ (do not mount into agent)"
70
+ }
71
+ }
tasks/codeql_python_benchmark51_v2/pyvul-1f5068a3fe5ca0192a07/task_prompt.md ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Python CodeQL detector synthesis
2
+
3
+ You are cc operating in `/work`. Starting only from the supplied patch,
4
+ before/after Python context, CodeQL references, and validation tools, synthesize a semantic CodeQL
5
+ detector for the vulnerability fixed by the patch. This is one fresh session. You may iterate inside
6
+ this session, but no later framework repair or resume will occur.
7
+
8
+ ## Inputs and owned outputs
9
+
10
+ - Read `patch.diff`, `python_patch.diff`, `pre_context.md`, and `post_context.md`.
11
+ - Read `references/codeql/convergence_protocol.md` and
12
+ `references/codeql/api_navigation.md` before experimenting. Read the remaining
13
+ `references/codeql/` files for the selected mechanism.
14
+ - Use `scripts/search_codeql_api.sh` to inspect the pinned official libraries when an API detail is
15
+ uncertain. Do not guess predicate names or build a large family of inspection queries.
16
+ - Complete the design contract in `state.json` and `scope_statement.md` before final validation.
17
+ - Replace `query/vulnerability.ql`; add only genuinely shared `.qll` helpers when useful. Keep the
18
+ fixed offline dependency in `query/qlpack.yml`.
19
+ - Preserve the exact `expected_query_id` from `config.json` as the query's sole `@id`. This
20
+ task-unique metadata must never be used in a query predicate.
21
+ - Use `scripts/compile_query.sh`, `scripts/run_before.sh`, and `scripts/run_after.sh`.
22
+ - Finish by writing `summary.json` with `status`, `query_path`, `query_kind`, `build_passed`,
23
+ `before_findings`, `after_findings`, `validation_completed`, and a concise `notes` field.
24
+
25
+ ## Required reasoning contract
26
+
27
+ Before coding, record this mapping in `state.json`:
28
+
29
+ ```text
30
+ vulnerable operation / trigger / patch safety condition
31
+ → CodeQL-observable evidence
32
+ → syntax, control-flow, local value-flow, global taint/value-flow, or interprocedural mechanism
33
+ → source, sink/report site, guard/barrier and query predicates
34
+ ```
35
+
36
+ Choose the lowest mechanism that can actually prove the condition. Guard-sensitive patches require
37
+ real path/control-flow semantics; provenance-sensitive patches require value flow. Do not replace
38
+ either with source-text matching or with the mere presence of patch-added syntax.
39
+
40
+ ## Mandatory convergence contract
41
+
42
+ The rollout has a 30-minute hard wall-clock ceiling and must be finalized by minute 27. Minutes
43
+ 27–30 are an emergency shutdown buffer, not exploration time. A sophisticated unfinished query is
44
+ a failure; an early compilable semantic candidate can be improved. Follow the checkpoints in
45
+ `references/codeql/convergence_protocol.md`:
46
+
47
+ 1. Record the mechanism contract, then replace the placeholder in `query/vulnerability.ql`
48
+ immediately. Do not wait until every CodeQL API detail is known.
49
+ 2. Use at most three distinct scratch `.ql` files. Prefer repeatedly editing one
50
+ `query/scratch.ql`. After two failed variants of one API assumption, inspect the exact bundled
51
+ definition with `scripts/search_codeql_api.sh` or simplify the mechanism.
52
+ 3. Obtain a compiling minimal main query before broadening it. Compile the main query after every
53
+ meaningful mechanism change.
54
+ 4. Move in order from compile → relevant before finding → after elimination → final contract. Do
55
+ not continue API exploration after the intended before/after differential is established.
56
+ 5. Run `scripts/check_progress.sh` at each checkpoint. It reports elapsed time, the minute-27
57
+ finalization deadline, and the minute-30 hard timeout. When it prints `finalize_now`, stop all
58
+ exploration, preserve the best compiling query, finish the contract files, and exit.
59
+
60
+ ## Semantic and generalization rules
61
+
62
+ - Report at the vulnerable call, operator, access, or sink.
63
+ - Do not use a patch-local path, line, commit hash, label, or local variable name as the primary
64
+ matching condition. Stable library/framework APIs or public project APIs are allowed only when
65
+ `scope_statement.md` explains why they define the intended vulnerability family.
66
+ - The safety condition introduced by the patch must be represented by the query.
67
+ - A lower after warning count is not enough: inspect SARIF and ensure at least one intended before
68
+ finding is in a patch-overlapping semantic unit and the corresponding finding disappears after.
69
+ - Avoid broad proxy queries that report an enclosing function or unrelated API merely because it
70
+ changed in the patch.
71
+
72
+ ## Final validation protocol
73
+
74
+ 1. Compile the final query.
75
+ 2. Run it on before and inspect `raw/before.sarif` for the intended report location.
76
+ 3. Run the identical query on after and inspect `raw/after.sarif`.
77
+ 4. Recheck query metadata, query kind/select signature, report locality, design-to-code consistency,
78
+ and absence of patch-local hardcoding.
79
+ 5. Update `state.json`, `scope_statement.md`, and write valid `summary.json`.
80
+
81
+ Do not modify the runtime databases, references, patch, context, or validation scripts except for
82
+ normal CodeQL-generated database caches produced by the provided run scripts.
tasks/codeql_python_benchmark51_v2/pyvul-2ab65d62986b80922362/patch.diff ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ diff --git a/grappelli/views/switch.py b/grappelli/views/switch.py
2
+ index 8e390b13..db2ee680 100644
3
+ --- a/grappelli/views/switch.py
4
+ +++ b/grappelli/views/switch.py
5
+ @@ -8,6 +8,7 @@ from django.core.exceptions import ObjectDoesNotExist
6
+ from django.http import Http404
7
+ from django.shortcuts import redirect
8
+ from django.utils.html import escape
9
+ +from django.utils.http import url_has_allowed_host_and_scheme
10
+ from django.utils.translation import gettext_lazy as _
11
+
12
+ from grappelli.settings import SWITCH_USER_ORIGINAL, SWITCH_USER_TARGET
13
+ @@ -28,30 +29,35 @@ def switch_user(request, object_id):
14
+
15
+ # check redirect
16
+ redirect_url = request.GET.get("redirect", None)
17
+ - if redirect_url is None or not redirect_url.startswith("/"):
18
+ + if redirect_url is None or not \
19
+ + url_has_allowed_host_and_scheme(
20
+ + url=redirect_url,
21
+ + allowed_hosts={request.get_host()},
22
+ + require_https=request.is_secure(),
23
+ + ):
24
+ raise Http404()
25
+ -
26
+ +
27
+ # check original_user
28
+ try:
29
+ original_user = User.objects.get(pk=session_user["id"], is_staff=True)
30
+ if not SWITCH_USER_ORIGINAL(original_user):
31
+ messages.add_message(request, messages.ERROR, _("Permission denied."))
32
+ - return redirect(request.GET.get("redirect"))
33
+ + return redirect(redirect_url)
34
+ except ObjectDoesNotExist:
35
+ msg = _('%(name)s object with primary key %(key)r does not exist.') % {'name': "User", 'key': escape(session_user["id"])}
36
+ messages.add_message(request, messages.ERROR, msg)
37
+ - return redirect(request.GET.get("redirect"))
38
+ + return redirect(redirect_url)
39
+
40
+ # check new user
41
+ try:
42
+ target_user = User.objects.get(pk=object_id, is_staff=True)
43
+ if target_user != original_user and not SWITCH_USER_TARGET(original_user, target_user):
44
+ messages.add_message(request, messages.ERROR, _("Permission denied."))
45
+ - return redirect(request.GET.get("redirect"))
46
+ + return redirect(redirect_url)
47
+ except ObjectDoesNotExist:
48
+ msg = _('%(name)s object with primary key %(key)r does not exist.') % {'name': "User", 'key': escape(object_id)}
49
+ messages.add_message(request, messages.ERROR, msg)
50
+ - return redirect(request.GET.get("redirect"))
51
+ + return redirect(redirect_url)
52
+
53
+ # find backend
54
+ if not hasattr(target_user, 'backend'):
55
+ @@ -66,4 +72,4 @@ def switch_user(request, object_id):
56
+ if original_user.id != target_user.id:
57
+ request.session["original_user"] = {"id": original_user.id, "username": original_user.get_username()}
58
+
59
+ - return redirect(request.GET.get("redirect"))
60
+ + return redirect(redirect_url)
tasks/codeql_python_benchmark51_v2/pyvul-2ab65d62986b80922362/post_context.md ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Patch-overlapping Python context after the fix
2
+
3
+ ## `grappelli/views/switch.py` — `function:switch_user` (lines 23-75)
4
+
5
+ ```python
6
+ def switch_user(request, object_id):
7
+
8
+ # current/session user
9
+ current_user = request.user
10
+ session_user = request.session.get("original_user", {"id": current_user.id, "username": current_user.get_username()})
11
+
12
+ # check redirect
13
+ redirect_url = request.GET.get("redirect", None)
14
+ if redirect_url is None or not \
15
+ url_has_allowed_host_and_scheme(
16
+ url=redirect_url,
17
+ allowed_hosts={request.get_host()},
18
+ require_https=request.is_secure(),
19
+ ):
20
+ raise Http404()
21
+
22
+ # check original_user
23
+ try:
24
+ original_user = User.objects.get(pk=session_user["id"], is_staff=True)
25
+ if not SWITCH_USER_ORIGINAL(original_user):
26
+ messages.add_message(request, messages.ERROR, _("Permission denied."))
27
+ return redirect(redirect_url)
28
+ except ObjectDoesNotExist:
29
+ msg = _('%(name)s object with primary key %(key)r does not exist.') % {'name': "User", 'key': escape(session_user["id"])}
30
+ messages.add_message(request, messages.ERROR, msg)
31
+ return redirect(redirect_url)
32
+
33
+ # check new user
34
+ try:
35
+ target_user = User.objects.get(pk=object_id, is_staff=True)
36
+ if target_user != original_user and not SWITCH_USER_TARGET(original_user, target_user):
37
+ messages.add_message(request, messages.ERROR, _("Permission denied."))
38
+ return redirect(redirect_url)
39
+ except ObjectDoesNotExist:
40
+ msg = _('%(name)s object with primary key %(key)r does not exist.') % {'name': "User", 'key': escape(object_id)}
41
+ messages.add_message(request, messages.ERROR, msg)
42
+ return redirect(redirect_url)
43
+
44
+ # find backend
45
+ if not hasattr(target_user, 'backend'):
46
+ for backend in settings.AUTHENTICATION_BACKENDS:
47
+ if target_user == load_backend(backend).get_user(target_user.pk):
48
+ target_user.backend = backend
49
+ break
50
+
51
+ # target user login, set original as session
52
+ if hasattr(target_user, 'backend'):
53
+ login(request, target_user)
54
+ if original_user.id != target_user.id:
55
+ request.session["original_user"] = {"id": original_user.id, "username": original_user.get_username()}
56
+
57
+ return redirect(redirect_url)
58
+ ```
59
+
60
+ ## `grappelli/views/switch.py` — `module:<module>@11` (lines 11-11)
61
+
62
+ ```python
63
+ from django.utils.http import url_has_allowed_host_and_scheme
64
+ ```
tasks/codeql_python_benchmark51_v2/pyvul-2ab65d62986b80922362/pre_context.md ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Patch-overlapping Python context before the fix
2
+
3
+ ## `grappelli/views/switch.py` — `function:switch_user` (lines 22-69)
4
+
5
+ ```python
6
+ def switch_user(request, object_id):
7
+
8
+ # current/session user
9
+ current_user = request.user
10
+ session_user = request.session.get("original_user", {"id": current_user.id, "username": current_user.get_username()})
11
+
12
+ # check redirect
13
+ redirect_url = request.GET.get("redirect", None)
14
+ if redirect_url is None or not redirect_url.startswith("/"):
15
+ raise Http404()
16
+
17
+ # check original_user
18
+ try:
19
+ original_user = User.objects.get(pk=session_user["id"], is_staff=True)
20
+ if not SWITCH_USER_ORIGINAL(original_user):
21
+ messages.add_message(request, messages.ERROR, _("Permission denied."))
22
+ return redirect(request.GET.get("redirect"))
23
+ except ObjectDoesNotExist:
24
+ msg = _('%(name)s object with primary key %(key)r does not exist.') % {'name': "User", 'key': escape(session_user["id"])}
25
+ messages.add_message(request, messages.ERROR, msg)
26
+ return redirect(request.GET.get("redirect"))
27
+
28
+ # check new user
29
+ try:
30
+ target_user = User.objects.get(pk=object_id, is_staff=True)
31
+ if target_user != original_user and not SWITCH_USER_TARGET(original_user, target_user):
32
+ messages.add_message(request, messages.ERROR, _("Permission denied."))
33
+ return redirect(request.GET.get("redirect"))
34
+ except ObjectDoesNotExist:
35
+ msg = _('%(name)s object with primary key %(key)r does not exist.') % {'name': "User", 'key': escape(object_id)}
36
+ messages.add_message(request, messages.ERROR, msg)
37
+ return redirect(request.GET.get("redirect"))
38
+
39
+ # find backend
40
+ if not hasattr(target_user, 'backend'):
41
+ for backend in settings.AUTHENTICATION_BACKENDS:
42
+ if target_user == load_backend(backend).get_user(target_user.pk):
43
+ target_user.backend = backend
44
+ break
45
+
46
+ # target user login, set original as session
47
+ if hasattr(target_user, 'backend'):
48
+ login(request, target_user)
49
+ if original_user.id != target_user.id:
50
+ request.session["original_user"] = {"id": original_user.id, "username": original_user.get_username()}
51
+
52
+ return redirect(request.GET.get("redirect"))
53
+ ```
54
+
55
+ ## `grappelli/views/switch.py` — `module:<module>@11` (lines 11-11)
56
+
57
+ ```python
58
+ from django.utils.translation import gettext_lazy as _
59
+ ```
tasks/codeql_python_benchmark51_v2/pyvul-2ab65d62986b80922362/task.json ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "schema_version": "synthesis-task-v1",
3
+ "task": {
4
+ "pair_id": "pyvul-2ab65d62986b80922362",
5
+ "dataset_id": "PyVul",
6
+ "dataset_item_id": "pyvul-2ab65d62986b80922362",
7
+ "project_id": "pyvul__sehmaschine__django-grappelli",
8
+ "language": "python",
9
+ "backend": "codeql"
10
+ },
11
+ "changed_python_files": [
12
+ "grappelli/views/switch.py"
13
+ ],
14
+ "patch_units": {
15
+ "before": [
16
+ "function:switch_user",
17
+ "module:<module>@11"
18
+ ],
19
+ "after": [
20
+ "function:switch_user",
21
+ "module:<module>@11"
22
+ ]
23
+ },
24
+ "runtime_assets": {
25
+ "before": {
26
+ "database": "assets/a651d858d8c6a33884674a524fc8f61c7e7ccfccade3966409515abaecba586d/database",
27
+ "cache_key": "a651d858d8c6a33884674a524fc8f61c7e7ccfccade3966409515abaecba586d",
28
+ "codeql_version": "2.26.4"
29
+ },
30
+ "after": {
31
+ "database": "assets/346863e80f97754d1d2004217a3308ad91897bf7891ed868b01ecd17ed39d300/database",
32
+ "cache_key": "346863e80f97754d1d2004217a3308ad91897bf7891ed868b01ecd17ed39d300",
33
+ "codeql_version": "2.26.4"
34
+ },
35
+ "refine": {
36
+ "database": "assets/091b842c9e7302a8f7aee586e6738c61c6607f0befe3559f5296b1b32275785b/database",
37
+ "cache_key": "091b842c9e7302a8f7aee586e6738c61c6607f0befe3559f5296b1b32275785b",
38
+ "codeql_version": "2.26.4"
39
+ }
40
+ },
41
+ "benchmark_contract": {
42
+ "agent_visible": true,
43
+ "reference_query_location": "references/pyvul-2ab65d62986b80922362/query/ (do not mount into agent)",
44
+ "evaluator_location": "evaluator/pyvul-2ab65d62986b80922362/ (do not mount into agent)"
45
+ }
46
+ }
tasks/codeql_python_benchmark51_v2/pyvul-2ab65d62986b80922362/task_prompt.md ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Python CodeQL detector synthesis
2
+
3
+ You are cc operating in `/work`. Starting only from the supplied patch,
4
+ before/after Python context, CodeQL references, and validation tools, synthesize a semantic CodeQL
5
+ detector for the vulnerability fixed by the patch. This is one fresh session. You may iterate inside
6
+ this session, but no later framework repair or resume will occur.
7
+
8
+ ## Inputs and owned outputs
9
+
10
+ - Read `patch.diff`, `python_patch.diff`, `pre_context.md`, and `post_context.md`.
11
+ - Read `references/codeql/convergence_protocol.md` and
12
+ `references/codeql/api_navigation.md` before experimenting. Read the remaining
13
+ `references/codeql/` files for the selected mechanism.
14
+ - Use `scripts/search_codeql_api.sh` to inspect the pinned official libraries when an API detail is
15
+ uncertain. Do not guess predicate names or build a large family of inspection queries.
16
+ - Complete the design contract in `state.json` and `scope_statement.md` before final validation.
17
+ - Replace `query/vulnerability.ql`; add only genuinely shared `.qll` helpers when useful. Keep the
18
+ fixed offline dependency in `query/qlpack.yml`.
19
+ - Preserve the exact `expected_query_id` from `config.json` as the query's sole `@id`. This
20
+ task-unique metadata must never be used in a query predicate.
21
+ - Use `scripts/compile_query.sh`, `scripts/run_before.sh`, and `scripts/run_after.sh`.
22
+ - Finish by writing `summary.json` with `status`, `query_path`, `query_kind`, `build_passed`,
23
+ `before_findings`, `after_findings`, `validation_completed`, and a concise `notes` field.
24
+
25
+ ## Required reasoning contract
26
+
27
+ Before coding, record this mapping in `state.json`:
28
+
29
+ ```text
30
+ vulnerable operation / trigger / patch safety condition
31
+ → CodeQL-observable evidence
32
+ → syntax, control-flow, local value-flow, global taint/value-flow, or interprocedural mechanism
33
+ → source, sink/report site, guard/barrier and query predicates
34
+ ```
35
+
36
+ Choose the lowest mechanism that can actually prove the condition. Guard-sensitive patches require
37
+ real path/control-flow semantics; provenance-sensitive patches require value flow. Do not replace
38
+ either with source-text matching or with the mere presence of patch-added syntax.
39
+
40
+ ## Mandatory convergence contract
41
+
42
+ The rollout has a 30-minute hard wall-clock ceiling and must be finalized by minute 27. Minutes
43
+ 27–30 are an emergency shutdown buffer, not exploration time. A sophisticated unfinished query is
44
+ a failure; an early compilable semantic candidate can be improved. Follow the checkpoints in
45
+ `references/codeql/convergence_protocol.md`:
46
+
47
+ 1. Record the mechanism contract, then replace the placeholder in `query/vulnerability.ql`
48
+ immediately. Do not wait until every CodeQL API detail is known.
49
+ 2. Use at most three distinct scratch `.ql` files. Prefer repeatedly editing one
50
+ `query/scratch.ql`. After two failed variants of one API assumption, inspect the exact bundled
51
+ definition with `scripts/search_codeql_api.sh` or simplify the mechanism.
52
+ 3. Obtain a compiling minimal main query before broadening it. Compile the main query after every
53
+ meaningful mechanism change.
54
+ 4. Move in order from compile → relevant before finding → after elimination → final contract. Do
55
+ not continue API exploration after the intended before/after differential is established.
56
+ 5. Run `scripts/check_progress.sh` at each checkpoint. It reports elapsed time, the minute-27
57
+ finalization deadline, and the minute-30 hard timeout. When it prints `finalize_now`, stop all
58
+ exploration, preserve the best compiling query, finish the contract files, and exit.
59
+
60
+ ## Semantic and generalization rules
61
+
62
+ - Report at the vulnerable call, operator, access, or sink.
63
+ - Do not use a patch-local path, line, commit hash, label, or local variable name as the primary
64
+ matching condition. Stable library/framework APIs or public project APIs are allowed only when
65
+ `scope_statement.md` explains why they define the intended vulnerability family.
66
+ - The safety condition introduced by the patch must be represented by the query.
67
+ - A lower after warning count is not enough: inspect SARIF and ensure at least one intended before
68
+ finding is in a patch-overlapping semantic unit and the corresponding finding disappears after.
69
+ - Avoid broad proxy queries that report an enclosing function or unrelated API merely because it
70
+ changed in the patch.
71
+
72
+ ## Final validation protocol
73
+
74
+ 1. Compile the final query.
75
+ 2. Run it on before and inspect `raw/before.sarif` for the intended report location.
76
+ 3. Run the identical query on after and inspect `raw/after.sarif`.
77
+ 4. Recheck query metadata, query kind/select signature, report locality, design-to-code consistency,
78
+ and absence of patch-local hardcoding.
79
+ 5. Update `state.json`, `scope_statement.md`, and write valid `summary.json`.
80
+
81
+ Do not modify the runtime databases, references, patch, context, or validation scripts except for
82
+ normal CodeQL-generated database caches produced by the provided run scripts.
tasks/codeql_python_benchmark51_v2/pyvul-3062589ff0b3b95c2ed7/patch.diff ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ diff --git a/CHANGELOG.md b/CHANGELOG.md
2
+ index ba9187c0a3..6149f587ea 100644
3
+ --- a/CHANGELOG.md
4
+ +++ b/CHANGELOG.md
5
+ @@ -51,6 +51,9 @@ The types of changes are:
6
+ - User preferences from cookie should always override experience preferences [#4405](https://github.com/ethyca/fides/pull/4405)
7
+ - Allow fides_consent cookie to be set from a subdirectory [#4426](https://github.com/ethyca/fides/pull/4426)
8
+
9
+ +### Security
10
+ +-- Use a more cryptographically secure random function for security code generation
11
+ +
12
+ ## [2.23.3](https://github.com/ethyca/fides/compare/2.23.2...2.23.3)
13
+
14
+ ### Fixed
15
+ diff --git a/src/fides/api/service/privacy_request/request_runner_service.py b/src/fides/api/service/privacy_request/request_runner_service.py
16
+ index d1154ba3e7..266a981cb1 100644
17
+ --- a/src/fides/api/service/privacy_request/request_runner_service.py
18
+ +++ b/src/fides/api/service/privacy_request/request_runner_service.py
19
+ @@ -1,4 +1,4 @@
20
+ -import random
21
+ +import secrets
22
+ from datetime import datetime, timedelta
23
+ from typing import Any, Dict, List, Optional, Set, Tuple
24
+
25
+ @@ -627,7 +627,7 @@ def generate_id_verification_code() -> str:
26
+ """
27
+ Generate one-time identity verification code
28
+ """
29
+ - return str(random.choice(range(100000, 999999)))
30
+ + return str(secrets.choice(range(100000, 999999)))
31
+
32
+
33
+ def _retrieve_child_results( # pylint: disable=R0911
tasks/codeql_python_benchmark51_v2/pyvul-3062589ff0b3b95c2ed7/post_context.md ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Patch-overlapping Python context after the fix
2
+
3
+ ## `src/fides/api/service/privacy_request/request_runner_service.py` — `function:generate_id_verification_code` (lines 626-630)
4
+
5
+ ```python
6
+ def generate_id_verification_code() -> str:
7
+ """
8
+ Generate one-time identity verification code
9
+ """
10
+ return str(secrets.choice(range(100000, 999999)))
11
+ ```
12
+
13
+ ## `src/fides/api/service/privacy_request/request_runner_service.py` — `module:<module>@1` (lines 1-1)
14
+
15
+ ```python
16
+ import secrets
17
+ ```
tasks/codeql_python_benchmark51_v2/pyvul-3062589ff0b3b95c2ed7/pre_context.md ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Patch-overlapping Python context before the fix
2
+
3
+ ## `src/fides/api/service/privacy_request/request_runner_service.py` — `function:generate_id_verification_code` (lines 626-630)
4
+
5
+ ```python
6
+ def generate_id_verification_code() -> str:
7
+ """
8
+ Generate one-time identity verification code
9
+ """
10
+ return str(random.choice(range(100000, 999999)))
11
+ ```
12
+
13
+ ## `src/fides/api/service/privacy_request/request_runner_service.py` — `module:<module>@1` (lines 1-1)
14
+
15
+ ```python
16
+ import random
17
+ ```
18
+
19
+ ## `src/fides/api/service/privacy_request/request_runner_service.py` — `module:<module>@2` (lines 2-2)
20
+
21
+ ```python
22
+ from datetime import datetime, timedelta
23
+ ```
tasks/codeql_python_benchmark51_v2/pyvul-3062589ff0b3b95c2ed7/task.json ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "schema_version": "synthesis-task-v1",
3
+ "task": {
4
+ "pair_id": "pyvul-3062589ff0b3b95c2ed7",
5
+ "dataset_id": "PyVul",
6
+ "dataset_item_id": "pyvul-3062589ff0b3b95c2ed7",
7
+ "project_id": "pyvul__ethyca__fides",
8
+ "language": "python",
9
+ "backend": "codeql"
10
+ },
11
+ "changed_python_files": [
12
+ "src/fides/api/service/privacy_request/request_runner_service.py"
13
+ ],
14
+ "patch_units": {
15
+ "before": [
16
+ "function:generate_id_verification_code",
17
+ "module:<module>@1",
18
+ "module:<module>@2"
19
+ ],
20
+ "after": [
21
+ "function:generate_id_verification_code",
22
+ "module:<module>@1"
23
+ ]
24
+ },
25
+ "runtime_assets": {
26
+ "before": {
27
+ "database": "assets/291915565ab089440fa07a9c16ad27e6484f7368a306466a2d88660ed05eb343/database",
28
+ "cache_key": "291915565ab089440fa07a9c16ad27e6484f7368a306466a2d88660ed05eb343",
29
+ "codeql_version": "2.26.4"
30
+ },
31
+ "after": {
32
+ "database": "assets/d92a2bb5d4325e1848a36ffc9bc6d9851def586947106947d01f951ef76928e5/database",
33
+ "cache_key": "d92a2bb5d4325e1848a36ffc9bc6d9851def586947106947d01f951ef76928e5",
34
+ "codeql_version": "2.26.4"
35
+ },
36
+ "refine": {
37
+ "database": "assets/f593a9e7147144ea94ddd83cc757db32e281fcd6c70e757a340641032a902d52/database",
38
+ "cache_key": "f593a9e7147144ea94ddd83cc757db32e281fcd6c70e757a340641032a902d52",
39
+ "codeql_version": "2.26.4"
40
+ }
41
+ },
42
+ "benchmark_contract": {
43
+ "agent_visible": true,
44
+ "reference_query_location": "references/pyvul-3062589ff0b3b95c2ed7/query/ (do not mount into agent)",
45
+ "evaluator_location": "evaluator/pyvul-3062589ff0b3b95c2ed7/ (do not mount into agent)"
46
+ }
47
+ }
tasks/codeql_python_benchmark51_v2/pyvul-3062589ff0b3b95c2ed7/task_prompt.md ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Python CodeQL detector synthesis
2
+
3
+ You are cc operating in `/work`. Starting only from the supplied patch,
4
+ before/after Python context, CodeQL references, and validation tools, synthesize a semantic CodeQL
5
+ detector for the vulnerability fixed by the patch. This is one fresh session. You may iterate inside
6
+ this session, but no later framework repair or resume will occur.
7
+
8
+ ## Inputs and owned outputs
9
+
10
+ - Read `patch.diff`, `python_patch.diff`, `pre_context.md`, and `post_context.md`.
11
+ - Read `references/codeql/convergence_protocol.md` and
12
+ `references/codeql/api_navigation.md` before experimenting. Read the remaining
13
+ `references/codeql/` files for the selected mechanism.
14
+ - Use `scripts/search_codeql_api.sh` to inspect the pinned official libraries when an API detail is
15
+ uncertain. Do not guess predicate names or build a large family of inspection queries.
16
+ - Complete the design contract in `state.json` and `scope_statement.md` before final validation.
17
+ - Replace `query/vulnerability.ql`; add only genuinely shared `.qll` helpers when useful. Keep the
18
+ fixed offline dependency in `query/qlpack.yml`.
19
+ - Preserve the exact `expected_query_id` from `config.json` as the query's sole `@id`. This
20
+ task-unique metadata must never be used in a query predicate.
21
+ - Use `scripts/compile_query.sh`, `scripts/run_before.sh`, and `scripts/run_after.sh`.
22
+ - Finish by writing `summary.json` with `status`, `query_path`, `query_kind`, `build_passed`,
23
+ `before_findings`, `after_findings`, `validation_completed`, and a concise `notes` field.
24
+
25
+ ## Required reasoning contract
26
+
27
+ Before coding, record this mapping in `state.json`:
28
+
29
+ ```text
30
+ vulnerable operation / trigger / patch safety condition
31
+ → CodeQL-observable evidence
32
+ → syntax, control-flow, local value-flow, global taint/value-flow, or interprocedural mechanism
33
+ → source, sink/report site, guard/barrier and query predicates
34
+ ```
35
+
36
+ Choose the lowest mechanism that can actually prove the condition. Guard-sensitive patches require
37
+ real path/control-flow semantics; provenance-sensitive patches require value flow. Do not replace
38
+ either with source-text matching or with the mere presence of patch-added syntax.
39
+
40
+ ## Mandatory convergence contract
41
+
42
+ The rollout has a 30-minute hard wall-clock ceiling and must be finalized by minute 27. Minutes
43
+ 27–30 are an emergency shutdown buffer, not exploration time. A sophisticated unfinished query is
44
+ a failure; an early compilable semantic candidate can be improved. Follow the checkpoints in
45
+ `references/codeql/convergence_protocol.md`:
46
+
47
+ 1. Record the mechanism contract, then replace the placeholder in `query/vulnerability.ql`
48
+ immediately. Do not wait until every CodeQL API detail is known.
49
+ 2. Use at most three distinct scratch `.ql` files. Prefer repeatedly editing one
50
+ `query/scratch.ql`. After two failed variants of one API assumption, inspect the exact bundled
51
+ definition with `scripts/search_codeql_api.sh` or simplify the mechanism.
52
+ 3. Obtain a compiling minimal main query before broadening it. Compile the main query after every
53
+ meaningful mechanism change.
54
+ 4. Move in order from compile → relevant before finding → after elimination → final contract. Do
55
+ not continue API exploration after the intended before/after differential is established.
56
+ 5. Run `scripts/check_progress.sh` at each checkpoint. It reports elapsed time, the minute-27
57
+ finalization deadline, and the minute-30 hard timeout. When it prints `finalize_now`, stop all
58
+ exploration, preserve the best compiling query, finish the contract files, and exit.
59
+
60
+ ## Semantic and generalization rules
61
+
62
+ - Report at the vulnerable call, operator, access, or sink.
63
+ - Do not use a patch-local path, line, commit hash, label, or local variable name as the primary
64
+ matching condition. Stable library/framework APIs or public project APIs are allowed only when
65
+ `scope_statement.md` explains why they define the intended vulnerability family.
66
+ - The safety condition introduced by the patch must be represented by the query.
67
+ - A lower after warning count is not enough: inspect SARIF and ensure at least one intended before
68
+ finding is in a patch-overlapping semantic unit and the corresponding finding disappears after.
69
+ - Avoid broad proxy queries that report an enclosing function or unrelated API merely because it
70
+ changed in the patch.
71
+
72
+ ## Final validation protocol
73
+
74
+ 1. Compile the final query.
75
+ 2. Run it on before and inspect `raw/before.sarif` for the intended report location.
76
+ 3. Run the identical query on after and inspect `raw/after.sarif`.
77
+ 4. Recheck query metadata, query kind/select signature, report locality, design-to-code consistency,
78
+ and absence of patch-local hardcoding.
79
+ 5. Update `state.json`, `scope_statement.md`, and write valid `summary.json`.
80
+
81
+ Do not modify the runtime databases, references, patch, context, or validation scripts except for
82
+ normal CodeQL-generated database caches produced by the provided run scripts.
tasks/codeql_python_benchmark51_v2/pyvul-3187445bcbbf39128a26/patch.diff ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ diff --git a/requirements.txt b/requirements.txt
2
+ index 7d2f3f5..9d73a97 100644
3
+ --- a/requirements.txt
4
+ +++ b/requirements.txt
5
+ @@ -1,7 +1,7 @@
6
+ Markdown==2.6.8
7
+ Pygments==1.6
8
+ Jinja2==2.7.3
9
+ -PyYAML==3.11
10
+ +PyYAML==5.1
11
+ docopt==0.6.1
12
+ ordereddict==1.1
13
+ watchdog==0.8.3
14
+ diff --git a/simiki/config.py b/simiki/config.py
15
+ index c0a1ef3..790178b 100644
16
+ --- a/simiki/config.py
17
+ +++ b/simiki/config.py
18
+ @@ -61,7 +61,7 @@ def parse_config(config_file):
19
+ default_config = _set_default_config()
20
+
21
+ with io.open(config_file, "rt", encoding="utf-8") as fd:
22
+ - config = yaml.load(fd)
23
+ + config = yaml.load(fd, Loader=yaml.FullLoader)
24
+
25
+ default_config.update(config)
26
+ config = _post_process(default_config)
27
+ diff --git a/simiki/generators.py b/simiki/generators.py
28
+ index 9816df0..148908b 100644
29
+ --- a/simiki/generators.py
30
+ +++ b/simiki/generators.py
31
+ @@ -208,7 +208,7 @@ class PageGenerator(BaseGenerator):
32
+ def parse_meta(self, yaml_str):
33
+ """Parse meta from yaml string, and validate yaml filed, return dict"""
34
+ try:
35
+ - meta = yaml.load(yaml_str)
36
+ + meta = yaml.load(yaml_str, Loader=yaml.FullLoader)
37
+ except yaml.YAMLError as e:
38
+ e.extra_msg = 'yaml format error'
39
+ raise
tasks/codeql_python_benchmark51_v2/pyvul-3187445bcbbf39128a26/post_context.md ADDED
@@ -0,0 +1,244 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Patch-overlapping Python context after the fix
2
+
3
+ ## `simiki/config.py` — `function:parse_config` (lines 57-69)
4
+
5
+ ```python
6
+ def parse_config(config_file):
7
+ if not os.path.exists(config_file):
8
+ raise ConfigFileNotFound("{0} not exists".format(config_file))
9
+
10
+ default_config = _set_default_config()
11
+
12
+ with io.open(config_file, "rt", encoding="utf-8") as fd:
13
+ config = yaml.load(fd, Loader=yaml.FullLoader)
14
+
15
+ default_config.update(config)
16
+ config = _post_process(default_config)
17
+
18
+ return config
19
+ ```
20
+
21
+ ## `simiki/generators.py` — `class:PageGenerator` (lines 92-284)
22
+
23
+ ```python
24
+ class PageGenerator(BaseGenerator):
25
+
26
+ def __init__(self, site_config, base_path, tags=None):
27
+ super(PageGenerator, self).__init__(site_config, base_path)
28
+ self._tags = tags
29
+ self._reset()
30
+
31
+ def _reset(self):
32
+ """Reset the global self variables"""
33
+ self._src_file = None # source file path relative to base_path
34
+ self.meta = None
35
+ self.content = None
36
+
37
+ def to_html(self, src_file, include_draft=False):
38
+ """Load template, and generate html
39
+
40
+ :src_file: the filename of the source file. This can either be an
41
+ absolute filename or a filename relative to the base path.
42
+ :include_draft: True/False, include draft pages or not to generate
43
+ """
44
+ self._reset()
45
+ self._src_file = os.path.relpath(src_file, self.base_path)
46
+ self.meta, self.content = self.get_meta_and_content()
47
+ # Page set `draft: True' mark current page as draft, and will
48
+ # be ignored if not forced generate include draft pages
49
+ if not include_draft and self.meta.get('draft', False):
50
+ return None
51
+ layout = self.get_layout(self.meta)
52
+ template_vars = self.get_template_vars(self.meta, self.content)
53
+ template = self.get_template(layout)
54
+ html = template.render(template_vars)
55
+
56
+ return html
57
+
58
+ @property
59
+ def src_file(self):
60
+ return self._src_file
61
+
62
+ @src_file.setter
63
+ def src_file(self, filename):
64
+ self._src_file = os.path.relpath(filename, self.base_path)
65
+
66
+ def get_meta_and_content(self, do_render=True):
67
+ meta_str, content_str = self.extract_page(self._src_file)
68
+ meta = self.parse_meta(meta_str)
69
+ # This is the most time consuming part
70
+ if do_render and meta.get('render', True):
71
+ content = self._parse_markup(content_str)
72
+ else:
73
+ content = content_str
74
+
75
+ return meta, content
76
+
77
+ def get_layout(self, meta):
78
+ """Get layout config in meta, default is `page'"""
79
+ if "layout" in meta:
80
+ # Compatible with previous version, which default layout is "post"
81
+ # XXX Will remove this checker in v2.0
82
+ if meta["layout"] == "post":
83
+ warn_msg = "{0}: layout `post' is deprecated, use `page'" \
84
+ .format(self._src_file)
85
+ if is_py2:
86
+ # XXX: warnings message require str, no matter whether
87
+ # py2 or py3; but in py3, bytes message is ok in simple
88
+ # test, but failed in unittest with py3.3, ok with py3.4?
89
+ warn_msg = warn_msg.encode('utf-8')
90
+ warnings.warn(warn_msg, DeprecationWarning)
91
+ layout = "page"
92
+ else:
93
+ layout = meta["layout"]
94
+ else:
95
+ layout = "page"
96
+
97
+ return layout
98
+
99
+ def get_template_vars(self, meta, content):
100
+ """Get template variables, include site config and page config"""
101
+ template_vars = copy.deepcopy(self._template_vars)
102
+ page = {"content": content}
103
+ page.update(meta)
104
+ page.update({'relation': self.get_relation()})
105
+
106
+ template_vars.update({'page': page})
107
+
108
+ return template_vars
109
+
110
+ def get_category_and_file(self):
111
+ """Get the name of category and file(with extension)"""
112
+ src_file_relpath_to_source = \
113
+ os.path.relpath(self._src_file, self.site_config['source'])
114
+ category, filename = os.path.split(src_file_relpath_to_source)
115
+ return (category, filename)
116
+
117
+ @staticmethod
118
+ def extract_page(filename):
119
+ """Split the page file texts by triple-dashed lines, return the mata
120
+ and content.
121
+
122
+ :param filename: the filename of markup page
123
+
124
+ returns:
125
+ meta_str (str): page's meta string
126
+ content_str (str): html parsed from markdown or other markup text.
127
+ """
128
+ regex = re.compile('(?sm)^---(?P<meta>.*?)^---(?P<body>.*)')
129
+ with io.open(filename, "rt", encoding="utf-8") as fd:
130
+ match_obj = re.match(regex, fd.read())
131
+ if match_obj:
132
+ meta_str = match_obj.group('meta')
133
+ content_str = match_obj.group('body')
134
+ else:
135
+ raise Exception('extracting page with format error, '
136
+ 'see <http://simiki.org/docs/metadata.html>')
137
+
138
+ return meta_str, content_str
139
+
140
+ def parse_meta(self, yaml_str):
141
+ """Parse meta from yaml string, and validate yaml filed, return dict"""
142
+ try:
143
+ meta = yaml.load(yaml_str, Loader=yaml.FullLoader)
144
+ except yaml.YAMLError as e:
145
+ e.extra_msg = 'yaml format error'
146
+ raise
147
+
148
+ category, src_fname = self.get_category_and_file()
149
+ dst_fname = src_fname.replace(
150
+ ".{0}".format(self.site_config['default_ext']), '.html')
151
+ meta.update({'category': category, 'filename': dst_fname})
152
+
153
+ if 'tag' in meta:
154
+ if isinstance(meta['tag'], basestring):
155
+ _tags = [t.strip() for t in meta['tag'].split(',')]
156
+ meta.update({'tag': _tags})
157
+
158
+ if "title" not in meta:
159
+ raise Exception("no 'title' in meta")
160
+
161
+ return meta
162
+
163
+ def _parse_markup(self, markup_text):
164
+ """Parse markup text to html
165
+
166
+ Only support Markdown for now.
167
+ """
168
+ markdown_extensions = self._set_markdown_extensions()
169
+
170
+ html_content = markdown.markdown(
171
+ markup_text,
172
+ extensions=markdown_extensions,
173
+ )
174
+
175
+ return html_content
176
+
177
+ def _set_markdown_extensions(self):
178
+ """Set the extensions for markdown parser"""
179
+ # Default enabled extensions
180
+ markdown_extensions_config = {
181
+ "fenced_code": {},
182
+ "nl2br": {},
183
+ "toc": {"title": "Table of Contents"},
184
+ "extra": {},
185
+ }
186
+ # Handle pygments
187
+ if self.site_config["pygments"]:
188
+ markdown_extensions_config.update({
189
+ "codehilite": {"css_class": "hlcode"}
190
+ })
191
+ # Handle markdown_ext
192
+ # Ref: https://pythonhosted.org/Markdown/extensions/index.html#officially-supported-extensions # noqa
193
+ if "markdown_ext" in self.site_config:
194
+ markdown_extensions_config.update(self.site_config["markdown_ext"])
195
+
196
+ markdown_extensions = []
197
+ for k, v in markdown_extensions_config.items():
198
+ ext = import_string("markdown.extensions." + k).makeExtension()
199
+ if v:
200
+ for i, j in v.items():
201
+ ext.setConfig(i, j)
202
+ markdown_extensions.append(ext)
203
+
204
+ return markdown_extensions
205
+
206
+ def get_relation(self):
207
+ rn = []
208
+ if self._tags and 'tag' in self.meta:
209
+ for t in self.meta['tag']:
210
+ rn.extend(self._tags[t])
211
+ # remove itself
212
+ rn = [r for r in rn if self.meta['title'] != r['title']]
213
+ # remove the duplicate items
214
+ # note this will change the items order
215
+ rn = [r for n, r in enumerate(rn) if r not in rn[n+1:]] # noqa: E226
216
+ return rn
217
+ ```
218
+
219
+ ## `simiki/generators.py` — `function:PageGenerator.parse_meta` (lines 208-229)
220
+
221
+ ```python
222
+ def parse_meta(self, yaml_str):
223
+ """Parse meta from yaml string, and validate yaml filed, return dict"""
224
+ try:
225
+ meta = yaml.load(yaml_str, Loader=yaml.FullLoader)
226
+ except yaml.YAMLError as e:
227
+ e.extra_msg = 'yaml format error'
228
+ raise
229
+
230
+ category, src_fname = self.get_category_and_file()
231
+ dst_fname = src_fname.replace(
232
+ ".{0}".format(self.site_config['default_ext']), '.html')
233
+ meta.update({'category': category, 'filename': dst_fname})
234
+
235
+ if 'tag' in meta:
236
+ if isinstance(meta['tag'], basestring):
237
+ _tags = [t.strip() for t in meta['tag'].split(',')]
238
+ meta.update({'tag': _tags})
239
+
240
+ if "title" not in meta:
241
+ raise Exception("no 'title' in meta")
242
+
243
+ return meta
244
+ ```
tasks/codeql_python_benchmark51_v2/pyvul-3187445bcbbf39128a26/pre_context.md ADDED
@@ -0,0 +1,244 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Patch-overlapping Python context before the fix
2
+
3
+ ## `simiki/config.py` — `function:parse_config` (lines 57-69)
4
+
5
+ ```python
6
+ def parse_config(config_file):
7
+ if not os.path.exists(config_file):
8
+ raise ConfigFileNotFound("{0} not exists".format(config_file))
9
+
10
+ default_config = _set_default_config()
11
+
12
+ with io.open(config_file, "rt", encoding="utf-8") as fd:
13
+ config = yaml.load(fd)
14
+
15
+ default_config.update(config)
16
+ config = _post_process(default_config)
17
+
18
+ return config
19
+ ```
20
+
21
+ ## `simiki/generators.py` — `class:PageGenerator` (lines 92-284)
22
+
23
+ ```python
24
+ class PageGenerator(BaseGenerator):
25
+
26
+ def __init__(self, site_config, base_path, tags=None):
27
+ super(PageGenerator, self).__init__(site_config, base_path)
28
+ self._tags = tags
29
+ self._reset()
30
+
31
+ def _reset(self):
32
+ """Reset the global self variables"""
33
+ self._src_file = None # source file path relative to base_path
34
+ self.meta = None
35
+ self.content = None
36
+
37
+ def to_html(self, src_file, include_draft=False):
38
+ """Load template, and generate html
39
+
40
+ :src_file: the filename of the source file. This can either be an
41
+ absolute filename or a filename relative to the base path.
42
+ :include_draft: True/False, include draft pages or not to generate
43
+ """
44
+ self._reset()
45
+ self._src_file = os.path.relpath(src_file, self.base_path)
46
+ self.meta, self.content = self.get_meta_and_content()
47
+ # Page set `draft: True' mark current page as draft, and will
48
+ # be ignored if not forced generate include draft pages
49
+ if not include_draft and self.meta.get('draft', False):
50
+ return None
51
+ layout = self.get_layout(self.meta)
52
+ template_vars = self.get_template_vars(self.meta, self.content)
53
+ template = self.get_template(layout)
54
+ html = template.render(template_vars)
55
+
56
+ return html
57
+
58
+ @property
59
+ def src_file(self):
60
+ return self._src_file
61
+
62
+ @src_file.setter
63
+ def src_file(self, filename):
64
+ self._src_file = os.path.relpath(filename, self.base_path)
65
+
66
+ def get_meta_and_content(self, do_render=True):
67
+ meta_str, content_str = self.extract_page(self._src_file)
68
+ meta = self.parse_meta(meta_str)
69
+ # This is the most time consuming part
70
+ if do_render and meta.get('render', True):
71
+ content = self._parse_markup(content_str)
72
+ else:
73
+ content = content_str
74
+
75
+ return meta, content
76
+
77
+ def get_layout(self, meta):
78
+ """Get layout config in meta, default is `page'"""
79
+ if "layout" in meta:
80
+ # Compatible with previous version, which default layout is "post"
81
+ # XXX Will remove this checker in v2.0
82
+ if meta["layout"] == "post":
83
+ warn_msg = "{0}: layout `post' is deprecated, use `page'" \
84
+ .format(self._src_file)
85
+ if is_py2:
86
+ # XXX: warnings message require str, no matter whether
87
+ # py2 or py3; but in py3, bytes message is ok in simple
88
+ # test, but failed in unittest with py3.3, ok with py3.4?
89
+ warn_msg = warn_msg.encode('utf-8')
90
+ warnings.warn(warn_msg, DeprecationWarning)
91
+ layout = "page"
92
+ else:
93
+ layout = meta["layout"]
94
+ else:
95
+ layout = "page"
96
+
97
+ return layout
98
+
99
+ def get_template_vars(self, meta, content):
100
+ """Get template variables, include site config and page config"""
101
+ template_vars = copy.deepcopy(self._template_vars)
102
+ page = {"content": content}
103
+ page.update(meta)
104
+ page.update({'relation': self.get_relation()})
105
+
106
+ template_vars.update({'page': page})
107
+
108
+ return template_vars
109
+
110
+ def get_category_and_file(self):
111
+ """Get the name of category and file(with extension)"""
112
+ src_file_relpath_to_source = \
113
+ os.path.relpath(self._src_file, self.site_config['source'])
114
+ category, filename = os.path.split(src_file_relpath_to_source)
115
+ return (category, filename)
116
+
117
+ @staticmethod
118
+ def extract_page(filename):
119
+ """Split the page file texts by triple-dashed lines, return the mata
120
+ and content.
121
+
122
+ :param filename: the filename of markup page
123
+
124
+ returns:
125
+ meta_str (str): page's meta string
126
+ content_str (str): html parsed from markdown or other markup text.
127
+ """
128
+ regex = re.compile('(?sm)^---(?P<meta>.*?)^---(?P<body>.*)')
129
+ with io.open(filename, "rt", encoding="utf-8") as fd:
130
+ match_obj = re.match(regex, fd.read())
131
+ if match_obj:
132
+ meta_str = match_obj.group('meta')
133
+ content_str = match_obj.group('body')
134
+ else:
135
+ raise Exception('extracting page with format error, '
136
+ 'see <http://simiki.org/docs/metadata.html>')
137
+
138
+ return meta_str, content_str
139
+
140
+ def parse_meta(self, yaml_str):
141
+ """Parse meta from yaml string, and validate yaml filed, return dict"""
142
+ try:
143
+ meta = yaml.load(yaml_str)
144
+ except yaml.YAMLError as e:
145
+ e.extra_msg = 'yaml format error'
146
+ raise
147
+
148
+ category, src_fname = self.get_category_and_file()
149
+ dst_fname = src_fname.replace(
150
+ ".{0}".format(self.site_config['default_ext']), '.html')
151
+ meta.update({'category': category, 'filename': dst_fname})
152
+
153
+ if 'tag' in meta:
154
+ if isinstance(meta['tag'], basestring):
155
+ _tags = [t.strip() for t in meta['tag'].split(',')]
156
+ meta.update({'tag': _tags})
157
+
158
+ if "title" not in meta:
159
+ raise Exception("no 'title' in meta")
160
+
161
+ return meta
162
+
163
+ def _parse_markup(self, markup_text):
164
+ """Parse markup text to html
165
+
166
+ Only support Markdown for now.
167
+ """
168
+ markdown_extensions = self._set_markdown_extensions()
169
+
170
+ html_content = markdown.markdown(
171
+ markup_text,
172
+ extensions=markdown_extensions,
173
+ )
174
+
175
+ return html_content
176
+
177
+ def _set_markdown_extensions(self):
178
+ """Set the extensions for markdown parser"""
179
+ # Default enabled extensions
180
+ markdown_extensions_config = {
181
+ "fenced_code": {},
182
+ "nl2br": {},
183
+ "toc": {"title": "Table of Contents"},
184
+ "extra": {},
185
+ }
186
+ # Handle pygments
187
+ if self.site_config["pygments"]:
188
+ markdown_extensions_config.update({
189
+ "codehilite": {"css_class": "hlcode"}
190
+ })
191
+ # Handle markdown_ext
192
+ # Ref: https://pythonhosted.org/Markdown/extensions/index.html#officially-supported-extensions # noqa
193
+ if "markdown_ext" in self.site_config:
194
+ markdown_extensions_config.update(self.site_config["markdown_ext"])
195
+
196
+ markdown_extensions = []
197
+ for k, v in markdown_extensions_config.items():
198
+ ext = import_string("markdown.extensions." + k).makeExtension()
199
+ if v:
200
+ for i, j in v.items():
201
+ ext.setConfig(i, j)
202
+ markdown_extensions.append(ext)
203
+
204
+ return markdown_extensions
205
+
206
+ def get_relation(self):
207
+ rn = []
208
+ if self._tags and 'tag' in self.meta:
209
+ for t in self.meta['tag']:
210
+ rn.extend(self._tags[t])
211
+ # remove itself
212
+ rn = [r for r in rn if self.meta['title'] != r['title']]
213
+ # remove the duplicate items
214
+ # note this will change the items order
215
+ rn = [r for n, r in enumerate(rn) if r not in rn[n+1:]] # noqa: E226
216
+ return rn
217
+ ```
218
+
219
+ ## `simiki/generators.py` — `function:PageGenerator.parse_meta` (lines 208-229)
220
+
221
+ ```python
222
+ def parse_meta(self, yaml_str):
223
+ """Parse meta from yaml string, and validate yaml filed, return dict"""
224
+ try:
225
+ meta = yaml.load(yaml_str)
226
+ except yaml.YAMLError as e:
227
+ e.extra_msg = 'yaml format error'
228
+ raise
229
+
230
+ category, src_fname = self.get_category_and_file()
231
+ dst_fname = src_fname.replace(
232
+ ".{0}".format(self.site_config['default_ext']), '.html')
233
+ meta.update({'category': category, 'filename': dst_fname})
234
+
235
+ if 'tag' in meta:
236
+ if isinstance(meta['tag'], basestring):
237
+ _tags = [t.strip() for t in meta['tag'].split(',')]
238
+ meta.update({'tag': _tags})
239
+
240
+ if "title" not in meta:
241
+ raise Exception("no 'title' in meta")
242
+
243
+ return meta
244
+ ```
tasks/codeql_python_benchmark51_v2/pyvul-3187445bcbbf39128a26/task.json ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "schema_version": "synthesis-task-v1",
3
+ "task": {
4
+ "pair_id": "pyvul-3187445bcbbf39128a26",
5
+ "dataset_id": "PyVul",
6
+ "dataset_item_id": "pyvul-3187445bcbbf39128a26",
7
+ "project_id": "pyvul__tankywoo__simiki",
8
+ "language": "python",
9
+ "backend": "codeql"
10
+ },
11
+ "changed_python_files": [
12
+ "simiki/config.py",
13
+ "simiki/generators.py"
14
+ ],
15
+ "patch_units": {
16
+ "before": [
17
+ "function:parse_config",
18
+ "class:PageGenerator",
19
+ "function:PageGenerator.parse_meta"
20
+ ],
21
+ "after": [
22
+ "function:parse_config",
23
+ "class:PageGenerator",
24
+ "function:PageGenerator.parse_meta"
25
+ ]
26
+ },
27
+ "runtime_assets": {
28
+ "before": {
29
+ "database": "assets/6c677522fd3c28ce7e1472d351798d0e087b50dd4e508e0f5fcc1bee0af173f1/database",
30
+ "cache_key": "6c677522fd3c28ce7e1472d351798d0e087b50dd4e508e0f5fcc1bee0af173f1",
31
+ "codeql_version": "2.26.4"
32
+ },
33
+ "after": {
34
+ "database": "assets/7e613b7efe30230563633a9a574d8c2fa71dcc345fff934fc4de7ceb656cf8fe/database",
35
+ "cache_key": "7e613b7efe30230563633a9a574d8c2fa71dcc345fff934fc4de7ceb656cf8fe",
36
+ "codeql_version": "2.26.4"
37
+ },
38
+ "refine": {
39
+ "database": "assets/8d8b60dfa034c14268f005e72f669accfdfac1fb52182a03fea8cd89a0322db3/database",
40
+ "cache_key": "8d8b60dfa034c14268f005e72f669accfdfac1fb52182a03fea8cd89a0322db3",
41
+ "codeql_version": "2.26.4"
42
+ }
43
+ },
44
+ "benchmark_contract": {
45
+ "agent_visible": true,
46
+ "reference_query_location": "references/pyvul-3187445bcbbf39128a26/query/ (do not mount into agent)",
47
+ "evaluator_location": "evaluator/pyvul-3187445bcbbf39128a26/ (do not mount into agent)"
48
+ }
49
+ }
tasks/codeql_python_benchmark51_v2/pyvul-3187445bcbbf39128a26/task_prompt.md ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Python CodeQL detector synthesis
2
+
3
+ You are cc operating in `/work`. Starting only from the supplied patch,
4
+ before/after Python context, CodeQL references, and validation tools, synthesize a semantic CodeQL
5
+ detector for the vulnerability fixed by the patch. This is one fresh session. You may iterate inside
6
+ this session, but no later framework repair or resume will occur.
7
+
8
+ ## Inputs and owned outputs
9
+
10
+ - Read `patch.diff`, `python_patch.diff`, `pre_context.md`, and `post_context.md`.
11
+ - Read `references/codeql/convergence_protocol.md` and
12
+ `references/codeql/api_navigation.md` before experimenting. Read the remaining
13
+ `references/codeql/` files for the selected mechanism.
14
+ - Use `scripts/search_codeql_api.sh` to inspect the pinned official libraries when an API detail is
15
+ uncertain. Do not guess predicate names or build a large family of inspection queries.
16
+ - Complete the design contract in `state.json` and `scope_statement.md` before final validation.
17
+ - Replace `query/vulnerability.ql`; add only genuinely shared `.qll` helpers when useful. Keep the
18
+ fixed offline dependency in `query/qlpack.yml`.
19
+ - Preserve the exact `expected_query_id` from `config.json` as the query's sole `@id`. This
20
+ task-unique metadata must never be used in a query predicate.
21
+ - Use `scripts/compile_query.sh`, `scripts/run_before.sh`, and `scripts/run_after.sh`.
22
+ - Finish by writing `summary.json` with `status`, `query_path`, `query_kind`, `build_passed`,
23
+ `before_findings`, `after_findings`, `validation_completed`, and a concise `notes` field.
24
+
25
+ ## Required reasoning contract
26
+
27
+ Before coding, record this mapping in `state.json`:
28
+
29
+ ```text
30
+ vulnerable operation / trigger / patch safety condition
31
+ → CodeQL-observable evidence
32
+ → syntax, control-flow, local value-flow, global taint/value-flow, or interprocedural mechanism
33
+ → source, sink/report site, guard/barrier and query predicates
34
+ ```
35
+
36
+ Choose the lowest mechanism that can actually prove the condition. Guard-sensitive patches require
37
+ real path/control-flow semantics; provenance-sensitive patches require value flow. Do not replace
38
+ either with source-text matching or with the mere presence of patch-added syntax.
39
+
40
+ ## Mandatory convergence contract
41
+
42
+ The rollout has a 30-minute hard wall-clock ceiling and must be finalized by minute 27. Minutes
43
+ 27–30 are an emergency shutdown buffer, not exploration time. A sophisticated unfinished query is
44
+ a failure; an early compilable semantic candidate can be improved. Follow the checkpoints in
45
+ `references/codeql/convergence_protocol.md`:
46
+
47
+ 1. Record the mechanism contract, then replace the placeholder in `query/vulnerability.ql`
48
+ immediately. Do not wait until every CodeQL API detail is known.
49
+ 2. Use at most three distinct scratch `.ql` files. Prefer repeatedly editing one
50
+ `query/scratch.ql`. After two failed variants of one API assumption, inspect the exact bundled
51
+ definition with `scripts/search_codeql_api.sh` or simplify the mechanism.
52
+ 3. Obtain a compiling minimal main query before broadening it. Compile the main query after every
53
+ meaningful mechanism change.
54
+ 4. Move in order from compile → relevant before finding → after elimination → final contract. Do
55
+ not continue API exploration after the intended before/after differential is established.
56
+ 5. Run `scripts/check_progress.sh` at each checkpoint. It reports elapsed time, the minute-27
57
+ finalization deadline, and the minute-30 hard timeout. When it prints `finalize_now`, stop all
58
+ exploration, preserve the best compiling query, finish the contract files, and exit.
59
+
60
+ ## Semantic and generalization rules
61
+
62
+ - Report at the vulnerable call, operator, access, or sink.
63
+ - Do not use a patch-local path, line, commit hash, label, or local variable name as the primary
64
+ matching condition. Stable library/framework APIs or public project APIs are allowed only when
65
+ `scope_statement.md` explains why they define the intended vulnerability family.
66
+ - The safety condition introduced by the patch must be represented by the query.
67
+ - A lower after warning count is not enough: inspect SARIF and ensure at least one intended before
68
+ finding is in a patch-overlapping semantic unit and the corresponding finding disappears after.
69
+ - Avoid broad proxy queries that report an enclosing function or unrelated API merely because it
70
+ changed in the patch.
71
+
72
+ ## Final validation protocol
73
+
74
+ 1. Compile the final query.
75
+ 2. Run it on before and inspect `raw/before.sarif` for the intended report location.
76
+ 3. Run the identical query on after and inspect `raw/after.sarif`.
77
+ 4. Recheck query metadata, query kind/select signature, report locality, design-to-code consistency,
78
+ and absence of patch-local hardcoding.
79
+ 5. Update `state.json`, `scope_statement.md`, and write valid `summary.json`.
80
+
81
+ Do not modify the runtime databases, references, patch, context, or validation scripts except for
82
+ normal CodeQL-generated database caches produced by the provided run scripts.
tasks/codeql_python_benchmark51_v2/pyvul-36a40541d7c74a9a7777/patch.diff ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ diff --git a/CHANGELOG.md b/CHANGELOG.md
2
+ index 225fced44..7bfe08edb 100644
3
+ --- a/CHANGELOG.md
4
+ +++ b/CHANGELOG.md
5
+ @@ -663,9 +663,13 @@ The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/).
6
+
7
+ - Fixed an issue where `HorovodStrategy.teardown()` did not complete gracefully if an exception was thrown during callback setup [#11752](https://github.com/PyTorchLightning/pytorch-lightning/pull/11752)
8
+
9
+ +
10
+ - Fixed security vulnerabilities CVE-2020-1747 and CVE-2020-14343 caused by the `PyYAML` dependency ([#11099](https://github.com/PyTorchLightning/pytorch-lightning/pull/11099))
11
+
12
+
13
+ +- Fixed security vulnerability "CWE-94: Improper Control of Generation of Code (Code Injection)" ([#12212](https://github.com/PyTorchLightning/pytorch-lightning/pull/12212))
14
+ +
15
+ +
16
+ - Fixed logging on `{test,validation}_epoch_end` with multiple dataloaders ([#11132](https://github.com/PyTorchLightning/pytorch-lightning/pull/11132))
17
+
18
+
19
+ diff --git a/pytorch_lightning/utilities/argparse.py b/pytorch_lightning/utilities/argparse.py
20
+ index e729f862c..8927ff093 100644
21
+ --- a/pytorch_lightning/utilities/argparse.py
22
+ +++ b/pytorch_lightning/utilities/argparse.py
23
+ @@ -17,6 +17,7 @@ import inspect
24
+ import os
25
+ from abc import ABC
26
+ from argparse import _ArgumentGroup, ArgumentParser, Namespace
27
+ +from ast import literal_eval
28
+ from contextlib import suppress
29
+ from functools import wraps
30
+ from typing import Any, Callable, cast, Dict, List, Tuple, Type, TypeVar, Union
31
+ @@ -121,7 +122,7 @@ def parse_env_variables(cls: Type["pl.Trainer"], template: str = "PL_%(cls_name)
32
+ # todo: specify the possible exception
33
+ with suppress(Exception):
34
+ # converting to native types like int/float/bool
35
+ - val = eval(val)
36
+ + val = literal_eval(val)
37
+ env_args[arg_name] = val
38
+ return Namespace(**env_args)
39
+
tasks/codeql_python_benchmark51_v2/pyvul-36a40541d7c74a9a7777/post_context.md ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Patch-overlapping Python context after the fix
2
+
3
+ ## `pytorch_lightning/utilities/argparse.py` — `function:parse_env_variables` (lines 100-127)
4
+
5
+ ```python
6
+ def parse_env_variables(cls: Type["pl.Trainer"], template: str = "PL_%(cls_name)s_%(cls_argument)s") -> Namespace:
7
+ """Parse environment arguments if they are defined.
8
+
9
+ Examples:
10
+
11
+ >>> from pytorch_lightning import Trainer
12
+ >>> parse_env_variables(Trainer)
13
+ Namespace()
14
+ >>> import os
15
+ >>> os.environ["PL_TRAINER_GPUS"] = '42'
16
+ >>> os.environ["PL_TRAINER_BLABLABLA"] = '1.23'
17
+ >>> parse_env_variables(Trainer)
18
+ Namespace(gpus=42)
19
+ >>> del os.environ["PL_TRAINER_GPUS"]
20
+ """
21
+ cls_arg_defaults = get_init_arguments_and_types(cls)
22
+
23
+ env_args = {}
24
+ for arg_name, _, _ in cls_arg_defaults:
25
+ env = template % {"cls_name": cls.__name__.upper(), "cls_argument": arg_name.upper()}
26
+ val = os.environ.get(env)
27
+ if not (val is None or val == ""):
28
+ # todo: specify the possible exception
29
+ with suppress(Exception):
30
+ # converting to native types like int/float/bool
31
+ val = literal_eval(val)
32
+ env_args[arg_name] = val
33
+ return Namespace(**env_args)
34
+ ```
35
+
36
+ ## `pytorch_lightning/utilities/argparse.py` — `module:<module>@20` (lines 20-20)
37
+
38
+ ```python
39
+ from ast import literal_eval
40
+ ```
tasks/codeql_python_benchmark51_v2/pyvul-36a40541d7c74a9a7777/pre_context.md ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Patch-overlapping Python context before the fix
2
+
3
+ ## `pytorch_lightning/utilities/argparse.py` — `function:parse_env_variables` (lines 99-126)
4
+
5
+ ```python
6
+ def parse_env_variables(cls: Type["pl.Trainer"], template: str = "PL_%(cls_name)s_%(cls_argument)s") -> Namespace:
7
+ """Parse environment arguments if they are defined.
8
+
9
+ Examples:
10
+
11
+ >>> from pytorch_lightning import Trainer
12
+ >>> parse_env_variables(Trainer)
13
+ Namespace()
14
+ >>> import os
15
+ >>> os.environ["PL_TRAINER_GPUS"] = '42'
16
+ >>> os.environ["PL_TRAINER_BLABLABLA"] = '1.23'
17
+ >>> parse_env_variables(Trainer)
18
+ Namespace(gpus=42)
19
+ >>> del os.environ["PL_TRAINER_GPUS"]
20
+ """
21
+ cls_arg_defaults = get_init_arguments_and_types(cls)
22
+
23
+ env_args = {}
24
+ for arg_name, _, _ in cls_arg_defaults:
25
+ env = template % {"cls_name": cls.__name__.upper(), "cls_argument": arg_name.upper()}
26
+ val = os.environ.get(env)
27
+ if not (val is None or val == ""):
28
+ # todo: specify the possible exception
29
+ with suppress(Exception):
30
+ # converting to native types like int/float/bool
31
+ val = eval(val)
32
+ env_args[arg_name] = val
33
+ return Namespace(**env_args)
34
+ ```
35
+
36
+ ## `pytorch_lightning/utilities/argparse.py` — `module:<module>@20` (lines 20-20)
37
+
38
+ ```python
39
+ from contextlib import suppress
40
+ ```
tasks/codeql_python_benchmark51_v2/pyvul-36a40541d7c74a9a7777/task.json ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "schema_version": "synthesis-task-v1",
3
+ "task": {
4
+ "pair_id": "pyvul-36a40541d7c74a9a7777",
5
+ "dataset_id": "PyVul",
6
+ "dataset_item_id": "pyvul-36a40541d7c74a9a7777",
7
+ "project_id": "pyvul__pytorchlightning__pytorch-lightning",
8
+ "language": "python",
9
+ "backend": "codeql"
10
+ },
11
+ "changed_python_files": [
12
+ "pytorch_lightning/utilities/argparse.py"
13
+ ],
14
+ "patch_units": {
15
+ "before": [
16
+ "function:parse_env_variables",
17
+ "module:<module>@20"
18
+ ],
19
+ "after": [
20
+ "function:parse_env_variables",
21
+ "module:<module>@20"
22
+ ]
23
+ },
24
+ "runtime_assets": {
25
+ "before": {
26
+ "database": "assets/f904a001805ca2a12850f3d3056b70f7b209467a621d3da7fe0e4e98faa4b9c9/database",
27
+ "cache_key": "f904a001805ca2a12850f3d3056b70f7b209467a621d3da7fe0e4e98faa4b9c9",
28
+ "codeql_version": "2.26.4"
29
+ },
30
+ "after": {
31
+ "database": "assets/f9a6566d69a61c361650443ebcecb4d650d674333e5dda7f6c57320a8ff0a764/database",
32
+ "cache_key": "f9a6566d69a61c361650443ebcecb4d650d674333e5dda7f6c57320a8ff0a764",
33
+ "codeql_version": "2.26.4"
34
+ },
35
+ "refine": {
36
+ "database": "assets/0e9729244a800a484f57498b45d84807d5007185f2cdaea70346b3a3ea9f43bc/database",
37
+ "cache_key": "0e9729244a800a484f57498b45d84807d5007185f2cdaea70346b3a3ea9f43bc",
38
+ "codeql_version": "2.26.4"
39
+ }
40
+ },
41
+ "benchmark_contract": {
42
+ "agent_visible": true,
43
+ "reference_query_location": "references/pyvul-36a40541d7c74a9a7777/query/ (do not mount into agent)",
44
+ "evaluator_location": "evaluator/pyvul-36a40541d7c74a9a7777/ (do not mount into agent)"
45
+ }
46
+ }
tasks/codeql_python_benchmark51_v2/pyvul-36a40541d7c74a9a7777/task_prompt.md ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Python CodeQL detector synthesis
2
+
3
+ You are cc operating in `/work`. Starting only from the supplied patch,
4
+ before/after Python context, CodeQL references, and validation tools, synthesize a semantic CodeQL
5
+ detector for the vulnerability fixed by the patch. This is one fresh session. You may iterate inside
6
+ this session, but no later framework repair or resume will occur.
7
+
8
+ ## Inputs and owned outputs
9
+
10
+ - Read `patch.diff`, `python_patch.diff`, `pre_context.md`, and `post_context.md`.
11
+ - Read `references/codeql/convergence_protocol.md` and
12
+ `references/codeql/api_navigation.md` before experimenting. Read the remaining
13
+ `references/codeql/` files for the selected mechanism.
14
+ - Use `scripts/search_codeql_api.sh` to inspect the pinned official libraries when an API detail is
15
+ uncertain. Do not guess predicate names or build a large family of inspection queries.
16
+ - Complete the design contract in `state.json` and `scope_statement.md` before final validation.
17
+ - Replace `query/vulnerability.ql`; add only genuinely shared `.qll` helpers when useful. Keep the
18
+ fixed offline dependency in `query/qlpack.yml`.
19
+ - Preserve the exact `expected_query_id` from `config.json` as the query's sole `@id`. This
20
+ task-unique metadata must never be used in a query predicate.
21
+ - Use `scripts/compile_query.sh`, `scripts/run_before.sh`, and `scripts/run_after.sh`.
22
+ - Finish by writing `summary.json` with `status`, `query_path`, `query_kind`, `build_passed`,
23
+ `before_findings`, `after_findings`, `validation_completed`, and a concise `notes` field.
24
+
25
+ ## Required reasoning contract
26
+
27
+ Before coding, record this mapping in `state.json`:
28
+
29
+ ```text
30
+ vulnerable operation / trigger / patch safety condition
31
+ → CodeQL-observable evidence
32
+ → syntax, control-flow, local value-flow, global taint/value-flow, or interprocedural mechanism
33
+ → source, sink/report site, guard/barrier and query predicates
34
+ ```
35
+
36
+ Choose the lowest mechanism that can actually prove the condition. Guard-sensitive patches require
37
+ real path/control-flow semantics; provenance-sensitive patches require value flow. Do not replace
38
+ either with source-text matching or with the mere presence of patch-added syntax.
39
+
40
+ ## Mandatory convergence contract
41
+
42
+ The rollout has a 30-minute hard wall-clock ceiling and must be finalized by minute 27. Minutes
43
+ 27–30 are an emergency shutdown buffer, not exploration time. A sophisticated unfinished query is
44
+ a failure; an early compilable semantic candidate can be improved. Follow the checkpoints in
45
+ `references/codeql/convergence_protocol.md`:
46
+
47
+ 1. Record the mechanism contract, then replace the placeholder in `query/vulnerability.ql`
48
+ immediately. Do not wait until every CodeQL API detail is known.
49
+ 2. Use at most three distinct scratch `.ql` files. Prefer repeatedly editing one
50
+ `query/scratch.ql`. After two failed variants of one API assumption, inspect the exact bundled
51
+ definition with `scripts/search_codeql_api.sh` or simplify the mechanism.
52
+ 3. Obtain a compiling minimal main query before broadening it. Compile the main query after every
53
+ meaningful mechanism change.
54
+ 4. Move in order from compile → relevant before finding → after elimination → final contract. Do
55
+ not continue API exploration after the intended before/after differential is established.
56
+ 5. Run `scripts/check_progress.sh` at each checkpoint. It reports elapsed time, the minute-27
57
+ finalization deadline, and the minute-30 hard timeout. When it prints `finalize_now`, stop all
58
+ exploration, preserve the best compiling query, finish the contract files, and exit.
59
+
60
+ ## Semantic and generalization rules
61
+
62
+ - Report at the vulnerable call, operator, access, or sink.
63
+ - Do not use a patch-local path, line, commit hash, label, or local variable name as the primary
64
+ matching condition. Stable library/framework APIs or public project APIs are allowed only when
65
+ `scope_statement.md` explains why they define the intended vulnerability family.
66
+ - The safety condition introduced by the patch must be represented by the query.
67
+ - A lower after warning count is not enough: inspect SARIF and ensure at least one intended before
68
+ finding is in a patch-overlapping semantic unit and the corresponding finding disappears after.
69
+ - Avoid broad proxy queries that report an enclosing function or unrelated API merely because it
70
+ changed in the patch.
71
+
72
+ ## Final validation protocol
73
+
74
+ 1. Compile the final query.
75
+ 2. Run it on before and inspect `raw/before.sarif` for the intended report location.
76
+ 3. Run the identical query on after and inspect `raw/after.sarif`.
77
+ 4. Recheck query metadata, query kind/select signature, report locality, design-to-code consistency,
78
+ and absence of patch-local hardcoding.
79
+ 5. Update `state.json`, `scope_statement.md`, and write valid `summary.json`.
80
+
81
+ Do not modify the runtime databases, references, patch, context, or validation scripts except for
82
+ normal CodeQL-generated database caches produced by the provided run scripts.
tasks/codeql_python_benchmark51_v2/pyvul-3819b1a7530257524a75/patch.diff ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ diff --git a/templated_dictionary/__init__.py b/templated_dictionary/__init__.py
2
+ index 994166a..ec004c0 100644
3
+ --- a/templated_dictionary/__init__.py
4
+ +++ b/templated_dictionary/__init__.py
5
+ @@ -2,7 +2,7 @@
6
+ # vim:expandtab:autoindent:tabstop=4:shiftwidth=4:filetype=python:textwidth=0:
7
+
8
+ from collections.abc import MutableMapping
9
+ -import jinja2
10
+ +from jinja2 import sandbox
11
+
12
+
13
+ # pylint: disable=no-member,unsupported-assignment-operation
14
+ @@ -19,6 +19,8 @@ class TemplatedDictionary(MutableMapping):
15
+ '''
16
+ self.__dict__.update(*args, **kwargs)
17
+
18
+ + self.sandbox = sandbox.SandboxedEnvironment(keep_trailing_newline=True)
19
+ +
20
+ self._aliases = {}
21
+ if alias_spec:
22
+ for aliased_to, aliases in alias_spec.items():
23
+ @@ -80,8 +82,7 @@ class TemplatedDictionary(MutableMapping):
24
+ orig = last = value
25
+ max_recursion = self.__dict__.get('jinja_max_recursion', 5)
26
+ for _ in range(max_recursion):
27
+ - template = jinja2.Template(value, keep_trailing_newline=True)
28
+ - value = _to_native(template.render(self.__dict__))
29
+ + value = _to_native(self.sandbox.from_string(value).render(self.__dict__, func=lambda:None))
30
+ if value == last:
31
+ return value
32
+ last = value
tasks/codeql_python_benchmark51_v2/pyvul-3819b1a7530257524a75/post_context.md ADDED
@@ -0,0 +1,130 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Patch-overlapping Python context after the fix
2
+
3
+ ## `templated_dictionary/__init__.py` — `class:TemplatedDictionary` (lines 9-89)
4
+
5
+ ```python
6
+ class TemplatedDictionary(MutableMapping):
7
+ """ Dictionary where __getitem__() is run through Jinja2 template """
8
+ def __init__(self, *args, alias_spec=None, **kwargs):
9
+ '''
10
+ Use the object dict.
11
+
12
+ Optional parameter 'alias_spec' is dictionary of form:
13
+ {'aliased_to': ['alias_one', 'alias_two', ...], ...}
14
+ When specified, and one of the aliases is accessed - the
15
+ 'aliased_to' config option is returned.
16
+ '''
17
+ self.__dict__.update(*args, **kwargs)
18
+
19
+ self.sandbox = sandbox.SandboxedEnvironment(keep_trailing_newline=True)
20
+
21
+ self._aliases = {}
22
+ if alias_spec:
23
+ for aliased_to, aliases in alias_spec.items():
24
+ for alias in aliases:
25
+ self._aliases[alias] = aliased_to
26
+
27
+ # The next five methods are requirements of the ABC.
28
+ def __setitem__(self, key, value):
29
+ key = self._aliases.get(key, key)
30
+ self.__dict__[key] = value
31
+
32
+ def __getitem__(self, key):
33
+ key = self._aliases.get(key, key)
34
+ if '__jinja_expand' in self.__dict__ and self.__dict__['__jinja_expand']:
35
+ return self.__render_value(self.__dict__[key])
36
+ return self.__dict__[key]
37
+
38
+ def __delitem__(self, key):
39
+ del self.__dict__[key]
40
+
41
+ def __iter__(self):
42
+ return iter(self.__dict__)
43
+
44
+ def __len__(self):
45
+ return len(self.__dict__)
46
+
47
+ # The final two methods aren't required, but nice to have
48
+ def __str__(self):
49
+ '''returns simple dict representation of the mapping'''
50
+ return str(self.__dict__)
51
+
52
+ def __repr__(self):
53
+ '''echoes class, id, & reproducible representation in the REPL'''
54
+ return '{}, TemplatedDictionary({})'.format(super(TemplatedDictionary, self).__repr__(),
55
+ self.__dict__)
56
+
57
+ def copy(self):
58
+ return TemplatedDictionary(self.__dict__)
59
+
60
+ def __render_value(self, value):
61
+ if isinstance(value, str):
62
+ return self.__render_string(value)
63
+ elif isinstance(value, list):
64
+ # we cannot use list comprehension here, as we need to NOT modify the list (pointer to list)
65
+ # and we need to modifiy only individual values in the list
66
+ # If we would create new list, we cannot assign to it, which often happens in configs (e.g. plugins)
67
+ for i in range(len(value)): # pylint: disable=consider-using-enumerate
68
+ value[i] = self.__render_value(value[i])
69
+ return value
70
+ elif isinstance(value, dict):
71
+ # we cannot use list comprehension here, same reasoning as for `list` above
72
+ for k in value.keys():
73
+ value[k] = self.__render_value(value[k])
74
+ return value
75
+ else:
76
+ return value
77
+
78
+ def __render_string(self, value):
79
+ orig = last = value
80
+ max_recursion = self.__dict__.get('jinja_max_recursion', 5)
81
+ for _ in range(max_recursion):
82
+ value = _to_native(self.sandbox.from_string(value).render(self.__dict__, func=lambda:None))
83
+ if value == last:
84
+ return value
85
+ last = value
86
+ raise ValueError("too deep jinja re-evaluation on '{}'".format(orig))
87
+ ```
88
+
89
+ ## `templated_dictionary/__init__.py` — `function:TemplatedDictionary.__init__` (lines 11-28)
90
+
91
+ ```python
92
+ def __init__(self, *args, alias_spec=None, **kwargs):
93
+ '''
94
+ Use the object dict.
95
+
96
+ Optional parameter 'alias_spec' is dictionary of form:
97
+ {'aliased_to': ['alias_one', 'alias_two', ...], ...}
98
+ When specified, and one of the aliases is accessed - the
99
+ 'aliased_to' config option is returned.
100
+ '''
101
+ self.__dict__.update(*args, **kwargs)
102
+
103
+ self.sandbox = sandbox.SandboxedEnvironment(keep_trailing_newline=True)
104
+
105
+ self._aliases = {}
106
+ if alias_spec:
107
+ for aliased_to, aliases in alias_spec.items():
108
+ for alias in aliases:
109
+ self._aliases[alias] = aliased_to
110
+ ```
111
+
112
+ ## `templated_dictionary/__init__.py` — `function:TemplatedDictionary.__render_string` (lines 81-89)
113
+
114
+ ```python
115
+ def __render_string(self, value):
116
+ orig = last = value
117
+ max_recursion = self.__dict__.get('jinja_max_recursion', 5)
118
+ for _ in range(max_recursion):
119
+ value = _to_native(self.sandbox.from_string(value).render(self.__dict__, func=lambda:None))
120
+ if value == last:
121
+ return value
122
+ last = value
123
+ raise ValueError("too deep jinja re-evaluation on '{}'".format(orig))
124
+ ```
125
+
126
+ ## `templated_dictionary/__init__.py` — `module:<module>@5` (lines 5-5)
127
+
128
+ ```python
129
+ from jinja2 import sandbox
130
+ ```
tasks/codeql_python_benchmark51_v2/pyvul-3819b1a7530257524a75/pre_context.md ADDED
@@ -0,0 +1,128 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Patch-overlapping Python context before the fix
2
+
3
+ ## `templated_dictionary/__init__.py` — `class:TemplatedDictionary` (lines 9-88)
4
+
5
+ ```python
6
+ class TemplatedDictionary(MutableMapping):
7
+ """ Dictionary where __getitem__() is run through Jinja2 template """
8
+ def __init__(self, *args, alias_spec=None, **kwargs):
9
+ '''
10
+ Use the object dict.
11
+
12
+ Optional parameter 'alias_spec' is dictionary of form:
13
+ {'aliased_to': ['alias_one', 'alias_two', ...], ...}
14
+ When specified, and one of the aliases is accessed - the
15
+ 'aliased_to' config option is returned.
16
+ '''
17
+ self.__dict__.update(*args, **kwargs)
18
+
19
+ self._aliases = {}
20
+ if alias_spec:
21
+ for aliased_to, aliases in alias_spec.items():
22
+ for alias in aliases:
23
+ self._aliases[alias] = aliased_to
24
+
25
+ # The next five methods are requirements of the ABC.
26
+ def __setitem__(self, key, value):
27
+ key = self._aliases.get(key, key)
28
+ self.__dict__[key] = value
29
+
30
+ def __getitem__(self, key):
31
+ key = self._aliases.get(key, key)
32
+ if '__jinja_expand' in self.__dict__ and self.__dict__['__jinja_expand']:
33
+ return self.__render_value(self.__dict__[key])
34
+ return self.__dict__[key]
35
+
36
+ def __delitem__(self, key):
37
+ del self.__dict__[key]
38
+
39
+ def __iter__(self):
40
+ return iter(self.__dict__)
41
+
42
+ def __len__(self):
43
+ return len(self.__dict__)
44
+
45
+ # The final two methods aren't required, but nice to have
46
+ def __str__(self):
47
+ '''returns simple dict representation of the mapping'''
48
+ return str(self.__dict__)
49
+
50
+ def __repr__(self):
51
+ '''echoes class, id, & reproducible representation in the REPL'''
52
+ return '{}, TemplatedDictionary({})'.format(super(TemplatedDictionary, self).__repr__(),
53
+ self.__dict__)
54
+
55
+ def copy(self):
56
+ return TemplatedDictionary(self.__dict__)
57
+
58
+ def __render_value(self, value):
59
+ if isinstance(value, str):
60
+ return self.__render_string(value)
61
+ elif isinstance(value, list):
62
+ # we cannot use list comprehension here, as we need to NOT modify the list (pointer to list)
63
+ # and we need to modifiy only individual values in the list
64
+ # If we would create new list, we cannot assign to it, which often happens in configs (e.g. plugins)
65
+ for i in range(len(value)): # pylint: disable=consider-using-enumerate
66
+ value[i] = self.__render_value(value[i])
67
+ return value
68
+ elif isinstance(value, dict):
69
+ # we cannot use list comprehension here, same reasoning as for `list` above
70
+ for k in value.keys():
71
+ value[k] = self.__render_value(value[k])
72
+ return value
73
+ else:
74
+ return value
75
+
76
+ def __render_string(self, value):
77
+ orig = last = value
78
+ max_recursion = self.__dict__.get('jinja_max_recursion', 5)
79
+ for _ in range(max_recursion):
80
+ template = jinja2.Template(value, keep_trailing_newline=True)
81
+ value = _to_native(template.render(self.__dict__))
82
+ if value == last:
83
+ return value
84
+ last = value
85
+ raise ValueError("too deep jinja re-evaluation on '{}'".format(orig))
86
+ ```
87
+
88
+ ## `templated_dictionary/__init__.py` — `function:TemplatedDictionary.__init__` (lines 11-26)
89
+
90
+ ```python
91
+ def __init__(self, *args, alias_spec=None, **kwargs):
92
+ '''
93
+ Use the object dict.
94
+
95
+ Optional parameter 'alias_spec' is dictionary of form:
96
+ {'aliased_to': ['alias_one', 'alias_two', ...], ...}
97
+ When specified, and one of the aliases is accessed - the
98
+ 'aliased_to' config option is returned.
99
+ '''
100
+ self.__dict__.update(*args, **kwargs)
101
+
102
+ self._aliases = {}
103
+ if alias_spec:
104
+ for aliased_to, aliases in alias_spec.items():
105
+ for alias in aliases:
106
+ self._aliases[alias] = aliased_to
107
+ ```
108
+
109
+ ## `templated_dictionary/__init__.py` — `function:TemplatedDictionary.__render_string` (lines 79-88)
110
+
111
+ ```python
112
+ def __render_string(self, value):
113
+ orig = last = value
114
+ max_recursion = self.__dict__.get('jinja_max_recursion', 5)
115
+ for _ in range(max_recursion):
116
+ template = jinja2.Template(value, keep_trailing_newline=True)
117
+ value = _to_native(template.render(self.__dict__))
118
+ if value == last:
119
+ return value
120
+ last = value
121
+ raise ValueError("too deep jinja re-evaluation on '{}'".format(orig))
122
+ ```
123
+
124
+ ## `templated_dictionary/__init__.py` — `module:<module>@5` (lines 5-5)
125
+
126
+ ```python
127
+ import jinja2
128
+ ```
tasks/codeql_python_benchmark51_v2/pyvul-3819b1a7530257524a75/task.json ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "schema_version": "synthesis-task-v1",
3
+ "task": {
4
+ "pair_id": "pyvul-3819b1a7530257524a75",
5
+ "dataset_id": "PyVul",
6
+ "dataset_item_id": "pyvul-3819b1a7530257524a75",
7
+ "project_id": "pyvul__xsuchy__templated-dictionary",
8
+ "language": "python",
9
+ "backend": "codeql"
10
+ },
11
+ "changed_python_files": [
12
+ "templated_dictionary/__init__.py"
13
+ ],
14
+ "patch_units": {
15
+ "before": [
16
+ "class:TemplatedDictionary",
17
+ "function:TemplatedDictionary.__init__",
18
+ "function:TemplatedDictionary.__render_string",
19
+ "module:<module>@5"
20
+ ],
21
+ "after": [
22
+ "class:TemplatedDictionary",
23
+ "function:TemplatedDictionary.__init__",
24
+ "function:TemplatedDictionary.__render_string",
25
+ "module:<module>@5"
26
+ ]
27
+ },
28
+ "runtime_assets": {
29
+ "before": {
30
+ "database": "assets/60090dd1e3d668fdc545d407347c4a6ba0250326e30297f90b2d463919aae8b3/database",
31
+ "cache_key": "60090dd1e3d668fdc545d407347c4a6ba0250326e30297f90b2d463919aae8b3",
32
+ "codeql_version": "2.26.4"
33
+ },
34
+ "after": {
35
+ "database": "assets/95b9d1bbebc8c5a413369012e35afae0fd0b6205fae69cab5ce281dfe2a80f3d/database",
36
+ "cache_key": "95b9d1bbebc8c5a413369012e35afae0fd0b6205fae69cab5ce281dfe2a80f3d",
37
+ "codeql_version": "2.26.4"
38
+ },
39
+ "refine": {
40
+ "database": "assets/9782c933de0fe5c1d90834d158773b8aa4076e68abc282bfc920352b51cc5b7b/database",
41
+ "cache_key": "9782c933de0fe5c1d90834d158773b8aa4076e68abc282bfc920352b51cc5b7b",
42
+ "codeql_version": "2.26.4"
43
+ }
44
+ },
45
+ "benchmark_contract": {
46
+ "agent_visible": true,
47
+ "reference_query_location": "references/pyvul-3819b1a7530257524a75/query/ (do not mount into agent)",
48
+ "evaluator_location": "evaluator/pyvul-3819b1a7530257524a75/ (do not mount into agent)"
49
+ }
50
+ }
tasks/codeql_python_benchmark51_v2/pyvul-3819b1a7530257524a75/task_prompt.md ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Python CodeQL detector synthesis
2
+
3
+ You are cc operating in `/work`. Starting only from the supplied patch,
4
+ before/after Python context, CodeQL references, and validation tools, synthesize a semantic CodeQL
5
+ detector for the vulnerability fixed by the patch. This is one fresh session. You may iterate inside
6
+ this session, but no later framework repair or resume will occur.
7
+
8
+ ## Inputs and owned outputs
9
+
10
+ - Read `patch.diff`, `python_patch.diff`, `pre_context.md`, and `post_context.md`.
11
+ - Read `references/codeql/convergence_protocol.md` and
12
+ `references/codeql/api_navigation.md` before experimenting. Read the remaining
13
+ `references/codeql/` files for the selected mechanism.
14
+ - Use `scripts/search_codeql_api.sh` to inspect the pinned official libraries when an API detail is
15
+ uncertain. Do not guess predicate names or build a large family of inspection queries.
16
+ - Complete the design contract in `state.json` and `scope_statement.md` before final validation.
17
+ - Replace `query/vulnerability.ql`; add only genuinely shared `.qll` helpers when useful. Keep the
18
+ fixed offline dependency in `query/qlpack.yml`.
19
+ - Preserve the exact `expected_query_id` from `config.json` as the query's sole `@id`. This
20
+ task-unique metadata must never be used in a query predicate.
21
+ - Use `scripts/compile_query.sh`, `scripts/run_before.sh`, and `scripts/run_after.sh`.
22
+ - Finish by writing `summary.json` with `status`, `query_path`, `query_kind`, `build_passed`,
23
+ `before_findings`, `after_findings`, `validation_completed`, and a concise `notes` field.
24
+
25
+ ## Required reasoning contract
26
+
27
+ Before coding, record this mapping in `state.json`:
28
+
29
+ ```text
30
+ vulnerable operation / trigger / patch safety condition
31
+ → CodeQL-observable evidence
32
+ → syntax, control-flow, local value-flow, global taint/value-flow, or interprocedural mechanism
33
+ → source, sink/report site, guard/barrier and query predicates
34
+ ```
35
+
36
+ Choose the lowest mechanism that can actually prove the condition. Guard-sensitive patches require
37
+ real path/control-flow semantics; provenance-sensitive patches require value flow. Do not replace
38
+ either with source-text matching or with the mere presence of patch-added syntax.
39
+
40
+ ## Mandatory convergence contract
41
+
42
+ The rollout has a 30-minute hard wall-clock ceiling and must be finalized by minute 27. Minutes
43
+ 27–30 are an emergency shutdown buffer, not exploration time. A sophisticated unfinished query is
44
+ a failure; an early compilable semantic candidate can be improved. Follow the checkpoints in
45
+ `references/codeql/convergence_protocol.md`:
46
+
47
+ 1. Record the mechanism contract, then replace the placeholder in `query/vulnerability.ql`
48
+ immediately. Do not wait until every CodeQL API detail is known.
49
+ 2. Use at most three distinct scratch `.ql` files. Prefer repeatedly editing one
50
+ `query/scratch.ql`. After two failed variants of one API assumption, inspect the exact bundled
51
+ definition with `scripts/search_codeql_api.sh` or simplify the mechanism.
52
+ 3. Obtain a compiling minimal main query before broadening it. Compile the main query after every
53
+ meaningful mechanism change.
54
+ 4. Move in order from compile → relevant before finding → after elimination → final contract. Do
55
+ not continue API exploration after the intended before/after differential is established.
56
+ 5. Run `scripts/check_progress.sh` at each checkpoint. It reports elapsed time, the minute-27
57
+ finalization deadline, and the minute-30 hard timeout. When it prints `finalize_now`, stop all
58
+ exploration, preserve the best compiling query, finish the contract files, and exit.
59
+
60
+ ## Semantic and generalization rules
61
+
62
+ - Report at the vulnerable call, operator, access, or sink.
63
+ - Do not use a patch-local path, line, commit hash, label, or local variable name as the primary
64
+ matching condition. Stable library/framework APIs or public project APIs are allowed only when
65
+ `scope_statement.md` explains why they define the intended vulnerability family.
66
+ - The safety condition introduced by the patch must be represented by the query.
67
+ - A lower after warning count is not enough: inspect SARIF and ensure at least one intended before
68
+ finding is in a patch-overlapping semantic unit and the corresponding finding disappears after.
69
+ - Avoid broad proxy queries that report an enclosing function or unrelated API merely because it
70
+ changed in the patch.
71
+
72
+ ## Final validation protocol
73
+
74
+ 1. Compile the final query.
75
+ 2. Run it on before and inspect `raw/before.sarif` for the intended report location.
76
+ 3. Run the identical query on after and inspect `raw/after.sarif`.
77
+ 4. Recheck query metadata, query kind/select signature, report locality, design-to-code consistency,
78
+ and absence of patch-local hardcoding.
79
+ 5. Update `state.json`, `scope_statement.md`, and write valid `summary.json`.
80
+
81
+ Do not modify the runtime databases, references, patch, context, or validation scripts except for
82
+ normal CodeQL-generated database caches produced by the provided run scripts.
tasks/codeql_python_benchmark51_v2/pyvul-394adf7b067d96b356ca/patch.diff ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ diff --git a/petl/io/xml.py b/petl/io/xml.py
2
+ index 983d9f6..b63287c 100644
3
+ --- a/petl/io/xml.py
4
+ +++ b/petl/io/xml.py
5
+ @@ -133,6 +133,9 @@ def fromxml(source, *args, **kwargs):
6
+ or list of paths can be provided, e.g.,
7
+ ``fromxml('example.html', './/tr', ('th', 'td'))``.
8
+
9
+ + Optionally a custom parser can be provided, e.g.,
10
+ + ``etl.fromxml('example1.xml', 'tr', 'td', parser=my_parser)``.
11
+ +
12
+ """
13
+
14
+ source = read_source_from_arg(source)
15
+ @@ -162,14 +165,15 @@ class XmlView(Table):
16
+ else:
17
+ assert False, 'bad parameters'
18
+ self.missing = kwargs.get('missing', None)
19
+ + self.user_parser = kwargs.get('parser', None)
20
+
21
+ def __iter__(self):
22
+ vmatch = self.vmatch
23
+ vdict = self.vdict
24
+
25
+ with self.source.open('rb') as xmlf:
26
+ -
27
+ - tree = etree.parse(xmlf)
28
+ + parser2 = _create_xml_parser(self.user_parser)
29
+ + tree = etree.parse(xmlf, parser=parser2)
30
+ if not hasattr(tree, 'iterfind'):
31
+ # Python 2.6 compatibility
32
+ tree.iterfind = tree.findall
33
+ @@ -219,6 +223,20 @@ class XmlView(Table):
34
+ for f in flds)
35
+
36
+
37
+ +def _create_xml_parser(user_parser):
38
+ + if user_parser is not None:
39
+ + return user_parser
40
+ + try:
41
+ + # Default lxml parser.
42
+ + # This will throw an error if parser is not set and lxml could not be imported
43
+ + # because Python's built XML parser doesn't like the `resolve_entities` kwarg.
44
+ + # return etree.XMLParser(resolve_entities=False)
45
+ + return etree.XMLParser(resolve_entities=False)
46
+ + except TypeError:
47
+ + # lxml not available
48
+ + return None
49
+ +
50
+ +
51
+ def element_text_getter(missing):
52
+ def _get(v):
53
+ if len(v) > 1:
tasks/codeql_python_benchmark51_v2/pyvul-394adf7b067d96b356ca/post_context.md ADDED
@@ -0,0 +1,314 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Patch-overlapping Python context after the fix
2
+
3
+ ## `petl/io/xml.py` — `function:fromxml` (lines 22-142)
4
+
5
+ ```python
6
+ def fromxml(source, *args, **kwargs):
7
+ """
8
+ Extract data from an XML file. E.g.::
9
+
10
+ >>> import petl as etl
11
+ >>> # setup a file to demonstrate with
12
+ ... d = '''<table>
13
+ ... <tr>
14
+ ... <td>foo</td><td>bar</td>
15
+ ... </tr>
16
+ ... <tr>
17
+ ... <td>a</td><td>1</td>
18
+ ... </tr>
19
+ ... <tr>
20
+ ... <td>b</td><td>2</td>
21
+ ... </tr>
22
+ ... <tr>
23
+ ... <td>c</td><td>2</td>
24
+ ... </tr>
25
+ ... </table>'''
26
+ >>> with open('example1.xml', 'w') as f:
27
+ ... f.write(d)
28
+ ...
29
+ 212
30
+ >>> table1 = etl.fromxml('example1.xml', 'tr', 'td')
31
+ >>> table1
32
+ +-----+-----+
33
+ | foo | bar |
34
+ +=====+=====+
35
+ | 'a' | '1' |
36
+ +-----+-----+
37
+ | 'b' | '2' |
38
+ +-----+-----+
39
+ | 'c' | '2' |
40
+ +-----+-----+
41
+
42
+
43
+ If the data values are stored in an attribute, provide the attribute
44
+ name as an extra positional argument::
45
+
46
+ >>> d = '''<table>
47
+ ... <tr>
48
+ ... <td v='foo'/><td v='bar'/>
49
+ ... </tr>
50
+ ... <tr>
51
+ ... <td v='a'/><td v='1'/>
52
+ ... </tr>
53
+ ... <tr>
54
+ ... <td v='b'/><td v='2'/>
55
+ ... </tr>
56
+ ... <tr>
57
+ ... <td v='c'/><td v='2'/>
58
+ ... </tr>
59
+ ... </table>'''
60
+ >>> with open('example2.xml', 'w') as f:
61
+ ... f.write(d)
62
+ ...
63
+ 220
64
+ >>> table2 = etl.fromxml('example2.xml', 'tr', 'td', 'v')
65
+ >>> table2
66
+ +-----+-----+
67
+ | foo | bar |
68
+ +=====+=====+
69
+ | 'a' | '1' |
70
+ +-----+-----+
71
+ | 'b' | '2' |
72
+ +-----+-----+
73
+ | 'c' | '2' |
74
+ +-----+-----+
75
+
76
+ Data values can also be extracted by providing a mapping of field
77
+ names to element paths::
78
+
79
+ >>> d = '''<table>
80
+ ... <row>
81
+ ... <foo>a</foo><baz><bar v='1'/><bar v='3'/></baz>
82
+ ... </row>
83
+ ... <row>
84
+ ... <foo>b</foo><baz><bar v='2'/></baz>
85
+ ... </row>
86
+ ... <row>
87
+ ... <foo>c</foo><baz><bar v='2'/></baz>
88
+ ... </row>
89
+ ... </table>'''
90
+ >>> with open('example3.xml', 'w') as f:
91
+ ... f.write(d)
92
+ ...
93
+ 223
94
+ >>> table3 = etl.fromxml('example3.xml', 'row',
95
+ ... {'foo': 'foo', 'bar': ('baz/bar', 'v')})
96
+ >>> table3
97
+ +------------+-----+
98
+ | bar | foo |
99
+ +============+=====+
100
+ | ('1', '3') | 'a' |
101
+ +------------+-----+
102
+ | '2' | 'b' |
103
+ +------------+-----+
104
+ | '2' | 'c' |
105
+ +------------+-----+
106
+
107
+ If `lxml <http://lxml.de/>`_ is installed, full XPath expressions can be
108
+ used.
109
+
110
+ Note that the implementation is currently **not** streaming, i.e.,
111
+ the whole document is loaded into memory.
112
+
113
+ If multiple elements match a given field, all values are reported as a
114
+ tuple.
115
+
116
+ If there is more than one element name used for row values, a tuple
117
+ or list of paths can be provided, e.g.,
118
+ ``fromxml('example.html', './/tr', ('th', 'td'))``.
119
+
120
+ Optionally a custom parser can be provided, e.g.,
121
+ ``etl.fromxml('example1.xml', 'tr', 'td', parser=my_parser)``.
122
+
123
+ """
124
+
125
+ source = read_source_from_arg(source)
126
+ return XmlView(source, *args, **kwargs)
127
+ ```
128
+
129
+ ## `petl/io/xml.py` — `class:XmlView` (lines 145-223)
130
+
131
+ ```python
132
+ class XmlView(Table):
133
+
134
+ def __init__(self, source, *args, **kwargs):
135
+ self.source = source
136
+ self.args = args
137
+ if len(args) == 2 and isinstance(args[1], (string_types, tuple, list)):
138
+ self.rmatch = args[0]
139
+ self.vmatch = args[1]
140
+ self.vdict = None
141
+ self.attr = None
142
+ elif len(args) == 2 and isinstance(args[1], dict):
143
+ self.rmatch = args[0]
144
+ self.vmatch = None
145
+ self.vdict = args[1]
146
+ self.attr = None
147
+ elif len(args) == 3:
148
+ self.rmatch = args[0]
149
+ self.vmatch = args[1]
150
+ self.vdict = None
151
+ self.attr = args[2]
152
+ else:
153
+ assert False, 'bad parameters'
154
+ self.missing = kwargs.get('missing', None)
155
+ self.user_parser = kwargs.get('parser', None)
156
+
157
+ def __iter__(self):
158
+ vmatch = self.vmatch
159
+ vdict = self.vdict
160
+
161
+ with self.source.open('rb') as xmlf:
162
+ parser2 = _create_xml_parser(self.user_parser)
163
+ tree = etree.parse(xmlf, parser=parser2)
164
+ if not hasattr(tree, 'iterfind'):
165
+ # Python 2.6 compatibility
166
+ tree.iterfind = tree.findall
167
+
168
+ if vmatch is not None:
169
+ # simple case, all value paths are the same
170
+ for rowelm in tree.iterfind(self.rmatch):
171
+ if self.attr is None:
172
+ getv = attrgetter('text')
173
+ else:
174
+ getv = lambda e: e.get(self.attr)
175
+ if isinstance(vmatch, string_types):
176
+ # match only one path
177
+ velms = rowelm.findall(vmatch)
178
+ else:
179
+ # match multiple paths
180
+ velms = itertools.chain(*[rowelm.findall(enm)
181
+ for enm in vmatch])
182
+ yield tuple(getv(velm)
183
+ for velm in velms)
184
+
185
+ else:
186
+ # difficult case, deal with different paths for each field
187
+
188
+ # determine output header
189
+ flds = tuple(sorted(map(text_type, vdict.keys())))
190
+ yield flds
191
+
192
+ # setup value getters
193
+ vmatches = dict()
194
+ vgetters = dict()
195
+ for f in flds:
196
+ vmatch = self.vdict[f]
197
+ if isinstance(vmatch, string_types):
198
+ # match element path
199
+ vmatches[f] = vmatch
200
+ vgetters[f] = element_text_getter(self.missing)
201
+ else:
202
+ # match element path and attribute name
203
+ vmatches[f] = vmatch[0]
204
+ attr = vmatch[1]
205
+ vgetters[f] = attribute_text_getter(attr, self.missing)
206
+
207
+ # determine data rows
208
+ for rowelm in tree.iterfind(self.rmatch):
209
+ yield tuple(vgetters[f](rowelm.findall(vmatches[f]))
210
+ for f in flds)
211
+ ```
212
+
213
+ ## `petl/io/xml.py` — `function:XmlView.__init__` (lines 147-168)
214
+
215
+ ```python
216
+ def __init__(self, source, *args, **kwargs):
217
+ self.source = source
218
+ self.args = args
219
+ if len(args) == 2 and isinstance(args[1], (string_types, tuple, list)):
220
+ self.rmatch = args[0]
221
+ self.vmatch = args[1]
222
+ self.vdict = None
223
+ self.attr = None
224
+ elif len(args) == 2 and isinstance(args[1], dict):
225
+ self.rmatch = args[0]
226
+ self.vmatch = None
227
+ self.vdict = args[1]
228
+ self.attr = None
229
+ elif len(args) == 3:
230
+ self.rmatch = args[0]
231
+ self.vmatch = args[1]
232
+ self.vdict = None
233
+ self.attr = args[2]
234
+ else:
235
+ assert False, 'bad parameters'
236
+ self.missing = kwargs.get('missing', None)
237
+ self.user_parser = kwargs.get('parser', None)
238
+ ```
239
+
240
+ ## `petl/io/xml.py` — `function:XmlView.__iter__` (lines 170-223)
241
+
242
+ ```python
243
+ def __iter__(self):
244
+ vmatch = self.vmatch
245
+ vdict = self.vdict
246
+
247
+ with self.source.open('rb') as xmlf:
248
+ parser2 = _create_xml_parser(self.user_parser)
249
+ tree = etree.parse(xmlf, parser=parser2)
250
+ if not hasattr(tree, 'iterfind'):
251
+ # Python 2.6 compatibility
252
+ tree.iterfind = tree.findall
253
+
254
+ if vmatch is not None:
255
+ # simple case, all value paths are the same
256
+ for rowelm in tree.iterfind(self.rmatch):
257
+ if self.attr is None:
258
+ getv = attrgetter('text')
259
+ else:
260
+ getv = lambda e: e.get(self.attr)
261
+ if isinstance(vmatch, string_types):
262
+ # match only one path
263
+ velms = rowelm.findall(vmatch)
264
+ else:
265
+ # match multiple paths
266
+ velms = itertools.chain(*[rowelm.findall(enm)
267
+ for enm in vmatch])
268
+ yield tuple(getv(velm)
269
+ for velm in velms)
270
+
271
+ else:
272
+ # difficult case, deal with different paths for each field
273
+
274
+ # determine output header
275
+ flds = tuple(sorted(map(text_type, vdict.keys())))
276
+ yield flds
277
+
278
+ # setup value getters
279
+ vmatches = dict()
280
+ vgetters = dict()
281
+ for f in flds:
282
+ vmatch = self.vdict[f]
283
+ if isinstance(vmatch, string_types):
284
+ # match element path
285
+ vmatches[f] = vmatch
286
+ vgetters[f] = element_text_getter(self.missing)
287
+ else:
288
+ # match element path and attribute name
289
+ vmatches[f] = vmatch[0]
290
+ attr = vmatch[1]
291
+ vgetters[f] = attribute_text_getter(attr, self.missing)
292
+
293
+ # determine data rows
294
+ for rowelm in tree.iterfind(self.rmatch):
295
+ yield tuple(vgetters[f](rowelm.findall(vmatches[f]))
296
+ for f in flds)
297
+ ```
298
+
299
+ ## `petl/io/xml.py` — `function:_create_xml_parser` (lines 226-237)
300
+
301
+ ```python
302
+ def _create_xml_parser(user_parser):
303
+ if user_parser is not None:
304
+ return user_parser
305
+ try:
306
+ # Default lxml parser.
307
+ # This will throw an error if parser is not set and lxml could not be imported
308
+ # because Python's built XML parser doesn't like the `resolve_entities` kwarg.
309
+ # return etree.XMLParser(resolve_entities=False)
310
+ return etree.XMLParser(resolve_entities=False)
311
+ except TypeError:
312
+ # lxml not available
313
+ return None
314
+ ```
tasks/codeql_python_benchmark51_v2/pyvul-394adf7b067d96b356ca/pre_context.md ADDED
@@ -0,0 +1,280 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Patch-overlapping Python context before the fix
2
+
3
+ ## `petl/io/xml.py` — `function:fromxml` (lines 22-139)
4
+
5
+ ```python
6
+ def fromxml(source, *args, **kwargs):
7
+ """
8
+ Extract data from an XML file. E.g.::
9
+
10
+ >>> import petl as etl
11
+ >>> # setup a file to demonstrate with
12
+ ... d = '''<table>
13
+ ... <tr>
14
+ ... <td>foo</td><td>bar</td>
15
+ ... </tr>
16
+ ... <tr>
17
+ ... <td>a</td><td>1</td>
18
+ ... </tr>
19
+ ... <tr>
20
+ ... <td>b</td><td>2</td>
21
+ ... </tr>
22
+ ... <tr>
23
+ ... <td>c</td><td>2</td>
24
+ ... </tr>
25
+ ... </table>'''
26
+ >>> with open('example1.xml', 'w') as f:
27
+ ... f.write(d)
28
+ ...
29
+ 212
30
+ >>> table1 = etl.fromxml('example1.xml', 'tr', 'td')
31
+ >>> table1
32
+ +-----+-----+
33
+ | foo | bar |
34
+ +=====+=====+
35
+ | 'a' | '1' |
36
+ +-----+-----+
37
+ | 'b' | '2' |
38
+ +-----+-----+
39
+ | 'c' | '2' |
40
+ +-----+-----+
41
+
42
+
43
+ If the data values are stored in an attribute, provide the attribute
44
+ name as an extra positional argument::
45
+
46
+ >>> d = '''<table>
47
+ ... <tr>
48
+ ... <td v='foo'/><td v='bar'/>
49
+ ... </tr>
50
+ ... <tr>
51
+ ... <td v='a'/><td v='1'/>
52
+ ... </tr>
53
+ ... <tr>
54
+ ... <td v='b'/><td v='2'/>
55
+ ... </tr>
56
+ ... <tr>
57
+ ... <td v='c'/><td v='2'/>
58
+ ... </tr>
59
+ ... </table>'''
60
+ >>> with open('example2.xml', 'w') as f:
61
+ ... f.write(d)
62
+ ...
63
+ 220
64
+ >>> table2 = etl.fromxml('example2.xml', 'tr', 'td', 'v')
65
+ >>> table2
66
+ +-----+-----+
67
+ | foo | bar |
68
+ +=====+=====+
69
+ | 'a' | '1' |
70
+ +-----+-----+
71
+ | 'b' | '2' |
72
+ +-----+-----+
73
+ | 'c' | '2' |
74
+ +-----+-----+
75
+
76
+ Data values can also be extracted by providing a mapping of field
77
+ names to element paths::
78
+
79
+ >>> d = '''<table>
80
+ ... <row>
81
+ ... <foo>a</foo><baz><bar v='1'/><bar v='3'/></baz>
82
+ ... </row>
83
+ ... <row>
84
+ ... <foo>b</foo><baz><bar v='2'/></baz>
85
+ ... </row>
86
+ ... <row>
87
+ ... <foo>c</foo><baz><bar v='2'/></baz>
88
+ ... </row>
89
+ ... </table>'''
90
+ >>> with open('example3.xml', 'w') as f:
91
+ ... f.write(d)
92
+ ...
93
+ 223
94
+ >>> table3 = etl.fromxml('example3.xml', 'row',
95
+ ... {'foo': 'foo', 'bar': ('baz/bar', 'v')})
96
+ >>> table3
97
+ +------------+-----+
98
+ | bar | foo |
99
+ +============+=====+
100
+ | ('1', '3') | 'a' |
101
+ +------------+-----+
102
+ | '2' | 'b' |
103
+ +------------+-----+
104
+ | '2' | 'c' |
105
+ +------------+-----+
106
+
107
+ If `lxml <http://lxml.de/>`_ is installed, full XPath expressions can be
108
+ used.
109
+
110
+ Note that the implementation is currently **not** streaming, i.e.,
111
+ the whole document is loaded into memory.
112
+
113
+ If multiple elements match a given field, all values are reported as a
114
+ tuple.
115
+
116
+ If there is more than one element name used for row values, a tuple
117
+ or list of paths can be provided, e.g.,
118
+ ``fromxml('example.html', './/tr', ('th', 'td'))``.
119
+
120
+ """
121
+
122
+ source = read_source_from_arg(source)
123
+ return XmlView(source, *args, **kwargs)
124
+ ```
125
+
126
+ ## `petl/io/xml.py` — `class:XmlView` (lines 142-219)
127
+
128
+ ```python
129
+ class XmlView(Table):
130
+
131
+ def __init__(self, source, *args, **kwargs):
132
+ self.source = source
133
+ self.args = args
134
+ if len(args) == 2 and isinstance(args[1], (string_types, tuple, list)):
135
+ self.rmatch = args[0]
136
+ self.vmatch = args[1]
137
+ self.vdict = None
138
+ self.attr = None
139
+ elif len(args) == 2 and isinstance(args[1], dict):
140
+ self.rmatch = args[0]
141
+ self.vmatch = None
142
+ self.vdict = args[1]
143
+ self.attr = None
144
+ elif len(args) == 3:
145
+ self.rmatch = args[0]
146
+ self.vmatch = args[1]
147
+ self.vdict = None
148
+ self.attr = args[2]
149
+ else:
150
+ assert False, 'bad parameters'
151
+ self.missing = kwargs.get('missing', None)
152
+
153
+ def __iter__(self):
154
+ vmatch = self.vmatch
155
+ vdict = self.vdict
156
+
157
+ with self.source.open('rb') as xmlf:
158
+
159
+ tree = etree.parse(xmlf)
160
+ if not hasattr(tree, 'iterfind'):
161
+ # Python 2.6 compatibility
162
+ tree.iterfind = tree.findall
163
+
164
+ if vmatch is not None:
165
+ # simple case, all value paths are the same
166
+ for rowelm in tree.iterfind(self.rmatch):
167
+ if self.attr is None:
168
+ getv = attrgetter('text')
169
+ else:
170
+ getv = lambda e: e.get(self.attr)
171
+ if isinstance(vmatch, string_types):
172
+ # match only one path
173
+ velms = rowelm.findall(vmatch)
174
+ else:
175
+ # match multiple paths
176
+ velms = itertools.chain(*[rowelm.findall(enm)
177
+ for enm in vmatch])
178
+ yield tuple(getv(velm)
179
+ for velm in velms)
180
+
181
+ else:
182
+ # difficult case, deal with different paths for each field
183
+
184
+ # determine output header
185
+ flds = tuple(sorted(map(text_type, vdict.keys())))
186
+ yield flds
187
+
188
+ # setup value getters
189
+ vmatches = dict()
190
+ vgetters = dict()
191
+ for f in flds:
192
+ vmatch = self.vdict[f]
193
+ if isinstance(vmatch, string_types):
194
+ # match element path
195
+ vmatches[f] = vmatch
196
+ vgetters[f] = element_text_getter(self.missing)
197
+ else:
198
+ # match element path and attribute name
199
+ vmatches[f] = vmatch[0]
200
+ attr = vmatch[1]
201
+ vgetters[f] = attribute_text_getter(attr, self.missing)
202
+
203
+ # determine data rows
204
+ for rowelm in tree.iterfind(self.rmatch):
205
+ yield tuple(vgetters[f](rowelm.findall(vmatches[f]))
206
+ for f in flds)
207
+ ```
208
+
209
+ ## `petl/io/xml.py` — `function:XmlView.__iter__` (lines 166-219)
210
+
211
+ ```python
212
+ def __iter__(self):
213
+ vmatch = self.vmatch
214
+ vdict = self.vdict
215
+
216
+ with self.source.open('rb') as xmlf:
217
+
218
+ tree = etree.parse(xmlf)
219
+ if not hasattr(tree, 'iterfind'):
220
+ # Python 2.6 compatibility
221
+ tree.iterfind = tree.findall
222
+
223
+ if vmatch is not None:
224
+ # simple case, all value paths are the same
225
+ for rowelm in tree.iterfind(self.rmatch):
226
+ if self.attr is None:
227
+ getv = attrgetter('text')
228
+ else:
229
+ getv = lambda e: e.get(self.attr)
230
+ if isinstance(vmatch, string_types):
231
+ # match only one path
232
+ velms = rowelm.findall(vmatch)
233
+ else:
234
+ # match multiple paths
235
+ velms = itertools.chain(*[rowelm.findall(enm)
236
+ for enm in vmatch])
237
+ yield tuple(getv(velm)
238
+ for velm in velms)
239
+
240
+ else:
241
+ # difficult case, deal with different paths for each field
242
+
243
+ # determine output header
244
+ flds = tuple(sorted(map(text_type, vdict.keys())))
245
+ yield flds
246
+
247
+ # setup value getters
248
+ vmatches = dict()
249
+ vgetters = dict()
250
+ for f in flds:
251
+ vmatch = self.vdict[f]
252
+ if isinstance(vmatch, string_types):
253
+ # match element path
254
+ vmatches[f] = vmatch
255
+ vgetters[f] = element_text_getter(self.missing)
256
+ else:
257
+ # match element path and attribute name
258
+ vmatches[f] = vmatch[0]
259
+ attr = vmatch[1]
260
+ vgetters[f] = attribute_text_getter(attr, self.missing)
261
+
262
+ # determine data rows
263
+ for rowelm in tree.iterfind(self.rmatch):
264
+ yield tuple(vgetters[f](rowelm.findall(vmatches[f]))
265
+ for f in flds)
266
+ ```
267
+
268
+ ## `petl/io/xml.py` — `function:element_text_getter` (lines 222-230)
269
+
270
+ ```python
271
+ def element_text_getter(missing):
272
+ def _get(v):
273
+ if len(v) > 1:
274
+ return tuple(e.text for e in v)
275
+ elif len(v) == 1:
276
+ return v[0].text
277
+ else:
278
+ return missing
279
+ return _get
280
+ ```
tasks/codeql_python_benchmark51_v2/pyvul-394adf7b067d96b356ca/task.json ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "schema_version": "synthesis-task-v1",
3
+ "task": {
4
+ "pair_id": "pyvul-394adf7b067d96b356ca",
5
+ "dataset_id": "PyVul",
6
+ "dataset_item_id": "pyvul-394adf7b067d96b356ca",
7
+ "project_id": "pyvul__petl-developers__petl",
8
+ "language": "python",
9
+ "backend": "codeql"
10
+ },
11
+ "changed_python_files": [
12
+ "petl/io/xml.py"
13
+ ],
14
+ "patch_units": {
15
+ "before": [
16
+ "function:fromxml",
17
+ "class:XmlView",
18
+ "function:XmlView.__iter__",
19
+ "function:element_text_getter"
20
+ ],
21
+ "after": [
22
+ "function:fromxml",
23
+ "class:XmlView",
24
+ "function:XmlView.__init__",
25
+ "function:XmlView.__iter__",
26
+ "function:_create_xml_parser"
27
+ ]
28
+ },
29
+ "runtime_assets": {
30
+ "before": {
31
+ "database": "assets/fcb47a17185a332c24eecb3d2d4506cc6dd1ab2f313ab3bcf087aed38ddb4ecb/database",
32
+ "cache_key": "fcb47a17185a332c24eecb3d2d4506cc6dd1ab2f313ab3bcf087aed38ddb4ecb",
33
+ "codeql_version": "2.26.4"
34
+ },
35
+ "after": {
36
+ "database": "assets/c269b96e8d78a0ff93ceeec45f19adcb8bd0807c764fc5ff1ddf3e141ec1e71a/database",
37
+ "cache_key": "c269b96e8d78a0ff93ceeec45f19adcb8bd0807c764fc5ff1ddf3e141ec1e71a",
38
+ "codeql_version": "2.26.4"
39
+ },
40
+ "refine": {
41
+ "database": "assets/83698b843f83dfc980db192656c5e8ad2835066c6e096f242e89cf727ededf65/database",
42
+ "cache_key": "83698b843f83dfc980db192656c5e8ad2835066c6e096f242e89cf727ededf65",
43
+ "codeql_version": "2.26.4"
44
+ }
45
+ },
46
+ "benchmark_contract": {
47
+ "agent_visible": true,
48
+ "reference_query_location": "references/pyvul-394adf7b067d96b356ca/query/ (do not mount into agent)",
49
+ "evaluator_location": "evaluator/pyvul-394adf7b067d96b356ca/ (do not mount into agent)"
50
+ }
51
+ }
tasks/codeql_python_benchmark51_v2/pyvul-394adf7b067d96b356ca/task_prompt.md ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Python CodeQL detector synthesis
2
+
3
+ You are cc operating in `/work`. Starting only from the supplied patch,
4
+ before/after Python context, CodeQL references, and validation tools, synthesize a semantic CodeQL
5
+ detector for the vulnerability fixed by the patch. This is one fresh session. You may iterate inside
6
+ this session, but no later framework repair or resume will occur.
7
+
8
+ ## Inputs and owned outputs
9
+
10
+ - Read `patch.diff`, `python_patch.diff`, `pre_context.md`, and `post_context.md`.
11
+ - Read `references/codeql/convergence_protocol.md` and
12
+ `references/codeql/api_navigation.md` before experimenting. Read the remaining
13
+ `references/codeql/` files for the selected mechanism.
14
+ - Use `scripts/search_codeql_api.sh` to inspect the pinned official libraries when an API detail is
15
+ uncertain. Do not guess predicate names or build a large family of inspection queries.
16
+ - Complete the design contract in `state.json` and `scope_statement.md` before final validation.
17
+ - Replace `query/vulnerability.ql`; add only genuinely shared `.qll` helpers when useful. Keep the
18
+ fixed offline dependency in `query/qlpack.yml`.
19
+ - Preserve the exact `expected_query_id` from `config.json` as the query's sole `@id`. This
20
+ task-unique metadata must never be used in a query predicate.
21
+ - Use `scripts/compile_query.sh`, `scripts/run_before.sh`, and `scripts/run_after.sh`.
22
+ - Finish by writing `summary.json` with `status`, `query_path`, `query_kind`, `build_passed`,
23
+ `before_findings`, `after_findings`, `validation_completed`, and a concise `notes` field.
24
+
25
+ ## Required reasoning contract
26
+
27
+ Before coding, record this mapping in `state.json`:
28
+
29
+ ```text
30
+ vulnerable operation / trigger / patch safety condition
31
+ → CodeQL-observable evidence
32
+ → syntax, control-flow, local value-flow, global taint/value-flow, or interprocedural mechanism
33
+ → source, sink/report site, guard/barrier and query predicates
34
+ ```
35
+
36
+ Choose the lowest mechanism that can actually prove the condition. Guard-sensitive patches require
37
+ real path/control-flow semantics; provenance-sensitive patches require value flow. Do not replace
38
+ either with source-text matching or with the mere presence of patch-added syntax.
39
+
40
+ ## Mandatory convergence contract
41
+
42
+ The rollout has a 30-minute hard wall-clock ceiling and must be finalized by minute 27. Minutes
43
+ 27–30 are an emergency shutdown buffer, not exploration time. A sophisticated unfinished query is
44
+ a failure; an early compilable semantic candidate can be improved. Follow the checkpoints in
45
+ `references/codeql/convergence_protocol.md`:
46
+
47
+ 1. Record the mechanism contract, then replace the placeholder in `query/vulnerability.ql`
48
+ immediately. Do not wait until every CodeQL API detail is known.
49
+ 2. Use at most three distinct scratch `.ql` files. Prefer repeatedly editing one
50
+ `query/scratch.ql`. After two failed variants of one API assumption, inspect the exact bundled
51
+ definition with `scripts/search_codeql_api.sh` or simplify the mechanism.
52
+ 3. Obtain a compiling minimal main query before broadening it. Compile the main query after every
53
+ meaningful mechanism change.
54
+ 4. Move in order from compile → relevant before finding → after elimination → final contract. Do
55
+ not continue API exploration after the intended before/after differential is established.
56
+ 5. Run `scripts/check_progress.sh` at each checkpoint. It reports elapsed time, the minute-27
57
+ finalization deadline, and the minute-30 hard timeout. When it prints `finalize_now`, stop all
58
+ exploration, preserve the best compiling query, finish the contract files, and exit.
59
+
60
+ ## Semantic and generalization rules
61
+
62
+ - Report at the vulnerable call, operator, access, or sink.
63
+ - Do not use a patch-local path, line, commit hash, label, or local variable name as the primary
64
+ matching condition. Stable library/framework APIs or public project APIs are allowed only when
65
+ `scope_statement.md` explains why they define the intended vulnerability family.
66
+ - The safety condition introduced by the patch must be represented by the query.
67
+ - A lower after warning count is not enough: inspect SARIF and ensure at least one intended before
68
+ finding is in a patch-overlapping semantic unit and the corresponding finding disappears after.
69
+ - Avoid broad proxy queries that report an enclosing function or unrelated API merely because it
70
+ changed in the patch.
71
+
72
+ ## Final validation protocol
73
+
74
+ 1. Compile the final query.
75
+ 2. Run it on before and inspect `raw/before.sarif` for the intended report location.
76
+ 3. Run the identical query on after and inspect `raw/after.sarif`.
77
+ 4. Recheck query metadata, query kind/select signature, report locality, design-to-code consistency,
78
+ and absence of patch-local hardcoding.
79
+ 5. Update `state.json`, `scope_statement.md`, and write valid `summary.json`.
80
+
81
+ Do not modify the runtime databases, references, patch, context, or validation scripts except for
82
+ normal CodeQL-generated database caches produced by the provided run scripts.
tasks/codeql_python_benchmark51_v2/pyvul-3994e3622b21c396ef8a/patch.diff ADDED
@@ -0,0 +1,912 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ diff --git a/poetry.lock b/poetry.lock
2
+ index a7197f5f28b..78b0adedf13 100644
3
+ --- a/poetry.lock
4
+ +++ b/poetry.lock
5
+ @@ -242,14 +242,14 @@ numpy = ">=1.15.0"
6
+
7
+ [[package]]
8
+ name = "boto3"
9
+ -version = "1.18.52"
10
+ +version = "1.18.58"
11
+ description = "The AWS SDK for Python"
12
+ category = "main"
13
+ optional = false
14
+ python-versions = ">= 3.6"
15
+
16
+ [package.dependencies]
17
+ -botocore = ">=1.21.52,<1.22.0"
18
+ +botocore = ">=1.21.58,<1.22.0"
19
+ jmespath = ">=0.7.1,<1.0.0"
20
+ s3transfer = ">=0.5.0,<0.6.0"
21
+
22
+ @@ -258,7 +258,7 @@ crt = ["botocore[crt] (>=1.21.0,<2.0a0)"]
23
+
24
+ [[package]]
25
+ name = "botocore"
26
+ -version = "1.21.52"
27
+ +version = "1.21.58"
28
+ description = "Low-level, data-driven core of boto 3."
29
+ category = "main"
30
+ optional = false
31
+ @@ -302,7 +302,7 @@ zipp = {version = ">=0.5", markers = "python_version < \"3.8\""}
32
+
33
+ [[package]]
34
+ name = "certifi"
35
+ -version = "2021.5.30"
36
+ +version = "2021.10.8"
37
+ description = "Python package for providing Mozilla's CA Bundle."
38
+ category = "main"
39
+ optional = false
40
+ @@ -440,7 +440,7 @@ yaml = ["PyYAML (>=3.10)"]
41
+
42
+ [[package]]
43
+ name = "cryptography"
44
+ -version = "3.4.8"
45
+ +version = "35.0.0"
46
+ description = "cryptography is a package which provides cryptographic recipes and primitives to Python developers."
47
+ category = "main"
48
+ optional = false
49
+ @@ -453,9 +453,9 @@ cffi = ">=1.12"
50
+ docs = ["sphinx (>=1.6.5,!=1.8.0,!=3.1.0,!=3.1.1)", "sphinx-rtd-theme"]
51
+ docstest = ["doc8", "pyenchant (>=1.6.11)", "twine (>=1.12.0)", "sphinxcontrib-spelling (>=4.0.1)"]
52
+ pep8test = ["black", "flake8", "flake8-import-order", "pep8-naming"]
53
+ -sdist = ["setuptools-rust (>=0.11.4)"]
54
+ +sdist = ["setuptools_rust (>=0.11.4)"]
55
+ ssh = ["bcrypt (>=3.1.5)"]
56
+ -test = ["pytest (>=6.0)", "pytest-cov", "pytest-subtests", "pytest-xdist", "pretend", "iso8601", "pytz", "hypothesis (>=1.11.4,!=3.79.2)"]
57
+ +test = ["pytest (>=6.2.0)", "pytest-cov", "pytest-subtests", "pytest-xdist", "pretend", "iso8601", "pytz", "hypothesis (>=1.11.4,!=3.79.2)"]
58
+
59
+ [[package]]
60
+ name = "cycler"
61
+ @@ -603,15 +603,15 @@ requests = ">=2.0"
62
+
63
+ [[package]]
64
+ name = "filelock"
65
+ -version = "3.2.0"
66
+ +version = "3.3.0"
67
+ description = "A platform independent file lock."
68
+ category = "main"
69
+ optional = true
70
+ -python-versions = "!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*,!=3.4.*,>=2.7"
71
+ +python-versions = ">=3.6"
72
+
73
+ [package.extras]
74
+ docs = ["furo (>=2021.8.17b43)", "sphinx (>=4.1)", "sphinx-autodoc-typehints (>=1.12)"]
75
+ -testing = ["coverage (>=4)", "pytest (>=4)", "pytest-cov", "pytest-timeout (>=1.4.2)"]
76
+ +testing = ["covdefaults (>=1.2.0)", "coverage (>=4)", "pytest (>=4)", "pytest-cov", "pytest-timeout (>=1.4.2)"]
77
+
78
+ [[package]]
79
+ name = "flake8"
80
+ @@ -717,7 +717,7 @@ typing-extensions = {version = ">=3.7.4.3", markers = "python_version < \"3.10\"
81
+
82
+ [[package]]
83
+ name = "google-api-core"
84
+ -version = "2.0.1"
85
+ +version = "2.1.0"
86
+ description = "Google API client core library"
87
+ category = "dev"
88
+ optional = false
89
+ @@ -770,7 +770,7 @@ tool = ["click (>=6.0.0)"]
90
+
91
+ [[package]]
92
+ name = "google-cloud-core"
93
+ -version = "2.0.0"
94
+ +version = "2.1.0"
95
+ description = "Google Cloud API client core library"
96
+ category = "dev"
97
+ optional = false
98
+ @@ -802,7 +802,7 @@ six = "*"
99
+
100
+ [[package]]
101
+ name = "google-crc32c"
102
+ -version = "1.2.0"
103
+ +version = "1.3.0"
104
+ description = "A python wrapper of the C library 'Google CRC32C'"
105
+ category = "dev"
106
+ optional = false
107
+ @@ -930,11 +930,11 @@ python-versions = ">=3.6"
108
+
109
+ [[package]]
110
+ name = "httplib2"
111
+ -version = "0.19.1"
112
+ +version = "0.20.1"
113
+ description = "A comprehensive HTTP client library."
114
+ category = "main"
115
+ optional = false
116
+ -python-versions = "*"
117
+ +python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*"
118
+
119
+ [package.dependencies]
120
+ pyparsing = ">=2.4.2,<3"
121
+ @@ -1087,7 +1087,7 @@ python-versions = "*"
122
+
123
+ [[package]]
124
+ name = "jinja2"
125
+ -version = "3.0.1"
126
+ +version = "3.0.2"
127
+ description = "A very fast and expressive template engine."
128
+ category = "main"
129
+ optional = false
130
+ @@ -1706,11 +1706,11 @@ wcwidth = "*"
131
+
132
+ [[package]]
133
+ name = "protobuf"
134
+ -version = "3.18.0"
135
+ +version = "3.18.1"
136
+ description = "Protocol Buffers"
137
+ category = "main"
138
+ optional = false
139
+ -python-versions = "*"
140
+ +python-versions = ">=3.5"
141
+
142
+ [[package]]
143
+ name = "psutil"
144
+ @@ -1849,18 +1849,18 @@ python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*"
145
+
146
+ [[package]]
147
+ name = "pyjwt"
148
+ -version = "2.1.0"
149
+ +version = "2.2.0"
150
+ description = "JSON Web Token implementation in Python"
151
+ category = "main"
152
+ optional = false
153
+ python-versions = ">=3.6"
154
+
155
+ [package.dependencies]
156
+ -cryptography = {version = ">=3.3.1,<4.0.0", optional = true, markers = "extra == \"crypto\""}
157
+ +cryptography = {version = ">=3.3.1", optional = true, markers = "extra == \"crypto\""}
158
+
159
+ [package.extras]
160
+ -crypto = ["cryptography (>=3.3.1,<4.0.0)"]
161
+ -dev = ["sphinx", "sphinx-rtd-theme", "zope.interface", "cryptography (>=3.3.1,<4.0.0)", "pytest (>=6.0.0,<7.0.0)", "coverage[toml] (==5.0.4)", "mypy", "pre-commit"]
162
+ +crypto = ["cryptography (>=3.3.1)"]
163
+ +dev = ["sphinx", "sphinx-rtd-theme", "zope.interface", "cryptography (>=3.3.1)", "pytest (>=6.0.0,<7.0.0)", "coverage[toml] (==5.0.4)", "mypy", "pre-commit"]
164
+ docs = ["sphinx", "sphinx-rtd-theme", "zope.interface"]
165
+ tests = ["pytest (>=6.0.0,<7.0.0)", "coverage[toml] (==5.0.4)"]
166
+
167
+ @@ -2100,7 +2100,7 @@ client = ["requests (>=2.21.0)", "websocket-client (>=0.54.0)"]
168
+
169
+ [[package]]
170
+ name = "pytz"
171
+ -version = "2021.1"
172
+ +version = "2021.3"
173
+ description = "World timezone definitions, modern and historical"
174
+ category = "main"
175
+ optional = false
176
+ @@ -2656,6 +2656,14 @@ python-versions = "*"
177
+ [package.extras]
178
+ widechars = ["wcwidth"]
179
+
180
+ +[[package]]
181
+ +name = "tarsafe"
182
+ +version = "0.0.3"
183
+ +description = "A safe subclass of the TarFile class for interacting with tar files. Can be used as a direct drop-in replacement for safe usage of extractall()"
184
+ +category = "main"
185
+ +optional = false
186
+ +python-versions = ">=3.6"
187
+ +
188
+ [[package]]
189
+ name = "tensorboard"
190
+ version = "2.6.0"
191
+ @@ -2854,7 +2862,7 @@ torch = ["torch (>=1.5.0)"]
192
+
193
+ [[package]]
194
+ name = "threadpoolctl"
195
+ -version = "2.2.0"
196
+ +version = "3.0.0"
197
+ description = "threadpoolctl"
198
+ category = "main"
199
+ optional = false
200
+ @@ -2970,7 +2978,7 @@ python-versions = "*"
201
+
202
+ [[package]]
203
+ name = "typeguard"
204
+ -version = "2.12.1"
205
+ +version = "2.13.0"
206
+ description = "Run-time type checker for Python"
207
+ category = "main"
208
+ optional = false
209
+ @@ -3066,11 +3074,11 @@ python-versions = ">=3.6"
210
+
211
+ [[package]]
212
+ name = "uritemplate"
213
+ -version = "3.0.1"
214
+ -description = "URI templates"
215
+ +version = "4.0.0"
216
+ +description = "Implementation of RFC 6570 URI Templates"
217
+ category = "main"
218
+ optional = true
219
+ -python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*"
220
+ +python-versions = ">=3.6"
221
+
222
+ [[package]]
223
+ name = "urllib3"
224
+ @@ -3144,7 +3152,7 @@ python-versions = ">=3.6"
225
+
226
+ [[package]]
227
+ name = "werkzeug"
228
+ -version = "2.0.1"
229
+ +version = "2.0.2"
230
+ description = "The comprehensive WSGI web application library."
231
+ category = "main"
232
+ optional = false
233
+ @@ -3174,7 +3182,7 @@ python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*"
234
+
235
+ [[package]]
236
+ name = "yarl"
237
+ -version = "1.6.3"
238
+ +version = "1.7.0"
239
+ description = "Yet another URL library"
240
+ category = "main"
241
+ optional = false
242
+ @@ -3207,7 +3215,7 @@ transformers = ["transformers"]
243
+ [metadata]
244
+ lock-version = "1.1"
245
+ python-versions = ">=3.6,<3.9"
246
+ -content-hash = "209f285fcf47fff7c9fbcec651ed96156f03eb286f49b23c8047579fdd5adf8a"
247
+ +content-hash = "2fc451ce1e7553b33a12596867363114792c8ab2cde3148b60f57126e6cc635c"
248
+
249
+ [metadata.files]
250
+ absl-py = [
251
+ @@ -3333,12 +3341,12 @@ blis = [
252
+ {file = "blis-0.7.4.tar.gz", hash = "sha256:7daa615a97d4f28db0f332b710bfe1900b15d0c25841c6d727965e4fd91e09cf"},
253
+ ]
254
+ boto3 = [
255
+ - {file = "boto3-1.18.52-py3-none-any.whl", hash = "sha256:27824d3767c5213f0006f71e552b912bc4659241b77ca8b0be0b813cf0518a9e"},
256
+ - {file = "boto3-1.18.52.tar.gz", hash = "sha256:5b585a279478bd6df4b07db7d6150f413ba6add1f38e68aaa533d3337efd0b22"},
257
+ + {file = "boto3-1.18.58-py3-none-any.whl", hash = "sha256:7309552da6ef9e610f8a9712c8abe29a8d3d45b514188cc3efad47bd1774bf77"},
258
+ + {file = "boto3-1.18.58.tar.gz", hash = "sha256:f680dee9c670d42ab4a6da5539ca3691d1ccbbcbf041e7021025029776864156"},
259
+ ]
260
+ botocore = [
261
+ - {file = "botocore-1.21.52-py3-none-any.whl", hash = "sha256:e8797c0933c660e130cf2f51667f5003950d7e592f4c3944e8f04f201493d17a"},
262
+ - {file = "botocore-1.21.52.tar.gz", hash = "sha256:04c071aec4f1981b38e3be760838b976337fd6ebd95a31ceeca9f9e4b4733c1f"},
263
+ + {file = "botocore-1.21.58-py3-none-any.whl", hash = "sha256:9d84a97015c0565a81c0b6d55e60af5ab1a2da28039ad93976388014a14186da"},
264
+ + {file = "botocore-1.21.58.tar.gz", hash = "sha256:87e881569c32b218a1b82ecb607a4dddb4dca3b80a5d1016571b99b51cef3158"},
265
+ ]
266
+ cached-property = [
267
+ {file = "cached-property-1.5.2.tar.gz", hash = "sha256:9fa5755838eecbb2d234c3aa390bd80fbd3ac6b6869109bfc1b499f7bd89a130"},
268
+ @@ -3353,8 +3361,8 @@ catalogue = [
269
+ {file = "catalogue-2.0.6.tar.gz", hash = "sha256:336a35603f447167042ef504114d6befa46688f03f4c14dabdc633a44587b245"},
270
+ ]
271
+ certifi = [
272
+ - {file = "certifi-2021.5.30-py2.py3-none-any.whl", hash = "sha256:50b1e4f8446b06f41be7dd6338db18e0990601dce795c2b1686458aa7e8fa7d8"},
273
+ - {file = "certifi-2021.5.30.tar.gz", hash = "sha256:2bbf76fd432960138b3ef6dda3dde0544f27cbf8546c458e60baf371917ba9ee"},
274
+ + {file = "certifi-2021.10.8-py2.py3-none-any.whl", hash = "sha256:d62a0163eb4c2344ac042ab2bdf75399a71a2d8c7d47eac2e2ee91b9d6339569"},
275
+ + {file = "certifi-2021.10.8.tar.gz", hash = "sha256:78884e7c1d4b00ce3cea67b44566851c4343c120abd683433ce934a68ea58872"},
276
+ ]
277
+ cffi = [
278
+ {file = "cffi-1.14.6-cp27-cp27m-macosx_10_9_x86_64.whl", hash = "sha256:22b9c3c320171c108e903d61a3723b51e37aaa8c81255b5e7ce102775bd01e2c"},
279
+ @@ -3499,23 +3507,26 @@ coveralls = [
280
+ {file = "coveralls-3.2.0.tar.gz", hash = "sha256:15a987d9df877fff44cd81948c5806ffb6eafb757b3443f737888358e96156ee"},
281
+ ]
282
+ cryptography = [
283
+ - {file = "cryptography-3.4.8-cp36-abi3-macosx_10_10_x86_64.whl", hash = "sha256:a00cf305f07b26c351d8d4e1af84ad7501eca8a342dedf24a7acb0e7b7406e14"},
284
+ - {file = "cryptography-3.4.8-cp36-abi3-macosx_11_0_arm64.whl", hash = "sha256:f44d141b8c4ea5eb4dbc9b3ad992d45580c1d22bf5e24363f2fbf50c2d7ae8a7"},
285
+ - {file = "cryptography-3.4.8-cp36-abi3-manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:0a7dcbcd3f1913f664aca35d47c1331fce738d44ec34b7be8b9d332151b0b01e"},
286
+ - {file = "cryptography-3.4.8-cp36-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:34dae04a0dce5730d8eb7894eab617d8a70d0c97da76b905de9efb7128ad7085"},
287
+ - {file = "cryptography-3.4.8-cp36-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:1eb7bb0df6f6f583dd8e054689def236255161ebbcf62b226454ab9ec663746b"},
288
+ - {file = "cryptography-3.4.8-cp36-abi3-manylinux_2_24_x86_64.whl", hash = "sha256:9965c46c674ba8cc572bc09a03f4c649292ee73e1b683adb1ce81e82e9a6a0fb"},
289
+ - {file = "cryptography-3.4.8-cp36-abi3-win32.whl", hash = "sha256:21ca464b3a4b8d8e86ba0ee5045e103a1fcfac3b39319727bc0fc58c09c6aff7"},
290
+ - {file = "cryptography-3.4.8-cp36-abi3-win_amd64.whl", hash = "sha256:3520667fda779eb788ea00080124875be18f2d8f0848ec00733c0ec3bb8219fc"},
291
+ - {file = "cryptography-3.4.8-pp36-pypy36_pp73-manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:d2a6e5ef66503da51d2110edf6c403dc6b494cc0082f85db12f54e9c5d4c3ec5"},
292
+ - {file = "cryptography-3.4.8-pp36-pypy36_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:a305600e7a6b7b855cd798e00278161b681ad6e9b7eca94c721d5f588ab212af"},
293
+ - {file = "cryptography-3.4.8-pp36-pypy36_pp73-manylinux_2_24_x86_64.whl", hash = "sha256:3fa3a7ccf96e826affdf1a0a9432be74dc73423125c8f96a909e3835a5ef194a"},
294
+ - {file = "cryptography-3.4.8-pp37-pypy37_pp73-macosx_10_10_x86_64.whl", hash = "sha256:d9ec0e67a14f9d1d48dd87a2531009a9b251c02ea42851c060b25c782516ff06"},
295
+ - {file = "cryptography-3.4.8-pp37-pypy37_pp73-manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:5b0fbfae7ff7febdb74b574055c7466da334a5371f253732d7e2e7525d570498"},
296
+ - {file = "cryptography-3.4.8-pp37-pypy37_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:94fff993ee9bc1b2440d3b7243d488c6a3d9724cc2b09cdb297f6a886d040ef7"},
297
+ - {file = "cryptography-3.4.8-pp37-pypy37_pp73-manylinux_2_24_x86_64.whl", hash = "sha256:8695456444f277af73a4877db9fc979849cd3ee74c198d04fc0776ebc3db52b9"},
298
+ - {file = "cryptography-3.4.8-pp37-pypy37_pp73-win_amd64.whl", hash = "sha256:cd65b60cfe004790c795cc35f272e41a3df4631e2fb6b35aa7ac6ef2859d554e"},
299
+ - {file = "cryptography-3.4.8.tar.gz", hash = "sha256:94cc5ed4ceaefcbe5bf38c8fba6a21fc1d365bb8fb826ea1688e3370b2e24a1c"},
300
+ + {file = "cryptography-35.0.0-cp36-abi3-macosx_10_10_x86_64.whl", hash = "sha256:d57e0cdc1b44b6cdf8af1d01807db06886f10177469312fbde8f44ccbb284bc9"},
301
+ + {file = "cryptography-35.0.0-cp36-abi3-macosx_11_0_arm64.whl", hash = "sha256:ced40344e811d6abba00295ced98c01aecf0c2de39481792d87af4fa58b7b4d6"},
302
+ + {file = "cryptography-35.0.0-cp36-abi3-manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:54b2605e5475944e2213258e0ab8696f4f357a31371e538ef21e8d61c843c28d"},
303
+ + {file = "cryptography-35.0.0-cp36-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.manylinux_2_24_aarch64.whl", hash = "sha256:7b7ceeff114c31f285528ba8b390d3e9cfa2da17b56f11d366769a807f17cbaa"},
304
+ + {file = "cryptography-35.0.0-cp36-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:2d69645f535f4b2c722cfb07a8eab916265545b3475fdb34e0be2f4ee8b0b15e"},
305
+ + {file = "cryptography-35.0.0-cp36-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:4a2d0e0acc20ede0f06ef7aa58546eee96d2592c00f450c9acb89c5879b61992"},
306
+ + {file = "cryptography-35.0.0-cp36-abi3-manylinux_2_24_x86_64.whl", hash = "sha256:07bb7fbfb5de0980590ddfc7f13081520def06dc9ed214000ad4372fb4e3c7f6"},
307
+ + {file = "cryptography-35.0.0-cp36-abi3-musllinux_1_1_aarch64.whl", hash = "sha256:7eba2cebca600a7806b893cb1d541a6e910afa87e97acf2021a22b32da1df52d"},
308
+ + {file = "cryptography-35.0.0-cp36-abi3-musllinux_1_1_x86_64.whl", hash = "sha256:18d90f4711bf63e2fb21e8c8e51ed8189438e6b35a6d996201ebd98a26abbbe6"},
309
+ + {file = "cryptography-35.0.0-cp36-abi3-win32.whl", hash = "sha256:c10c797ac89c746e488d2ee92bd4abd593615694ee17b2500578b63cad6b93a8"},
310
+ + {file = "cryptography-35.0.0-cp36-abi3-win_amd64.whl", hash = "sha256:7075b304cd567694dc692ffc9747f3e9cb393cc4aa4fb7b9f3abd6f5c4e43588"},
311
+ + {file = "cryptography-35.0.0-pp36-pypy36_pp73-manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:a688ebcd08250eab5bb5bca318cc05a8c66de5e4171a65ca51db6bd753ff8953"},
312
+ + {file = "cryptography-35.0.0-pp36-pypy36_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:d99915d6ab265c22873f1b4d6ea5ef462ef797b4140be4c9d8b179915e0985c6"},
313
+ + {file = "cryptography-35.0.0-pp36-pypy36_pp73-manylinux_2_24_x86_64.whl", hash = "sha256:928185a6d1ccdb816e883f56ebe92e975a262d31cc536429041921f8cb5a62fd"},
314
+ + {file = "cryptography-35.0.0-pp37-pypy37_pp73-macosx_10_10_x86_64.whl", hash = "sha256:ebeddd119f526bcf323a89f853afb12e225902a24d29b55fe18dd6fcb2838a76"},
315
+ + {file = "cryptography-35.0.0-pp37-pypy37_pp73-manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:22a38e96118a4ce3b97509443feace1d1011d0571fae81fc3ad35f25ba3ea999"},
316
+ + {file = "cryptography-35.0.0-pp37-pypy37_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:eb80e8a1f91e4b7ef8b33041591e6d89b2b8e122d787e87eeb2b08da71bb16ad"},
317
+ + {file = "cryptography-35.0.0-pp37-pypy37_pp73-manylinux_2_24_x86_64.whl", hash = "sha256:abb5a361d2585bb95012a19ed9b2c8f412c5d723a9836418fab7aaa0243e67d2"},
318
+ + {file = "cryptography-35.0.0-pp37-pypy37_pp73-win_amd64.whl", hash = "sha256:1ed82abf16df40a60942a8c211251ae72858b25b7421ce2497c2eb7a1cee817c"},
319
+ + {file = "cryptography-35.0.0.tar.gz", hash = "sha256:9933f28f70d0517686bd7de36166dda42094eac49415459d9bdf5e7df3e0086d"},
320
+ ]
321
+ cycler = [
322
+ {file = "cycler-0.10.0-py2.py3-none-any.whl", hash = "sha256:1d8a5ae1ff6c5cf9b93e8811e581232ad8920aeec647c37316ceac982b08cb2d"},
323
+ @@ -3595,8 +3606,8 @@ fbmessenger = [
324
+ {file = "fbmessenger-6.0.0.tar.gz", hash = "sha256:6e42c4588a4c942547be228886278bbc7a084e0b34799c7e6ebd786129f021e6"},
325
+ ]
326
+ filelock = [
327
+ - {file = "filelock-3.2.0-py2.py3-none-any.whl", hash = "sha256:61a99e9b12b47b685d1389f4cf969c1eba0efd2348a8471f86e01e8c622267af"},
328
+ - {file = "filelock-3.2.0.tar.gz", hash = "sha256:85ecb30757aa19d06bfcdad29cc332b9a3e4851bf59976aea1e8dadcbd9ef883"},
329
+ + {file = "filelock-3.3.0-py3-none-any.whl", hash = "sha256:bbc6a0382fe8ec4744ecdf6683a2e07f65eb10ff1aff53fc02a202565446cde0"},
330
+ + {file = "filelock-3.3.0.tar.gz", hash = "sha256:8c7eab13dc442dc249e95158bcc12dec724465919bdc9831fdbf0660f03d1785"},
331
+ ]
332
+ flake8 = [
333
+ {file = "flake8-3.9.2-py2.py3-none-any.whl", hash = "sha256:bf8fd333346d844f616e8d47905ef3a3384edae6b4e9beb0c5101e25e3110907"},
334
+ @@ -3634,8 +3645,8 @@ gitpython = [
335
+ {file = "GitPython-3.1.20.tar.gz", hash = "sha256:df0e072a200703a65387b0cfdf0466e3bab729c0458cf6b7349d0e9877636519"},
336
+ ]
337
+ google-api-core = [
338
+ - {file = "google-api-core-2.0.1.tar.gz", hash = "sha256:d6760f21b3a064a8397916b33be7383fc169d1a3c3d7fae7b47eb92bba7892b8"},
339
+ - {file = "google_api_core-2.0.1-py2.py3-none-any.whl", hash = "sha256:b8ad41f72a70dd709dd13a08478936172aecf5f2d34a18ab378efa6d2d6ab575"},
340
+ + {file = "google-api-core-2.1.0.tar.gz", hash = "sha256:5ec27b942b34d04559cbf3674430bb83fc3d74e7d32b8bbd31c4466e71740b83"},
341
+ + {file = "google_api_core-2.1.0-py2.py3-none-any.whl", hash = "sha256:c344e1aacd8330527c5130bdfe03118d8859ce798bcf0e5d23770ab6873e0615"},
342
+ ]
343
+ google-auth = [
344
+ {file = "google-auth-1.35.0.tar.gz", hash = "sha256:b7033be9028c188ee30200b204ea00ed82ea1162e8ac1df4aa6ded19a191d88e"},
345
+ @@ -3646,57 +3657,57 @@ google-auth-oauthlib = [
346
+ {file = "google_auth_oauthlib-0.4.6-py2.py3-none-any.whl", hash = "sha256:3f2a6e802eebbb6fb736a370fbf3b055edcb6b52878bf2f26330b5e041316c73"},
347
+ ]
348
+ google-cloud-core = [
349
+ - {file = "google-cloud-core-2.0.0.tar.gz", hash = "sha256:90ee99648ccf9e11a16781a7fc58d13e58f662b439c737d48c24ef18662c2702"},
350
+ - {file = "google_cloud_core-2.0.0-py2.py3-none-any.whl", hash = "sha256:31785d1e1d02f90ad3f1b020d4aed63db4865c3394ff7c128a296b6995eef31f"},
351
+ + {file = "google-cloud-core-2.1.0.tar.gz", hash = "sha256:35a1f5f02a86e0fa2e28c669f0db4a76d928671a28fbbbb493ab59ba9d1cb9a9"},
352
+ + {file = "google_cloud_core-2.1.0-py2.py3-none-any.whl", hash = "sha256:8d5fed11731dae8bc8656a2c9fa8ff17bdfdfd083cba97569324e35b94e7e002"},
353
+ ]
354
+ google-cloud-storage = [
355
+ {file = "google-cloud-storage-1.42.3.tar.gz", hash = "sha256:7754d4dcaa45975514b404ece0da2bb4292acbc67ca559a69e12a19d54fcdb06"},
356
+ {file = "google_cloud_storage-1.42.3-py2.py3-none-any.whl", hash = "sha256:71ee3a0dcf2c139f034a054181cd7658f1ec8f12837d2769c450a8a00fcd4c6d"},
357
+ ]
358
+ google-crc32c = [
359
+ - {file = "google-crc32c-1.2.0.tar.gz", hash = "sha256:258caf72c4ab03d91e593ed9f988c13c118754f5ce46d8bcbc40b109d14cb8b7"},
360
+ - {file = "google_crc32c-1.2.0-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:b64bd23a66410883c22c156834b73515e3f3d8c890c0407620f960b4c25cc8a3"},
361
+ - {file = "google_crc32c-1.2.0-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:61080f164ea51e156153c601b1de35ccb574d77efb669c11ade75f8635ce2d29"},
362
+ - {file = "google_crc32c-1.2.0-cp310-cp310-manylinux_2_12_i686.manylinux2010_i686.whl", hash = "sha256:f563a48074de0a4ebf1ef1d55aeb16bdaa6715c33091dad3b6a32716d2a5d4a4"},
363
+ - {file = "google_crc32c-1.2.0-cp310-cp310-manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:242274e127e349e6ede67d7232872bdac9f6c36da6233216e8e4f5923eef1a7c"},
364
+ - {file = "google_crc32c-1.2.0-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:93f1377269cf30b15b296e760ac3f6e13ea52556a764739410fa2e7b32a39e93"},
365
+ - {file = "google_crc32c-1.2.0-cp310-cp310-win32.whl", hash = "sha256:60f9e93e29cbaa47f57230907733af884685dbac78d462019ffe02d514bbfddc"},
366
+ - {file = "google_crc32c-1.2.0-cp310-cp310-win_amd64.whl", hash = "sha256:b28e81707257802d1e07aee4a2513d1316f623a1b48b78885c1ca2a9ec47949d"},
367
+ - {file = "google_crc32c-1.2.0-cp36-cp36m-macosx_10_9_x86_64.whl", hash = "sha256:837a17d940dac5b0d0a88868a2be924bbb31578de20c250620c09ac7c3f9d1fd"},
368
+ - {file = "google_crc32c-1.2.0-cp36-cp36m-manylinux_2_12_i686.manylinux2010_i686.whl", hash = "sha256:966186c535fec30606cb7787e3caa283631f80c50cbd7226e7db1589ede0f177"},
369
+ - {file = "google_crc32c-1.2.0-cp36-cp36m-manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:617ec1f65d769e670dd35d9e8db0244d03bb09b8728262e28ebeab82de8d1341"},
370
+ - {file = "google_crc32c-1.2.0-cp36-cp36m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:ca0f7bcb47dbd1367bb8f2d7dfc90568a7f69e4062dd70b21a365fc361c9929d"},
371
+ - {file = "google_crc32c-1.2.0-cp36-cp36m-manylinux_2_5_x86_64.manylinux1_x86_64.whl", hash = "sha256:e7b98a2dabe06a460219ecad21113d1c9d793910ceeeae8b4fb64871ef203c4c"},
372
+ - {file = "google_crc32c-1.2.0-cp36-cp36m-win32.whl", hash = "sha256:a6307368bc04f07d3bdf554109d5ebd64b350c12e1a3604686e7a2d913585b1e"},
373
+ - {file = "google_crc32c-1.2.0-cp36-cp36m-win_amd64.whl", hash = "sha256:4b2f3a9f61f264029ffbaf9f503340da1e72e602650eb46d34940a431e3a2676"},
374
+ - {file = "google_crc32c-1.2.0-cp37-cp37m-macosx_10_9_x86_64.whl", hash = "sha256:ce877f9ce49db4f465d942ea910475d79148b390e5890efb2e505df9596d5ced"},
375
+ - {file = "google_crc32c-1.2.0-cp37-cp37m-manylinux_2_12_i686.manylinux2010_i686.whl", hash = "sha256:c9a057c13a268c3a03d1fc8aa08358952b7ff560bb2893fe46dd5823cc0f47b7"},
376
+ - {file = "google_crc32c-1.2.0-cp37-cp37m-manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:ad1cfabad6e9d4affd03684fde2763fa47b6d5a9696a03df3bb23f197cf55af1"},
377
+ - {file = "google_crc32c-1.2.0-cp37-cp37m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:b19ee0a14107fc29a24129982f16648908363b0c43cf6a2b68ece7768c4d038b"},
378
+ - {file = "google_crc32c-1.2.0-cp37-cp37m-manylinux_2_5_x86_64.manylinux1_x86_64.whl", hash = "sha256:fd55f480bb87e1f03b08a8bff13a0689efa7bf10426f1b58f2081168a05b3463"},
379
+ - {file = "google_crc32c-1.2.0-cp37-cp37m-win32.whl", hash = "sha256:6690bbdbfafc39f7031e19e07965b28b91cf41f3a66267e9e9f75b7bcbcd8ac6"},
380
+ - {file = "google_crc32c-1.2.0-cp37-cp37m-win_amd64.whl", hash = "sha256:8331f0cbf8d91e868858a95c3608c26c2b8872f0ed8464c58425995aa92cb70b"},
381
+ - {file = "google_crc32c-1.2.0-cp38-cp38-macosx_10_9_universal2.whl", hash = "sha256:96e7057e29abfe763db02877b7cafff8a076145feb446106409f4fc12549d281"},
382
+ - {file = "google_crc32c-1.2.0-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:496d7d6ac406f3a8e9f1e2fea93bc5470d5ff02c6ea34745c9aa5f22c876f30e"},
383
+ - {file = "google_crc32c-1.2.0-cp38-cp38-manylinux_2_12_i686.manylinux2010_i686.whl", hash = "sha256:8a862ea73b86c3b6589847224195e1027a876c85dc1f87475509b58d2aaafcda"},
384
+ - {file = "google_crc32c-1.2.0-cp38-cp38-manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:eb32e021526e905500c08aa030461621e5af934bf68a910322f5ddebb8c2bbf9"},
385
+ - {file = "google_crc32c-1.2.0-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:6e720b0c9df6a58d4786c299407c2561993e9abd41d37c38e09d33288a3aca0d"},
386
+ - {file = "google_crc32c-1.2.0-cp38-cp38-manylinux_2_5_x86_64.manylinux1_x86_64.whl", hash = "sha256:8aa4de2ffad9d5521d9ba105a1a59126423389598cb4f9af9d28d4da845c0414"},
387
+ - {file = "google_crc32c-1.2.0-cp38-cp38-win32.whl", hash = "sha256:adb721315435d8530a9eabce2cf3731db015ca0af5f8f983bf5c6e5272385c02"},
388
+ - {file = "google_crc32c-1.2.0-cp38-cp38-win_amd64.whl", hash = "sha256:a7920ea4770ec6b98a30e99f9ab90aacc0a447a316c165701f264234d8dbf731"},
389
+ - {file = "google_crc32c-1.2.0-cp39-cp39-macosx_10_9_universal2.whl", hash = "sha256:c242c82eef7fb75ee698ecc65596e324b3273ae3dd78a8e5f05bf3cb627caa3b"},
390
+ - {file = "google_crc32c-1.2.0-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:a6694773dd45c88b2babef6b702b6233723ae4f42cca0fbc68114e81ed389188"},
391
+ - {file = "google_crc32c-1.2.0-cp39-cp39-manylinux_2_12_i686.manylinux2010_i686.whl", hash = "sha256:70670518d50babd6012de3206472aa406a41b79acb11b6e46931f842e25a356a"},
392
+ - {file = "google_crc32c-1.2.0-cp39-cp39-manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:dc12aef85a7b8e5c52d7639cf23e27548f09fba798b8050f59fdd5bee08051f2"},
393
+ - {file = "google_crc32c-1.2.0-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:8e13c8f1fbde9b543f693c42c0f82ba6c57683d66cc2c5960c6c66fccb42a736"},
394
+ - {file = "google_crc32c-1.2.0-cp39-cp39-manylinux_2_5_x86_64.manylinux1_x86_64.whl", hash = "sha256:483694ccb1d0ceab8219afc4f20939565b09f81531bf8dd2bf3efb3ea84766fe"},
395
+ - {file = "google_crc32c-1.2.0-cp39-cp39-win32.whl", hash = "sha256:618c304e803fb5e4b1dbe4d529e1047450d913b64dc4e49826bb3e5a0ef73a9e"},
396
+ - {file = "google_crc32c-1.2.0-cp39-cp39-win_amd64.whl", hash = "sha256:60c4f32d1fbd25234ff9468de24c1c8a9556e90ac94818a99c8cfc83328214d1"},
397
+ - {file = "google_crc32c-1.2.0-pp37-pypy37_pp73-macosx_10_9_x86_64.whl", hash = "sha256:4b8c7579269e3c64dda1d63cc9b9ba7615b51092c905b68d43c907be80fc641f"},
398
+ - {file = "google_crc32c-1.2.0-pp37-pypy37_pp73-manylinux_2_12_i686.manylinux2010_i686.whl", hash = "sha256:c24e7e78756f617ebf006adcb0edb74aaf93a31a45440266e66f5fb2b8c75512"},
399
+ - {file = "google_crc32c-1.2.0-pp37-pypy37_pp73-manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:81c2e088041fb38b099b5a7fb2407deff74ee9bec3b36c38180564b4686bc1fa"},
400
+ - {file = "google_crc32c-1.2.0-pp37-pypy37_pp73-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:c422331bdeb5214ecc8a98f85dcbbc5b3222d173b1348874f1087b1f938313d8"},
401
+ - {file = "google_crc32c-1.2.0-pp37-pypy37_pp73-win_amd64.whl", hash = "sha256:9caf25a7f2551b117e063ce1e1f3959ef64d8c4e96587e4ce6ee1be7b441b3b7"},
402
+ + {file = "google-crc32c-1.3.0.tar.gz", hash = "sha256:276de6273eb074a35bc598f8efbc00c7869c5cf2e29c90748fccc8c898c244df"},
403
+ + {file = "google_crc32c-1.3.0-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:cb6994fff247987c66a8a4e550ef374671c2b82e3c0d2115e689d21e511a652d"},
404
+ + {file = "google_crc32c-1.3.0-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:c9da0a39b53d2fab3e5467329ed50e951eb91386e9d0d5b12daf593973c3b168"},
405
+ + {file = "google_crc32c-1.3.0-cp310-cp310-manylinux_2_12_i686.manylinux2010_i686.whl", hash = "sha256:eb0b14523758e37802f27b7f8cd973f5f3d33be7613952c0df904b68c4842f0e"},
406
+ + {file = "google_crc32c-1.3.0-cp310-cp310-manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:95c68a4b9b7828ba0428f8f7e3109c5d476ca44996ed9a5f8aac6269296e2d59"},
407
+ + {file = "google_crc32c-1.3.0-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:9c3cf890c3c0ecfe1510a452a165431b5831e24160c5fcf2071f0f85ca5a47cd"},
408
+ + {file = "google_crc32c-1.3.0-cp310-cp310-win32.whl", hash = "sha256:3bbce1be3687bbfebe29abdb7631b83e6b25da3f4e1856a1611eb21854b689ea"},
409
+ + {file = "google_crc32c-1.3.0-cp310-cp310-win_amd64.whl", hash = "sha256:c124b8c8779bf2d35d9b721e52d4adb41c9bfbde45e6a3f25f0820caa9aba73f"},
410
+ + {file = "google_crc32c-1.3.0-cp36-cp36m-macosx_10_9_x86_64.whl", hash = "sha256:42ae4781333e331a1743445931b08ebdad73e188fd554259e772556fc4937c48"},
411
+ + {file = "google_crc32c-1.3.0-cp36-cp36m-manylinux_2_12_i686.manylinux2010_i686.whl", hash = "sha256:ff71073ebf0e42258a42a0b34f2c09ec384977e7f6808999102eedd5b49920e3"},
412
+ + {file = "google_crc32c-1.3.0-cp36-cp36m-manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:fe31de3002e7b08eb20823b3735b97c86c5926dd0581c7710a680b418a8709d4"},
413
+ + {file = "google_crc32c-1.3.0-cp36-cp36m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:dd7760a88a8d3d705ff562aa93f8445ead54f58fd482e4f9e2bafb7e177375d4"},
414
+ + {file = "google_crc32c-1.3.0-cp36-cp36m-manylinux_2_5_x86_64.manylinux1_x86_64.whl", hash = "sha256:a0b9e622c3b2b8d0ce32f77eba617ab0d6768b82836391e4f8f9e2074582bf02"},
415
+ + {file = "google_crc32c-1.3.0-cp36-cp36m-win32.whl", hash = "sha256:779cbf1ce375b96111db98fca913c1f5ec11b1d870e529b1dc7354b2681a8c3a"},
416
+ + {file = "google_crc32c-1.3.0-cp36-cp36m-win_amd64.whl", hash = "sha256:04e7c220798a72fd0f08242bc8d7a05986b2a08a0573396187fd32c1dcdd58b3"},
417
+ + {file = "google_crc32c-1.3.0-cp37-cp37m-macosx_10_9_x86_64.whl", hash = "sha256:e7a539b9be7b9c00f11ef16b55486141bc2cdb0c54762f84e3c6fc091917436d"},
418
+ + {file = "google_crc32c-1.3.0-cp37-cp37m-manylinux_2_12_i686.manylinux2010_i686.whl", hash = "sha256:ca60076c388728d3b6ac3846842474f4250c91efbfe5afa872d3ffd69dd4b318"},
419
+ + {file = "google_crc32c-1.3.0-cp37-cp37m-manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:05340b60bf05b574159e9bd940152a47d38af3fb43803ffe71f11d704b7696a6"},
420
+ + {file = "google_crc32c-1.3.0-cp37-cp37m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:318f73f5484b5671f0c7f5f63741ab020a599504ed81d209b5c7129ee4667407"},
421
+ + {file = "google_crc32c-1.3.0-cp37-cp37m-manylinux_2_5_x86_64.manylinux1_x86_64.whl", hash = "sha256:9f58099ad7affc0754ae42e6d87443299f15d739b0ce03c76f515153a5cda06c"},
422
+ + {file = "google_crc32c-1.3.0-cp37-cp37m-win32.whl", hash = "sha256:f52a4ad2568314ee713715b1e2d79ab55fab11e8b304fd1462ff5cccf4264b3e"},
423
+ + {file = "google_crc32c-1.3.0-cp37-cp37m-win_amd64.whl", hash = "sha256:bab4aebd525218bab4ee615786c4581952eadc16b1ff031813a2fd51f0cc7b08"},
424
+ + {file = "google_crc32c-1.3.0-cp38-cp38-macosx_10_9_universal2.whl", hash = "sha256:dda4d8a3bb0b50f540f6ff4b6033f3a74e8bf0bd5320b70fab2c03e512a62812"},
425
+ + {file = "google_crc32c-1.3.0-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:fec221a051150eeddfdfcff162e6db92c65ecf46cb0f7bb1bf812a1520ec026b"},
426
+ + {file = "google_crc32c-1.3.0-cp38-cp38-manylinux_2_12_i686.manylinux2010_i686.whl", hash = "sha256:226f2f9b8e128a6ca6a9af9b9e8384f7b53a801907425c9a292553a3a7218ce0"},
427
+ + {file = "google_crc32c-1.3.0-cp38-cp38-manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:a7f9cbea4245ee36190f85fe1814e2d7b1e5f2186381b082f5d59f99b7f11328"},
428
+ + {file = "google_crc32c-1.3.0-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:6a4db36f9721fdf391646685ecffa404eb986cbe007a3289499020daf72e88a2"},
429
+ + {file = "google_crc32c-1.3.0-cp38-cp38-manylinux_2_5_x86_64.manylinux1_x86_64.whl", hash = "sha256:12674a4c3b56b706153a358eaa1018c4137a5a04635b92b4652440d3d7386206"},
430
+ + {file = "google_crc32c-1.3.0-cp38-cp38-win32.whl", hash = "sha256:650e2917660e696041ab3dcd7abac160b4121cd9a484c08406f24c5964099829"},
431
+ + {file = "google_crc32c-1.3.0-cp38-cp38-win_amd64.whl", hash = "sha256:58be56ae0529c664cc04a9c76e68bb92b091e0194d6e3c50bea7e0f266f73713"},
432
+ + {file = "google_crc32c-1.3.0-cp39-cp39-macosx_10_9_universal2.whl", hash = "sha256:96a8918a78d5d64e07c8ea4ed2bc44354e3f93f46a4866a40e8db934e4c0d74b"},
433
+ + {file = "google_crc32c-1.3.0-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:13af315c3a0eec8bb8b8d80b8b128cb3fcd17d7e4edafc39647846345a3f003a"},
434
+ + {file = "google_crc32c-1.3.0-cp39-cp39-manylinux_2_12_i686.manylinux2010_i686.whl", hash = "sha256:6311853aa2bba4064d0c28ca54e7b50c4d48e3de04f6770f6c60ebda1e975267"},
435
+ + {file = "google_crc32c-1.3.0-cp39-cp39-manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:ed447680ff21c14aaceb6a9f99a5f639f583ccfe4ce1a5e1d48eb41c3d6b3217"},
436
+ + {file = "google_crc32c-1.3.0-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:d1c1d6236feab51200272d79b3d3e0f12cf2cbb12b208c835b175a21efdb0a73"},
437
+ + {file = "google_crc32c-1.3.0-cp39-cp39-manylinux_2_5_x86_64.manylinux1_x86_64.whl", hash = "sha256:e0f1ff55dde0ebcfbef027edc21f71c205845585fffe30d4ec4979416613e9b3"},
438
+ + {file = "google_crc32c-1.3.0-cp39-cp39-win32.whl", hash = "sha256:fbd60c6aaa07c31d7754edbc2334aef50601b7f1ada67a96eb1eb57c7c72378f"},
439
+ + {file = "google_crc32c-1.3.0-cp39-cp39-win_amd64.whl", hash = "sha256:127f9cc3ac41b6a859bd9dc4321097b1a4f6aa7fdf71b4f9227b9e3ebffb4422"},
440
+ + {file = "google_crc32c-1.3.0-pp37-pypy37_pp73-macosx_10_9_x86_64.whl", hash = "sha256:fc28e0db232c62ca0c3600884933178f0825c99be4474cdd645e378a10588125"},
441
+ + {file = "google_crc32c-1.3.0-pp37-pypy37_pp73-manylinux_2_12_i686.manylinux2010_i686.whl", hash = "sha256:1926fd8de0acb9d15ee757175ce7242e235482a783cd4ec711cc999fc103c24e"},
442
+ + {file = "google_crc32c-1.3.0-pp37-pypy37_pp73-manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:5da2c81575cc3ccf05d9830f9e8d3c70954819ca9a63828210498c0774fda1a3"},
443
+ + {file = "google_crc32c-1.3.0-pp37-pypy37_pp73-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:891f712ce54e0d631370e1f4997b3f182f3368179198efc30d477c75d1f44942"},
444
+ + {file = "google_crc32c-1.3.0-pp37-pypy37_pp73-win_amd64.whl", hash = "sha256:7f6fe42536d9dcd3e2ffb9d3053f5d05221ae3bbcefbe472bdf2c71c793e3183"},
445
+ ]
446
+ google-pasta = [
447
+ {file = "google-pasta-0.2.0.tar.gz", hash = "sha256:c9f2c8dfc8f96d0d5808299920721be30c9eec37f2389f28904f454565c8a16e"},
448
+ @@ -3841,8 +3852,8 @@ hstspreload = [
449
+ {file = "hstspreload-2021.10.1.tar.gz", hash = "sha256:5bb90f438bec40faf320170ee48cf1978f40423ee1ba39a57bb686f3f9c061c7"},
450
+ ]
451
+ httplib2 = [
452
+ - {file = "httplib2-0.19.1-py3-none-any.whl", hash = "sha256:2ad195faf9faf079723f6714926e9a9061f694d07724b846658ce08d40f522b4"},
453
+ - {file = "httplib2-0.19.1.tar.gz", hash = "sha256:0b12617eeca7433d4c396a100eaecfa4b08ee99aa881e6df6e257a7aad5d533d"},
454
+ + {file = "httplib2-0.20.1-py3-none-any.whl", hash = "sha256:8fa4dbf2fbf839b71f8c7837a831e00fcdc860feca99b8bda58ceae4bc53d185"},
455
+ + {file = "httplib2-0.20.1.tar.gz", hash = "sha256:0efbcb8bfbfbc11578130d87d8afcc65c2274c6eb446e59fc674e4d7c972d327"},
456
+ ]
457
+ httptools = [
458
+ {file = "httptools-0.3.0-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:4137137de8976511a392e27bfdcf231bd926ac13d375e0414e927b08217d779e"},
459
+ @@ -3942,8 +3953,8 @@ jieba = [
460
+ {file = "jieba-0.42.1.tar.gz", hash = "sha256:055ca12f62674fafed09427f176506079bc135638a14e23e25be909131928db2"},
461
+ ]
462
+ jinja2 = [
463
+ - {file = "Jinja2-3.0.1-py3-none-any.whl", hash = "sha256:1f06f2da51e7b56b8f238affdd6b4e2c61e39598a378cc49345bc1bd42a978a4"},
464
+ - {file = "Jinja2-3.0.1.tar.gz", hash = "sha256:703f484b47a6af502e743c9122595cc812b0271f661722403114f71a79d0f5a4"},
465
+ + {file = "Jinja2-3.0.2-py3-none-any.whl", hash = "sha256:8569982d3f0889eed11dd620c706d39b60c36d6d25843961f33f77fb6bc6b20c"},
466
+ + {file = "Jinja2-3.0.2.tar.gz", hash = "sha256:827a0e32839ab1600d4eb1c4c33ec5a8edfbc5cb42dafa13b81f182f97784b45"},
467
+ ]
468
+ jmespath = [
469
+ {file = "jmespath-0.10.0-py2.py3-none-any.whl", hash = "sha256:cdf6525904cc597730141d61b36f2e4b8ecc257c420fa2f4549bac2c2d0cb72f"},
470
+ @@ -3991,14 +4002,18 @@ kiwisolver = [
471
+ {file = "kiwisolver-1.3.1-cp37-cp37m-manylinux2014_ppc64le.whl", hash = "sha256:1e1bc12fb773a7b2ffdeb8380609f4f8064777877b2225dec3da711b421fda31"},
472
+ {file = "kiwisolver-1.3.1-cp37-cp37m-win32.whl", hash = "sha256:72c99e39d005b793fb7d3d4e660aed6b6281b502e8c1eaf8ee8346023c8e03bc"},
473
+ {file = "kiwisolver-1.3.1-cp37-cp37m-win_amd64.whl", hash = "sha256:8be8d84b7d4f2ba4ffff3665bcd0211318aa632395a1a41553250484a871d454"},
474
+ + {file = "kiwisolver-1.3.1-cp38-cp38-macosx_10_9_universal2.whl", hash = "sha256:24cc411232d14c8abafbd0dddb83e1a4f54d77770b53db72edcfe1d611b3bf11"},
475
+ {file = "kiwisolver-1.3.1-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:31dfd2ac56edc0ff9ac295193eeaea1c0c923c0355bf948fbd99ed6018010b72"},
476
+ + {file = "kiwisolver-1.3.1-cp38-cp38-macosx_11_0_arm64.whl", hash = "sha256:ef6eefcf3944e75508cdfa513c06cf80bafd7d179e14c1334ebdca9ebb8c2c66"},
477
+ {file = "kiwisolver-1.3.1-cp38-cp38-manylinux1_i686.whl", hash = "sha256:563c649cfdef27d081c84e72a03b48ea9408c16657500c312575ae9d9f7bc1c3"},
478
+ {file = "kiwisolver-1.3.1-cp38-cp38-manylinux1_x86_64.whl", hash = "sha256:78751b33595f7f9511952e7e60ce858c6d64db2e062afb325985ddbd34b5c131"},
479
+ {file = "kiwisolver-1.3.1-cp38-cp38-manylinux2014_aarch64.whl", hash = "sha256:a357fd4f15ee49b4a98b44ec23a34a95f1e00292a139d6015c11f55774ef10de"},
480
+ {file = "kiwisolver-1.3.1-cp38-cp38-manylinux2014_ppc64le.whl", hash = "sha256:5989db3b3b34b76c09253deeaf7fbc2707616f130e166996606c284395da3f18"},
481
+ {file = "kiwisolver-1.3.1-cp38-cp38-win32.whl", hash = "sha256:c08e95114951dc2090c4a630c2385bef681cacf12636fb0241accdc6b303fd81"},
482
+ {file = "kiwisolver-1.3.1-cp38-cp38-win_amd64.whl", hash = "sha256:44a62e24d9b01ba94ae7a4a6c3fb215dc4af1dde817e7498d901e229aaf50e4e"},
483
+ + {file = "kiwisolver-1.3.1-cp39-cp39-macosx_10_9_universal2.whl", hash = "sha256:6d9d8d9b31aa8c2d80a690693aebd8b5e2b7a45ab065bb78f1609995d2c79240"},
484
+ {file = "kiwisolver-1.3.1-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:50af681a36b2a1dee1d3c169ade9fdc59207d3c31e522519181e12f1b3ba7000"},
485
+ + {file = "kiwisolver-1.3.1-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:792e69140828babe9649de583e1a03a0f2ff39918a71782c76b3c683a67c6dfd"},
486
+ {file = "kiwisolver-1.3.1-cp39-cp39-manylinux1_i686.whl", hash = "sha256:a53d27d0c2a0ebd07e395e56a1fbdf75ffedc4a05943daf472af163413ce9598"},
487
+ {file = "kiwisolver-1.3.1-cp39-cp39-manylinux1_x86_64.whl", hash = "sha256:834ee27348c4aefc20b479335fd422a2c69db55f7d9ab61721ac8cd83eb78882"},
488
+ {file = "kiwisolver-1.3.1-cp39-cp39-manylinux2014_aarch64.whl", hash = "sha256:5c3e6455341008a054cccee8c5d24481bcfe1acdbc9add30aa95798e95c65621"},
489
+ @@ -4008,6 +4023,7 @@ kiwisolver = [
490
+ {file = "kiwisolver-1.3.1-pp36-pypy36_pp73-macosx_10_9_x86_64.whl", hash = "sha256:0cd53f403202159b44528498de18f9285b04482bab2a6fc3f5dd8dbb9352e30d"},
491
+ {file = "kiwisolver-1.3.1-pp36-pypy36_pp73-manylinux2010_x86_64.whl", hash = "sha256:33449715e0101e4d34f64990352bce4095c8bf13bed1b390773fc0a7295967b3"},
492
+ {file = "kiwisolver-1.3.1-pp36-pypy36_pp73-win32.whl", hash = "sha256:401a2e9afa8588589775fe34fc22d918ae839aaaf0c0e96441c0fdbce6d8ebe6"},
493
+ + {file = "kiwisolver-1.3.1-pp37-pypy37_pp73-macosx_10_9_x86_64.whl", hash = "sha256:d6563ccd46b645e966b400bb8a95d3457ca6cf3bba1e908f9e0927901dfebeb1"},
494
+ {file = "kiwisolver-1.3.1.tar.gz", hash = "sha256:950a199911a8d94683a6b10321f9345d5a3a8433ec58b217ace979e18f16e248"},
495
+ ]
496
+ markdown = [
497
+ @@ -4015,12 +4031,22 @@ markdown = [
498
+ {file = "Markdown-3.3.4.tar.gz", hash = "sha256:31b5b491868dcc87d6c24b7e3d19a0d730d59d3e46f4eea6430a321bed387a49"},
499
+ ]
500
+ markupsafe = [
501
+ + {file = "MarkupSafe-2.0.1-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:d8446c54dc28c01e5a2dbac5a25f071f6653e6e40f3a8818e8b45d790fe6ef53"},
502
+ + {file = "MarkupSafe-2.0.1-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:36bc903cbb393720fad60fc28c10de6acf10dc6cc883f3e24ee4012371399a38"},
503
+ + {file = "MarkupSafe-2.0.1-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:2d7d807855b419fc2ed3e631034685db6079889a1f01d5d9dac950f764da3dad"},
504
+ + {file = "MarkupSafe-2.0.1-cp310-cp310-manylinux_2_5_i686.manylinux1_i686.manylinux_2_12_i686.manylinux2010_i686.whl", hash = "sha256:add36cb2dbb8b736611303cd3bfcee00afd96471b09cda130da3581cbdc56a6d"},
505
+ + {file = "MarkupSafe-2.0.1-cp310-cp310-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:168cd0a3642de83558a5153c8bd34f175a9a6e7f6dc6384b9655d2697312a646"},
506
+ + {file = "MarkupSafe-2.0.1-cp310-cp310-win32.whl", hash = "sha256:99df47edb6bda1249d3e80fdabb1dab8c08ef3975f69aed437cb69d0a5de1e28"},
507
+ + {file = "MarkupSafe-2.0.1-cp310-cp310-win_amd64.whl", hash = "sha256:e0f138900af21926a02425cf736db95be9f4af72ba1bb21453432a07f6082134"},
508
+ {file = "MarkupSafe-2.0.1-cp36-cp36m-macosx_10_9_x86_64.whl", hash = "sha256:f9081981fe268bd86831e5c75f7de206ef275defcb82bc70740ae6dc507aee51"},
509
+ {file = "MarkupSafe-2.0.1-cp36-cp36m-manylinux1_i686.whl", hash = "sha256:0955295dd5eec6cb6cc2fe1698f4c6d84af2e92de33fbcac4111913cd100a6ff"},
510
+ {file = "MarkupSafe-2.0.1-cp36-cp36m-manylinux1_x86_64.whl", hash = "sha256:0446679737af14f45767963a1a9ef7620189912317d095f2d9ffa183a4d25d2b"},
511
+ {file = "MarkupSafe-2.0.1-cp36-cp36m-manylinux2010_i686.whl", hash = "sha256:f826e31d18b516f653fe296d967d700fddad5901ae07c622bb3705955e1faa94"},
512
+ {file = "MarkupSafe-2.0.1-cp36-cp36m-manylinux2010_x86_64.whl", hash = "sha256:fa130dd50c57d53368c9d59395cb5526eda596d3ffe36666cd81a44d56e48872"},
513
+ {file = "MarkupSafe-2.0.1-cp36-cp36m-manylinux2014_aarch64.whl", hash = "sha256:905fec760bd2fa1388bb5b489ee8ee5f7291d692638ea5f67982d968366bef9f"},
514
+ + {file = "MarkupSafe-2.0.1-cp36-cp36m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:bf5d821ffabf0ef3533c39c518f3357b171a1651c1ff6827325e4489b0e46c3c"},
515
+ + {file = "MarkupSafe-2.0.1-cp36-cp36m-manylinux_2_5_i686.manylinux1_i686.manylinux_2_12_i686.manylinux2010_i686.whl", hash = "sha256:0d4b31cc67ab36e3392bbf3862cfbadac3db12bdd8b02a2731f509ed5b829724"},
516
+ + {file = "MarkupSafe-2.0.1-cp36-cp36m-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:baa1a4e8f868845af802979fcdbf0bb11f94f1cb7ced4c4b8a351bb60d108145"},
517
+ {file = "MarkupSafe-2.0.1-cp36-cp36m-win32.whl", hash = "sha256:6c4ca60fa24e85fe25b912b01e62cb969d69a23a5d5867682dd3e80b5b02581d"},
518
+ {file = "MarkupSafe-2.0.1-cp36-cp36m-win_amd64.whl", hash = "sha256:b2f4bf27480f5e5e8ce285a8c8fd176c0b03e93dcc6646477d4630e83440c6a9"},
519
+ {file = "MarkupSafe-2.0.1-cp37-cp37m-macosx_10_9_x86_64.whl", hash = "sha256:0717a7390a68be14b8c793ba258e075c6f4ca819f15edfc2a3a027c823718567"},
520
+ @@ -4029,14 +4055,21 @@ markupsafe = [
521
+ {file = "MarkupSafe-2.0.1-cp37-cp37m-manylinux2010_i686.whl", hash = "sha256:d7f9850398e85aba693bb640262d3611788b1f29a79f0c93c565694658f4071f"},
522
+ {file = "MarkupSafe-2.0.1-cp37-cp37m-manylinux2010_x86_64.whl", hash = "sha256:6a7fae0dd14cf60ad5ff42baa2e95727c3d81ded453457771d02b7d2b3f9c0c2"},
523
+ {file = "MarkupSafe-2.0.1-cp37-cp37m-manylinux2014_aarch64.whl", hash = "sha256:b7f2d075102dc8c794cbde1947378051c4e5180d52d276987b8d28a3bd58c17d"},
524
+ + {file = "MarkupSafe-2.0.1-cp37-cp37m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:e9936f0b261d4df76ad22f8fee3ae83b60d7c3e871292cd42f40b81b70afae85"},
525
+ + {file = "MarkupSafe-2.0.1-cp37-cp37m-manylinux_2_5_i686.manylinux1_i686.manylinux_2_12_i686.manylinux2010_i686.whl", hash = "sha256:2a7d351cbd8cfeb19ca00de495e224dea7e7d919659c2841bbb7f420ad03e2d6"},
526
+ + {file = "MarkupSafe-2.0.1-cp37-cp37m-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:60bf42e36abfaf9aff1f50f52644b336d4f0a3fd6d8a60ca0d054ac9f713a864"},
527
+ {file = "MarkupSafe-2.0.1-cp37-cp37m-win32.whl", hash = "sha256:a30e67a65b53ea0a5e62fe23682cfe22712e01f453b95233b25502f7c61cb415"},
528
+ {file = "MarkupSafe-2.0.1-cp37-cp37m-win_amd64.whl", hash = "sha256:611d1ad9a4288cf3e3c16014564df047fe08410e628f89805e475368bd304914"},
529
+ + {file = "MarkupSafe-2.0.1-cp38-cp38-macosx_10_9_universal2.whl", hash = "sha256:5bb28c636d87e840583ee3adeb78172efc47c8b26127267f54a9c0ec251d41a9"},
530
+ {file = "MarkupSafe-2.0.1-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:be98f628055368795d818ebf93da628541e10b75b41c559fdf36d104c5787066"},
531
+ {file = "MarkupSafe-2.0.1-cp38-cp38-manylinux1_i686.whl", hash = "sha256:1d609f577dc6e1aa17d746f8bd3c31aa4d258f4070d61b2aa5c4166c1539de35"},
532
+ {file = "MarkupSafe-2.0.1-cp38-cp38-manylinux1_x86_64.whl", hash = "sha256:7d91275b0245b1da4d4cfa07e0faedd5b0812efc15b702576d103293e252af1b"},
533
+ {file = "MarkupSafe-2.0.1-cp38-cp38-manylinux2010_i686.whl", hash = "sha256:01a9b8ea66f1658938f65b93a85ebe8bc016e6769611be228d797c9d998dd298"},
534
+ {file = "MarkupSafe-2.0.1-cp38-cp38-manylinux2010_x86_64.whl", hash = "sha256:47ab1e7b91c098ab893b828deafa1203de86d0bc6ab587b160f78fe6c4011f75"},
535
+ {file = "MarkupSafe-2.0.1-cp38-cp38-manylinux2014_aarch64.whl", hash = "sha256:97383d78eb34da7e1fa37dd273c20ad4320929af65d156e35a5e2d89566d9dfb"},
536
+ + {file = "MarkupSafe-2.0.1-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:6fcf051089389abe060c9cd7caa212c707e58153afa2c649f00346ce6d260f1b"},
537
+ + {file = "MarkupSafe-2.0.1-cp38-cp38-manylinux_2_5_i686.manylinux1_i686.manylinux_2_12_i686.manylinux2010_i686.whl", hash = "sha256:5855f8438a7d1d458206a2466bf82b0f104a3724bf96a1c781ab731e4201731a"},
538
+ + {file = "MarkupSafe-2.0.1-cp38-cp38-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:3dd007d54ee88b46be476e293f48c85048603f5f516008bee124ddd891398ed6"},
539
+ {file = "MarkupSafe-2.0.1-cp38-cp38-win32.whl", hash = "sha256:023cb26ec21ece8dc3907c0e8320058b2e0cb3c55cf9564da612bc325bed5e64"},
540
+ {file = "MarkupSafe-2.0.1-cp38-cp38-win_amd64.whl", hash = "sha256:984d76483eb32f1bcb536dc27e4ad56bba4baa70be32fa87152832cdd9db0833"},
541
+ {file = "MarkupSafe-2.0.1-cp39-cp39-macosx_10_9_universal2.whl", hash = "sha256:2ef54abee730b502252bcdf31b10dacb0a416229b72c18b19e24a4509f273d26"},
542
+ @@ -4046,6 +4079,9 @@ markupsafe = [
543
+ {file = "MarkupSafe-2.0.1-cp39-cp39-manylinux2010_i686.whl", hash = "sha256:4efca8f86c54b22348a5467704e3fec767b2db12fc39c6d963168ab1d3fc9135"},
544
+ {file = "MarkupSafe-2.0.1-cp39-cp39-manylinux2010_x86_64.whl", hash = "sha256:ab3ef638ace319fa26553db0624c4699e31a28bb2a835c5faca8f8acf6a5a902"},
545
+ {file = "MarkupSafe-2.0.1-cp39-cp39-manylinux2014_aarch64.whl", hash = "sha256:f8ba0e8349a38d3001fae7eadded3f6606f0da5d748ee53cc1dab1d6527b9509"},
546
+ + {file = "MarkupSafe-2.0.1-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:c47adbc92fc1bb2b3274c4b3a43ae0e4573d9fbff4f54cd484555edbf030baf1"},
547
+ + {file = "MarkupSafe-2.0.1-cp39-cp39-manylinux_2_5_i686.manylinux1_i686.manylinux_2_12_i686.manylinux2010_i686.whl", hash = "sha256:37205cac2a79194e3750b0af2a5720d95f786a55ce7df90c3af697bfa100eaac"},
548
+ + {file = "MarkupSafe-2.0.1-cp39-cp39-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:1f2ade76b9903f39aa442b4aadd2177decb66525062db244b35d71d0ee8599b6"},
549
+ {file = "MarkupSafe-2.0.1-cp39-cp39-win32.whl", hash = "sha256:10f82115e21dc0dfec9ab5c0223652f7197feb168c940f3ef61563fc2d6beb74"},
550
+ {file = "MarkupSafe-2.0.1-cp39-cp39-win_amd64.whl", hash = "sha256:693ce3f9e70a6cf7d2fb9e6c9d8b204b6b39897a2c4a1aa65728d5ac97dcc1d8"},
551
+ {file = "MarkupSafe-2.0.1.tar.gz", hash = "sha256:594c67807fb16238b30c44bdf74f36c02cdf22d1c8cda91ef8a0ed8dabf5620a"},
552
+ @@ -4369,27 +4405,27 @@ prompt-toolkit = [
553
+ {file = "prompt_toolkit-2.0.10.tar.gz", hash = "sha256:f15af68f66e664eaa559d4ac8a928111eebd5feda0c11738b5998045224829db"},
554
+ ]
555
+ protobuf = [
556
+ - {file = "protobuf-3.18.0-cp36-cp36m-macosx_10_9_x86_64.whl", hash = "sha256:9072cb18fca8998b77f969fb74d25a11d7f4a39a8b1ddc3cf76cd5abda8499cb"},
557
+ - {file = "protobuf-3.18.0-cp36-cp36m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:f589346b5b3f702c1d30e2343c9897e6c35e7bd495c10a0e17d11ecb5ee5bd06"},
558
+ - {file = "protobuf-3.18.0-cp36-cp36m-win32.whl", hash = "sha256:93c077fd83879cf48f327a2491c24da447a09da6a7ab3cc311a6f5a61fcb5de0"},
559
+ - {file = "protobuf-3.18.0-cp36-cp36m-win_amd64.whl", hash = "sha256:3b5b81bb665aac548b413480f4e0d8c38a74bc4dea57835f288a3ce74f63dfe9"},
560
+ - {file = "protobuf-3.18.0-cp37-cp37m-macosx_10_9_x86_64.whl", hash = "sha256:d11465040cadcea8ecf5f0b131af5099a9696f9d0bef6f88148b372bacc1c52d"},
561
+ - {file = "protobuf-3.18.0-cp37-cp37m-manylinux2014_aarch64.whl", hash = "sha256:f6138462643adce0ed6e49007a63b7fd7dc4fda1ef4e15a70fcebe76c1407a71"},
562
+ - {file = "protobuf-3.18.0-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:877664b1b8d1e23553634f625e4e12aae4ff16cbbef473f8118c239d478f422a"},
563
+ - {file = "protobuf-3.18.0-cp37-cp37m-win32.whl", hash = "sha256:5201333b7aa711965c5769b250f8565a9924e8e27f8b622bbc5e6847aeaab1b1"},
564
+ - {file = "protobuf-3.18.0-cp37-cp37m-win_amd64.whl", hash = "sha256:1f3ecec3038c2fb4dad952d3d6cb9ca301999903a09e43794fb348da48f7577f"},
565
+ - {file = "protobuf-3.18.0-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:17181fc0814655812aac108e755bd5185d71aa8d81bd241cec6e232c84097918"},
566
+ - {file = "protobuf-3.18.0-cp38-cp38-manylinux2014_aarch64.whl", hash = "sha256:7646c20605fbee57e77fdbc4a90175538281b152f46ba17019916593f8062c2a"},
567
+ - {file = "protobuf-3.18.0-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:80b0a5157f3a53043daf8eb7cfa1220b27a5a63dd6655dbd8e1e6f7b5dcd6347"},
568
+ - {file = "protobuf-3.18.0-cp38-cp38-win32.whl", hash = "sha256:5730de255c95b3403eedd1a568eb28203b913b6192ff5a3fdc3ff30f37107a38"},
569
+ - {file = "protobuf-3.18.0-cp38-cp38-win_amd64.whl", hash = "sha256:9147565f93e6699d7512747766598afe63205f226ac7b61f47954974c9aab852"},
570
+ - {file = "protobuf-3.18.0-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:568c049ff002a7523ed33fb612e6b97da002bf87ffb619a1fc3eadf2257a3b31"},
571
+ - {file = "protobuf-3.18.0-cp39-cp39-manylinux2014_aarch64.whl", hash = "sha256:7e791a94db391ae22b3943fc88f6ba0e1f62b6ad58b33db7517df576c7834d23"},
572
+ - {file = "protobuf-3.18.0-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:42c04e66ec5a38ad2171639dc9860c2f9594668f709ea3a4a192acf7346853a7"},
573
+ - {file = "protobuf-3.18.0-cp39-cp39-win32.whl", hash = "sha256:0a59ea8da307118372750e2fdfe0961622e675b8dd35e05c42384d618189a938"},
574
+ - {file = "protobuf-3.18.0-cp39-cp39-win_amd64.whl", hash = "sha256:f7c8193ec805324ff6024242b00f64a24b94d56b895f62bf28a9d72a228d4fca"},
575
+ - {file = "protobuf-3.18.0-py2.py3-none-any.whl", hash = "sha256:615099e52e9fbc9fde00177267a94ca820ecf4e80093e390753568b7d8cb3c1a"},
576
+ - {file = "protobuf-3.18.0.tar.gz", hash = "sha256:18b308946a592e245299391e53c01b5b8efc2794f49986e80f37d7b5e60a270f"},
577
+ + {file = "protobuf-3.18.1-cp36-cp36m-macosx_10_9_x86_64.whl", hash = "sha256:fa6d1049d5315566f55c04d0b50c0033415144f96a9d25c820dc542fe2bb7f45"},
578
+ + {file = "protobuf-3.18.1-cp36-cp36m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:c0e2790c580070cff2921b93d562539ae027064340151c50db6aaf94c33048cd"},
579
+ + {file = "protobuf-3.18.1-cp36-cp36m-win32.whl", hash = "sha256:7e2f0677d68ecdd1cfda2abea65873f5bc7c3f5aae199404a3f5c1d1198c1a63"},
580
+ + {file = "protobuf-3.18.1-cp36-cp36m-win_amd64.whl", hash = "sha256:6f714f5de9d40b3bec90ede4a688cce52f637ccdc5403afcda1f67598f4fdcd7"},
581
+ + {file = "protobuf-3.18.1-cp37-cp37m-macosx_10_9_x86_64.whl", hash = "sha256:7a7be937c319146cc9f2626f0181e6809062c353e1fe449ecd0df374ba1036b2"},
582
+ + {file = "protobuf-3.18.1-cp37-cp37m-manylinux2014_aarch64.whl", hash = "sha256:10544fc7ace885a882623083c24da5b14148c77563acddc3c58d66f6153c09cd"},
583
+ + {file = "protobuf-3.18.1-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:e2ee8b11e3eb2ed38f12137c3c132270a0b1dd509e317228ac47b67f21a583f1"},
584
+ + {file = "protobuf-3.18.1-cp37-cp37m-win32.whl", hash = "sha256:c492c217d3f69f4d2d5619571e52ab98538edbf53caf67e53ea92bd0a3b5670f"},
585
+ + {file = "protobuf-3.18.1-cp37-cp37m-win_amd64.whl", hash = "sha256:3c1644f8a7f19b45c7a4c32278e2a55ae9e7e2f9e5f02d960a61f04a4890d3e6"},
586
+ + {file = "protobuf-3.18.1-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:e9ac691f7b24e4371dcd3980e4f5d6c840a2010da37986203053fee995786ec5"},
587
+ + {file = "protobuf-3.18.1-cp38-cp38-manylinux2014_aarch64.whl", hash = "sha256:93bad12895d8b0ebc66b605c2ef1802311595f881aef032d9f13282b7550e6b2"},
588
+ + {file = "protobuf-3.18.1-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:0851b5b89191e1976d34fa2e8eb8659829dfb45252053224cf9df857fb5f6a45"},
589
+ + {file = "protobuf-3.18.1-cp38-cp38-win32.whl", hash = "sha256:09d9268f6f9da81b7657adcf2fb397524c82f20cdf9e0db3ff4e7567977abd67"},
590
+ + {file = "protobuf-3.18.1-cp38-cp38-win_amd64.whl", hash = "sha256:d6d927774c0ec746fed15a4faff5f44aad0b7a3421fadb6f3ae5ca1f2f8ae26e"},
591
+ + {file = "protobuf-3.18.1-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:4d19c9cb805fd2be1d59eee39e152367ee92a30167e77bd06c8819f8f0009a4c"},
592
+ + {file = "protobuf-3.18.1-cp39-cp39-manylinux2014_aarch64.whl", hash = "sha256:387f621bf7295a331f8c8a6962d097ceddeb85356792888cfa6a5c6bfc6886a4"},
593
+ + {file = "protobuf-3.18.1-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:8c1c5d3966c856f60a9d8d62f4455d70c31026422acdd5c228edf22b65b16c38"},
594
+ + {file = "protobuf-3.18.1-cp39-cp39-win32.whl", hash = "sha256:f20f803892f2135e8b96dc58c9a0c6a7ad8436794bf8784af229498d939b4c77"},
595
+ + {file = "protobuf-3.18.1-cp39-cp39-win_amd64.whl", hash = "sha256:d76201380f41a2d83fb613a4683059d1fcafbe969518b3e409e279a8788fde2f"},
596
+ + {file = "protobuf-3.18.1-py2.py3-none-any.whl", hash = "sha256:61ca58e14033ca0dfa484a31d57237c1be3b6013454c7f53876a20fc88dd69b1"},
597
+ + {file = "protobuf-3.18.1.tar.gz", hash = "sha256:1c9bb40503751087300dd12ce2e90899d68628977905c76effc48e66d089391e"},
598
+ ]
599
+ psutil = [
600
+ {file = "psutil-5.8.0-cp27-cp27m-macosx_10_9_x86_64.whl", hash = "sha256:0066a82f7b1b37d334e68697faba68e5ad5e858279fd6351c8ca6024e8d6ba64"},
601
+ @@ -4535,8 +4571,8 @@ pyflakes = [
602
+ {file = "pyflakes-2.3.1.tar.gz", hash = "sha256:f5bc8ecabc05bb9d291eb5203d6810b49040f6ff446a756326104746cc00c1db"},
603
+ ]
604
+ pyjwt = [
605
+ - {file = "PyJWT-2.1.0-py3-none-any.whl", hash = "sha256:934d73fbba91b0483d3857d1aff50e96b2a892384ee2c17417ed3203f173fca1"},
606
+ - {file = "PyJWT-2.1.0.tar.gz", hash = "sha256:fba44e7898bbca160a2b2b501f492824fc8382485d3a6f11ba5d0c1937ce6130"},
607
+ + {file = "PyJWT-2.2.0-py3-none-any.whl", hash = "sha256:b0ed5824c8ecc5362e540c65dc6247567db130c4226670bf7699aec92fb4dae1"},
608
+ + {file = "PyJWT-2.2.0.tar.gz", hash = "sha256:a0b9a3b4e5ca5517cac9f1a6e9cd30bf1aa80be74fcdf4e28eded582ecfcfbae"},
609
+ ]
610
+ pykwalify = [
611
+ {file = "pykwalify-1.8.0-py2.py3-none-any.whl", hash = "sha256:731dfa87338cca9f559d1fca2bdea37299116e3139b73f78ca90a543722d6651"},
612
+ @@ -4713,8 +4749,8 @@ python-socketio = [
613
+ {file = "python_socketio-5.4.0-py3-none-any.whl", hash = "sha256:7ed57f6c024abdfeb9b25c74c0c00ffc18da47d903e8d72deecb87584370d1fc"},
614
+ ]
615
+ pytz = [
616
+ - {file = "pytz-2021.1-py2.py3-none-any.whl", hash = "sha256:eb10ce3e7736052ed3623d49975ce333bcd712c7bb19a58b9e2089d4057d0798"},
617
+ - {file = "pytz-2021.1.tar.gz", hash = "sha256:83a4a90894bf38e243cf052c8b58f381bfe9a7a483f6a9cab140bc7f702ac4da"},
618
+ + {file = "pytz-2021.3-py2.py3-none-any.whl", hash = "sha256:3672058bc3453457b622aab7a1c3bfd5ab0bdae451512f6cf25f64ed37f5b87c"},
619
+ + {file = "pytz-2021.3.tar.gz", hash = "sha256:acad2d8b20a1af07d4e4c9d2e9285c5ed9104354062f275f3fcd88dcef4f1326"},
620
+ ]
621
+ pyyaml = [
622
+ {file = "PyYAML-5.4.1-cp27-cp27m-macosx_10_9_x86_64.whl", hash = "sha256:3b2b1824fe7112845700f815ff6a489360226a5609b96ec2190a45e62a9fc922"},
623
+ @@ -4768,6 +4804,10 @@ regex = [
624
+ {file = "regex-2021.7.6-cp36-cp36m-manylinux2014_i686.whl", hash = "sha256:b85ac458354165405c8a84725de7bbd07b00d9f72c31a60ffbf96bb38d3e25fa"},
625
+ {file = "regex-2021.7.6-cp36-cp36m-manylinux2014_x86_64.whl", hash = "sha256:3f5716923d3d0bfb27048242a6e0f14eecdb2e2a7fac47eda1d055288595f222"},
626
+ {file = "regex-2021.7.6-cp36-cp36m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:e5983c19d0beb6af88cb4d47afb92d96751fb3fa1784d8785b1cdf14c6519407"},
627
+ + {file = "regex-2021.7.6-cp36-cp36m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:bf1d2d183abc7faa101ebe0b8d04fd19cb9138820abc8589083035c9440b8ca6"},
628
+ + {file = "regex-2021.7.6-cp36-cp36m-manylinux_2_5_i686.manylinux1_i686.manylinux_2_12_i686.manylinux2010_i686.whl", hash = "sha256:1947e7de155063e1c495c50590229fb98720d4c383af5031bbcb413db33fa1be"},
629
+ + {file = "regex-2021.7.6-cp36-cp36m-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:17d8a3f99b18d87ac54a449b836d485cc8c195bb6f5e4379c84c8519045facc9"},
630
+ + {file = "regex-2021.7.6-cp36-cp36m-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:d30895ec80cc80358392841add9dde81ea1d54a4949049269115e6b0555d0498"},
631
+ {file = "regex-2021.7.6-cp36-cp36m-win32.whl", hash = "sha256:c92831dac113a6e0ab28bc98f33781383fe294df1a2c3dfd1e850114da35fd5b"},
632
+ {file = "regex-2021.7.6-cp36-cp36m-win_amd64.whl", hash = "sha256:791aa1b300e5b6e5d597c37c346fb4d66422178566bbb426dd87eaae475053fb"},
633
+ {file = "regex-2021.7.6-cp37-cp37m-macosx_10_9_x86_64.whl", hash = "sha256:59506c6e8bd9306cd8a41511e32d16d5d1194110b8cfe5a11d102d8b63cf945d"},
634
+ @@ -4778,6 +4818,10 @@ regex = [
635
+ {file = "regex-2021.7.6-cp37-cp37m-manylinux2014_i686.whl", hash = "sha256:173bc44ff95bc1e96398c38f3629d86fa72e539c79900283afa895694229fe6a"},
636
+ {file = "regex-2021.7.6-cp37-cp37m-manylinux2014_x86_64.whl", hash = "sha256:15dddb19823f5147e7517bb12635b3c82e6f2a3a6b696cc3e321522e8b9308ad"},
637
+ {file = "regex-2021.7.6-cp37-cp37m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:2ddeabc7652024803666ea09f32dd1ed40a0579b6fbb2a213eba590683025895"},
638
+ + {file = "regex-2021.7.6-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:8244c681018423a0d1784bc6b9af33bdf55f2ab8acb1f3cd9dd83d90e0813253"},
639
+ + {file = "regex-2021.7.6-cp37-cp37m-manylinux_2_5_i686.manylinux1_i686.manylinux_2_12_i686.manylinux2010_i686.whl", hash = "sha256:8a4c742089faf0e51469c6a1ad7e3d3d21afae54a16a6cead85209dfe0a1ce65"},
640
+ + {file = "regex-2021.7.6-cp37-cp37m-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:914e626dc8e75fe4fc9b7214763f141d9f40165d00dfe680b104fa1b24063bbf"},
641
+ + {file = "regex-2021.7.6-cp37-cp37m-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:3fabb19c82ecf39832a3f5060dfea9a7ab270ef156039a1143a29a83a09a62de"},
642
+ {file = "regex-2021.7.6-cp37-cp37m-win32.whl", hash = "sha256:f080248b3e029d052bf74a897b9d74cfb7643537fbde97fe8225a6467fb559b5"},
643
+ {file = "regex-2021.7.6-cp37-cp37m-win_amd64.whl", hash = "sha256:d8bbce0c96462dbceaa7ac4a7dfbbee92745b801b24bce10a98d2f2b1ea9432f"},
644
+ {file = "regex-2021.7.6-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:edd1a68f79b89b0c57339bce297ad5d5ffcc6ae7e1afdb10f1947706ed066c9c"},
645
+ @@ -4788,6 +4832,10 @@ regex = [
646
+ {file = "regex-2021.7.6-cp38-cp38-manylinux2014_i686.whl", hash = "sha256:bc84fb254a875a9f66616ed4538542fb7965db6356f3df571d783f7c8d256edd"},
647
+ {file = "regex-2021.7.6-cp38-cp38-manylinux2014_x86_64.whl", hash = "sha256:598c0a79b4b851b922f504f9f39a863d83ebdfff787261a5ed061c21e67dd761"},
648
+ {file = "regex-2021.7.6-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:875c355360d0f8d3d827e462b29ea7682bf52327d500a4f837e934e9e4656068"},
649
+ + {file = "regex-2021.7.6-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:dfc0957c4a4b91eff5ad036088769e600a25774256cd0e1154378591ce573f08"},
650
+ + {file = "regex-2021.7.6-cp38-cp38-manylinux_2_5_i686.manylinux1_i686.manylinux_2_12_i686.manylinux2010_i686.whl", hash = "sha256:efb4af05fa4d2fc29766bf516f1f5098d6b5c3ed846fde980c18bf8646ad3979"},
651
+ + {file = "regex-2021.7.6-cp38-cp38-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:7423aca7cc30a6228ccdcf2ea76f12923d652c5c7c6dc1959a0b004e308f39fb"},
652
+ + {file = "regex-2021.7.6-cp38-cp38-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:bb9834c1e77493efd7343b8e38950dee9797d2d6f2d5fd91c008dfaef64684b9"},
653
+ {file = "regex-2021.7.6-cp38-cp38-win32.whl", hash = "sha256:e586f448df2bbc37dfadccdb7ccd125c62b4348cb90c10840d695592aa1b29e0"},
654
+ {file = "regex-2021.7.6-cp38-cp38-win_amd64.whl", hash = "sha256:2fe5e71e11a54e3355fa272137d521a40aace5d937d08b494bed4529964c19c4"},
655
+ {file = "regex-2021.7.6-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:6110bab7eab6566492618540c70edd4d2a18f40ca1d51d704f1d81c52d245026"},
656
+ @@ -4798,6 +4846,10 @@ regex = [
657
+ {file = "regex-2021.7.6-cp39-cp39-manylinux2014_i686.whl", hash = "sha256:2bceeb491b38225b1fee4517107b8491ba54fba77cf22a12e996d96a3c55613d"},
658
+ {file = "regex-2021.7.6-cp39-cp39-manylinux2014_x86_64.whl", hash = "sha256:f98dc35ab9a749276f1a4a38ab3e0e2ba1662ce710f6530f5b0a6656f1c32b58"},
659
+ {file = "regex-2021.7.6-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:319eb2a8d0888fa6f1d9177705f341bc9455a2c8aca130016e52c7fe8d6c37a3"},
660
+ + {file = "regex-2021.7.6-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:598ee917dbe961dcf827217bf2466bb86e4ee5a8559705af57cbabb3489dd37e"},
661
+ + {file = "regex-2021.7.6-cp39-cp39-manylinux_2_5_i686.manylinux1_i686.manylinux_2_12_i686.manylinux2010_i686.whl", hash = "sha256:56fc7045a1999a8d9dd1896715bc5c802dfec5b9b60e883d2cbdecb42adedea4"},
662
+ + {file = "regex-2021.7.6-cp39-cp39-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:e8363ac90ea63c3dd0872dfdb695f38aff3334bfa5712cffb238bd3ffef300e3"},
663
+ + {file = "regex-2021.7.6-cp39-cp39-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:716a6db91b3641f566531ffcc03ceec00b2447f0db9942b3c6ea5d2827ad6be3"},
664
+ {file = "regex-2021.7.6-cp39-cp39-win32.whl", hash = "sha256:eaf58b9e30e0e546cdc3ac06cf9165a1ca5b3de8221e9df679416ca667972035"},
665
+ {file = "regex-2021.7.6-cp39-cp39-win_amd64.whl", hash = "sha256:4c9c3155fe74269f61e27617529b7f09552fbb12e44b1189cebbdb24294e6e1c"},
666
+ {file = "regex-2021.7.6.tar.gz", hash = "sha256:8394e266005f2d8c6f0bc6780001f7afa3ef81a7a2111fa35058ded6fce79e4d"},
667
+ @@ -5100,6 +5152,10 @@ tabulate = [
668
+ {file = "tabulate-0.8.9-py3-none-any.whl", hash = "sha256:d7c013fe7abbc5e491394e10fa845f8f32fe54f8dc60c6622c6cf482d25d47e4"},
669
+ {file = "tabulate-0.8.9.tar.gz", hash = "sha256:eb1d13f25760052e8931f2ef80aaf6045a6cceb47514db8beab24cded16f13a7"},
670
+ ]
671
+ +tarsafe = [
672
+ + {file = "tarsafe-0.0.3-py3-none-any.whl", hash = "sha256:f8181c5559aea70af2579a0dc0811d2e9e3eabd706dd594555b4dfa52c0be51a"},
673
+ + {file = "tarsafe-0.0.3.tar.gz", hash = "sha256:7acf73a11b576fcbb003b52adecf4706d6c3009c6af28a01fd21949235ffd806"},
674
+ +]
675
+ tensorboard = [
676
+ {file = "tensorboard-2.6.0-py3-none-any.whl", hash = "sha256:f7dac4cdfb52d14c9e3f74585ce2aaf8e6203620a864e51faf84988b09f7bbdb"},
677
+ ]
678
+ @@ -5184,8 +5240,8 @@ thinc = [
679
+ {file = "thinc-8.0.10.tar.gz", hash = "sha256:b5e4db8d24e6be8a5f1e4a17854772b79a2b560224519f50a21f3951ca24001f"},
680
+ ]
681
+ threadpoolctl = [
682
+ - {file = "threadpoolctl-2.2.0-py3-none-any.whl", hash = "sha256:e5a995e3ffae202758fa8a90082e35783b9370699627ae2733cd1c3a73553616"},
683
+ - {file = "threadpoolctl-2.2.0.tar.gz", hash = "sha256:86d4b6801456d780e94681d155779058759eaef3c3564758b17b6c99db5f81cb"},
684
+ + {file = "threadpoolctl-3.0.0-py3-none-any.whl", hash = "sha256:4fade5b3b48ae4b1c30f200b28f39180371104fccc642e039e0f2435ec8cc211"},
685
+ + {file = "threadpoolctl-3.0.0.tar.gz", hash = "sha256:d03115321233d0be715f0d3a5ad1d6c065fe425ddc2d671ca8e45e9fd5d7a52a"},
686
+ ]
687
+ tokenizers = [
688
+ {file = "tokenizers-0.7.0-cp35-cp35m-macosx_10_10_x86_64.whl", hash = "sha256:c9edc043bc14462faf8b261b528661718e9c4f0b8424fb25be71cae26187432a"},
689
+ @@ -5258,8 +5314,8 @@ typed-ast = [
690
+ {file = "typed_ast-1.4.3.tar.gz", hash = "sha256:fb1bbeac803adea29cedd70781399c99138358c26d05fcbd23c13016b7f5ec65"},
691
+ ]
692
+ typeguard = [
693
+ - {file = "typeguard-2.12.1-py3-none-any.whl", hash = "sha256:cc15ef2704c9909ef9c80e19c62fb8468c01f75aad12f651922acf4dbe822e02"},
694
+ - {file = "typeguard-2.12.1.tar.gz", hash = "sha256:c2af8b9bdd7657f4bd27b45336e7930171aead796711bc4cfc99b4731bb9d051"},
695
+ + {file = "typeguard-2.13.0-py3-none-any.whl", hash = "sha256:0bc44d1ff865b522eda969627868b0e001c8329296ce50aededbea03febc79ee"},
696
+ + {file = "typeguard-2.13.0.tar.gz", hash = "sha256:04e38f92eb59410c9375d3be23df65e0a7643f2e8bcbd421423d808d2f9e99df"},
697
+ ]
698
+ typer = [
699
+ {file = "typer-0.4.0-py3-none-any.whl", hash = "sha256:d81169725140423d072df464cad1ff25ee154ef381aaf5b8225352ea187ca338"},
700
+ @@ -5341,8 +5397,8 @@ ujson = [
701
+ {file = "ujson-4.2.0.tar.gz", hash = "sha256:fffe509f556861c7343c6cba57ed05fe7bcf4b48a934a5b946ccb45428cf8883"},
702
+ ]
703
+ uritemplate = [
704
+ - {file = "uritemplate-3.0.1-py2.py3-none-any.whl", hash = "sha256:07620c3f3f8eed1f12600845892b0e036a2420acf513c53f7de0abd911a5894f"},
705
+ - {file = "uritemplate-3.0.1.tar.gz", hash = "sha256:5af8ad10cec94f215e3f48112de2022e1d5a37ed427fbd88652fa908f2ab7cae"},
706
+ + {file = "uritemplate-4.0.0-py2.py3-none-any.whl", hash = "sha256:9de62e39c3f7f7584982a4159d70e6aafda5a479a91cccc18e89ae865eab4ae4"},
707
+ + {file = "uritemplate-4.0.0.tar.gz", hash = "sha256:6f4c5b093c915d269df69f291028a72dfdcaf68c8345b92e180f31daf53c4971"},
708
+ ]
709
+ urllib3 = [
710
+ {file = "urllib3-1.26.7-py2.py3-none-any.whl", hash = "sha256:c4fdf4019605b6e5423637e01bc9fe4daef873709a7973e195ceba0a62bbc844"},
711
+ @@ -5404,8 +5460,8 @@ websockets = [
712
+ {file = "websockets-8.0.2.tar.gz", hash = "sha256:882a7266fa867a2ebb2c0baaa0f9159cabf131cf18c1b4270d79ad42f9208dc5"},
713
+ ]
714
+ werkzeug = [
715
+ - {file = "Werkzeug-2.0.1-py3-none-any.whl", hash = "sha256:6c1ec500dcdba0baa27600f6a22f6333d8b662d22027ff9f6202e3367413caa8"},
716
+ - {file = "Werkzeug-2.0.1.tar.gz", hash = "sha256:1de1db30d010ff1af14a009224ec49ab2329ad2cde454c8a708130642d579c42"},
717
+ + {file = "Werkzeug-2.0.2-py3-none-any.whl", hash = "sha256:63d3dc1cf60e7b7e35e97fa9861f7397283b75d765afcaefd993d6046899de8f"},
718
+ + {file = "Werkzeug-2.0.2.tar.gz", hash = "sha256:aa2bb6fc8dee8d6c504c0ac1e7f5f7dc5810a9903e793b6f715a9f015bdadb9a"},
719
+ ]
720
+ wrapt = [
721
+ {file = "wrapt-1.12.1.tar.gz", hash = "sha256:b62ffa81fb85f4332a4f609cab4ac40709470da05643a082ec1eb88e6d9b97d7"},
722
+ @@ -5415,43 +5471,78 @@ xmltodict = [
723
+ {file = "xmltodict-0.12.0.tar.gz", hash = "sha256:50d8c638ed7ecb88d90561beedbf720c9b4e851a9fa6c47ebd64e99d166d8a21"},
724
+ ]
725
+ yarl = [
726
+ - {file = "yarl-1.6.3-cp36-cp36m-macosx_10_14_x86_64.whl", hash = "sha256:0355a701b3998dcd832d0dc47cc5dedf3874f966ac7f870e0f3a6788d802d434"},
727
+ - {file = "yarl-1.6.3-cp36-cp36m-manylinux1_i686.whl", hash = "sha256:bafb450deef6861815ed579c7a6113a879a6ef58aed4c3a4be54400ae8871478"},
728
+ - {file = "yarl-1.6.3-cp36-cp36m-manylinux2014_aarch64.whl", hash = "sha256:547f7665ad50fa8563150ed079f8e805e63dd85def6674c97efd78eed6c224a6"},
729
+ - {file = "yarl-1.6.3-cp36-cp36m-manylinux2014_i686.whl", hash = "sha256:63f90b20ca654b3ecc7a8d62c03ffa46999595f0167d6450fa8383bab252987e"},
730
+ - {file = "yarl-1.6.3-cp36-cp36m-manylinux2014_ppc64le.whl", hash = "sha256:97b5bdc450d63c3ba30a127d018b866ea94e65655efaf889ebeabc20f7d12406"},
731
+ - {file = "yarl-1.6.3-cp36-cp36m-manylinux2014_s390x.whl", hash = "sha256:d8d07d102f17b68966e2de0e07bfd6e139c7c02ef06d3a0f8d2f0f055e13bb76"},
732
+ - {file = "yarl-1.6.3-cp36-cp36m-manylinux2014_x86_64.whl", hash = "sha256:15263c3b0b47968c1d90daa89f21fcc889bb4b1aac5555580d74565de6836366"},
733
+ - {file = "yarl-1.6.3-cp36-cp36m-win32.whl", hash = "sha256:b5dfc9a40c198334f4f3f55880ecf910adebdcb2a0b9a9c23c9345faa9185721"},
734
+ - {file = "yarl-1.6.3-cp36-cp36m-win_amd64.whl", hash = "sha256:b2e9a456c121e26d13c29251f8267541bd75e6a1ccf9e859179701c36a078643"},
735
+ - {file = "yarl-1.6.3-cp37-cp37m-macosx_10_14_x86_64.whl", hash = "sha256:ce3beb46a72d9f2190f9e1027886bfc513702d748047b548b05dab7dfb584d2e"},
736
+ - {file = "yarl-1.6.3-cp37-cp37m-manylinux1_i686.whl", hash = "sha256:2ce4c621d21326a4a5500c25031e102af589edb50c09b321049e388b3934eec3"},
737
+ - {file = "yarl-1.6.3-cp37-cp37m-manylinux2014_aarch64.whl", hash = "sha256:d26608cf178efb8faa5ff0f2d2e77c208f471c5a3709e577a7b3fd0445703ac8"},
738
+ - {file = "yarl-1.6.3-cp37-cp37m-manylinux2014_i686.whl", hash = "sha256:4c5bcfc3ed226bf6419f7a33982fb4b8ec2e45785a0561eb99274ebbf09fdd6a"},
739
+ - {file = "yarl-1.6.3-cp37-cp37m-manylinux2014_ppc64le.whl", hash = "sha256:4736eaee5626db8d9cda9eb5282028cc834e2aeb194e0d8b50217d707e98bb5c"},
740
+ - {file = "yarl-1.6.3-cp37-cp37m-manylinux2014_s390x.whl", hash = "sha256:68dc568889b1c13f1e4745c96b931cc94fdd0defe92a72c2b8ce01091b22e35f"},
741
+ - {file = "yarl-1.6.3-cp37-cp37m-manylinux2014_x86_64.whl", hash = "sha256:7356644cbed76119d0b6bd32ffba704d30d747e0c217109d7979a7bc36c4d970"},
742
+ - {file = "yarl-1.6.3-cp37-cp37m-win32.whl", hash = "sha256:00d7ad91b6583602eb9c1d085a2cf281ada267e9a197e8b7cae487dadbfa293e"},
743
+ - {file = "yarl-1.6.3-cp37-cp37m-win_amd64.whl", hash = "sha256:69ee97c71fee1f63d04c945f56d5d726483c4762845400a6795a3b75d56b6c50"},
744
+ - {file = "yarl-1.6.3-cp38-cp38-macosx_10_14_x86_64.whl", hash = "sha256:e46fba844f4895b36f4c398c5af062a9808d1f26b2999c58909517384d5deda2"},
745
+ - {file = "yarl-1.6.3-cp38-cp38-manylinux1_i686.whl", hash = "sha256:31ede6e8c4329fb81c86706ba8f6bf661a924b53ba191b27aa5fcee5714d18ec"},
746
+ - {file = "yarl-1.6.3-cp38-cp38-manylinux2014_aarch64.whl", hash = "sha256:fcbb48a93e8699eae920f8d92f7160c03567b421bc17362a9ffbbd706a816f71"},
747
+ - {file = "yarl-1.6.3-cp38-cp38-manylinux2014_i686.whl", hash = "sha256:72a660bdd24497e3e84f5519e57a9ee9220b6f3ac4d45056961bf22838ce20cc"},
748
+ - {file = "yarl-1.6.3-cp38-cp38-manylinux2014_ppc64le.whl", hash = "sha256:324ba3d3c6fee56e2e0b0d09bf5c73824b9f08234339d2b788af65e60040c959"},
749
+ - {file = "yarl-1.6.3-cp38-cp38-manylinux2014_s390x.whl", hash = "sha256:e6b5460dc5ad42ad2b36cca524491dfcaffbfd9c8df50508bddc354e787b8dc2"},
750
+ - {file = "yarl-1.6.3-cp38-cp38-manylinux2014_x86_64.whl", hash = "sha256:6d6283d8e0631b617edf0fd726353cb76630b83a089a40933043894e7f6721e2"},
751
+ - {file = "yarl-1.6.3-cp38-cp38-win32.whl", hash = "sha256:9ede61b0854e267fd565e7527e2f2eb3ef8858b301319be0604177690e1a3896"},
752
+ - {file = "yarl-1.6.3-cp38-cp38-win_amd64.whl", hash = "sha256:f0b059678fd549c66b89bed03efcabb009075bd131c248ecdf087bdb6faba24a"},
753
+ - {file = "yarl-1.6.3-cp39-cp39-macosx_10_14_x86_64.whl", hash = "sha256:329412812ecfc94a57cd37c9d547579510a9e83c516bc069470db5f75684629e"},
754
+ - {file = "yarl-1.6.3-cp39-cp39-manylinux1_i686.whl", hash = "sha256:c49ff66d479d38ab863c50f7bb27dee97c6627c5fe60697de15529da9c3de724"},
755
+ - {file = "yarl-1.6.3-cp39-cp39-manylinux2014_aarch64.whl", hash = "sha256:f040bcc6725c821a4c0665f3aa96a4d0805a7aaf2caf266d256b8ed71b9f041c"},
756
+ - {file = "yarl-1.6.3-cp39-cp39-manylinux2014_i686.whl", hash = "sha256:d5c32c82990e4ac4d8150fd7652b972216b204de4e83a122546dce571c1bdf25"},
757
+ - {file = "yarl-1.6.3-cp39-cp39-manylinux2014_ppc64le.whl", hash = "sha256:d597767fcd2c3dc49d6eea360c458b65643d1e4dbed91361cf5e36e53c1f8c96"},
758
+ - {file = "yarl-1.6.3-cp39-cp39-manylinux2014_s390x.whl", hash = "sha256:8aa3decd5e0e852dc68335abf5478a518b41bf2ab2f330fe44916399efedfae0"},
759
+ - {file = "yarl-1.6.3-cp39-cp39-manylinux2014_x86_64.whl", hash = "sha256:73494d5b71099ae8cb8754f1df131c11d433b387efab7b51849e7e1e851f07a4"},
760
+ - {file = "yarl-1.6.3-cp39-cp39-win32.whl", hash = "sha256:5b883e458058f8d6099e4420f0cc2567989032b5f34b271c0827de9f1079a424"},
761
+ - {file = "yarl-1.6.3-cp39-cp39-win_amd64.whl", hash = "sha256:4953fb0b4fdb7e08b2f3b3be80a00d28c5c8a2056bb066169de00e6501b986b6"},
762
+ - {file = "yarl-1.6.3.tar.gz", hash = "sha256:8a9066529240171b68893d60dca86a763eae2139dd42f42106b03cf4b426bf10"},
763
+ + {file = "yarl-1.7.0-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:e35d8230e4b08d86ea65c32450533b906a8267a87b873f2954adeaecede85169"},
764
+ + {file = "yarl-1.7.0-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:eb4b3f277880c314e47720b4b6bb2c85114ab3c04c5442c9bc7006b3787904d8"},
765
+ + {file = "yarl-1.7.0-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:c7015dcedb91d90a138eebdc7e432aec8966e0147ab2a55f2df27b1904fa7291"},
766
+ + {file = "yarl-1.7.0-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:bb3e478175e15e00d659fb0354a6a8db71a7811a2a5052aed98048bc972e5d2b"},
767
+ + {file = "yarl-1.7.0-cp310-cp310-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:8b8c409aa3a7966647e7c1c524846b362a6bcbbe120bf8a176431f940d2b9a2e"},
768
+ + {file = "yarl-1.7.0-cp310-cp310-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:b22ea41c7e98170474a01e3eded1377d46b2dfaef45888a0005c683eaaa49285"},
769
+ + {file = "yarl-1.7.0-cp310-cp310-manylinux_2_5_i686.manylinux1_i686.manylinux_2_12_i686.manylinux2010_i686.whl", hash = "sha256:a7dfc46add4cfe5578013dbc4127893edc69fe19132d2836ff2f6e49edc5ecd6"},
770
+ + {file = "yarl-1.7.0-cp310-cp310-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:82ff6f85f67500a4f74885d81659cd270eb24dfe692fe44e622b8a2fd57e7279"},
771
+ + {file = "yarl-1.7.0-cp310-cp310-musllinux_1_1_aarch64.whl", hash = "sha256:f3cd2158b2ed0fb25c6811adfdcc47224efe075f2d68a750071dacc03a7a66e4"},
772
+ + {file = "yarl-1.7.0-cp310-cp310-musllinux_1_1_i686.whl", hash = "sha256:59c0f13f9592820c51280d1cf811294d753e4a18baf90f0139d1dc93d4b6fc5f"},
773
+ + {file = "yarl-1.7.0-cp310-cp310-musllinux_1_1_ppc64le.whl", hash = "sha256:7f7655ad83d1a8afa48435a449bf2f3009293da1604f5dd95b5ddcf5f673bd69"},
774
+ + {file = "yarl-1.7.0-cp310-cp310-musllinux_1_1_s390x.whl", hash = "sha256:aa9f0d9b62d15182341b3e9816582f46182cab91c1a57b2d308b9a3c4e2c4f78"},
775
+ + {file = "yarl-1.7.0-cp310-cp310-musllinux_1_1_x86_64.whl", hash = "sha256:fdd1b90c225a653b1bd1c0cae8edf1957892b9a09c8bf7ee6321eeb8208eac0f"},
776
+ + {file = "yarl-1.7.0-cp310-cp310-win32.whl", hash = "sha256:7c8d0bb76eabc5299db203e952ec55f8f4c53f08e0df4285aac8c92bd9e12675"},
777
+ + {file = "yarl-1.7.0-cp310-cp310-win_amd64.whl", hash = "sha256:622a36fa779efb4ff9eff5fe52730ff17521431379851a31e040958fc251670c"},
778
+ + {file = "yarl-1.7.0-cp36-cp36m-macosx_10_9_x86_64.whl", hash = "sha256:3d461b7a8e139b9e4b41f62eb417ffa0b98d1c46d4caf14c845e6a3b349c0bb1"},
779
+ + {file = "yarl-1.7.0-cp36-cp36m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:81cfacdd1e40bc931b5519499342efa388d24d262c30a3d31187bfa04f4a7001"},
780
+ + {file = "yarl-1.7.0-cp36-cp36m-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:821b978f2152be7695d4331ef0621d207aedf9bbd591ba23a63412a3efc29a01"},
781
+ + {file = "yarl-1.7.0-cp36-cp36m-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:b64bd24c8c9a487f4a12260dc26732bf41028816dbf0c458f17864fbebdb3131"},
782
+ + {file = "yarl-1.7.0-cp36-cp36m-manylinux_2_5_i686.manylinux1_i686.manylinux_2_12_i686.manylinux2010_i686.whl", hash = "sha256:98c9ddb92b60a83c21be42c776d3d9d5ec632a762a094c41bda37b7dfbd2cd83"},
783
+ + {file = "yarl-1.7.0-cp36-cp36m-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:a532d75ca74431c053a88a802e161fb3d651b8bf5821a3440bc3616e38754583"},
784
+ + {file = "yarl-1.7.0-cp36-cp36m-musllinux_1_1_aarch64.whl", hash = "sha256:053e09817eafb892e94e172d05406c1b3a22a93bc68f6eff5198363a3d764459"},
785
+ + {file = "yarl-1.7.0-cp36-cp36m-musllinux_1_1_i686.whl", hash = "sha256:98c51f02d542945d306c8e934aa2c1e66ba5e9c1c86b5bf37f3a51c8a747067e"},
786
+ + {file = "yarl-1.7.0-cp36-cp36m-musllinux_1_1_ppc64le.whl", hash = "sha256:15ec41a5a5fdb7bace6d7b16701f9440007a82734f69127c0fbf6d87e10f4a1e"},
787
+ + {file = "yarl-1.7.0-cp36-cp36m-musllinux_1_1_s390x.whl", hash = "sha256:a7f08819dba1e1255d6991ed37448a1bf4b1352c004bcd899b9da0c47958513d"},
788
+ + {file = "yarl-1.7.0-cp36-cp36m-musllinux_1_1_x86_64.whl", hash = "sha256:8e3ffab21db0542ffd1887f3b9575ddd58961f2cf61429cb6458afc00c4581e0"},
789
+ + {file = "yarl-1.7.0-cp36-cp36m-win32.whl", hash = "sha256:50127634f519b2956005891507e3aa4ac345f66a7ea7bbc2d7dcba7401f41898"},
790
+ + {file = "yarl-1.7.0-cp36-cp36m-win_amd64.whl", hash = "sha256:36ec44f15193f6d5288d42ebb8e751b967ebdfb72d6830983838d45ab18edb4f"},
791
+ + {file = "yarl-1.7.0-cp37-cp37m-macosx_10_9_x86_64.whl", hash = "sha256:ec1b5a25a25c880c976d0bb3d107def085bb08dbb3db7f4442e0a2b980359d24"},
792
+ + {file = "yarl-1.7.0-cp37-cp37m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:b36f5a63c891f813c6f04ef19675b382efc190fd5ce7e10ab19386d2548bca06"},
793
+ + {file = "yarl-1.7.0-cp37-cp37m-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:38173b8c3a29945e7ecade9a3f6ff39581eee8201338ee6a2c8882db5df3e806"},
794
+ + {file = "yarl-1.7.0-cp37-cp37m-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:8ba402f32184f0b405fb281b93bd0d8ab7e3257735b57b62a6ed2e94cdf4fe50"},
795
+ + {file = "yarl-1.7.0-cp37-cp37m-manylinux_2_5_i686.manylinux1_i686.manylinux_2_12_i686.manylinux2010_i686.whl", hash = "sha256:be52bc5208d767cdd8308a9e93059b3b36d1e048fecbea0e0346d0d24a76adc0"},
796
+ + {file = "yarl-1.7.0-cp37-cp37m-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:08c2044a956f4ef30405f2f433ce77f1f57c2c773bf81ae43201917831044d5a"},
797
+ + {file = "yarl-1.7.0-cp37-cp37m-musllinux_1_1_aarch64.whl", hash = "sha256:484d61c047c45670ef5967653a1d0783e232c54bf9dd786a7737036828fa8d54"},
798
+ + {file = "yarl-1.7.0-cp37-cp37m-musllinux_1_1_i686.whl", hash = "sha256:b7de92a4af85cfcaf4081f8aa6165b1d63ee5de150af3ee85f954145f93105a7"},
799
+ + {file = "yarl-1.7.0-cp37-cp37m-musllinux_1_1_ppc64le.whl", hash = "sha256:376e41775aab79c5575534924a386c8e0f1a5d91db69fc6133fd27a489bcaf10"},
800
+ + {file = "yarl-1.7.0-cp37-cp37m-musllinux_1_1_s390x.whl", hash = "sha256:8a8b10d0e7bac154f959b709fcea593cda527b234119311eb950096653816a86"},
801
+ + {file = "yarl-1.7.0-cp37-cp37m-musllinux_1_1_x86_64.whl", hash = "sha256:f46cd4c43e6175030e2a56def8f1d83b64e6706eeb2bb9ab0ef4756f65eab23f"},
802
+ + {file = "yarl-1.7.0-cp37-cp37m-win32.whl", hash = "sha256:b28cfb46140efe1a6092b8c5c4994a1fe70dc83c38fbcea4992401e0c6fb9cce"},
803
+ + {file = "yarl-1.7.0-cp37-cp37m-win_amd64.whl", hash = "sha256:9624154ec9c02a776802da1086eed7f5034bd1971977f5146233869c2ac80297"},
804
+ + {file = "yarl-1.7.0-cp38-cp38-macosx_10_9_universal2.whl", hash = "sha256:69945d13e1bbf81784a9bc48824feb9cd66491e6a503d4e83f6cd7c7cc861361"},
805
+ + {file = "yarl-1.7.0-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:46a742ed9e363bd01be64160ce7520e92e11989bd4cb224403cfd31c101cc83d"},
806
+ + {file = "yarl-1.7.0-cp38-cp38-macosx_11_0_arm64.whl", hash = "sha256:cb4ff1ac7cb4500f43581b3f4cbd627d702143aa6be1fdc1fa3ebffaf4dc1be5"},
807
+ + {file = "yarl-1.7.0-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:3ad51e17cd65ea3debb0e10f0120cf8dd987c741fe423ed2285087368090b33d"},
808
+ + {file = "yarl-1.7.0-cp38-cp38-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:7e37786ea89a5d3ffbbf318ea9790926f8dfda83858544f128553c347ad143c6"},
809
+ + {file = "yarl-1.7.0-cp38-cp38-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:c63c1e208f800daad71715786bfeb1cecdc595d87e2e9b1cd234fd6e597fd71d"},
810
+ + {file = "yarl-1.7.0-cp38-cp38-manylinux_2_5_i686.manylinux1_i686.manylinux_2_12_i686.manylinux2010_i686.whl", hash = "sha256:91cbe24300c11835ef186436363352b3257db7af165e0a767f4f17aa25761388"},
811
+ + {file = "yarl-1.7.0-cp38-cp38-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:e510dbec7c59d32eaa61ffa48173d5e3d7170a67f4a03e8f5e2e9e3971aca622"},
812
+ + {file = "yarl-1.7.0-cp38-cp38-musllinux_1_1_aarch64.whl", hash = "sha256:3def6e681cc02397e5d8141ee97b41d02932b2bcf0fb34532ad62855eab7c60e"},
813
+ + {file = "yarl-1.7.0-cp38-cp38-musllinux_1_1_i686.whl", hash = "sha256:263c81b94e6431942b27f6f671fa62f430a0a5c14bb255f2ab69eeb9b2b66ff7"},
814
+ + {file = "yarl-1.7.0-cp38-cp38-musllinux_1_1_ppc64le.whl", hash = "sha256:e78c91faefe88d601ddd16e3882918dbde20577a2438e2320f8239c8b7507b8f"},
815
+ + {file = "yarl-1.7.0-cp38-cp38-musllinux_1_1_s390x.whl", hash = "sha256:22b2430c49713bfb2f0a0dd4a8d7aab218b28476ba86fd1c78ad8899462cbcf2"},
816
+ + {file = "yarl-1.7.0-cp38-cp38-musllinux_1_1_x86_64.whl", hash = "sha256:2e7ad9db939082f5d0b9269cfd92c025cb8f2fbbb1f1b9dc5a393c639db5bd92"},
817
+ + {file = "yarl-1.7.0-cp38-cp38-win32.whl", hash = "sha256:3a31e4a8dcb1beaf167b7e7af61b88cb961b220db8d3ba1c839723630e57eef7"},
818
+ + {file = "yarl-1.7.0-cp38-cp38-win_amd64.whl", hash = "sha256:d579957439933d752358c6a300c93110f84aae67b63dd0c19dde6ecbf4056f6b"},
819
+ + {file = "yarl-1.7.0-cp39-cp39-macosx_10_9_universal2.whl", hash = "sha256:87721b549505a546eb003252185103b5ec8147de6d3ad3714d148a5a67b6fe53"},
820
+ + {file = "yarl-1.7.0-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:a1fa866fa24d9f4108f9e58ea8a2135655419885cdb443e36b39a346e1181532"},
821
+ + {file = "yarl-1.7.0-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:1d3b8449dfedfe94eaff2b77954258b09b24949f6818dfa444b05dbb05ae1b7e"},
822
+ + {file = "yarl-1.7.0-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:db2372e350794ce8b9f810feb094c606b7e0e4aa6807141ac4fadfe5ddd75bb0"},
823
+ + {file = "yarl-1.7.0-cp39-cp39-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:a06d9d0b9a97fa99b84fee71d9dd11e69e21ac8a27229089f07b5e5e50e8d63c"},
824
+ + {file = "yarl-1.7.0-cp39-cp39-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:a3455c2456d6307bcfa80bc1157b8603f7d93573291f5bdc7144489ca0df4628"},
825
+ + {file = "yarl-1.7.0-cp39-cp39-manylinux_2_5_i686.manylinux1_i686.manylinux_2_12_i686.manylinux2010_i686.whl", hash = "sha256:d30d67e3486aea61bb2cbf7cf81385364c2e4f7ce7469a76ed72af76a5cdfe6b"},
826
+ + {file = "yarl-1.7.0-cp39-cp39-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:c18a4b286e8d780c3a40c31d7b79836aa93b720f71d5743f20c08b7e049ca073"},
827
+ + {file = "yarl-1.7.0-cp39-cp39-musllinux_1_1_aarch64.whl", hash = "sha256:d54c925396e7891666cabc0199366ca55b27d003393465acef63fd29b8b7aa92"},
828
+ + {file = "yarl-1.7.0-cp39-cp39-musllinux_1_1_i686.whl", hash = "sha256:64773840952de17851a1c7346ad7f71688c77e74248d1f0bc230e96680f84028"},
829
+ + {file = "yarl-1.7.0-cp39-cp39-musllinux_1_1_ppc64le.whl", hash = "sha256:acbf1756d9dc7cd0ae943d883be72e84e04396f6c2ff93a6ddeca929d562039f"},
830
+ + {file = "yarl-1.7.0-cp39-cp39-musllinux_1_1_s390x.whl", hash = "sha256:2e48f27936aa838939c798f466c851ba4ae79e347e8dfce43b009c64b930df12"},
831
+ + {file = "yarl-1.7.0-cp39-cp39-musllinux_1_1_x86_64.whl", hash = "sha256:1beef4734ca1ad40a9d8c6b20a76ab46e3a2ed09f38561f01e4aa2ea82cafcef"},
832
+ + {file = "yarl-1.7.0-cp39-cp39-win32.whl", hash = "sha256:8ee78c9a5f3c642219d4607680a4693b59239c27a3aa608b64ef79ddc9698039"},
833
+ + {file = "yarl-1.7.0-cp39-cp39-win_amd64.whl", hash = "sha256:d750503682605088a14d29a4701548c15c510da4f13c8b17409c4097d5b04c52"},
834
+ + {file = "yarl-1.7.0.tar.gz", hash = "sha256:8e7ebaf62e19c2feb097ffb7c94deb0f0c9fab52590784c8cd679d30ab009162"},
835
+ ]
836
+ zipp = [
837
+ {file = "zipp-3.6.0-py3-none-any.whl", hash = "sha256:9fe5ea21568a0a70e50f273397638d39b03353731e6cbbb3fd8502a33fec40bc"},
838
+ diff --git a/pyproject.toml b/pyproject.toml
839
+ index 69364c5f6e5..0be486aa0e9 100644
840
+ --- a/pyproject.toml
841
+ +++ b/pyproject.toml
842
+ @@ -122,6 +122,7 @@ joblib = ">=0.15.1,<1.1.0"
843
+ sentry-sdk = ">=0.17.0,<1.3.0"
844
+ aio-pika = "^6.7.1"
845
+ pyTelegramBotAPI = "^3.7.3"
846
+ +tarsafe = "^0.0.3"
847
+
848
+ [tool.poetry.dev-dependencies]
849
+ pytest-cov = "^2.10.0"
850
+ diff --git a/rasa/model.py b/rasa/model.py
851
+ index 78be4034060..21ff2b14de0 100644
852
+ --- a/rasa/model.py
853
+ +++ b/rasa/model.py
854
+ @@ -222,13 +222,14 @@ def unpack_model(
855
+
856
+ """
857
+ import tarfile
858
+ + from tarsafe import TarSafe
859
+
860
+ if working_directory is None:
861
+ working_directory = tempfile.mkdtemp()
862
+
863
+ # All files are in a subdirectory.
864
+ try:
865
+ - with tarfile.open(model_file, mode="r:gz") as tar:
866
+ + with TarSafe.open(model_file, mode="r:gz") as tar:
867
+ tar.extractall(working_directory)
868
+ logger.debug(f"Extracted model to '{working_directory}'.")
869
+ except (tarfile.TarError, ValueError) as e:
870
+ diff --git a/rasa/nlu/persistor.py b/rasa/nlu/persistor.py
871
+ index 9ba50b8e0ed..9f777aeb659 100644
872
+ --- a/rasa/nlu/persistor.py
873
+ +++ b/rasa/nlu/persistor.py
874
+ @@ -2,7 +2,7 @@ import abc
875
+ import logging
876
+ import os
877
+ import shutil
878
+ -import tarfile
879
+ +from tarsafe import TarSafe
880
+ from typing import Optional, Text, Tuple, TYPE_CHECKING
881
+
882
+ import rasa.shared.utils.common
883
+ @@ -103,7 +103,7 @@ class Persistor(abc.ABC):
884
+ @staticmethod
885
+ def _decompress(compressed_path: Text, target_path: Text) -> None:
886
+
887
+ - with tarfile.open(compressed_path, "r:gz") as tar:
888
+ + with TarSafe.open(compressed_path, "r:gz") as tar:
889
+ tar.extractall(target_path) # target dir will be created if it not exists
890
+
891
+
892
+ diff --git a/rasa/utils/io.py b/rasa/utils/io.py
893
+ index 65aa2069759..c0831be91d2 100644
894
+ --- a/rasa/utils/io.py
895
+ +++ b/rasa/utils/io.py
896
+ @@ -3,6 +3,7 @@ import logging
897
+ import os
898
+ import pickle
899
+ import tarfile
900
+ +from tarsafe import TarSafe
901
+ import tempfile
902
+ import warnings
903
+ import zipfile
904
+ @@ -87,7 +88,7 @@ def unarchive(byte_array: bytes, directory: Text) -> Text:
905
+ Tries to use tar first to unpack, if that fails, zip will be used."""
906
+
907
+ try:
908
+ - tar = tarfile.open(fileobj=IOReader(byte_array))
909
+ + tar = TarSafe.open(fileobj=IOReader(byte_array))
910
+ tar.extractall(directory)
911
+ tar.close()
912
+ return directory
tasks/codeql_python_benchmark51_v2/pyvul-3994e3622b21c396ef8a/post_context.md ADDED
@@ -0,0 +1,140 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Patch-overlapping Python context after the fix
2
+
3
+ ## `rasa/model.py` — `function:unpack_model` (lines 210-239)
4
+
5
+ ```python
6
+ def unpack_model(
7
+ model_file: Text, working_directory: Optional[Union[Path, Text]] = None
8
+ ) -> TempDirectoryPath:
9
+ """Unpack a zipped Rasa model.
10
+
11
+ Args:
12
+ model_file: Path to zipped model.
13
+ working_directory: Location where the model should be unpacked to.
14
+ If `None` a temporary directory will be created.
15
+
16
+ Returns:
17
+ Path to unpacked Rasa model.
18
+
19
+ """
20
+ import tarfile
21
+ from tarsafe import TarSafe
22
+
23
+ if working_directory is None:
24
+ working_directory = tempfile.mkdtemp()
25
+
26
+ # All files are in a subdirectory.
27
+ try:
28
+ with TarSafe.open(model_file, mode="r:gz") as tar:
29
+ tar.extractall(working_directory)
30
+ logger.debug(f"Extracted model to '{working_directory}'.")
31
+ except (tarfile.TarError, ValueError) as e:
32
+ logger.error(f"Failed to extract model at {model_file}. Error: {e}")
33
+ raise
34
+
35
+ return TempDirectoryPath(working_directory)
36
+ ```
37
+
38
+ ## `rasa/nlu/persistor.py` — `class:Persistor` (lines 50-107)
39
+
40
+ ```python
41
+ class Persistor(abc.ABC):
42
+ """Store models in cloud and fetch them when needed."""
43
+
44
+ def persist(self, model_directory: Text, model_name: Text) -> None:
45
+ """Uploads a model persisted in the `target_dir` to cloud storage."""
46
+ if not os.path.isdir(model_directory):
47
+ raise ValueError(f"Target directory '{model_directory}' not found.")
48
+
49
+ file_key, tar_path = self._compress(model_directory, model_name)
50
+ self._persist_tar(file_key, tar_path)
51
+
52
+ def retrieve(self, model_name: Text, target_path: Text) -> None:
53
+ """Downloads a model that has been persisted to cloud storage."""
54
+ tar_name = model_name
55
+
56
+ if not model_name.endswith("tar.gz"):
57
+ # ensure backward compatibility
58
+ tar_name = self._tar_name(model_name)
59
+
60
+ self._retrieve_tar(tar_name)
61
+ self._decompress(os.path.basename(tar_name), target_path)
62
+
63
+ @abc.abstractmethod
64
+ def _retrieve_tar(self, filename: Text) -> Text:
65
+ """Downloads a model previously persisted to cloud storage."""
66
+ raise NotImplementedError
67
+
68
+ @abc.abstractmethod
69
+ def _persist_tar(self, filekey: Text, tarname: Text) -> None: # noqa: F841
70
+ """Uploads a model persisted in the `target_dir` to cloud storage."""
71
+ raise NotImplementedError
72
+
73
+ def _compress(self, model_directory: Text, model_name: Text) -> Tuple[Text, Text]:
74
+ """Creates a compressed archive and returns key and tar."""
75
+ import tempfile
76
+
77
+ dirpath = tempfile.mkdtemp()
78
+ base_name = self._tar_name(model_name, include_extension=False)
79
+ tar_name = shutil.make_archive(
80
+ os.path.join(dirpath, base_name),
81
+ "gztar",
82
+ root_dir=model_directory,
83
+ base_dir=".",
84
+ )
85
+ file_key = os.path.basename(tar_name)
86
+ return file_key, tar_name
87
+
88
+ @staticmethod
89
+ def _tar_name(model_name: Text, include_extension: bool = True) -> Text:
90
+
91
+ ext = ".tar.gz" if include_extension else ""
92
+ return f"{model_name}{ext}"
93
+
94
+ @staticmethod
95
+ def _decompress(compressed_path: Text, target_path: Text) -> None:
96
+
97
+ with TarSafe.open(compressed_path, "r:gz") as tar:
98
+ tar.extractall(target_path) # target dir will be created if it not exists
99
+ ```
100
+
101
+ ## `rasa/nlu/persistor.py` — `function:Persistor._decompress` (lines 103-107)
102
+
103
+ ```python
104
+ def _decompress(compressed_path: Text, target_path: Text) -> None:
105
+
106
+ with TarSafe.open(compressed_path, "r:gz") as tar:
107
+ tar.extractall(target_path) # target dir will be created if it not exists
108
+ ```
109
+
110
+ ## `rasa/nlu/persistor.py` — `module:<module>@5` (lines 5-5)
111
+
112
+ ```python
113
+ from tarsafe import TarSafe
114
+ ```
115
+
116
+ ## `rasa/utils/io.py` — `function:unarchive` (lines 85-99)
117
+
118
+ ```python
119
+ def unarchive(byte_array: bytes, directory: Text) -> Text:
120
+ """Tries to unpack a byte array interpreting it as an archive.
121
+
122
+ Tries to use tar first to unpack, if that fails, zip will be used."""
123
+
124
+ try:
125
+ tar = TarSafe.open(fileobj=IOReader(byte_array))
126
+ tar.extractall(directory)
127
+ tar.close()
128
+ return directory
129
+ except tarfile.TarError:
130
+ zip_ref = zipfile.ZipFile(IOReader(byte_array))
131
+ zip_ref.extractall(directory)
132
+ zip_ref.close()
133
+ return directory
134
+ ```
135
+
136
+ ## `rasa/utils/io.py` — `module:<module>@6` (lines 6-6)
137
+
138
+ ```python
139
+ from tarsafe import TarSafe
140
+ ```
tasks/codeql_python_benchmark51_v2/pyvul-3994e3622b21c396ef8a/pre_context.md ADDED
@@ -0,0 +1,145 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Patch-overlapping Python context before the fix
2
+
3
+ ## `rasa/model.py` — `function:unpack_model` (lines 210-238)
4
+
5
+ ```python
6
+ def unpack_model(
7
+ model_file: Text, working_directory: Optional[Union[Path, Text]] = None
8
+ ) -> TempDirectoryPath:
9
+ """Unpack a zipped Rasa model.
10
+
11
+ Args:
12
+ model_file: Path to zipped model.
13
+ working_directory: Location where the model should be unpacked to.
14
+ If `None` a temporary directory will be created.
15
+
16
+ Returns:
17
+ Path to unpacked Rasa model.
18
+
19
+ """
20
+ import tarfile
21
+
22
+ if working_directory is None:
23
+ working_directory = tempfile.mkdtemp()
24
+
25
+ # All files are in a subdirectory.
26
+ try:
27
+ with tarfile.open(model_file, mode="r:gz") as tar:
28
+ tar.extractall(working_directory)
29
+ logger.debug(f"Extracted model to '{working_directory}'.")
30
+ except (tarfile.TarError, ValueError) as e:
31
+ logger.error(f"Failed to extract model at {model_file}. Error: {e}")
32
+ raise
33
+
34
+ return TempDirectoryPath(working_directory)
35
+ ```
36
+
37
+ ## `rasa/nlu/persistor.py` — `class:Persistor` (lines 50-107)
38
+
39
+ ```python
40
+ class Persistor(abc.ABC):
41
+ """Store models in cloud and fetch them when needed."""
42
+
43
+ def persist(self, model_directory: Text, model_name: Text) -> None:
44
+ """Uploads a model persisted in the `target_dir` to cloud storage."""
45
+ if not os.path.isdir(model_directory):
46
+ raise ValueError(f"Target directory '{model_directory}' not found.")
47
+
48
+ file_key, tar_path = self._compress(model_directory, model_name)
49
+ self._persist_tar(file_key, tar_path)
50
+
51
+ def retrieve(self, model_name: Text, target_path: Text) -> None:
52
+ """Downloads a model that has been persisted to cloud storage."""
53
+ tar_name = model_name
54
+
55
+ if not model_name.endswith("tar.gz"):
56
+ # ensure backward compatibility
57
+ tar_name = self._tar_name(model_name)
58
+
59
+ self._retrieve_tar(tar_name)
60
+ self._decompress(os.path.basename(tar_name), target_path)
61
+
62
+ @abc.abstractmethod
63
+ def _retrieve_tar(self, filename: Text) -> Text:
64
+ """Downloads a model previously persisted to cloud storage."""
65
+ raise NotImplementedError
66
+
67
+ @abc.abstractmethod
68
+ def _persist_tar(self, filekey: Text, tarname: Text) -> None: # noqa: F841
69
+ """Uploads a model persisted in the `target_dir` to cloud storage."""
70
+ raise NotImplementedError
71
+
72
+ def _compress(self, model_directory: Text, model_name: Text) -> Tuple[Text, Text]:
73
+ """Creates a compressed archive and returns key and tar."""
74
+ import tempfile
75
+
76
+ dirpath = tempfile.mkdtemp()
77
+ base_name = self._tar_name(model_name, include_extension=False)
78
+ tar_name = shutil.make_archive(
79
+ os.path.join(dirpath, base_name),
80
+ "gztar",
81
+ root_dir=model_directory,
82
+ base_dir=".",
83
+ )
84
+ file_key = os.path.basename(tar_name)
85
+ return file_key, tar_name
86
+
87
+ @staticmethod
88
+ def _tar_name(model_name: Text, include_extension: bool = True) -> Text:
89
+
90
+ ext = ".tar.gz" if include_extension else ""
91
+ return f"{model_name}{ext}"
92
+
93
+ @staticmethod
94
+ def _decompress(compressed_path: Text, target_path: Text) -> None:
95
+
96
+ with tarfile.open(compressed_path, "r:gz") as tar:
97
+ tar.extractall(target_path) # target dir will be created if it not exists
98
+ ```
99
+
100
+ ## `rasa/nlu/persistor.py` — `function:Persistor._decompress` (lines 103-107)
101
+
102
+ ```python
103
+ def _decompress(compressed_path: Text, target_path: Text) -> None:
104
+
105
+ with tarfile.open(compressed_path, "r:gz") as tar:
106
+ tar.extractall(target_path) # target dir will be created if it not exists
107
+ ```
108
+
109
+ ## `rasa/nlu/persistor.py` — `module:<module>@5` (lines 5-5)
110
+
111
+ ```python
112
+ import tarfile
113
+ ```
114
+
115
+ ## `rasa/nlu/persistor.py` — `module:<module>@6` (lines 6-6)
116
+
117
+ ```python
118
+ from typing import Optional, Text, Tuple, TYPE_CHECKING
119
+ ```
120
+
121
+ ## `rasa/utils/io.py` — `function:unarchive` (lines 84-98)
122
+
123
+ ```python
124
+ def unarchive(byte_array: bytes, directory: Text) -> Text:
125
+ """Tries to unpack a byte array interpreting it as an archive.
126
+
127
+ Tries to use tar first to unpack, if that fails, zip will be used."""
128
+
129
+ try:
130
+ tar = tarfile.open(fileobj=IOReader(byte_array))
131
+ tar.extractall(directory)
132
+ tar.close()
133
+ return directory
134
+ except tarfile.TarError:
135
+ zip_ref = zipfile.ZipFile(IOReader(byte_array))
136
+ zip_ref.extractall(directory)
137
+ zip_ref.close()
138
+ return directory
139
+ ```
140
+
141
+ ## `rasa/utils/io.py` — `module:<module>@6` (lines 6-6)
142
+
143
+ ```python
144
+ import tempfile
145
+ ```
tasks/codeql_python_benchmark51_v2/pyvul-3994e3622b21c396ef8a/task.json ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "schema_version": "synthesis-task-v1",
3
+ "task": {
4
+ "pair_id": "pyvul-3994e3622b21c396ef8a",
5
+ "dataset_id": "PyVul",
6
+ "dataset_item_id": "pyvul-3994e3622b21c396ef8a",
7
+ "project_id": "pyvul__rasahq__rasa",
8
+ "language": "python",
9
+ "backend": "codeql"
10
+ },
11
+ "changed_python_files": [
12
+ "rasa/model.py",
13
+ "rasa/nlu/persistor.py",
14
+ "rasa/utils/io.py"
15
+ ],
16
+ "patch_units": {
17
+ "before": [
18
+ "function:unpack_model",
19
+ "class:Persistor",
20
+ "function:Persistor._decompress",
21
+ "module:<module>@5",
22
+ "module:<module>@6",
23
+ "function:unarchive",
24
+ "module:<module>@6"
25
+ ],
26
+ "after": [
27
+ "function:unpack_model",
28
+ "class:Persistor",
29
+ "function:Persistor._decompress",
30
+ "module:<module>@5",
31
+ "function:unarchive",
32
+ "module:<module>@6"
33
+ ]
34
+ },
35
+ "runtime_assets": {
36
+ "before": {
37
+ "database": "assets/c55507b377561f903462ad5cec29b5fc43df8b9f6e8a1eb5bc87da87c5348d2f/database",
38
+ "cache_key": "c55507b377561f903462ad5cec29b5fc43df8b9f6e8a1eb5bc87da87c5348d2f",
39
+ "codeql_version": "2.26.4"
40
+ },
41
+ "after": {
42
+ "database": "assets/9d2daedadeb33c7c140f4863247d20ea58e9e5a26e7947a1305e447ef40f18d3/database",
43
+ "cache_key": "9d2daedadeb33c7c140f4863247d20ea58e9e5a26e7947a1305e447ef40f18d3",
44
+ "codeql_version": "2.26.4"
45
+ },
46
+ "refine": {
47
+ "database": "assets/b7688a4b944f994a4f8cdc0dc46c7126c07a3197c53b14714e52625daac53337/database",
48
+ "cache_key": "b7688a4b944f994a4f8cdc0dc46c7126c07a3197c53b14714e52625daac53337",
49
+ "codeql_version": "2.26.4"
50
+ }
51
+ },
52
+ "benchmark_contract": {
53
+ "agent_visible": true,
54
+ "reference_query_location": "references/pyvul-3994e3622b21c396ef8a/query/ (do not mount into agent)",
55
+ "evaluator_location": "evaluator/pyvul-3994e3622b21c396ef8a/ (do not mount into agent)"
56
+ }
57
+ }
tasks/codeql_python_benchmark51_v2/pyvul-3994e3622b21c396ef8a/task_prompt.md ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Python CodeQL detector synthesis
2
+
3
+ You are cc operating in `/work`. Starting only from the supplied patch,
4
+ before/after Python context, CodeQL references, and validation tools, synthesize a semantic CodeQL
5
+ detector for the vulnerability fixed by the patch. This is one fresh session. You may iterate inside
6
+ this session, but no later framework repair or resume will occur.
7
+
8
+ ## Inputs and owned outputs
9
+
10
+ - Read `patch.diff`, `python_patch.diff`, `pre_context.md`, and `post_context.md`.
11
+ - Read `references/codeql/convergence_protocol.md` and
12
+ `references/codeql/api_navigation.md` before experimenting. Read the remaining
13
+ `references/codeql/` files for the selected mechanism.
14
+ - Use `scripts/search_codeql_api.sh` to inspect the pinned official libraries when an API detail is
15
+ uncertain. Do not guess predicate names or build a large family of inspection queries.
16
+ - Complete the design contract in `state.json` and `scope_statement.md` before final validation.
17
+ - Replace `query/vulnerability.ql`; add only genuinely shared `.qll` helpers when useful. Keep the
18
+ fixed offline dependency in `query/qlpack.yml`.
19
+ - Preserve the exact `expected_query_id` from `config.json` as the query's sole `@id`. This
20
+ task-unique metadata must never be used in a query predicate.
21
+ - Use `scripts/compile_query.sh`, `scripts/run_before.sh`, and `scripts/run_after.sh`.
22
+ - Finish by writing `summary.json` with `status`, `query_path`, `query_kind`, `build_passed`,
23
+ `before_findings`, `after_findings`, `validation_completed`, and a concise `notes` field.
24
+
25
+ ## Required reasoning contract
26
+
27
+ Before coding, record this mapping in `state.json`:
28
+
29
+ ```text
30
+ vulnerable operation / trigger / patch safety condition
31
+ → CodeQL-observable evidence
32
+ → syntax, control-flow, local value-flow, global taint/value-flow, or interprocedural mechanism
33
+ → source, sink/report site, guard/barrier and query predicates
34
+ ```
35
+
36
+ Choose the lowest mechanism that can actually prove the condition. Guard-sensitive patches require
37
+ real path/control-flow semantics; provenance-sensitive patches require value flow. Do not replace
38
+ either with source-text matching or with the mere presence of patch-added syntax.
39
+
40
+ ## Mandatory convergence contract
41
+
42
+ The rollout has a 30-minute hard wall-clock ceiling and must be finalized by minute 27. Minutes
43
+ 27–30 are an emergency shutdown buffer, not exploration time. A sophisticated unfinished query is
44
+ a failure; an early compilable semantic candidate can be improved. Follow the checkpoints in
45
+ `references/codeql/convergence_protocol.md`:
46
+
47
+ 1. Record the mechanism contract, then replace the placeholder in `query/vulnerability.ql`
48
+ immediately. Do not wait until every CodeQL API detail is known.
49
+ 2. Use at most three distinct scratch `.ql` files. Prefer repeatedly editing one
50
+ `query/scratch.ql`. After two failed variants of one API assumption, inspect the exact bundled
51
+ definition with `scripts/search_codeql_api.sh` or simplify the mechanism.
52
+ 3. Obtain a compiling minimal main query before broadening it. Compile the main query after every
53
+ meaningful mechanism change.
54
+ 4. Move in order from compile → relevant before finding → after elimination → final contract. Do
55
+ not continue API exploration after the intended before/after differential is established.
56
+ 5. Run `scripts/check_progress.sh` at each checkpoint. It reports elapsed time, the minute-27
57
+ finalization deadline, and the minute-30 hard timeout. When it prints `finalize_now`, stop all
58
+ exploration, preserve the best compiling query, finish the contract files, and exit.
59
+
60
+ ## Semantic and generalization rules
61
+
62
+ - Report at the vulnerable call, operator, access, or sink.
63
+ - Do not use a patch-local path, line, commit hash, label, or local variable name as the primary
64
+ matching condition. Stable library/framework APIs or public project APIs are allowed only when
65
+ `scope_statement.md` explains why they define the intended vulnerability family.
66
+ - The safety condition introduced by the patch must be represented by the query.
67
+ - A lower after warning count is not enough: inspect SARIF and ensure at least one intended before
68
+ finding is in a patch-overlapping semantic unit and the corresponding finding disappears after.
69
+ - Avoid broad proxy queries that report an enclosing function or unrelated API merely because it
70
+ changed in the patch.
71
+
72
+ ## Final validation protocol
73
+
74
+ 1. Compile the final query.
75
+ 2. Run it on before and inspect `raw/before.sarif` for the intended report location.
76
+ 3. Run the identical query on after and inspect `raw/after.sarif`.
77
+ 4. Recheck query metadata, query kind/select signature, report locality, design-to-code consistency,
78
+ and absence of patch-local hardcoding.
79
+ 5. Update `state.json`, `scope_statement.md`, and write valid `summary.json`.
80
+
81
+ Do not modify the runtime databases, references, patch, context, or validation scripts except for
82
+ normal CodeQL-generated database caches produced by the provided run scripts.
tasks/codeql_python_benchmark51_v2/pyvul-4954e5890cce23c8b03d/patch.diff ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ diff --git a/PIL/EpsImagePlugin.py b/PIL/EpsImagePlugin.py
2
+ index a8706b05f..fcfae8a81 100644
3
+ --- a/PIL/EpsImagePlugin.py
4
+ +++ b/PIL/EpsImagePlugin.py
5
+ @@ -67,7 +67,8 @@ def Ghostscript(tile, size, fp, scale=1):
6
+
7
+ import tempfile, os, subprocess
8
+
9
+ - file = tempfile.mktemp()
10
+ + out_fd, file = tempfile.mkstemp()
11
+ + os.close(out_fd)
12
+
13
+ # Build ghostscript command
14
+ command = ["gs",
15
+ diff --git a/PIL/Image.py b/PIL/Image.py
16
+ index 87631d6f7..915f5b1df 100644
17
+ --- a/PIL/Image.py
18
+ +++ b/PIL/Image.py
19
+ @@ -495,14 +495,17 @@ class Image:
20
+ self.readonly = 0
21
+
22
+ def _dump(self, file=None, format=None):
23
+ - import tempfile
24
+ + import tempfile, os
25
+ if not file:
26
+ - file = tempfile.mktemp()
27
+ + f, file = tempfile.mkstemp(format or '')
28
+ + os.close(f)
29
+ +
30
+ self.load()
31
+ if not format or format == "PPM":
32
+ self.im.save_ppm(file)
33
+ else:
34
+ - file = file + "." + format
35
+ + if file.endswith(format):
36
+ + file = file + "." + format
37
+ self.save(file, format)
38
+ return file
39
+
40
+ diff --git a/PIL/IptcImagePlugin.py b/PIL/IptcImagePlugin.py
41
+ index 157b73509..104153002 100644
42
+ --- a/PIL/IptcImagePlugin.py
43
+ +++ b/PIL/IptcImagePlugin.py
44
+ @@ -172,8 +172,8 @@ class IptcImageFile(ImageFile.ImageFile):
45
+ self.fp.seek(offset)
46
+
47
+ # Copy image data to temporary file
48
+ - outfile = tempfile.mktemp()
49
+ - o = open(outfile, "wb")
50
+ + o_fd, outfile = tempfile.mkstemp(text=False)
51
+ + o = os.fdopen(o_fd)
52
+ if encoding == "raw":
53
+ # To simplify access to the extracted file,
54
+ # prepend a PPM header
55
+ diff --git a/PIL/JpegImagePlugin.py b/PIL/JpegImagePlugin.py
56
+ index 90d3b5194..67dc5ba7d 100644
57
+ --- a/PIL/JpegImagePlugin.py
58
+ +++ b/PIL/JpegImagePlugin.py
59
+ @@ -344,13 +344,17 @@ class JpegImageFile(ImageFile.ImageFile):
60
+ # ALTERNATIVE: handle JPEGs via the IJG command line utilities
61
+
62
+ import tempfile, os
63
+ - file = tempfile.mktemp()
64
+ - os.system("djpeg %s >%s" % (self.filename, file))
65
+ + f, path = tempfile.mkstemp()
66
+ + os.close(f)
67
+ + if os.path.exists(self.filename):
68
+ + os.system("djpeg '%s' >'%s'" % (self.filename, path))
69
+ + else:
70
+ + raise ValueError("Invalid Filename")
71
+
72
+ try:
73
+ - self.im = Image.core.open_ppm(file)
74
+ + self.im = Image.core.open_ppm(path)
75
+ finally:
76
+ - try: os.unlink(file)
77
+ + try: os.unlink(path)
78
+ except: pass
79
+
80
+ self.mode = self.im.mode
tasks/codeql_python_benchmark51_v2/pyvul-4954e5890cce23c8b03d/post_context.md ADDED
@@ -0,0 +1,1683 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Patch-overlapping Python context after the fix
2
+
3
+ ## `PIL/EpsImagePlugin.py` — `function:Ghostscript` (lines 53-110)
4
+
5
+ ```python
6
+ def Ghostscript(tile, size, fp, scale=1):
7
+ """Render an image using Ghostscript"""
8
+
9
+ # Unpack decoder tile
10
+ decoder, tile, offset, data = tile[0]
11
+ length, bbox = data
12
+
13
+ #Hack to support hi-res rendering
14
+ scale = int(scale) or 1
15
+ orig_size = size
16
+ orig_bbox = bbox
17
+ size = (size[0] * scale, size[1] * scale)
18
+ bbox = [bbox[0], bbox[1], bbox[2] * scale, bbox[3] * scale]
19
+ #print("Ghostscript", scale, size, orig_size, bbox, orig_bbox)
20
+
21
+ import tempfile, os, subprocess
22
+
23
+ out_fd, file = tempfile.mkstemp()
24
+ os.close(out_fd)
25
+
26
+ # Build ghostscript command
27
+ command = ["gs",
28
+ "-q", # quite mode
29
+ "-g%dx%d" % size, # set output geometry (pixels)
30
+ "-r%d" % (72*scale), # set input DPI (dots per inch)
31
+ "-dNOPAUSE -dSAFER", # don't pause between pages, safe mode
32
+ "-sDEVICE=ppmraw", # ppm driver
33
+ "-sOutputFile=%s" % file,# output file
34
+ ]
35
+
36
+ if gs_windows_binary is not None:
37
+ if gs_windows_binary is False:
38
+ raise WindowsError('Unable to locate Ghostscript on paths')
39
+ command[0] = gs_windows_binary
40
+
41
+ # push data through ghostscript
42
+ try:
43
+ gs = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
44
+ # adjust for image origin
45
+ if bbox[0] != 0 or bbox[1] != 0:
46
+ gs.stdin.write(("%d %d translate\n" % (-bbox[0], -bbox[1])).encode('ascii'))
47
+ fp.seek(offset)
48
+ while length > 0:
49
+ s = fp.read(8192)
50
+ if not s:
51
+ break
52
+ length = length - len(s)
53
+ gs.stdin.write(s)
54
+ gs.stdin.close()
55
+ status = gs.wait()
56
+ if status:
57
+ raise IOError("gs failed (status %d)" % status)
58
+ im = Image.core.open_ppm(file)
59
+ finally:
60
+ try: os.unlink(file)
61
+ except: pass
62
+
63
+ return im
64
+ ```
65
+
66
+ ## `PIL/Image.py` — `class:Image` (lines 447-1705)
67
+
68
+ ```python
69
+ class Image:
70
+ """
71
+ This class represents an image object. To create
72
+ :py:class:`~PIL.Image.Image` objects, use the appropriate factory
73
+ functions. There's hardly ever any reason to call the Image constructor
74
+ directly.
75
+
76
+ * :py:func:`~PIL.Image.open`
77
+ * :py:func:`~PIL.Image.new`
78
+ * :py:func:`~PIL.Image.frombytes`
79
+ """
80
+ format = None
81
+ format_description = None
82
+
83
+ def __init__(self):
84
+ # FIXME: take "new" parameters / other image?
85
+ # FIXME: turn mode and size into delegating properties?
86
+ self.im = None
87
+ self.mode = ""
88
+ self.size = (0, 0)
89
+ self.palette = None
90
+ self.info = {}
91
+ self.category = NORMAL
92
+ self.readonly = 0
93
+
94
+ def _new(self, im):
95
+ new = Image()
96
+ new.im = im
97
+ new.mode = im.mode
98
+ new.size = im.size
99
+ new.palette = self.palette
100
+ if im.mode == "P" and not new.palette:
101
+ from PIL import ImagePalette
102
+ new.palette = ImagePalette.ImagePalette()
103
+ try:
104
+ new.info = self.info.copy()
105
+ except AttributeError:
106
+ # fallback (pre-1.5.2)
107
+ new.info = {}
108
+ for k, v in self.info:
109
+ new.info[k] = v
110
+ return new
111
+
112
+ _makeself = _new # compatibility
113
+
114
+ def _copy(self):
115
+ self.load()
116
+ self.im = self.im.copy()
117
+ self.readonly = 0
118
+
119
+ def _dump(self, file=None, format=None):
120
+ import tempfile, os
121
+ if not file:
122
+ f, file = tempfile.mkstemp(format or '')
123
+ os.close(f)
124
+
125
+ self.load()
126
+ if not format or format == "PPM":
127
+ self.im.save_ppm(file)
128
+ else:
129
+ if file.endswith(format):
130
+ file = file + "." + format
131
+ self.save(file, format)
132
+ return file
133
+
134
+ def __repr__(self):
135
+ return "<%s.%s image mode=%s size=%dx%d at 0x%X>" % (
136
+ self.__class__.__module__, self.__class__.__name__,
137
+ self.mode, self.size[0], self.size[1],
138
+ id(self)
139
+ )
140
+
141
+ def __getattr__(self, name):
142
+ if name == "__array_interface__":
143
+ # numpy array interface support
144
+ new = {}
145
+ shape, typestr = _conv_type_shape(self)
146
+ new['shape'] = shape
147
+ new['typestr'] = typestr
148
+ new['data'] = self.tobytes()
149
+ return new
150
+ raise AttributeError(name)
151
+
152
+ def tobytes(self, encoder_name="raw", *args):
153
+ """
154
+ Return image as a bytes object
155
+
156
+ :param encoder_name: What encoder to use. The default is to
157
+ use the standard "raw" encoder.
158
+ :param args: Extra arguments to the encoder.
159
+ :rtype: A bytes object.
160
+ """
161
+
162
+ # may pass tuple instead of argument list
163
+ if len(args) == 1 and isinstance(args[0], tuple):
164
+ args = args[0]
165
+
166
+ if encoder_name == "raw" and args == ():
167
+ args = self.mode
168
+
169
+ self.load()
170
+
171
+ # unpack data
172
+ e = _getencoder(self.mode, encoder_name, args)
173
+ e.setimage(self.im)
174
+
175
+ bufsize = max(65536, self.size[0] * 4) # see RawEncode.c
176
+
177
+ data = []
178
+ while True:
179
+ l, s, d = e.encode(bufsize)
180
+ data.append(d)
181
+ if s:
182
+ break
183
+ if s < 0:
184
+ raise RuntimeError("encoder error %d in tobytes" % s)
185
+
186
+ return b"".join(data)
187
+
188
+ # Declare tostring as alias to tobytes
189
+ def tostring(self, *args, **kw):
190
+ warnings.warn(
191
+ 'tostring() is deprecated. Please call tobytes() instead.',
192
+ DeprecationWarning,
193
+ stacklevel=2,
194
+ )
195
+ return self.tobytes(*args, **kw)
196
+
197
+ def tobitmap(self, name="image"):
198
+ """
199
+ Returns the image converted to an X11 bitmap.
200
+
201
+ .. note:: This method only works for mode "1" images.
202
+
203
+ :param name: The name prefix to use for the bitmap variables.
204
+ :returns: A string containing an X11 bitmap.
205
+ :raises ValueError: If the mode is not "1"
206
+ """
207
+
208
+ self.load()
209
+ if self.mode != "1":
210
+ raise ValueError("not a bitmap")
211
+ data = self.tobytes("xbm")
212
+ return b"".join([("#define %s_width %d\n" % (name, self.size[0])).encode('ascii'),
213
+ ("#define %s_height %d\n"% (name, self.size[1])).encode('ascii'),
214
+ ("static char %s_bits[] = {\n" % name).encode('ascii'), data, b"};"])
215
+
216
+ def frombytes(self, data, decoder_name="raw", *args):
217
+ """
218
+ Loads this image with pixel data from a bytes object.
219
+
220
+ This method is similar to the :py:func:`~PIL.Image.frombytes` function,
221
+ but loads data into this image instead of creating a new image object.
222
+ """
223
+
224
+ # may pass tuple instead of argument list
225
+ if len(args) == 1 and isinstance(args[0], tuple):
226
+ args = args[0]
227
+
228
+ # default format
229
+ if decoder_name == "raw" and args == ():
230
+ args = self.mode
231
+
232
+ # unpack data
233
+ d = _getdecoder(self.mode, decoder_name, args)
234
+ d.setimage(self.im)
235
+ s = d.decode(data)
236
+
237
+ if s[0] >= 0:
238
+ raise ValueError("not enough image data")
239
+ if s[1] != 0:
240
+ raise ValueError("cannot decode image data")
241
+
242
+ def fromstring(self, *args, **kw):
243
+ """Deprecated alias to frombytes.
244
+
245
+ .. deprecated:: 2.0
246
+ """
247
+ warnings.warn('fromstring() is deprecated. Please call frombytes() instead.', DeprecationWarning)
248
+ return self.frombytes(*args, **kw)
249
+
250
+ def load(self):
251
+ """
252
+ Allocates storage for the image and loads the pixel data. In
253
+ normal cases, you don't need to call this method, since the
254
+ Image class automatically loads an opened image when it is
255
+ accessed for the first time.
256
+
257
+ :returns: An image access object.
258
+ """
259
+ if self.im and self.palette and self.palette.dirty:
260
+ # realize palette
261
+ self.im.putpalette(*self.palette.getdata())
262
+ self.palette.dirty = 0
263
+ self.palette.mode = "RGB"
264
+ self.palette.rawmode = None
265
+ if "transparency" in self.info:
266
+ if isinstance(self.info["transparency"], int):
267
+ self.im.putpalettealpha(self.info["transparency"], 0)
268
+ else:
269
+ self.im.putpalettealphas(self.info["transparency"])
270
+ self.palette.mode = "RGBA"
271
+
272
+ if self.im:
273
+ return self.im.pixel_access(self.readonly)
274
+
275
+ def verify(self):
276
+ """
277
+ Verifies the contents of a file. For data read from a file, this
278
+ method attempts to determine if the file is broken, without
279
+ actually decoding the image data. If this method finds any
280
+ problems, it raises suitable exceptions. If you need to load
281
+ the image after using this method, you must reopen the image
282
+ file.
283
+ """
284
+ pass
285
+
286
+ def convert(self, mode=None, matrix=None, dither=None,
287
+ palette=WEB, colors=256):
288
+ """
289
+ Returns a converted copy of this image. For the "P" mode, this
290
+ method translates pixels through the palette. If mode is
291
+ omitted, a mode is chosen so that all information in the image
292
+ and the palette can be represented without a palette.
293
+
294
+ The current version supports all possible conversions between
295
+ "L", "RGB" and "CMYK." The **matrix** argument only supports "L"
296
+ and "RGB".
297
+
298
+ When translating a color image to black and white (mode "L"),
299
+ the library uses the ITU-R 601-2 luma transform::
300
+
301
+ L = R * 299/1000 + G * 587/1000 + B * 114/1000
302
+
303
+ The default method of converting a greyscale ("L") or "RGB"
304
+ image into a bilevel (mode "1") image uses Floyd-Steinberg
305
+ dither to approximate the original image luminosity levels. If
306
+ dither is NONE, all non-zero values are set to 255 (white). To
307
+ use other thresholds, use the :py:meth:`~PIL.Image.Image.point`
308
+ method.
309
+
310
+ :param mode: The requested mode.
311
+ :param matrix: An optional conversion matrix. If given, this
312
+ should be 4- or 16-tuple containing floating point values.
313
+ :param dither: Dithering method, used when converting from
314
+ mode "RGB" to "P" or from "RGB" or "L" to "1".
315
+ Available methods are NONE or FLOYDSTEINBERG (default).
316
+ :param palette: Palette to use when converting from mode "RGB"
317
+ to "P". Available palettes are WEB or ADAPTIVE.
318
+ :param colors: Number of colors to use for the ADAPTIVE palette.
319
+ Defaults to 256.
320
+ :rtype: :py:class:`~PIL.Image.Image`
321
+ :returns: An :py:class:`~PIL.Image.Image` object.
322
+ """
323
+
324
+ if not mode:
325
+ # determine default mode
326
+ if self.mode == "P":
327
+ self.load()
328
+ if self.palette:
329
+ mode = self.palette.mode
330
+ else:
331
+ mode = "RGB"
332
+ else:
333
+ return self.copy()
334
+
335
+ self.load()
336
+
337
+ if matrix:
338
+ # matrix conversion
339
+ if mode not in ("L", "RGB"):
340
+ raise ValueError("illegal conversion")
341
+ im = self.im.convert_matrix(mode, matrix)
342
+ return self._new(im)
343
+
344
+ if mode == "P" and palette == ADAPTIVE:
345
+ im = self.im.quantize(colors)
346
+ return self._new(im)
347
+
348
+ # colorspace conversion
349
+ if dither is None:
350
+ dither = FLOYDSTEINBERG
351
+
352
+ # Use transparent conversion to promote from transparent color to an alpha channel.
353
+ if self.mode in ("L", "RGB") and mode == "RGBA" and "transparency" in self.info:
354
+ return self._new(self.im.convert_transparent(mode, self.info['transparency']))
355
+
356
+ try:
357
+ im = self.im.convert(mode, dither)
358
+ except ValueError:
359
+ try:
360
+ # normalize source image and try again
361
+ im = self.im.convert(getmodebase(self.mode))
362
+ im = im.convert(mode, dither)
363
+ except KeyError:
364
+ raise ValueError("illegal conversion")
365
+
366
+ return self._new(im)
367
+
368
+ def quantize(self, colors=256, method=0, kmeans=0, palette=None):
369
+
370
+ # methods:
371
+ # 0 = median cut
372
+ # 1 = maximum coverage
373
+ # 2 = fast octree
374
+
375
+ # NOTE: this functionality will be moved to the extended
376
+ # quantizer interface in a later version of PIL.
377
+
378
+ self.load()
379
+
380
+ if palette:
381
+ # use palette from reference image
382
+ palette.load()
383
+ if palette.mode != "P":
384
+ raise ValueError("bad mode for palette image")
385
+ if self.mode != "RGB" and self.mode != "L":
386
+ raise ValueError(
387
+ "only RGB or L mode images can be quantized to a palette"
388
+ )
389
+ im = self.im.convert("P", 1, palette.im)
390
+ return self._makeself(im)
391
+
392
+ im = self.im.quantize(colors, method, kmeans)
393
+ return self._new(im)
394
+
395
+ def copy(self):
396
+ """
397
+ Copies this image. Use this method if you wish to paste things
398
+ into an image, but still retain the original.
399
+
400
+ :rtype: :py:class:`~PIL.Image.Image`
401
+ :returns: An :py:class:`~PIL.Image.Image` object.
402
+ """
403
+ self.load()
404
+ im = self.im.copy()
405
+ return self._new(im)
406
+
407
+ def crop(self, box=None):
408
+ """
409
+ Returns a rectangular region from this image. The box is a
410
+ 4-tuple defining the left, upper, right, and lower pixel
411
+ coordinate.
412
+
413
+ This is a lazy operation. Changes to the source image may or
414
+ may not be reflected in the cropped image. To break the
415
+ connection, call the :py:meth:`~PIL.Image.Image.load` method on
416
+ the cropped copy.
417
+
418
+ :param box: The crop rectangle, as a (left, upper, right, lower)-tuple.
419
+ :rtype: :py:class:`~PIL.Image.Image`
420
+ :returns: An :py:class:`~PIL.Image.Image` object.
421
+ """
422
+
423
+ self.load()
424
+ if box is None:
425
+ return self.copy()
426
+
427
+ # lazy operation
428
+ return _ImageCrop(self, box)
429
+
430
+ def draft(self, mode, size):
431
+ """
432
+ Configures the image file loader so it returns a version of the
433
+ image that as closely as possible matches the given mode and
434
+ size. For example, you can use this method to convert a color
435
+ JPEG to greyscale while loading it, or to extract a 128x192
436
+ version from a PCD file.
437
+
438
+ Note that this method modifies the :py:class:`~PIL.Image.Image` object
439
+ in place. If the image has already been loaded, this method has no
440
+ effect.
441
+
442
+ :param mode: The requested mode.
443
+ :param size: The requested size.
444
+ """
445
+ pass
446
+
447
+ def _expand(self, xmargin, ymargin=None):
448
+ if ymargin is None:
449
+ ymargin = xmargin
450
+ self.load()
451
+ return self._new(self.im.expand(xmargin, ymargin, 0))
452
+
453
+ def filter(self, filter):
454
+ """
455
+ Filters this image using the given filter. For a list of
456
+ available filters, see the :py:mod:`~PIL.ImageFilter` module.
457
+
458
+ :param filter: Filter kernel.
459
+ :returns: An :py:class:`~PIL.Image.Image` object. """
460
+
461
+ self.load()
462
+
463
+ if isinstance(filter, collections.Callable):
464
+ filter = filter()
465
+ if not hasattr(filter, "filter"):
466
+ raise TypeError("filter argument should be ImageFilter.Filter instance or class")
467
+
468
+ if self.im.bands == 1:
469
+ return self._new(filter.filter(self.im))
470
+ # fix to handle multiband images since _imaging doesn't
471
+ ims = []
472
+ for c in range(self.im.bands):
473
+ ims.append(self._new(filter.filter(self.im.getband(c))))
474
+ return merge(self.mode, ims)
475
+
476
+ def getbands(self):
477
+ """
478
+ Returns a tuple containing the name of each band in this image.
479
+ For example, **getbands** on an RGB image returns ("R", "G", "B").
480
+
481
+ :returns: A tuple containing band names.
482
+ :rtype: tuple
483
+ """
484
+ return ImageMode.getmode(self.mode).bands
485
+
486
+ def getbbox(self):
487
+ """
488
+ Calculates the bounding box of the non-zero regions in the
489
+ image.
490
+
491
+ :returns: The bounding box is returned as a 4-tuple defining the
492
+ left, upper, right, and lower pixel coordinate. If the image
493
+ is completely empty, this method returns None.
494
+
495
+ """
496
+
497
+ self.load()
498
+ return self.im.getbbox()
499
+
500
+ def getcolors(self, maxcolors=256):
501
+ """
502
+ Returns a list of colors used in this image.
503
+
504
+ :param maxcolors: Maximum number of colors. If this number is
505
+ exceeded, this method returns None. The default limit is
506
+ 256 colors.
507
+ :returns: An unsorted list of (count, pixel) values.
508
+ """
509
+
510
+ self.load()
511
+ if self.mode in ("1", "L", "P"):
512
+ h = self.im.histogram()
513
+ out = []
514
+ for i in range(256):
515
+ if h[i]:
516
+ out.append((h[i], i))
517
+ if len(out) > maxcolors:
518
+ return None
519
+ return out
520
+ return self.im.getcolors(maxcolors)
521
+
522
+ def getdata(self, band = None):
523
+ """
524
+ Returns the contents of this image as a sequence object
525
+ containing pixel values. The sequence object is flattened, so
526
+ that values for line one follow directly after the values of
527
+ line zero, and so on.
528
+
529
+ Note that the sequence object returned by this method is an
530
+ internal PIL data type, which only supports certain sequence
531
+ operations. To convert it to an ordinary sequence (e.g. for
532
+ printing), use **list(im.getdata())**.
533
+
534
+ :param band: What band to return. The default is to return
535
+ all bands. To return a single band, pass in the index
536
+ value (e.g. 0 to get the "R" band from an "RGB" image).
537
+ :returns: A sequence-like object.
538
+ """
539
+
540
+ self.load()
541
+ if band is not None:
542
+ return self.im.getband(band)
543
+ return self.im # could be abused
544
+
545
+ def getextrema(self):
546
+ """
547
+ Gets the the minimum and maximum pixel values for each band in
548
+ the image.
549
+
550
+ :returns: For a single-band image, a 2-tuple containing the
551
+ minimum and maximum pixel value. For a multi-band image,
552
+ a tuple containing one 2-tuple for each band.
553
+ """
554
+
555
+ self.load()
556
+ if self.im.bands > 1:
557
+ extrema = []
558
+ for i in range(self.im.bands):
559
+ extrema.append(self.im.getband(i).getextrema())
560
+ return tuple(extrema)
561
+ return self.im.getextrema()
562
+
563
+ def getim(self):
564
+ """
565
+ Returns a capsule that points to the internal image memory.
566
+
567
+ :returns: A capsule object.
568
+ """
569
+
570
+ self.load()
571
+ return self.im.ptr
572
+
573
+
574
+ def getpalette(self):
575
+ """
576
+ Returns the image palette as a list.
577
+
578
+ :returns: A list of color values [r, g, b, ...], or None if the
579
+ image has no palette.
580
+ """
581
+
582
+ self.load()
583
+ try:
584
+ if bytes is str:
585
+ return [i8(c) for c in self.im.getpalette()]
586
+ else:
587
+ return list(self.im.getpalette())
588
+ except ValueError:
589
+ return None # no palette
590
+
591
+
592
+ def getpixel(self, xy):
593
+ """
594
+ Returns the pixel value at a given position.
595
+
596
+ :param xy: The coordinate, given as (x, y).
597
+ :returns: The pixel value. If the image is a multi-layer image,
598
+ this method returns a tuple.
599
+ """
600
+
601
+ self.load()
602
+ return self.im.getpixel(xy)
603
+
604
+ def getprojection(self):
605
+ """
606
+ Get projection to x and y axes
607
+
608
+ :returns: Two sequences, indicating where there are non-zero
609
+ pixels along the X-axis and the Y-axis, respectively.
610
+ """
611
+
612
+ self.load()
613
+ x, y = self.im.getprojection()
614
+ return [i8(c) for c in x], [i8(c) for c in y]
615
+
616
+ def histogram(self, mask=None, extrema=None):
617
+ """
618
+ Returns a histogram for the image. The histogram is returned as
619
+ a list of pixel counts, one for each pixel value in the source
620
+ image. If the image has more than one band, the histograms for
621
+ all bands are concatenated (for example, the histogram for an
622
+ "RGB" image contains 768 values).
623
+
624
+ A bilevel image (mode "1") is treated as a greyscale ("L") image
625
+ by this method.
626
+
627
+ If a mask is provided, the method returns a histogram for those
628
+ parts of the image where the mask image is non-zero. The mask
629
+ image must have the same size as the image, and be either a
630
+ bi-level image (mode "1") or a greyscale image ("L").
631
+
632
+ :param mask: An optional mask.
633
+ :returns: A list containing pixel counts.
634
+ """
635
+ self.load()
636
+ if mask:
637
+ mask.load()
638
+ return self.im.histogram((0, 0), mask.im)
639
+ if self.mode in ("I", "F"):
640
+ if extrema is None:
641
+ extrema = self.getextrema()
642
+ return self.im.histogram(extrema)
643
+ return self.im.histogram()
644
+
645
+ def offset(self, xoffset, yoffset=None):
646
+ """
647
+ .. deprecated:: 2.0
648
+
649
+ .. note:: New code should use :py:func:`PIL.ImageChops.offset`.
650
+
651
+ Returns a copy of the image where the data has been offset by the given
652
+ distances. Data wraps around the edges. If **yoffset** is omitted, it
653
+ is assumed to be equal to **xoffset**.
654
+
655
+ :param xoffset: The horizontal distance.
656
+ :param yoffset: The vertical distance. If omitted, both
657
+ distances are set to the same value.
658
+ :returns: An :py:class:`~PIL.Image.Image` object.
659
+ """
660
+ if warnings:
661
+ warnings.warn(
662
+ "'offset' is deprecated; use 'ImageChops.offset' instead",
663
+ DeprecationWarning, stacklevel=2
664
+ )
665
+ from PIL import ImageChops
666
+ return ImageChops.offset(self, xoffset, yoffset)
667
+
668
+ def paste(self, im, box=None, mask=None):
669
+ """
670
+ Pastes another image into this image. The box argument is either
671
+ a 2-tuple giving the upper left corner, a 4-tuple defining the
672
+ left, upper, right, and lower pixel coordinate, or None (same as
673
+ (0, 0)). If a 4-tuple is given, the size of the pasted image
674
+ must match the size of the region.
675
+
676
+ If the modes don't match, the pasted image is converted to the mode of
677
+ this image (see the :py:meth:`~PIL.Image.Image.convert` method for
678
+ details).
679
+
680
+ Instead of an image, the source can be a integer or tuple
681
+ containing pixel values. The method then fills the region
682
+ with the given color. When creating RGB images, you can
683
+ also use color strings as supported by the ImageColor module.
684
+
685
+ If a mask is given, this method updates only the regions
686
+ indicated by the mask. You can use either "1", "L" or "RGBA"
687
+ images (in the latter case, the alpha band is used as mask).
688
+ Where the mask is 255, the given image is copied as is. Where
689
+ the mask is 0, the current value is preserved. Intermediate
690
+ values can be used for transparency effects.
691
+
692
+ Note that if you paste an "RGBA" image, the alpha band is
693
+ ignored. You can work around this by using the same image as
694
+ both source image and mask.
695
+
696
+ :param im: Source image or pixel value (integer or tuple).
697
+ :param box: An optional 4-tuple giving the region to paste into.
698
+ If a 2-tuple is used instead, it's treated as the upper left
699
+ corner. If omitted or None, the source is pasted into the
700
+ upper left corner.
701
+
702
+ If an image is given as the second argument and there is no
703
+ third, the box defaults to (0, 0), and the second argument
704
+ is interpreted as a mask image.
705
+ :param mask: An optional mask image.
706
+ :returns: An :py:class:`~PIL.Image.Image` object.
707
+ """
708
+
709
+ if isImageType(box) and mask is None:
710
+ # abbreviated paste(im, mask) syntax
711
+ mask = box; box = None
712
+
713
+ if box is None:
714
+ # cover all of self
715
+ box = (0, 0) + self.size
716
+
717
+ if len(box) == 2:
718
+ # lower left corner given; get size from image or mask
719
+ if isImageType(im):
720
+ size = im.size
721
+ elif isImageType(mask):
722
+ size = mask.size
723
+ else:
724
+ # FIXME: use self.size here?
725
+ raise ValueError(
726
+ "cannot determine region size; use 4-item box"
727
+ )
728
+ box = box + (box[0]+size[0], box[1]+size[1])
729
+
730
+ if isStringType(im):
731
+ from PIL import ImageColor
732
+ im = ImageColor.getcolor(im, self.mode)
733
+
734
+ elif isImageType(im):
735
+ im.load()
736
+ if self.mode != im.mode:
737
+ if self.mode != "RGB" or im.mode not in ("RGBA", "RGBa"):
738
+ # should use an adapter for this!
739
+ im = im.convert(self.mode)
740
+ im = im.im
741
+
742
+ self.load()
743
+ if self.readonly:
744
+ self._copy()
745
+
746
+ if mask:
747
+ mask.load()
748
+ self.im.paste(im, box, mask.im)
749
+ else:
750
+ self.im.paste(im, box)
751
+
752
+ def point(self, lut, mode=None):
753
+ """
754
+ Maps this image through a lookup table or function.
755
+
756
+ :param lut: A lookup table, containing 256 (or 65336 if
757
+ self.mode=="I" and mode == "L") values per band in the
758
+ image. A function can be used instead, it should take a
759
+ single argument. The function is called once for each
760
+ possible pixel value, and the resulting table is applied to
761
+ all bands of the image.
762
+ :param mode: Output mode (default is same as input). In the
763
+ current version, this can only be used if the source image
764
+ has mode "L" or "P", and the output has mode "1" or the
765
+ source image mode is "I" and the output mode is "L".
766
+ :returns: An :py:class:`~PIL.Image.Image` object.
767
+ """
768
+
769
+ self.load()
770
+
771
+ if isinstance(lut, ImagePointHandler):
772
+ return lut.point(self)
773
+
774
+ if callable(lut):
775
+ # if it isn't a list, it should be a function
776
+ if self.mode in ("I", "I;16", "F"):
777
+ # check if the function can be used with point_transform
778
+ # UNDONE wiredfool -- I think this prevents us from ever doing
779
+ # a gamma function point transform on > 8bit images.
780
+ scale, offset = _getscaleoffset(lut)
781
+ return self._new(self.im.point_transform(scale, offset))
782
+ # for other modes, convert the function to a table
783
+ lut = [lut(i) for i in range(256)] * self.im.bands
784
+
785
+ if self.mode == "F":
786
+ # FIXME: _imaging returns a confusing error message for this case
787
+ raise ValueError("point operation not supported for this mode")
788
+
789
+ return self._new(self.im.point(lut, mode))
790
+
791
+ def putalpha(self, alpha):
792
+ """
793
+ Adds or replaces the alpha layer in this image. If the image
794
+ does not have an alpha layer, it's converted to "LA" or "RGBA".
795
+ The new layer must be either "L" or "1".
796
+
797
+ :param alpha: The new alpha layer. This can either be an "L" or "1"
798
+ image having the same size as this image, or an integer or
799
+ other color value.
800
+ """
801
+
802
+ self.load()
803
+ if self.readonly:
804
+ self._copy()
805
+
806
+ if self.mode not in ("LA", "RGBA"):
807
+ # attempt to promote self to a matching alpha mode
808
+ try:
809
+ mode = getmodebase(self.mode) + "A"
810
+ try:
811
+ self.im.setmode(mode)
812
+ except (AttributeError, ValueError):
813
+ # do things the hard way
814
+ im = self.im.convert(mode)
815
+ if im.mode not in ("LA", "RGBA"):
816
+ raise ValueError # sanity check
817
+ self.im = im
818
+ self.mode = self.im.mode
819
+ except (KeyError, ValueError):
820
+ raise ValueError("illegal image mode")
821
+
822
+ if self.mode == "LA":
823
+ band = 1
824
+ else:
825
+ band = 3
826
+
827
+ if isImageType(alpha):
828
+ # alpha layer
829
+ if alpha.mode not in ("1", "L"):
830
+ raise ValueError("illegal image mode")
831
+ alpha.load()
832
+ if alpha.mode == "1":
833
+ alpha = alpha.convert("L")
834
+ else:
835
+ # constant alpha
836
+ try:
837
+ self.im.fillband(band, alpha)
838
+ except (AttributeError, ValueError):
839
+ # do things the hard way
840
+ alpha = new("L", self.size, alpha)
841
+ else:
842
+ return
843
+
844
+ self.im.putband(alpha.im, band)
845
+
846
+ def putdata(self, data, scale=1.0, offset=0.0):
847
+ """
848
+ Copies pixel data to this image. This method copies data from a
849
+ sequence object into the image, starting at the upper left
850
+ corner (0, 0), and continuing until either the image or the
851
+ sequence ends. The scale and offset values are used to adjust
852
+ the sequence values: **pixel = value*scale + offset**.
853
+
854
+ :param data: A sequence object.
855
+ :param scale: An optional scale value. The default is 1.0.
856
+ :param offset: An optional offset value. The default is 0.0.
857
+ """
858
+
859
+ self.load()
860
+ if self.readonly:
861
+ self._copy()
862
+
863
+ self.im.putdata(data, scale, offset)
864
+
865
+ def putpalette(self, data, rawmode="RGB"):
866
+ """
867
+ Attaches a palette to this image. The image must be a "P" or
868
+ "L" image, and the palette sequence must contain 768 integer
869
+ values, where each group of three values represent the red,
870
+ green, and blue values for the corresponding pixel
871
+ index. Instead of an integer sequence, you can use an 8-bit
872
+ string.
873
+
874
+ :param data: A palette sequence (either a list or a string).
875
+ """
876
+ from PIL import ImagePalette
877
+
878
+ if self.mode not in ("L", "P"):
879
+ raise ValueError("illegal image mode")
880
+ self.load()
881
+ if isinstance(data, ImagePalette.ImagePalette):
882
+ palette = ImagePalette.raw(data.rawmode, data.palette)
883
+ else:
884
+ if not isinstance(data, bytes):
885
+ if bytes is str:
886
+ data = "".join(chr(x) for x in data)
887
+ else:
888
+ data = bytes(data)
889
+ palette = ImagePalette.raw(rawmode, data)
890
+ self.mode = "P"
891
+ self.palette = palette
892
+ self.palette.mode = "RGB"
893
+ self.load() # install new palette
894
+
895
+ def putpixel(self, xy, value):
896
+ """
897
+ Modifies the pixel at the given position. The color is given as
898
+ a single numerical value for single-band images, and a tuple for
899
+ multi-band images.
900
+
901
+ Note that this method is relatively slow. For more extensive changes,
902
+ use :py:meth:`~PIL.Image.Image.paste` or the :py:mod:`~PIL.ImageDraw`
903
+ module instead.
904
+
905
+ See:
906
+
907
+ * :py:meth:`~PIL.Image.Image.paste`
908
+ * :py:meth:`~PIL.Image.Image.putdata`
909
+ * :py:mod:`~PIL.ImageDraw`
910
+
911
+ :param xy: The pixel coordinate, given as (x, y).
912
+ :param value: The pixel value.
913
+ """
914
+
915
+ self.load()
916
+ if self.readonly:
917
+ self._copy()
918
+
919
+ return self.im.putpixel(xy, value)
920
+
921
+ def resize(self, size, resample=NEAREST):
922
+ """
923
+ Returns a resized copy of this image.
924
+
925
+ :param size: The requested size in pixels, as a 2-tuple:
926
+ (width, height).
927
+ :param filter: An optional resampling filter. This can be
928
+ one of :py:attr:`PIL.Image.NEAREST` (use nearest neighbour),
929
+ :py:attr:`PIL.Image.BILINEAR` (linear interpolation in a 2x2
930
+ environment), :py:attr:`PIL.Image.BICUBIC` (cubic spline
931
+ interpolation in a 4x4 environment), or
932
+ :py:attr:`PIL.Image.ANTIALIAS` (a high-quality downsampling filter).
933
+ If omitted, or if the image has mode "1" or "P", it is
934
+ set :py:attr:`PIL.Image.NEAREST`.
935
+ :returns: An :py:class:`~PIL.Image.Image` object.
936
+ """
937
+
938
+ if resample not in (NEAREST, BILINEAR, BICUBIC, ANTIALIAS):
939
+ raise ValueError("unknown resampling filter")
940
+
941
+ self.load()
942
+
943
+ if self.mode in ("1", "P"):
944
+ resample = NEAREST
945
+
946
+ if self.mode == 'RGBA':
947
+ return self.convert('RGBa').resize(size, resample).convert('RGBA')
948
+
949
+ if resample == ANTIALIAS:
950
+ # requires stretch support (imToolkit & PIL 1.1.3)
951
+ try:
952
+ im = self.im.stretch(size, resample)
953
+ except AttributeError:
954
+ raise ValueError("unsupported resampling filter")
955
+ else:
956
+ im = self.im.resize(size, resample)
957
+
958
+ return self._new(im)
959
+
960
+ def rotate(self, angle, resample=NEAREST, expand=0):
961
+ """
962
+ Returns a rotated copy of this image. This method returns a
963
+ copy of this image, rotated the given number of degrees counter
964
+ clockwise around its centre.
965
+
966
+ :param angle: In degrees counter clockwise.
967
+ :param filter: An optional resampling filter. This can be
968
+ one of :py:attr:`PIL.Image.NEAREST` (use nearest neighbour),
969
+ :py:attr:`PIL.Image.BILINEAR` (linear interpolation in a 2x2
970
+ environment), or :py:attr:`PIL.Image.BICUBIC`
971
+ (cubic spline interpolation in a 4x4 environment).
972
+ If omitted, or if the image has mode "1" or "P", it is
973
+ set :py:attr:`PIL.Image.NEAREST`.
974
+ :param expand: Optional expansion flag. If true, expands the output
975
+ image to make it large enough to hold the entire rotated image.
976
+ If false or omitted, make the output image the same size as the
977
+ input image.
978
+ :returns: An :py:class:`~PIL.Image.Image` object.
979
+ """
980
+
981
+ if expand:
982
+ import math
983
+ angle = -angle * math.pi / 180
984
+ matrix = [
985
+ math.cos(angle), math.sin(angle), 0.0,
986
+ -math.sin(angle), math.cos(angle), 0.0
987
+ ]
988
+ def transform(x, y, matrix=matrix):
989
+ (a, b, c, d, e, f) = matrix
990
+ return a*x + b*y + c, d*x + e*y + f
991
+
992
+ # calculate output size
993
+ w, h = self.size
994
+ xx = []
995
+ yy = []
996
+ for x, y in ((0, 0), (w, 0), (w, h), (0, h)):
997
+ x, y = transform(x, y)
998
+ xx.append(x)
999
+ yy.append(y)
1000
+ w = int(math.ceil(max(xx)) - math.floor(min(xx)))
1001
+ h = int(math.ceil(max(yy)) - math.floor(min(yy)))
1002
+
1003
+ # adjust center
1004
+ x, y = transform(w / 2.0, h / 2.0)
1005
+ matrix[2] = self.size[0] / 2.0 - x
1006
+ matrix[5] = self.size[1] / 2.0 - y
1007
+
1008
+ return self.transform((w, h), AFFINE, matrix, resample)
1009
+
1010
+ if resample not in (NEAREST, BILINEAR, BICUBIC):
1011
+ raise ValueError("unknown resampling filter")
1012
+
1013
+ self.load()
1014
+
1015
+ if self.mode in ("1", "P"):
1016
+ resample = NEAREST
1017
+
1018
+ return self._new(self.im.rotate(angle, resample))
1019
+
1020
+ def save(self, fp, format=None, **params):
1021
+ """
1022
+ Saves this image under the given filename. If no format is
1023
+ specified, the format to use is determined from the filename
1024
+ extension, if possible.
1025
+
1026
+ Keyword options can be used to provide additional instructions
1027
+ to the writer. If a writer doesn't recognise an option, it is
1028
+ silently ignored. The available options are described later in
1029
+ this handbook.
1030
+
1031
+ You can use a file object instead of a filename. In this case,
1032
+ you must always specify the format. The file object must
1033
+ implement the **seek**, **tell**, and **write**
1034
+ methods, and be opened in binary mode.
1035
+
1036
+ :param file: File name or file object.
1037
+ :param format: Optional format override. If omitted, the
1038
+ format to use is determined from the filename extension.
1039
+ If a file object was used instead of a filename, this
1040
+ parameter should always be used.
1041
+ :param options: Extra parameters to the image writer.
1042
+ :returns: None
1043
+ :exception KeyError: If the output format could not be determined
1044
+ from the file name. Use the format option to solve this.
1045
+ :exception IOError: If the file could not be written. The file
1046
+ may have been created, and may contain partial data.
1047
+ """
1048
+
1049
+ if isPath(fp):
1050
+ filename = fp
1051
+ else:
1052
+ if hasattr(fp, "name") and isPath(fp.name):
1053
+ filename = fp.name
1054
+ else:
1055
+ filename = ""
1056
+
1057
+ # may mutate self!
1058
+ self.load()
1059
+
1060
+ self.encoderinfo = params
1061
+ self.encoderconfig = ()
1062
+
1063
+ preinit()
1064
+
1065
+ ext = os.path.splitext(filename)[1].lower()
1066
+
1067
+ if not format:
1068
+ try:
1069
+ format = EXTENSION[ext]
1070
+ except KeyError:
1071
+ init()
1072
+ try:
1073
+ format = EXTENSION[ext]
1074
+ except KeyError:
1075
+ raise KeyError(ext) # unknown extension
1076
+
1077
+ try:
1078
+ save_handler = SAVE[format.upper()]
1079
+ except KeyError:
1080
+ init()
1081
+ save_handler = SAVE[format.upper()] # unknown format
1082
+
1083
+ if isPath(fp):
1084
+ fp = builtins.open(fp, "wb")
1085
+ close = 1
1086
+ else:
1087
+ close = 0
1088
+
1089
+ try:
1090
+ save_handler(self, fp, filename)
1091
+ finally:
1092
+ # do what we can to clean up
1093
+ if close:
1094
+ fp.close()
1095
+
1096
+ def seek(self, frame):
1097
+ """
1098
+ Seeks to the given frame in this sequence file. If you seek
1099
+ beyond the end of the sequence, the method raises an
1100
+ **EOFError** exception. When a sequence file is opened, the
1101
+ library automatically seeks to frame 0.
1102
+
1103
+ Note that in the current version of the library, most sequence
1104
+ formats only allows you to seek to the next frame.
1105
+
1106
+ See :py:meth:`~PIL.Image.Image.tell`.
1107
+
1108
+ :param frame: Frame number, starting at 0.
1109
+ :exception EOFError: If the call attempts to seek beyond the end
1110
+ of the sequence.
1111
+ """
1112
+
1113
+ # overridden by file handlers
1114
+ if frame != 0:
1115
+ raise EOFError
1116
+
1117
+ def show(self, title=None, command=None):
1118
+ """
1119
+ Displays this image. This method is mainly intended for
1120
+ debugging purposes.
1121
+
1122
+ On Unix platforms, this method saves the image to a temporary
1123
+ PPM file, and calls the **xv** utility.
1124
+
1125
+ On Windows, it saves the image to a temporary BMP file, and uses
1126
+ the standard BMP display utility to show it (usually Paint).
1127
+
1128
+ :param title: Optional title to use for the image window,
1129
+ where possible.
1130
+ :param command: command used to show the image
1131
+ """
1132
+
1133
+ _show(self, title=title, command=command)
1134
+
1135
+ def split(self):
1136
+ """
1137
+ Split this image into individual bands. This method returns a
1138
+ tuple of individual image bands from an image. For example,
1139
+ splitting an "RGB" image creates three new images each
1140
+ containing a copy of one of the original bands (red, green,
1141
+ blue).
1142
+
1143
+ :returns: A tuple containing bands.
1144
+ """
1145
+
1146
+ self.load()
1147
+ if self.im.bands == 1:
1148
+ ims = [self.copy()]
1149
+ else:
1150
+ ims = []
1151
+ for i in range(self.im.bands):
1152
+ ims.append(self._new(self.im.getband(i)))
1153
+ return tuple(ims)
1154
+
1155
+ def tell(self):
1156
+ """
1157
+ Returns the current frame number. See :py:meth:`~PIL.Image.Image.seek`.
1158
+
1159
+ :returns: Frame number, starting with 0.
1160
+ """
1161
+ return 0
1162
+
1163
+ def thumbnail(self, size, resample=NEAREST):
1164
+ """
1165
+ Make this image into a thumbnail. This method modifies the
1166
+ image to contain a thumbnail version of itself, no larger than
1167
+ the given size. This method calculates an appropriate thumbnail
1168
+ size to preserve the aspect of the image, calls the
1169
+ :py:meth:`~PIL.Image.Image.draft` method to configure the file reader
1170
+ (where applicable), and finally resizes the image.
1171
+
1172
+ Note that the bilinear and bicubic filters in the current
1173
+ version of PIL are not well-suited for thumbnail generation.
1174
+ You should use :py:attr:`PIL.Image.ANTIALIAS` unless speed is much more
1175
+ important than quality.
1176
+
1177
+ Also note that this function modifies the :py:class:`~PIL.Image.Image`
1178
+ object in place. If you need to use the full resolution image as well, apply
1179
+ this method to a :py:meth:`~PIL.Image.Image.copy` of the original image.
1180
+
1181
+ :param size: Requested size.
1182
+ :param resample: Optional resampling filter. This can be one
1183
+ of :py:attr:`PIL.Image.NEAREST`, :py:attr:`PIL.Image.BILINEAR`,
1184
+ :py:attr:`PIL.Image.BICUBIC`, or :py:attr:`PIL.Image.ANTIALIAS`
1185
+ (best quality). If omitted, it defaults to
1186
+ :py:attr:`PIL.Image.NEAREST` (this will be changed to ANTIALIAS in a
1187
+ future version).
1188
+ :returns: None
1189
+ """
1190
+
1191
+ # FIXME: the default resampling filter will be changed
1192
+ # to ANTIALIAS in future versions
1193
+
1194
+ # preserve aspect ratio
1195
+ x, y = self.size
1196
+ if x > size[0]: y = int(max(y * size[0] / x, 1)); x = int(size[0])
1197
+ if y > size[1]: x = int(max(x * size[1] / y, 1)); y = int(size[1])
1198
+ size = x, y
1199
+
1200
+ if size == self.size:
1201
+ return
1202
+
1203
+ self.draft(None, size)
1204
+
1205
+ self.load()
1206
+
1207
+ try:
1208
+ im = self.resize(size, resample)
1209
+ except ValueError:
1210
+ if resample != ANTIALIAS:
1211
+ raise
1212
+ im = self.resize(size, NEAREST) # fallback
1213
+
1214
+ self.im = im.im
1215
+ self.mode = im.mode
1216
+ self.size = size
1217
+
1218
+ self.readonly = 0
1219
+
1220
+ # FIXME: the different tranform methods need further explanation
1221
+ # instead of bloating the method docs, add a separate chapter.
1222
+ def transform(self, size, method, data=None, resample=NEAREST, fill=1):
1223
+ """
1224
+ Transforms this image. This method creates a new image with the
1225
+ given size, and the same mode as the original, and copies data
1226
+ to the new image using the given transform.
1227
+
1228
+ :param size: The output size.
1229
+ :param method: The transformation method. This is one of
1230
+ :py:attr:`PIL.Image.EXTENT` (cut out a rectangular subregion),
1231
+ :py:attr:`PIL.Image.AFFINE` (affine transform),
1232
+ :py:attr:`PIL.Image.PERSPECTIVE` (perspective transform),
1233
+ :py:attr:`PIL.Image.QUAD` (map a quadrilateral to a rectangle), or
1234
+ :py:attr:`PIL.Image.MESH` (map a number of source quadrilaterals
1235
+ in one operation).
1236
+ :param data: Extra data to the transformation method.
1237
+ :param resample: Optional resampling filter. It can be one of
1238
+ :py:attr:`PIL.Image.NEAREST` (use nearest neighbour),
1239
+ :py:attr:`PIL.Image.BILINEAR` (linear interpolation in a 2x2
1240
+ environment), or :py:attr:`PIL.Image.BICUBIC` (cubic spline
1241
+ interpolation in a 4x4 environment). If omitted, or if the image
1242
+ has mode "1" or "P", it is set to :py:attr:`PIL.Image.NEAREST`.
1243
+ :returns: An :py:class:`~PIL.Image.Image` object.
1244
+ """
1245
+
1246
+ if self.mode == 'RGBA':
1247
+ return self.convert('RGBa').transform(size, method, data, resample, fill).convert('RGBA')
1248
+
1249
+ if isinstance(method, ImageTransformHandler):
1250
+ return method.transform(size, self, resample=resample, fill=fill)
1251
+ if hasattr(method, "getdata"):
1252
+ # compatibility w. old-style transform objects
1253
+ method, data = method.getdata()
1254
+ if data is None:
1255
+ raise ValueError("missing method data")
1256
+
1257
+ im = new(self.mode, size, None)
1258
+ if method == MESH:
1259
+ # list of quads
1260
+ for box, quad in data:
1261
+ im.__transformer(box, self, QUAD, quad, resample, fill)
1262
+ else:
1263
+ im.__transformer((0, 0)+size, self, method, data, resample, fill)
1264
+
1265
+ return im
1266
+
1267
+ def __transformer(self, box, image, method, data,
1268
+ resample=NEAREST, fill=1):
1269
+
1270
+ # FIXME: this should be turned into a lazy operation (?)
1271
+
1272
+ w = box[2]-box[0]
1273
+ h = box[3]-box[1]
1274
+
1275
+ if method == AFFINE:
1276
+ # change argument order to match implementation
1277
+ data = (data[2], data[0], data[1],
1278
+ data[5], data[3], data[4])
1279
+ elif method == EXTENT:
1280
+ # convert extent to an affine transform
1281
+ x0, y0, x1, y1 = data
1282
+ xs = float(x1 - x0) / w
1283
+ ys = float(y1 - y0) / h
1284
+ method = AFFINE
1285
+ data = (x0 + xs/2, xs, 0, y0 + ys/2, 0, ys)
1286
+ elif method == PERSPECTIVE:
1287
+ # change argument order to match implementation
1288
+ data = (data[2], data[0], data[1],
1289
+ data[5], data[3], data[4],
1290
+ data[6], data[7])
1291
+ elif method == QUAD:
1292
+ # quadrilateral warp. data specifies the four corners
1293
+ # given as NW, SW, SE, and NE.
1294
+ nw = data[0:2]; sw = data[2:4]; se = data[4:6]; ne = data[6:8]
1295
+ x0, y0 = nw; As = 1.0 / w; At = 1.0 / h
1296
+ data = (x0, (ne[0]-x0)*As, (sw[0]-x0)*At,
1297
+ (se[0]-sw[0]-ne[0]+x0)*As*At,
1298
+ y0, (ne[1]-y0)*As, (sw[1]-y0)*At,
1299
+ (se[1]-sw[1]-ne[1]+y0)*As*At)
1300
+ else:
1301
+ raise ValueError("unknown transformation method")
1302
+
1303
+ if resample not in (NEAREST, BILINEAR, BICUBIC):
1304
+ raise ValueError("unknown resampling filter")
1305
+
1306
+ image.load()
1307
+
1308
+ self.load()
1309
+
1310
+ if image.mode in ("1", "P"):
1311
+ resample = NEAREST
1312
+
1313
+ self.im.transform2(box, image.im, method, data, resample, fill)
1314
+
1315
+ def transpose(self, method):
1316
+ """
1317
+ Transpose image (flip or rotate in 90 degree steps)
1318
+
1319
+ :param method: One of :py:attr:`PIL.Image.FLIP_LEFT_RIGHT`,
1320
+ :py:attr:`PIL.Image.FLIP_TOP_BOTTOM`, :py:attr:`PIL.Image.ROTATE_90`,
1321
+ :py:attr:`PIL.Image.ROTATE_180`, or :py:attr:`PIL.Image.ROTATE_270`.
1322
+ :returns: Returns a flipped or rotated copy of this image.
1323
+ """
1324
+
1325
+ self.load()
1326
+ im = self.im.transpose(method)
1327
+ return self._new(im)
1328
+ ```
1329
+
1330
+ ## `PIL/Image.py` — `function:Image._dump` (lines 497-510)
1331
+
1332
+ ```python
1333
+ def _dump(self, file=None, format=None):
1334
+ import tempfile, os
1335
+ if not file:
1336
+ f, file = tempfile.mkstemp(format or '')
1337
+ os.close(f)
1338
+
1339
+ self.load()
1340
+ if not format or format == "PPM":
1341
+ self.im.save_ppm(file)
1342
+ else:
1343
+ if file.endswith(format):
1344
+ file = file + "." + format
1345
+ self.save(file, format)
1346
+ return file
1347
+ ```
1348
+
1349
+ ## `PIL/IptcImagePlugin.py` — `class:IptcImageFile` (lines 53-204)
1350
+
1351
+ ```python
1352
+ class IptcImageFile(ImageFile.ImageFile):
1353
+
1354
+ format = "IPTC"
1355
+ format_description = "IPTC/NAA"
1356
+
1357
+ def getint(self, key):
1358
+ return i(self.info[key])
1359
+
1360
+ def field(self):
1361
+ #
1362
+ # get a IPTC field header
1363
+ s = self.fp.read(5)
1364
+ if not len(s):
1365
+ return None, 0
1366
+
1367
+ tag = i8(s[1]), i8(s[2])
1368
+
1369
+ # syntax
1370
+ if i8(s[0]) != 0x1C or tag[0] < 1 or tag[0] > 9:
1371
+ raise SyntaxError("invalid IPTC/NAA file")
1372
+
1373
+ # field size
1374
+ size = i8(s[3])
1375
+ if size > 132:
1376
+ raise IOError("illegal field length in IPTC/NAA file")
1377
+ elif size == 128:
1378
+ size = 0
1379
+ elif size > 128:
1380
+ size = i(self.fp.read(size-128))
1381
+ else:
1382
+ size = i16(s[3:])
1383
+
1384
+ return tag, size
1385
+
1386
+ def _is_raw(self, offset, size):
1387
+ #
1388
+ # check if the file can be mapped
1389
+
1390
+ # DISABLED: the following only slows things down...
1391
+ return 0
1392
+
1393
+ self.fp.seek(offset)
1394
+ t, sz = self.field()
1395
+ if sz != size[0]:
1396
+ return 0
1397
+ y = 1
1398
+ while True:
1399
+ self.fp.seek(sz, 1)
1400
+ t, s = self.field()
1401
+ if t != (8, 10):
1402
+ break
1403
+ if s != sz:
1404
+ return 0
1405
+ y = y + 1
1406
+ return y == size[1]
1407
+
1408
+ def _open(self):
1409
+
1410
+ # load descriptive fields
1411
+ while True:
1412
+ offset = self.fp.tell()
1413
+ tag, size = self.field()
1414
+ if not tag or tag == (8,10):
1415
+ break
1416
+ if size:
1417
+ tagdata = self.fp.read(size)
1418
+ else:
1419
+ tagdata = None
1420
+ if tag in list(self.info.keys()):
1421
+ if isinstance(self.info[tag], list):
1422
+ self.info[tag].append(tagdata)
1423
+ else:
1424
+ self.info[tag] = [self.info[tag], tagdata]
1425
+ else:
1426
+ self.info[tag] = tagdata
1427
+
1428
+ # print tag, self.info[tag]
1429
+
1430
+ # mode
1431
+ layers = i8(self.info[(3,60)][0])
1432
+ component = i8(self.info[(3,60)][1])
1433
+ if (3,65) in self.info:
1434
+ id = i8(self.info[(3,65)][0])-1
1435
+ else:
1436
+ id = 0
1437
+ if layers == 1 and not component:
1438
+ self.mode = "L"
1439
+ elif layers == 3 and component:
1440
+ self.mode = "RGB"[id]
1441
+ elif layers == 4 and component:
1442
+ self.mode = "CMYK"[id]
1443
+
1444
+ # size
1445
+ self.size = self.getint((3,20)), self.getint((3,30))
1446
+
1447
+ # compression
1448
+ try:
1449
+ compression = COMPRESSION[self.getint((3,120))]
1450
+ except KeyError:
1451
+ raise IOError("Unknown IPTC image compression")
1452
+
1453
+ # tile
1454
+ if tag == (8,10):
1455
+ if compression == "raw" and self._is_raw(offset, self.size):
1456
+ self.tile = [(compression, (offset, size + 5, -1),
1457
+ (0, 0, self.size[0], self.size[1]))]
1458
+ else:
1459
+ self.tile = [("iptc", (compression, offset),
1460
+ (0, 0, self.size[0], self.size[1]))]
1461
+
1462
+ def load(self):
1463
+
1464
+ if len(self.tile) != 1 or self.tile[0][0] != "iptc":
1465
+ return ImageFile.ImageFile.load(self)
1466
+
1467
+ type, tile, box = self.tile[0]
1468
+
1469
+ encoding, offset = tile
1470
+
1471
+ self.fp.seek(offset)
1472
+
1473
+ # Copy image data to temporary file
1474
+ o_fd, outfile = tempfile.mkstemp(text=False)
1475
+ o = os.fdopen(o_fd)
1476
+ if encoding == "raw":
1477
+ # To simplify access to the extracted file,
1478
+ # prepend a PPM header
1479
+ o.write("P5\n%d %d\n255\n" % self.size)
1480
+ while True:
1481
+ type, size = self.field()
1482
+ if type != (8, 10):
1483
+ break
1484
+ while size > 0:
1485
+ s = self.fp.read(min(size, 8192))
1486
+ if not s:
1487
+ break
1488
+ o.write(s)
1489
+ size = size - len(s)
1490
+ o.close()
1491
+
1492
+ try:
1493
+ try:
1494
+ # fast
1495
+ self.im = Image.core.open_ppm(outfile)
1496
+ except:
1497
+ # slightly slower
1498
+ im = Image.open(outfile)
1499
+ im.load()
1500
+ self.im = im.im
1501
+ finally:
1502
+ try: os.unlink(outfile)
1503
+ except: pass
1504
+ ```
1505
+
1506
+ ## `PIL/IptcImagePlugin.py` — `function:IptcImageFile.load` (lines 163-204)
1507
+
1508
+ ```python
1509
+ def load(self):
1510
+
1511
+ if len(self.tile) != 1 or self.tile[0][0] != "iptc":
1512
+ return ImageFile.ImageFile.load(self)
1513
+
1514
+ type, tile, box = self.tile[0]
1515
+
1516
+ encoding, offset = tile
1517
+
1518
+ self.fp.seek(offset)
1519
+
1520
+ # Copy image data to temporary file
1521
+ o_fd, outfile = tempfile.mkstemp(text=False)
1522
+ o = os.fdopen(o_fd)
1523
+ if encoding == "raw":
1524
+ # To simplify access to the extracted file,
1525
+ # prepend a PPM header
1526
+ o.write("P5\n%d %d\n255\n" % self.size)
1527
+ while True:
1528
+ type, size = self.field()
1529
+ if type != (8, 10):
1530
+ break
1531
+ while size > 0:
1532
+ s = self.fp.read(min(size, 8192))
1533
+ if not s:
1534
+ break
1535
+ o.write(s)
1536
+ size = size - len(s)
1537
+ o.close()
1538
+
1539
+ try:
1540
+ try:
1541
+ # fast
1542
+ self.im = Image.core.open_ppm(outfile)
1543
+ except:
1544
+ # slightly slower
1545
+ im = Image.open(outfile)
1546
+ im.load()
1547
+ self.im = im.im
1548
+ finally:
1549
+ try: os.unlink(outfile)
1550
+ except: pass
1551
+ ```
1552
+
1553
+ ## `PIL/JpegImagePlugin.py` — `class:JpegImageFile` (lines 267-366)
1554
+
1555
+ ```python
1556
+ class JpegImageFile(ImageFile.ImageFile):
1557
+
1558
+ format = "JPEG"
1559
+ format_description = "JPEG (ISO 10918)"
1560
+
1561
+ def _open(self):
1562
+
1563
+ s = self.fp.read(1)
1564
+
1565
+ if i8(s[0]) != 255:
1566
+ raise SyntaxError("not a JPEG file")
1567
+
1568
+ # Create attributes
1569
+ self.bits = self.layers = 0
1570
+
1571
+ # JPEG specifics (internal)
1572
+ self.layer = []
1573
+ self.huffman_dc = {}
1574
+ self.huffman_ac = {}
1575
+ self.quantization = {}
1576
+ self.app = {} # compatibility
1577
+ self.applist = []
1578
+ self.icclist = []
1579
+
1580
+ while True:
1581
+
1582
+ s = s + self.fp.read(1)
1583
+
1584
+ i = i16(s)
1585
+
1586
+ if i in MARKER:
1587
+ name, description, handler = MARKER[i]
1588
+ # print hex(i), name, description
1589
+ if handler is not None:
1590
+ handler(self, i)
1591
+ if i == 0xFFDA: # start of scan
1592
+ rawmode = self.mode
1593
+ if self.mode == "CMYK":
1594
+ rawmode = "CMYK;I" # assume adobe conventions
1595
+ self.tile = [("jpeg", (0,0) + self.size, 0, (rawmode, ""))]
1596
+ # self.__offset = self.fp.tell()
1597
+ break
1598
+ s = self.fp.read(1)
1599
+ elif i == 0 or i == 65535:
1600
+ # padded marker or junk; move on
1601
+ s = "\xff"
1602
+ else:
1603
+ raise SyntaxError("no marker found")
1604
+
1605
+ def draft(self, mode, size):
1606
+
1607
+ if len(self.tile) != 1:
1608
+ return
1609
+
1610
+ d, e, o, a = self.tile[0]
1611
+ scale = 0
1612
+
1613
+ if a[0] == "RGB" and mode in ["L", "YCbCr"]:
1614
+ self.mode = mode
1615
+ a = mode, ""
1616
+
1617
+ if size:
1618
+ scale = max(self.size[0] // size[0], self.size[1] // size[1])
1619
+ for s in [8, 4, 2, 1]:
1620
+ if scale >= s:
1621
+ break
1622
+ e = e[0], e[1], (e[2]-e[0]+s-1)//s+e[0], (e[3]-e[1]+s-1)//s+e[1]
1623
+ self.size = ((self.size[0]+s-1)//s, (self.size[1]+s-1)//s)
1624
+ scale = s
1625
+
1626
+ self.tile = [(d, e, o, a)]
1627
+ self.decoderconfig = (scale, 1)
1628
+
1629
+ return self
1630
+
1631
+ def load_djpeg(self):
1632
+
1633
+ # ALTERNATIVE: handle JPEGs via the IJG command line utilities
1634
+
1635
+ import tempfile, os
1636
+ f, path = tempfile.mkstemp()
1637
+ os.close(f)
1638
+ if os.path.exists(self.filename):
1639
+ os.system("djpeg '%s' >'%s'" % (self.filename, path))
1640
+ else:
1641
+ raise ValueError("Invalid Filename")
1642
+
1643
+ try:
1644
+ self.im = Image.core.open_ppm(path)
1645
+ finally:
1646
+ try: os.unlink(path)
1647
+ except: pass
1648
+
1649
+ self.mode = self.im.mode
1650
+ self.size = self.im.size
1651
+
1652
+ self.tile = []
1653
+
1654
+ def _getexif(self):
1655
+ return _getexif(self)
1656
+ ```
1657
+
1658
+ ## `PIL/JpegImagePlugin.py` — `function:JpegImageFile.load_djpeg` (lines 342-363)
1659
+
1660
+ ```python
1661
+ def load_djpeg(self):
1662
+
1663
+ # ALTERNATIVE: handle JPEGs via the IJG command line utilities
1664
+
1665
+ import tempfile, os
1666
+ f, path = tempfile.mkstemp()
1667
+ os.close(f)
1668
+ if os.path.exists(self.filename):
1669
+ os.system("djpeg '%s' >'%s'" % (self.filename, path))
1670
+ else:
1671
+ raise ValueError("Invalid Filename")
1672
+
1673
+ try:
1674
+ self.im = Image.core.open_ppm(path)
1675
+ finally:
1676
+ try: os.unlink(path)
1677
+ except: pass
1678
+
1679
+ self.mode = self.im.mode
1680
+ self.size = self.im.size
1681
+
1682
+ self.tile = []
1683
+ ```
tasks/codeql_python_benchmark51_v2/pyvul-4954e5890cce23c8b03d/pre_context.md ADDED
@@ -0,0 +1,1668 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Patch-overlapping Python context before the fix
2
+
3
+ ## `PIL/EpsImagePlugin.py` — `function:Ghostscript` (lines 53-109)
4
+
5
+ ```python
6
+ def Ghostscript(tile, size, fp, scale=1):
7
+ """Render an image using Ghostscript"""
8
+
9
+ # Unpack decoder tile
10
+ decoder, tile, offset, data = tile[0]
11
+ length, bbox = data
12
+
13
+ #Hack to support hi-res rendering
14
+ scale = int(scale) or 1
15
+ orig_size = size
16
+ orig_bbox = bbox
17
+ size = (size[0] * scale, size[1] * scale)
18
+ bbox = [bbox[0], bbox[1], bbox[2] * scale, bbox[3] * scale]
19
+ #print("Ghostscript", scale, size, orig_size, bbox, orig_bbox)
20
+
21
+ import tempfile, os, subprocess
22
+
23
+ file = tempfile.mktemp()
24
+
25
+ # Build ghostscript command
26
+ command = ["gs",
27
+ "-q", # quite mode
28
+ "-g%dx%d" % size, # set output geometry (pixels)
29
+ "-r%d" % (72*scale), # set input DPI (dots per inch)
30
+ "-dNOPAUSE -dSAFER", # don't pause between pages, safe mode
31
+ "-sDEVICE=ppmraw", # ppm driver
32
+ "-sOutputFile=%s" % file,# output file
33
+ ]
34
+
35
+ if gs_windows_binary is not None:
36
+ if gs_windows_binary is False:
37
+ raise WindowsError('Unable to locate Ghostscript on paths')
38
+ command[0] = gs_windows_binary
39
+
40
+ # push data through ghostscript
41
+ try:
42
+ gs = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
43
+ # adjust for image origin
44
+ if bbox[0] != 0 or bbox[1] != 0:
45
+ gs.stdin.write(("%d %d translate\n" % (-bbox[0], -bbox[1])).encode('ascii'))
46
+ fp.seek(offset)
47
+ while length > 0:
48
+ s = fp.read(8192)
49
+ if not s:
50
+ break
51
+ length = length - len(s)
52
+ gs.stdin.write(s)
53
+ gs.stdin.close()
54
+ status = gs.wait()
55
+ if status:
56
+ raise IOError("gs failed (status %d)" % status)
57
+ im = Image.core.open_ppm(file)
58
+ finally:
59
+ try: os.unlink(file)
60
+ except: pass
61
+
62
+ return im
63
+ ```
64
+
65
+ ## `PIL/Image.py` — `class:Image` (lines 447-1702)
66
+
67
+ ```python
68
+ class Image:
69
+ """
70
+ This class represents an image object. To create
71
+ :py:class:`~PIL.Image.Image` objects, use the appropriate factory
72
+ functions. There's hardly ever any reason to call the Image constructor
73
+ directly.
74
+
75
+ * :py:func:`~PIL.Image.open`
76
+ * :py:func:`~PIL.Image.new`
77
+ * :py:func:`~PIL.Image.frombytes`
78
+ """
79
+ format = None
80
+ format_description = None
81
+
82
+ def __init__(self):
83
+ # FIXME: take "new" parameters / other image?
84
+ # FIXME: turn mode and size into delegating properties?
85
+ self.im = None
86
+ self.mode = ""
87
+ self.size = (0, 0)
88
+ self.palette = None
89
+ self.info = {}
90
+ self.category = NORMAL
91
+ self.readonly = 0
92
+
93
+ def _new(self, im):
94
+ new = Image()
95
+ new.im = im
96
+ new.mode = im.mode
97
+ new.size = im.size
98
+ new.palette = self.palette
99
+ if im.mode == "P" and not new.palette:
100
+ from PIL import ImagePalette
101
+ new.palette = ImagePalette.ImagePalette()
102
+ try:
103
+ new.info = self.info.copy()
104
+ except AttributeError:
105
+ # fallback (pre-1.5.2)
106
+ new.info = {}
107
+ for k, v in self.info:
108
+ new.info[k] = v
109
+ return new
110
+
111
+ _makeself = _new # compatibility
112
+
113
+ def _copy(self):
114
+ self.load()
115
+ self.im = self.im.copy()
116
+ self.readonly = 0
117
+
118
+ def _dump(self, file=None, format=None):
119
+ import tempfile
120
+ if not file:
121
+ file = tempfile.mktemp()
122
+ self.load()
123
+ if not format or format == "PPM":
124
+ self.im.save_ppm(file)
125
+ else:
126
+ file = file + "." + format
127
+ self.save(file, format)
128
+ return file
129
+
130
+ def __repr__(self):
131
+ return "<%s.%s image mode=%s size=%dx%d at 0x%X>" % (
132
+ self.__class__.__module__, self.__class__.__name__,
133
+ self.mode, self.size[0], self.size[1],
134
+ id(self)
135
+ )
136
+
137
+ def __getattr__(self, name):
138
+ if name == "__array_interface__":
139
+ # numpy array interface support
140
+ new = {}
141
+ shape, typestr = _conv_type_shape(self)
142
+ new['shape'] = shape
143
+ new['typestr'] = typestr
144
+ new['data'] = self.tobytes()
145
+ return new
146
+ raise AttributeError(name)
147
+
148
+ def tobytes(self, encoder_name="raw", *args):
149
+ """
150
+ Return image as a bytes object
151
+
152
+ :param encoder_name: What encoder to use. The default is to
153
+ use the standard "raw" encoder.
154
+ :param args: Extra arguments to the encoder.
155
+ :rtype: A bytes object.
156
+ """
157
+
158
+ # may pass tuple instead of argument list
159
+ if len(args) == 1 and isinstance(args[0], tuple):
160
+ args = args[0]
161
+
162
+ if encoder_name == "raw" and args == ():
163
+ args = self.mode
164
+
165
+ self.load()
166
+
167
+ # unpack data
168
+ e = _getencoder(self.mode, encoder_name, args)
169
+ e.setimage(self.im)
170
+
171
+ bufsize = max(65536, self.size[0] * 4) # see RawEncode.c
172
+
173
+ data = []
174
+ while True:
175
+ l, s, d = e.encode(bufsize)
176
+ data.append(d)
177
+ if s:
178
+ break
179
+ if s < 0:
180
+ raise RuntimeError("encoder error %d in tobytes" % s)
181
+
182
+ return b"".join(data)
183
+
184
+ # Declare tostring as alias to tobytes
185
+ def tostring(self, *args, **kw):
186
+ warnings.warn(
187
+ 'tostring() is deprecated. Please call tobytes() instead.',
188
+ DeprecationWarning,
189
+ stacklevel=2,
190
+ )
191
+ return self.tobytes(*args, **kw)
192
+
193
+ def tobitmap(self, name="image"):
194
+ """
195
+ Returns the image converted to an X11 bitmap.
196
+
197
+ .. note:: This method only works for mode "1" images.
198
+
199
+ :param name: The name prefix to use for the bitmap variables.
200
+ :returns: A string containing an X11 bitmap.
201
+ :raises ValueError: If the mode is not "1"
202
+ """
203
+
204
+ self.load()
205
+ if self.mode != "1":
206
+ raise ValueError("not a bitmap")
207
+ data = self.tobytes("xbm")
208
+ return b"".join([("#define %s_width %d\n" % (name, self.size[0])).encode('ascii'),
209
+ ("#define %s_height %d\n"% (name, self.size[1])).encode('ascii'),
210
+ ("static char %s_bits[] = {\n" % name).encode('ascii'), data, b"};"])
211
+
212
+ def frombytes(self, data, decoder_name="raw", *args):
213
+ """
214
+ Loads this image with pixel data from a bytes object.
215
+
216
+ This method is similar to the :py:func:`~PIL.Image.frombytes` function,
217
+ but loads data into this image instead of creating a new image object.
218
+ """
219
+
220
+ # may pass tuple instead of argument list
221
+ if len(args) == 1 and isinstance(args[0], tuple):
222
+ args = args[0]
223
+
224
+ # default format
225
+ if decoder_name == "raw" and args == ():
226
+ args = self.mode
227
+
228
+ # unpack data
229
+ d = _getdecoder(self.mode, decoder_name, args)
230
+ d.setimage(self.im)
231
+ s = d.decode(data)
232
+
233
+ if s[0] >= 0:
234
+ raise ValueError("not enough image data")
235
+ if s[1] != 0:
236
+ raise ValueError("cannot decode image data")
237
+
238
+ def fromstring(self, *args, **kw):
239
+ """Deprecated alias to frombytes.
240
+
241
+ .. deprecated:: 2.0
242
+ """
243
+ warnings.warn('fromstring() is deprecated. Please call frombytes() instead.', DeprecationWarning)
244
+ return self.frombytes(*args, **kw)
245
+
246
+ def load(self):
247
+ """
248
+ Allocates storage for the image and loads the pixel data. In
249
+ normal cases, you don't need to call this method, since the
250
+ Image class automatically loads an opened image when it is
251
+ accessed for the first time.
252
+
253
+ :returns: An image access object.
254
+ """
255
+ if self.im and self.palette and self.palette.dirty:
256
+ # realize palette
257
+ self.im.putpalette(*self.palette.getdata())
258
+ self.palette.dirty = 0
259
+ self.palette.mode = "RGB"
260
+ self.palette.rawmode = None
261
+ if "transparency" in self.info:
262
+ if isinstance(self.info["transparency"], int):
263
+ self.im.putpalettealpha(self.info["transparency"], 0)
264
+ else:
265
+ self.im.putpalettealphas(self.info["transparency"])
266
+ self.palette.mode = "RGBA"
267
+
268
+ if self.im:
269
+ return self.im.pixel_access(self.readonly)
270
+
271
+ def verify(self):
272
+ """
273
+ Verifies the contents of a file. For data read from a file, this
274
+ method attempts to determine if the file is broken, without
275
+ actually decoding the image data. If this method finds any
276
+ problems, it raises suitable exceptions. If you need to load
277
+ the image after using this method, you must reopen the image
278
+ file.
279
+ """
280
+ pass
281
+
282
+ def convert(self, mode=None, matrix=None, dither=None,
283
+ palette=WEB, colors=256):
284
+ """
285
+ Returns a converted copy of this image. For the "P" mode, this
286
+ method translates pixels through the palette. If mode is
287
+ omitted, a mode is chosen so that all information in the image
288
+ and the palette can be represented without a palette.
289
+
290
+ The current version supports all possible conversions between
291
+ "L", "RGB" and "CMYK." The **matrix** argument only supports "L"
292
+ and "RGB".
293
+
294
+ When translating a color image to black and white (mode "L"),
295
+ the library uses the ITU-R 601-2 luma transform::
296
+
297
+ L = R * 299/1000 + G * 587/1000 + B * 114/1000
298
+
299
+ The default method of converting a greyscale ("L") or "RGB"
300
+ image into a bilevel (mode "1") image uses Floyd-Steinberg
301
+ dither to approximate the original image luminosity levels. If
302
+ dither is NONE, all non-zero values are set to 255 (white). To
303
+ use other thresholds, use the :py:meth:`~PIL.Image.Image.point`
304
+ method.
305
+
306
+ :param mode: The requested mode.
307
+ :param matrix: An optional conversion matrix. If given, this
308
+ should be 4- or 16-tuple containing floating point values.
309
+ :param dither: Dithering method, used when converting from
310
+ mode "RGB" to "P" or from "RGB" or "L" to "1".
311
+ Available methods are NONE or FLOYDSTEINBERG (default).
312
+ :param palette: Palette to use when converting from mode "RGB"
313
+ to "P". Available palettes are WEB or ADAPTIVE.
314
+ :param colors: Number of colors to use for the ADAPTIVE palette.
315
+ Defaults to 256.
316
+ :rtype: :py:class:`~PIL.Image.Image`
317
+ :returns: An :py:class:`~PIL.Image.Image` object.
318
+ """
319
+
320
+ if not mode:
321
+ # determine default mode
322
+ if self.mode == "P":
323
+ self.load()
324
+ if self.palette:
325
+ mode = self.palette.mode
326
+ else:
327
+ mode = "RGB"
328
+ else:
329
+ return self.copy()
330
+
331
+ self.load()
332
+
333
+ if matrix:
334
+ # matrix conversion
335
+ if mode not in ("L", "RGB"):
336
+ raise ValueError("illegal conversion")
337
+ im = self.im.convert_matrix(mode, matrix)
338
+ return self._new(im)
339
+
340
+ if mode == "P" and palette == ADAPTIVE:
341
+ im = self.im.quantize(colors)
342
+ return self._new(im)
343
+
344
+ # colorspace conversion
345
+ if dither is None:
346
+ dither = FLOYDSTEINBERG
347
+
348
+ # Use transparent conversion to promote from transparent color to an alpha channel.
349
+ if self.mode in ("L", "RGB") and mode == "RGBA" and "transparency" in self.info:
350
+ return self._new(self.im.convert_transparent(mode, self.info['transparency']))
351
+
352
+ try:
353
+ im = self.im.convert(mode, dither)
354
+ except ValueError:
355
+ try:
356
+ # normalize source image and try again
357
+ im = self.im.convert(getmodebase(self.mode))
358
+ im = im.convert(mode, dither)
359
+ except KeyError:
360
+ raise ValueError("illegal conversion")
361
+
362
+ return self._new(im)
363
+
364
+ def quantize(self, colors=256, method=0, kmeans=0, palette=None):
365
+
366
+ # methods:
367
+ # 0 = median cut
368
+ # 1 = maximum coverage
369
+ # 2 = fast octree
370
+
371
+ # NOTE: this functionality will be moved to the extended
372
+ # quantizer interface in a later version of PIL.
373
+
374
+ self.load()
375
+
376
+ if palette:
377
+ # use palette from reference image
378
+ palette.load()
379
+ if palette.mode != "P":
380
+ raise ValueError("bad mode for palette image")
381
+ if self.mode != "RGB" and self.mode != "L":
382
+ raise ValueError(
383
+ "only RGB or L mode images can be quantized to a palette"
384
+ )
385
+ im = self.im.convert("P", 1, palette.im)
386
+ return self._makeself(im)
387
+
388
+ im = self.im.quantize(colors, method, kmeans)
389
+ return self._new(im)
390
+
391
+ def copy(self):
392
+ """
393
+ Copies this image. Use this method if you wish to paste things
394
+ into an image, but still retain the original.
395
+
396
+ :rtype: :py:class:`~PIL.Image.Image`
397
+ :returns: An :py:class:`~PIL.Image.Image` object.
398
+ """
399
+ self.load()
400
+ im = self.im.copy()
401
+ return self._new(im)
402
+
403
+ def crop(self, box=None):
404
+ """
405
+ Returns a rectangular region from this image. The box is a
406
+ 4-tuple defining the left, upper, right, and lower pixel
407
+ coordinate.
408
+
409
+ This is a lazy operation. Changes to the source image may or
410
+ may not be reflected in the cropped image. To break the
411
+ connection, call the :py:meth:`~PIL.Image.Image.load` method on
412
+ the cropped copy.
413
+
414
+ :param box: The crop rectangle, as a (left, upper, right, lower)-tuple.
415
+ :rtype: :py:class:`~PIL.Image.Image`
416
+ :returns: An :py:class:`~PIL.Image.Image` object.
417
+ """
418
+
419
+ self.load()
420
+ if box is None:
421
+ return self.copy()
422
+
423
+ # lazy operation
424
+ return _ImageCrop(self, box)
425
+
426
+ def draft(self, mode, size):
427
+ """
428
+ Configures the image file loader so it returns a version of the
429
+ image that as closely as possible matches the given mode and
430
+ size. For example, you can use this method to convert a color
431
+ JPEG to greyscale while loading it, or to extract a 128x192
432
+ version from a PCD file.
433
+
434
+ Note that this method modifies the :py:class:`~PIL.Image.Image` object
435
+ in place. If the image has already been loaded, this method has no
436
+ effect.
437
+
438
+ :param mode: The requested mode.
439
+ :param size: The requested size.
440
+ """
441
+ pass
442
+
443
+ def _expand(self, xmargin, ymargin=None):
444
+ if ymargin is None:
445
+ ymargin = xmargin
446
+ self.load()
447
+ return self._new(self.im.expand(xmargin, ymargin, 0))
448
+
449
+ def filter(self, filter):
450
+ """
451
+ Filters this image using the given filter. For a list of
452
+ available filters, see the :py:mod:`~PIL.ImageFilter` module.
453
+
454
+ :param filter: Filter kernel.
455
+ :returns: An :py:class:`~PIL.Image.Image` object. """
456
+
457
+ self.load()
458
+
459
+ if isinstance(filter, collections.Callable):
460
+ filter = filter()
461
+ if not hasattr(filter, "filter"):
462
+ raise TypeError("filter argument should be ImageFilter.Filter instance or class")
463
+
464
+ if self.im.bands == 1:
465
+ return self._new(filter.filter(self.im))
466
+ # fix to handle multiband images since _imaging doesn't
467
+ ims = []
468
+ for c in range(self.im.bands):
469
+ ims.append(self._new(filter.filter(self.im.getband(c))))
470
+ return merge(self.mode, ims)
471
+
472
+ def getbands(self):
473
+ """
474
+ Returns a tuple containing the name of each band in this image.
475
+ For example, **getbands** on an RGB image returns ("R", "G", "B").
476
+
477
+ :returns: A tuple containing band names.
478
+ :rtype: tuple
479
+ """
480
+ return ImageMode.getmode(self.mode).bands
481
+
482
+ def getbbox(self):
483
+ """
484
+ Calculates the bounding box of the non-zero regions in the
485
+ image.
486
+
487
+ :returns: The bounding box is returned as a 4-tuple defining the
488
+ left, upper, right, and lower pixel coordinate. If the image
489
+ is completely empty, this method returns None.
490
+
491
+ """
492
+
493
+ self.load()
494
+ return self.im.getbbox()
495
+
496
+ def getcolors(self, maxcolors=256):
497
+ """
498
+ Returns a list of colors used in this image.
499
+
500
+ :param maxcolors: Maximum number of colors. If this number is
501
+ exceeded, this method returns None. The default limit is
502
+ 256 colors.
503
+ :returns: An unsorted list of (count, pixel) values.
504
+ """
505
+
506
+ self.load()
507
+ if self.mode in ("1", "L", "P"):
508
+ h = self.im.histogram()
509
+ out = []
510
+ for i in range(256):
511
+ if h[i]:
512
+ out.append((h[i], i))
513
+ if len(out) > maxcolors:
514
+ return None
515
+ return out
516
+ return self.im.getcolors(maxcolors)
517
+
518
+ def getdata(self, band = None):
519
+ """
520
+ Returns the contents of this image as a sequence object
521
+ containing pixel values. The sequence object is flattened, so
522
+ that values for line one follow directly after the values of
523
+ line zero, and so on.
524
+
525
+ Note that the sequence object returned by this method is an
526
+ internal PIL data type, which only supports certain sequence
527
+ operations. To convert it to an ordinary sequence (e.g. for
528
+ printing), use **list(im.getdata())**.
529
+
530
+ :param band: What band to return. The default is to return
531
+ all bands. To return a single band, pass in the index
532
+ value (e.g. 0 to get the "R" band from an "RGB" image).
533
+ :returns: A sequence-like object.
534
+ """
535
+
536
+ self.load()
537
+ if band is not None:
538
+ return self.im.getband(band)
539
+ return self.im # could be abused
540
+
541
+ def getextrema(self):
542
+ """
543
+ Gets the the minimum and maximum pixel values for each band in
544
+ the image.
545
+
546
+ :returns: For a single-band image, a 2-tuple containing the
547
+ minimum and maximum pixel value. For a multi-band image,
548
+ a tuple containing one 2-tuple for each band.
549
+ """
550
+
551
+ self.load()
552
+ if self.im.bands > 1:
553
+ extrema = []
554
+ for i in range(self.im.bands):
555
+ extrema.append(self.im.getband(i).getextrema())
556
+ return tuple(extrema)
557
+ return self.im.getextrema()
558
+
559
+ def getim(self):
560
+ """
561
+ Returns a capsule that points to the internal image memory.
562
+
563
+ :returns: A capsule object.
564
+ """
565
+
566
+ self.load()
567
+ return self.im.ptr
568
+
569
+
570
+ def getpalette(self):
571
+ """
572
+ Returns the image palette as a list.
573
+
574
+ :returns: A list of color values [r, g, b, ...], or None if the
575
+ image has no palette.
576
+ """
577
+
578
+ self.load()
579
+ try:
580
+ if bytes is str:
581
+ return [i8(c) for c in self.im.getpalette()]
582
+ else:
583
+ return list(self.im.getpalette())
584
+ except ValueError:
585
+ return None # no palette
586
+
587
+
588
+ def getpixel(self, xy):
589
+ """
590
+ Returns the pixel value at a given position.
591
+
592
+ :param xy: The coordinate, given as (x, y).
593
+ :returns: The pixel value. If the image is a multi-layer image,
594
+ this method returns a tuple.
595
+ """
596
+
597
+ self.load()
598
+ return self.im.getpixel(xy)
599
+
600
+ def getprojection(self):
601
+ """
602
+ Get projection to x and y axes
603
+
604
+ :returns: Two sequences, indicating where there are non-zero
605
+ pixels along the X-axis and the Y-axis, respectively.
606
+ """
607
+
608
+ self.load()
609
+ x, y = self.im.getprojection()
610
+ return [i8(c) for c in x], [i8(c) for c in y]
611
+
612
+ def histogram(self, mask=None, extrema=None):
613
+ """
614
+ Returns a histogram for the image. The histogram is returned as
615
+ a list of pixel counts, one for each pixel value in the source
616
+ image. If the image has more than one band, the histograms for
617
+ all bands are concatenated (for example, the histogram for an
618
+ "RGB" image contains 768 values).
619
+
620
+ A bilevel image (mode "1") is treated as a greyscale ("L") image
621
+ by this method.
622
+
623
+ If a mask is provided, the method returns a histogram for those
624
+ parts of the image where the mask image is non-zero. The mask
625
+ image must have the same size as the image, and be either a
626
+ bi-level image (mode "1") or a greyscale image ("L").
627
+
628
+ :param mask: An optional mask.
629
+ :returns: A list containing pixel counts.
630
+ """
631
+ self.load()
632
+ if mask:
633
+ mask.load()
634
+ return self.im.histogram((0, 0), mask.im)
635
+ if self.mode in ("I", "F"):
636
+ if extrema is None:
637
+ extrema = self.getextrema()
638
+ return self.im.histogram(extrema)
639
+ return self.im.histogram()
640
+
641
+ def offset(self, xoffset, yoffset=None):
642
+ """
643
+ .. deprecated:: 2.0
644
+
645
+ .. note:: New code should use :py:func:`PIL.ImageChops.offset`.
646
+
647
+ Returns a copy of the image where the data has been offset by the given
648
+ distances. Data wraps around the edges. If **yoffset** is omitted, it
649
+ is assumed to be equal to **xoffset**.
650
+
651
+ :param xoffset: The horizontal distance.
652
+ :param yoffset: The vertical distance. If omitted, both
653
+ distances are set to the same value.
654
+ :returns: An :py:class:`~PIL.Image.Image` object.
655
+ """
656
+ if warnings:
657
+ warnings.warn(
658
+ "'offset' is deprecated; use 'ImageChops.offset' instead",
659
+ DeprecationWarning, stacklevel=2
660
+ )
661
+ from PIL import ImageChops
662
+ return ImageChops.offset(self, xoffset, yoffset)
663
+
664
+ def paste(self, im, box=None, mask=None):
665
+ """
666
+ Pastes another image into this image. The box argument is either
667
+ a 2-tuple giving the upper left corner, a 4-tuple defining the
668
+ left, upper, right, and lower pixel coordinate, or None (same as
669
+ (0, 0)). If a 4-tuple is given, the size of the pasted image
670
+ must match the size of the region.
671
+
672
+ If the modes don't match, the pasted image is converted to the mode of
673
+ this image (see the :py:meth:`~PIL.Image.Image.convert` method for
674
+ details).
675
+
676
+ Instead of an image, the source can be a integer or tuple
677
+ containing pixel values. The method then fills the region
678
+ with the given color. When creating RGB images, you can
679
+ also use color strings as supported by the ImageColor module.
680
+
681
+ If a mask is given, this method updates only the regions
682
+ indicated by the mask. You can use either "1", "L" or "RGBA"
683
+ images (in the latter case, the alpha band is used as mask).
684
+ Where the mask is 255, the given image is copied as is. Where
685
+ the mask is 0, the current value is preserved. Intermediate
686
+ values can be used for transparency effects.
687
+
688
+ Note that if you paste an "RGBA" image, the alpha band is
689
+ ignored. You can work around this by using the same image as
690
+ both source image and mask.
691
+
692
+ :param im: Source image or pixel value (integer or tuple).
693
+ :param box: An optional 4-tuple giving the region to paste into.
694
+ If a 2-tuple is used instead, it's treated as the upper left
695
+ corner. If omitted or None, the source is pasted into the
696
+ upper left corner.
697
+
698
+ If an image is given as the second argument and there is no
699
+ third, the box defaults to (0, 0), and the second argument
700
+ is interpreted as a mask image.
701
+ :param mask: An optional mask image.
702
+ :returns: An :py:class:`~PIL.Image.Image` object.
703
+ """
704
+
705
+ if isImageType(box) and mask is None:
706
+ # abbreviated paste(im, mask) syntax
707
+ mask = box; box = None
708
+
709
+ if box is None:
710
+ # cover all of self
711
+ box = (0, 0) + self.size
712
+
713
+ if len(box) == 2:
714
+ # lower left corner given; get size from image or mask
715
+ if isImageType(im):
716
+ size = im.size
717
+ elif isImageType(mask):
718
+ size = mask.size
719
+ else:
720
+ # FIXME: use self.size here?
721
+ raise ValueError(
722
+ "cannot determine region size; use 4-item box"
723
+ )
724
+ box = box + (box[0]+size[0], box[1]+size[1])
725
+
726
+ if isStringType(im):
727
+ from PIL import ImageColor
728
+ im = ImageColor.getcolor(im, self.mode)
729
+
730
+ elif isImageType(im):
731
+ im.load()
732
+ if self.mode != im.mode:
733
+ if self.mode != "RGB" or im.mode not in ("RGBA", "RGBa"):
734
+ # should use an adapter for this!
735
+ im = im.convert(self.mode)
736
+ im = im.im
737
+
738
+ self.load()
739
+ if self.readonly:
740
+ self._copy()
741
+
742
+ if mask:
743
+ mask.load()
744
+ self.im.paste(im, box, mask.im)
745
+ else:
746
+ self.im.paste(im, box)
747
+
748
+ def point(self, lut, mode=None):
749
+ """
750
+ Maps this image through a lookup table or function.
751
+
752
+ :param lut: A lookup table, containing 256 (or 65336 if
753
+ self.mode=="I" and mode == "L") values per band in the
754
+ image. A function can be used instead, it should take a
755
+ single argument. The function is called once for each
756
+ possible pixel value, and the resulting table is applied to
757
+ all bands of the image.
758
+ :param mode: Output mode (default is same as input). In the
759
+ current version, this can only be used if the source image
760
+ has mode "L" or "P", and the output has mode "1" or the
761
+ source image mode is "I" and the output mode is "L".
762
+ :returns: An :py:class:`~PIL.Image.Image` object.
763
+ """
764
+
765
+ self.load()
766
+
767
+ if isinstance(lut, ImagePointHandler):
768
+ return lut.point(self)
769
+
770
+ if callable(lut):
771
+ # if it isn't a list, it should be a function
772
+ if self.mode in ("I", "I;16", "F"):
773
+ # check if the function can be used with point_transform
774
+ # UNDONE wiredfool -- I think this prevents us from ever doing
775
+ # a gamma function point transform on > 8bit images.
776
+ scale, offset = _getscaleoffset(lut)
777
+ return self._new(self.im.point_transform(scale, offset))
778
+ # for other modes, convert the function to a table
779
+ lut = [lut(i) for i in range(256)] * self.im.bands
780
+
781
+ if self.mode == "F":
782
+ # FIXME: _imaging returns a confusing error message for this case
783
+ raise ValueError("point operation not supported for this mode")
784
+
785
+ return self._new(self.im.point(lut, mode))
786
+
787
+ def putalpha(self, alpha):
788
+ """
789
+ Adds or replaces the alpha layer in this image. If the image
790
+ does not have an alpha layer, it's converted to "LA" or "RGBA".
791
+ The new layer must be either "L" or "1".
792
+
793
+ :param alpha: The new alpha layer. This can either be an "L" or "1"
794
+ image having the same size as this image, or an integer or
795
+ other color value.
796
+ """
797
+
798
+ self.load()
799
+ if self.readonly:
800
+ self._copy()
801
+
802
+ if self.mode not in ("LA", "RGBA"):
803
+ # attempt to promote self to a matching alpha mode
804
+ try:
805
+ mode = getmodebase(self.mode) + "A"
806
+ try:
807
+ self.im.setmode(mode)
808
+ except (AttributeError, ValueError):
809
+ # do things the hard way
810
+ im = self.im.convert(mode)
811
+ if im.mode not in ("LA", "RGBA"):
812
+ raise ValueError # sanity check
813
+ self.im = im
814
+ self.mode = self.im.mode
815
+ except (KeyError, ValueError):
816
+ raise ValueError("illegal image mode")
817
+
818
+ if self.mode == "LA":
819
+ band = 1
820
+ else:
821
+ band = 3
822
+
823
+ if isImageType(alpha):
824
+ # alpha layer
825
+ if alpha.mode not in ("1", "L"):
826
+ raise ValueError("illegal image mode")
827
+ alpha.load()
828
+ if alpha.mode == "1":
829
+ alpha = alpha.convert("L")
830
+ else:
831
+ # constant alpha
832
+ try:
833
+ self.im.fillband(band, alpha)
834
+ except (AttributeError, ValueError):
835
+ # do things the hard way
836
+ alpha = new("L", self.size, alpha)
837
+ else:
838
+ return
839
+
840
+ self.im.putband(alpha.im, band)
841
+
842
+ def putdata(self, data, scale=1.0, offset=0.0):
843
+ """
844
+ Copies pixel data to this image. This method copies data from a
845
+ sequence object into the image, starting at the upper left
846
+ corner (0, 0), and continuing until either the image or the
847
+ sequence ends. The scale and offset values are used to adjust
848
+ the sequence values: **pixel = value*scale + offset**.
849
+
850
+ :param data: A sequence object.
851
+ :param scale: An optional scale value. The default is 1.0.
852
+ :param offset: An optional offset value. The default is 0.0.
853
+ """
854
+
855
+ self.load()
856
+ if self.readonly:
857
+ self._copy()
858
+
859
+ self.im.putdata(data, scale, offset)
860
+
861
+ def putpalette(self, data, rawmode="RGB"):
862
+ """
863
+ Attaches a palette to this image. The image must be a "P" or
864
+ "L" image, and the palette sequence must contain 768 integer
865
+ values, where each group of three values represent the red,
866
+ green, and blue values for the corresponding pixel
867
+ index. Instead of an integer sequence, you can use an 8-bit
868
+ string.
869
+
870
+ :param data: A palette sequence (either a list or a string).
871
+ """
872
+ from PIL import ImagePalette
873
+
874
+ if self.mode not in ("L", "P"):
875
+ raise ValueError("illegal image mode")
876
+ self.load()
877
+ if isinstance(data, ImagePalette.ImagePalette):
878
+ palette = ImagePalette.raw(data.rawmode, data.palette)
879
+ else:
880
+ if not isinstance(data, bytes):
881
+ if bytes is str:
882
+ data = "".join(chr(x) for x in data)
883
+ else:
884
+ data = bytes(data)
885
+ palette = ImagePalette.raw(rawmode, data)
886
+ self.mode = "P"
887
+ self.palette = palette
888
+ self.palette.mode = "RGB"
889
+ self.load() # install new palette
890
+
891
+ def putpixel(self, xy, value):
892
+ """
893
+ Modifies the pixel at the given position. The color is given as
894
+ a single numerical value for single-band images, and a tuple for
895
+ multi-band images.
896
+
897
+ Note that this method is relatively slow. For more extensive changes,
898
+ use :py:meth:`~PIL.Image.Image.paste` or the :py:mod:`~PIL.ImageDraw`
899
+ module instead.
900
+
901
+ See:
902
+
903
+ * :py:meth:`~PIL.Image.Image.paste`
904
+ * :py:meth:`~PIL.Image.Image.putdata`
905
+ * :py:mod:`~PIL.ImageDraw`
906
+
907
+ :param xy: The pixel coordinate, given as (x, y).
908
+ :param value: The pixel value.
909
+ """
910
+
911
+ self.load()
912
+ if self.readonly:
913
+ self._copy()
914
+
915
+ return self.im.putpixel(xy, value)
916
+
917
+ def resize(self, size, resample=NEAREST):
918
+ """
919
+ Returns a resized copy of this image.
920
+
921
+ :param size: The requested size in pixels, as a 2-tuple:
922
+ (width, height).
923
+ :param filter: An optional resampling filter. This can be
924
+ one of :py:attr:`PIL.Image.NEAREST` (use nearest neighbour),
925
+ :py:attr:`PIL.Image.BILINEAR` (linear interpolation in a 2x2
926
+ environment), :py:attr:`PIL.Image.BICUBIC` (cubic spline
927
+ interpolation in a 4x4 environment), or
928
+ :py:attr:`PIL.Image.ANTIALIAS` (a high-quality downsampling filter).
929
+ If omitted, or if the image has mode "1" or "P", it is
930
+ set :py:attr:`PIL.Image.NEAREST`.
931
+ :returns: An :py:class:`~PIL.Image.Image` object.
932
+ """
933
+
934
+ if resample not in (NEAREST, BILINEAR, BICUBIC, ANTIALIAS):
935
+ raise ValueError("unknown resampling filter")
936
+
937
+ self.load()
938
+
939
+ if self.mode in ("1", "P"):
940
+ resample = NEAREST
941
+
942
+ if self.mode == 'RGBA':
943
+ return self.convert('RGBa').resize(size, resample).convert('RGBA')
944
+
945
+ if resample == ANTIALIAS:
946
+ # requires stretch support (imToolkit & PIL 1.1.3)
947
+ try:
948
+ im = self.im.stretch(size, resample)
949
+ except AttributeError:
950
+ raise ValueError("unsupported resampling filter")
951
+ else:
952
+ im = self.im.resize(size, resample)
953
+
954
+ return self._new(im)
955
+
956
+ def rotate(self, angle, resample=NEAREST, expand=0):
957
+ """
958
+ Returns a rotated copy of this image. This method returns a
959
+ copy of this image, rotated the given number of degrees counter
960
+ clockwise around its centre.
961
+
962
+ :param angle: In degrees counter clockwise.
963
+ :param filter: An optional resampling filter. This can be
964
+ one of :py:attr:`PIL.Image.NEAREST` (use nearest neighbour),
965
+ :py:attr:`PIL.Image.BILINEAR` (linear interpolation in a 2x2
966
+ environment), or :py:attr:`PIL.Image.BICUBIC`
967
+ (cubic spline interpolation in a 4x4 environment).
968
+ If omitted, or if the image has mode "1" or "P", it is
969
+ set :py:attr:`PIL.Image.NEAREST`.
970
+ :param expand: Optional expansion flag. If true, expands the output
971
+ image to make it large enough to hold the entire rotated image.
972
+ If false or omitted, make the output image the same size as the
973
+ input image.
974
+ :returns: An :py:class:`~PIL.Image.Image` object.
975
+ """
976
+
977
+ if expand:
978
+ import math
979
+ angle = -angle * math.pi / 180
980
+ matrix = [
981
+ math.cos(angle), math.sin(angle), 0.0,
982
+ -math.sin(angle), math.cos(angle), 0.0
983
+ ]
984
+ def transform(x, y, matrix=matrix):
985
+ (a, b, c, d, e, f) = matrix
986
+ return a*x + b*y + c, d*x + e*y + f
987
+
988
+ # calculate output size
989
+ w, h = self.size
990
+ xx = []
991
+ yy = []
992
+ for x, y in ((0, 0), (w, 0), (w, h), (0, h)):
993
+ x, y = transform(x, y)
994
+ xx.append(x)
995
+ yy.append(y)
996
+ w = int(math.ceil(max(xx)) - math.floor(min(xx)))
997
+ h = int(math.ceil(max(yy)) - math.floor(min(yy)))
998
+
999
+ # adjust center
1000
+ x, y = transform(w / 2.0, h / 2.0)
1001
+ matrix[2] = self.size[0] / 2.0 - x
1002
+ matrix[5] = self.size[1] / 2.0 - y
1003
+
1004
+ return self.transform((w, h), AFFINE, matrix, resample)
1005
+
1006
+ if resample not in (NEAREST, BILINEAR, BICUBIC):
1007
+ raise ValueError("unknown resampling filter")
1008
+
1009
+ self.load()
1010
+
1011
+ if self.mode in ("1", "P"):
1012
+ resample = NEAREST
1013
+
1014
+ return self._new(self.im.rotate(angle, resample))
1015
+
1016
+ def save(self, fp, format=None, **params):
1017
+ """
1018
+ Saves this image under the given filename. If no format is
1019
+ specified, the format to use is determined from the filename
1020
+ extension, if possible.
1021
+
1022
+ Keyword options can be used to provide additional instructions
1023
+ to the writer. If a writer doesn't recognise an option, it is
1024
+ silently ignored. The available options are described later in
1025
+ this handbook.
1026
+
1027
+ You can use a file object instead of a filename. In this case,
1028
+ you must always specify the format. The file object must
1029
+ implement the **seek**, **tell**, and **write**
1030
+ methods, and be opened in binary mode.
1031
+
1032
+ :param file: File name or file object.
1033
+ :param format: Optional format override. If omitted, the
1034
+ format to use is determined from the filename extension.
1035
+ If a file object was used instead of a filename, this
1036
+ parameter should always be used.
1037
+ :param options: Extra parameters to the image writer.
1038
+ :returns: None
1039
+ :exception KeyError: If the output format could not be determined
1040
+ from the file name. Use the format option to solve this.
1041
+ :exception IOError: If the file could not be written. The file
1042
+ may have been created, and may contain partial data.
1043
+ """
1044
+
1045
+ if isPath(fp):
1046
+ filename = fp
1047
+ else:
1048
+ if hasattr(fp, "name") and isPath(fp.name):
1049
+ filename = fp.name
1050
+ else:
1051
+ filename = ""
1052
+
1053
+ # may mutate self!
1054
+ self.load()
1055
+
1056
+ self.encoderinfo = params
1057
+ self.encoderconfig = ()
1058
+
1059
+ preinit()
1060
+
1061
+ ext = os.path.splitext(filename)[1].lower()
1062
+
1063
+ if not format:
1064
+ try:
1065
+ format = EXTENSION[ext]
1066
+ except KeyError:
1067
+ init()
1068
+ try:
1069
+ format = EXTENSION[ext]
1070
+ except KeyError:
1071
+ raise KeyError(ext) # unknown extension
1072
+
1073
+ try:
1074
+ save_handler = SAVE[format.upper()]
1075
+ except KeyError:
1076
+ init()
1077
+ save_handler = SAVE[format.upper()] # unknown format
1078
+
1079
+ if isPath(fp):
1080
+ fp = builtins.open(fp, "wb")
1081
+ close = 1
1082
+ else:
1083
+ close = 0
1084
+
1085
+ try:
1086
+ save_handler(self, fp, filename)
1087
+ finally:
1088
+ # do what we can to clean up
1089
+ if close:
1090
+ fp.close()
1091
+
1092
+ def seek(self, frame):
1093
+ """
1094
+ Seeks to the given frame in this sequence file. If you seek
1095
+ beyond the end of the sequence, the method raises an
1096
+ **EOFError** exception. When a sequence file is opened, the
1097
+ library automatically seeks to frame 0.
1098
+
1099
+ Note that in the current version of the library, most sequence
1100
+ formats only allows you to seek to the next frame.
1101
+
1102
+ See :py:meth:`~PIL.Image.Image.tell`.
1103
+
1104
+ :param frame: Frame number, starting at 0.
1105
+ :exception EOFError: If the call attempts to seek beyond the end
1106
+ of the sequence.
1107
+ """
1108
+
1109
+ # overridden by file handlers
1110
+ if frame != 0:
1111
+ raise EOFError
1112
+
1113
+ def show(self, title=None, command=None):
1114
+ """
1115
+ Displays this image. This method is mainly intended for
1116
+ debugging purposes.
1117
+
1118
+ On Unix platforms, this method saves the image to a temporary
1119
+ PPM file, and calls the **xv** utility.
1120
+
1121
+ On Windows, it saves the image to a temporary BMP file, and uses
1122
+ the standard BMP display utility to show it (usually Paint).
1123
+
1124
+ :param title: Optional title to use for the image window,
1125
+ where possible.
1126
+ :param command: command used to show the image
1127
+ """
1128
+
1129
+ _show(self, title=title, command=command)
1130
+
1131
+ def split(self):
1132
+ """
1133
+ Split this image into individual bands. This method returns a
1134
+ tuple of individual image bands from an image. For example,
1135
+ splitting an "RGB" image creates three new images each
1136
+ containing a copy of one of the original bands (red, green,
1137
+ blue).
1138
+
1139
+ :returns: A tuple containing bands.
1140
+ """
1141
+
1142
+ self.load()
1143
+ if self.im.bands == 1:
1144
+ ims = [self.copy()]
1145
+ else:
1146
+ ims = []
1147
+ for i in range(self.im.bands):
1148
+ ims.append(self._new(self.im.getband(i)))
1149
+ return tuple(ims)
1150
+
1151
+ def tell(self):
1152
+ """
1153
+ Returns the current frame number. See :py:meth:`~PIL.Image.Image.seek`.
1154
+
1155
+ :returns: Frame number, starting with 0.
1156
+ """
1157
+ return 0
1158
+
1159
+ def thumbnail(self, size, resample=NEAREST):
1160
+ """
1161
+ Make this image into a thumbnail. This method modifies the
1162
+ image to contain a thumbnail version of itself, no larger than
1163
+ the given size. This method calculates an appropriate thumbnail
1164
+ size to preserve the aspect of the image, calls the
1165
+ :py:meth:`~PIL.Image.Image.draft` method to configure the file reader
1166
+ (where applicable), and finally resizes the image.
1167
+
1168
+ Note that the bilinear and bicubic filters in the current
1169
+ version of PIL are not well-suited for thumbnail generation.
1170
+ You should use :py:attr:`PIL.Image.ANTIALIAS` unless speed is much more
1171
+ important than quality.
1172
+
1173
+ Also note that this function modifies the :py:class:`~PIL.Image.Image`
1174
+ object in place. If you need to use the full resolution image as well, apply
1175
+ this method to a :py:meth:`~PIL.Image.Image.copy` of the original image.
1176
+
1177
+ :param size: Requested size.
1178
+ :param resample: Optional resampling filter. This can be one
1179
+ of :py:attr:`PIL.Image.NEAREST`, :py:attr:`PIL.Image.BILINEAR`,
1180
+ :py:attr:`PIL.Image.BICUBIC`, or :py:attr:`PIL.Image.ANTIALIAS`
1181
+ (best quality). If omitted, it defaults to
1182
+ :py:attr:`PIL.Image.NEAREST` (this will be changed to ANTIALIAS in a
1183
+ future version).
1184
+ :returns: None
1185
+ """
1186
+
1187
+ # FIXME: the default resampling filter will be changed
1188
+ # to ANTIALIAS in future versions
1189
+
1190
+ # preserve aspect ratio
1191
+ x, y = self.size
1192
+ if x > size[0]: y = int(max(y * size[0] / x, 1)); x = int(size[0])
1193
+ if y > size[1]: x = int(max(x * size[1] / y, 1)); y = int(size[1])
1194
+ size = x, y
1195
+
1196
+ if size == self.size:
1197
+ return
1198
+
1199
+ self.draft(None, size)
1200
+
1201
+ self.load()
1202
+
1203
+ try:
1204
+ im = self.resize(size, resample)
1205
+ except ValueError:
1206
+ if resample != ANTIALIAS:
1207
+ raise
1208
+ im = self.resize(size, NEAREST) # fallback
1209
+
1210
+ self.im = im.im
1211
+ self.mode = im.mode
1212
+ self.size = size
1213
+
1214
+ self.readonly = 0
1215
+
1216
+ # FIXME: the different tranform methods need further explanation
1217
+ # instead of bloating the method docs, add a separate chapter.
1218
+ def transform(self, size, method, data=None, resample=NEAREST, fill=1):
1219
+ """
1220
+ Transforms this image. This method creates a new image with the
1221
+ given size, and the same mode as the original, and copies data
1222
+ to the new image using the given transform.
1223
+
1224
+ :param size: The output size.
1225
+ :param method: The transformation method. This is one of
1226
+ :py:attr:`PIL.Image.EXTENT` (cut out a rectangular subregion),
1227
+ :py:attr:`PIL.Image.AFFINE` (affine transform),
1228
+ :py:attr:`PIL.Image.PERSPECTIVE` (perspective transform),
1229
+ :py:attr:`PIL.Image.QUAD` (map a quadrilateral to a rectangle), or
1230
+ :py:attr:`PIL.Image.MESH` (map a number of source quadrilaterals
1231
+ in one operation).
1232
+ :param data: Extra data to the transformation method.
1233
+ :param resample: Optional resampling filter. It can be one of
1234
+ :py:attr:`PIL.Image.NEAREST` (use nearest neighbour),
1235
+ :py:attr:`PIL.Image.BILINEAR` (linear interpolation in a 2x2
1236
+ environment), or :py:attr:`PIL.Image.BICUBIC` (cubic spline
1237
+ interpolation in a 4x4 environment). If omitted, or if the image
1238
+ has mode "1" or "P", it is set to :py:attr:`PIL.Image.NEAREST`.
1239
+ :returns: An :py:class:`~PIL.Image.Image` object.
1240
+ """
1241
+
1242
+ if self.mode == 'RGBA':
1243
+ return self.convert('RGBa').transform(size, method, data, resample, fill).convert('RGBA')
1244
+
1245
+ if isinstance(method, ImageTransformHandler):
1246
+ return method.transform(size, self, resample=resample, fill=fill)
1247
+ if hasattr(method, "getdata"):
1248
+ # compatibility w. old-style transform objects
1249
+ method, data = method.getdata()
1250
+ if data is None:
1251
+ raise ValueError("missing method data")
1252
+
1253
+ im = new(self.mode, size, None)
1254
+ if method == MESH:
1255
+ # list of quads
1256
+ for box, quad in data:
1257
+ im.__transformer(box, self, QUAD, quad, resample, fill)
1258
+ else:
1259
+ im.__transformer((0, 0)+size, self, method, data, resample, fill)
1260
+
1261
+ return im
1262
+
1263
+ def __transformer(self, box, image, method, data,
1264
+ resample=NEAREST, fill=1):
1265
+
1266
+ # FIXME: this should be turned into a lazy operation (?)
1267
+
1268
+ w = box[2]-box[0]
1269
+ h = box[3]-box[1]
1270
+
1271
+ if method == AFFINE:
1272
+ # change argument order to match implementation
1273
+ data = (data[2], data[0], data[1],
1274
+ data[5], data[3], data[4])
1275
+ elif method == EXTENT:
1276
+ # convert extent to an affine transform
1277
+ x0, y0, x1, y1 = data
1278
+ xs = float(x1 - x0) / w
1279
+ ys = float(y1 - y0) / h
1280
+ method = AFFINE
1281
+ data = (x0 + xs/2, xs, 0, y0 + ys/2, 0, ys)
1282
+ elif method == PERSPECTIVE:
1283
+ # change argument order to match implementation
1284
+ data = (data[2], data[0], data[1],
1285
+ data[5], data[3], data[4],
1286
+ data[6], data[7])
1287
+ elif method == QUAD:
1288
+ # quadrilateral warp. data specifies the four corners
1289
+ # given as NW, SW, SE, and NE.
1290
+ nw = data[0:2]; sw = data[2:4]; se = data[4:6]; ne = data[6:8]
1291
+ x0, y0 = nw; As = 1.0 / w; At = 1.0 / h
1292
+ data = (x0, (ne[0]-x0)*As, (sw[0]-x0)*At,
1293
+ (se[0]-sw[0]-ne[0]+x0)*As*At,
1294
+ y0, (ne[1]-y0)*As, (sw[1]-y0)*At,
1295
+ (se[1]-sw[1]-ne[1]+y0)*As*At)
1296
+ else:
1297
+ raise ValueError("unknown transformation method")
1298
+
1299
+ if resample not in (NEAREST, BILINEAR, BICUBIC):
1300
+ raise ValueError("unknown resampling filter")
1301
+
1302
+ image.load()
1303
+
1304
+ self.load()
1305
+
1306
+ if image.mode in ("1", "P"):
1307
+ resample = NEAREST
1308
+
1309
+ self.im.transform2(box, image.im, method, data, resample, fill)
1310
+
1311
+ def transpose(self, method):
1312
+ """
1313
+ Transpose image (flip or rotate in 90 degree steps)
1314
+
1315
+ :param method: One of :py:attr:`PIL.Image.FLIP_LEFT_RIGHT`,
1316
+ :py:attr:`PIL.Image.FLIP_TOP_BOTTOM`, :py:attr:`PIL.Image.ROTATE_90`,
1317
+ :py:attr:`PIL.Image.ROTATE_180`, or :py:attr:`PIL.Image.ROTATE_270`.
1318
+ :returns: Returns a flipped or rotated copy of this image.
1319
+ """
1320
+
1321
+ self.load()
1322
+ im = self.im.transpose(method)
1323
+ return self._new(im)
1324
+ ```
1325
+
1326
+ ## `PIL/Image.py` — `function:Image._dump` (lines 497-507)
1327
+
1328
+ ```python
1329
+ def _dump(self, file=None, format=None):
1330
+ import tempfile
1331
+ if not file:
1332
+ file = tempfile.mktemp()
1333
+ self.load()
1334
+ if not format or format == "PPM":
1335
+ self.im.save_ppm(file)
1336
+ else:
1337
+ file = file + "." + format
1338
+ self.save(file, format)
1339
+ return file
1340
+ ```
1341
+
1342
+ ## `PIL/IptcImagePlugin.py` — `class:IptcImageFile` (lines 53-204)
1343
+
1344
+ ```python
1345
+ class IptcImageFile(ImageFile.ImageFile):
1346
+
1347
+ format = "IPTC"
1348
+ format_description = "IPTC/NAA"
1349
+
1350
+ def getint(self, key):
1351
+ return i(self.info[key])
1352
+
1353
+ def field(self):
1354
+ #
1355
+ # get a IPTC field header
1356
+ s = self.fp.read(5)
1357
+ if not len(s):
1358
+ return None, 0
1359
+
1360
+ tag = i8(s[1]), i8(s[2])
1361
+
1362
+ # syntax
1363
+ if i8(s[0]) != 0x1C or tag[0] < 1 or tag[0] > 9:
1364
+ raise SyntaxError("invalid IPTC/NAA file")
1365
+
1366
+ # field size
1367
+ size = i8(s[3])
1368
+ if size > 132:
1369
+ raise IOError("illegal field length in IPTC/NAA file")
1370
+ elif size == 128:
1371
+ size = 0
1372
+ elif size > 128:
1373
+ size = i(self.fp.read(size-128))
1374
+ else:
1375
+ size = i16(s[3:])
1376
+
1377
+ return tag, size
1378
+
1379
+ def _is_raw(self, offset, size):
1380
+ #
1381
+ # check if the file can be mapped
1382
+
1383
+ # DISABLED: the following only slows things down...
1384
+ return 0
1385
+
1386
+ self.fp.seek(offset)
1387
+ t, sz = self.field()
1388
+ if sz != size[0]:
1389
+ return 0
1390
+ y = 1
1391
+ while True:
1392
+ self.fp.seek(sz, 1)
1393
+ t, s = self.field()
1394
+ if t != (8, 10):
1395
+ break
1396
+ if s != sz:
1397
+ return 0
1398
+ y = y + 1
1399
+ return y == size[1]
1400
+
1401
+ def _open(self):
1402
+
1403
+ # load descriptive fields
1404
+ while True:
1405
+ offset = self.fp.tell()
1406
+ tag, size = self.field()
1407
+ if not tag or tag == (8,10):
1408
+ break
1409
+ if size:
1410
+ tagdata = self.fp.read(size)
1411
+ else:
1412
+ tagdata = None
1413
+ if tag in list(self.info.keys()):
1414
+ if isinstance(self.info[tag], list):
1415
+ self.info[tag].append(tagdata)
1416
+ else:
1417
+ self.info[tag] = [self.info[tag], tagdata]
1418
+ else:
1419
+ self.info[tag] = tagdata
1420
+
1421
+ # print tag, self.info[tag]
1422
+
1423
+ # mode
1424
+ layers = i8(self.info[(3,60)][0])
1425
+ component = i8(self.info[(3,60)][1])
1426
+ if (3,65) in self.info:
1427
+ id = i8(self.info[(3,65)][0])-1
1428
+ else:
1429
+ id = 0
1430
+ if layers == 1 and not component:
1431
+ self.mode = "L"
1432
+ elif layers == 3 and component:
1433
+ self.mode = "RGB"[id]
1434
+ elif layers == 4 and component:
1435
+ self.mode = "CMYK"[id]
1436
+
1437
+ # size
1438
+ self.size = self.getint((3,20)), self.getint((3,30))
1439
+
1440
+ # compression
1441
+ try:
1442
+ compression = COMPRESSION[self.getint((3,120))]
1443
+ except KeyError:
1444
+ raise IOError("Unknown IPTC image compression")
1445
+
1446
+ # tile
1447
+ if tag == (8,10):
1448
+ if compression == "raw" and self._is_raw(offset, self.size):
1449
+ self.tile = [(compression, (offset, size + 5, -1),
1450
+ (0, 0, self.size[0], self.size[1]))]
1451
+ else:
1452
+ self.tile = [("iptc", (compression, offset),
1453
+ (0, 0, self.size[0], self.size[1]))]
1454
+
1455
+ def load(self):
1456
+
1457
+ if len(self.tile) != 1 or self.tile[0][0] != "iptc":
1458
+ return ImageFile.ImageFile.load(self)
1459
+
1460
+ type, tile, box = self.tile[0]
1461
+
1462
+ encoding, offset = tile
1463
+
1464
+ self.fp.seek(offset)
1465
+
1466
+ # Copy image data to temporary file
1467
+ outfile = tempfile.mktemp()
1468
+ o = open(outfile, "wb")
1469
+ if encoding == "raw":
1470
+ # To simplify access to the extracted file,
1471
+ # prepend a PPM header
1472
+ o.write("P5\n%d %d\n255\n" % self.size)
1473
+ while True:
1474
+ type, size = self.field()
1475
+ if type != (8, 10):
1476
+ break
1477
+ while size > 0:
1478
+ s = self.fp.read(min(size, 8192))
1479
+ if not s:
1480
+ break
1481
+ o.write(s)
1482
+ size = size - len(s)
1483
+ o.close()
1484
+
1485
+ try:
1486
+ try:
1487
+ # fast
1488
+ self.im = Image.core.open_ppm(outfile)
1489
+ except:
1490
+ # slightly slower
1491
+ im = Image.open(outfile)
1492
+ im.load()
1493
+ self.im = im.im
1494
+ finally:
1495
+ try: os.unlink(outfile)
1496
+ except: pass
1497
+ ```
1498
+
1499
+ ## `PIL/IptcImagePlugin.py` — `function:IptcImageFile.load` (lines 163-204)
1500
+
1501
+ ```python
1502
+ def load(self):
1503
+
1504
+ if len(self.tile) != 1 or self.tile[0][0] != "iptc":
1505
+ return ImageFile.ImageFile.load(self)
1506
+
1507
+ type, tile, box = self.tile[0]
1508
+
1509
+ encoding, offset = tile
1510
+
1511
+ self.fp.seek(offset)
1512
+
1513
+ # Copy image data to temporary file
1514
+ outfile = tempfile.mktemp()
1515
+ o = open(outfile, "wb")
1516
+ if encoding == "raw":
1517
+ # To simplify access to the extracted file,
1518
+ # prepend a PPM header
1519
+ o.write("P5\n%d %d\n255\n" % self.size)
1520
+ while True:
1521
+ type, size = self.field()
1522
+ if type != (8, 10):
1523
+ break
1524
+ while size > 0:
1525
+ s = self.fp.read(min(size, 8192))
1526
+ if not s:
1527
+ break
1528
+ o.write(s)
1529
+ size = size - len(s)
1530
+ o.close()
1531
+
1532
+ try:
1533
+ try:
1534
+ # fast
1535
+ self.im = Image.core.open_ppm(outfile)
1536
+ except:
1537
+ # slightly slower
1538
+ im = Image.open(outfile)
1539
+ im.load()
1540
+ self.im = im.im
1541
+ finally:
1542
+ try: os.unlink(outfile)
1543
+ except: pass
1544
+ ```
1545
+
1546
+ ## `PIL/JpegImagePlugin.py` — `class:JpegImageFile` (lines 267-362)
1547
+
1548
+ ```python
1549
+ class JpegImageFile(ImageFile.ImageFile):
1550
+
1551
+ format = "JPEG"
1552
+ format_description = "JPEG (ISO 10918)"
1553
+
1554
+ def _open(self):
1555
+
1556
+ s = self.fp.read(1)
1557
+
1558
+ if i8(s[0]) != 255:
1559
+ raise SyntaxError("not a JPEG file")
1560
+
1561
+ # Create attributes
1562
+ self.bits = self.layers = 0
1563
+
1564
+ # JPEG specifics (internal)
1565
+ self.layer = []
1566
+ self.huffman_dc = {}
1567
+ self.huffman_ac = {}
1568
+ self.quantization = {}
1569
+ self.app = {} # compatibility
1570
+ self.applist = []
1571
+ self.icclist = []
1572
+
1573
+ while True:
1574
+
1575
+ s = s + self.fp.read(1)
1576
+
1577
+ i = i16(s)
1578
+
1579
+ if i in MARKER:
1580
+ name, description, handler = MARKER[i]
1581
+ # print hex(i), name, description
1582
+ if handler is not None:
1583
+ handler(self, i)
1584
+ if i == 0xFFDA: # start of scan
1585
+ rawmode = self.mode
1586
+ if self.mode == "CMYK":
1587
+ rawmode = "CMYK;I" # assume adobe conventions
1588
+ self.tile = [("jpeg", (0,0) + self.size, 0, (rawmode, ""))]
1589
+ # self.__offset = self.fp.tell()
1590
+ break
1591
+ s = self.fp.read(1)
1592
+ elif i == 0 or i == 65535:
1593
+ # padded marker or junk; move on
1594
+ s = "\xff"
1595
+ else:
1596
+ raise SyntaxError("no marker found")
1597
+
1598
+ def draft(self, mode, size):
1599
+
1600
+ if len(self.tile) != 1:
1601
+ return
1602
+
1603
+ d, e, o, a = self.tile[0]
1604
+ scale = 0
1605
+
1606
+ if a[0] == "RGB" and mode in ["L", "YCbCr"]:
1607
+ self.mode = mode
1608
+ a = mode, ""
1609
+
1610
+ if size:
1611
+ scale = max(self.size[0] // size[0], self.size[1] // size[1])
1612
+ for s in [8, 4, 2, 1]:
1613
+ if scale >= s:
1614
+ break
1615
+ e = e[0], e[1], (e[2]-e[0]+s-1)//s+e[0], (e[3]-e[1]+s-1)//s+e[1]
1616
+ self.size = ((self.size[0]+s-1)//s, (self.size[1]+s-1)//s)
1617
+ scale = s
1618
+
1619
+ self.tile = [(d, e, o, a)]
1620
+ self.decoderconfig = (scale, 1)
1621
+
1622
+ return self
1623
+
1624
+ def load_djpeg(self):
1625
+
1626
+ # ALTERNATIVE: handle JPEGs via the IJG command line utilities
1627
+
1628
+ import tempfile, os
1629
+ file = tempfile.mktemp()
1630
+ os.system("djpeg %s >%s" % (self.filename, file))
1631
+
1632
+ try:
1633
+ self.im = Image.core.open_ppm(file)
1634
+ finally:
1635
+ try: os.unlink(file)
1636
+ except: pass
1637
+
1638
+ self.mode = self.im.mode
1639
+ self.size = self.im.size
1640
+
1641
+ self.tile = []
1642
+
1643
+ def _getexif(self):
1644
+ return _getexif(self)
1645
+ ```
1646
+
1647
+ ## `PIL/JpegImagePlugin.py` — `function:JpegImageFile.load_djpeg` (lines 342-359)
1648
+
1649
+ ```python
1650
+ def load_djpeg(self):
1651
+
1652
+ # ALTERNATIVE: handle JPEGs via the IJG command line utilities
1653
+
1654
+ import tempfile, os
1655
+ file = tempfile.mktemp()
1656
+ os.system("djpeg %s >%s" % (self.filename, file))
1657
+
1658
+ try:
1659
+ self.im = Image.core.open_ppm(file)
1660
+ finally:
1661
+ try: os.unlink(file)
1662
+ except: pass
1663
+
1664
+ self.mode = self.im.mode
1665
+ self.size = self.im.size
1666
+
1667
+ self.tile = []
1668
+ ```
tasks/codeql_python_benchmark51_v2/pyvul-4954e5890cce23c8b03d/task.json ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "schema_version": "synthesis-task-v1",
3
+ "task": {
4
+ "pair_id": "pyvul-4954e5890cce23c8b03d",
5
+ "dataset_id": "PyVul",
6
+ "dataset_item_id": "pyvul-4954e5890cce23c8b03d",
7
+ "project_id": "pyvul__python-imaging__pillow",
8
+ "language": "python",
9
+ "backend": "codeql"
10
+ },
11
+ "changed_python_files": [
12
+ "PIL/EpsImagePlugin.py",
13
+ "PIL/Image.py",
14
+ "PIL/IptcImagePlugin.py",
15
+ "PIL/JpegImagePlugin.py"
16
+ ],
17
+ "patch_units": {
18
+ "before": [
19
+ "function:Ghostscript",
20
+ "class:Image",
21
+ "function:Image._dump",
22
+ "class:IptcImageFile",
23
+ "function:IptcImageFile.load",
24
+ "class:JpegImageFile",
25
+ "function:JpegImageFile.load_djpeg"
26
+ ],
27
+ "after": [
28
+ "function:Ghostscript",
29
+ "class:Image",
30
+ "function:Image._dump",
31
+ "class:IptcImageFile",
32
+ "function:IptcImageFile.load",
33
+ "class:JpegImageFile",
34
+ "function:JpegImageFile.load_djpeg"
35
+ ]
36
+ },
37
+ "runtime_assets": {
38
+ "before": {
39
+ "database": "assets/08f641daaaf70221449c3b5c4a84e91796936219a20b91e4d35203686e7f7f18/database",
40
+ "cache_key": "08f641daaaf70221449c3b5c4a84e91796936219a20b91e4d35203686e7f7f18",
41
+ "codeql_version": "2.26.4"
42
+ },
43
+ "after": {
44
+ "database": "assets/62d7667e51007d1b94a468ba2fb246305f5f01a271bec41480f941757aef828b/database",
45
+ "cache_key": "62d7667e51007d1b94a468ba2fb246305f5f01a271bec41480f941757aef828b",
46
+ "codeql_version": "2.26.4"
47
+ },
48
+ "refine": {
49
+ "database": "assets/25ef67aaf353265855d3a53ef7158ae4fa13015799c0bf4d700c936c6487ed7d/database",
50
+ "cache_key": "25ef67aaf353265855d3a53ef7158ae4fa13015799c0bf4d700c936c6487ed7d",
51
+ "codeql_version": "2.26.4"
52
+ }
53
+ },
54
+ "benchmark_contract": {
55
+ "agent_visible": true,
56
+ "reference_query_location": "references/pyvul-4954e5890cce23c8b03d/query/ (do not mount into agent)",
57
+ "evaluator_location": "evaluator/pyvul-4954e5890cce23c8b03d/ (do not mount into agent)"
58
+ }
59
+ }
tasks/codeql_python_benchmark51_v2/pyvul-4954e5890cce23c8b03d/task_prompt.md ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Python CodeQL detector synthesis
2
+
3
+ You are cc operating in `/work`. Starting only from the supplied patch,
4
+ before/after Python context, CodeQL references, and validation tools, synthesize a semantic CodeQL
5
+ detector for the vulnerability fixed by the patch. This is one fresh session. You may iterate inside
6
+ this session, but no later framework repair or resume will occur.
7
+
8
+ ## Inputs and owned outputs
9
+
10
+ - Read `patch.diff`, `python_patch.diff`, `pre_context.md`, and `post_context.md`.
11
+ - Read `references/codeql/convergence_protocol.md` and
12
+ `references/codeql/api_navigation.md` before experimenting. Read the remaining
13
+ `references/codeql/` files for the selected mechanism.
14
+ - Use `scripts/search_codeql_api.sh` to inspect the pinned official libraries when an API detail is
15
+ uncertain. Do not guess predicate names or build a large family of inspection queries.
16
+ - Complete the design contract in `state.json` and `scope_statement.md` before final validation.
17
+ - Replace `query/vulnerability.ql`; add only genuinely shared `.qll` helpers when useful. Keep the
18
+ fixed offline dependency in `query/qlpack.yml`.
19
+ - Preserve the exact `expected_query_id` from `config.json` as the query's sole `@id`. This
20
+ task-unique metadata must never be used in a query predicate.
21
+ - Use `scripts/compile_query.sh`, `scripts/run_before.sh`, and `scripts/run_after.sh`.
22
+ - Finish by writing `summary.json` with `status`, `query_path`, `query_kind`, `build_passed`,
23
+ `before_findings`, `after_findings`, `validation_completed`, and a concise `notes` field.
24
+
25
+ ## Required reasoning contract
26
+
27
+ Before coding, record this mapping in `state.json`:
28
+
29
+ ```text
30
+ vulnerable operation / trigger / patch safety condition
31
+ → CodeQL-observable evidence
32
+ → syntax, control-flow, local value-flow, global taint/value-flow, or interprocedural mechanism
33
+ → source, sink/report site, guard/barrier and query predicates
34
+ ```
35
+
36
+ Choose the lowest mechanism that can actually prove the condition. Guard-sensitive patches require
37
+ real path/control-flow semantics; provenance-sensitive patches require value flow. Do not replace
38
+ either with source-text matching or with the mere presence of patch-added syntax.
39
+
40
+ ## Mandatory convergence contract
41
+
42
+ The rollout has a 30-minute hard wall-clock ceiling and must be finalized by minute 27. Minutes
43
+ 27–30 are an emergency shutdown buffer, not exploration time. A sophisticated unfinished query is
44
+ a failure; an early compilable semantic candidate can be improved. Follow the checkpoints in
45
+ `references/codeql/convergence_protocol.md`:
46
+
47
+ 1. Record the mechanism contract, then replace the placeholder in `query/vulnerability.ql`
48
+ immediately. Do not wait until every CodeQL API detail is known.
49
+ 2. Use at most three distinct scratch `.ql` files. Prefer repeatedly editing one
50
+ `query/scratch.ql`. After two failed variants of one API assumption, inspect the exact bundled
51
+ definition with `scripts/search_codeql_api.sh` or simplify the mechanism.
52
+ 3. Obtain a compiling minimal main query before broadening it. Compile the main query after every
53
+ meaningful mechanism change.
54
+ 4. Move in order from compile → relevant before finding → after elimination → final contract. Do
55
+ not continue API exploration after the intended before/after differential is established.
56
+ 5. Run `scripts/check_progress.sh` at each checkpoint. It reports elapsed time, the minute-27
57
+ finalization deadline, and the minute-30 hard timeout. When it prints `finalize_now`, stop all
58
+ exploration, preserve the best compiling query, finish the contract files, and exit.
59
+
60
+ ## Semantic and generalization rules
61
+
62
+ - Report at the vulnerable call, operator, access, or sink.
63
+ - Do not use a patch-local path, line, commit hash, label, or local variable name as the primary
64
+ matching condition. Stable library/framework APIs or public project APIs are allowed only when
65
+ `scope_statement.md` explains why they define the intended vulnerability family.
66
+ - The safety condition introduced by the patch must be represented by the query.
67
+ - A lower after warning count is not enough: inspect SARIF and ensure at least one intended before
68
+ finding is in a patch-overlapping semantic unit and the corresponding finding disappears after.
69
+ - Avoid broad proxy queries that report an enclosing function or unrelated API merely because it
70
+ changed in the patch.
71
+
72
+ ## Final validation protocol
73
+
74
+ 1. Compile the final query.
75
+ 2. Run it on before and inspect `raw/before.sarif` for the intended report location.
76
+ 3. Run the identical query on after and inspect `raw/after.sarif`.
77
+ 4. Recheck query metadata, query kind/select signature, report locality, design-to-code consistency,
78
+ and absence of patch-local hardcoding.
79
+ 5. Update `state.json`, `scope_statement.md`, and write valid `summary.json`.
80
+
81
+ Do not modify the runtime databases, references, patch, context, or validation scripts except for
82
+ normal CodeQL-generated database caches produced by the provided run scripts.
tasks/codeql_python_benchmark51_v2/pyvul-4ac3440b9023e6511a91/patch.diff ADDED
@@ -0,0 +1,184 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ diff --git a/nautobot_device_onboarding/jobs.py b/nautobot_device_onboarding/jobs.py
2
+ index cca9e9c..72b843d 100644
3
+ --- a/nautobot_device_onboarding/jobs.py
4
+ +++ b/nautobot_device_onboarding/jobs.py
5
+ @@ -13,12 +13,7 @@ PLUGIN_SETTINGS = settings.PLUGINS_CONFIG["nautobot_device_onboarding"]
6
+
7
+
8
+ class OnboardingTask(Job):
9
+ - class Meta:
10
+ - """Meta object boilerplate for onboarding."""
11
+ -
12
+ - name = "Perform Device Onboarding"
13
+ - description = "Login to a device and populate Nautobot device object."
14
+ - has_sensitive_variables = False
15
+ + """Nautobot Job for onboarding a new device."""
16
+
17
+ location = ObjectVar(model=Location, query_params={"": ""}, required=False, description="")
18
+ ip_address = IPAddressVar(description="", label="")
19
+ @@ -29,18 +24,32 @@ class OnboardingTask(Job):
20
+ role = ObjectVar(model=Role, query_params={"": ""}, required=False, description="")
21
+ device_type = ObjectVar(model=DeviceType, required=False, description="")
22
+
23
+ + class Meta: # pylint: disable=too-few-public-methods
24
+ + """Meta object boilerplate for onboarding."""
25
+ +
26
+ + name = "Perform Device Onboarding"
27
+ + description = "Login to a device and populate Nautobot device object."
28
+ + has_sensitive_variables = False
29
+ +
30
+ + def __init__(self, *args, **kwargs):
31
+ + """Overload init to instantiate class attributes per W0201."""
32
+ + self.username = None
33
+ + self.password = None
34
+ + self.secret = None
35
+ + super().__init__(*args, **kwargs)
36
+ +
37
+ def run(self, *args, **data):
38
+ """Process a single Onboarding Task instance."""
39
+ self.logger.info("START: onboard device")
40
+ - credentials = self._parse_credentials(data["credentials"])
41
+ + self._parse_credentials(data["credentials"])
42
+ platform = data["platform"]
43
+ netdev = NetdevKeeper(
44
+ hostname=data["ip_address"],
45
+ port=data["port"],
46
+ timeout=data["timeout"],
47
+ - username=credentials["username"],
48
+ - password=credentials["password"],
49
+ - secret=credentials["secret"],
50
+ + username=self.username,
51
+ + password=self.password,
52
+ + secret=self.secret,
53
+ napalm_driver=platform.napalm_driver if platform and platform.napalm_driver else None,
54
+ optional_args=platform.napalm_args if platform and platform.napalm_args else settings.NAPALM_ARGS,
55
+ )
56
+ @@ -72,18 +81,16 @@ class OnboardingTask(Job):
57
+
58
+ def _parse_credentials(self, credentials):
59
+ """Parse and return dictionary of credentials."""
60
+ -
61
+ if credentials:
62
+ - self.username = (credentials.secrets.get(secret_type=SecretsGroupSecretTypeChoices.TYPE_USERNAME),)
63
+ - self.password = (credentials.secrets.get(secret_type=SecretsGroupSecretTypeChoices.TYPE_PASSWORD),)
64
+ - self.secret = (None,)
65
+ + self.username = credentials.secrets.get(secret_type=SecretsGroupSecretTypeChoices.TYPE_USERNAME)
66
+ + self.password = credentials.secrets.get(secret_type=SecretsGroupSecretTypeChoices.TYPE_PASSWORD)
67
+ secret = credentials.secrets.filter(secret_type=SecretsGroupSecretTypeChoices.TYPE_SECRET)
68
+ if secret.exists():
69
+ self.secret = secret.first()
70
+ else:
71
+ - self.username = (settings.NAPALM_USERNAME,)
72
+ - self.password = (settings.NAPALM_PASSWORD,)
73
+ - self.secret = (settings.NAPALM_ARGS.get("secret", None),)
74
+ + self.username = settings.NAPALM_USERNAME
75
+ + self.password = settings.NAPALM_PASSWORD
76
+ + self.secret = settings.NAPALM_ARGS.get("secret", None)
77
+
78
+
79
+ register_jobs(OnboardingTask)
80
+ diff --git a/nautobot_device_onboarding/tests/test_netdev_keeper.py b/nautobot_device_onboarding/tests/test_netdev_keeper.py
81
+ deleted file mode 100644
82
+ index 91fbde6..0000000
83
+ --- a/nautobot_device_onboarding/tests/test_netdev_keeper.py
84
+ +++ /dev/null
85
+ @@ -1,72 +0,0 @@
86
+ -"""Unit tests for nautobot_device_onboarding.netdev_keeper module and its classes."""
87
+ -
88
+ -from socket import gaierror
89
+ -from unittest import mock
90
+ -
91
+ -from django.contrib.contenttypes.models import ContentType
92
+ -from django.test import TestCase
93
+ -
94
+ -from nautobot.dcim.models import Device, Location, LocationType, Platform
95
+ -from nautobot.extras.models import Role, Status
96
+ -
97
+ -from nautobot_device_onboarding.exceptions import OnboardException
98
+ -from nautobot_device_onboarding.helpers import onboarding_task_fqdn_to_ip
99
+ -# from nautobot_device_onboarding.models import OnboardingTask
100
+ -
101
+ -
102
+ -class NetdevKeeperTestCase(TestCase):
103
+ - """Test the NetdevKeeper Class."""
104
+ -
105
+ - def setUp(self):
106
+ - """Create a superuser and token for API calls."""
107
+ - role_content_type = ContentType.objects.get_for_model(Device)
108
+ - status = Status.objects.get(name="Active")
109
+ - location_type = LocationType.objects.create(name="site")
110
+ - self.site1 = Location.objects.create(name="USWEST", location_type=location_type, status=status)
111
+ - self.device_role1 = Role.objects.create(name="Firewall")
112
+ - self.device_role1.content_types.set([role_content_type])
113
+ -
114
+ - self.platform1 = Platform.objects.create(name="JunOS", napalm_driver="junos")
115
+ - # self.platform2 = Platform.objects.create(name="Cisco NX-OS", slug="cisco-nx-os")
116
+ -
117
+ - # self.onboarding_task4 = OnboardingTask.objects.create(
118
+ - # ip_address="ntc123.local", location=self.site1, role=self.device_role1, platform=self.platform1
119
+ - # )
120
+ -
121
+ - # self.onboarding_task5 = OnboardingTask.objects.create(
122
+ - # ip_address="bad.local", location=self.site1, role=self.device_role1, platform=self.platform1
123
+ - # )
124
+ -
125
+ - # self.onboarding_task7 = OnboardingTask.objects.create(
126
+ - # ip_address="192.0.2.1/32", location=self.site1, role=self.device_role1, platform=self.platform1
127
+ - # )
128
+ -
129
+ - # @mock.patch("nautobot_device_onboarding.helpers.socket.gethostbyname")
130
+ - # def test_check_ip(self, mock_get_hostbyname):
131
+ - # """Check DNS to IP address."""
132
+ - # # Look up response value
133
+ - # mock_get_hostbyname.return_value = "192.0.2.1"
134
+ -
135
+ - # # FQDN -> IP
136
+ - # onboarding_task_fqdn_to_ip(onboarding_task=self.onboarding_task4)
137
+ -
138
+ - # # Run the check to change the IP address
139
+ - # self.assertEqual(self.onboarding_task4.ip_address, "192.0.2.1")
140
+ -
141
+ - # @mock.patch("nautobot_device_onboarding.helpers.socket.gethostbyname")
142
+ - # def test_failed_check_ip(self, mock_get_hostbyname):
143
+ - # """Check DNS to IP address failing."""
144
+ - # # Look up a failed response
145
+ - # mock_get_hostbyname.side_effect = gaierror(8)
146
+ -
147
+ - # # Check for bad.local raising an exception
148
+ - # with self.assertRaises(OnboardException) as exc_info:
149
+ - # onboarding_task_fqdn_to_ip(onboarding_task=self.onboarding_task5)
150
+ - # self.assertEqual(exc_info.exception.message, "ERROR failed to complete DNS lookup: bad.local")
151
+ - # self.assertEqual(exc_info.exception.reason, "fail-dns")
152
+ -
153
+ - # # Check for exception with prefix address entered
154
+ - # with self.assertRaises(OnboardException) as exc_info:
155
+ - # onboarding_task_fqdn_to_ip(onboarding_task=self.onboarding_task7)
156
+ - # self.assertEqual(exc_info.exception.reason, "fail-prefix")
157
+ - # self.assertEqual(exc_info.exception.message, "ERROR appears a prefix was entered: 192.0.2.1/32")
158
+ diff --git a/nautobot_device_onboarding/tests/test_onboarding.py b/nautobot_device_onboarding/tests/test_onboarding.py
159
+ index d7a938c..f427bba 100644
160
+ --- a/nautobot_device_onboarding/tests/test_onboarding.py
161
+ +++ b/nautobot_device_onboarding/tests/test_onboarding.py
162
+ @@ -1,16 +1,15 @@
163
+ """Unit tests for nautobot_device_onboarding.netdev_keeper module and its classes."""
164
+ -from unittest import mock
165
+ +# from unittest import mock
166
+
167
+ from django.conf import settings
168
+ -from django.test import TestCase
169
+ -from django.contrib.contenttypes.models import ContentType
170
+
171
+ +# from django.test import TestCase
172
+ +# from django.contrib.contenttypes.models import ContentType
173
+
174
+ -from nautobot.dcim.models import Device, Location, LocationType, Platform
175
+ -from nautobot.extras.models import Status
176
+
177
+ -# from nautobot_device_onboarding.models import OnboardingTask
178
+ -# from nautobot_device_onboarding.onboard import OnboardingManager
179
+ +# from nautobot.dcim.models import Device, Location, LocationType, Platform
180
+ +# from nautobot.extras.models import Status
181
+ +
182
+
183
+ PLUGIN_SETTINGS = settings.PLUGINS_CONFIG["nautobot_device_onboarding"]
184
+
tasks/codeql_python_benchmark51_v2/pyvul-4ac3440b9023e6511a91/post_context.md ADDED
@@ -0,0 +1,169 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Patch-overlapping Python context after the fix
2
+
3
+ ## `nautobot_device_onboarding/jobs.py` — `class:OnboardingTask` (lines 15-93)
4
+
5
+ ```python
6
+ class OnboardingTask(Job):
7
+ """Nautobot Job for onboarding a new device."""
8
+
9
+ location = ObjectVar(model=Location, query_params={"": ""}, required=False, description="")
10
+ ip_address = IPAddressVar(description="", label="")
11
+ port = IntegerVar(description="")
12
+ timeout = IntegerVar(description="")
13
+ credentials = ObjectVar(model=SecretsGroup, query_params={"": ""}, required=False, description="")
14
+ platform = ObjectVar(model=Platform, required=False, description="")
15
+ role = ObjectVar(model=Role, query_params={"": ""}, required=False, description="")
16
+ device_type = ObjectVar(model=DeviceType, required=False, description="")
17
+
18
+ class Meta: # pylint: disable=too-few-public-methods
19
+ """Meta object boilerplate for onboarding."""
20
+
21
+ name = "Perform Device Onboarding"
22
+ description = "Login to a device and populate Nautobot device object."
23
+ has_sensitive_variables = False
24
+
25
+ def __init__(self, *args, **kwargs):
26
+ """Overload init to instantiate class attributes per W0201."""
27
+ self.username = None
28
+ self.password = None
29
+ self.secret = None
30
+ super().__init__(*args, **kwargs)
31
+
32
+ def run(self, *args, **data):
33
+ """Process a single Onboarding Task instance."""
34
+ self.logger.info("START: onboard device")
35
+ self._parse_credentials(data["credentials"])
36
+ platform = data["platform"]
37
+ netdev = NetdevKeeper(
38
+ hostname=data["ip_address"],
39
+ port=data["port"],
40
+ timeout=data["timeout"],
41
+ username=self.username,
42
+ password=self.password,
43
+ secret=self.secret,
44
+ napalm_driver=platform.napalm_driver if platform and platform.napalm_driver else None,
45
+ optional_args=platform.napalm_args if platform and platform.napalm_args else settings.NAPALM_ARGS,
46
+ )
47
+ netdev.get_onboarding_facts()
48
+ netdev_dict = netdev.get_netdev_dict()
49
+
50
+ onboarding_kwargs = {
51
+ # Kwargs extracted from OnboardingTask:
52
+ "netdev_mgmt_ip_address": data["ip_address"],
53
+ "netdev_nb_location_name": data["location"].name,
54
+ "netdev_nb_device_type_name": data["device_type"],
55
+ "netdev_nb_role_name": data["role"].name if data["role"] else PLUGIN_SETTINGS["default_device_role"],
56
+ "netdev_nb_role_color": PLUGIN_SETTINGS["default_device_role_color"],
57
+ "netdev_nb_platform_name": data["platform"].name if data["platform"] else None,
58
+ # Kwargs discovered on the Onboarded Device:
59
+ "netdev_hostname": netdev_dict["netdev_hostname"],
60
+ "netdev_vendor": netdev_dict["netdev_vendor"],
61
+ "netdev_model": netdev_dict["netdev_model"],
62
+ "netdev_serial_number": netdev_dict["netdev_serial_number"],
63
+ "netdev_mgmt_ifname": netdev_dict["netdev_mgmt_ifname"],
64
+ "netdev_mgmt_pflen": netdev_dict["netdev_mgmt_pflen"],
65
+ "netdev_netmiko_device_type": netdev_dict["netdev_netmiko_device_type"],
66
+ "onboarding_class": netdev_dict["onboarding_class"],
67
+ "driver_addon_result": netdev_dict["driver_addon_result"],
68
+ }
69
+ onboarding_cls = netdev_dict["onboarding_class"]()
70
+ onboarding_cls.credentials = {"username": self.username, "password": self.password, "secret": self.secret}
71
+ onboarding_cls.run(onboarding_kwargs=onboarding_kwargs)
72
+
73
+ def _parse_credentials(self, credentials):
74
+ """Parse and return dictionary of credentials."""
75
+ if credentials:
76
+ self.username = credentials.secrets.get(secret_type=SecretsGroupSecretTypeChoices.TYPE_USERNAME)
77
+ self.password = credentials.secrets.get(secret_type=SecretsGroupSecretTypeChoices.TYPE_PASSWORD)
78
+ secret = credentials.secrets.filter(secret_type=SecretsGroupSecretTypeChoices.TYPE_SECRET)
79
+ if secret.exists():
80
+ self.secret = secret.first()
81
+ else:
82
+ self.username = settings.NAPALM_USERNAME
83
+ self.password = settings.NAPALM_PASSWORD
84
+ self.secret = settings.NAPALM_ARGS.get("secret", None)
85
+ ```
86
+
87
+ ## `nautobot_device_onboarding/jobs.py` — `class:OnboardingTask.Meta` (lines 27-32)
88
+
89
+ ```python
90
+ class Meta: # pylint: disable=too-few-public-methods
91
+ """Meta object boilerplate for onboarding."""
92
+
93
+ name = "Perform Device Onboarding"
94
+ description = "Login to a device and populate Nautobot device object."
95
+ has_sensitive_variables = False
96
+ ```
97
+
98
+ ## `nautobot_device_onboarding/jobs.py` — `function:OnboardingTask.__init__` (lines 34-39)
99
+
100
+ ```python
101
+ def __init__(self, *args, **kwargs):
102
+ """Overload init to instantiate class attributes per W0201."""
103
+ self.username = None
104
+ self.password = None
105
+ self.secret = None
106
+ super().__init__(*args, **kwargs)
107
+ ```
108
+
109
+ ## `nautobot_device_onboarding/jobs.py` — `function:OnboardingTask.run` (lines 41-80)
110
+
111
+ ```python
112
+ def run(self, *args, **data):
113
+ """Process a single Onboarding Task instance."""
114
+ self.logger.info("START: onboard device")
115
+ self._parse_credentials(data["credentials"])
116
+ platform = data["platform"]
117
+ netdev = NetdevKeeper(
118
+ hostname=data["ip_address"],
119
+ port=data["port"],
120
+ timeout=data["timeout"],
121
+ username=self.username,
122
+ password=self.password,
123
+ secret=self.secret,
124
+ napalm_driver=platform.napalm_driver if platform and platform.napalm_driver else None,
125
+ optional_args=platform.napalm_args if platform and platform.napalm_args else settings.NAPALM_ARGS,
126
+ )
127
+ netdev.get_onboarding_facts()
128
+ netdev_dict = netdev.get_netdev_dict()
129
+
130
+ onboarding_kwargs = {
131
+ # Kwargs extracted from OnboardingTask:
132
+ "netdev_mgmt_ip_address": data["ip_address"],
133
+ "netdev_nb_location_name": data["location"].name,
134
+ "netdev_nb_device_type_name": data["device_type"],
135
+ "netdev_nb_role_name": data["role"].name if data["role"] else PLUGIN_SETTINGS["default_device_role"],
136
+ "netdev_nb_role_color": PLUGIN_SETTINGS["default_device_role_color"],
137
+ "netdev_nb_platform_name": data["platform"].name if data["platform"] else None,
138
+ # Kwargs discovered on the Onboarded Device:
139
+ "netdev_hostname": netdev_dict["netdev_hostname"],
140
+ "netdev_vendor": netdev_dict["netdev_vendor"],
141
+ "netdev_model": netdev_dict["netdev_model"],
142
+ "netdev_serial_number": netdev_dict["netdev_serial_number"],
143
+ "netdev_mgmt_ifname": netdev_dict["netdev_mgmt_ifname"],
144
+ "netdev_mgmt_pflen": netdev_dict["netdev_mgmt_pflen"],
145
+ "netdev_netmiko_device_type": netdev_dict["netdev_netmiko_device_type"],
146
+ "onboarding_class": netdev_dict["onboarding_class"],
147
+ "driver_addon_result": netdev_dict["driver_addon_result"],
148
+ }
149
+ onboarding_cls = netdev_dict["onboarding_class"]()
150
+ onboarding_cls.credentials = {"username": self.username, "password": self.password, "secret": self.secret}
151
+ onboarding_cls.run(onboarding_kwargs=onboarding_kwargs)
152
+ ```
153
+
154
+ ## `nautobot_device_onboarding/jobs.py` — `function:OnboardingTask._parse_credentials` (lines 82-93)
155
+
156
+ ```python
157
+ def _parse_credentials(self, credentials):
158
+ """Parse and return dictionary of credentials."""
159
+ if credentials:
160
+ self.username = credentials.secrets.get(secret_type=SecretsGroupSecretTypeChoices.TYPE_USERNAME)
161
+ self.password = credentials.secrets.get(secret_type=SecretsGroupSecretTypeChoices.TYPE_PASSWORD)
162
+ secret = credentials.secrets.filter(secret_type=SecretsGroupSecretTypeChoices.TYPE_SECRET)
163
+ if secret.exists():
164
+ self.secret = secret.first()
165
+ else:
166
+ self.username = settings.NAPALM_USERNAME
167
+ self.password = settings.NAPALM_PASSWORD
168
+ self.secret = settings.NAPALM_ARGS.get("secret", None)
169
+ ```