






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    SCREAMING_SNAKE_CASE_							(							__magic_name__					:  str	,			__magic_name__					:  Optional[int]=False					)		->			Tuple:






	"""simple docstring"""



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


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

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

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

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

def    SCREAMING_SNAKE_CASE_							(							__magic_name__					:  Dict					)		->			Any:






	"""simple docstring"""



	try:
		import faiss  # noqa
	except ImportError:
		UpperCamelCase     :List[str]          =	unittest.skip("""test requires faiss"""					)(__magic_name__					)
	return test_case

def    SCREAMING_SNAKE_CASE_							(							__magic_name__					:  Tuple					)		->			int:






	"""simple docstring"""



	try:
		import regex  # noqa
	except ImportError:
		UpperCamelCase     :Dict          =	unittest.skip("""test requires regex"""					)(__magic_name__					)
	return test_case

def    SCREAMING_SNAKE_CASE_							(							__magic_name__					:  Any					)		->			Dict:






	"""simple docstring"""



	try:
		import elasticsearch  # noqa
	except ImportError:
		UpperCamelCase     :int          =	unittest.skip("""test requires elasticsearch"""					)(__magic_name__					)
	return test_case

def    SCREAMING_SNAKE_CASE_							(							__magic_name__					:  str					)		->			Dict:






	"""simple docstring"""



	try:
		import sqlalchemy  # noqa
	except ImportError:
		UpperCamelCase     :Tuple          =	unittest.skip("""test requires sqlalchemy"""					)(__magic_name__					)
	return test_case

def    SCREAMING_SNAKE_CASE_							(							__magic_name__					:  Any					)		->			List[Any]:






	"""simple docstring"""



	if not config.TORCH_AVAILABLE:
		UpperCamelCase     :int          =	unittest.skip("""test requires PyTorch"""					)(__magic_name__					)
	return test_case

def    SCREAMING_SNAKE_CASE_							(							__magic_name__					:  Optional[Any]					)		->			List[Any]:






	"""simple docstring"""



	if not config.TF_AVAILABLE:
		UpperCamelCase     :str          =	unittest.skip("""test requires TensorFlow"""					)(__magic_name__					)
	return test_case

def    SCREAMING_SNAKE_CASE_							(							__magic_name__					:  List[Any]					)		->			Optional[Any]:






	"""simple docstring"""



	if not config.JAX_AVAILABLE:
		UpperCamelCase     :Optional[int]          =	unittest.skip("""test requires JAX"""					)(__magic_name__					)
	return test_case

def    SCREAMING_SNAKE_CASE_							(							__magic_name__					:  Optional[Any]					)		->			Union[str, Any]:






	"""simple docstring"""



	if not config.PIL_AVAILABLE:
		UpperCamelCase     :int          =	unittest.skip("""test requires Pillow"""					)(__magic_name__					)
	return test_case

def    SCREAMING_SNAKE_CASE_							(							__magic_name__					:  Optional[int]					)		->			Dict:






	"""simple docstring"""



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

def    SCREAMING_SNAKE_CASE_							(							__magic_name__					:  str					)		->			int:






	"""simple docstring"""



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

def    SCREAMING_SNAKE_CASE_							(							__magic_name__					:  List[Any]					)		->			List[str]:






	"""simple docstring"""



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

def    SCREAMING_SNAKE_CASE_							(							__magic_name__					:  Optional[Any]					)		->			Tuple:






	"""simple docstring"""



	def _require_spacy_model(__magic_name__					:  List[str]					):
		try:
			import spacy  # noqa F401

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

	return _require_spacy_model

def    SCREAMING_SNAKE_CASE_							(							__magic_name__					:  Tuple					)		->			List[Any]:






	"""simple docstring"""



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

def    SCREAMING_SNAKE_CASE_							(							__magic_name__					:  Tuple					)		->			Optional[int]:






	"""simple docstring"""



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

def    SCREAMING_SNAKE_CASE_							(							__magic_name__					:  str					)		->			List[str]:






	"""simple docstring"""



	if not _run_slow_tests or _run_slow_tests == 0:
		UpperCamelCase     :Optional[int]          =	unittest.skip("""test is slow"""					)(__magic_name__					)
	return test_case

def    SCREAMING_SNAKE_CASE_							(							__magic_name__					:  Any					)		->			Union[str, Any]:






	"""simple docstring"""



	if not _run_local_tests or _run_local_tests == 0:
		UpperCamelCase     :str          =	unittest.skip("""test is local"""					)(__magic_name__					)
	return test_case

def    SCREAMING_SNAKE_CASE_							(							__magic_name__					:  Any					)		->			int:






	"""simple docstring"""



	if not _run_packaged_tests or _run_packaged_tests == 0:
		UpperCamelCase     :Optional[int]          =	unittest.skip("""test is packaged"""					)(__magic_name__					)
	return test_case

