





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    A				(							UpperCAmelCase  ,  UpperCAmelCase=False				):
					try:
										_snake_case       :					Any				       =   os.environ[key]
					except KeyError:
										# KEY isn't set, default to `default`.
										_snake_case       :					List[str]				       =   default
					else:
										# KEY is set, convert it to True or False.
										try:
															_snake_case       :					Union[str, Any]				       =   strtobool(snake_case__				)
										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


__lowerCAmelCase :List[str]     =    parse_flag_from_env('RUN_SLOW', default=False)
__lowerCAmelCase :Optional[int]     =    parse_flag_from_env('RUN_REMOTE', default=False)
__lowerCAmelCase :List[Any]     =    parse_flag_from_env('RUN_LOCAL', default=True)
__lowerCAmelCase :Dict     =    parse_flag_from_env('RUN_PACKAGED', default=True)

# Compression
__lowerCAmelCase :Union[str, Any]     =    pytest.mark.skipif(not config.LZ4_AVAILABLE, reason='test requires lz4')
__lowerCAmelCase :Any     =    pytest.mark.skipif(not config.PY7ZR_AVAILABLE, reason='test requires py7zr')
__lowerCAmelCase :int     =    pytest.mark.skipif(not config.ZSTANDARD_AVAILABLE, reason='test requires zstandard')

# Audio
__lowerCAmelCase :List[str]     =    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
__lowerCAmelCase :List[str]     =    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
__lowerCAmelCase :str     =    pytest.mark.skipif(
    config.DILL_VERSION <= version.parse('0.3.2'),
    reason='test requires dill>0.3.2 for cloudpickle compatibility',
)

# Windows
__lowerCAmelCase :Optional[Any]     =    pytest.mark.skipif(
    sys.platform == 'win32',
    reason='test should not be run on Windows',
)







def    A				(							UpperCAmelCase				):
					try:
										import faiss  # noqa
					except ImportError:
										_snake_case       :					Optional[int]				       =   unittest.skip("test requires faiss"				)(snake_case__				)
					return test_case







def    A				(							UpperCAmelCase				):
					try:
										import regex  # noqa
					except ImportError:
										_snake_case       :					List[Any]				       =   unittest.skip("test requires regex"				)(snake_case__				)
					return test_case







def    A				(							UpperCAmelCase				):
					try:
										import elasticsearch  # noqa
					except ImportError:
										_snake_case       :					int				       =   unittest.skip("test requires elasticsearch"				)(snake_case__				)
					return test_case







def    A				(							UpperCAmelCase				):
					try:
										import sqlalchemy  # noqa
					except ImportError:
										_snake_case       :					Any				       =   unittest.skip("test requires sqlalchemy"				)(snake_case__				)
					return test_case







def    A				(							UpperCAmelCase				):
					if not config.TORCH_AVAILABLE:
										_snake_case       :					List[Any]				       =   unittest.skip("test requires PyTorch"				)(snake_case__				)
					return test_case







def    A				(							UpperCAmelCase				):
					if not config.TF_AVAILABLE:
										_snake_case       :					int				       =   unittest.skip("test requires TensorFlow"				)(snake_case__				)
					return test_case







def    A				(							UpperCAmelCase				):
					if not config.JAX_AVAILABLE:
										_snake_case       :					int				       =   unittest.skip("test requires JAX"				)(snake_case__				)
					return test_case







def    A				(							UpperCAmelCase				):
					if not config.PIL_AVAILABLE:
										_snake_case       :					Optional[int]				       =   unittest.skip("test requires Pillow"				)(snake_case__				)
					return test_case







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







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







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







def    A				(							UpperCAmelCase				):

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

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

					return _require_spacy_model







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







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







def    A				(							UpperCAmelCase				):
					if not _run_slow_tests or _run_slow_tests == 0:
										_snake_case       :					Dict				       =   unittest.skip("test is slow"				)(snake_case__				)
					return test_case







def    A				(							UpperCAmelCase				):
					if not _run_local_tests or _run_local_tests == 0:
										_snake_case       :					Optional[Any]				       =   unittest.skip("test is local"				)(snake_case__				)
					return test_case







def    A				(							UpperCAmelCase				):
					if not _run_packaged_tests or _run_packaged_tests == 0:
										_snake_case       :					Optional[int]				       =   unittest.skip("test is packaged"				)(snake_case__				)
					return test_case







def    A				(							UpperCAmelCase				):
					if not _run_remote_tests or _run_remote_tests == 0:
										_snake_case       :					List[str]				       =   unittest.skip("test requires remote"				)(snake_case__				)
					return test_case







def    A				(							*UpperCAmelCase				):
					def decorate(cls				):
										for name, fn in cls.__dict__.items():
															if callable(snake_case__				) and name.startswith("test"				):
																				for decorator in decorators:
																									_snake_case       :					int				       =   decorator(snake_case__				)
																				setattr(cls  ,  snake_case__  ,  snake_case__				)
										return cls

					return decorate






class        _a(    _lowercase    ):
		pass






class        _a(    _lowercase    ):
		lowerCamelCase__     :List[str]   				=		0
		lowerCamelCase__     :Dict   				=		1
		lowerCamelCase__     :Any   				=		2







