



"""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      _lowercase							(    __snake_case   ,__snake_case=False      )		->  Tuple:
			try:
						__lowerCAmelCase :    Optional[int]				=			os.environ[key]
			except KeyError:
						# KEY isn't set, default to `default`.
						__lowerCAmelCase :    Tuple				=			default
			else:
						# KEY is set, convert it to True or False.
						try:
									__lowerCAmelCase :    Tuple				=			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


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

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

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

# Windows
__snake_case				:  Dict =       pytest.mark.skipif(
    sys.platform == 'win32',
    reason='test should not be run on Windows',
)


def      _lowercase							(    __snake_case      )		->  int:
			try:
						import faiss  # noqa
			except ImportError:
						__lowerCAmelCase :    Optional[int]				=			unittest.skip("test requires faiss"      )(__snake_case      )
			return test_case


def      _lowercase							(    __snake_case      )		->  str:
			try:
						import regex  # noqa
			except ImportError:
						__lowerCAmelCase :    str				=			unittest.skip("test requires regex"      )(__snake_case      )
			return test_case


def      _lowercase							(    __snake_case      )		->  int:
			try:
						import elasticsearch  # noqa
			except ImportError:
						__lowerCAmelCase :    int				=			unittest.skip("test requires elasticsearch"      )(__snake_case      )
			return test_case


def      _lowercase							(    __snake_case      )		->  Tuple:
			try:
						import sqlalchemy  # noqa
			except ImportError:
						__lowerCAmelCase :    List[str]				=			unittest.skip("test requires sqlalchemy"      )(__snake_case      )
			return test_case


def      _lowercase							(    __snake_case      )		->  Union[str, Any]:
			if not config.TORCH_AVAILABLE:
						__lowerCAmelCase :    Optional[Any]				=			unittest.skip("test requires PyTorch"      )(__snake_case      )
			return test_case


def      _lowercase							(    __snake_case      )		->  List[Any]:
			if not config.TF_AVAILABLE:
						__lowerCAmelCase :    Dict				=			unittest.skip("test requires TensorFlow"      )(__snake_case      )
			return test_case


def      _lowercase							(    __snake_case      )		->  List[str]:
			if not config.JAX_AVAILABLE:
						__lowerCAmelCase :    Optional[Any]				=			unittest.skip("test requires JAX"      )(__snake_case      )
			return test_case


def      _lowercase							(    __snake_case      )		->  Tuple:
			if not config.PIL_AVAILABLE:
						__lowerCAmelCase :    Optional[int]				=			unittest.skip("test requires Pillow"      )(__snake_case      )
			return test_case


def      _lowercase							(    __snake_case      )		->  Tuple:
			try:
						import transformers  # noqa F401
			except ImportError:
						return unittest.skip("test requires transformers"      )(__snake_case      )
			else:
						return test_case


def      _lowercase							(    __snake_case      )		->  Union[str, Any]:
			try:
						import tiktoken  # noqa F401
			except ImportError:
						return unittest.skip("test requires tiktoken"      )(__snake_case      )
			else:
						return test_case


def      _lowercase							(    __snake_case      )		->  str:
			try:
						import spacy  # noqa F401
			except ImportError:
						return unittest.skip("test requires spacy"      )(__snake_case      )
			else:
						return test_case


def      _lowercase							(    __snake_case      )		->  Union[str, Any]:

			def _require_spacy_model(__snake_case      ):
						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      _lowercase							(    __snake_case      )		->  Optional[Any]:
			try:
						import pyspark  # noqa F401
			except ImportError:
						return unittest.skip("test requires pyspark"      )(__snake_case      )
			else:
						return test_case


def      _lowercase							(    __snake_case      )		->  Union[str, Any]:
			try:
						import joblibspark  # noqa F401
			except ImportError:
						return unittest.skip("test requires joblibspark"      )(__snake_case      )
			else:
						return test_case


def      _lowercase							(    __snake_case      )		->  Optional[int]:
			if not _run_slow_tests or _run_slow_tests == 0:
						__lowerCAmelCase :    List[Any]				=			unittest.skip("test is slow"      )(__snake_case      )
			return test_case


def      _lowercase							(    __snake_case      )		->  List[str]:
			if not _run_local_tests or _run_local_tests == 0:
						__lowerCAmelCase :    Optional[int]				=			unittest.skip("test is local"      )(__snake_case      )
			return test_case


def      _lowercase							(    __snake_case      )		->  Any:
			if not _run_packaged_tests or _run_packaged_tests == 0:
						__lowerCAmelCase :    List[str]				=			unittest.skip("test is packaged"      )(__snake_case      )
			return test_case


def      _lowercase							(    __snake_case      )		->  Optional[int]:
			if not _run_remote_tests or _run_remote_tests == 0:
						__lowerCAmelCase :    List[str]				=			unittest.skip("test requires remote"      )(__snake_case      )
			return test_case


def      _lowercase							(    *__snake_case      )		->  Optional[int]:
			def decorate(cls      ):
						for name, fn in cls.__dict__.items():
									if callable(__snake_case      ) and name.startswith("test"      ):
												for decorator in decorators:
															__lowerCAmelCase :    str				=			decorator(__snake_case      )
												setattr(cls   ,__snake_case   ,__snake_case      )
						return cls

			return decorate



class      A__  (    __a				):




	'''simple docstring'''





	pass






class      A__  (    __a				):




	'''simple docstring'''





	SCREAMING_SNAKE_CASE        =      0
	SCREAMING_SNAKE_CASE        =      1
	SCREAMING_SNAKE_CASE        =      2






@contextmanager
def      _lowercase							(    __snake_case=OfflineSimulationMode.CONNECTION_FAILS   ,__snake_case=1e-1_6      )		->  str:
			__lowerCAmelCase :    Optional[int]				=			requests.Session().request

			def timeout_request(__snake_case   ,__snake_case   ,__snake_case   ,**__snake_case      ):
						# Change the url to an invalid url so that the connection hangs
						__lowerCAmelCase :    Optional[int]				=			"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."""      )
						__lowerCAmelCase :    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
									__lowerCAmelCase :    Union[str, Any]				=			url
									__lowerCAmelCase :    int				=			e.args[0]
									__lowerCAmelCase :    List[str]				=			(max_retry_error.args[0].replace("10.255.255.1"   ,F"""OfflineMock[{url}]"""      ),)
									__lowerCAmelCase :    str				=			(max_retry_error,)
									raise

			def raise_connection_error(__snake_case   ,__snake_case   ,**__snake_case      ):
						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      _lowercase							(    *__snake_case   ,**__snake_case      )		->  int:
			__lowerCAmelCase :    List[str]				=			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      _lowercase							(    )		->  Tuple:
			import gc

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


