



'''simple docstring'''




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      (			lowerCamelCase__						,				lowerCamelCase__=False   ):
			'''simple docstring'''





			try:
						A_     :						int     =					os.environ[key]
			except KeyError:
						# KEY isn't set, default to `default`.
						A_     :						List[str]     =					default
			else:
						# KEY is set, convert it to True or False.
						try:
									A_     :						Optional[Any]     =					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


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

# Compression
lowerCamelCase							:Dict       = pytest.mark.skipif(not config.LZ4_AVAILABLE, reason='''test requires lz4''')
lowerCamelCase							:int       = pytest.mark.skipif(not config.PY7ZR_AVAILABLE, reason='''test requires py7zr''')
lowerCamelCase							:Tuple       = pytest.mark.skipif(not config.ZSTANDARD_AVAILABLE, reason='''test requires zstandard''')

# Audio
lowerCamelCase							: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[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
lowerCamelCase							:List[Any]       = 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      (			lowerCamelCase__   ):
			'''simple docstring'''





			try:
						import faiss  # noqa
			except ImportError:
						A_     :						Union[str, Any]     =					unittest.skip("""test requires faiss"""   )(lowerCamelCase__   )
			return test_case



def      a      (			lowerCamelCase__   ):
			'''simple docstring'''





			try:
						import regex  # noqa
			except ImportError:
						A_     :						int     =					unittest.skip("""test requires regex"""   )(lowerCamelCase__   )
			return test_case



def      a      (			lowerCamelCase__   ):
			'''simple docstring'''





			try:
						import elasticsearch  # noqa
			except ImportError:
						A_     :						str     =					unittest.skip("""test requires elasticsearch"""   )(lowerCamelCase__   )
			return test_case



def      a      (			lowerCamelCase__   ):
			'''simple docstring'''





			try:
						import sqlalchemy  # noqa
			except ImportError:
						A_     :						List[str]     =					unittest.skip("""test requires sqlalchemy"""   )(lowerCamelCase__   )
			return test_case



def      a      (			lowerCamelCase__   ):
			'''simple docstring'''





			if not config.TORCH_AVAILABLE:
						A_     :						Optional[int]     =					unittest.skip("""test requires PyTorch"""   )(lowerCamelCase__   )
			return test_case



def      a      (			lowerCamelCase__   ):
			'''simple docstring'''





			if not config.TF_AVAILABLE:
						A_     :						Optional[int]     =					unittest.skip("""test requires TensorFlow"""   )(lowerCamelCase__   )
			return test_case



def      a      (			lowerCamelCase__   ):
			'''simple docstring'''





			if not config.JAX_AVAILABLE:
						A_     :						Dict     =					unittest.skip("""test requires JAX"""   )(lowerCamelCase__   )
			return test_case



def      a      (			lowerCamelCase__   ):
			'''simple docstring'''





			if not config.PIL_AVAILABLE:
						A_     :						List[str]     =					unittest.skip("""test requires Pillow"""   )(lowerCamelCase__   )
			return test_case



def      a      (			lowerCamelCase__   ):
			'''simple docstring'''





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



def      a      (			lowerCamelCase__   ):
			'''simple docstring'''





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



def      a      (			lowerCamelCase__   ):
			'''simple docstring'''





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



def      a      (			lowerCamelCase__   ):
			'''simple docstring'''





			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      a      (			lowerCamelCase__   ):
			'''simple docstring'''





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



def      a      (			lowerCamelCase__   ):
			'''simple docstring'''





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



def      a      (			lowerCamelCase__   ):
			'''simple docstring'''





			if not _run_slow_tests or _run_slow_tests == 0:
						A_     :						List[str]     =					unittest.skip("""test is slow"""   )(lowerCamelCase__   )
			return test_case



def      a      (			lowerCamelCase__   ):
			'''simple docstring'''





			if not _run_local_tests or _run_local_tests == 0:
						A_     :						Optional[int]     =					unittest.skip("""test is local"""   )(lowerCamelCase__   )
			return test_case



def      a      (			lowerCamelCase__   ):
			'''simple docstring'''





			if not _run_packaged_tests or _run_packaged_tests == 0:
						A_     :						Optional[Any]     =					unittest.skip("""test is packaged"""   )(lowerCamelCase__   )
			return test_case



def      a      (			lowerCamelCase__   ):
			'''simple docstring'''





			if not _run_remote_tests or _run_remote_tests == 0:
						A_     :						Tuple     =					unittest.skip("""test requires remote"""   )(lowerCamelCase__   )
			return test_case



def      a      (			*lowerCamelCase__   ):
			'''simple docstring'''





			def decorate(cls   ):
						for name, fn in cls.__dict__.items():
									if callable(lowerCamelCase__   ) and name.startswith("""test"""   ):
												for decorator in decorators:
															A_     :						Optional[int]     =					decorator(lowerCamelCase__   )
												setattr(cls						,				lowerCamelCase__						,				lowerCamelCase__   )
						return cls

			return decorate







class      _lowerCAmelCase							(      __UpperCAmelCase			):
	pass







class      _lowerCAmelCase							(      __UpperCAmelCase			):
	__SCREAMING_SNAKE_CASE       :		List[Any]		      = 0
	__SCREAMING_SNAKE_CASE       :		Dict		      = 1
	__SCREAMING_SNAKE_CASE       :		Dict		      = 2






@contextmanager
def      a      (			lowerCamelCase__=OfflineSimulationMode.CONNECTION_FAILS						,				lowerCamelCase__=1E-16   ):
			'''simple docstring'''





			A_     :						Dict     =					requests.Session().request

			def timeout_request(lowerCamelCase__						,				lowerCamelCase__						,				lowerCamelCase__						,				**lowerCamelCase__   ):
						# Change the url to an invalid url so that the connection hangs
						A_     :						Union[str, 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.'   )
						A_     :						Tuple     =					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
									A_     :						List[str]     =					url
									A_     :						Optional[int]     =					e.args[0]
									A_     :						Optional[Any]     =					(max_retry_error.args[0].replace("""10.255.255.1"""						,				f'OfflineMock[{url}]'   ),)
									A_     :						Optional[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      a      (			*lowerCamelCase__						,				**lowerCamelCase__   ):
			'''simple docstring'''





			A_     :						List[str]     =					str(Path().resolve()   )
			with tempfile.TemporaryDirectory(*lowerCamelCase__						,				**lowerCamelCase__   ) as tmp_dir:
						try:
									os.chdir(lowerCamelCase__   )
									yield
						finally:
									os.chdir(lowerCamelCase__   )



@contextmanager
def      a      (			):
			'''simple docstring'''





			import gc

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



@contextmanager
def      a      (			):
			'''simple docstring'''





			import gc

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



def      a      (			lowerCamelCase__						,				lowerCamelCase__   ):
			'''simple docstring'''





			return deepcopy(lowerCamelCase__   ).integers(0						,				1_00						,				10   ).tolist() == deepcopy(lowerCamelCase__   ).integers(0						,				1_00						,				10   ).tolist()



def      a      (			lowerCamelCase__   ):
			'''simple docstring'''





			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      _lowerCAmelCase							:


	def __init__(self	,				lowercase	,				lowercase	,				lowercase							):
				A_     :						List[str]     =					returncode
				A_     :						Optional[int]     =					stdout
				A_     :						Dict     =					stderr






async def      a      (			lowerCamelCase__						,				lowerCamelCase__   ):
			'''simple docstring'''





			while True:
						A_     :						Union[str, Any]     =					await stream.readline()
						if line:
									callback(lowerCamelCase__   )
						else:
									break



async def      a      (			lowerCamelCase__						,				lowerCamelCase__=None						,				lowerCamelCase__=None						,				lowerCamelCase__=None						,				lowerCamelCase__=False						,				lowerCamelCase__=False   ):
			'''simple docstring'''





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

			A_     :						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)

			A_     :						Optional[Any]     =					[]
			A_     :						List[str]     =					[]

			def tee(lowerCamelCase__						,				lowerCamelCase__						,				lowerCamelCase__						,				lowerCamelCase__=""   ):
						A_     :						List[Any]     =					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      a      (			lowerCamelCase__						,				lowerCamelCase__=None						,				lowerCamelCase__=None						,				lowerCamelCase__=1_80						,				lowerCamelCase__=False						,				lowerCamelCase__=True   ):
			'''simple docstring'''





			A_     :						Any     =					asyncio.get_event_loop()
			A_     :						Optional[Any]     =					loop.run_until_complete(
			    _stream_subprocess(lowerCamelCase__						,				env=lowerCamelCase__						,				stdin=lowerCamelCase__						,				timeout=lowerCamelCase__						,				quiet=lowerCamelCase__						,				echo=lowerCamelCase__   )   )

			A_     :						Tuple     =					""" """.join(lowerCamelCase__   )
			if result.returncode > 0:
						A_     :						Dict     =					"""\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      (			):
			'''simple docstring'''





			A_     :						Dict     =					os.environ.get("""PYTEST_XDIST_WORKER"""						,				"""gw0"""   )
			A_     :						List[Any]     =					re.sub(r"""^gw"""						,				""""""						,				lowerCamelCase__						,				0						,				re.M   )
			return int(lowerCamelCase__   )



def      a      (			):
			'''simple docstring'''





			A_     :						List[Any]     =					2_95_00
			A_     :						Any     =					pytest_xdist_worker_id()
			return port + uniq_delta








'''simple docstring'''




from __future__ import annotations

from collections.abc import Callable

lowerCamelCase							:List[Any]       = list[list[float | int]]



def      a      (			lowerCamelCase__						,				lowerCamelCase__   ):
			'''simple docstring'''





			A_     :						int     =					len(lowerCamelCase__   )
			A_     :						Matrix     =					[[0 for _ in range(size + 1   )] for _ in range(lowerCamelCase__   )]
			A_     :						int
			A_     :						int
			A_     :						int
			A_     :						int
			A_     :						int
			A_     :						float

			for row in range(lowerCamelCase__   ):
						for col in range(lowerCamelCase__   ):
									A_     :						List[str]     =					matrix[row][col]

						A_     :						Optional[int]     =					vector[row][0]

			A_     :						Tuple     =					0
			A_     :						Tuple     =					0
			while row < size and col < size:
						# pivoting
						A_     :						Dict     =					max((abs(augmented[rowa][col]   ), rowa) for rowa in range(lowerCamelCase__						,				lowerCamelCase__   )   )[
						    1
						]
						if augmented[pivot_row][col] == 0:
									col += 1
									continue
						else:
									A_,   A_     :						Optional[Any]     =					augmented[pivot_row], augmented[row]

						for rowa in range(row + 1						,				lowerCamelCase__   ):
									A_     :						int     =					augmented[rowa][col] / augmented[row][col]
									A_     :						Union[str, Any]     =					0
									for cola in range(col + 1						,				size + 1   ):
												augmented[rowa][cola] -= augmented[row][cola] * ratio

						row += 1
						col += 1

			# back substitution
			for col in range(1						,				lowerCamelCase__   ):
						for row in range(lowerCamelCase__   ):
									A_     :						Tuple     =					augmented[row][col] / augmented[col][col]
									for cola in range(lowerCamelCase__						,				size + 1   ):
												augmented[row][cola] -= augmented[col][cola] * ratio

    # round to get rid of numbers like 2.000000000000004
			return [
			    [round(augmented[row][size] / augmented[row][row]						,				10   )] for row in range(lowerCamelCase__   )
			]



def      a      (			lowerCamelCase__   ):
			'''simple docstring'''





			A_     :						int     =					len(lowerCamelCase__   )
			A_     :						Matrix     =					[[0 for _ in range(lowerCamelCase__   )] for _ in range(lowerCamelCase__   )]
			A_     :						Matrix     =					[[0] for _ in range(lowerCamelCase__   )]
			A_     :						Matrix
			A_     :						int
			A_     :						int
			A_     :						int

			for x_val, y_val in enumerate(lowerCamelCase__   ):
						for col in range(lowerCamelCase__   ):
									A_     :						Dict     =					(x_val + 1) ** (size - col - 1)
						A_     :						Any     =					y_val

			A_     :						Dict     =					solve(lowerCamelCase__						,				lowerCamelCase__   )

			def interpolated_func(lowerCamelCase__   ) -> int:
						return sum(
						    round(coeffs[x_val][0]   ) * (var ** (size - x_val - 1))
						    for x_val in range(lowerCamelCase__   )   )

			return interpolated_func



def      a      (			lowerCamelCase__   ):
			'''simple docstring'''





			return (
			    1
			    - variable
			    + variable**2
			    - variable**3
			    + variable**4
			    - variable**5
			    + variable**6
			    - variable**7
			    + variable**8
			    - variable**9
			    + variable**10
			)



def      a      (			lowerCamelCase__ = question_function						,				lowerCamelCase__ = 10   ):
			'''simple docstring'''





			A_     :						list[int]     =					[func(lowerCamelCase__   ) for x_val in range(1						,				order + 1   )]

			A_     :						list[Callable[[int], int]]     =					[
			    interpolate(data_points[:max_coeff]   ) for max_coeff in range(1						,				order + 1   )
			]

			A_     :						int     =					0
			A_     :						Callable[[int], int]
			A_     :						int

			for poly in polynomials:
						A_     :						int     =					1
						while func(lowerCamelCase__   ) == poly(lowerCamelCase__   ):
									x_val += 1

						ret += poly(lowerCamelCase__   )

			return ret


if __name__ == "__main__":
						print(F"{solution() = }")