s42chen commited on
Commit
3df94d5
·
verified ·
1 Parent(s): d9a34ca

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. shared/package-files/28/2808ec768e7053bc77b6b2471c20a81e1fdaebde861bd0348f7979a9713db535/upsample_linear1d_backward_cuda_dispatch.h +28 -0
  2. shared/package-files/28/281fb0de8cc41105084cd2ed32dc7c3fd25e0eb8d0a3c1bbb98b159ea9dae1cf/_table_schema.py +387 -0
  3. shared/package-files/28/284621cae64b99ea4346e679b9d0ab35ac5a02fd76b71985ac1cb8a2a5ccef6a/logdet.h +30 -0
  4. shared/package-files/28/2868c82c87d01c0551beda25dbdc12c0db675f9cca8c6dba37ace150f19e0b39/rolodex +204 -0
  5. shared/package-files/28/288452b8eb988dc8d10b89524477cac6d80a7a4c25697d7eb8843b17ebae584a/libev.so.4 +0 -0
  6. shared/package-files/28/2889a273f20bca1c5abdb1b15676be02c71ffbea2489b6a564994ae386b97627/RegistrationDeclarations.h +4 -0
  7. shared/package-files/28/28948c9b3b5746a4efa66901fa4cbe592548a80320fc6716a1ec13711c49d42c/_gauss_legendre.py +62 -0
  8. shared/package-files/28/289651087fe34e9e4e64cf38ee1520b41c7964bd42b54dc3435d9a5ca860f0fe/vt100-putty +0 -0
  9. shared/package-files/28/28b1c1421f5a5a02d859b7aac36922c906ae18d0e22a669d78c9a5b6274696b9/dateformat.pyi +63 -0
  10. shared/package-files/28/28b67a74effbbbc3a40a4843484feede592668c2034961f874e769ae9735b45b/pattern_utils.py +200 -0
  11. shared/package-files/28/28d386370beed69d9b6a2bd16e57502882be80a593a8ba8387c3998b1335031e/geqrf.h +39 -0
  12. shared/package-files/28/28d7d9b92f072ab5cd552454a18b713166359c210b1989e0fd90efd9687db686/logical_not_ops.h +50 -0
  13. shared/package-files/28/28f219e4406c50b28204a450f09ac5fa14fa3330f06c8ba9023b389ad5ba417b/combinatorics.py +126 -0
  14. shared/package-files/28/28fb1334a9a73ef48610a5800571c0f53c8198270ee8b4292a58a857e62f5308/att500 +0 -0
  15. shared/package-files/28/28fb1334a9a73ef48610a5800571c0f53c8198270ee8b4292a58a857e62f5308/att513 +0 -0
  16. shared/package-files/74/740228db814b6dd426a989aca58f20a3d2d66d795fbbe022b417249c26ea324e/inspect_pkg.py +359 -0
  17. shared/package-files/74/740d6bff1586f7434d0efb47a6bd7527135409cfc4ed0a08120a1498c2efadd7/test_page.py +20 -0
  18. shared/package-files/74/74215f00e53cb2cf1fcbb5fa28d3c206789cdb1c98ce3510b66b0397734ba4c4/_native_batch_norm_legit.h +58 -0
  19. shared/package-files/74/7435b58c6e505b4ad84566f3966050f0f4f6bfd65d5a0149d0844786f0494324/__init__.pyi +24 -0
  20. shared/package-files/74/7435f850d700fce2f0a7c1821c704b5717494b767a62c815be2fbe57cc610074/special_erfinv.h +39 -0
  21. shared/package-files/74/743857b19d6f384a0e30a0f691b06b04fe8e33a419c4596ae57c6ddba8740e08/reciprocal_cpu_dispatch.h +26 -0
  22. shared/package-files/74/743d6cd7703766653ad5d97023d063c0bba212eb748ef0d54b76af8b863afc20/test_numba.py +129 -0
  23. shared/package-files/74/7445d870e3d174c32214e605bd833ec8d4484aeaf70539ba521e7d9ba871c799/darwin-160x64-m +0 -0
  24. shared/package-files/74/7445d870e3d174c32214e605bd833ec8d4484aeaf70539ba521e7d9ba871c799/xnuppc-160x64-m +0 -0
  25. shared/package-files/74/7449d4c5166158cf346487d0dfd70bcf3251376c76576582fadddcb8560c5443/dependencies.py +818 -0
  26. shared/package-files/74/744e964536e572ae3424a8572500ec3b0be114f26cb63ffc71e8222ed847d24b/__init__.py +43 -0
  27. shared/package-files/74/7455918576862d910a3b1211c3ff1a24afea4eb8599047fc8943809a0d9aecf5/python_compiled_autograd.h +7 -0
  28. shared/package-files/74/745753959035fda80cbb13f5384474d9c2aa67e451f1d874112ffaf5774fdb4c/test_numconv.py +38 -0
  29. shared/package-files/74/746362b4d3db1f374ca77994944796cd71235f222fa69d4d26d0cfd4a6cd94fb/darwin-80x25-m +0 -0
  30. shared/package-files/74/74640986f3954e36f52d54f9a8f64b271a31df4b83326383076e88cfa4e355b7/_tv_tensor.py +132 -0
  31. shared/package-files/74/7468a8b3ed64f900467b0ed817338d653cd55b1cfe69801aaa571c976fe1e41a/_extended_precision.py +27 -0
  32. shared/package-files/74/746b38d4187c578e5834bdffa3c2afbf111e6c49d1dd1778bd411f27b09633b8/sparse_compressed_tensor_ops.h +39 -0
  33. shared/package-files/74/746f744513890193f4e0ff0a4f36c93849b9c3ee656c73df3f5b54e486c4ac9a/site.pyi +15 -0
  34. shared/package-files/74/747f4d6e7edb335308724829e44f9f65dcf83ed53ba4f1172e79c746431eaf7a/pad_native.h +21 -0
  35. shared/package-files/74/7498883445447692d2af9f99fdaec1c68606bc0d7ea427c789aff1885d137d8a/ubsan.h +97 -0
  36. shared/package-files/74/7498de6addc14be4d89f546b505570b9f50c6ac6edccb7d8468cbf1d710d7854/utils.py +136 -0
  37. shared/package-files/74/749937a279c373f53a387e2e04d9a3a45d0a70b0081d981fe2dbcf0a8c856921/special_shifted_chebyshev_polynomial_v_meta.h +27 -0
  38. shared/package-files/74/74a59a0d9a6268c92e571a57aaa93109f4e759e489b30dc04b88a2b5d99b611e/base.py +448 -0
  39. shared/package-files/74/74b12fdedc6706b1d8c5a8ce60042103c080edac62b8fc351026da1cbe69df7f/test_adjlist.py +268 -0
  40. shared/package-files/74/74ba44a36438f5d10c9a8d777f8f5a7381f2d738b1883b155de85acc125f8b9e/nonascii.py +4 -0
  41. shared/package-files/74/74bf2c9f2530363853404d854367570148d36e8117847d8939e850a2f1df8b17/type_fwd.h +28 -0
  42. shared/package-files/74/74cb5a1b5d641a526b8092601961036590269cefc77d3dcbe17f2923bd8b2c56/Boa_Vista +0 -0
  43. shared/package-files/74/74d25b704e4e54363fc07c0dfd4054b5f211775dceaaef910443bbe20e52b010/scalar_byte.sav +0 -0
  44. shared/package-files/74/74dfbdd489c7257280129e4310ebc2f1baa5ee71feac829ef373bc0d40f3d15a/bartlett_window_native.h +24 -0
  45. shared/package-files/74/74e2d737140952e364e42db839d1c1aef4e603493ae640b9d73ddd0f98163b30/aaa-30-rv +0 -0
  46. shared/package-files/74/74e2d737140952e364e42db839d1c1aef4e603493ae640b9d73ddd0f98163b30/aaa-rv +0 -0
  47. shared/package-files/74/74f9be00518ea6c3d0a8651ec053f14fa9a337dbb1bcbde3a410f753bc970bc9/_ctc_loss_backward_cpu_dispatch.h +24 -0
  48. shared/package-files/7d/7d012c25bec6b3ff55abd574c47202074105c4d446cb1b9baf8c386459867316/__init__.py +904 -0
  49. shared/package-files/7d/7d02875b6c4be3248997fbfbfc675fc4203a743c230c631d37b02ae9fd84422e/minix-1.5 +0 -0
  50. shared/package-files/7d/7d02875b6c4be3248997fbfbfc675fc4203a743c230c631d37b02ae9fd84422e/minix-old +0 -0