def    SCREAMING_SNAKE_CASE_							(							__magic_name__					:  Optional[Any]					)		->			Union[str, Any]:






	"""simple docstring"""



	if not _run_remote_tests or _run_remote_tests == 0:
		UpperCamelCase     :Optional[int]          =	unittest.skip("""test requires remote"""					)(__magic_name__					)
	return test_case

def    SCREAMING_SNAKE_CASE_							(							*__magic_name__					:  int					)		->			List[str]:






	"""simple docstring"""



	def decorate(cls					:  int					):
		for name, fn in cls.__dict__.items():
			if callable(__magic_name__					) and name.startswith("""test"""					):
				for decorator in decorators:
					UpperCamelCase     :int          =	decorator(__magic_name__					)
				setattr(cls	,			__magic_name__	,			__magic_name__					)
		return cls

	return decorate

class     _SCREAMING_SNAKE_CASE       (			_a      ):
	pass

class     _SCREAMING_SNAKE_CASE       (			_a      ):
	snake_case__							:     Union[str, Any]     	=  0
	snake_case__							:     Union[str, Any]     	=  1
	snake_case__							:     List[str]     	=  2

@contextmanager
def    SCREAMING_SNAKE_CASE_							(							__magic_name__					:  Dict=OfflineSimulationMode.CONNECTION_FAILS	,			__magic_name__					:  str=1E-16					)		->			Any:






	"""simple docstring"""



	UpperCamelCase     :Optional[int]          =	requests.Session().request

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

	def raise_connection_error(__magic_name__					:  Tuple	,			__magic_name__					:  int	,			**__magic_name__					:  str					):
		raise requests.ConnectionError("""Offline mode is enabled."""	,			request=__magic_name__					)

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

@contextmanager
def    SCREAMING_SNAKE_CASE_							(							*__magic_name__					:  str	,			**__magic_name__					:  Dict					)		->			List[Any]:






	"""simple docstring"""



	UpperCamelCase     :Optional[int]          =	str(Path().resolve()					)
	with tempfile.TemporaryDirectory(*__magic_name__	,			**__magic_name__					) as tmp_dir:
		try:
			os.chdir(__magic_name__					)
			yield
		finally:
			os.chdir(__magic_name__					)

@contextmanager
def    SCREAMING_SNAKE_CASE_							(							)		->			Optional[int]:






	"""simple docstring"""



	import gc

	gc.collect()
	UpperCamelCase     :Tuple          =	pa.total_allocated_bytes()
	yield
	assert pa.total_allocated_bytes() - previous_allocated_memory > 0, "Arrow memory didn't increase."

@contextmanager
def    SCREAMING_SNAKE_CASE_							(							)		->			Optional[Any]:






	"""simple docstring"""



	import gc

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

def    SCREAMING_SNAKE_CASE_							(							__magic_name__					:  Dict	,			__magic_name__					:  Dict					)		->			Tuple:






	"""simple docstring"""



	return deepcopy(__magic_name__					).integers(0	,			100	,			10					).tolist() == deepcopy(__magic_name__					).integers(0	,			100	,			10					).tolist()

def    SCREAMING_SNAKE_CASE_							(							__magic_name__					:  List[str]					)		->			Union[str, Any]:






	"""simple docstring"""



	import decorator
	from requests.exceptions import HTTPError

	def _wrapper(__magic_name__					:  Tuple	,			*__magic_name__					:  List[str]	,			**__magic_name__					:  List[Any]					):
		try:
			return func(*__magic_name__	,			**__magic_name__					)
		except HTTPError as err:
			if str(__magic_name__					).startswith("""500"""					) or str(__magic_name__					).startswith("""502"""					):
				pytest.xfail(str(__magic_name__					)					)
			raise err

	return decorator.decorator(_wrapper	,			__magic_name__					)

class     _SCREAMING_SNAKE_CASE       :





	def __init__(		self				:					Tuple ,  __lowerCamelCase				:					Dict ,  __lowerCamelCase				:					Union[str, Any] ,  __lowerCamelCase				:					Any	):
		UpperCamelCase     :int          =	returncode
		UpperCamelCase     :Tuple          =	stdout
		UpperCamelCase     :List[str]          =	stderr

async def    SCREAMING_SNAKE_CASE_							(							__magic_name__					:  Dict	,			__magic_name__					:  List[str]					)		->			Union[str, Any]:






	"""simple docstring"""



	while True:
		UpperCamelCase     :List[str]          =	await stream.readline()
		if line:
			callback(__magic_name__					)
		else:
			break

async def    SCREAMING_SNAKE_CASE_							(							__magic_name__					:  Tuple	,			__magic_name__					:  List[str]=None	,			__magic_name__					:  Optional[int]=None	,			__magic_name__					:  int=None	,			__magic_name__					:  int=False	,			__magic_name__					:  str=False					)		->			_RunOutput:






	"""simple docstring"""



	if echo:
		print("""\nRunning: """	,			""" """.join(__magic_name__					)					)

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

	# 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)

	UpperCamelCase     :List[Any]          =	[]
	UpperCamelCase     :List[Any]          =	[]

	def tee(__magic_name__					:  List[str]	,			__magic_name__					:  List[Any]	,			__magic_name__					:  int	,			__magic_name__					:  Optional[Any]=""					):
		UpperCamelCase     :List[Any]          =	line.decode("""utf-8"""					).rstrip()
		sink.append(__magic_name__					)
		if not quiet:
			print(__magic_name__	,			__magic_name__	,			file=__magic_name__					)

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