@contextmanager
def      _lowercase							(    )		->  Dict:
			import gc

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


def      _lowercase							(    __snake_case   ,__snake_case      )		->  Any:
			return deepcopy(__snake_case      ).integers(0   ,100   ,10      ).tolist() == deepcopy(__snake_case      ).integers(0   ,100   ,10      ).tolist()


def      _lowercase							(    __snake_case      )		->  Dict:
			import decorator
			from requests.exceptions import HTTPError

			def _wrapper(__snake_case   ,*__snake_case   ,**__snake_case      ):
						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__  :




	'''simple docstring'''





	def __init__(	self:						Optional[int]			,     _SCREAMING_SNAKE_CASE:						Tuple			,     _SCREAMING_SNAKE_CASE:						List[str]			,     _SCREAMING_SNAKE_CASE:						Union[str, Any])							->			List[str]:

				"""simple docstring"""

				__lowerCAmelCase :    Any				=			returncode
				__lowerCAmelCase :    Tuple				=			stdout
				__lowerCAmelCase :    Union[str, Any]				=			stderr






async def      _lowercase							(    __snake_case   ,__snake_case      )		->  List[Any]:
			while True:
						__lowerCAmelCase :    int				=			await stream.readline()
						if line:
									callback(__snake_case      )
						else:
									break


async def      _lowercase							(    __snake_case   ,__snake_case=None   ,__snake_case=None   ,__snake_case=None   ,__snake_case=False   ,__snake_case=False      )		->  _RunOutput:
			if echo:
						print("\nRunning: "   ," ".join(__snake_case      )      )

			__lowerCAmelCase :    Any				=			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)

			__lowerCAmelCase :    Optional[Any]				=			[]
			__lowerCAmelCase :    int				=			[]

			def tee(__snake_case   ,__snake_case   ,__snake_case   ,__snake_case=""      ):
						__lowerCAmelCase :    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 __snake_case      : tee(__snake_case   ,__snake_case   ,sys.stdout   ,label="stdout:"      )      ),
			        _read_stream(p.stderr   ,lambda __snake_case      : tee(__snake_case   ,__snake_case   ,sys.stderr   ,label="stderr:"      )      ),
			    ]   ,timeout=__snake_case   ,)
			return _RunOutput(await p.wait()   ,__snake_case   ,__snake_case      )


def      _lowercase							(    __snake_case   ,__snake_case=None   ,__snake_case=None   ,__snake_case=180   ,__snake_case=False   ,__snake_case=True      )		->  _RunOutput:
			__lowerCAmelCase :    Dict				=			asyncio.get_event_loop()
			__lowerCAmelCase :    Optional[Any]				=			loop.run_until_complete(
			    _stream_subprocess(__snake_case   ,env=__snake_case   ,stdin=__snake_case   ,timeout=__snake_case   ,quiet=__snake_case   ,echo=__snake_case      )      )

			__lowerCAmelCase :    Dict				=			" ".join(__snake_case      )
			if result.returncode > 0:
						__lowerCAmelCase :    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      _lowercase							(    )		->  Dict:
			__lowerCAmelCase :    List[str]				=			os.environ.get("PYTEST_XDIST_WORKER"   ,"gw0"      )
			__lowerCAmelCase :    Optional[int]				=			re.sub(r"^gw"   ,""   ,__snake_case   ,0   ,re.M      )
			return int(__snake_case      )





def      _lowercase							(    )		->  Dict:
			__lowerCAmelCase :    List[str]				=			29_500
			__lowerCAmelCase :    List[Any]				=			pytest_xdist_worker_id()
			return port + uniq_delta
'''simple docstring'''

from __future__ import annotations

from typing import Any



def snake_case_      (					__snake_case  :							list[Any])			->					None:
   create_state_space_tree(__snake_case	,   []	,   0)



def snake_case_      (					__snake_case  :							list[Any]	,   __snake_case  :							list[Any]	,   __snake_case  :							int)			->					None:

   if index == len(__snake_case):
      print(__snake_case)
      return

   create_state_space_tree(__snake_case	,   __snake_case	,   index + 1)
   current_subsequence.append(sequence[index])
   create_state_space_tree(__snake_case	,   __snake_case	,   index + 1)
   current_subsequence.pop()


if __name__ == "__main__":
 A_     :						list[Any]    							=[3, 1, 2, 4]
 generate_all_subsequences(seq)

 seq.clear()
 seq.extend(['''A''', '''B''', '''C'''])
 generate_all_subsequences(seq)





