


import asyncio
import os
import re
import sys
import tempfile
import unittest
from contextlib import contextmanager
from copy import deepcopy
from distutils.util import strtobool
from enum import Enum
from importlib.util import find_spec
from pathlib import Path
from unittest.mock import patch

import pyarrow as pa
import pytest
import requests
from packaging import version

from datasets import config


if config.PY_VERSION < version.parse("3.8"):
			import importlib_metadata
else:
			import importlib.metadata as importlib_metadata







def        lowerCAmelCase_  (      __lowerCamelCase							,			__lowerCamelCase=False			):
							try:
														__snake_case	:    List[str]											=     os.environ[key]
							except KeyError:
														# KEY isn't set, default to `default`.
														__snake_case	:    Optional[int]											=     default
							else:
														# KEY is set, convert it to True or False.
														try:
																					__snake_case	:    str											=     strtobool(__lowerCamelCase			)
														except ValueError:
																					# More values are supported, but let's keep the message simple.
																					raise ValueError(F'If set, {key} must be yes or no.'			)
							return _value


_snake_case  :	Dict			      =       parse_flag_from_env("RUN_SLOW", default=False)
_snake_case  :	Tuple			      =       parse_flag_from_env("RUN_REMOTE", default=False)
_snake_case  :	int			      =       parse_flag_from_env("RUN_LOCAL", default=True)
_snake_case  :	Optional[int]			      =       parse_flag_from_env("RUN_PACKAGED", default=True)

# Compression
_snake_case  :	str			      =       pytest.mark.skipif(not config.LZ4_AVAILABLE, reason="test requires lz4")
_snake_case  :	Dict			      =       pytest.mark.skipif(not config.PY7ZR_AVAILABLE, reason="test requires py7zr")
_snake_case  :	Dict			      =       pytest.mark.skipif(not config.ZSTANDARD_AVAILABLE, reason="test requires zstandard")

# Audio
_snake_case  :	Optional[Any]			      =       pytest.mark.skipif(
    # On Windows and OS X, soundfile installs sndfile
    find_spec("soundfile") is None or version.parse(importlib_metadata.version("soundfile")) < version.parse("0.12.0"),
    reason="test requires sndfile>=0.12.1: 'pip install \"soundfile>=0.12.1\"'; ",
)

# Beam
_snake_case  :	Optional[Any]			      =       pytest.mark.skipif(
    not config.BEAM_AVAILABLE or config.DILL_VERSION >= version.parse("0.3.2"),
    reason="test requires apache-beam and a compatible dill version",
)

# Dill-cloudpickle compatibility
_snake_case  :	Optional[Any]			      =       pytest.mark.skipif(
    config.DILL_VERSION <= version.parse("0.3.2"),
    reason="test requires dill>0.3.2 for cloudpickle compatibility",
)

# Windows
_snake_case  :	int			      =       pytest.mark.skipif(
    sys.platform == "win32",
    reason="test should not be run on Windows",
)







def        lowerCAmelCase_  (      __lowerCamelCase			):
							try:
														import faiss  # noqa
							except ImportError:
														__snake_case	:    Dict											=     unittest.skip("test requires faiss"			)(__lowerCamelCase			)
							return test_case







def        lowerCAmelCase_  (      __lowerCamelCase			):
							try:
														import regex  # noqa
							except ImportError:
														__snake_case	:    Any											=     unittest.skip("test requires regex"			)(__lowerCamelCase			)
							return test_case







def        lowerCAmelCase_  (      __lowerCamelCase			):
							try:
														import elasticsearch  # noqa
							except ImportError:
														__snake_case	:    Optional[int]											=     unittest.skip("test requires elasticsearch"			)(__lowerCamelCase			)
							return test_case







def        lowerCAmelCase_  (      __lowerCamelCase			):
							try:
														import sqlalchemy  # noqa
							except ImportError:
														__snake_case	:    List[Any]											=     unittest.skip("test requires sqlalchemy"			)(__lowerCamelCase			)
							return test_case







def        lowerCAmelCase_  (      __lowerCamelCase			):
							if not config.TORCH_AVAILABLE:
														__snake_case	:    Optional[Any]											=     unittest.skip("test requires PyTorch"			)(__lowerCamelCase			)
							return test_case