def    SCREAMING_SNAKE_CASE_							(							__magic_name__					:  int	,			__magic_name__					:  List[Any]=None	,			__magic_name__					:  Optional[Any]=None	,			__magic_name__					:  List[str]=180	,			__magic_name__					:  Optional[Any]=False	,			__magic_name__					:  Any=True					)		->			_RunOutput:






	"""simple docstring"""



	UpperCamelCase     :str          =	asyncio.get_event_loop()
	UpperCamelCase     :Optional[int]          =	loop.run_until_complete(
	    _stream_subprocess(__magic_name__	,			env=__magic_name__	,			stdin=__magic_name__	,			timeout=__magic_name__	,			quiet=__magic_name__	,			echo=__magic_name__					)					)

	UpperCamelCase     :Tuple          =	""" """.join(__magic_name__					)
	if result.returncode > 0:
		UpperCamelCase     :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    SCREAMING_SNAKE_CASE_							(							)		->			Union[str, Any]:






	"""simple docstring"""



	UpperCamelCase     :int          =	os.environ.get("""PYTEST_XDIST_WORKER"""	,			"""gw0"""					)
	UpperCamelCase     :str          =	re.sub(R"""^gw"""	,			""""""	,			__magic_name__	,			0	,			re.M					)
	return int(__magic_name__					)

def    SCREAMING_SNAKE_CASE_							(							)		->			Any:






	"""simple docstring"""



	UpperCamelCase     :Union[str, Any]          =	2_9500
	UpperCamelCase     :Union[str, Any]          =	pytest_xdist_worker_id()
	return port + uniq_delta

"""simple docstring"""






from __future__ import annotations

from scipy.special import comb  # type: ignore





class  _A						:

      def __init__(						self		,       __lowerCAmelCase						):







            """simple docstring"""



            lowercase														=	list_of_points
            # Degree determines the flexibility of the curve.
            # Degree = 1 will produce a straight line.
            lowercase														=	len(__lowerCAmelCase						) - 1

      def 				A__       (						self		,       __lowerCAmelCase						):







            """simple docstring"""



            assert 0 <= t <= 1, "Time t must be between 0 and 1."
            lowercase														=	[]
            for i in range(len(self.list_of_points						)						):
                  # basis function for each i
                  output_values.append(
                      comb(self.degree		,       __lowerCAmelCase						) * ((1 - t) ** (self.degree - i)) * (t**i)						)
            # the basis must sum up to 1 for it to produce a valid Bezier curve.
            assert round(sum(__lowerCAmelCase						)		,       5						) == 1
            return output_values

      def 				A__       (						self		,       __lowerCAmelCase						):







            """simple docstring"""



            assert 0 <= t <= 1, "Time t must be between 0 and 1."

            lowercase														=	self.basis_function(__lowerCAmelCase						)
            lowercase														=	0.0
            lowercase														=	0.0
            for i in range(len(self.list_of_points						)						):
                  # For all points, sum up the product of i-th basis function and i-th point.
                  x += basis_function[i] * self.list_of_points[i][0]
                  y += basis_function[i] * self.list_of_points[i][1]
            return (x, y)







      def 				A__       (						self		,       __lowerCAmelCase = 0.0_1						):







            """simple docstring"""



            from matplotlib import pyplot as plt  # type: ignore

            lowercase														=	[]  # x coordinates of points to plot
            lowercase														=	[]  # y coordinates of points to plot

            lowercase														=	0.0
            while t <= 1:
                  lowercase														=	self.bezier_curve_function(__lowerCAmelCase						)
                  to_plot_x.append(value[0]						)
                  to_plot_y.append(value[1]						)
                  t += step_size

            lowercase														=	[i[0] for i in self.list_of_points]
            lowercase														=	[i[1] for i in self.list_of_points]

            plt.plot(
                __lowerCAmelCase		,       __lowerCAmelCase		,       color="""blue"""		,       label="""Curve of Degree """ + str(self.degree						)		,       )
            plt.scatter(__lowerCAmelCase		,       __lowerCAmelCase		,       color="""red"""		,       label="""Control Points"""						)
            plt.legend()
            plt.show()


if __name__ == "__main__":
       import doctest

       doctest.testmod()

       BezierCurve([(1, 2), (3, 5)]).plot_curve()  # degree 1
       BezierCurve([(0, 0), (5, 5), (5, 0)]).plot_curve()  # degree 2
       BezierCurve([(0, 0), (5, 5), (5, 0), (2.5, -2.5)]).plot_curve()  # degree 3