@contextmanager
def    A				(							UpperCAmelCase=OfflineSimulationMode.CONNECTION_FAILS  ,  UpperCAmelCase=1e-16				):
					_snake_case       :					Any				       =   requests.Session().request

					def timeout_request(UpperCAmelCase  ,  UpperCAmelCase  ,  UpperCAmelCase  ,  **UpperCAmelCase				):
										# Change the url to an invalid url so that the connection hangs
										_snake_case       :					List[str]				       =   "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(snake_case__  ,  snake_case__  ,  **snake_case__				)
										except Exception as e:
															# The following changes in the error are just here to make the offline timeout error prettier
															_snake_case       :					Union[str, Any]				       =   url
															_snake_case       :					Optional[Any]				       =   e.args[0]
															_snake_case       :					int				       =   (max_retry_error.args[0].replace("10.255.255.1"  ,  F"""OfflineMock[{url}]"""				),)
															_snake_case       :					int				       =   (max_retry_error,)
															raise

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

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







@contextmanager
def    A				(							*UpperCAmelCase  ,  **UpperCAmelCase				):
					_snake_case       :					List[Any]				       =   str(Path().resolve()				)
					with tempfile.TemporaryDirectory(*snake_case__  ,  **snake_case__				) as tmp_dir:
										try:
															os.chdir(snake_case__				)
															yield
										finally:
															os.chdir(snake_case__				)







@contextmanager
def    A				(							):
					import gc

					gc.collect()
					_snake_case       :					Union[str, Any]				       =   pa.total_allocated_bytes()
					yield
					assert pa.total_allocated_bytes() - previous_allocated_memory > 0, "Arrow memory didn't increase."







@contextmanager
def    A				(							):
					import gc

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







def    A				(							UpperCAmelCase  ,  UpperCAmelCase				):
					return deepcopy(snake_case__				).integers(0  ,  100  ,  10				).tolist() == deepcopy(snake_case__				).integers(0  ,  100  ,  10				).tolist()







def    A				(							UpperCAmelCase				):
					import decorator
					from requests.exceptions import HTTPError

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

					return decorator.decorator(_wrapper  ,  snake_case__				)






class        _a:







		def __init__(    self ,						__snake_case ,						__snake_case ,						__snake_case				)      ->      Any:


							'''simple docstring'''

							_snake_case       :					Union[str, Any]				       =   returncode
							_snake_case       :					List[Any]				       =   stdout
							_snake_case       :					Union[str, Any]				       =   stderr







async def    A				(							UpperCAmelCase  ,  UpperCAmelCase				):
					while True:
										_snake_case       :					Union[str, Any]				       =   await stream.readline()
										if line:
															callback(snake_case__				)
										else:
															break







async def    A				(							UpperCAmelCase  ,  UpperCAmelCase=None  ,  UpperCAmelCase=None  ,  UpperCAmelCase=None  ,  UpperCAmelCase=False  ,  UpperCAmelCase=False				):
					if echo:
										print("\nRunning: "  ,  " ".join(snake_case__				)				)

					_snake_case       :					Optional[int]				       =   await asyncio.create_subprocess_exec(
					    cmd[0]  ,  *cmd[1:]  ,  stdin=snake_case__  ,  stdout=asyncio.subprocess.PIPE  ,  stderr=asyncio.subprocess.PIPE  ,  env=snake_case__  ,  )

					# 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[int]				       =   []
					_snake_case       :					List[str]				       =   []

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

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







def    A				(							UpperCAmelCase  ,  UpperCAmelCase=None  ,  UpperCAmelCase=None  ,  UpperCAmelCase=180  ,  UpperCAmelCase=False  ,  UpperCAmelCase=True				):
					_snake_case       :					Tuple				       =   asyncio.get_event_loop()
					_snake_case       :					int				       =   loop.run_until_complete(
					    _stream_subprocess(snake_case__  ,  env=snake_case__  ,  stdin=snake_case__  ,  timeout=snake_case__  ,  quiet=snake_case__  ,  echo=snake_case__				)				)

					_snake_case       :					Union[str, Any]				       =   " ".join(snake_case__				)
					if result.returncode > 0:
										_snake_case       :					Tuple				       =   "\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    A				(							):
					_snake_case       :					Optional[Any]				       =   os.environ.get("PYTEST_XDIST_WORKER"  ,  "gw0"				)
					_snake_case       :					Dict				       =   re.sub(R"^gw"  ,  ""  ,  snake_case__  ,  0  ,  re.M				)
					return int(snake_case__				)







def    A				(							):
					_snake_case       :					Any				       =   29_500
					_snake_case       :					Optional[Any]				       =   pytest_xdist_worker_id()
					return port + uniq_delta






import math

from numpy import inf
from scipy.integrate import quad







def    A				(							UpperCAmelCase				):
					if num <= 0:
										raise ValueError("math domain error"				)

					return quad(UpperCAmelCase  ,  0  ,  UpperCAmelCase  ,  args=(UpperCAmelCase)				)[0]







def    A				(							UpperCAmelCase  ,  UpperCAmelCase				):
					return math.pow(UpperCAmelCase  ,  z - 1				) * math.exp(-x				)


if __name__ == "__main__":
							from doctest import testmod

							testmod()