def        lowerCAmelCase_  (      __lowerCamelCase			):
							if not config.TF_AVAILABLE:
														__snake_case	:    Optional[int]											=     unittest.skip("test requires TensorFlow"			)(__lowerCamelCase			)
							return test_case







def        lowerCAmelCase_  (      __lowerCamelCase			):
							if not config.JAX_AVAILABLE:
														__snake_case	:    Optional[int]											=     unittest.skip("test requires JAX"			)(__lowerCamelCase			)
							return test_case







def        lowerCAmelCase_  (      __lowerCamelCase			):
							if not config.PIL_AVAILABLE:
														__snake_case	:    Any											=     unittest.skip("test requires Pillow"			)(__lowerCamelCase			)
							return test_case







def        lowerCAmelCase_  (      __lowerCamelCase			):
							try:
														import transformers  # noqa F401
							except ImportError:
														return unittest.skip("test requires transformers"			)(__lowerCamelCase			)
							else:
														return test_case







def        lowerCAmelCase_  (      __lowerCamelCase			):
							try:
														import tiktoken  # noqa F401
							except ImportError:
														return unittest.skip("test requires tiktoken"			)(__lowerCamelCase			)
							else:
														return test_case







def        lowerCAmelCase_  (      __lowerCamelCase			):
							try:
														import spacy  # noqa F401
							except ImportError:
														return unittest.skip("test requires spacy"			)(__lowerCamelCase			)
							else:
														return test_case







def        lowerCAmelCase_  (      __lowerCamelCase			):

							def _require_spacy_model(__lowerCamelCase			):
														try:
																					import spacy  # noqa F401

																					spacy.load(__lowerCamelCase			)
														except ImportError:
																					return unittest.skip("test requires spacy"			)(__lowerCamelCase			)
														except OSError:
																					return unittest.skip("test requires spacy model '{}'".format(__lowerCamelCase			)			)(__lowerCamelCase			)
														else:
																					return test_case

							return _require_spacy_model







def        lowerCAmelCase_  (      __lowerCamelCase			):
							try:
														import pyspark  # noqa F401
							except ImportError:
														return unittest.skip("test requires pyspark"			)(__lowerCamelCase			)
							else:
														return test_case







def        lowerCAmelCase_  (      __lowerCamelCase			):
							try:
														import joblibspark  # noqa F401
							except ImportError:
														return unittest.skip("test requires joblibspark"			)(__lowerCamelCase			)
							else:
														return test_case







def        lowerCAmelCase_  (      __lowerCamelCase			):
							if not _run_slow_tests or _run_slow_tests == 0:
														__snake_case	:    Dict											=     unittest.skip("test is slow"			)(__lowerCamelCase			)
							return test_case







def        lowerCAmelCase_  (      __lowerCamelCase			):
							if not _run_local_tests or _run_local_tests == 0:
														__snake_case	:    int											=     unittest.skip("test is local"			)(__lowerCamelCase			)
							return test_case







def        lowerCAmelCase_  (      __lowerCamelCase			):
							if not _run_packaged_tests or _run_packaged_tests == 0:
														__snake_case	:    Optional[int]											=     unittest.skip("test is packaged"			)(__lowerCamelCase			)
							return test_case







def        lowerCAmelCase_  (      __lowerCamelCase			):
							if not _run_remote_tests or _run_remote_tests == 0:
														__snake_case	:    str											=     unittest.skip("test requires remote"			)(__lowerCamelCase			)
							return test_case







def        lowerCAmelCase_  (      *__lowerCamelCase			):
							def decorate(cls			):
														for name, fn in cls.__dict__.items():
																					if callable(__lowerCamelCase			) and name.startswith("test"			):
																												for decorator in decorators:
																																			__snake_case	:    Dict											=     decorator(__lowerCamelCase			)
																												setattr(cls							,			__lowerCamelCase							,			__lowerCamelCase			)
														return cls

							return decorate

class        a	(_lowerCAmelCase   ):




							"""simple docstring"""


							pass

class        a	(_lowerCAmelCase   ):




							"""simple docstring"""


							__UpperCAmelCase					:							Optional[int]  						=						0
							__UpperCAmelCase					:							Dict  						=						1
							__UpperCAmelCase					:							str  						=						2