shared/package-files/28/2808ec768e7053bc77b6b2471c20a81e1fdaebde861bd0348f7979a9713db535/upsample_linear1d_backward_cuda_dispatch.h ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ // @generated by torchgen/gen.py from DispatchKeyFunction.h
3
+
4
+ // NB: The implementing C++ file is RegisterDispatchKey.cpp
5
+
6
+ // The only #includes we need are for custom classes that have defaults in the C++ API
7
+ #include <c10/core/MemoryFormat.h>
8
+ #include <c10/core/Scalar.h>
9
+ #include <ATen/core/Reduction.h>
10
+
11
+ // Forward declarations of any types needed in the operator signatures.
12
+ // We can't directly include these classes because it will cause circular include dependencies.
13
+ // This file is included by TensorBody.h, which defines the Tensor class.
14
+ #include <ATen/core/ATen_fwd.h>
15
+
16
+ namespace at {
17
+
18
+ namespace cuda {
19
+
20
+ TORCH_API at::Tensor upsample_linear1d_backward(const at::Tensor & grad_output, at::IntArrayRef output_size, at::IntArrayRef input_size, bool align_corners, c10::optional<double> scales=c10::nullopt);
21
+ TORCH_API at::Tensor upsample_linear1d_backward_symint(const at::Tensor & grad_output, c10::SymIntArrayRef output_size, c10::SymIntArrayRef input_size, bool align_corners, c10::optional<double> scales=c10::nullopt);
22
+ TORCH_API at::Tensor & upsample_linear1d_backward_out(at::Tensor & grad_input, const at::Tensor & grad_output, at::IntArrayRef output_size, at::IntArrayRef input_size, bool align_corners, c10::optional<double> scales=c10::nullopt);
23
+ TORCH_API at::Tensor & upsample_linear1d_backward_outf(const at::Tensor & grad_output, at::IntArrayRef output_size, at::IntArrayRef input_size, bool align_corners, c10::optional<double> scales, at::Tensor & grad_input);
24
+ TORCH_API at::Tensor & upsample_linear1d_backward_symint_out(at::Tensor & grad_input, const at::Tensor & grad_output, c10::SymIntArrayRef output_size, c10::SymIntArrayRef input_size, bool align_corners, c10::optional<double> scales=c10::nullopt);
25
+ TORCH_API at::Tensor & upsample_linear1d_backward_symint_outf(const at::Tensor & grad_output, c10::SymIntArrayRef output_size, c10::SymIntArrayRef input_size, bool align_corners, c10::optional<double> scales, at::Tensor & grad_input);
26
+
27
+ } // namespace cuda
28
+ } // namespace at
shared/package-files/28/281fb0de8cc41105084cd2ed32dc7c3fd25e0eb8d0a3c1bbb98b159ea9dae1cf/_table_schema.py ADDED
@@ -0,0 +1,387 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Table Schema builders
3
+
4
+ https://specs.frictionlessdata.io/table-schema/
5
+ """
6
+ from __future__ import annotations
7
+
8
+ from typing import (
9
+ TYPE_CHECKING,
10
+ Any,
11
+ cast,
12
+ )
13
+ import warnings
14
+
15
+ from pandas._libs import lib
16
+ from pandas._libs.json import ujson_loads
17
+ from pandas._libs.tslibs import timezones
18
+ from pandas._libs.tslibs.dtypes import freq_to_period_freqstr
19
+ from pandas.util._exceptions import find_stack_level
20
+
21
+ from pandas.core.dtypes.base import _registry as registry
22
+ from pandas.core.dtypes.common import (
23
+ is_bool_dtype,
24
+ is_integer_dtype,
25
+ is_numeric_dtype,
26
+ is_string_dtype,
27
+ )
28
+ from pandas.core.dtypes.dtypes import (
29
+ CategoricalDtype,
30
+ DatetimeTZDtype,
31
+ ExtensionDtype,
32
+ PeriodDtype,
33
+ )
34
+
35
+ from pandas import DataFrame
36
+ import pandas.core.common as com
37
+
38
+ from pandas.tseries.frequencies import to_offset
39
+
40
+ if TYPE_CHECKING:
41
+ from pandas._typing import (
42
+ DtypeObj,
43
+ JSONSerializable,
44
+ )
45
+
46
+ from pandas import Series
47
+ from pandas.core.indexes.multi import MultiIndex
48
+
49
+
50
+ TABLE_SCHEMA_VERSION = "1.4.0"
51
+
52
+
53
+ def as_json_table_type(x: DtypeObj) -> str:
54
+ """
55
+ Convert a NumPy / pandas type to its corresponding json_table.
56
+
57
+ Parameters
58
+ ----------
59
+ x : np.dtype or ExtensionDtype
60
+
61
+ Returns
62
+ -------
63
+ str
64
+ the Table Schema data types
65
+
66
+ Notes
67
+ -----
68
+ This table shows the relationship between NumPy / pandas dtypes,
69
+ and Table Schema dtypes.
70
+
71
+ ============== =================
72
+ Pandas type Table Schema type
73
+ ============== =================
74
+ int64 integer
75
+ float64 number
76
+ bool boolean
77
+ datetime64[ns] datetime
78
+ timedelta64[ns] duration
79
+ object str
80
+ categorical any
81
+ =============== =================
82
+ """
83
+ if is_integer_dtype(x):
84
+ return "integer"
85
+ elif is_bool_dtype(x):
86
+ return "boolean"
87
+ elif is_numeric_dtype(x):
88
+ return "number"
89
+ elif lib.is_np_dtype(x, "M") or isinstance(x, (DatetimeTZDtype, PeriodDtype)):
90
+ return "datetime"
91
+ elif lib.is_np_dtype(x, "m"):
92
+ return "duration"
93
+ elif is_string_dtype(x):
94
+ return "string"
95
+ else:
96
+ return "any"
97
+
98
+
99
+ def set_default_names(data):
100
+ """Sets index names to 'index' for regular, or 'level_x' for Multi"""
101
+ if com.all_not_none(*data.index.names):
102
+ nms = data.index.names
103
+ if len(nms) == 1 and data.index.name == "index":
104
+ warnings.warn(
105
+ "Index name of 'index' is not round-trippable.",
106
+ stacklevel=find_stack_level(),
107
+ )
108
+ elif len(nms) > 1 and any(x.startswith("level_") for x in nms):
109
+ warnings.warn(
110
+ "Index names beginning with 'level_' are not round-trippable.",
111
+ stacklevel=find_stack_level(),
112
+ )
113
+ return data
114
+
115
+ data = data.copy()
116
+ if data.index.nlevels > 1:
117
+ data.index.names = com.fill_missing_names(data.index.names)
118
+ else:
119
+ data.index.name = data.index.name or "index"
120
+ return data
121
+
122
+
123
+ def convert_pandas_type_to_json_field(arr) -> dict[str, JSONSerializable]:
124
+ dtype = arr.dtype
125
+ name: JSONSerializable
126
+ if arr.name is None:
127
+ name = "values"
128
+ else:
129
+ name = arr.name
130
+ field: dict[str, JSONSerializable] = {
131
+ "name": name,
132
+ "type": as_json_table_type(dtype),
133
+ }
134
+
135
+ if isinstance(dtype, CategoricalDtype):
136
+ cats = dtype.categories
137
+ ordered = dtype.ordered
138
+
139
+ field["constraints"] = {"enum": list(cats)}
140
+ field["ordered"] = ordered
141
+ elif isinstance(dtype, PeriodDtype):
142
+ field["freq"] = dtype.freq.freqstr
143
+ elif isinstance(dtype, DatetimeTZDtype):
144
+ if timezones.is_utc(dtype.tz):
145
+ # timezone.utc has no "zone" attr
146
+ field["tz"] = "UTC"
147
+ else:
148
+ # error: "tzinfo" has no attribute "zone"
149
+ field["tz"] = dtype.tz.zone # type: ignore[attr-defined]
150
+ elif isinstance(dtype, ExtensionDtype):
151
+ field["extDtype"] = dtype.name
152
+ return field
153
+
154
+
155
+ def convert_json_field_to_pandas_type(field) -> str | CategoricalDtype:
156
+ """
157
+ Converts a JSON field descriptor into its corresponding NumPy / pandas type
158
+
159
+ Parameters
160
+ ----------
161
+ field
162
+ A JSON field descriptor
163
+
164
+ Returns
165
+ -------
166
+ dtype
167
+
168
+ Raises
169
+ ------
170
+ ValueError
171
+ If the type of the provided field is unknown or currently unsupported
172
+
173
+ Examples
174
+ --------
175
+ >>> convert_json_field_to_pandas_type({"name": "an_int", "type": "integer"})
176
+ 'int64'
177
+
178
+ >>> convert_json_field_to_pandas_type(
179
+ ... {
180
+ ... "name": "a_categorical",
181
+ ... "type": "any",
182
+ ... "constraints": {"enum": ["a", "b", "c"]},
183
+ ... "ordered": True,
184
+ ... }
185
+ ... )
186
+ CategoricalDtype(categories=['a', 'b', 'c'], ordered=True, categories_dtype=object)
187
+
188
+ >>> convert_json_field_to_pandas_type({"name": "a_datetime", "type": "datetime"})
189
+ 'datetime64[ns]'
190
+
191
+ >>> convert_json_field_to_pandas_type(
192
+ ... {"name": "a_datetime_with_tz", "type": "datetime", "tz": "US/Central"}
193
+ ... )
194
+ 'datetime64[ns, US/Central]'
195
+ """
196
+ typ = field["type"]
197
+ if typ == "string":
198
+ return field.get("extDtype", None)
199
+ elif typ == "integer":
200
+ return field.get("extDtype", "int64")
201
+ elif typ == "number":
202
+ return field.get("extDtype", "float64")
203
+ elif typ == "boolean":
204
+ return field.get("extDtype", "bool")
205
+ elif typ == "duration":
206
+ return "timedelta64"
207
+ elif typ == "datetime":
208
+ if field.get("tz"):
209
+ return f"datetime64[ns, {field['tz']}]"
210
+ elif field.get("freq"):
211
+ # GH#9586 rename frequency M to ME for offsets
212
+ offset = to_offset(field["freq"])
213
+ freq_n, freq_name = offset.n, offset.name
214
+ freq = freq_to_period_freqstr(freq_n, freq_name)
215
+ # GH#47747 using datetime over period to minimize the change surface
216
+ return f"period[{freq}]"
217
+ else:
218
+ return "datetime64[ns]"
219
+ elif typ == "any":
220
+ if "constraints" in field and "ordered" in field:
221
+ return CategoricalDtype(
222
+ categories=field["constraints"]["enum"], ordered=field["ordered"]
223
+ )
224
+ elif "extDtype" in field:
225
+ return registry.find(field["extDtype"])
226
+ else:
227
+ return "object"
228
+
229
+ raise ValueError(f"Unsupported or invalid field type: {typ}")
230
+
231
+
232
+ def build_table_schema(
233
+ data: DataFrame | Series,
234
+ index: bool = True,
235
+ primary_key: bool | None = None,
236
+ version: bool = True,
237
+ ) -> dict[str, JSONSerializable]:
238
+ """
239
+ Create a Table schema from ``data``.
240
+
241
+ Parameters
242
+ ----------
243
+ data : Series, DataFrame
244
+ index : bool, default True
245
+ Whether to include ``data.index`` in the schema.
246
+ primary_key : bool or None, default True
247
+ Column names to designate as the primary key.
248
+ The default `None` will set `'primaryKey'` to the index
249
+ level or levels if the index is unique.
250
+ version : bool, default True
251
+ Whether to include a field `pandas_version` with the version
252
+ of pandas that last revised the table schema. This version
253
+ can be different from the installed pandas version.
254
+
255
+ Returns
256
+ -------
257
+ dict
258
+
259
+ Notes
260
+ -----
261
+ See `Table Schema
262
+ <https://pandas.pydata.org/docs/user_guide/io.html#table-schema>`__ for
263
+ conversion types.
264
+ Timedeltas as converted to ISO8601 duration format with
265
+ 9 decimal places after the seconds field for nanosecond precision.
266
+
267
+ Categoricals are converted to the `any` dtype, and use the `enum` field
268
+ constraint to list the allowed values. The `ordered` attribute is included
269
+ in an `ordered` field.
270
+
271
+ Examples
272
+ --------
273
+ >>> from pandas.io.json._table_schema import build_table_schema
274
+ >>> df = pd.DataFrame(
275
+ ... {'A': [1, 2, 3],
276
+ ... 'B': ['a', 'b', 'c'],
277
+ ... 'C': pd.date_range('2016-01-01', freq='d', periods=3),
278
+ ... }, index=pd.Index(range(3), name='idx'))
279
+ >>> build_table_schema(df)
280
+ {'fields': \
281
+ [{'name': 'idx', 'type': 'integer'}, \
282
+ {'name': 'A', 'type': 'integer'}, \
283
+ {'name': 'B', 'type': 'string'}, \
284
+ {'name': 'C', 'type': 'datetime'}], \
285
+ 'primaryKey': ['idx'], \
286
+ 'pandas_version': '1.4.0'}
287
+ """
288
+ if index is True:
289
+ data = set_default_names(data)
290
+
291
+ schema: dict[str, Any] = {}
292
+ fields = []
293
+
294
+ if index:
295
+ if data.index.nlevels > 1:
296
+ data.index = cast("MultiIndex", data.index)
297
+ for level, name in zip(data.index.levels, data.index.names):
298
+ new_field = convert_pandas_type_to_json_field(level)
299
+ new_field["name"] = name
300
+ fields.append(new_field)
301
+ else:
302
+ fields.append(convert_pandas_type_to_json_field(data.index))
303
+
304
+ if data.ndim > 1:
305
+ for column, s in data.items():
306
+ fields.append(convert_pandas_type_to_json_field(s))
307
+ else:
308
+ fields.append(convert_pandas_type_to_json_field(data))
309
+
310
+ schema["fields"] = fields
311
+ if index and data.index.is_unique and primary_key is None:
312
+ if data.index.nlevels == 1:
313
+ schema["primaryKey"] = [data.index.name]
314
+ else:
315
+ schema["primaryKey"] = data.index.names
316
+ elif primary_key is not None:
317
+ schema["primaryKey"] = primary_key
318
+
319
+ if version:
320
+ schema["pandas_version"] = TABLE_SCHEMA_VERSION
321
+ return schema
322
+
323
+
324
+ def parse_table_schema(json, precise_float: bool) -> DataFrame:
325
+ """
326
+ Builds a DataFrame from a given schema
327
+
328
+ Parameters
329
+ ----------
330
+ json :
331
+ A JSON table schema
332
+ precise_float : bool
333
+ Flag controlling precision when decoding string to double values, as
334
+ dictated by ``read_json``
335
+
336
+ Returns
337
+ -------
338
+ df : DataFrame
339
+
340
+ Raises
341
+ ------
342
+ NotImplementedError
343
+ If the JSON table schema contains either timezone or timedelta data
344
+
345
+ Notes
346
+ -----
347
+ Because :func:`DataFrame.to_json` uses the string 'index' to denote a
348
+ name-less :class:`Index`, this function sets the name of the returned
349
+ :class:`DataFrame` to ``None`` when said string is encountered with a
350
+ normal :class:`Index`. For a :class:`MultiIndex`, the same limitation
351
+ applies to any strings beginning with 'level_'. Therefore, an
352
+ :class:`Index` name of 'index' and :class:`MultiIndex` names starting
353
+ with 'level_' are not supported.
354
+
355
+ See Also
356
+ --------
357
+ build_table_schema : Inverse function.
358
+ pandas.read_json
359
+ """
360
+ table = ujson_loads(json, precise_float=precise_float)
361
+ col_order = [field["name"] for field in table["schema"]["fields"]]
362
+ df = DataFrame(table["data"], columns=col_order)[col_order]
363
+
364
+ dtypes = {
365
+ field["name"]: convert_json_field_to_pandas_type(field)
366
+ for field in table["schema"]["fields"]
367
+ }
368
+
369
+ # No ISO constructor for Timedelta as of yet, so need to raise
370
+ if "timedelta64" in dtypes.values():
371
+ raise NotImplementedError(
372
+ 'table="orient" can not yet read ISO-formatted Timedelta data'
373
+ )
374
+
375
+ df = df.astype(dtypes)
376
+
377
+ if "primaryKey" in table["schema"]:
378
+ df = df.set_index(table["schema"]["primaryKey"])
379
+ if len(df.index.names) == 1:
380
+ if df.index.name == "index":
381
+ df.index.name = None
382
+ else:
383
+ df.index.names = [
384
+ None if x.startswith("level_") else x for x in df.index.names
385
+ ]
386
+
387
+ return df
shared/package-files/28/284621cae64b99ea4346e679b9d0ab35ac5a02fd76b71985ac1cb8a2a5ccef6a/logdet.h ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from Function.h
4
+
5
+ #include <ATen/Context.h>
6
+ #include <ATen/DeviceGuard.h>
7
+ #include <ATen/TensorUtils.h>
8
+ #include <ATen/TracerMode.h>
9
+ #include <ATen/core/Generator.h>
10
+ #include <ATen/core/Reduction.h>
11
+ #include <ATen/core/Tensor.h>
12
+ #include <c10/core/Scalar.h>
13
+ #include <c10/core/Storage.h>
14
+ #include <c10/core/TensorOptions.h>
15
+ #include <c10/util/Deprecated.h>
16
+ #include <c10/util/Optional.h>
17
+
18
+
19
+
20
+ #include <ATen/ops/logdet_ops.h>
21
+
22
+ namespace at {
23
+
24
+
25
+ // aten::logdet(Tensor self) -> Tensor
26
+ inline at::Tensor logdet(const at::Tensor & self) {
27
+ return at::_ops::logdet::call(self);
28
+ }
29
+
30
+ }
shared/package-files/28/2868c82c87d01c0551beda25dbdc12c0db675f9cca8c6dba37ace150f19e0b39/rolodex ADDED
@@ -0,0 +1,204 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/sh
2
+ # the next line restarts using wish \
3
+ exec wish8.6 "$0" ${1+"$@"}
4
+
5
+ # rolodex --
6
+ # This script was written as an entry in Tom LaStrange's rolodex
7
+ # benchmark. It creates something that has some of the look and
8
+ # feel of a rolodex program, although it's lifeless and doesn't
9
+ # actually do the rolodex application.
10
+
11
+ package require Tk
12
+
13
+ foreach i [winfo child .] {
14
+ catch {destroy $i}
15
+ }
16
+
17
+ set version 1.2
18
+
19
+ #------------------------------------------
20
+ # Phase 0: create the front end.
21
+ #------------------------------------------
22
+
23
+ frame .frame -relief flat
24
+ pack .frame -side top -fill y -anchor center
25
+
26
+ set names {{} Name: Address: {} {} {Home Phone:} {Work Phone:} Fax:}
27
+ foreach i {1 2 3 4 5 6 7} {
28
+ label .frame.label$i -text [lindex $names $i] -anchor e
29
+ entry .frame.entry$i -width 35
30
+ grid .frame.label$i .frame.entry$i -sticky ew -pady 2 -padx 1
31
+ }
32
+
33
+ frame .buttons
34
+ pack .buttons -side bottom -pady 2 -anchor center
35
+ button .buttons.clear -text Clear
36
+ button .buttons.add -text Add
37
+ button .buttons.search -text Search
38
+ button .buttons.delete -text "Delete ..."
39
+ pack .buttons.clear .buttons.add .buttons.search .buttons.delete \
40
+ -side left -padx 2
41
+
42
+ #------------------------------------------
43
+ # Phase 1: Add menus, dialog boxes
44
+ #------------------------------------------
45
+
46
+ # DKF - note that this is an old-style menu bar; I just have not yet
47
+ # got around to converting the context help code to work with the new
48
+ # menu system and its <<MenuSelect>> virtual event.
49
+
50
+ frame .menu -relief raised -borderwidth 1
51
+ pack .menu -before .frame -side top -fill x
52
+
53
+ menubutton .menu.file -text "File" -menu .menu.file.m -underline 0
54
+ menu .menu.file.m
55
+ .menu.file.m add command -label "Load ..." -command fileAction -underline 0
56
+ .menu.file.m add command -label "Exit" -command {destroy .} -underline 0
57
+ pack .menu.file -side left
58
+
59
+ menubutton .menu.help -text "Help" -menu .menu.help.m -underline 0
60
+ menu .menu.help.m
61
+ pack .menu.help -side right
62
+
63
+ proc deleteAction {} {
64
+ if {[tk_dialog .delete {Confirm Action} {Are you sure?} {} 0 Cancel]
65
+ == 0} {
66
+ clearAction
67
+ }
68
+ }
69
+ .buttons.delete config -command deleteAction
70
+
71
+ proc fileAction {} {
72
+ tk_dialog .fileSelection {File Selection} {This is a dummy file selection dialog box, which is used because there isn't a good file selection dialog built into Tk yet.} {} 0 OK
73
+ puts stderr {dummy file name}
74
+ }
75
+
76
+ #------------------------------------------
77
+ # Phase 3: Print contents of card
78
+ #------------------------------------------
79
+
80
+ proc addAction {} {
81
+ global names
82
+ foreach i {1 2 3 4 5 6 7} {
83
+ puts stderr [format "%-12s %s" [lindex $names $i] [.frame.entry$i get]]
84
+ }
85
+ }
86
+ .buttons.add config -command addAction
87
+
88
+ #------------------------------------------
89
+ # Phase 4: Miscellaneous other actions
90
+ #------------------------------------------
91
+
92
+ proc clearAction {} {
93
+ foreach i {1 2 3 4 5 6 7} {
94
+ .frame.entry$i delete 0 end
95
+ }
96
+ }
97
+ .buttons.clear config -command clearAction
98
+
99
+ proc fillCard {} {
100
+ clearAction
101
+ .frame.entry1 insert 0 "John Ousterhout"
102
+ .frame.entry2 insert 0 "CS Division, Department of EECS"
103
+ .frame.entry3 insert 0 "University of California"
104
+ .frame.entry4 insert 0 "Berkeley, CA 94720"
105
+ .frame.entry5 insert 0 "private"
106
+ .frame.entry6 insert 0 "510-642-0865"
107
+ .frame.entry7 insert 0 "510-642-5775"
108
+ }
109
+ .buttons.search config -command "addAction; fillCard"
110
+
111
+ #----------------------------------------------------
112
+ # Phase 5: Accelerators, mnemonics, command-line info
113
+ #----------------------------------------------------
114
+
115
+ .buttons.clear config -text "Clear Ctrl+C"
116
+ bind . <Control-c> clearAction
117
+ .buttons.add config -text "Add Ctrl+A"
118
+ bind . <Control-a> addAction
119
+ .buttons.search config -text "Search Ctrl+S"
120
+ bind . <Control-s> "addAction; fillCard"
121
+ .buttons.delete config -text "Delete... Ctrl+D"
122
+ bind . <Control-d> deleteAction
123
+
124
+ .menu.file.m entryconfig 1 -accel Ctrl+F
125
+ bind . <Control-f> fileAction
126
+ .menu.file.m entryconfig 2 -accel Ctrl+Q
127
+ bind . <Control-q> {destroy .}
128
+
129
+ focus .frame.entry1
130
+
131
+ #----------------------------------------------------
132
+ # Phase 6: help
133
+ #----------------------------------------------------
134
+
135
+ proc Help {topic {x 0} {y 0}} {
136
+ global helpTopics helpCmds
137
+ if {$topic == ""} return
138
+ while {[info exists helpCmds($topic)]} {
139
+ set topic [eval $helpCmds($topic)]
140
+ }
141
+ if [info exists helpTopics($topic)] {
142
+ set msg $helpTopics($topic)
143
+ } else {
144
+ set msg "Sorry, but no help is available for this topic"
145
+ }
146
+ tk_dialog .help {Rolodex Help} "Information on $topic:\n\n$msg" \
147
+ {} 0 OK
148
+ }
149
+
150
+ proc getMenuTopic {w x y} {
151
+ return $w.[$w index @[expr {$y-[winfo rooty $w]}]]
152
+ }
153
+
154
+ event add <<Help>> <F1> <Help>
155
+ bind . <<Help>> {Help [winfo containing %X %Y] %X %Y}
156
+ bind Menu <<Help>> {Help [winfo containing %X %Y] %X %Y}
157
+
158
+ # Help text and commands follow:
159
+
160
+ set helpTopics(.menu.file) {This is the "file" menu. It can be used to invoke some overall operations on the rolodex applications, such as loading a file or exiting.}
161
+
162
+ set helpCmds(.menu.file.m) {getMenuTopic $topic $x $y}
163
+ set helpTopics(.menu.file.m.1) {The "Load" entry in the "File" menu posts a dialog box that you can use to select a rolodex file}
164
+ set helpTopics(.menu.file.m.2) {The "Exit" entry in the "File" menu causes the rolodex application to terminate}
165
+ set helpCmds(.menu.file.m.none) {set topic ".menu.file"}
166
+
167
+ set helpTopics(.frame.entry1) {In this field of the rolodex entry you should type the person's name}
168
+ set helpTopics(.frame.entry2) {In this field of the rolodex entry you should type the first line of the person's address}
169
+ set helpTopics(.frame.entry3) {In this field of the rolodex entry you should type the second line of the person's address}
170
+ set helpTopics(.frame.entry4) {In this field of the rolodex entry you should type the third line of the person's address}
171
+ set helpTopics(.frame.entry5) {In this field of the rolodex entry you should type the person's home phone number, or "private" if the person doesn't want his or her number publicized}
172
+ set helpTopics(.frame.entry6) {In this field of the rolodex entry you should type the person's work phone number}
173
+ set helpTopics(.frame.entry7) {In this field of the rolodex entry you should type the phone number for the person's FAX machine}
174
+
175
+ set helpCmds(.frame.label1) {set topic .frame.entry1}
176
+ set helpCmds(.frame.label2) {set topic .frame.entry2}
177
+ set helpCmds(.frame.label3) {set topic .frame.entry3}
178
+ set helpCmds(.frame.label4) {set topic .frame.entry4}
179
+ set helpCmds(.frame.label5) {set topic .frame.entry5}
180
+ set helpCmds(.frame.label6) {set topic .frame.entry6}
181
+ set helpCmds(.frame.label7) {set topic .frame.entry7}
182
+
183
+ set helpTopics(context) {Unfortunately, this application doesn't support context-sensitive help in the usual way, because when this demo was written Tk didn't have a grab mechanism and this is needed for context-sensitive help. Instead, you can achieve much the same effect by simply moving the mouse over the window you're curious about and pressing the Help or F1 keys. You can do this anytime.}
184
+ set helpTopics(help) {This application provides only very crude help. Besides the entries in this menu, you can get help on individual windows by moving the mouse cursor over the window and pressing the Help or F1 keys.}
185
+ set helpTopics(window) {This window is a dummy rolodex application created as part of Tom LaStrange's toolkit benchmark. It doesn't really do anything useful except to demonstrate a few features of the Tk toolkit.}
186
+ set helpTopics(keys) "The following accelerator keys are defined for this application (in addition to those already available for the entry windows):\n\nCtrl+A:\t\tAdd\nCtrl+C:\t\tClear\nCtrl+D:\t\tDelete\nCtrl+F:\t\tEnter file name\nCtrl+Q:\t\tExit application (quit)\nCtrl+S:\t\tSearch (dummy operation)"
187
+ set helpTopics(version) "This is version $version."
188
+
189
+ # Entries in "Help" menu
190
+
191
+ .menu.help.m add command -label "On Context..." -command {Help context} \
192
+ -underline 3
193
+ .menu.help.m add command -label "On Help..." -command {Help help} \
194
+ -underline 3
195
+ .menu.help.m add command -label "On Window..." -command {Help window} \
196
+ -underline 3
197
+ .menu.help.m add command -label "On Keys..." -command {Help keys} \
198
+ -underline 3
199
+ .menu.help.m add command -label "On Version..." -command {Help version} \
200
+ -underline 3
201
+
202
+ # Local Variables:
203
+ # mode: tcl
204
+ # End:
shared/package-files/28/288452b8eb988dc8d10b89524477cac6d80a7a4c25697d7eb8843b17ebae584a/libev.so.4 ADDED
Binary file (69 kB). View file
 
shared/package-files/28/2889a273f20bca1c5abdb1b15676be02c71ffbea2489b6a564994ae386b97627/RegistrationDeclarations.h ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ // This file contains all native_functions that can be registered to
2
+ // and the schema string that they should be registered with
3
+
4
+ ${registration_declarations}
shared/package-files/28/28948c9b3b5746a4efa66901fa4cbe592548a80320fc6716a1ec13711c49d42c/_gauss_legendre.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from scipy._lib._array_api import array_namespace, np_compat
2
+
3
+ from functools import cached_property
4
+
5
+ from scipy.special import roots_legendre
6
+
7
+ from ._base import FixedRule
8
+
9
+
10
+ class GaussLegendreQuadrature(FixedRule):
11
+ """
12
+ Gauss-Legendre quadrature.
13
+
14
+ Parameters
15
+ ----------
16
+ npoints : int
17
+ Number of nodes for the higher-order rule.
18
+
19
+ xp : array_namespace, optional
20
+ The namespace for the node and weight arrays. Default is None, where NumPy is
21
+ used.
22
+
23
+ Examples
24
+ --------
25
+ Evaluate a 1D integral. Note in this example that ``f`` returns an array, so the
26
+ estimates will also be arrays.
27
+
28
+ >>> import numpy as np
29
+ >>> from scipy.integrate import cubature
30
+ >>> from scipy.integrate._rules import GaussLegendreQuadrature
31
+ >>> def f(x):
32
+ ... return np.cos(x)
33
+ >>> rule = GaussLegendreQuadrature(21) # Use 21-point GaussLegendre
34
+ >>> a, b = np.array([0]), np.array([1])
35
+ >>> rule.estimate(f, a, b) # True value sin(1), approximately 0.84147
36
+ array([0.84147098])
37
+ >>> rule.estimate_error(f, a, b)
38
+ array([1.11022302e-16])
39
+ """
40
+
41
+ def __init__(self, npoints, xp=None):
42
+ if npoints < 2:
43
+ raise ValueError(
44
+ "At least 2 nodes required for Gauss-Legendre cubature"
45
+ )
46
+
47
+ self.npoints = npoints
48
+
49
+ if xp is None:
50
+ xp = np_compat
51
+
52
+ self.xp = array_namespace(xp.empty(0))
53
+
54
+ @cached_property
55
+ def nodes_and_weights(self):
56
+ # TODO: current converting to/from numpy
57
+ nodes, weights = roots_legendre(self.npoints)
58
+
59
+ return (
60
+ self.xp.asarray(nodes, dtype=self.xp.float64),
61
+ self.xp.asarray(weights, dtype=self.xp.float64)
62
+ )
shared/package-files/28/289651087fe34e9e4e64cf38ee1520b41c7964bd42b54dc3435d9a5ca860f0fe/vt100-putty ADDED
Binary file (1.29 kB). View file
 
shared/package-files/28/28b1c1421f5a5a02d859b7aac36922c906ae18d0e22a669d78c9a5b6274696b9/dateformat.pyi ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from datetime import datetime, date
2
+ from typing import Any, Optional, Union
3
+
4
+ from django.utils.timezone import FixedOffset
5
+
6
+ re_formatchars: Any
7
+ re_escaped: Any
8
+
9
+ class Formatter:
10
+ def format(self, formatstr: str) -> str: ...
11
+
12
+ class TimeFormat(Formatter):
13
+ data: Union[datetime, str] = ...
14
+ timezone: Optional[FixedOffset] = ...
15
+ def __init__(self, obj: Union[datetime, str]) -> None: ...
16
+ def a(self) -> str: ...
17
+ def A(self) -> str: ...
18
+ def B(self) -> None: ...
19
+ def e(self) -> str: ...
20
+ def f(self) -> Union[int, str]: ...
21
+ def g(self) -> int: ...
22
+ def G(self) -> int: ...
23
+ def h(self) -> str: ...
24
+ def H(self) -> str: ...
25
+ def i(self) -> str: ...
26
+ def O(self) -> str: ...
27
+ def P(self) -> str: ...
28
+ def s(self) -> str: ...
29
+ def T(self) -> str: ...
30
+ def u(self) -> str: ...
31
+ def Z(self) -> Union[int, str]: ...
32
+
33
+ class DateFormat(TimeFormat):
34
+ data: Union[datetime, str]
35
+ timezone: Optional[FixedOffset]
36
+ year_days: Any = ...
37
+ def b(self): ...
38
+ def c(self) -> str: ...
39
+ def d(self) -> str: ...
40
+ def D(self): ...
41
+ def E(self): ...
42
+ def F(self): ...
43
+ def I(self) -> str: ...
44
+ def j(self) -> int: ...
45
+ def l(self): ...
46
+ def L(self) -> bool: ...
47
+ def m(self) -> str: ...
48
+ def M(self) -> str: ...
49
+ def n(self) -> int: ...
50
+ def N(self): ...
51
+ def o(self) -> int: ...
52
+ def r(self) -> str: ...
53
+ def S(self) -> str: ...
54
+ def t(self) -> str: ...
55
+ def U(self) -> int: ...
56
+ def w(self) -> int: ...
57
+ def W(self) -> int: ...
58
+ def y(self) -> str: ...
59
+ def Y(self) -> int: ...
60
+ def z(self) -> int: ...
61
+
62
+ def format(value: Union[datetime, str, date], format_string: str) -> str: ...
63
+ def time_format(value: Union[datetime, str], format_string: str) -> str: ...
shared/package-files/28/28b67a74effbbbc3a40a4843484feede592668c2034961f874e769ae9735b45b/pattern_utils.py ADDED
@@ -0,0 +1,200 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ import torch.nn.functional as F
4
+ toq = torch.ops.quantized
5
+
6
+ from torch.fx import GraphModule
7
+ from torch.fx.graph import Node
8
+
9
+ from torch.ao.quantization.backend_config import get_native_backend_config
10
+ from torch.ao.quantization.fx.quantize_handler import _get_pattern_to_quantize_handlers
11
+ from torch.ao.quantization.utils import getattr_from_fqn
12
+ from .ns_types import NSNodeTargetType
13
+ from torch.ao.quantization import (
14
+ ObserverBase,
15
+ FakeQuantizeBase,
16
+ )
17
+
18
+ from typing import Dict, Tuple, Set, Callable, Any, Union, List
19
+
20
+
21
+ def get_type_a_related_to_b(
22
+ base_name_to_sets_of_related_ops: Dict[str, Set[NSNodeTargetType]],
23
+ ) -> Set[Tuple[NSNodeTargetType, NSNodeTargetType]]:
24
+ # TODO(future PR): allow customizations
25
+ # TODO(future PR): reuse existing quantization mappings
26
+ # TODO(future PR): add the rest of modules and ops here
27
+ type_a_related_to_b: Set[Tuple[NSNodeTargetType, NSNodeTargetType]] = set()
28
+
29
+ for s in base_name_to_sets_of_related_ops.values():
30
+ s_list = list(s)
31
+ # add every bidirectional pair
32
+ for idx_0 in range(0, len(s_list)):
33
+ for idx_1 in range(idx_0, len(s_list)):
34
+ type_a_related_to_b.add((s_list[idx_0], s_list[idx_1]))
35
+ type_a_related_to_b.add((s_list[idx_1], s_list[idx_0]))
36
+
37
+ return type_a_related_to_b
38
+
39
+
40
+ NSFusionElType = Union[
41
+ Callable, # call_function or call_module type, example: F.linear or nn.Conv2d
42
+ str, # call_method name, example: "dequantize"
43
+ Tuple[str, Any], # call_method name and first argument, example: ("to", torch.float16)
44
+ ]
45
+ NSFusionType = Union[
46
+ Tuple[NSFusionElType, NSFusionElType],
47
+ Tuple[NSFusionElType, NSFusionElType, NSFusionElType, NSFusionElType],
48
+ ]
49
+
50
+ def get_reversed_fusions() -> List[Tuple[NSFusionType, int]]:
51
+ """
52
+ Set of potential fusions, in reverse order. The order is reversed
53
+ to match how fusion patterns are defined in quantization code.
54
+
55
+ Fusion format:
56
+ ((fusion_op_0, fusion_op_1), base_op_idx)
57
+
58
+ Where base_op_idx is the idx of the op we should use to match other related
59
+ ops. Note: base_op_idx is specified in non-reverse order, i.e. a base_op_idx
60
+ of 0 represents the first op in regular (non-reverse) order, 1 represents the
61
+ second op, etc.
62
+ """
63
+ results: List[Tuple[NSFusionType, int]] = []
64
+
65
+ # Possible syntaxes:
66
+ # * single op: torch.nn.Conv2d
67
+ # * multiple ops: (torch.nn.ReLU, torch.nn.Conv2d)
68
+ # For fusions, we only care about patterns composed of multiple ops.
69
+ # TODO(future PR): allow customizations from default patterns.
70
+ all_quant_patterns = _get_pattern_to_quantize_handlers(get_native_backend_config())
71
+
72
+ default_base_op_idx = 0
73
+ for quant_pattern in all_quant_patterns.keys():
74
+ # TODO: this is a temporary hack to flatten the patterns from quantization so
75
+ # that it works with the ns matcher function, maybe we should use `_is_match`
76
+ # in torch.ao.quantization.fx.match_utils to match the patterns
77
+ if isinstance(quant_pattern, tuple) and len(quant_pattern) == 2 and \
78
+ isinstance(quant_pattern[1], tuple) and len(quant_pattern[1]) == 2:
79
+ # flatten the pattern with form (nn.ReLU, (nn.BatchNorm2d, nn.Conv2d))
80
+ quant_pattern = (quant_pattern[0], quant_pattern[1][0], quant_pattern[1][1])
81
+
82
+ # Only patterns of multiple ops are fusions, ignore
83
+ # patterns which contain a single ops (they get matched
84
+ # without caring about fusions).
85
+ if isinstance(quant_pattern, tuple):
86
+ results.append((quant_pattern, default_base_op_idx)) # type: ignore[arg-type]
87
+
88
+ # For each pattern, add additional patterns with observers and
89
+ # fake quants at the end.
90
+ # TODO(future PR): if needed, implement matching for a node
91
+ # having multiple output observers.
92
+ for cls in (ObserverBase, FakeQuantizeBase):
93
+ if isinstance(quant_pattern, tuple):
94
+ new_pattern = (cls, *quant_pattern)
95
+ else:
96
+ new_pattern = (cls, quant_pattern)
97
+ results.append((new_pattern, default_base_op_idx)) # type: ignore[arg-type]
98
+
99
+
100
+ # After this point, results contains values such as
101
+ # [..., ((torch.nn.Relu, torch.nn.Conv2d), 0), ...]
102
+
103
+ # Patterns for matching fp16 emulation are not specified in the quantization
104
+ # fusion mappings. For now, define them here.
105
+ fp16_em_base_op_idx = 1
106
+ patterns_to_add = [
107
+ # linear-relu fp16 emulation:
108
+ # fp16_to_fp32 -> linear -> relu -> fp32_to_fp16
109
+ ((("to", torch.float16), F.relu, F.linear, "dequantize"), fp16_em_base_op_idx,),
110
+ # Conv-BN fusion (this happens outside of quantization patterns,
111
+ # which is why it is defined separately here).
112
+ ((nn.BatchNorm1d, nn.Conv1d), default_base_op_idx),
113
+ ((nn.BatchNorm2d, nn.Conv2d), default_base_op_idx),
114
+ ((nn.BatchNorm3d, nn.Conv3d), default_base_op_idx),
115
+ ((nn.ReLU, nn.BatchNorm1d, nn.Conv1d), default_base_op_idx),
116
+ ((nn.ReLU, nn.BatchNorm2d, nn.Conv2d), default_base_op_idx),
117
+ ((nn.ReLU, nn.BatchNorm3d, nn.Conv3d), default_base_op_idx),
118
+ ]
119
+ for p in patterns_to_add:
120
+ results.append(p) # type: ignore[arg-type]
121
+ results.append(((ObserverBase, *p[0]), p[1])) # type: ignore[arg-type]
122
+ results.append(((FakeQuantizeBase, *p[0]), p[1])) # type: ignore[arg-type]
123
+
124
+ return results
125
+
126
+
127
+ def end_node_matches_reversed_fusion(
128
+ end_node: Node,
129
+ reversed_fusion: NSFusionType,
130
+ gm: GraphModule,
131
+ seen_nodes: Set[Node],
132
+ ) -> bool:
133
+ """
134
+ Returns true if a pattern ending with `end_node` matches
135
+ the fusion pattern.
136
+ """
137
+ cur_node = end_node
138
+ for fusion_idx in range(len(reversed_fusion)):
139
+ # each node can only belong to one matched pattern
140
+ if cur_node in seen_nodes:
141
+ return False
142
+
143
+ cur_fusion_el = reversed_fusion[fusion_idx]
144
+
145
+ if cur_node.op == 'call_function':
146
+ fusion_el_is_fun = (not isinstance(cur_fusion_el, str)) and \
147
+ (not isinstance(cur_fusion_el, type))
148
+ if fusion_el_is_fun:
149
+ if cur_node.target != cur_fusion_el:
150
+ return False
151
+ if len(cur_node.args) > 0 and isinstance(cur_node.args[0], Node):
152
+ cur_node = cur_node.args[0]
153
+ else:
154
+ return False
155
+ else:
156
+ return False
157
+
158
+ elif cur_node.op == 'call_module':
159
+ fusion_el_is_mod = isinstance(cur_fusion_el, type)
160
+ if fusion_el_is_mod:
161
+ assert isinstance(cur_node.target, str)
162
+ target_mod = getattr_from_fqn(gm, cur_node.target)
163
+ if not isinstance(cur_fusion_el, type):
164
+ return False
165
+ if not isinstance(target_mod, cur_fusion_el):
166
+ return False
167
+ if len(cur_node.args) > 0 and isinstance(cur_node.args[0], Node):
168
+ cur_node = cur_node.args[0]
169
+ else:
170
+ return False
171
+ else:
172
+ return False
173
+
174
+ elif cur_node.op == 'call_method':
175
+ fusion_el_is_meth_with_second_arg = \
176
+ isinstance(cur_fusion_el, tuple) and len(cur_fusion_el) == 2
177
+ fusion_el_is_meth_without_args = isinstance(cur_fusion_el, str)
178
+ if fusion_el_is_meth_without_args or fusion_el_is_meth_with_second_arg:
179
+ if fusion_el_is_meth_without_args:
180
+ if cur_node.target != cur_fusion_el:
181
+ return False
182
+ else:
183
+ assert isinstance(cur_fusion_el, tuple)
184
+ if cur_node.target != cur_fusion_el[0]:
185
+ return False
186
+ elif len(cur_node.args) < 2:
187
+ return False
188
+ elif cur_node.args[1] != cur_fusion_el[1]:
189
+ return False
190
+
191
+ if len(cur_node.args) > 0 and isinstance(cur_node.args[0], Node):
192
+ cur_node = cur_node.args[0]
193
+ else:
194
+ return False
195
+ else:
196
+ return False
197
+ else:
198
+ return False
199
+
200
+ return True
shared/package-files/28/28d386370beed69d9b6a2bd16e57502882be80a593a8ba8387c3998b1335031e/geqrf.h ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from Function.h
4
+
5
+ #include <ATen/Context.h>
6
+ #include <ATen/DeviceGuard.h>
7
+ #include <ATen/TensorUtils.h>
8
+ #include <ATen/TracerMode.h>
9
+ #include <ATen/core/Generator.h>
10
+ #include <ATen/core/Reduction.h>
11
+ #include <ATen/core/Tensor.h>
12
+ #include <c10/core/Scalar.h>
13
+ #include <c10/core/Storage.h>
14
+ #include <c10/core/TensorOptions.h>
15
+ #include <c10/util/Deprecated.h>
16
+ #include <c10/util/Optional.h>
17
+
18
+
19
+
20
+ #include <ATen/ops/geqrf_ops.h>
21
+
22
+ namespace at {
23
+
24
+
25
+ // aten::geqrf.a(Tensor self, *, Tensor(a!) a, Tensor(b!) tau) -> (Tensor(a!) a, Tensor(b!) tau)
26
+ inline ::std::tuple<at::Tensor &,at::Tensor &> geqrf_out(at::Tensor & a, at::Tensor & tau, const at::Tensor & self) {
27
+ return at::_ops::geqrf_a::call(self, a, tau);
28
+ }
29
+ // aten::geqrf.a(Tensor self, *, Tensor(a!) a, Tensor(b!) tau) -> (Tensor(a!) a, Tensor(b!) tau)
30
+ inline ::std::tuple<at::Tensor &,at::Tensor &> geqrf_outf(const at::Tensor & self, at::Tensor & a, at::Tensor & tau) {
31
+ return at::_ops::geqrf_a::call(self, a, tau);
32
+ }
33
+
34
+ // aten::geqrf(Tensor self) -> (Tensor a, Tensor tau)
35
+ inline ::std::tuple<at::Tensor,at::Tensor> geqrf(const at::Tensor & self) {
36
+ return at::_ops::geqrf::call(self);
37
+ }
38
+
39
+ }
shared/package-files/28/28d7d9b92f072ab5cd552454a18b713166359c210b1989e0fd90efd9687db686/logical_not_ops.h ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from Operator.h
4
+
5
+ #include <tuple>
6
+ #include <vector>
7
+
8
+ // Forward declarations of any types needed in the operator signatures.
9
+ // We can't directly include these classes because it will cause circular include dependencies.
10
+ // This file is included by TensorBody.h, which defines the Tensor class.
11
+ #include <ATen/core/ATen_fwd.h>
12
+
13
+ namespace at {
14
+ namespace _ops {
15
+
16
+
17
+ struct TORCH_API logical_not {
18
+ using schema = at::Tensor (const at::Tensor &);
19
+ using ptr_schema = schema*;
20
+ // See Note [static constexpr char* members for windows NVCC]
21
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::logical_not")
22
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "")
23
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "logical_not(Tensor self) -> Tensor")
24
+ static at::Tensor call(const at::Tensor & self);
25
+ static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self);
26
+ };
27
+
28
+ struct TORCH_API logical_not_ {
29
+ using schema = at::Tensor & (at::Tensor &);
30
+ using ptr_schema = schema*;
31
+ // See Note [static constexpr char* members for windows NVCC]
32
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::logical_not_")
33
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "")
34
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "logical_not_(Tensor(a!) self) -> Tensor(a!)")
35
+ static at::Tensor & call(at::Tensor & self);
36
+ static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, at::Tensor & self);
37
+ };
38
+
39
+ struct TORCH_API logical_not_out {
40
+ using schema = at::Tensor & (const at::Tensor &, at::Tensor &);
41
+ using ptr_schema = schema*;
42
+ // See Note [static constexpr char* members for windows NVCC]
43
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::logical_not")
44
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out")
45
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "logical_not.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)")
46
+ static at::Tensor & call(const at::Tensor & self, at::Tensor & out);
47
+ static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, at::Tensor & out);
48
+ };
49
+
50
+ }} // namespace at::_ops
shared/package-files/28/28f219e4406c50b28204a450f09ac5fa14fa3330f06c8ba9023b389ad5ba417b/combinatorics.py ADDED
@@ -0,0 +1,126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import random
2
+
3
+ import torch
4
+ from torch.utils.data.datapipes.datapipe import IterDataPipe, MapDataPipe
5
+ from typing import Iterator, List, Optional, TypeVar
6
+
7
+ __all__ = ["ShufflerIterDataPipe", ]
8
+
9
+
10
+ T_co = TypeVar('T_co', covariant=True)
11
+
12
+
13
+ # @functional_datapipe('shuffle')
14
+ class ShufflerIterDataPipe(IterDataPipe[T_co]):
15
+ r"""
16
+ Shuffle the input MapDataPipe via its indices (functional name: ``shuffle``).
17
+
18
+ When it is used with :class:`~torch.utils.data.DataLoader`, the methods to
19
+ set up random seed are different based on :attr:`num_workers`.
20
+
21
+ For single-process mode (:attr:`num_workers == 0`), the random seed is set before
22
+ the :class:`~torch.utils.data.DataLoader` in the main process. For multi-process
23
+ mode (:attr:`num_worker > 0`), ``worker_init_fn`` is used to set up a random seed
24
+ for each worker process.
25
+
26
+ Args:
27
+ datapipe: MapDataPipe being shuffled
28
+ indices: a list of indices of the MapDataPipe. If not provided, we assume it uses 0-based indexing
29
+
30
+ Example:
31
+ >>> # xdoctest: +SKIP
32
+ >>> from torchdata.datapipes.map import SequenceWrapper
33
+ >>> dp = SequenceWrapper(range(10))
34
+ >>> shuffle_dp = dp.shuffle().set_seed(0)
35
+ >>> list(shuffle_dp)
36
+ [7, 8, 1, 5, 3, 4, 2, 0, 9, 6]
37
+ >>> list(shuffle_dp)
38
+ [6, 1, 9, 5, 2, 4, 7, 3, 8, 0]
39
+ >>> # Reset seed for Shuffler
40
+ >>> shuffle_dp = shuffle_dp.set_seed(0)
41
+ >>> list(shuffle_dp)
42
+ [7, 8, 1, 5, 3, 4, 2, 0, 9, 6]
43
+
44
+ Note:
45
+ Even thought this ``shuffle`` operation takes a ``MapDataPipe`` as the input, it would return an
46
+ ``IterDataPipe`` rather than a ``MapDataPipe``, because ``MapDataPipe`` should be non-sensitive to
47
+ the order of data order for the sake of random reads, but ``IterDataPipe`` depends on the order
48
+ of data during data-processing.
49
+ """
50
+
51
+ datapipe: MapDataPipe[T_co]
52
+ _enabled: bool
53
+ _seed: Optional[int]
54
+ _rng: random.Random
55
+
56
+ def __init__(self,
57
+ datapipe: MapDataPipe[T_co],
58
+ *,
59
+ indices: Optional[List] = None,
60
+ ) -> None:
61
+ super().__init__()
62
+ self.datapipe = datapipe
63
+ self.indices = list(range(len(datapipe))) if indices is None else indices
64
+ self._enabled = True
65
+ self._seed = None
66
+ self._rng = random.Random()
67
+ self._shuffled_indices: List = self.indices
68
+
69
+ def set_shuffle(self, shuffle=True):
70
+ self._enabled = shuffle
71
+ return self
72
+
73
+ def set_seed(self, seed: int):
74
+ self._seed = seed
75
+ return self
76
+
77
+ def __iter__(self) -> Iterator[T_co]:
78
+ if not self._enabled:
79
+ for idx in self.indices:
80
+ yield self.datapipe[idx]
81
+ else:
82
+ while self._shuffled_indices:
83
+ idx = self._shuffled_indices.pop()
84
+ yield self.datapipe[idx]
85
+
86
+ def reset(self) -> None:
87
+ if self._enabled and self._seed is None:
88
+ self._seed = int(torch.empty((), dtype=torch.int64).random_().item())
89
+ self._rng.seed(self._seed)
90
+ self._seed = None
91
+ self._shuffled_indices = self._rng.sample(self.indices, len(self.indices))
92
+
93
+ def __len__(self) -> int:
94
+ return len(self.datapipe)
95
+
96
+ def __getstate__(self):
97
+ state = (
98
+ self.datapipe,
99
+ self.indices,
100
+ self._enabled,
101
+ self._seed,
102
+ self._rng.getstate(),
103
+ self._shuffled_indices,
104
+ self._valid_iterator_id,
105
+ self._number_of_samples_yielded,
106
+ )
107
+ if IterDataPipe.getstate_hook is not None:
108
+ return IterDataPipe.getstate_hook(state)
109
+ return state
110
+
111
+ def __setstate__(self, state):
112
+ (
113
+ self.datapipe,
114
+ self.indices,
115
+ self._enabled,
116
+ self._seed,
117
+ rng_state,
118
+ self._shuffled_indices,
119
+ self._valid_iterator_id,
120
+ self._number_of_samples_yielded,
121
+ ) = state
122
+ self._rng = random.Random()
123
+ self._rng.setstate(rng_state)
124
+
125
+
126
+ MapDataPipe.register_datapipe_as_function("shuffle", ShufflerIterDataPipe)
shared/package-files/28/28fb1334a9a73ef48610a5800571c0f53c8198270ee8b4292a58a857e62f5308/att500 ADDED
Binary file (1.89 kB). View file
 
shared/package-files/28/28fb1334a9a73ef48610a5800571c0f53c8198270ee8b4292a58a857e62f5308/att513 ADDED
Binary file (1.89 kB). View file
 
shared/package-files/74/740228db814b6dd426a989aca58f20a3d2d66d795fbbe022b417249c26ea324e/inspect_pkg.py ADDED
@@ -0,0 +1,359 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (C) 2014 Anaconda, Inc
2
+ # SPDX-License-Identifier: BSD-3-Clause
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ import sys
8
+ from collections import defaultdict
9
+ from itertools import groupby
10
+ from operator import itemgetter
11
+ from os.path import abspath, basename, dirname, exists, join, normcase
12
+ from pathlib import Path
13
+ from tempfile import TemporaryDirectory
14
+ from typing import TYPE_CHECKING
15
+
16
+ from conda.api import Solver
17
+ from conda.core.index import get_index
18
+ from conda.core.prefix_data import PrefixData
19
+ from conda.models.records import PrefixRecord
20
+
21
+ from . import conda_interface
22
+ from .conda_interface import (
23
+ specs_from_args,
24
+ )
25
+ from .os_utils.ldd import (
26
+ get_linkages,
27
+ get_package_obj_files,
28
+ get_untracked_obj_files,
29
+ )
30
+ from .os_utils.liefldd import codefile_class, machofile
31
+ from .os_utils.macho import get_rpaths, human_filetype
32
+ from .utils import (
33
+ comma_join,
34
+ ensure_list,
35
+ get_logger,
36
+ on_linux,
37
+ on_mac,
38
+ on_win,
39
+ package_has_file,
40
+ )
41
+
42
+ if TYPE_CHECKING:
43
+ from typing import Iterable, Literal
44
+
45
+ log = get_logger(__name__)
46
+
47
+
48
+ def which_package(
49
+ path: str | os.PathLike | Path,
50
+ prefix: str | os.PathLike | Path,
51
+ ) -> Iterable[PrefixRecord]:
52
+ """Detect which package(s) a path belongs to.
53
+
54
+ Given the path (of a (presumably) conda installed file) iterate over
55
+ the conda packages the file came from. Usually the iteration yields
56
+ only one package.
57
+ """
58
+ try:
59
+ path = Path(path).relative_to(prefix)
60
+ except ValueError:
61
+ # ValueError: path is already relative to prefix
62
+ pass
63
+ # On Windows, be lenient and allow case-insensitive path comparisons.
64
+ # NOTE: On macOS, although case-insensitive filesystem is default, still
65
+ # require case-sensitive matches (i.e., normcase on macOS is a no-op).
66
+ normcase_path = normcase(path)
67
+
68
+ for prec in PrefixData(str(prefix)).iter_records():
69
+ if normcase_path in (normcase(file) for file in prec["files"]):
70
+ yield prec
71
+
72
+
73
+ def print_object_info(info, key):
74
+ output_string = ""
75
+ for header, group in groupby(sorted(info, key=itemgetter(key)), itemgetter(key)):
76
+ output_string += header + "\n"
77
+ for f_info in sorted(group, key=itemgetter("filename")):
78
+ for data in sorted(f_info):
79
+ if data == key:
80
+ continue
81
+ if f_info[data] is None:
82
+ continue
83
+ output_string += f" {data}: {f_info[data]}\n"
84
+ if len([i for i in f_info if f_info[i] is not None and i != key]) > 1:
85
+ output_string += "\n"
86
+ output_string += "\n"
87
+ return output_string
88
+
89
+
90
+ class _untracked_package:
91
+ def __str__(self):
92
+ return "<untracked>"
93
+
94
+
95
+ untracked_package = _untracked_package()
96
+
97
+
98
+ def check_install(
99
+ packages: Iterable[str],
100
+ subdir: str | None = None,
101
+ channel_urls: Iterable[str] = (),
102
+ ) -> None:
103
+ with TemporaryDirectory() as prefix:
104
+ Solver(
105
+ prefix,
106
+ channel_urls,
107
+ [subdir or conda_interface.subdir],
108
+ specs_from_args(packages),
109
+ ).solve_for_transaction(ignore_pinned=True).print_transaction_summary()
110
+
111
+
112
+ def print_linkages(
113
+ depmap: dict[
114
+ PrefixRecord | Literal["not found" | "system" | "untracked"],
115
+ list[tuple[str, str, str]],
116
+ ],
117
+ show_files: bool = False,
118
+ ) -> str:
119
+ # print system, not found, and untracked last
120
+ sort_order = {
121
+ # PrefixRecord: (0, PrefixRecord.name),
122
+ "system": (1, "system"),
123
+ "not found": (2, "not found"),
124
+ "untracked": (3, "untracked"),
125
+ # str: (4, str),
126
+ }
127
+
128
+ output_string = ""
129
+ for prec, links in sorted(
130
+ depmap.items(),
131
+ key=(
132
+ lambda key: (0, key[0].name)
133
+ if isinstance(key[0], PrefixRecord)
134
+ else sort_order.get(key[0], (4, key[0]))
135
+ ),
136
+ ):
137
+ output_string += "%s:\n" % prec
138
+ if show_files:
139
+ for lib, path, binary in sorted(links):
140
+ output_string += f" {lib} ({path}) from {binary}\n"
141
+ else:
142
+ for lib, path in sorted(set(map(itemgetter(0, 1), links))):
143
+ output_string += f" {lib} ({path})\n"
144
+ output_string += "\n"
145
+ return output_string
146
+
147
+
148
+ def replace_path(binary, path, prefix):
149
+ if on_linux:
150
+ return abspath(path)
151
+ elif on_mac:
152
+ if path == basename(binary):
153
+ return abspath(join(prefix, binary))
154
+ if "@rpath" in path:
155
+ rpaths = get_rpaths(join(prefix, binary))
156
+ if not rpaths:
157
+ return "NO LC_RPATH FOUND"
158
+ else:
159
+ for rpath in rpaths:
160
+ path1 = path.replace("@rpath", rpath)
161
+ path1 = path1.replace("@loader_path", join(prefix, dirname(binary)))
162
+ if exists(abspath(join(prefix, path1))):
163
+ path = path1
164
+ break
165
+ else:
166
+ return "not found"
167
+ path = path.replace("@loader_path", join(prefix, dirname(binary)))
168
+ if path.startswith("/"):
169
+ return abspath(path)
170
+ return "not found"
171
+
172
+
173
+ def test_installable(channel: str = "defaults") -> bool:
174
+ success = True
175
+ for subdir in ["osx-64", "linux-32", "linux-64", "win-32", "win-64"]:
176
+ log.info("######## Testing subdir %s ########", subdir)
177
+ for prec in get_index(channel_urls=[channel], prepend=False, platform=subdir):
178
+ name = prec["name"]
179
+ if name in {"conda", "conda-build"}:
180
+ # conda can only be installed in the root environment
181
+ continue
182
+ elif name.endswith("@"):
183
+ # this is a 'virtual' feature record that conda adds to the index for the solver
184
+ # and should be ignored here
185
+ continue
186
+
187
+ version = prec["version"]
188
+ log.info("Testing %s=%s", name, version)
189
+
190
+ try:
191
+ check_install(
192
+ [f"{name}={version}"],
193
+ channel_urls=[channel],
194
+ prepend=False,
195
+ subdir=subdir,
196
+ )
197
+ except Exception as err:
198
+ success = False
199
+ log.error(
200
+ "[%s/%s::%s=%s] %s",
201
+ channel,
202
+ subdir,
203
+ name,
204
+ version,
205
+ repr(err),
206
+ )
207
+ return success
208
+
209
+
210
+ def _underlined_text(text):
211
+ return str(text) + "\n" + "-" * len(str(text)) + "\n\n"
212
+
213
+
214
+ def inspect_linkages(
215
+ packages: Iterable[str | _untracked_package],
216
+ prefix: str | os.PathLike | Path = sys.prefix,
217
+ untracked: bool = False,
218
+ all_packages: bool = False,
219
+ show_files: bool = False,
220
+ groupby: Literal["package" | "dependency"] = "package",
221
+ sysroot="",
222
+ ):
223
+ if not packages and not untracked and not all_packages:
224
+ sys.exit("At least one package or --untracked or --all must be provided")
225
+ elif on_win:
226
+ sys.exit("Error: conda inspect linkages is only implemented in Linux and OS X")
227
+
228
+ prefix = Path(prefix)
229
+ installed = {prec.name: prec for prec in PrefixData(str(prefix)).iter_records()}
230
+
231
+ if all_packages:
232
+ packages = sorted(installed.keys())
233
+ packages = ensure_list(packages)
234
+ if untracked:
235
+ packages.append(untracked_package)
236
+
237
+ pkgmap: dict[str | _untracked_package, dict[str, list]] = {}
238
+ for name in packages:
239
+ if name == untracked_package:
240
+ obj_files = get_untracked_obj_files(prefix)
241
+ elif name not in installed:
242
+ sys.exit(f"Package {name} is not installed in {prefix}")
243
+ else:
244
+ obj_files = get_package_obj_files(installed[name], prefix)
245
+
246
+ linkages = get_linkages(obj_files, prefix, sysroot)
247
+ pkgmap[name] = depmap = defaultdict(list)
248
+ for binary, paths in linkages.items():
249
+ for lib, path in paths:
250
+ path = (
251
+ replace_path(binary, path, prefix)
252
+ if path not in {"", "not found"}
253
+ else path
254
+ )
255
+ try:
256
+ relative = str(Path(path).relative_to(prefix))
257
+ except ValueError:
258
+ # ValueError: path is not relative to prefix
259
+ relative = None
260
+ if relative:
261
+ precs = list(which_package(relative, prefix))
262
+ if len(precs) > 1:
263
+ get_logger(__name__).warn(
264
+ "Warning: %s comes from multiple packages: %s",
265
+ path,
266
+ comma_join(map(str, precs)),
267
+ )
268
+ elif not precs:
269
+ if exists(path):
270
+ depmap["untracked"].append((lib, relative, binary))
271
+ else:
272
+ depmap["not found"].append((lib, relative, binary))
273
+ for prec in precs:
274
+ depmap[prec].append((lib, relative, binary))
275
+ elif path == "not found":
276
+ depmap["not found"].append((lib, path, binary))
277
+ else:
278
+ depmap["system"].append((lib, path, binary))
279
+
280
+ output_string = ""
281
+ if groupby == "package":
282
+ for pkg in packages:
283
+ output_string += _underlined_text(pkg)
284
+ output_string += print_linkages(pkgmap[pkg], show_files=show_files)
285
+
286
+ elif groupby == "dependency":
287
+ # {pkg: {dep: [files]}} -> {dep: {pkg: [files]}}
288
+ inverted_map = defaultdict(lambda: defaultdict(list))
289
+ for pkg in pkgmap:
290
+ for dep in pkgmap[pkg]:
291
+ if pkgmap[pkg][dep]:
292
+ inverted_map[dep][pkg] = pkgmap[pkg][dep]
293
+
294
+ # print system and not found last
295
+ k = sorted(set(inverted_map.keys()) - {"system", "not found"})
296
+ for dep in k + ["system", "not found"]:
297
+ output_string += _underlined_text(dep)
298
+ output_string += print_linkages(inverted_map[dep], show_files=show_files)
299
+
300
+ else:
301
+ raise ValueError("Unrecognized groupby: %s" % groupby)
302
+ if hasattr(output_string, "decode"):
303
+ output_string = output_string.decode("utf-8")
304
+ return output_string
305
+
306
+
307
+ def inspect_objects(
308
+ packages: Iterable[str],
309
+ prefix: str | os.PathLike | Path = sys.prefix,
310
+ groupby: str = "package",
311
+ ):
312
+ if not on_mac:
313
+ sys.exit("Error: conda inspect objects is only implemented in OS X")
314
+
315
+ prefix = Path(prefix)
316
+ installed = {prec.name: prec for prec in PrefixData(str(prefix)).iter_records()}
317
+
318
+ output_string = ""
319
+ for name in ensure_list(packages):
320
+ if name == untracked_package:
321
+ obj_files = get_untracked_obj_files(prefix)
322
+ elif name not in installed:
323
+ raise ValueError(f"Package {name} is not installed in {prefix}")
324
+ else:
325
+ obj_files = get_package_obj_files(installed[name], prefix)
326
+
327
+ output_string += _underlined_text(name)
328
+
329
+ info = []
330
+ for f in obj_files:
331
+ path = join(prefix, f)
332
+ codefile = codefile_class(path, skip_symlinks=True)
333
+ if codefile == machofile:
334
+ info.append(
335
+ {
336
+ "filetype": human_filetype(path, None),
337
+ "rpath": ":".join(get_rpaths(path)),
338
+ "filename": f,
339
+ }
340
+ )
341
+
342
+ output_string += print_object_info(info, groupby)
343
+ if hasattr(output_string, "decode"):
344
+ output_string = output_string.decode("utf-8")
345
+ return output_string
346
+
347
+
348
+ def get_hash_input(packages):
349
+ hash_inputs = {}
350
+ for pkg in ensure_list(packages):
351
+ pkgname = os.path.basename(pkg)
352
+ hash_inputs[pkgname] = {}
353
+ hash_input = package_has_file(pkg, "info/hash_input.json")
354
+ if hash_input:
355
+ hash_inputs[pkgname]["recipe"] = json.loads(hash_input)
356
+ else:
357
+ hash_inputs[pkgname] = "<no hash_input.json in file>"
358
+
359
+ return hash_inputs
shared/package-files/74/740d6bff1586f7434d0efb47a6bd7527135409cfc4ed0a08120a1498c2efadd7/test_page.py ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #-----------------------------------------------------------------------------
2
+ # Copyright (C) 2010-2011 The IPython Development Team.
3
+ #
4
+ # Distributed under the terms of the BSD License.
5
+ #
6
+ # The full license is in the file COPYING.txt, distributed with this software.
7
+ #-----------------------------------------------------------------------------
8
+ import io
9
+
10
+ # N.B. For the test suite, page.page is overridden (see IPython.testing.globalipapp)
11
+ from IPython.core import page
12
+
13
+ def test_detect_screen_size():
14
+ """Simple smoketest for page._detect_screen_size."""
15
+ try:
16
+ page._detect_screen_size(True, 25)
17
+ except (TypeError, io.UnsupportedOperation):
18
+ # This can happen in the test suite, because stdout may not have a
19
+ # fileno.
20
+ pass
shared/package-files/74/74215f00e53cb2cf1fcbb5fa28d3c206789cdb1c98ce3510b66b0397734ba4c4/_native_batch_norm_legit.h ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from Function.h
4
+
5
+ #include <ATen/Context.h>
6
+ #include <ATen/DeviceGuard.h>
7
+ #include <ATen/TensorUtils.h>
8
+ #include <ATen/TracerMode.h>
9
+ #include <ATen/core/Generator.h>
10
+ #include <ATen/core/Reduction.h>
11
+ #include <ATen/core/Tensor.h>
12
+ #include <c10/core/Scalar.h>
13
+ #include <c10/core/Storage.h>
14
+ #include <c10/core/TensorOptions.h>
15
+ #include <c10/util/Deprecated.h>
16
+ #include <c10/util/Optional.h>
17
+
18
+
19
+
20
+ #include <ATen/ops/_native_batch_norm_legit_ops.h>
21
+
22
+ namespace at {
23
+
24
+
25
+ // aten::_native_batch_norm_legit(Tensor input, Tensor? weight, Tensor? bias, Tensor(a!) running_mean, Tensor(b!) running_var, bool training, float momentum, float eps) -> (Tensor, Tensor, Tensor)
26
+ inline ::std::tuple<at::Tensor,at::Tensor,at::Tensor> _native_batch_norm_legit(const at::Tensor & input, const c10::optional<at::Tensor> & weight, const c10::optional<at::Tensor> & bias, at::Tensor & running_mean, at::Tensor & running_var, bool training, double momentum, double eps) {
27
+ return at::_ops::_native_batch_norm_legit::call(input, weight, bias, running_mean, running_var, training, momentum, eps);
28
+ }
29
+
30
+ // aten::_native_batch_norm_legit.out(Tensor input, Tensor? weight, Tensor? bias, Tensor(a!) running_mean, Tensor(b!) running_var, bool training, float momentum, float eps, *, Tensor(d!) out, Tensor(e!) save_mean, Tensor(f!) save_invstd) -> (Tensor(d!), Tensor(e!), Tensor(f!))
31
+ inline ::std::tuple<at::Tensor &,at::Tensor &,at::Tensor &> _native_batch_norm_legit_out(at::Tensor & out, at::Tensor & save_mean, at::Tensor & save_invstd, const at::Tensor & input, const c10::optional<at::Tensor> & weight, const c10::optional<at::Tensor> & bias, at::Tensor & running_mean, at::Tensor & running_var, bool training, double momentum, double eps) {
32
+ return at::_ops::_native_batch_norm_legit_out::call(input, weight, bias, running_mean, running_var, training, momentum, eps, out, save_mean, save_invstd);
33
+ }
34
+ // aten::_native_batch_norm_legit.out(Tensor input, Tensor? weight, Tensor? bias, Tensor(a!) running_mean, Tensor(b!) running_var, bool training, float momentum, float eps, *, Tensor(d!) out, Tensor(e!) save_mean, Tensor(f!) save_invstd) -> (Tensor(d!), Tensor(e!), Tensor(f!))
35
+ inline ::std::tuple<at::Tensor &,at::Tensor &,at::Tensor &> _native_batch_norm_legit_outf(const at::Tensor & input, const c10::optional<at::Tensor> & weight, const c10::optional<at::Tensor> & bias, at::Tensor & running_mean, at::Tensor & running_var, bool training, double momentum, double eps, at::Tensor & out, at::Tensor & save_mean, at::Tensor & save_invstd) {
36
+ return at::_ops::_native_batch_norm_legit_out::call(input, weight, bias, running_mean, running_var, training, momentum, eps, out, save_mean, save_invstd);
37
+ }
38
+
39
+ // aten::_native_batch_norm_legit.no_stats(Tensor input, Tensor? weight, Tensor? bias, bool training, float momentum, float eps) -> (Tensor, Tensor, Tensor)
40
+ inline ::std::tuple<at::Tensor,at::Tensor,at::Tensor> _native_batch_norm_legit(const at::Tensor & input, const c10::optional<at::Tensor> & weight, const c10::optional<at::Tensor> & bias, bool training, double momentum, double eps) {
41
+ return at::_ops::_native_batch_norm_legit_no_stats::call(input, weight, bias, training, momentum, eps);
42
+ }
43
+
44
+ // aten::_native_batch_norm_legit.no_stats_out(Tensor input, Tensor? weight, Tensor? bias, bool training, float momentum, float eps, *, Tensor(a!) out, Tensor(b!) save_mean, Tensor(c!) save_invstd) -> (Tensor(a!), Tensor(b!), Tensor(c!))
45
+ inline ::std::tuple<at::Tensor &,at::Tensor &,at::Tensor &> _native_batch_norm_legit_out(at::Tensor & out, at::Tensor & save_mean, at::Tensor & save_invstd, const at::Tensor & input, const c10::optional<at::Tensor> & weight, const c10::optional<at::Tensor> & bias, bool training, double momentum, double eps) {
46
+ return at::_ops::_native_batch_norm_legit_no_stats_out::call(input, weight, bias, training, momentum, eps, out, save_mean, save_invstd);
47
+ }
48
+ // aten::_native_batch_norm_legit.no_stats_out(Tensor input, Tensor? weight, Tensor? bias, bool training, float momentum, float eps, *, Tensor(a!) out, Tensor(b!) save_mean, Tensor(c!) save_invstd) -> (Tensor(a!), Tensor(b!), Tensor(c!))
49
+ inline ::std::tuple<at::Tensor &,at::Tensor &,at::Tensor &> _native_batch_norm_legit_outf(const at::Tensor & input, const c10::optional<at::Tensor> & weight, const c10::optional<at::Tensor> & bias, bool training, double momentum, double eps, at::Tensor & out, at::Tensor & save_mean, at::Tensor & save_invstd) {
50
+ return at::_ops::_native_batch_norm_legit_no_stats_out::call(input, weight, bias, training, momentum, eps, out, save_mean, save_invstd);
51
+ }
52
+
53
+ // aten::_native_batch_norm_legit_functional(Tensor input, Tensor? weight, Tensor? bias, Tensor running_mean, Tensor running_var, bool training, float momentum, float eps) -> (Tensor, Tensor, Tensor, Tensor running_mean_out, Tensor running_var_out)
54
+ inline ::std::tuple<at::Tensor,at::Tensor,at::Tensor,at::Tensor,at::Tensor> _native_batch_norm_legit_functional(const at::Tensor & input, const c10::optional<at::Tensor> & weight, const c10::optional<at::Tensor> & bias, const at::Tensor & running_mean, const at::Tensor & running_var, bool training, double momentum, double eps) {
55
+ return at::_ops::_native_batch_norm_legit_functional::call(input, weight, bias, running_mean, running_var, training, momentum, eps);
56
+ }
57
+
58
+ }
shared/package-files/74/7435b58c6e505b4ad84566f3966050f0f4f6bfd65d5a0149d0844786f0494324/__init__.pyi ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .general import (
2
+ ArrayAgg as ArrayAgg,
3
+ BitAnd as BitAnd,
4
+ BitOr as BitOr,
5
+ BoolAnd as BoolAnd,
6
+ BoolOr as BoolOr,
7
+ JSONBAgg as JSONBAgg,
8
+ StringAgg as StringAgg,
9
+ )
10
+
11
+ from .statistics import (
12
+ Corr as Corr,
13
+ CovarPop as CovarPop,
14
+ RegrAvgX as RegrAvgX,
15
+ RegrAvgY as RegrAvgY,
16
+ RegrCount as RegrCount,
17
+ RegrIntercept as RegrIntercept,
18
+ RegrR2 as RegrR2,
19
+ RegrSlope as RegrSlope,
20
+ RegrSXX as RegrSXX,
21
+ RegrSXY as RegrSXY,
22
+ RegrSYY as RegrSYY,
23
+ StatAggregate as StatAggregate,
24
+ )
shared/package-files/74/7435f850d700fce2f0a7c1821c704b5717494b767a62c815be2fbe57cc610074/special_erfinv.h ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from Function.h
4
+
5
+ #include <ATen/Context.h>
6
+ #include <ATen/DeviceGuard.h>
7
+ #include <ATen/TensorUtils.h>
8
+ #include <ATen/TracerMode.h>
9
+ #include <ATen/core/Generator.h>
10
+ #include <ATen/core/Reduction.h>
11
+ #include <ATen/core/Tensor.h>
12
+ #include <c10/core/Scalar.h>
13
+ #include <c10/core/Storage.h>
14
+ #include <c10/core/TensorOptions.h>
15
+ #include <c10/util/Deprecated.h>
16
+ #include <c10/util/Optional.h>
17
+
18
+
19
+
20
+ #include <ATen/ops/special_erfinv_ops.h>
21
+
22
+ namespace at {
23
+
24
+
25
+ // aten::special_erfinv(Tensor self) -> Tensor
26
+ inline at::Tensor special_erfinv(const at::Tensor & self) {
27
+ return at::_ops::special_erfinv::call(self);
28
+ }
29
+
30
+ // aten::special_erfinv.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
31
+ inline at::Tensor & special_erfinv_out(at::Tensor & out, const at::Tensor & self) {
32
+ return at::_ops::special_erfinv_out::call(self, out);
33
+ }
34
+ // aten::special_erfinv.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
35
+ inline at::Tensor & special_erfinv_outf(const at::Tensor & self, at::Tensor & out) {
36
+ return at::_ops::special_erfinv_out::call(self, out);
37
+ }
38
+
39
+ }
shared/package-files/74/743857b19d6f384a0e30a0f691b06b04fe8e33a419c4596ae57c6ddba8740e08/reciprocal_cpu_dispatch.h ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ // @generated by torchgen/gen.py from DispatchKeyFunction.h
3
+
4
+ // NB: The implementing C++ file is RegisterDispatchKey.cpp
5
+
6
+ // The only #includes we need are for custom classes that have defaults in the C++ API
7
+ #include <c10/core/MemoryFormat.h>
8
+ #include <c10/core/Scalar.h>
9
+ #include <ATen/core/Reduction.h>
10
+
11
+ // Forward declarations of any types needed in the operator signatures.
12
+ // We can't directly include these classes because it will cause circular include dependencies.
13
+ // This file is included by TensorBody.h, which defines the Tensor class.
14
+ #include <ATen/core/ATen_fwd.h>
15
+
16
+ namespace at {
17
+
18
+ namespace cpu {
19
+
20
+ TORCH_API at::Tensor reciprocal(const at::Tensor & self);
21
+ TORCH_API at::Tensor & reciprocal_out(at::Tensor & out, const at::Tensor & self);
22
+ TORCH_API at::Tensor & reciprocal_outf(const at::Tensor & self, at::Tensor & out);
23
+ TORCH_API at::Tensor & reciprocal_(at::Tensor & self);
24
+
25
+ } // namespace cpu
26
+ } // namespace at
shared/package-files/74/743d6cd7703766653ad5d97023d063c0bba212eb748ef0d54b76af8b863afc20/test_numba.py ADDED
@@ -0,0 +1,129 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import pytest
3
+
4
+ from pandas.compat import is_platform_arm
5
+ import pandas.util._test_decorators as td
6
+
7
+ import pandas as pd
8
+ from pandas import (
9
+ DataFrame,
10
+ Index,
11
+ )
12
+ import pandas._testing as tm
13
+ from pandas.util.version import Version
14
+
15
+ pytestmark = [td.skip_if_no("numba"), pytest.mark.single_cpu, pytest.mark.skipif()]
16
+
17
+ numba = pytest.importorskip("numba")
18
+ pytestmark.append(
19
+ pytest.mark.skipif(
20
+ Version(numba.__version__) == Version("0.61") and is_platform_arm(),
21
+ reason=f"Segfaults on ARM platforms with numba {numba.__version__}",
22
+ )
23
+ )
24
+
25
+
26
+ @pytest.fixture(params=[0, 1])
27
+ def apply_axis(request):
28
+ return request.param
29
+
30
+
31
+ def test_numba_vs_python_noop(float_frame, apply_axis):
32
+ func = lambda x: x
33
+ result = float_frame.apply(func, engine="numba", axis=apply_axis)
34
+ expected = float_frame.apply(func, engine="python", axis=apply_axis)
35
+ tm.assert_frame_equal(result, expected)
36
+
37
+
38
+ def test_numba_vs_python_string_index():
39
+ # GH#56189
40
+ df = DataFrame(
41
+ 1,
42
+ index=Index(["a", "b"], dtype=pd.StringDtype(na_value=np.nan)),
43
+ columns=Index(["x", "y"], dtype=pd.StringDtype(na_value=np.nan)),
44
+ )
45
+ func = lambda x: x
46
+ result = df.apply(func, engine="numba", axis=0)
47
+ expected = df.apply(func, engine="python", axis=0)
48
+ tm.assert_frame_equal(
49
+ result, expected, check_column_type=False, check_index_type=False
50
+ )
51
+
52
+
53
+ def test_numba_vs_python_indexing():
54
+ frame = DataFrame(
55
+ {"a": [1, 2, 3], "b": [4, 5, 6], "c": [7.0, 8.0, 9.0]},
56
+ index=Index(["A", "B", "C"]),
57
+ )
58
+ row_func = lambda x: x["c"]
59
+ result = frame.apply(row_func, engine="numba", axis=1)
60
+ expected = frame.apply(row_func, engine="python", axis=1)
61
+ tm.assert_series_equal(result, expected)
62
+
63
+ col_func = lambda x: x["A"]
64
+ result = frame.apply(col_func, engine="numba", axis=0)
65
+ expected = frame.apply(col_func, engine="python", axis=0)
66
+ tm.assert_series_equal(result, expected)
67
+
68
+
69
+ @pytest.mark.parametrize(
70
+ "reduction",
71
+ [lambda x: x.mean(), lambda x: x.min(), lambda x: x.max(), lambda x: x.sum()],
72
+ )
73
+ def test_numba_vs_python_reductions(reduction, apply_axis):
74
+ df = DataFrame(np.ones((4, 4), dtype=np.float64))
75
+ result = df.apply(reduction, engine="numba", axis=apply_axis)
76
+ expected = df.apply(reduction, engine="python", axis=apply_axis)
77
+ tm.assert_series_equal(result, expected)
78
+
79
+
80
+ @pytest.mark.parametrize("colnames", [[1, 2, 3], [1.0, 2.0, 3.0]])
81
+ def test_numba_numeric_colnames(colnames):
82
+ # Check that numeric column names lower properly and can be indxed on
83
+ df = DataFrame(
84
+ np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype=np.int64), columns=colnames
85
+ )
86
+ first_col = colnames[0]
87
+ f = lambda x: x[first_col] # Get the first column
88
+ result = df.apply(f, engine="numba", axis=1)
89
+ expected = df.apply(f, engine="python", axis=1)
90
+ tm.assert_series_equal(result, expected)
91
+
92
+
93
+ def test_numba_parallel_unsupported(float_frame):
94
+ f = lambda x: x
95
+ with pytest.raises(
96
+ NotImplementedError,
97
+ match="Parallel apply is not supported when raw=False and engine='numba'",
98
+ ):
99
+ float_frame.apply(f, engine="numba", engine_kwargs={"parallel": True})
100
+
101
+
102
+ def test_numba_nonunique_unsupported(apply_axis):
103
+ f = lambda x: x
104
+ df = DataFrame({"a": [1, 2]}, index=Index(["a", "a"]))
105
+ with pytest.raises(
106
+ NotImplementedError,
107
+ match="The index/columns must be unique when raw=False and engine='numba'",
108
+ ):
109
+ df.apply(f, engine="numba", axis=apply_axis)
110
+
111
+
112
+ def test_numba_unsupported_dtypes(apply_axis):
113
+ pytest.importorskip("pyarrow")
114
+ f = lambda x: x
115
+ df = DataFrame({"a": [1, 2], "b": ["a", "b"], "c": [4, 5]})
116
+ df["c"] = df["c"].astype("double[pyarrow]")
117
+
118
+ with pytest.raises(
119
+ ValueError,
120
+ match="Column b must have a numeric dtype. Found 'object|str' instead",
121
+ ):
122
+ df.apply(f, engine="numba", axis=apply_axis)
123
+
124
+ with pytest.raises(
125
+ ValueError,
126
+ match="Column c is backed by an extension array, "
127
+ "which is not supported by the numba engine.",
128
+ ):
129
+ df["c"].to_frame().apply(f, engine="numba", axis=apply_axis)
shared/package-files/74/7445d870e3d174c32214e605bd833ec8d4484aeaf70539ba521e7d9ba871c799/darwin-160x64-m ADDED
Binary file (987 Bytes). View file
 
shared/package-files/74/7445d870e3d174c32214e605bd833ec8d4484aeaf70539ba521e7d9ba871c799/xnuppc-160x64-m ADDED
Binary file (987 Bytes). View file
 
shared/package-files/74/7449d4c5166158cf346487d0dfd70bcf3251376c76576582fadddcb8560c5443/dependencies.py ADDED
@@ -0,0 +1,818 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # pandas / Polars / etc. : if a user passes a dataframe from one of these
2
+ # libraries, it means they must already have imported the given module.
3
+ # So, we can just check sys.modules.
4
+ from __future__ import annotations
5
+
6
+ import sys
7
+ from typing import TYPE_CHECKING, Any
8
+
9
+ from narwhals._exceptions import issue_warning
10
+
11
+ if TYPE_CHECKING:
12
+ from typing import TypeGuard
13
+
14
+ import cudf
15
+ import dask.dataframe as dd
16
+ import duckdb
17
+ import ibis
18
+ import modin.pandas as mpd
19
+ import pandas as pd
20
+ import polars as pl
21
+ import pyarrow as pa
22
+ import pyspark.sql as pyspark_sql
23
+ from pyspark.sql.connect.dataframe import DataFrame as PySparkConnectDataFrame
24
+ from typing_extensions import TypeIs
25
+
26
+ from narwhals._spark_like.dataframe import SQLFrameDataFrame
27
+ from narwhals.dataframe import DataFrame, LazyFrame
28
+ from narwhals.series import Series
29
+ from narwhals.typing import (
30
+ IntoDataFrameT,
31
+ IntoLazyFrameT,
32
+ IntoSeriesT,
33
+ PandasLikeDType,
34
+ _1DArray,
35
+ _1DArrayInt,
36
+ _2DArray,
37
+ _NDArray,
38
+ _NumpyScalar,
39
+ _ShapeT,
40
+ )
41
+
42
+
43
+ # We silently allow these but - given that they claim
44
+ # to be drop-in replacements for pandas - testing is
45
+ # their responsibility.
46
+ IMPORT_HOOKS = frozenset(["fireducks"])
47
+
48
+
49
+ def get_polars() -> Any:
50
+ """Get Polars module (if already imported - else return None)."""
51
+ return sys.modules.get("polars", None)
52
+
53
+
54
+ def get_pandas() -> Any:
55
+ """Get pandas module (if already imported - else return None)."""
56
+ return sys.modules.get("pandas", None)
57
+
58
+
59
+ def get_modin() -> Any: # pragma: no cover
60
+ """Get modin.pandas module (if already imported - else return None)."""
61
+ return sys.modules.get("modin.pandas", None)
62
+
63
+
64
+ def get_cudf() -> Any:
65
+ """Get cudf module (if already imported - else return None)."""
66
+ return sys.modules.get("cudf", None)
67
+
68
+
69
+ def get_cupy() -> Any:
70
+ """Get cupy module (if already imported - else return None)."""
71
+ return sys.modules.get("cupy", None)
72
+
73
+
74
+ def get_pyarrow() -> Any: # pragma: no cover
75
+ """Get pyarrow module (if already imported - else return None)."""
76
+ return sys.modules.get("pyarrow", None)
77
+
78
+
79
+ def get_numpy() -> Any:
80
+ """Get numpy module (if already imported - else return None)."""
81
+ return sys.modules.get("numpy", None)
82
+
83
+
84
+ def get_dask() -> Any: # pragma: no cover
85
+ """Get dask (if already imported - else return None)."""
86
+ return sys.modules.get("dask", None)
87
+
88
+
89
+ def get_dask_dataframe() -> Any:
90
+ """Get dask.dataframe module (if already imported - else return None)."""
91
+ return sys.modules.get("dask.dataframe", None)
92
+
93
+
94
+ def get_duckdb() -> Any:
95
+ """Get duckdb module (if already imported - else return None)."""
96
+ return sys.modules.get("duckdb", None)
97
+
98
+
99
+ def get_ibis() -> Any:
100
+ """Get ibis module (if already imported - else return None)."""
101
+ return sys.modules.get("ibis", None)
102
+
103
+
104
+ def get_dask_expr() -> Any: # pragma: no cover
105
+ """Get dask_expr module (if already imported - else return None)."""
106
+ if (dd := get_dask_dataframe()) is not None and hasattr(dd, "dask_expr"):
107
+ return dd.dask_expr
108
+ return sys.modules.get("dask_expr", None)
109
+
110
+
111
+ def get_pyspark() -> Any: # pragma: no cover
112
+ """Get pyspark module (if already imported - else return None)."""
113
+ return sys.modules.get("pyspark", None)
114
+
115
+
116
+ def get_pyspark_sql() -> Any:
117
+ """Get pyspark.sql module (if already imported - else return None)."""
118
+ return sys.modules.get("pyspark.sql", None)
119
+
120
+
121
+ def get_pyspark_connect() -> Any:
122
+ """Get pyspark.sql.connect module (if already imported - else return None)."""
123
+ return sys.modules.get("pyspark.sql.connect", None)
124
+
125
+
126
+ def get_sqlframe() -> Any:
127
+ """Get sqlframe module (if already imported - else return None)."""
128
+ return sys.modules.get("sqlframe", None)
129
+
130
+
131
+ def _warn_if_narwhals_df_or_lf(frame: Any, /) -> None:
132
+ if is_narwhals_dataframe(frame) or is_narwhals_lazyframe(frame):
133
+ from narwhals._utils import qualified_type_name
134
+
135
+ caller = sys._getframe(1).f_code.co_name
136
+ msg = (
137
+ f"You passed a `{qualified_type_name(frame)}` to `{caller}`.\n\n"
138
+ f"Hint: Instead of e.g. `{caller}(frame)`, "
139
+ f"did you mean `{caller}(frame.to_native())`?"
140
+ )
141
+ issue_warning(msg, UserWarning)
142
+
143
+
144
+ def _warn_if_narwhals_series(ser: Any, /) -> None:
145
+ if is_narwhals_series(ser):
146
+ from narwhals._utils import qualified_type_name
147
+
148
+ caller = sys._getframe(1).f_code.co_name
149
+ msg = (
150
+ f"You passed a `{qualified_type_name(ser)}` to `{caller}`.\n\n"
151
+ f"Hint: Instead of e.g. `{caller}(ser)`, "
152
+ f"did you mean `{caller}(ser.to_native())`?"
153
+ )
154
+ issue_warning(msg, UserWarning)
155
+
156
+
157
+ def _is_pandas_dataframe(df: Any) -> TypeIs[pd.DataFrame]:
158
+ """Check whether `df` is a pandas DataFrame without importing pandas."""
159
+ return ((pd := get_pandas()) is not None and isinstance(df, pd.DataFrame)) or any(
160
+ (mod := sys.modules.get(module_name, None)) is not None
161
+ and isinstance(df, mod.pandas.DataFrame)
162
+ for module_name in IMPORT_HOOKS
163
+ )
164
+
165
+
166
+ def is_pandas_dataframe(df: Any) -> TypeIs[pd.DataFrame]:
167
+ """Check whether `df` is a pandas DataFrame without importing pandas.
168
+
169
+ Warning:
170
+ This method cannot be called on a Narwhals DataFrame/LazyFrame.
171
+ """
172
+ _warn_if_narwhals_df_or_lf(df)
173
+ return _is_pandas_dataframe(df)
174
+
175
+
176
+ def _is_pandas_series(ser: Any) -> TypeIs[pd.Series[Any]]:
177
+ """Check whether `ser` is a pandas Series without importing pandas."""
178
+ return ((pd := get_pandas()) is not None and isinstance(ser, pd.Series)) or any(
179
+ (mod := sys.modules.get(module_name, None)) is not None
180
+ and isinstance(ser, mod.pandas.Series)
181
+ for module_name in IMPORT_HOOKS
182
+ )
183
+
184
+
185
+ def is_pandas_series(ser: Any) -> TypeIs[pd.Series[Any]]:
186
+ """Check whether `ser` is a pandas Series without importing pandas.
187
+
188
+ Warning:
189
+ This method cannot be called on Narwhals Series.
190
+ """
191
+ _warn_if_narwhals_series(ser)
192
+ return _is_pandas_series(ser)
193
+
194
+
195
+ def is_pandas_index(index: Any) -> TypeIs[pd.Index[Any]]:
196
+ """Check whether `index` is a pandas Index without importing pandas."""
197
+ return ((pd := get_pandas()) is not None and isinstance(index, pd.Index)) or any(
198
+ (mod := sys.modules.get(module_name, None)) is not None
199
+ and isinstance(index, mod.pandas.Index)
200
+ for module_name in IMPORT_HOOKS
201
+ )
202
+
203
+
204
+ def _is_modin_dataframe(df: Any) -> TypeIs[mpd.DataFrame]:
205
+ """Check whether `df` is a modin DataFrame without importing modin."""
206
+ return (mpd := get_modin()) is not None and isinstance(df, mpd.DataFrame)
207
+
208
+
209
+ def is_modin_dataframe(df: Any) -> TypeIs[mpd.DataFrame]:
210
+ """Check whether `df` is a modin DataFrame without importing modin.
211
+
212
+ Warning:
213
+ This method cannot be called on a Narwhals DataFrame/LazyFrame.
214
+ """
215
+ _warn_if_narwhals_df_or_lf(df)
216
+ return _is_modin_dataframe(df)
217
+
218
+
219
+ def _is_modin_series(ser: Any) -> TypeIs[mpd.Series]:
220
+ """Check whether `ser` is a modin Series without importing modin."""
221
+ return (mpd := get_modin()) is not None and isinstance(ser, mpd.Series)
222
+
223
+
224
+ def is_modin_series(ser: Any) -> TypeIs[mpd.Series]:
225
+ """Check whether `ser` is a modin Series without importing modin.
226
+
227
+ Warning:
228
+ This method cannot be called on Narwhals Series.
229
+ """
230
+ _warn_if_narwhals_series(ser)
231
+ return _is_modin_series(ser)
232
+
233
+
234
+ def is_modin_index(index: Any) -> TypeIs[mpd.Index[Any]]: # pragma: no cover
235
+ """Check whether `index` is a modin Index without importing modin."""
236
+ return (mpd := get_modin()) is not None and isinstance(index, mpd.Index)
237
+
238
+
239
+ def _is_cudf_dataframe(df: Any) -> TypeIs[cudf.DataFrame]:
240
+ """Check whether `df` is a cudf DataFrame without importing cudf."""
241
+ return (cudf := get_cudf()) is not None and isinstance(df, cudf.DataFrame)
242
+
243
+
244
+ def is_cudf_dataframe(df: Any) -> TypeIs[cudf.DataFrame]:
245
+ """Check whether `df` is a cudf DataFrame without importing cudf.
246
+
247
+ Warning:
248
+ This method cannot be called on a Narwhals DataFrame/LazyFrame.
249
+ """
250
+ _warn_if_narwhals_df_or_lf(df)
251
+ return _is_cudf_dataframe(df)
252
+
253
+
254
+ def _is_cudf_series(ser: Any) -> TypeIs[cudf.Series[Any]]:
255
+ """Check whether `ser` is a cudf Series without importing cudf."""
256
+ return (cudf := get_cudf()) is not None and isinstance(ser, cudf.Series)
257
+
258
+
259
+ def is_cudf_series(ser: Any) -> TypeIs[cudf.Series[Any]]:
260
+ """Check whether `ser` is a cudf Series without importing cudf.
261
+
262
+ Warning:
263
+ This method cannot be called on Narwhals Series.
264
+ """
265
+ _warn_if_narwhals_series(ser)
266
+ return _is_cudf_series(ser)
267
+
268
+
269
+ def is_cudf_index(index: Any) -> TypeIs[cudf.Index]:
270
+ """Check whether `index` is a cudf Index without importing cudf."""
271
+ return (cudf := get_cudf()) is not None and isinstance(
272
+ index, cudf.Index
273
+ ) # pragma: no cover
274
+
275
+
276
+ def is_cupy_scalar(obj: Any) -> bool:
277
+ return (
278
+ (cupy := get_cupy()) is not None
279
+ and isinstance(obj, cupy.ndarray)
280
+ and obj.size == 1
281
+ ) # pragma: no cover
282
+
283
+
284
+ def _is_dask_dataframe(df: Any) -> TypeIs[dd.DataFrame]:
285
+ """Check whether `df` is a Dask DataFrame without importing Dask."""
286
+ return (dd := get_dask_dataframe()) is not None and isinstance(df, dd.DataFrame)
287
+
288
+
289
+ def is_dask_dataframe(df: Any) -> TypeIs[dd.DataFrame]:
290
+ """Check whether `df` is a Dask DataFrame without importing Dask.
291
+
292
+ Warning:
293
+ This method cannot be called on a Narwhals DataFrame/LazyFrame.
294
+ """
295
+ _warn_if_narwhals_df_or_lf(df)
296
+ return _is_dask_dataframe(df)
297
+
298
+
299
+ def _is_duckdb_relation(df: Any) -> TypeIs[duckdb.DuckDBPyRelation]:
300
+ """Check whether `df` is a DuckDB Relation without importing DuckDB."""
301
+ return (duckdb := get_duckdb()) is not None and isinstance(
302
+ df, duckdb.DuckDBPyRelation
303
+ )
304
+
305
+
306
+ def is_duckdb_relation(df: Any) -> TypeIs[duckdb.DuckDBPyRelation]:
307
+ """Check whether `df` is a DuckDB Relation without importing DuckDB.
308
+
309
+ Warning:
310
+ This method cannot be called on Narwhals DataFrame/LazyFrame.
311
+ """
312
+ _warn_if_narwhals_df_or_lf(df)
313
+ return _is_duckdb_relation(df)
314
+
315
+
316
+ def _is_ibis_table(df: Any) -> TypeIs[ibis.Table]:
317
+ """Check whether `df` is a Ibis Table without importing Ibis."""
318
+ return (ibis := get_ibis()) is not None and isinstance(df, ibis.expr.types.Table)
319
+
320
+
321
+ def is_ibis_table(df: Any) -> TypeIs[ibis.Table]:
322
+ """Check whether `df` is a Ibis Table without importing Ibis.
323
+
324
+ Warning:
325
+ This method cannot be called on Narwhals DataFrame/LazyFrame.
326
+ """
327
+ _warn_if_narwhals_df_or_lf(df)
328
+ return _is_ibis_table(df)
329
+
330
+
331
+ def _is_polars_dataframe(df: Any) -> TypeIs[pl.DataFrame]:
332
+ """Check whether `df` is a Polars DataFrame without importing Polars."""
333
+ return (pl := get_polars()) is not None and isinstance(df, pl.DataFrame)
334
+
335
+
336
+ def is_polars_dataframe(df: Any) -> TypeIs[pl.DataFrame]:
337
+ """Check whether `df` is a Polars DataFrame without importing Polars.
338
+
339
+ Warning:
340
+ This method cannot be called on a Narwhals DataFrame/LazyFrame.
341
+ """
342
+ _warn_if_narwhals_df_or_lf(df)
343
+ return _is_polars_dataframe(df)
344
+
345
+
346
+ def _is_polars_lazyframe(df: Any) -> TypeIs[pl.LazyFrame]:
347
+ """Check whether `df` is a Polars LazyFrame without importing Polars."""
348
+ return (pl := get_polars()) is not None and isinstance(df, pl.LazyFrame)
349
+
350
+
351
+ def is_polars_lazyframe(df: Any) -> TypeIs[pl.LazyFrame]:
352
+ """Check whether `df` is a Polars LazyFrame without importing Polars.
353
+
354
+ Warning:
355
+ This method cannot be called on Narwhals DataFrame/LazyFrame.
356
+ """
357
+ _warn_if_narwhals_df_or_lf(df)
358
+ return _is_polars_lazyframe(df)
359
+
360
+
361
+ def _is_polars_series(ser: Any) -> TypeIs[pl.Series]:
362
+ """Check whether `ser` is a Polars Series without importing Polars."""
363
+ return (pl := get_polars()) is not None and isinstance(ser, pl.Series)
364
+
365
+
366
+ def is_polars_series(ser: Any) -> TypeIs[pl.Series]:
367
+ """Check whether `ser` is a Polars Series without importing Polars.
368
+
369
+ Warning:
370
+ This method cannot be called on Narwhals Series.
371
+ """
372
+ _warn_if_narwhals_series(ser)
373
+ return _is_polars_series(ser)
374
+
375
+
376
+ def is_polars_schema(obj: Any) -> TypeIs[pl.Schema]:
377
+ return (
378
+ bool(pl := get_polars()) and hasattr(pl, "Schema") and isinstance(obj, pl.Schema)
379
+ )
380
+
381
+
382
+ # NOTE: For `pl.Schema` only instantiated dtypes are expected
383
+ def is_polars_data_type(obj: Any) -> TypeIs[pl.DataType]:
384
+ return bool(pl := get_polars()) and isinstance(obj, pl.DataType)
385
+
386
+
387
+ def _is_pyarrow_chunked_array(ser: Any) -> TypeIs[pa.ChunkedArray[Any]]:
388
+ """Check whether `ser` is a PyArrow ChunkedArray without importing PyArrow."""
389
+ return (pa := get_pyarrow()) is not None and isinstance(ser, pa.ChunkedArray)
390
+
391
+
392
+ def is_pyarrow_chunked_array(ser: Any) -> TypeIs[pa.ChunkedArray[Any]]:
393
+ """Check whether `ser` is a PyArrow ChunkedArray without importing PyArrow.
394
+
395
+ Warning:
396
+ This method cannot be called on Narwhals Series.
397
+ """
398
+ _warn_if_narwhals_series(ser)
399
+ return _is_pyarrow_chunked_array(ser)
400
+
401
+
402
+ def _is_pyarrow_table(df: Any) -> TypeIs[pa.Table]:
403
+ """Check whether `df` is a PyArrow Table without importing PyArrow."""
404
+ return (pa := get_pyarrow()) is not None and isinstance(df, pa.Table)
405
+
406
+
407
+ def is_pyarrow_table(df: Any) -> TypeIs[pa.Table]:
408
+ """Check whether `df` is a PyArrow Table without importing PyArrow.
409
+
410
+ Warning:
411
+ This method cannot be called on a Narwhals DataFrame/LazyFrame.
412
+ """
413
+ _warn_if_narwhals_df_or_lf(df)
414
+ return _is_pyarrow_table(df)
415
+
416
+
417
+ def is_pyarrow_scalar(obj: Any) -> TypeIs[pa.Scalar[Any]]:
418
+ return (pa := get_pyarrow()) is not None and isinstance(obj, pa.Scalar)
419
+
420
+
421
+ def is_pyarrow_schema(obj: Any) -> TypeIs[pa.Schema]:
422
+ return bool(pa := get_pyarrow()) and isinstance(obj, pa.Schema)
423
+
424
+
425
+ def is_pyarrow_data_type(obj: Any) -> TypeIs[pa.DataType]:
426
+ return bool(pa := get_pyarrow()) and isinstance(obj, pa.DataType)
427
+
428
+
429
+ def _is_pyspark_dataframe(df: Any) -> TypeIs[pyspark_sql.DataFrame]:
430
+ """Check whether `df` is a PySpark DataFrame without importing PySpark."""
431
+ return bool(
432
+ (pyspark_sql := get_pyspark_sql()) is not None
433
+ and isinstance(df, pyspark_sql.DataFrame)
434
+ )
435
+
436
+
437
+ def is_pyspark_dataframe(df: Any) -> TypeIs[pyspark_sql.DataFrame]:
438
+ """Check whether `df` is a PySpark DataFrame without importing PySpark.
439
+
440
+ Warning:
441
+ This method cannot be called on a Narwhals DataFrame/LazyFrame.
442
+ """
443
+ _warn_if_narwhals_df_or_lf(df)
444
+ return _is_pyspark_dataframe(df)
445
+
446
+
447
+ def _is_pyspark_connect_dataframe(df: Any) -> TypeIs[PySparkConnectDataFrame]:
448
+ """Check whether `df` is a PySpark Connect DataFrame without importing PySpark."""
449
+ if get_pyspark_connect() is not None: # pragma: no cover
450
+ try:
451
+ from pyspark.sql.connect.dataframe import DataFrame
452
+ except ImportError:
453
+ return False
454
+ return isinstance(df, DataFrame)
455
+ return False
456
+
457
+
458
+ def is_pyspark_connect_dataframe(df: Any) -> TypeIs[PySparkConnectDataFrame]:
459
+ """Check whether `df` is a PySpark Connect DataFrame without importing PySpark.
460
+
461
+ Warning:
462
+ This method cannot be called on a Narwhals DataFrame/LazyFrame.
463
+ """
464
+ _warn_if_narwhals_df_or_lf(df)
465
+ return _is_pyspark_connect_dataframe(df)
466
+
467
+
468
+ def _is_sqlframe_dataframe(df: Any) -> TypeIs[SQLFrameDataFrame]:
469
+ """Check whether `df` is a SQLFrame DataFrame without importing SQLFrame."""
470
+ if get_sqlframe() is not None:
471
+ from sqlframe.base.dataframe import BaseDataFrame
472
+
473
+ return isinstance(df, BaseDataFrame)
474
+ return False # pragma: no cover
475
+
476
+
477
+ def is_sqlframe_dataframe(df: Any) -> TypeIs[SQLFrameDataFrame]:
478
+ """Check whether `df` is a SQLFrame DataFrame without importing SQLFrame.
479
+
480
+ Warning:
481
+ This method cannot be called on a Narwhals DataFrame/LazyFrame.
482
+ """
483
+ _warn_if_narwhals_df_or_lf(df)
484
+ return _is_sqlframe_dataframe(df)
485
+
486
+
487
+ def is_numpy_array(arr: Any | _NDArray[_ShapeT]) -> TypeIs[_NDArray[_ShapeT]]:
488
+ """Check whether `arr` is a NumPy Array without importing NumPy."""
489
+ return (np := get_numpy()) is not None and isinstance(arr, np.ndarray)
490
+
491
+
492
+ def is_numpy_array_1d(arr: Any) -> TypeIs[_1DArray]:
493
+ """Check whether `arr` is a 1D NumPy Array without importing NumPy."""
494
+ return is_numpy_array(arr) and arr.ndim == 1
495
+
496
+
497
+ def is_numpy_array_1d_int(arr: Any) -> TypeIs[_1DArrayInt]:
498
+ return (
499
+ (np := get_numpy())
500
+ and is_numpy_array_1d(arr)
501
+ and np.issubdtype(arr.dtype, np.integer)
502
+ )
503
+
504
+
505
+ def is_numpy_array_1d_bool(arr: Any) -> TypeIs[_1DArrayInt]:
506
+ return (
507
+ (np := get_numpy())
508
+ and is_numpy_array_1d(arr)
509
+ and np.issubdtype(arr.dtype, np.bool_)
510
+ )
511
+
512
+
513
+ def is_numpy_array_2d(arr: Any) -> TypeIs[_2DArray]:
514
+ """Check whether `arr` is a 2D NumPy Array without importing NumPy."""
515
+ return is_numpy_array(arr) and arr.ndim == 2
516
+
517
+
518
+ def is_numpy_scalar(scalar: Any) -> TypeGuard[_NumpyScalar]:
519
+ """Check whether `scalar` is a NumPy Scalar without importing NumPy."""
520
+ # NOTE: Needs to stay as `TypeGuard`
521
+ # - Used in `Series.__getitem__`, but not annotated
522
+ # - `TypeGuard` is *hiding* that the check introduces an intersection
523
+ return (np := get_numpy()) is not None and isinstance(scalar, np.generic)
524
+
525
+
526
+ def _is_pandas_like_dataframe(df: Any) -> bool:
527
+ """Check whether `df` is a pandas-like DataFrame without doing any imports.
528
+
529
+ By "pandas-like", we mean: pandas, Modin, cuDF.
530
+ """
531
+ return _is_pandas_dataframe(df) or _is_modin_dataframe(df) or _is_cudf_dataframe(df)
532
+
533
+
534
+ def is_pandas_like_dataframe(df: Any) -> bool:
535
+ """Check whether `df` is a pandas-like DataFrame without doing any imports.
536
+
537
+ By "pandas-like", we mean: pandas, Modin, cuDF.
538
+
539
+ Warning:
540
+ This method cannot be called on a Narwhals DataFrame/LazyFrame.
541
+ """
542
+ _warn_if_narwhals_df_or_lf(df)
543
+ return _is_pandas_like_dataframe(df)
544
+
545
+
546
+ def _is_pandas_like_series(ser: Any) -> bool:
547
+ """Check whether `ser` is a pandas-like Series without doing any imports.
548
+
549
+ By "pandas-like", we mean: pandas, Modin, cuDF.
550
+ """
551
+ return _is_pandas_series(ser) or _is_modin_series(ser) or _is_cudf_series(ser)
552
+
553
+
554
+ def is_pandas_like_series(ser: Any) -> bool:
555
+ """Check whether `ser` is a pandas-like Series without doing any imports.
556
+
557
+ By "pandas-like", we mean: pandas, Modin, cuDF.
558
+
559
+ Warning:
560
+ This method cannot be called on Narwhals Series.
561
+ """
562
+ _warn_if_narwhals_series(ser)
563
+ return _is_pandas_like_series(ser)
564
+
565
+
566
+ def is_pandas_like_index(index: Any) -> bool:
567
+ """Check whether `index` is a pandas-like Index without doing any imports.
568
+
569
+ By "pandas-like", we mean: pandas, Modin, cuDF.
570
+ """
571
+ return (
572
+ is_pandas_index(index) or is_modin_index(index) or is_cudf_index(index)
573
+ ) # pragma: no cover
574
+
575
+
576
+ def is_pandas_like_dtype(obj: Any) -> TypeIs[PandasLikeDType]:
577
+ return bool(pd := get_pandas()) and isinstance(
578
+ obj, (pd.api.extensions.ExtensionDtype, get_numpy().dtype)
579
+ )
580
+
581
+
582
+ def is_cudf_dtype(
583
+ obj: Any,
584
+ ) -> TypeIs[pd.api.extensions.ExtensionDtype]: # pragma: no cover
585
+ return (
586
+ bool(pd := get_pandas())
587
+ and isinstance(obj, (pd.api.extensions.ExtensionDtype))
588
+ and hasattr(obj, "to_arrow")
589
+ )
590
+
591
+
592
+ def _is_native_series(obj: Any | IntoSeriesT) -> TypeIs[IntoSeriesT]:
593
+ from narwhals import plugins
594
+ from narwhals._utils import _hasattr_static
595
+
596
+ return (
597
+ _hasattr_static(obj, "__narwhals_series__")
598
+ or _is_polars_series(obj)
599
+ or _is_pyarrow_chunked_array(obj)
600
+ or _is_pandas_like_series(obj)
601
+ or plugins.is_native_series(obj)
602
+ )
603
+
604
+
605
+ def _is_native_dataframe(obj: Any | IntoDataFrameT) -> TypeIs[IntoDataFrameT]:
606
+ from narwhals import plugins
607
+ from narwhals._utils import _hasattr_static
608
+
609
+ return (
610
+ _hasattr_static(obj, "__narwhals_dataframe__")
611
+ or _is_polars_dataframe(obj)
612
+ or _is_pyarrow_table(obj)
613
+ or _is_pandas_like_dataframe(obj)
614
+ or plugins.is_native_dataframe(obj)
615
+ )
616
+
617
+
618
+ def _is_native_lazyframe(obj: Any | IntoLazyFrameT) -> TypeIs[IntoLazyFrameT]:
619
+ from narwhals import plugins
620
+ from narwhals._utils import _hasattr_static
621
+
622
+ return (
623
+ _hasattr_static(obj, "__narwhals_lazyframe__")
624
+ or _is_polars_lazyframe(obj)
625
+ or _is_dask_dataframe(obj)
626
+ or _is_duckdb_relation(obj)
627
+ or _is_ibis_table(obj)
628
+ or _is_pyspark_dataframe(obj)
629
+ or _is_pyspark_connect_dataframe(obj)
630
+ or _is_sqlframe_dataframe(obj)
631
+ or plugins.is_native_lazyframe(obj)
632
+ )
633
+
634
+
635
+ def is_into_series(native_series: Any | IntoSeriesT) -> TypeIs[IntoSeriesT]:
636
+ """Check whether `native_series` can be converted to a Narwhals Series.
637
+
638
+ Arguments:
639
+ native_series: The object to check.
640
+
641
+ Examples:
642
+ >>> import pandas as pd
643
+ >>> import polars as pl
644
+ >>> import numpy as np
645
+ >>> import narwhals as nw
646
+
647
+ >>> s_pd = pd.Series([1, 2, 3])
648
+ >>> s_pl = pl.Series([1, 2, 3])
649
+ >>> np_arr = np.array([1, 2, 3])
650
+
651
+ >>> nw.dependencies.is_into_series(s_pd)
652
+ True
653
+ >>> nw.dependencies.is_into_series(s_pl)
654
+ True
655
+ >>> nw.dependencies.is_into_series(np_arr)
656
+ False
657
+ """
658
+ from narwhals.series import Series
659
+
660
+ return isinstance(native_series, Series) or _is_native_series(native_series)
661
+
662
+
663
+ def is_into_dataframe(native_dataframe: Any | IntoDataFrameT) -> TypeIs[IntoDataFrameT]:
664
+ """Check whether `native_dataframe` can be converted to a Narwhals DataFrame.
665
+
666
+ Arguments:
667
+ native_dataframe: The object to check.
668
+
669
+ Examples:
670
+ >>> import pandas as pd
671
+ >>> import polars as pl
672
+ >>> import numpy as np
673
+ >>> from narwhals.dependencies import is_into_dataframe
674
+
675
+ >>> df_pd = pd.DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})
676
+ >>> df_pl = pl.DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})
677
+ >>> np_arr = np.array([[1, 4], [2, 5], [3, 6]])
678
+
679
+ >>> is_into_dataframe(df_pd)
680
+ True
681
+ >>> is_into_dataframe(df_pl)
682
+ True
683
+ >>> is_into_dataframe(np_arr)
684
+ False
685
+ """
686
+ from narwhals.dataframe import DataFrame
687
+
688
+ return isinstance(native_dataframe, DataFrame) or _is_native_dataframe(
689
+ native_dataframe
690
+ )
691
+
692
+
693
+ def is_into_lazyframe(native_lazyframe: Any | IntoLazyFrameT) -> TypeIs[IntoLazyFrameT]:
694
+ """Check whether `native_lazyframe` can be converted to a Narwhals LazyFrame.
695
+
696
+ Arguments:
697
+ native_lazyframe: The object to check.
698
+
699
+ Examples:
700
+ >>> import pandas as pd
701
+ >>> import polars as pl
702
+ >>> import numpy as np
703
+ >>> from narwhals.dependencies import is_into_lazyframe
704
+
705
+ >>> df_pd = pd.DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})
706
+ >>> lf_pl = pl.LazyFrame({"a": [1, 2, 3], "b": [4, 5, 6]})
707
+ >>> np_arr = np.array([[1, 4], [2, 5], [3, 6]])
708
+
709
+ >>> is_into_lazyframe(df_pd)
710
+ False
711
+ >>> is_into_lazyframe(lf_pl)
712
+ True
713
+ >>> is_into_lazyframe(np_arr)
714
+ False
715
+ """
716
+ from narwhals.dataframe import LazyFrame
717
+
718
+ return isinstance(native_lazyframe, LazyFrame) or _is_native_lazyframe(
719
+ native_lazyframe
720
+ )
721
+
722
+
723
+ def is_narwhals_dataframe(
724
+ df: DataFrame[IntoDataFrameT] | Any,
725
+ ) -> TypeIs[DataFrame[IntoDataFrameT]]:
726
+ """Check whether `df` is a Narwhals DataFrame.
727
+
728
+ This is useful if you expect a user to pass in a Narwhals
729
+ DataFrame directly, and you want to catch both `narwhals.DataFrame`
730
+ and `narwhals.stable.v1.DataFrame`.
731
+ """
732
+ from narwhals.dataframe import DataFrame
733
+
734
+ return isinstance(df, DataFrame)
735
+
736
+
737
+ def is_narwhals_lazyframe(
738
+ lf: Any | LazyFrame[IntoLazyFrameT],
739
+ ) -> TypeIs[LazyFrame[IntoLazyFrameT]]:
740
+ """Check whether `lf` is a Narwhals LazyFrame.
741
+
742
+ This is useful if you expect a user to pass in a Narwhals
743
+ LazyFrame directly, and you want to catch both `narwhals.LazyFrame`
744
+ and `narwhals.stable.v1.LazyFrame`.
745
+ """
746
+ from narwhals.dataframe import LazyFrame
747
+
748
+ return isinstance(lf, LazyFrame)
749
+
750
+
751
+ def is_narwhals_series(ser: Any | Series[IntoSeriesT]) -> TypeIs[Series[IntoSeriesT]]:
752
+ """Check whether `ser` is a Narwhals Series.
753
+
754
+ This is useful if you expect a user to pass in a Narwhals
755
+ Series directly, and you want to catch both `narwhals.Series`
756
+ and `narwhals.stable.v1.Series`.
757
+ """
758
+ from narwhals.series import Series
759
+
760
+ return isinstance(ser, Series)
761
+
762
+
763
+ def is_narwhals_series_int(ser: Any | Series[IntoSeriesT]) -> TypeIs[Series[IntoSeriesT]]:
764
+ return is_narwhals_series(ser) and ser.dtype.is_integer()
765
+
766
+
767
+ def is_narwhals_series_bool(
768
+ ser: Any | Series[IntoSeriesT],
769
+ ) -> TypeIs[Series[IntoSeriesT]]:
770
+ return is_narwhals_series(ser) and ser.dtype.is_boolean()
771
+
772
+
773
+ __all__ = [
774
+ "get_cudf",
775
+ "get_dask",
776
+ "get_dask_dataframe",
777
+ "get_duckdb",
778
+ "get_ibis",
779
+ "get_modin",
780
+ "get_numpy",
781
+ "get_pandas",
782
+ "get_polars",
783
+ "get_pyarrow",
784
+ "get_pyspark",
785
+ "get_pyspark_connect",
786
+ "get_pyspark_sql",
787
+ "get_sqlframe",
788
+ "is_cudf_dataframe",
789
+ "is_cudf_index",
790
+ "is_cudf_series",
791
+ "is_dask_dataframe",
792
+ "is_duckdb_relation",
793
+ "is_ibis_table",
794
+ "is_into_dataframe",
795
+ "is_into_lazyframe",
796
+ "is_into_series",
797
+ "is_modin_dataframe",
798
+ "is_modin_index",
799
+ "is_modin_series",
800
+ "is_narwhals_dataframe",
801
+ "is_narwhals_lazyframe",
802
+ "is_narwhals_series",
803
+ "is_numpy_array",
804
+ "is_pandas_dataframe",
805
+ "is_pandas_index",
806
+ "is_pandas_like_dataframe",
807
+ "is_pandas_like_index",
808
+ "is_pandas_like_series",
809
+ "is_pandas_series",
810
+ "is_polars_dataframe",
811
+ "is_polars_lazyframe",
812
+ "is_polars_series",
813
+ "is_pyarrow_chunked_array",
814
+ "is_pyarrow_table",
815
+ "is_pyspark_connect_dataframe",
816
+ "is_pyspark_dataframe",
817
+ "is_sqlframe_dataframe",
818
+ ]
shared/package-files/74/744e964536e572ae3424a8572500ec3b0be114f26cb63ffc71e8222ed847d24b/__init__.py ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pandas.core.arrays.arrow import ArrowExtensionArray
2
+ from pandas.core.arrays.base import (
3
+ ExtensionArray,
4
+ ExtensionOpsMixin,
5
+ ExtensionScalarOpsMixin,
6
+ )
7
+ from pandas.core.arrays.boolean import BooleanArray
8
+ from pandas.core.arrays.categorical import Categorical
9
+ from pandas.core.arrays.datetimes import DatetimeArray
10
+ from pandas.core.arrays.floating import FloatingArray
11
+ from pandas.core.arrays.integer import IntegerArray
12
+ from pandas.core.arrays.interval import IntervalArray
13
+ from pandas.core.arrays.masked import BaseMaskedArray
14
+ from pandas.core.arrays.numpy_ import NumpyExtensionArray
15
+ from pandas.core.arrays.period import (
16
+ PeriodArray,
17
+ period_array,
18
+ )
19
+ from pandas.core.arrays.sparse import SparseArray
20
+ from pandas.core.arrays.string_ import StringArray
21
+ from pandas.core.arrays.string_arrow import ArrowStringArray
22
+ from pandas.core.arrays.timedeltas import TimedeltaArray
23
+
24
+ __all__ = [
25
+ "ArrowExtensionArray",
26
+ "ExtensionArray",
27
+ "ExtensionOpsMixin",
28
+ "ExtensionScalarOpsMixin",
29
+ "ArrowStringArray",
30
+ "BaseMaskedArray",
31
+ "BooleanArray",
32
+ "Categorical",
33
+ "DatetimeArray",
34
+ "FloatingArray",
35
+ "IntegerArray",
36
+ "IntervalArray",
37
+ "NumpyExtensionArray",
38
+ "PeriodArray",
39
+ "period_array",
40
+ "SparseArray",
41
+ "StringArray",
42
+ "TimedeltaArray",
43
+ ]
shared/package-files/74/7455918576862d910a3b1211c3ff1a24afea4eb8599047fc8943809a0d9aecf5/python_compiled_autograd.h ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ #include <torch/csrc/utils/python_stub.h>
3
+
4
+ // see [Note: Compiled Autograd]
5
+ namespace torch::dynamo::autograd {
6
+ PyObject* torch_c_dynamo_compiled_autograd_init();
7
+ } // namespace torch::dynamo::autograd
shared/package-files/74/745753959035fda80cbb13f5384474d9c2aa67e451f1d874112ffaf5774fdb4c/test_numconv.py ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import itertools
2
+ import unittest
3
+ from numba import njit
4
+ from numba.core import types
5
+
6
+
7
+ def template(fromty, toty):
8
+ def closure(self):
9
+ def cast(x):
10
+ y = x
11
+ return y
12
+
13
+ cfunc = njit(toty(fromty))(cast)
14
+ self.assertAlmostEqual(cfunc(1), 1)
15
+
16
+ return closure
17
+
18
+
19
+ class TestNumberConversion(unittest.TestCase):
20
+ """
21
+ Test all int/float numeric conversion to ensure we have all the external
22
+ dependencies to perform these conversions.
23
+ """
24
+ # NOTE: more implicit tests are in test_numberctor
25
+
26
+ @classmethod
27
+ def automatic_populate(cls):
28
+ tys = types.integer_domain | types.real_domain
29
+ for fromty, toty in itertools.permutations(tys, r=2):
30
+ test_name = "test_{fromty}_to_{toty}".format(fromty=fromty,
31
+ toty=toty)
32
+ setattr(cls, test_name, template(fromty, toty))
33
+
34
+
35
+ TestNumberConversion.automatic_populate()
36
+
37
+ if __name__ == '__main__':
38
+ unittest.main()
shared/package-files/74/746362b4d3db1f374ca77994944796cd71235f222fa69d4d26d0cfd4a6cd94fb/darwin-80x25-m ADDED
Binary file (985 Bytes). View file
 
shared/package-files/74/74640986f3954e36f52d54f9a8f64b271a31df4b83326383076e88cfa4e355b7/_tv_tensor.py ADDED
@@ -0,0 +1,132 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from typing import Any, Callable, Dict, Mapping, Optional, Sequence, Tuple, Type, TypeVar, Union
4
+
5
+ import torch
6
+ from torch._C import DisableTorchFunctionSubclass
7
+ from torch.types import _device, _dtype, _size
8
+
9
+ from torchvision.tv_tensors._torch_function_helpers import _FORCE_TORCHFUNCTION_SUBCLASS, _must_return_subclass
10
+
11
+
12
+ D = TypeVar("D", bound="TVTensor")
13
+
14
+
15
+ class TVTensor(torch.Tensor):
16
+ """Base class for all TVTensors.
17
+
18
+ You probably don't want to use this class unless you're defining your own
19
+ custom TVTensors. See
20
+ :ref:`sphx_glr_auto_examples_transforms_plot_custom_tv_tensors.py` for details.
21
+ """
22
+
23
+ @staticmethod
24
+ def _to_tensor(
25
+ data: Any,
26
+ dtype: Optional[torch.dtype] = None,
27
+ device: Optional[Union[torch.device, str, int]] = None,
28
+ requires_grad: Optional[bool] = None,
29
+ ) -> torch.Tensor:
30
+ if requires_grad is None:
31
+ requires_grad = data.requires_grad if isinstance(data, torch.Tensor) else False
32
+ return torch.as_tensor(data, dtype=dtype, device=device).requires_grad_(requires_grad)
33
+
34
+ @classmethod
35
+ def _wrap_output(
36
+ cls,
37
+ output: torch.Tensor,
38
+ args: Sequence[Any] = (),
39
+ kwargs: Optional[Mapping[str, Any]] = None,
40
+ ) -> torch.Tensor:
41
+ # Same as torch._tensor._convert
42
+ if isinstance(output, torch.Tensor) and not isinstance(output, cls):
43
+ output = output.as_subclass(cls)
44
+
45
+ if isinstance(output, (tuple, list)):
46
+ # Also handles things like namedtuples
47
+ output = type(output)(cls._wrap_output(part, args, kwargs) for part in output)
48
+ return output
49
+
50
+ @classmethod
51
+ def __torch_function__(
52
+ cls,
53
+ func: Callable[..., torch.Tensor],
54
+ types: Tuple[Type[torch.Tensor], ...],
55
+ args: Sequence[Any] = (),
56
+ kwargs: Optional[Mapping[str, Any]] = None,
57
+ ) -> torch.Tensor:
58
+ """For general information about how the __torch_function__ protocol works,
59
+ see https://pytorch.org/docs/stable/notes/extending.html#extending-torch
60
+
61
+ TL;DR: Every time a PyTorch operator is called, it goes through the inputs and looks for the
62
+ ``__torch_function__`` method. If one is found, it is invoked with the operator as ``func`` as well as the
63
+ ``args`` and ``kwargs`` of the original call.
64
+
65
+ Why do we override this? Because the base implementation in torch.Tensor would preserve the TVTensor type
66
+ of the output. In our case, we want to return pure tensors instead (with a few exceptions). Refer to the
67
+ "TVTensors FAQ" gallery example for a rationale of this behaviour (TL;DR: perf + no silver bullet).
68
+
69
+ Our implementation below is very similar to the base implementation in ``torch.Tensor`` - go check it out.
70
+ """
71
+ if not all(issubclass(cls, t) for t in types):
72
+ return NotImplemented
73
+
74
+ # Like in the base Tensor.__torch_function__ implementation, it's easier to always use
75
+ # DisableTorchFunctionSubclass and then manually re-wrap the output if necessary
76
+ with DisableTorchFunctionSubclass():
77
+ output = func(*args, **kwargs or dict())
78
+
79
+ must_return_subclass = _must_return_subclass()
80
+ if must_return_subclass or (func in _FORCE_TORCHFUNCTION_SUBCLASS and isinstance(args[0], cls)):
81
+ # If you're wondering why we need the `isinstance(args[0], cls)` check, remove it and see what fails
82
+ # in test_to_tv_tensor_reference().
83
+ # The __torch_function__ protocol will invoke the __torch_function__ method on *all* types involved in
84
+ # the computation by walking the MRO upwards. For example,
85
+ # `out = a_pure_tensor.to(an_image)` will invoke `Image.__torch_function__` with
86
+ # `args = (a_pure_tensor, an_image)` first. Without this guard, `out` would
87
+ # be wrapped into an `Image`.
88
+ return cls._wrap_output(output, args, kwargs)
89
+
90
+ if not must_return_subclass and isinstance(output, cls):
91
+ # DisableTorchFunctionSubclass is ignored by inplace ops like `.add_(...)`,
92
+ # so for those, the output is still a TVTensor. Thus, we need to manually unwrap.
93
+ return output.as_subclass(torch.Tensor)
94
+
95
+ return output
96
+
97
+ def _make_repr(self, **kwargs: Any) -> str:
98
+ # This is a poor man's implementation of the proposal in https://github.com/pytorch/pytorch/issues/76532.
99
+ # If that ever gets implemented, remove this in favor of the solution on the `torch.Tensor` class.
100
+ extra_repr = ", ".join(f"{key}={value}" for key, value in kwargs.items())
101
+ return f"{super().__repr__()[:-1]}, {extra_repr})"
102
+
103
+ # Add properties for common attributes like shape, dtype, device, ndim etc
104
+ # this way we return the result without passing into __torch_function__
105
+ @property
106
+ def shape(self) -> _size: # type: ignore[override]
107
+ with DisableTorchFunctionSubclass():
108
+ return super().shape
109
+
110
+ @property
111
+ def ndim(self) -> int: # type: ignore[override]
112
+ with DisableTorchFunctionSubclass():
113
+ return super().ndim
114
+
115
+ @property
116
+ def device(self, *args: Any, **kwargs: Any) -> _device: # type: ignore[override]
117
+ with DisableTorchFunctionSubclass():
118
+ return super().device
119
+
120
+ @property
121
+ def dtype(self) -> _dtype: # type: ignore[override]
122
+ with DisableTorchFunctionSubclass():
123
+ return super().dtype
124
+
125
+ def __deepcopy__(self: D, memo: Dict[int, Any]) -> D:
126
+ # We need to detach first, since a plain `Tensor.clone` will be part of the computation graph, which does
127
+ # *not* happen for `deepcopy(Tensor)`. A side-effect from detaching is that the `Tensor.requires_grad`
128
+ # attribute is cleared, so we need to refill it before we return.
129
+ # Note: We don't explicitly handle deep-copying of the metadata here. The only metadata we currently have is
130
+ # `BoundingBoxes.format` and `BoundingBoxes.canvas_size`, which are immutable and thus implicitly deep-copied by
131
+ # `BoundingBoxes.clone()`.
132
+ return self.detach().clone().requires_grad_(self.requires_grad) # type: ignore[return-value]
shared/package-files/74/7468a8b3ed64f900467b0ed817338d653cd55b1cfe69801aaa571c976fe1e41a/_extended_precision.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """A module with platform-specific extended precision
2
+ `numpy.number` subclasses.
3
+
4
+ The subclasses are defined here (instead of ``__init__.pyi``) such
5
+ that they can be imported conditionally via the numpy's mypy plugin.
6
+ """
7
+
8
+ import numpy as np
9
+ from . import (
10
+ _80Bit,
11
+ _96Bit,
12
+ _128Bit,
13
+ _256Bit,
14
+ )
15
+
16
+ uint128 = np.unsignedinteger[_128Bit]
17
+ uint256 = np.unsignedinteger[_256Bit]
18
+ int128 = np.signedinteger[_128Bit]
19
+ int256 = np.signedinteger[_256Bit]
20
+ float80 = np.floating[_80Bit]
21
+ float96 = np.floating[_96Bit]
22
+ float128 = np.floating[_128Bit]
23
+ float256 = np.floating[_256Bit]
24
+ complex160 = np.complexfloating[_80Bit, _80Bit]
25
+ complex192 = np.complexfloating[_96Bit, _96Bit]
26
+ complex256 = np.complexfloating[_128Bit, _128Bit]
27
+ complex512 = np.complexfloating[_256Bit, _256Bit]
shared/package-files/74/746b38d4187c578e5834bdffa3c2afbf111e6c49d1dd1778bd411f27b09633b8/sparse_compressed_tensor_ops.h ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from Operator.h
4
+
5
+ #include <tuple>
6
+ #include <vector>
7
+
8
+ // Forward declarations of any types needed in the operator signatures.
9
+ // We can't directly include these classes because it will cause circular include dependencies.
10
+ // This file is included by TensorBody.h, which defines the Tensor class.
11
+ #include <ATen/core/ATen_fwd.h>
12
+
13
+ namespace at {
14
+ namespace _ops {
15
+
16
+
17
+ struct TORCH_API sparse_compressed_tensor_comp_plain_value_size {
18
+ using schema = at::Tensor (const at::Tensor &, const at::Tensor &, const at::Tensor &, c10::SymIntArrayRef, c10::optional<at::ScalarType>, c10::optional<at::Layout>, c10::optional<at::Device>, c10::optional<bool>);
19
+ using ptr_schema = schema*;
20
+ // See Note [static constexpr char* members for windows NVCC]
21
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::sparse_compressed_tensor")
22
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "comp_plain_value_size")
23
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "sparse_compressed_tensor.comp_plain_value_size(Tensor compressed_indices, Tensor plain_indices, Tensor values, SymInt[] size, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=False) -> Tensor")
24
+ static at::Tensor call(const at::Tensor & compressed_indices, const at::Tensor & plain_indices, const at::Tensor & values, c10::SymIntArrayRef size, c10::optional<at::ScalarType> dtype, c10::optional<at::Layout> layout, c10::optional<at::Device> device, c10::optional<bool> pin_memory);
25
+ static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & compressed_indices, const at::Tensor & plain_indices, const at::Tensor & values, c10::SymIntArrayRef size, c10::optional<at::ScalarType> dtype, c10::optional<at::Layout> layout, c10::optional<at::Device> device, c10::optional<bool> pin_memory);
26
+ };
27
+
28
+ struct TORCH_API sparse_compressed_tensor_comp_plain_value {
29
+ using schema = at::Tensor (const at::Tensor &, const at::Tensor &, const at::Tensor &, c10::optional<at::ScalarType>, c10::optional<at::Layout>, c10::optional<at::Device>, c10::optional<bool>);
30
+ using ptr_schema = schema*;
31
+ // See Note [static constexpr char* members for windows NVCC]
32
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::sparse_compressed_tensor")
33
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "comp_plain_value")
34
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "sparse_compressed_tensor.comp_plain_value(Tensor compressed_indices, Tensor plain_indices, Tensor values, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=False) -> Tensor")
35
+ static at::Tensor call(const at::Tensor & compressed_indices, const at::Tensor & plain_indices, const at::Tensor & values, c10::optional<at::ScalarType> dtype, c10::optional<at::Layout> layout, c10::optional<at::Device> device, c10::optional<bool> pin_memory);
36
+ static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & compressed_indices, const at::Tensor & plain_indices, const at::Tensor & values, c10::optional<at::ScalarType> dtype, c10::optional<at::Layout> layout, c10::optional<at::Device> device, c10::optional<bool> pin_memory);
37
+ };
38
+
39
+ }} // namespace at::_ops
shared/package-files/74/746f744513890193f4e0ff0a4f36c93849b9c3ee656c73df3f5b54e486c4ac9a/site.pyi ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ from typing import Iterable, List, Optional
3
+
4
+ PREFIXES: List[str]
5
+ ENABLE_USER_SITE: Optional[bool]
6
+ USER_SITE: Optional[str]
7
+ USER_BASE: Optional[str]
8
+
9
+ if sys.version_info < (3,):
10
+ def main() -> None: ...
11
+
12
+ def addsitedir(sitedir: str, known_paths: Optional[Iterable[str]] = ...) -> None: ...
13
+ def getsitepackages(prefixes: Optional[Iterable[str]] = ...) -> List[str]: ...
14
+ def getuserbase() -> str: ...
15
+ def getusersitepackages() -> str: ...
shared/package-files/74/747f4d6e7edb335308724829e44f9f65dcf83ed53ba4f1172e79c746431eaf7a/pad_native.h ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from NativeFunction.h
4
+
5
+ #include <c10/core/Scalar.h>
6
+ #include <c10/core/Storage.h>
7
+ #include <c10/core/TensorOptions.h>
8
+ #include <c10/util/Deprecated.h>
9
+ #include <c10/util/Optional.h>
10
+ #include <c10/core/QScheme.h>
11
+ #include <ATen/core/Reduction.h>
12
+ #include <ATen/core/Tensor.h>
13
+ #include <tuple>
14
+ #include <vector>
15
+
16
+
17
+ namespace at {
18
+ namespace native {
19
+ TORCH_API at::Tensor pad_symint(const at::Tensor & self, c10::SymIntArrayRef pad, c10::string_view mode="constant", c10::optional<double> value=c10::nullopt);
20
+ } // namespace native
21
+ } // namespace at
shared/package-files/74/7498883445447692d2af9f99fdaec1c68606bc0d7ea427c789aff1885d137d8a/ubsan.h ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Licensed to the Apache Software Foundation (ASF) under one
2
+ // or more contributor license agreements. See the NOTICE file
3
+ // distributed with this work for additional information
4
+ // regarding copyright ownership. The ASF licenses this file
5
+ // to you under the Apache License, Version 2.0 (the
6
+ // "License"); you may not use this file except in compliance
7
+ // with the License. You may obtain a copy of the License at
8
+ //
9
+ // http://www.apache.org/licenses/LICENSE-2.0
10
+ //
11
+ // Unless required by applicable law or agreed to in writing,
12
+ // software distributed under the License is distributed on an
13
+ // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
+ // KIND, either express or implied. See the License for the
15
+ // specific language governing permissions and limitations
16
+ // under the License.
17
+
18
+ // Contains utilities for making UBSan happy.
19
+
20
+ #pragma once
21
+
22
+ #include <cstring>
23
+ #include <memory>
24
+ #include <type_traits>
25
+
26
+ #include "arrow/util/aligned_storage.h"
27
+ #include "arrow/util/macros.h"
28
+
29
+ namespace arrow {
30
+ namespace util {
31
+
32
+ namespace internal {
33
+
34
+ constexpr uint8_t kNonNullFiller = 0;
35
+
36
+ } // namespace internal
37
+
38
+ /// \brief Returns maybe_null if not null or a non-null pointer to an arbitrary memory
39
+ /// that shouldn't be dereferenced.
40
+ ///
41
+ /// Memset/Memcpy are undefined when a nullptr is passed as an argument use this utility
42
+ /// method to wrap locations where this could happen.
43
+ ///
44
+ /// Note: Flatbuffers has UBSan warnings if a zero length vector is passed.
45
+ /// https://github.com/google/flatbuffers/pull/5355 is trying to resolve
46
+ /// them.
47
+ template <typename T>
48
+ inline T* MakeNonNull(T* maybe_null = NULLPTR) {
49
+ if (ARROW_PREDICT_TRUE(maybe_null != NULLPTR)) {
50
+ return maybe_null;
51
+ }
52
+
53
+ return const_cast<T*>(reinterpret_cast<const T*>(&internal::kNonNullFiller));
54
+ }
55
+
56
+ template <typename T>
57
+ inline std::enable_if_t<std::is_trivially_copyable_v<T>, T> SafeLoadAs(
58
+ const uint8_t* unaligned) {
59
+ using Type = std::remove_const_t<T>;
60
+ arrow::internal::AlignedStorage<Type> raw_data;
61
+ std::memcpy(raw_data.get(), unaligned, sizeof(T));
62
+ auto data = *raw_data.get();
63
+ raw_data.destroy();
64
+ return data;
65
+ }
66
+
67
+ template <typename T>
68
+ inline std::enable_if_t<std::is_trivially_copyable_v<T>, T> SafeLoad(const T* unaligned) {
69
+ using Type = std::remove_const_t<T>;
70
+ arrow::internal::AlignedStorage<Type> raw_data;
71
+ std::memcpy(raw_data.get(), static_cast<const void*>(unaligned), sizeof(T));
72
+ auto data = *raw_data.get();
73
+ raw_data.destroy();
74
+ return data;
75
+ }
76
+
77
+ template <typename U, typename T>
78
+ inline std::enable_if_t<std::is_trivially_copyable_v<T> &&
79
+ std::is_trivially_copyable_v<U> && sizeof(T) == sizeof(U),
80
+ U>
81
+ SafeCopy(T value) {
82
+ using TypeU = std::remove_const_t<U>;
83
+ arrow::internal::AlignedStorage<TypeU> raw_data;
84
+ std::memcpy(raw_data.get(), static_cast<const void*>(&value), sizeof(T));
85
+ auto data = *raw_data.get();
86
+ raw_data.destroy();
87
+ return data;
88
+ }
89
+
90
+ template <typename T>
91
+ inline std::enable_if_t<std::is_trivially_copyable_v<T>, void> SafeStore(void* unaligned,
92
+ T value) {
93
+ std::memcpy(unaligned, &value, sizeof(T));
94
+ }
95
+
96
+ } // namespace util
97
+ } // namespace arrow
shared/package-files/74/7498de6addc14be4d89f546b505570b9f50c6ac6edccb7d8468cbf1d710d7854/utils.py ADDED
@@ -0,0 +1,136 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is dual licensed under the terms of the Apache License, Version
2
+ # 2.0, and the BSD License. See the LICENSE file in the root of this repository
3
+ # for complete details.
4
+
5
+ import re
6
+ from typing import FrozenSet, NewType, Tuple, Union, cast
7
+
8
+ from .tags import Tag, parse_tag
9
+ from .version import InvalidVersion, Version
10
+
11
+ BuildTag = Union[Tuple[()], Tuple[int, str]]
12
+ NormalizedName = NewType("NormalizedName", str)
13
+
14
+
15
+ class InvalidWheelFilename(ValueError):
16
+ """
17
+ An invalid wheel filename was found, users should refer to PEP 427.
18
+ """
19
+
20
+
21
+ class InvalidSdistFilename(ValueError):
22
+ """
23
+ An invalid sdist filename was found, users should refer to the packaging user guide.
24
+ """
25
+
26
+
27
+ _canonicalize_regex = re.compile(r"[-_.]+")
28
+ # PEP 427: The build number must start with a digit.
29
+ _build_tag_regex = re.compile(r"(\d+)(.*)")
30
+
31
+
32
+ def canonicalize_name(name: str) -> NormalizedName:
33
+ # This is taken from PEP 503.
34
+ value = _canonicalize_regex.sub("-", name).lower()
35
+ return cast(NormalizedName, value)
36
+
37
+
38
+ def canonicalize_version(version: Union[Version, str]) -> str:
39
+ """
40
+ This is very similar to Version.__str__, but has one subtle difference
41
+ with the way it handles the release segment.
42
+ """
43
+ if isinstance(version, str):
44
+ try:
45
+ parsed = Version(version)
46
+ except InvalidVersion:
47
+ # Legacy versions cannot be normalized
48
+ return version
49
+ else:
50
+ parsed = version
51
+
52
+ parts = []
53
+
54
+ # Epoch
55
+ if parsed.epoch != 0:
56
+ parts.append(f"{parsed.epoch}!")
57
+
58
+ # Release segment
59
+ # NB: This strips trailing '.0's to normalize
60
+ parts.append(re.sub(r"(\.0)+$", "", ".".join(str(x) for x in parsed.release)))
61
+
62
+ # Pre-release
63
+ if parsed.pre is not None:
64
+ parts.append("".join(str(x) for x in parsed.pre))
65
+
66
+ # Post-release
67
+ if parsed.post is not None:
68
+ parts.append(f".post{parsed.post}")
69
+
70
+ # Development release
71
+ if parsed.dev is not None:
72
+ parts.append(f".dev{parsed.dev}")
73
+
74
+ # Local version segment
75
+ if parsed.local is not None:
76
+ parts.append(f"+{parsed.local}")
77
+
78
+ return "".join(parts)
79
+
80
+
81
+ def parse_wheel_filename(
82
+ filename: str,
83
+ ) -> Tuple[NormalizedName, Version, BuildTag, FrozenSet[Tag]]:
84
+ if not filename.endswith(".whl"):
85
+ raise InvalidWheelFilename(
86
+ f"Invalid wheel filename (extension must be '.whl'): {filename}"
87
+ )
88
+
89
+ filename = filename[:-4]
90
+ dashes = filename.count("-")
91
+ if dashes not in (4, 5):
92
+ raise InvalidWheelFilename(
93
+ f"Invalid wheel filename (wrong number of parts): {filename}"
94
+ )
95
+
96
+ parts = filename.split("-", dashes - 2)
97
+ name_part = parts[0]
98
+ # See PEP 427 for the rules on escaping the project name
99
+ if "__" in name_part or re.match(r"^[\w\d._]*$", name_part, re.UNICODE) is None:
100
+ raise InvalidWheelFilename(f"Invalid project name: {filename}")
101
+ name = canonicalize_name(name_part)
102
+ version = Version(parts[1])
103
+ if dashes == 5:
104
+ build_part = parts[2]
105
+ build_match = _build_tag_regex.match(build_part)
106
+ if build_match is None:
107
+ raise InvalidWheelFilename(
108
+ f"Invalid build number: {build_part} in '{filename}'"
109
+ )
110
+ build = cast(BuildTag, (int(build_match.group(1)), build_match.group(2)))
111
+ else:
112
+ build = ()
113
+ tags = parse_tag(parts[-1])
114
+ return (name, version, build, tags)
115
+
116
+
117
+ def parse_sdist_filename(filename: str) -> Tuple[NormalizedName, Version]:
118
+ if filename.endswith(".tar.gz"):
119
+ file_stem = filename[: -len(".tar.gz")]
120
+ elif filename.endswith(".zip"):
121
+ file_stem = filename[: -len(".zip")]
122
+ else:
123
+ raise InvalidSdistFilename(
124
+ f"Invalid sdist filename (extension must be '.tar.gz' or '.zip'):"
125
+ f" {filename}"
126
+ )
127
+
128
+ # We are requiring a PEP 440 version, which cannot contain dashes,
129
+ # so we split on the last dash.
130
+ name_part, sep, version_part = file_stem.rpartition("-")
131
+ if not sep:
132
+ raise InvalidSdistFilename(f"Invalid sdist filename: {filename}")
133
+
134
+ name = canonicalize_name(name_part)
135
+ version = Version(version_part)
136
+ return (name, version)
shared/package-files/74/749937a279c373f53a387e2e04d9a3a45d0a70b0081d981fe2dbcf0a8c856921/special_shifted_chebyshev_polynomial_v_meta.h ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from NativeMetaFunction.h
4
+
5
+ #include <c10/core/Scalar.h>
6
+ #include <c10/core/Storage.h>
7
+ #include <c10/core/TensorOptions.h>
8
+ #include <c10/util/Deprecated.h>
9
+ #include <c10/util/Optional.h>
10
+ #include <c10/core/QScheme.h>
11
+ #include <ATen/core/Reduction.h>
12
+ #include <ATen/TensorIterator.h>
13
+ #include <ATen/TensorMeta.h>
14
+ #include <tuple>
15
+ #include <vector>
16
+
17
+ namespace at {
18
+ namespace meta {
19
+
20
+ struct TORCH_API structured_special_shifted_chebyshev_polynomial_v : public TensorIteratorBase {
21
+
22
+
23
+ void meta(const at::Tensor & x, const at::Tensor & n);
24
+ };
25
+
26
+ } // namespace native
27
+ } // namespace at
shared/package-files/74/74a59a0d9a6268c92e571a57aaa93109f4e759e489b30dc04b88a2b5d99b611e/base.py ADDED
@@ -0,0 +1,448 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Progress bar implementation on top of prompt_toolkit.
3
+
4
+ ::
5
+
6
+ with ProgressBar(...) as pb:
7
+ for item in pb(data):
8
+ ...
9
+ """
10
+ from __future__ import annotations
11
+
12
+ import contextvars
13
+ import datetime
14
+ import functools
15
+ import os
16
+ import signal
17
+ import threading
18
+ import traceback
19
+ from typing import (
20
+ Callable,
21
+ Generic,
22
+ Iterable,
23
+ Iterator,
24
+ Sequence,
25
+ Sized,
26
+ TextIO,
27
+ TypeVar,
28
+ cast,
29
+ )
30
+
31
+ from prompt_toolkit.application import Application
32
+ from prompt_toolkit.application.current import get_app_session
33
+ from prompt_toolkit.filters import Condition, is_done, renderer_height_is_known
34
+ from prompt_toolkit.formatted_text import (
35
+ AnyFormattedText,
36
+ StyleAndTextTuples,
37
+ to_formatted_text,
38
+ )
39
+ from prompt_toolkit.input import Input
40
+ from prompt_toolkit.key_binding import KeyBindings
41
+ from prompt_toolkit.key_binding.key_processor import KeyPressEvent
42
+ from prompt_toolkit.layout import (
43
+ ConditionalContainer,
44
+ FormattedTextControl,
45
+ HSplit,
46
+ Layout,
47
+ VSplit,
48
+ Window,
49
+ )
50
+ from prompt_toolkit.layout.controls import UIContent, UIControl
51
+ from prompt_toolkit.layout.dimension import AnyDimension, D
52
+ from prompt_toolkit.output import ColorDepth, Output
53
+ from prompt_toolkit.styles import BaseStyle
54
+ from prompt_toolkit.utils import in_main_thread
55
+
56
+ from .formatters import Formatter, create_default_formatters
57
+
58
+ __all__ = ["ProgressBar"]
59
+
60
+ E = KeyPressEvent
61
+
62
+ _SIGWINCH = getattr(signal, "SIGWINCH", None)
63
+
64
+
65
+ def create_key_bindings(cancel_callback: Callable[[], None] | None) -> KeyBindings:
66
+ """
67
+ Key bindings handled by the progress bar.
68
+ (The main thread is not supposed to handle any key bindings.)
69
+ """
70
+ kb = KeyBindings()
71
+
72
+ @kb.add("c-l")
73
+ def _clear(event: E) -> None:
74
+ event.app.renderer.clear()
75
+
76
+ if cancel_callback is not None:
77
+
78
+ @kb.add("c-c")
79
+ def _interrupt(event: E) -> None:
80
+ "Kill the 'body' of the progress bar, but only if we run from the main thread."
81
+ assert cancel_callback is not None
82
+ cancel_callback()
83
+
84
+ return kb
85
+
86
+
87
+ _T = TypeVar("_T")
88
+
89
+
90
+ class ProgressBar:
91
+ """
92
+ Progress bar context manager.
93
+
94
+ Usage ::
95
+
96
+ with ProgressBar(...) as pb:
97
+ for item in pb(data):
98
+ ...
99
+
100
+ :param title: Text to be displayed above the progress bars. This can be a
101
+ callable or formatted text as well.
102
+ :param formatters: List of :class:`.Formatter` instances.
103
+ :param bottom_toolbar: Text to be displayed in the bottom toolbar. This
104
+ can be a callable or formatted text.
105
+ :param style: :class:`prompt_toolkit.styles.BaseStyle` instance.
106
+ :param key_bindings: :class:`.KeyBindings` instance.
107
+ :param cancel_callback: Callback function that's called when control-c is
108
+ pressed by the user. This can be used for instance to start "proper"
109
+ cancellation if the wrapped code supports it.
110
+ :param file: The file object used for rendering, by default `sys.stderr` is used.
111
+
112
+ :param color_depth: `prompt_toolkit` `ColorDepth` instance.
113
+ :param output: :class:`~prompt_toolkit.output.Output` instance.
114
+ :param input: :class:`~prompt_toolkit.input.Input` instance.
115
+ """
116
+
117
+ def __init__(
118
+ self,
119
+ title: AnyFormattedText = None,
120
+ formatters: Sequence[Formatter] | None = None,
121
+ bottom_toolbar: AnyFormattedText = None,
122
+ style: BaseStyle | None = None,
123
+ key_bindings: KeyBindings | None = None,
124
+ cancel_callback: Callable[[], None] | None = None,
125
+ file: TextIO | None = None,
126
+ color_depth: ColorDepth | None = None,
127
+ output: Output | None = None,
128
+ input: Input | None = None,
129
+ ) -> None:
130
+ self.title = title
131
+ self.formatters = formatters or create_default_formatters()
132
+ self.bottom_toolbar = bottom_toolbar
133
+ self.counters: list[ProgressBarCounter[object]] = []
134
+ self.style = style
135
+ self.key_bindings = key_bindings
136
+ self.cancel_callback = cancel_callback
137
+
138
+ # If no `cancel_callback` was given, and we're creating the progress
139
+ # bar from the main thread. Cancel by sending a `KeyboardInterrupt` to
140
+ # the main thread.
141
+ if self.cancel_callback is None and in_main_thread():
142
+
143
+ def keyboard_interrupt_to_main_thread() -> None:
144
+ os.kill(os.getpid(), signal.SIGINT)
145
+
146
+ self.cancel_callback = keyboard_interrupt_to_main_thread
147
+
148
+ # Note that we use __stderr__ as default error output, because that
149
+ # works best with `patch_stdout`.
150
+ self.color_depth = color_depth
151
+ self.output = output or get_app_session().output
152
+ self.input = input or get_app_session().input
153
+
154
+ self._thread: threading.Thread | None = None
155
+
156
+ self._has_sigwinch = False
157
+ self._app_started = threading.Event()
158
+
159
+ def __enter__(self) -> ProgressBar:
160
+ # Create UI Application.
161
+ title_toolbar = ConditionalContainer(
162
+ Window(
163
+ FormattedTextControl(lambda: self.title),
164
+ height=1,
165
+ style="class:progressbar,title",
166
+ ),
167
+ filter=Condition(lambda: self.title is not None),
168
+ )
169
+
170
+ bottom_toolbar = ConditionalContainer(
171
+ Window(
172
+ FormattedTextControl(
173
+ lambda: self.bottom_toolbar, style="class:bottom-toolbar.text"
174
+ ),
175
+ style="class:bottom-toolbar",
176
+ height=1,
177
+ ),
178
+ filter=~is_done
179
+ & renderer_height_is_known
180
+ & Condition(lambda: self.bottom_toolbar is not None),
181
+ )
182
+
183
+ def width_for_formatter(formatter: Formatter) -> AnyDimension:
184
+ # Needs to be passed as callable (partial) to the 'width'
185
+ # parameter, because we want to call it on every resize.
186
+ return formatter.get_width(progress_bar=self)
187
+
188
+ progress_controls = [
189
+ Window(
190
+ content=_ProgressControl(self, f, self.cancel_callback),
191
+ width=functools.partial(width_for_formatter, f),
192
+ )
193
+ for f in self.formatters
194
+ ]
195
+
196
+ self.app: Application[None] = Application(
197
+ min_redraw_interval=0.05,
198
+ layout=Layout(
199
+ HSplit(
200
+ [
201
+ title_toolbar,
202
+ VSplit(
203
+ progress_controls,
204
+ height=lambda: D(
205
+ preferred=len(self.counters), max=len(self.counters)
206
+ ),
207
+ ),
208
+ Window(),
209
+ bottom_toolbar,
210
+ ]
211
+ )
212
+ ),
213
+ style=self.style,
214
+ key_bindings=self.key_bindings,
215
+ refresh_interval=0.3,
216
+ color_depth=self.color_depth,
217
+ output=self.output,
218
+ input=self.input,
219
+ )
220
+
221
+ # Run application in different thread.
222
+ def run() -> None:
223
+ try:
224
+ self.app.run(pre_run=self._app_started.set)
225
+ except BaseException as e:
226
+ traceback.print_exc()
227
+ print(e)
228
+
229
+ ctx: contextvars.Context = contextvars.copy_context()
230
+
231
+ self._thread = threading.Thread(target=ctx.run, args=(run,))
232
+ self._thread.start()
233
+
234
+ return self
235
+
236
+ def __exit__(self, *a: object) -> None:
237
+ # Wait for the app to be started. Make sure we don't quit earlier,
238
+ # otherwise `self.app.exit` won't terminate the app because
239
+ # `self.app.future` has not yet been set.
240
+ self._app_started.wait()
241
+
242
+ # Quit UI application.
243
+ if self.app.is_running and self.app.loop is not None:
244
+ self.app.loop.call_soon_threadsafe(self.app.exit)
245
+
246
+ if self._thread is not None:
247
+ self._thread.join()
248
+
249
+ def __call__(
250
+ self,
251
+ data: Iterable[_T] | None = None,
252
+ label: AnyFormattedText = "",
253
+ remove_when_done: bool = False,
254
+ total: int | None = None,
255
+ ) -> ProgressBarCounter[_T]:
256
+ """
257
+ Start a new counter.
258
+
259
+ :param label: Title text or description for this progress. (This can be
260
+ formatted text as well).
261
+ :param remove_when_done: When `True`, hide this progress bar.
262
+ :param total: Specify the maximum value if it can't be calculated by
263
+ calling ``len``.
264
+ """
265
+ counter = ProgressBarCounter(
266
+ self, data, label=label, remove_when_done=remove_when_done, total=total
267
+ )
268
+ self.counters.append(counter)
269
+ return counter
270
+
271
+ def invalidate(self) -> None:
272
+ self.app.invalidate()
273
+
274
+
275
+ class _ProgressControl(UIControl):
276
+ """
277
+ User control for the progress bar.
278
+ """
279
+
280
+ def __init__(
281
+ self,
282
+ progress_bar: ProgressBar,
283
+ formatter: Formatter,
284
+ cancel_callback: Callable[[], None] | None,
285
+ ) -> None:
286
+ self.progress_bar = progress_bar
287
+ self.formatter = formatter
288
+ self._key_bindings = create_key_bindings(cancel_callback)
289
+
290
+ def create_content(self, width: int, height: int) -> UIContent:
291
+ items: list[StyleAndTextTuples] = []
292
+
293
+ for pr in self.progress_bar.counters:
294
+ try:
295
+ text = self.formatter.format(self.progress_bar, pr, width)
296
+ except BaseException:
297
+ traceback.print_exc()
298
+ text = "ERROR"
299
+
300
+ items.append(to_formatted_text(text))
301
+
302
+ def get_line(i: int) -> StyleAndTextTuples:
303
+ return items[i]
304
+
305
+ return UIContent(get_line=get_line, line_count=len(items), show_cursor=False)
306
+
307
+ def is_focusable(self) -> bool:
308
+ return True # Make sure that the key bindings work.
309
+
310
+ def get_key_bindings(self) -> KeyBindings:
311
+ return self._key_bindings
312
+
313
+
314
+ _CounterItem = TypeVar("_CounterItem", covariant=True)
315
+
316
+
317
+ class ProgressBarCounter(Generic[_CounterItem]):
318
+ """
319
+ An individual counter (A progress bar can have multiple counters).
320
+ """
321
+
322
+ def __init__(
323
+ self,
324
+ progress_bar: ProgressBar,
325
+ data: Iterable[_CounterItem] | None = None,
326
+ label: AnyFormattedText = "",
327
+ remove_when_done: bool = False,
328
+ total: int | None = None,
329
+ ) -> None:
330
+ self.start_time = datetime.datetime.now()
331
+ self.stop_time: datetime.datetime | None = None
332
+ self.progress_bar = progress_bar
333
+ self.data = data
334
+ self.items_completed = 0
335
+ self.label = label
336
+ self.remove_when_done = remove_when_done
337
+ self._done = False
338
+ self.total: int | None
339
+
340
+ if total is None:
341
+ try:
342
+ self.total = len(cast(Sized, data))
343
+ except TypeError:
344
+ self.total = None # We don't know the total length.
345
+ else:
346
+ self.total = total
347
+
348
+ def __iter__(self) -> Iterator[_CounterItem]:
349
+ if self.data is not None:
350
+ try:
351
+ for item in self.data:
352
+ yield item
353
+ self.item_completed()
354
+
355
+ # Only done if we iterate to the very end.
356
+ self.done = True
357
+ finally:
358
+ # Ensure counter has stopped even if we did not iterate to the
359
+ # end (e.g. break or exceptions).
360
+ self.stopped = True
361
+ else:
362
+ raise NotImplementedError("No data defined to iterate over.")
363
+
364
+ def item_completed(self) -> None:
365
+ """
366
+ Start handling the next item.
367
+
368
+ (Can be called manually in case we don't have a collection to loop through.)
369
+ """
370
+ self.items_completed += 1
371
+ self.progress_bar.invalidate()
372
+
373
+ @property
374
+ def done(self) -> bool:
375
+ """Whether a counter has been completed.
376
+
377
+ Done counter have been stopped (see stopped) and removed depending on
378
+ remove_when_done value.
379
+
380
+ Contrast this with stopped. A stopped counter may be terminated before
381
+ 100% completion. A done counter has reached its 100% completion.
382
+ """
383
+ return self._done
384
+
385
+ @done.setter
386
+ def done(self, value: bool) -> None:
387
+ self._done = value
388
+ self.stopped = value
389
+
390
+ if value and self.remove_when_done:
391
+ self.progress_bar.counters.remove(self)
392
+
393
+ @property
394
+ def stopped(self) -> bool:
395
+ """Whether a counter has been stopped.
396
+
397
+ Stopped counters no longer have increasing time_elapsed. This distinction is
398
+ also used to prevent the Bar formatter with unknown totals from continuing to run.
399
+
400
+ A stopped counter (but not done) can be used to signal that a given counter has
401
+ encountered an error but allows other counters to continue
402
+ (e.g. download X of Y failed). Given how only done counters are removed
403
+ (see remove_when_done) this can help aggregate failures from a large number of
404
+ successes.
405
+
406
+ Contrast this with done. A done counter has reached its 100% completion.
407
+ A stopped counter may be terminated before 100% completion.
408
+ """
409
+ return self.stop_time is not None
410
+
411
+ @stopped.setter
412
+ def stopped(self, value: bool) -> None:
413
+ if value:
414
+ # This counter has not already been stopped.
415
+ if not self.stop_time:
416
+ self.stop_time = datetime.datetime.now()
417
+ else:
418
+ # Clearing any previously set stop_time.
419
+ self.stop_time = None
420
+
421
+ @property
422
+ def percentage(self) -> float:
423
+ if self.total is None:
424
+ return 0
425
+ else:
426
+ return self.items_completed * 100 / max(self.total, 1)
427
+
428
+ @property
429
+ def time_elapsed(self) -> datetime.timedelta:
430
+ """
431
+ Return how much time has been elapsed since the start.
432
+ """
433
+ if self.stop_time is None:
434
+ return datetime.datetime.now() - self.start_time
435
+ else:
436
+ return self.stop_time - self.start_time
437
+
438
+ @property
439
+ def time_left(self) -> datetime.timedelta | None:
440
+ """
441
+ Timedelta representing the time left.
442
+ """
443
+ if self.total is None or not self.percentage:
444
+ return None
445
+ elif self.done or self.stopped:
446
+ return datetime.timedelta(0)
447
+ else:
448
+ return self.time_elapsed * (100 - self.percentage) / self.percentage
shared/package-files/74/74b12fdedc6706b1d8c5a8ce60042103c080edac62b8fc351026da1cbe69df7f/test_adjlist.py ADDED
@@ -0,0 +1,268 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Unit tests for adjlist.
3
+ """
4
+ import io
5
+ import os
6
+ import tempfile
7
+
8
+ import pytest
9
+
10
+ import networkx as nx
11
+ from networkx.utils import edges_equal, graphs_equal, nodes_equal
12
+
13
+
14
+ class TestAdjlist:
15
+ @classmethod
16
+ def setup_class(cls):
17
+ cls.G = nx.Graph(name="test")
18
+ e = [("a", "b"), ("b", "c"), ("c", "d"), ("d", "e"), ("e", "f"), ("a", "f")]
19
+ cls.G.add_edges_from(e)
20
+ cls.G.add_node("g")
21
+ cls.DG = nx.DiGraph(cls.G)
22
+ cls.XG = nx.MultiGraph()
23
+ cls.XG.add_weighted_edges_from([(1, 2, 5), (1, 2, 5), (1, 2, 1), (3, 3, 42)])
24
+ cls.XDG = nx.MultiDiGraph(cls.XG)
25
+
26
+ def test_read_multiline_adjlist_1(self):
27
+ # Unit test for https://networkx.lanl.gov/trac/ticket/252
28
+ s = b"""# comment line
29
+ 1 2
30
+ # comment line
31
+ 2
32
+ 3
33
+ """
34
+ bytesIO = io.BytesIO(s)
35
+ G = nx.read_multiline_adjlist(bytesIO)
36
+ adj = {"1": {"3": {}, "2": {}}, "3": {"1": {}}, "2": {"1": {}}}
37
+ assert graphs_equal(G, nx.Graph(adj))
38
+
39
+ def test_unicode(self):
40
+ G = nx.Graph()
41
+ name1 = chr(2344) + chr(123) + chr(6543)
42
+ name2 = chr(5543) + chr(1543) + chr(324)
43
+ G.add_edge(name1, "Radiohead", **{name2: 3})
44
+ fd, fname = tempfile.mkstemp()
45
+ nx.write_multiline_adjlist(G, fname)
46
+ H = nx.read_multiline_adjlist(fname)
47
+ assert graphs_equal(G, H)
48
+ os.close(fd)
49
+ os.unlink(fname)
50
+
51
+ def test_latin1_err(self):
52
+ G = nx.Graph()
53
+ name1 = chr(2344) + chr(123) + chr(6543)
54
+ name2 = chr(5543) + chr(1543) + chr(324)
55
+ G.add_edge(name1, "Radiohead", **{name2: 3})
56
+ fd, fname = tempfile.mkstemp()
57
+ pytest.raises(
58
+ UnicodeEncodeError, nx.write_multiline_adjlist, G, fname, encoding="latin-1"
59
+ )
60
+ os.close(fd)
61
+ os.unlink(fname)
62
+
63
+ def test_latin1(self):
64
+ G = nx.Graph()
65
+ name1 = "Bj" + chr(246) + "rk"
66
+ name2 = chr(220) + "ber"
67
+ G.add_edge(name1, "Radiohead", **{name2: 3})
68
+ fd, fname = tempfile.mkstemp()
69
+ nx.write_multiline_adjlist(G, fname, encoding="latin-1")
70
+ H = nx.read_multiline_adjlist(fname, encoding="latin-1")
71
+ assert graphs_equal(G, H)
72
+ os.close(fd)
73
+ os.unlink(fname)
74
+
75
+ def test_parse_adjlist(self):
76
+ lines = ["1 2 5", "2 3 4", "3 5", "4", "5"]
77
+ nx.parse_adjlist(lines, nodetype=int) # smoke test
78
+ with pytest.raises(TypeError):
79
+ nx.parse_adjlist(lines, nodetype="int")
80
+ lines = ["1 2 5", "2 b", "c"]
81
+ with pytest.raises(TypeError):
82
+ nx.parse_adjlist(lines, nodetype=int)
83
+
84
+ def test_adjlist_graph(self):
85
+ G = self.G
86
+ (fd, fname) = tempfile.mkstemp()
87
+ nx.write_adjlist(G, fname)
88
+ H = nx.read_adjlist(fname)
89
+ H2 = nx.read_adjlist(fname)
90
+ assert H is not H2 # they should be different graphs
91
+ assert nodes_equal(list(H), list(G))
92
+ assert edges_equal(list(H.edges()), list(G.edges()))
93
+ os.close(fd)
94
+ os.unlink(fname)
95
+
96
+ def test_adjlist_digraph(self):
97
+ G = self.DG
98
+ (fd, fname) = tempfile.mkstemp()
99
+ nx.write_adjlist(G, fname)
100
+ H = nx.read_adjlist(fname, create_using=nx.DiGraph())
101
+ H2 = nx.read_adjlist(fname, create_using=nx.DiGraph())
102
+ assert H is not H2 # they should be different graphs
103
+ assert nodes_equal(list(H), list(G))
104
+ assert edges_equal(list(H.edges()), list(G.edges()))
105
+ os.close(fd)
106
+ os.unlink(fname)
107
+
108
+ def test_adjlist_integers(self):
109
+ (fd, fname) = tempfile.mkstemp()
110
+ G = nx.convert_node_labels_to_integers(self.G)
111
+ nx.write_adjlist(G, fname)
112
+ H = nx.read_adjlist(fname, nodetype=int)
113
+ H2 = nx.read_adjlist(fname, nodetype=int)
114
+ assert H is not H2 # they should be different graphs
115
+ assert nodes_equal(list(H), list(G))
116
+ assert edges_equal(list(H.edges()), list(G.edges()))
117
+ os.close(fd)
118
+ os.unlink(fname)
119
+
120
+ def test_adjlist_multigraph(self):
121
+ G = self.XG
122
+ (fd, fname) = tempfile.mkstemp()
123
+ nx.write_adjlist(G, fname)
124
+ H = nx.read_adjlist(fname, nodetype=int, create_using=nx.MultiGraph())
125
+ H2 = nx.read_adjlist(fname, nodetype=int, create_using=nx.MultiGraph())
126
+ assert H is not H2 # they should be different graphs
127
+ assert nodes_equal(list(H), list(G))
128
+ assert edges_equal(list(H.edges()), list(G.edges()))
129
+ os.close(fd)
130
+ os.unlink(fname)
131
+
132
+ def test_adjlist_multidigraph(self):
133
+ G = self.XDG
134
+ (fd, fname) = tempfile.mkstemp()
135
+ nx.write_adjlist(G, fname)
136
+ H = nx.read_adjlist(fname, nodetype=int, create_using=nx.MultiDiGraph())
137
+ H2 = nx.read_adjlist(fname, nodetype=int, create_using=nx.MultiDiGraph())
138
+ assert H is not H2 # they should be different graphs
139
+ assert nodes_equal(list(H), list(G))
140
+ assert edges_equal(list(H.edges()), list(G.edges()))
141
+ os.close(fd)
142
+ os.unlink(fname)
143
+
144
+ def test_adjlist_delimiter(self):
145
+ fh = io.BytesIO()
146
+ G = nx.path_graph(3)
147
+ nx.write_adjlist(G, fh, delimiter=":")
148
+ fh.seek(0)
149
+ H = nx.read_adjlist(fh, nodetype=int, delimiter=":")
150
+ assert nodes_equal(list(H), list(G))
151
+ assert edges_equal(list(H.edges()), list(G.edges()))
152
+
153
+
154
+ class TestMultilineAdjlist:
155
+ @classmethod
156
+ def setup_class(cls):
157
+ cls.G = nx.Graph(name="test")
158
+ e = [("a", "b"), ("b", "c"), ("c", "d"), ("d", "e"), ("e", "f"), ("a", "f")]
159
+ cls.G.add_edges_from(e)
160
+ cls.G.add_node("g")
161
+ cls.DG = nx.DiGraph(cls.G)
162
+ cls.DG.remove_edge("b", "a")
163
+ cls.DG.remove_edge("b", "c")
164
+ cls.XG = nx.MultiGraph()
165
+ cls.XG.add_weighted_edges_from([(1, 2, 5), (1, 2, 5), (1, 2, 1), (3, 3, 42)])
166
+ cls.XDG = nx.MultiDiGraph(cls.XG)
167
+
168
+ def test_parse_multiline_adjlist(self):
169
+ lines = [
170
+ "1 2",
171
+ "b {'weight':3, 'name': 'Frodo'}",
172
+ "c {}",
173
+ "d 1",
174
+ "e {'weight':6, 'name': 'Saruman'}",
175
+ ]
176
+ nx.parse_multiline_adjlist(iter(lines)) # smoke test
177
+ with pytest.raises(TypeError):
178
+ nx.parse_multiline_adjlist(iter(lines), nodetype=int)
179
+ nx.parse_multiline_adjlist(iter(lines), edgetype=str) # smoke test
180
+ with pytest.raises(TypeError):
181
+ nx.parse_multiline_adjlist(iter(lines), nodetype=int)
182
+ lines = ["1 a"]
183
+ with pytest.raises(TypeError):
184
+ nx.parse_multiline_adjlist(iter(lines))
185
+ lines = ["a 2"]
186
+ with pytest.raises(TypeError):
187
+ nx.parse_multiline_adjlist(iter(lines), nodetype=int)
188
+ lines = ["1 2"]
189
+ with pytest.raises(TypeError):
190
+ nx.parse_multiline_adjlist(iter(lines))
191
+ lines = ["1 2", "2 {}"]
192
+ with pytest.raises(TypeError):
193
+ nx.parse_multiline_adjlist(iter(lines))
194
+
195
+ def test_multiline_adjlist_graph(self):
196
+ G = self.G
197
+ (fd, fname) = tempfile.mkstemp()
198
+ nx.write_multiline_adjlist(G, fname)
199
+ H = nx.read_multiline_adjlist(fname)
200
+ H2 = nx.read_multiline_adjlist(fname)
201
+ assert H is not H2 # they should be different graphs
202
+ assert nodes_equal(list(H), list(G))
203
+ assert edges_equal(list(H.edges()), list(G.edges()))
204
+ os.close(fd)
205
+ os.unlink(fname)
206
+
207
+ def test_multiline_adjlist_digraph(self):
208
+ G = self.DG
209
+ (fd, fname) = tempfile.mkstemp()
210
+ nx.write_multiline_adjlist(G, fname)
211
+ H = nx.read_multiline_adjlist(fname, create_using=nx.DiGraph())
212
+ H2 = nx.read_multiline_adjlist(fname, create_using=nx.DiGraph())
213
+ assert H is not H2 # they should be different graphs
214
+ assert nodes_equal(list(H), list(G))
215
+ assert edges_equal(list(H.edges()), list(G.edges()))
216
+ os.close(fd)
217
+ os.unlink(fname)
218
+
219
+ def test_multiline_adjlist_integers(self):
220
+ (fd, fname) = tempfile.mkstemp()
221
+ G = nx.convert_node_labels_to_integers(self.G)
222
+ nx.write_multiline_adjlist(G, fname)
223
+ H = nx.read_multiline_adjlist(fname, nodetype=int)
224
+ H2 = nx.read_multiline_adjlist(fname, nodetype=int)
225
+ assert H is not H2 # they should be different graphs
226
+ assert nodes_equal(list(H), list(G))
227
+ assert edges_equal(list(H.edges()), list(G.edges()))
228
+ os.close(fd)
229
+ os.unlink(fname)
230
+
231
+ def test_multiline_adjlist_multigraph(self):
232
+ G = self.XG
233
+ (fd, fname) = tempfile.mkstemp()
234
+ nx.write_multiline_adjlist(G, fname)
235
+ H = nx.read_multiline_adjlist(fname, nodetype=int, create_using=nx.MultiGraph())
236
+ H2 = nx.read_multiline_adjlist(
237
+ fname, nodetype=int, create_using=nx.MultiGraph()
238
+ )
239
+ assert H is not H2 # they should be different graphs
240
+ assert nodes_equal(list(H), list(G))
241
+ assert edges_equal(list(H.edges()), list(G.edges()))
242
+ os.close(fd)
243
+ os.unlink(fname)
244
+
245
+ def test_multiline_adjlist_multidigraph(self):
246
+ G = self.XDG
247
+ (fd, fname) = tempfile.mkstemp()
248
+ nx.write_multiline_adjlist(G, fname)
249
+ H = nx.read_multiline_adjlist(
250
+ fname, nodetype=int, create_using=nx.MultiDiGraph()
251
+ )
252
+ H2 = nx.read_multiline_adjlist(
253
+ fname, nodetype=int, create_using=nx.MultiDiGraph()
254
+ )
255
+ assert H is not H2 # they should be different graphs
256
+ assert nodes_equal(list(H), list(G))
257
+ assert edges_equal(list(H.edges()), list(G.edges()))
258
+ os.close(fd)
259
+ os.unlink(fname)
260
+
261
+ def test_multiline_adjlist_delimiter(self):
262
+ fh = io.BytesIO()
263
+ G = nx.path_graph(3)
264
+ nx.write_multiline_adjlist(G, fh, delimiter=":")
265
+ fh.seek(0)
266
+ H = nx.read_multiline_adjlist(fh, nodetype=int, delimiter=":")
267
+ assert nodes_equal(list(H), list(G))
268
+ assert edges_equal(list(H.edges()), list(G.edges()))
shared/package-files/74/74ba44a36438f5d10c9a8d777f8f5a7381f2d738b1883b155de85acc125f8b9e/nonascii.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ # coding: iso-8859-5
2
+ # (Unlikely to be the default encoding for most testers.)
3
+ # ������������������� <- Cyrillic characters
4
+ u = "����"
shared/package-files/74/74bf2c9f2530363853404d854367570148d36e8117847d8939e850a2f1df8b17/type_fwd.h ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Licensed to the Apache Software Foundation (ASF) under one
2
+ // or more contributor license agreements. See the NOTICE file
3
+ // distributed with this work for additional information
4
+ // regarding copyright ownership. The ASF licenses this file
5
+ // to you under the Apache License, Version 2.0 (the
6
+ // "License"); you may not use this file except in compliance
7
+ // with the License. You may obtain a copy of the License at
8
+ //
9
+ // http://www.apache.org/licenses/LICENSE-2.0
10
+ //
11
+ // Unless required by applicable law or agreed to in writing,
12
+ // software distributed under the License is distributed on an
13
+ // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
+ // KIND, either express or implied. See the License for the
15
+ // specific language governing permissions and limitations
16
+ // under the License.
17
+
18
+ #pragma once
19
+
20
+ namespace parquet {
21
+
22
+ class Decryptor;
23
+ class Encryptor;
24
+
25
+ class InternalFileDecryptor;
26
+ class InternalFileEncryptor;
27
+
28
+ } // namespace parquet
shared/package-files/74/74cb5a1b5d641a526b8092601961036590269cefc77d3dcbe17f2923bd8b2c56/Boa_Vista ADDED
Binary file (618 Bytes). View file
 
shared/package-files/74/74d25b704e4e54363fc07c0dfd4054b5f211775dceaaef910443bbe20e52b010/scalar_byte.sav ADDED
Binary file (2.08 kB). View file
 
shared/package-files/74/74dfbdd489c7257280129e4310ebc2f1baa5ee71feac829ef373bc0d40f3d15a/bartlett_window_native.h ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from NativeFunction.h
4
+
5
+ #include <c10/core/Scalar.h>
6
+ #include <c10/core/Storage.h>
7
+ #include <c10/core/TensorOptions.h>
8
+ #include <c10/util/Deprecated.h>
9
+ #include <c10/util/Optional.h>
10
+ #include <c10/core/QScheme.h>
11
+ #include <ATen/core/Reduction.h>
12
+ #include <ATen/core/Tensor.h>
13
+ #include <tuple>
14
+ #include <vector>
15
+
16
+
17
+ namespace at {
18
+ namespace native {
19
+ TORCH_API at::Tensor bartlett_window(int64_t window_length, c10::optional<at::ScalarType> dtype={}, c10::optional<at::Layout> layout={}, c10::optional<at::Device> device={}, c10::optional<bool> pin_memory={});
20
+ TORCH_API at::Tensor & bartlett_window_out(int64_t window_length, at::Tensor & out);
21
+ TORCH_API at::Tensor bartlett_window(int64_t window_length, bool periodic, c10::optional<at::ScalarType> dtype={}, c10::optional<at::Layout> layout={}, c10::optional<at::Device> device={}, c10::optional<bool> pin_memory={});
22
+ TORCH_API at::Tensor & bartlett_window_periodic_out(int64_t window_length, bool periodic, at::Tensor & out);
23
+ } // namespace native
24
+ } // namespace at
shared/package-files/74/74e2d737140952e364e42db839d1c1aef4e603493ae640b9d73ddd0f98163b30/aaa-30-rv ADDED
Binary file (1.33 kB). View file
 
shared/package-files/74/74e2d737140952e364e42db839d1c1aef4e603493ae640b9d73ddd0f98163b30/aaa-rv ADDED
Binary file (1.33 kB). View file
 
shared/package-files/74/74f9be00518ea6c3d0a8651ec053f14fa9a337dbb1bcbde3a410f753bc970bc9/_ctc_loss_backward_cpu_dispatch.h ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ // @generated by torchgen/gen.py from DispatchKeyFunction.h
3
+
4
+ // NB: The implementing C++ file is RegisterDispatchKey.cpp
5
+
6
+ // The only #includes we need are for custom classes that have defaults in the C++ API
7
+ #include <c10/core/MemoryFormat.h>
8
+ #include <c10/core/Scalar.h>
9
+ #include <ATen/core/Reduction.h>
10
+
11
+ // Forward declarations of any types needed in the operator signatures.
12
+ // We can't directly include these classes because it will cause circular include dependencies.
13
+ // This file is included by TensorBody.h, which defines the Tensor class.
14
+ #include <ATen/core/ATen_fwd.h>
15
+
16
+ namespace at {
17
+
18
+ namespace cpu {
19
+
20
+ TORCH_API at::Tensor _ctc_loss_backward(const at::Tensor & grad, const at::Tensor & log_probs, const at::Tensor & targets, at::IntArrayRef input_lengths, at::IntArrayRef target_lengths, const at::Tensor & neg_log_likelihood, const at::Tensor & log_alpha, int64_t blank, bool zero_infinity=false);
21
+ TORCH_API at::Tensor _ctc_loss_backward(const at::Tensor & grad, const at::Tensor & log_probs, const at::Tensor & targets, const at::Tensor & input_lengths, const at::Tensor & target_lengths, const at::Tensor & neg_log_likelihood, const at::Tensor & log_alpha, int64_t blank, bool zero_infinity=false);
22
+
23
+ } // namespace cpu
24
+ } // namespace at
shared/package-files/7d/7d012c25bec6b3ff55abd574c47202074105c4d446cb1b9baf8c386459867316/__init__.py ADDED
@@ -0,0 +1,904 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import re
3
+ import abc
4
+ import csv
5
+ import sys
6
+ from .. import zipp
7
+ import email
8
+ import pathlib
9
+ import operator
10
+ import textwrap
11
+ import warnings
12
+ import functools
13
+ import itertools
14
+ import posixpath
15
+ import collections
16
+
17
+ from . import _adapters, _meta, _py39compat
18
+ from ._collections import FreezableDefaultDict, Pair
19
+ from ._compat import (
20
+ NullFinder,
21
+ install,
22
+ pypy_partial,
23
+ )
24
+ from ._functools import method_cache, pass_none
25
+ from ._itertools import always_iterable, unique_everseen
26
+ from ._meta import PackageMetadata, SimplePath
27
+
28
+ from contextlib import suppress
29
+ from importlib import import_module
30
+ from importlib.abc import MetaPathFinder
31
+ from itertools import starmap
32
+ from typing import List, Mapping, Optional
33
+
34
+
35
+ __all__ = [
36
+ 'Distribution',
37
+ 'DistributionFinder',
38
+ 'PackageMetadata',
39
+ 'PackageNotFoundError',
40
+ 'distribution',
41
+ 'distributions',
42
+ 'entry_points',
43
+ 'files',
44
+ 'metadata',
45
+ 'packages_distributions',
46
+ 'requires',
47
+ 'version',
48
+ ]
49
+
50
+
51
+ class PackageNotFoundError(ModuleNotFoundError):
52
+ """The package was not found."""
53
+
54
+ def __str__(self):
55
+ return f"No package metadata was found for {self.name}"
56
+
57
+ @property
58
+ def name(self):
59
+ (name,) = self.args
60
+ return name
61
+
62
+
63
+ class Sectioned:
64
+ """
65
+ A simple entry point config parser for performance
66
+
67
+ >>> for item in Sectioned.read(Sectioned._sample):
68
+ ... print(item)
69
+ Pair(name='sec1', value='# comments ignored')
70
+ Pair(name='sec1', value='a = 1')
71
+ Pair(name='sec1', value='b = 2')
72
+ Pair(name='sec2', value='a = 2')
73
+
74
+ >>> res = Sectioned.section_pairs(Sectioned._sample)
75
+ >>> item = next(res)
76
+ >>> item.name
77
+ 'sec1'
78
+ >>> item.value
79
+ Pair(name='a', value='1')
80
+ >>> item = next(res)
81
+ >>> item.value
82
+ Pair(name='b', value='2')
83
+ >>> item = next(res)
84
+ >>> item.name
85
+ 'sec2'
86
+ >>> item.value
87
+ Pair(name='a', value='2')
88
+ >>> list(res)
89
+ []
90
+ """
91
+
92
+ _sample = textwrap.dedent(
93
+ """
94
+ [sec1]
95
+ # comments ignored
96
+ a = 1
97
+ b = 2
98
+
99
+ [sec2]
100
+ a = 2
101
+ """
102
+ ).lstrip()
103
+
104
+ @classmethod
105
+ def section_pairs(cls, text):
106
+ return (
107
+ section._replace(value=Pair.parse(section.value))
108
+ for section in cls.read(text, filter_=cls.valid)
109
+ if section.name is not None
110
+ )
111
+
112
+ @staticmethod
113
+ def read(text, filter_=None):
114
+ lines = filter(filter_, map(str.strip, text.splitlines()))
115
+ name = None
116
+ for value in lines:
117
+ section_match = value.startswith('[') and value.endswith(']')
118
+ if section_match:
119
+ name = value.strip('[]')
120
+ continue
121
+ yield Pair(name, value)
122
+
123
+ @staticmethod
124
+ def valid(line):
125
+ return line and not line.startswith('#')
126
+
127
+
128
+ class DeprecatedTuple:
129
+ """
130
+ Provide subscript item access for backward compatibility.
131
+
132
+ >>> recwarn = getfixture('recwarn')
133
+ >>> ep = EntryPoint(name='name', value='value', group='group')
134
+ >>> ep[:]
135
+ ('name', 'value', 'group')
136
+ >>> ep[0]
137
+ 'name'
138
+ >>> len(recwarn)
139
+ 1
140
+ """
141
+
142
+ # Do not remove prior to 2023-05-01 or Python 3.13
143
+ _warn = functools.partial(
144
+ warnings.warn,
145
+ "EntryPoint tuple interface is deprecated. Access members by name.",
146
+ DeprecationWarning,
147
+ stacklevel=pypy_partial(2),
148
+ )
149
+
150
+ def __getitem__(self, item):
151
+ self._warn()
152
+ return self._key()[item]
153
+
154
+
155
+ class EntryPoint(DeprecatedTuple):
156
+ """An entry point as defined by Python packaging conventions.
157
+
158
+ See `the packaging docs on entry points
159
+ <https://packaging.python.org/specifications/entry-points/>`_
160
+ for more information.
161
+
162
+ >>> ep = EntryPoint(
163
+ ... name=None, group=None, value='package.module:attr [extra1, extra2]')
164
+ >>> ep.module
165
+ 'package.module'
166
+ >>> ep.attr
167
+ 'attr'
168
+ >>> ep.extras
169
+ ['extra1', 'extra2']
170
+ """
171
+
172
+ pattern = re.compile(
173
+ r'(?P<module>[\w.]+)\s*'
174
+ r'(:\s*(?P<attr>[\w.]+)\s*)?'
175
+ r'((?P<extras>\[.*\])\s*)?$'
176
+ )
177
+ """
178
+ A regular expression describing the syntax for an entry point,
179
+ which might look like:
180
+
181
+ - module
182
+ - package.module
183
+ - package.module:attribute
184
+ - package.module:object.attribute
185
+ - package.module:attr [extra1, extra2]
186
+
187
+ Other combinations are possible as well.
188
+
189
+ The expression is lenient about whitespace around the ':',
190
+ following the attr, and following any extras.
191
+ """
192
+
193
+ name: str
194
+ value: str
195
+ group: str
196
+
197
+ dist: Optional['Distribution'] = None
198
+
199
+ def __init__(self, name, value, group):
200
+ vars(self).update(name=name, value=value, group=group)
201
+
202
+ def load(self):
203
+ """Load the entry point from its definition. If only a module
204
+ is indicated by the value, return that module. Otherwise,
205
+ return the named object.
206
+ """
207
+ match = self.pattern.match(self.value)
208
+ module = import_module(match.group('module'))
209
+ attrs = filter(None, (match.group('attr') or '').split('.'))
210
+ return functools.reduce(getattr, attrs, module)
211
+
212
+ @property
213
+ def module(self):
214
+ match = self.pattern.match(self.value)
215
+ return match.group('module')
216
+
217
+ @property
218
+ def attr(self):
219
+ match = self.pattern.match(self.value)
220
+ return match.group('attr')
221
+
222
+ @property
223
+ def extras(self):
224
+ match = self.pattern.match(self.value)
225
+ return re.findall(r'\w+', match.group('extras') or '')
226
+
227
+ def _for(self, dist):
228
+ vars(self).update(dist=dist)
229
+ return self
230
+
231
+ def matches(self, **params):
232
+ """
233
+ EntryPoint matches the given parameters.
234
+
235
+ >>> ep = EntryPoint(group='foo', name='bar', value='bing:bong [extra1, extra2]')
236
+ >>> ep.matches(group='foo')
237
+ True
238
+ >>> ep.matches(name='bar', value='bing:bong [extra1, extra2]')
239
+ True
240
+ >>> ep.matches(group='foo', name='other')
241
+ False
242
+ >>> ep.matches()
243
+ True
244
+ >>> ep.matches(extras=['extra1', 'extra2'])
245
+ True
246
+ >>> ep.matches(module='bing')
247
+ True
248
+ >>> ep.matches(attr='bong')
249
+ True
250
+ """
251
+ attrs = (getattr(self, param) for param in params)
252
+ return all(map(operator.eq, params.values(), attrs))
253
+
254
+ def _key(self):
255
+ return self.name, self.value, self.group
256
+
257
+ def __lt__(self, other):
258
+ return self._key() < other._key()
259
+
260
+ def __eq__(self, other):
261
+ return self._key() == other._key()
262
+
263
+ def __setattr__(self, name, value):
264
+ raise AttributeError("EntryPoint objects are immutable.")
265
+
266
+ def __repr__(self):
267
+ return (
268
+ f'EntryPoint(name={self.name!r}, value={self.value!r}, '
269
+ f'group={self.group!r})'
270
+ )
271
+
272
+ def __hash__(self):
273
+ return hash(self._key())
274
+
275
+
276
+ class EntryPoints(tuple):
277
+ """
278
+ An immutable collection of selectable EntryPoint objects.
279
+ """
280
+
281
+ __slots__ = ()
282
+
283
+ def __getitem__(self, name): # -> EntryPoint:
284
+ """
285
+ Get the EntryPoint in self matching name.
286
+ """
287
+ try:
288
+ return next(iter(self.select(name=name)))
289
+ except StopIteration:
290
+ raise KeyError(name)
291
+
292
+ def select(self, **params):
293
+ """
294
+ Select entry points from self that match the
295
+ given parameters (typically group and/or name).
296
+ """
297
+ return EntryPoints(ep for ep in self if _py39compat.ep_matches(ep, **params))
298
+
299
+ @property
300
+ def names(self):
301
+ """
302
+ Return the set of all names of all entry points.
303
+ """
304
+ return {ep.name for ep in self}
305
+
306
+ @property
307
+ def groups(self):
308
+ """
309
+ Return the set of all groups of all entry points.
310
+ """
311
+ return {ep.group for ep in self}
312
+
313
+ @classmethod
314
+ def _from_text_for(cls, text, dist):
315
+ return cls(ep._for(dist) for ep in cls._from_text(text))
316
+
317
+ @staticmethod
318
+ def _from_text(text):
319
+ return (
320
+ EntryPoint(name=item.value.name, value=item.value.value, group=item.name)
321
+ for item in Sectioned.section_pairs(text or '')
322
+ )
323
+
324
+
325
+ class PackagePath(pathlib.PurePosixPath):
326
+ """A reference to a path in a package"""
327
+
328
+ def read_text(self, encoding='utf-8'):
329
+ with self.locate().open(encoding=encoding) as stream:
330
+ return stream.read()
331
+
332
+ def read_binary(self):
333
+ with self.locate().open('rb') as stream:
334
+ return stream.read()
335
+
336
+ def locate(self):
337
+ """Return a path-like object for this path"""
338
+ return self.dist.locate_file(self)
339
+
340
+
341
+ class FileHash:
342
+ def __init__(self, spec):
343
+ self.mode, _, self.value = spec.partition('=')
344
+
345
+ def __repr__(self):
346
+ return f'<FileHash mode: {self.mode} value: {self.value}>'
347
+
348
+
349
+ class Distribution(metaclass=abc.ABCMeta):
350
+ """A Python distribution package."""
351
+
352
+ @abc.abstractmethod
353
+ def read_text(self, filename):
354
+ """Attempt to load metadata file given by the name.
355
+
356
+ :param filename: The name of the file in the distribution info.
357
+ :return: The text if found, otherwise None.
358
+ """
359
+
360
+ @abc.abstractmethod
361
+ def locate_file(self, path):
362
+ """
363
+ Given a path to a file in this distribution, return a path
364
+ to it.
365
+ """
366
+
367
+ @classmethod
368
+ def from_name(cls, name: str):
369
+ """Return the Distribution for the given package name.
370
+
371
+ :param name: The name of the distribution package to search for.
372
+ :return: The Distribution instance (or subclass thereof) for the named
373
+ package, if found.
374
+ :raises PackageNotFoundError: When the named package's distribution
375
+ metadata cannot be found.
376
+ :raises ValueError: When an invalid value is supplied for name.
377
+ """
378
+ if not name:
379
+ raise ValueError("A distribution name is required.")
380
+ try:
381
+ return next(cls.discover(name=name))
382
+ except StopIteration:
383
+ raise PackageNotFoundError(name)
384
+
385
+ @classmethod
386
+ def discover(cls, **kwargs):
387
+ """Return an iterable of Distribution objects for all packages.
388
+
389
+ Pass a ``context`` or pass keyword arguments for constructing
390
+ a context.
391
+
392
+ :context: A ``DistributionFinder.Context`` object.
393
+ :return: Iterable of Distribution objects for all packages.
394
+ """
395
+ context = kwargs.pop('context', None)
396
+ if context and kwargs:
397
+ raise ValueError("cannot accept context and kwargs")
398
+ context = context or DistributionFinder.Context(**kwargs)
399
+ return itertools.chain.from_iterable(
400
+ resolver(context) for resolver in cls._discover_resolvers()
401
+ )
402
+
403
+ @staticmethod
404
+ def at(path):
405
+ """Return a Distribution for the indicated metadata path
406
+
407
+ :param path: a string or path-like object
408
+ :return: a concrete Distribution instance for the path
409
+ """
410
+ return PathDistribution(pathlib.Path(path))
411
+
412
+ @staticmethod
413
+ def _discover_resolvers():
414
+ """Search the meta_path for resolvers."""
415
+ declared = (
416
+ getattr(finder, 'find_distributions', None) for finder in sys.meta_path
417
+ )
418
+ return filter(None, declared)
419
+
420
+ @property
421
+ def metadata(self) -> _meta.PackageMetadata:
422
+ """Return the parsed metadata for this Distribution.
423
+
424
+ The returned object will have keys that name the various bits of
425
+ metadata. See PEP 566 for details.
426
+ """
427
+ text = (
428
+ self.read_text('METADATA')
429
+ or self.read_text('PKG-INFO')
430
+ # This last clause is here to support old egg-info files. Its
431
+ # effect is to just end up using the PathDistribution's self._path
432
+ # (which points to the egg-info file) attribute unchanged.
433
+ or self.read_text('')
434
+ )
435
+ return _adapters.Message(email.message_from_string(text))
436
+
437
+ @property
438
+ def name(self):
439
+ """Return the 'Name' metadata for the distribution package."""
440
+ return self.metadata['Name']
441
+
442
+ @property
443
+ def _normalized_name(self):
444
+ """Return a normalized version of the name."""
445
+ return Prepared.normalize(self.name)
446
+
447
+ @property
448
+ def version(self):
449
+ """Return the 'Version' metadata for the distribution package."""
450
+ return self.metadata['Version']
451
+
452
+ @property
453
+ def entry_points(self):
454
+ return EntryPoints._from_text_for(self.read_text('entry_points.txt'), self)
455
+
456
+ @property
457
+ def files(self):
458
+ """Files in this distribution.
459
+
460
+ :return: List of PackagePath for this distribution or None
461
+
462
+ Result is `None` if the metadata file that enumerates files
463
+ (i.e. RECORD for dist-info or SOURCES.txt for egg-info) is
464
+ missing.
465
+ Result may be empty if the metadata exists but is empty.
466
+ """
467
+
468
+ def make_file(name, hash=None, size_str=None):
469
+ result = PackagePath(name)
470
+ result.hash = FileHash(hash) if hash else None
471
+ result.size = int(size_str) if size_str else None
472
+ result.dist = self
473
+ return result
474
+
475
+ @pass_none
476
+ def make_files(lines):
477
+ return list(starmap(make_file, csv.reader(lines)))
478
+
479
+ return make_files(self._read_files_distinfo() or self._read_files_egginfo())
480
+
481
+ def _read_files_distinfo(self):
482
+ """
483
+ Read the lines of RECORD
484
+ """
485
+ text = self.read_text('RECORD')
486
+ return text and text.splitlines()
487
+
488
+ def _read_files_egginfo(self):
489
+ """
490
+ SOURCES.txt might contain literal commas, so wrap each line
491
+ in quotes.
492
+ """
493
+ text = self.read_text('SOURCES.txt')
494
+ return text and map('"{}"'.format, text.splitlines())
495
+
496
+ @property
497
+ def requires(self):
498
+ """Generated requirements specified for this Distribution"""
499
+ reqs = self._read_dist_info_reqs() or self._read_egg_info_reqs()
500
+ return reqs and list(reqs)
501
+
502
+ def _read_dist_info_reqs(self):
503
+ return self.metadata.get_all('Requires-Dist')
504
+
505
+ def _read_egg_info_reqs(self):
506
+ source = self.read_text('requires.txt')
507
+ return pass_none(self._deps_from_requires_text)(source)
508
+
509
+ @classmethod
510
+ def _deps_from_requires_text(cls, source):
511
+ return cls._convert_egg_info_reqs_to_simple_reqs(Sectioned.read(source))
512
+
513
+ @staticmethod
514
+ def _convert_egg_info_reqs_to_simple_reqs(sections):
515
+ """
516
+ Historically, setuptools would solicit and store 'extra'
517
+ requirements, including those with environment markers,
518
+ in separate sections. More modern tools expect each
519
+ dependency to be defined separately, with any relevant
520
+ extras and environment markers attached directly to that
521
+ requirement. This method converts the former to the
522
+ latter. See _test_deps_from_requires_text for an example.
523
+ """
524
+
525
+ def make_condition(name):
526
+ return name and f'extra == "{name}"'
527
+
528
+ def quoted_marker(section):
529
+ section = section or ''
530
+ extra, sep, markers = section.partition(':')
531
+ if extra and markers:
532
+ markers = f'({markers})'
533
+ conditions = list(filter(None, [markers, make_condition(extra)]))
534
+ return '; ' + ' and '.join(conditions) if conditions else ''
535
+
536
+ def url_req_space(req):
537
+ """
538
+ PEP 508 requires a space between the url_spec and the quoted_marker.
539
+ Ref python/importlib_metadata#357.
540
+ """
541
+ # '@' is uniquely indicative of a url_req.
542
+ return ' ' * ('@' in req)
543
+
544
+ for section in sections:
545
+ space = url_req_space(section.value)
546
+ yield section.value + space + quoted_marker(section.name)
547
+
548
+
549
+ class DistributionFinder(MetaPathFinder):
550
+ """
551
+ A MetaPathFinder capable of discovering installed distributions.
552
+ """
553
+
554
+ class Context:
555
+ """
556
+ Keyword arguments presented by the caller to
557
+ ``distributions()`` or ``Distribution.discover()``
558
+ to narrow the scope of a search for distributions
559
+ in all DistributionFinders.
560
+
561
+ Each DistributionFinder may expect any parameters
562
+ and should attempt to honor the canonical
563
+ parameters defined below when appropriate.
564
+ """
565
+
566
+ name = None
567
+ """
568
+ Specific name for which a distribution finder should match.
569
+ A name of ``None`` matches all distributions.
570
+ """
571
+
572
+ def __init__(self, **kwargs):
573
+ vars(self).update(kwargs)
574
+
575
+ @property
576
+ def path(self):
577
+ """
578
+ The sequence of directory path that a distribution finder
579
+ should search.
580
+
581
+ Typically refers to Python installed package paths such as
582
+ "site-packages" directories and defaults to ``sys.path``.
583
+ """
584
+ return vars(self).get('path', sys.path)
585
+
586
+ @abc.abstractmethod
587
+ def find_distributions(self, context=Context()):
588
+ """
589
+ Find distributions.
590
+
591
+ Return an iterable of all Distribution instances capable of
592
+ loading the metadata for packages matching the ``context``,
593
+ a DistributionFinder.Context instance.
594
+ """
595
+
596
+
597
+ class FastPath:
598
+ """
599
+ Micro-optimized class for searching a path for
600
+ children.
601
+
602
+ >>> FastPath('').children()
603
+ ['...']
604
+ """
605
+
606
+ @functools.lru_cache() # type: ignore
607
+ def __new__(cls, root):
608
+ return super().__new__(cls)
609
+
610
+ def __init__(self, root):
611
+ self.root = root
612
+
613
+ def joinpath(self, child):
614
+ return pathlib.Path(self.root, child)
615
+
616
+ def children(self):
617
+ with suppress(Exception):
618
+ return os.listdir(self.root or '.')
619
+ with suppress(Exception):
620
+ return self.zip_children()
621
+ return []
622
+
623
+ def zip_children(self):
624
+ zip_path = zipp.Path(self.root)
625
+ names = zip_path.root.namelist()
626
+ self.joinpath = zip_path.joinpath
627
+
628
+ return dict.fromkeys(child.split(posixpath.sep, 1)[0] for child in names)
629
+
630
+ def search(self, name):
631
+ return self.lookup(self.mtime).search(name)
632
+
633
+ @property
634
+ def mtime(self):
635
+ with suppress(OSError):
636
+ return os.stat(self.root).st_mtime
637
+ self.lookup.cache_clear()
638
+
639
+ @method_cache
640
+ def lookup(self, mtime):
641
+ return Lookup(self)
642
+
643
+
644
+ class Lookup:
645
+ def __init__(self, path: FastPath):
646
+ base = os.path.basename(path.root).lower()
647
+ base_is_egg = base.endswith(".egg")
648
+ self.infos = FreezableDefaultDict(list)
649
+ self.eggs = FreezableDefaultDict(list)
650
+
651
+ for child in path.children():
652
+ low = child.lower()
653
+ if low.endswith((".dist-info", ".egg-info")):
654
+ # rpartition is faster than splitext and suitable for this purpose.
655
+ name = low.rpartition(".")[0].partition("-")[0]
656
+ normalized = Prepared.normalize(name)
657
+ self.infos[normalized].append(path.joinpath(child))
658
+ elif base_is_egg and low == "egg-info":
659
+ name = base.rpartition(".")[0].partition("-")[0]
660
+ legacy_normalized = Prepared.legacy_normalize(name)
661
+ self.eggs[legacy_normalized].append(path.joinpath(child))
662
+
663
+ self.infos.freeze()
664
+ self.eggs.freeze()
665
+
666
+ def search(self, prepared):
667
+ infos = (
668
+ self.infos[prepared.normalized]
669
+ if prepared
670
+ else itertools.chain.from_iterable(self.infos.values())
671
+ )
672
+ eggs = (
673
+ self.eggs[prepared.legacy_normalized]
674
+ if prepared
675
+ else itertools.chain.from_iterable(self.eggs.values())
676
+ )
677
+ return itertools.chain(infos, eggs)
678
+
679
+
680
+ class Prepared:
681
+ """
682
+ A prepared search for metadata on a possibly-named package.
683
+ """
684
+
685
+ normalized = None
686
+ legacy_normalized = None
687
+
688
+ def __init__(self, name):
689
+ self.name = name
690
+ if name is None:
691
+ return
692
+ self.normalized = self.normalize(name)
693
+ self.legacy_normalized = self.legacy_normalize(name)
694
+
695
+ @staticmethod
696
+ def normalize(name):
697
+ """
698
+ PEP 503 normalization plus dashes as underscores.
699
+ """
700
+ return re.sub(r"[-_.]+", "-", name).lower().replace('-', '_')
701
+
702
+ @staticmethod
703
+ def legacy_normalize(name):
704
+ """
705
+ Normalize the package name as found in the convention in
706
+ older packaging tools versions and specs.
707
+ """
708
+ return name.lower().replace('-', '_')
709
+
710
+ def __bool__(self):
711
+ return bool(self.name)
712
+
713
+
714
+ @install
715
+ class MetadataPathFinder(NullFinder, DistributionFinder):
716
+ """A degenerate finder for distribution packages on the file system.
717
+
718
+ This finder supplies only a find_distributions() method for versions
719
+ of Python that do not have a PathFinder find_distributions().
720
+ """
721
+
722
+ def find_distributions(self, context=DistributionFinder.Context()):
723
+ """
724
+ Find distributions.
725
+
726
+ Return an iterable of all Distribution instances capable of
727
+ loading the metadata for packages matching ``context.name``
728
+ (or all names if ``None`` indicated) along the paths in the list
729
+ of directories ``context.path``.
730
+ """
731
+ found = self._search_paths(context.name, context.path)
732
+ return map(PathDistribution, found)
733
+
734
+ @classmethod
735
+ def _search_paths(cls, name, paths):
736
+ """Find metadata directories in paths heuristically."""
737
+ prepared = Prepared(name)
738
+ return itertools.chain.from_iterable(
739
+ path.search(prepared) for path in map(FastPath, paths)
740
+ )
741
+
742
+ def invalidate_caches(cls):
743
+ FastPath.__new__.cache_clear()
744
+
745
+
746
+ class PathDistribution(Distribution):
747
+ def __init__(self, path: SimplePath):
748
+ """Construct a distribution.
749
+
750
+ :param path: SimplePath indicating the metadata directory.
751
+ """
752
+ self._path = path
753
+
754
+ def read_text(self, filename):
755
+ with suppress(
756
+ FileNotFoundError,
757
+ IsADirectoryError,
758
+ KeyError,
759
+ NotADirectoryError,
760
+ PermissionError,
761
+ ):
762
+ return self._path.joinpath(filename).read_text(encoding='utf-8')
763
+
764
+ read_text.__doc__ = Distribution.read_text.__doc__
765
+
766
+ def locate_file(self, path):
767
+ return self._path.parent / path
768
+
769
+ @property
770
+ def _normalized_name(self):
771
+ """
772
+ Performance optimization: where possible, resolve the
773
+ normalized name from the file system path.
774
+ """
775
+ stem = os.path.basename(str(self._path))
776
+ return (
777
+ pass_none(Prepared.normalize)(self._name_from_stem(stem))
778
+ or super()._normalized_name
779
+ )
780
+
781
+ @staticmethod
782
+ def _name_from_stem(stem):
783
+ """
784
+ >>> PathDistribution._name_from_stem('foo-3.0.egg-info')
785
+ 'foo'
786
+ >>> PathDistribution._name_from_stem('CherryPy-3.0.dist-info')
787
+ 'CherryPy'
788
+ >>> PathDistribution._name_from_stem('face.egg-info')
789
+ 'face'
790
+ >>> PathDistribution._name_from_stem('foo.bar')
791
+ """
792
+ filename, ext = os.path.splitext(stem)
793
+ if ext not in ('.dist-info', '.egg-info'):
794
+ return
795
+ name, sep, rest = filename.partition('-')
796
+ return name
797
+
798
+
799
+ def distribution(distribution_name):
800
+ """Get the ``Distribution`` instance for the named package.
801
+
802
+ :param distribution_name: The name of the distribution package as a string.
803
+ :return: A ``Distribution`` instance (or subclass thereof).
804
+ """
805
+ return Distribution.from_name(distribution_name)
806
+
807
+
808
+ def distributions(**kwargs):
809
+ """Get all ``Distribution`` instances in the current environment.
810
+
811
+ :return: An iterable of ``Distribution`` instances.
812
+ """
813
+ return Distribution.discover(**kwargs)
814
+
815
+
816
+ def metadata(distribution_name) -> _meta.PackageMetadata:
817
+ """Get the metadata for the named package.
818
+
819
+ :param distribution_name: The name of the distribution package to query.
820
+ :return: A PackageMetadata containing the parsed metadata.
821
+ """
822
+ return Distribution.from_name(distribution_name).metadata
823
+
824
+
825
+ def version(distribution_name):
826
+ """Get the version string for the named package.
827
+
828
+ :param distribution_name: The name of the distribution package to query.
829
+ :return: The version string for the package as defined in the package's
830
+ "Version" metadata key.
831
+ """
832
+ return distribution(distribution_name).version
833
+
834
+
835
+ _unique = functools.partial(
836
+ unique_everseen,
837
+ key=_py39compat.normalized_name,
838
+ )
839
+ """
840
+ Wrapper for ``distributions`` to return unique distributions by name.
841
+ """
842
+
843
+
844
+ def entry_points(**params) -> EntryPoints:
845
+ """Return EntryPoint objects for all installed packages.
846
+
847
+ Pass selection parameters (group or name) to filter the
848
+ result to entry points matching those properties (see
849
+ EntryPoints.select()).
850
+
851
+ :return: EntryPoints for all installed packages.
852
+ """
853
+ eps = itertools.chain.from_iterable(
854
+ dist.entry_points for dist in _unique(distributions())
855
+ )
856
+ return EntryPoints(eps).select(**params)
857
+
858
+
859
+ def files(distribution_name):
860
+ """Return a list of files for the named package.
861
+
862
+ :param distribution_name: The name of the distribution package to query.
863
+ :return: List of files composing the distribution.
864
+ """
865
+ return distribution(distribution_name).files
866
+
867
+
868
+ def requires(distribution_name):
869
+ """
870
+ Return a list of requirements for the named package.
871
+
872
+ :return: An iterator of requirements, suitable for
873
+ packaging.requirement.Requirement.
874
+ """
875
+ return distribution(distribution_name).requires
876
+
877
+
878
+ def packages_distributions() -> Mapping[str, List[str]]:
879
+ """
880
+ Return a mapping of top-level packages to their
881
+ distributions.
882
+
883
+ >>> import collections.abc
884
+ >>> pkgs = packages_distributions()
885
+ >>> all(isinstance(dist, collections.abc.Sequence) for dist in pkgs.values())
886
+ True
887
+ """
888
+ pkg_to_dist = collections.defaultdict(list)
889
+ for dist in distributions():
890
+ for pkg in _top_level_declared(dist) or _top_level_inferred(dist):
891
+ pkg_to_dist[pkg].append(dist.metadata['Name'])
892
+ return dict(pkg_to_dist)
893
+
894
+
895
+ def _top_level_declared(dist):
896
+ return (dist.read_text('top_level.txt') or '').split()
897
+
898
+
899
+ def _top_level_inferred(dist):
900
+ return {
901
+ f.parts[0] if len(f.parts) > 1 else f.with_suffix('').name
902
+ for f in always_iterable(dist.files)
903
+ if f.suffix == ".py"
904
+ }
shared/package-files/7d/7d02875b6c4be3248997fbfbfc675fc4203a743c230c631d37b02ae9fd84422e/minix-1.5 ADDED
Binary file (607 Bytes). View file
 
shared/package-files/7d/7d02875b6c4be3248997fbfbfc675fc4203a743c230c631d37b02ae9fd84422e/minix-old ADDED
Binary file (607 Bytes). View file