@contextmanager
def        lowerCAmelCase_  (      __lowerCamelCase=OfflineSimulationMode.CONNECTION_FAILS							,			__lowerCamelCase=1e-16			):
							__snake_case	:    Tuple											=     requests.Session().request

							def timeout_request(__lowerCamelCase							,			__lowerCamelCase							,			__lowerCamelCase							,			**__lowerCamelCase			):
														# Change the url to an invalid url so that the connection hangs
														__snake_case	:    Optional[Any]											=     "https://10.255.255.1"
														if kwargs.get("timeout"			) is None:
																					raise RequestWouldHangIndefinitelyError(
																					    F'Tried a call to {url} in offline mode with no timeout set. Please set a timeout.'			)
														__snake_case	:    str											=     timeout
														try:
																					return online_request(__lowerCamelCase							,			__lowerCamelCase							,			**__lowerCamelCase			)
														except Exception as e:
																					# The following changes in the error are just here to make the offline timeout error prettier
																					__snake_case	:    Dict											=     url
																					__snake_case	:    Optional[int]											=     e.args[0]
																					__snake_case	:    Tuple											=     (max_retry_error.args[0].replace("10.255.255.1"							,			F'OfflineMock[{url}]'			),)
																					__snake_case	:    Union[str, Any]											=     (max_retry_error,)
																					raise

							def raise_connection_error(__lowerCamelCase							,			__lowerCamelCase							,			**__lowerCamelCase			):
														raise requests.ConnectionError("Offline mode is enabled."							,			request=__lowerCamelCase			)

							if mode is OfflineSimulationMode.CONNECTION_FAILS:
														with patch("requests.Session.send"							,			__lowerCamelCase			):
																					yield
							elif mode is OfflineSimulationMode.CONNECTION_TIMES_OUT:
														# inspired from https://stackoverflow.com/a/904609
														with patch("requests.Session.request"							,			__lowerCamelCase			):
																					yield
							elif mode is OfflineSimulationMode.HF_DATASETS_OFFLINE_SET_TO_1:
														with patch("datasets.config.HF_DATASETS_OFFLINE"							,			__lowerCamelCase			):
																					yield
							else:
														raise ValueError("Please use a value from the OfflineSimulationMode enum."			)







@contextmanager
def        lowerCAmelCase_  (      *__lowerCamelCase							,			**__lowerCamelCase			):
							__snake_case	:    str											=     str(Path().resolve()			)
							with tempfile.TemporaryDirectory(*__lowerCamelCase							,			**__lowerCamelCase			) as tmp_dir:
														try:
																					os.chdir(__lowerCamelCase			)
																					yield
														finally:
																					os.chdir(__lowerCamelCase			)







@contextmanager
def        lowerCAmelCase_  (      ):
							import gc

							gc.collect()
							__snake_case	:    Optional[int]											=     pa.total_allocated_bytes()
							yield
							assert pa.total_allocated_bytes() - previous_allocated_memory > 0, "Arrow memory didn't increase."







@contextmanager
def        lowerCAmelCase_  (      ):
							import gc

							gc.collect()
							__snake_case	:    int											=     pa.total_allocated_bytes()
							yield
							assert pa.total_allocated_bytes() - previous_allocated_memory <= 0, "Arrow memory wasn't expected to increase."







def        lowerCAmelCase_  (      __lowerCamelCase							,			__lowerCamelCase			):
							return deepcopy(__lowerCamelCase			).integers(0							,			1_0_0							,			1_0			).tolist() == deepcopy(__lowerCamelCase			).integers(0							,			1_0_0							,			1_0			).tolist()







def        lowerCAmelCase_  (      __lowerCamelCase			):
							import decorator
							from requests.exceptions import HTTPError

							def _wrapper(__lowerCamelCase							,			*__lowerCamelCase							,			**__lowerCamelCase			):
														try:
																					return func(*__lowerCamelCase							,			**__lowerCamelCase			)
														except HTTPError as err:
																					if str(__lowerCamelCase			).startswith("500"			) or str(__lowerCamelCase			).startswith("502"			):
																												pytest.xfail(str(__lowerCamelCase			)			)
																					raise err

							return decorator.decorator(_wrapper							,			__lowerCamelCase			)

class        a	:




							"""simple docstring"""


							def __init__(							self :						Optional[int]					,			lowerCamelCase :						Optional[int]					,			lowerCamelCase :						Tuple					,			lowerCamelCase :						List[Any]       )			->					int:
														__snake_case	:    Optional[int]											=     returncode
														__snake_case	:    List[str]											=     stdout
														__snake_case	:    Union[str, Any]											=     stderr







async def        lowerCAmelCase_  (      __lowerCamelCase							,			__lowerCamelCase			):
							while True:
														__snake_case	:    Tuple											=     await stream.readline()
														if line:
																					callback(__lowerCamelCase			)
														else:
																					break







async def        lowerCAmelCase_  (      __lowerCamelCase							,			__lowerCamelCase=None							,			__lowerCamelCase=None							,			__lowerCamelCase=None							,			__lowerCamelCase=False							,			__lowerCamelCase=False			):
							if echo:
														print("\nRunning: "							,			" ".join(__lowerCamelCase			)			)

							__snake_case	:    str											=     await asyncio.create_subprocess_exec(
							    cmd[0]							,			*cmd[1:]							,			stdin=__lowerCamelCase							,			stdout=asyncio.subprocess.PIPE							,			stderr=asyncio.subprocess.PIPE							,			env=__lowerCamelCase							,			)

							# note: there is a warning for a possible deadlock when using `wait` with huge amounts of data in the pipe
							# https://docs.python.org/3/library/asyncio-subprocess.html#asyncio.asyncio.subprocess.Process.wait
							#
							# If it starts hanging, will need to switch to the following code. The problem is that no data
							# will be seen until it's done and if it hangs for example there will be no debug info.
							# out, err = await p.communicate()
							# return _RunOutput(p.returncode, out, err)

							__snake_case	:    Optional[Any]											=     []
							__snake_case	:    Optional[int]											=     []

							def tee(__lowerCamelCase							,			__lowerCamelCase							,			__lowerCamelCase							,			__lowerCamelCase=""			):
														__snake_case	:    str											=     line.decode("utf-8"			).rstrip()
														sink.append(__lowerCamelCase			)
														if not quiet:
																					print(__lowerCamelCase							,			__lowerCamelCase							,			file=__lowerCamelCase			)

    # XXX: the timeout doesn't seem to make any difference here
							await asyncio.wait(
							    [
							        _read_stream(p.stdout							,			lambda __lowerCamelCase			: tee(__lowerCamelCase							,			__lowerCamelCase							,			sys.stdout							,			label="stdout:"			)			),
							        _read_stream(p.stderr							,			lambda __lowerCamelCase			: tee(__lowerCamelCase							,			__lowerCamelCase							,			sys.stderr							,			label="stderr:"			)			),
							    ]							,			timeout=__lowerCamelCase							,			)
							return _RunOutput(await p.wait()							,			__lowerCamelCase							,			__lowerCamelCase			)







def        lowerCAmelCase_  (      __lowerCamelCase							,			__lowerCamelCase=None							,			__lowerCamelCase=None							,			__lowerCamelCase=1_8_0							,			__lowerCamelCase=False							,			__lowerCamelCase=True			):
							__snake_case	:    List[str]											=     asyncio.get_event_loop()
							__snake_case	:    int											=     loop.run_until_complete(
							    _stream_subprocess(__lowerCamelCase							,			env=__lowerCamelCase							,			stdin=__lowerCamelCase							,			timeout=__lowerCamelCase							,			quiet=__lowerCamelCase							,			echo=__lowerCamelCase			)			)

							__snake_case	:    Union[str, Any]											=     " ".join(__lowerCamelCase			)
							if result.returncode > 0:
														__snake_case	:    int											=     "\n".join(result.stderr			)
														raise RuntimeError(
														    F'\'{cmd_str}\' failed with returncode {result.returncode}\n\n'
														    F'The combined stderr from workers follows:\n{stderr}'			)

							# check that the subprocess actually did run and produced some output, should the test rely on
							# the remote side to do the testing
							if not result.stdout and not result.stderr:
														raise RuntimeError(F'\'{cmd_str}\' produced no output.'			)

							return result







def        lowerCAmelCase_  (      ):
							__snake_case	:    Tuple											=     os.environ.get("PYTEST_XDIST_WORKER"							,			"gw0"			)
							__snake_case	:    Tuple											=     re.sub(R"^gw"							,			""							,			__lowerCamelCase							,			0							,			re.M			)
							return int(__lowerCamelCase			)







def        lowerCAmelCase_  (      ):
							__snake_case	:    Tuple											=     2_9_5_0_0
							__snake_case	:    Union[str, Any]											=     pytest_xdist_worker_id()
							return port + uniq_delta





import unittest

import numpy as np







def        lowerCAmelCase_  (      __lowerCamelCase							,			__lowerCamelCase							,			__lowerCamelCase							,			__lowerCamelCase = None							,			):
							__snake_case	:    List[str]											=     np.shape(__lowerCamelCase			)
							__snake_case	:    Optional[Any]											=     np.shape(__lowerCamelCase			)
							__snake_case	:    List[str]											=     np.shape(__lowerCamelCase			)

							if shape_a[0] != shape_b[0]:
														__snake_case	:    Any											=     (
														    "Expected the same number of rows for A and B. "
														    F'Instead found A of size {shape_a} and B of size {shape_b}'
														)
														raise ValueError(__lowerCamelCase			)

							if shape_b[1] != shape_c[1]:
														__snake_case	:    int											=     (
														    "Expected the same number of columns for B and C. "
														    F'Instead found B of size {shape_b} and C of size {shape_c}'
														)
														raise ValueError(__lowerCamelCase			)

							__snake_case	:    str											=     pseudo_inv
							if a_inv is None:
														try:
																					__snake_case	:    Optional[Any]											=     np.linalg.inv(__lowerCamelCase			)
														except np.linalg.LinAlgError:
																					raise ValueError(
																					    "Input matrix A is not invertible. Cannot compute Schur complement."			)

							return mat_c - mat_b.T @ a_inv @ mat_b

class        a	(unittest.TestCase   ):




							"""simple docstring"""


							def 					__snake_case      (							self :						Tuple       )			->					None:
														__snake_case	:    str											=     np.array([[1, 2, 1], [2, 1, 2], [3, 2, 4]]       )
														__snake_case	:    str											=     np.array([[0, 3], [3, 0], [2, 3]]       )
														__snake_case	:    Dict											=     np.array([[2, 1], [6, 3]]       )

														__snake_case	:    Dict											=     schur_complement(lowerCamelCase					,			lowerCamelCase					,			lowerCamelCase       )

														__snake_case	:    int											=     np.block([[a, b], [b.T, c]]       )

														__snake_case	:    Optional[int]											=     np.linalg.det(lowerCamelCase       )
														__snake_case	:    Any											=     np.linalg.det(lowerCamelCase       )
														__snake_case	:    Tuple											=     np.linalg.det(lowerCamelCase       )

														self.assertAlmostEqual(lowerCamelCase					,			det_a * det_s       )

							def 					__snake_case      (							self :						int       )			->					None:
														__snake_case	:    str											=     np.array([[1, 2, 1], [2, 1, 2], [3, 2, 4]]       )
														__snake_case	:    Dict											=     np.array([[0, 3], [3, 0], [2, 3]]       )
														__snake_case	:    Tuple											=     np.array([[2, 1], [6, 3]]       )

														with self.assertRaises(lowerCamelCase       ):
																					schur_complement(lowerCamelCase					,			lowerCamelCase					,			lowerCamelCase       )






							def 					__snake_case      (							self :						List[Any]       )			->					None:
														__snake_case	:    List[Any]											=     np.array([[1, 2, 1], [2, 1, 2], [3, 2, 4]]       )
														__snake_case	:    Tuple											=     np.array([[0, 3], [3, 0], [2, 3]]       )
														__snake_case	:    List[Any]											=     np.array([[2, 1, 3], [6, 3, 5]]       )

														with self.assertRaises(lowerCamelCase       ):
																					schur_complement(lowerCamelCase					,			lowerCamelCase					,			lowerCamelCase       )


if __name__ == "__main__":
			import doctest

			doctest.testmod()
			unittest.main()

