



"""simple docstring"""






import asyncio
import os
import shutil
import subprocess
import sys
import tempfile
import unittest
from distutils.util import strtobool
from functools import partial
from pathlib import Path
from typing import List, Union
from unittest import mock

import torch

from ..state import AcceleratorState, PartialState
from ..utils import (
    gather,
    is_bnb_available,
    is_comet_ml_available,
    is_datasets_available,
    is_deepspeed_available,
    is_mps_available,
    is_safetensors_available,
    is_tensorboard_available,
    is_torch_version,
    is_tpu_available,
    is_transformers_available,
    is_wandb_available,
    is_xpu_available,
)






def 	snake_case_  (				A_ :		Dict,    A_ :		Dict=False						):


							'''simple docstring'''





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






def 	snake_case_  (				A_ :		List[str]						):


							'''simple docstring'''





							return unittest.skip('''Test was skipped'''						)(A_						)






def 	snake_case_  (				A_ :		Tuple						):


							'''simple docstring'''





							return unittest.skipUnless(_run_slow_tests,    '''test is slow'''						)(A_						)






def 	snake_case_  (				A_ :		int						):


							'''simple docstring'''





							return unittest.skipUnless(not torch.cuda.is_available(),    '''test requires only a CPU'''						)(A_						)






def 	snake_case_  (				A_ :		Any						):


							'''simple docstring'''





							return unittest.skipUnless(torch.cuda.is_available(),    '''test requires a GPU'''						)(A_						)






def 	snake_case_  (				A_ :		List[str]						):


							'''simple docstring'''





							return unittest.skipUnless(is_xpu_available(),    '''test requires a XPU'''						)(A_						)






def 	snake_case_  (				A_ :		Dict						):


							'''simple docstring'''





							return unittest.skipUnless(is_mps_available(),    '''test requires a `mps` backend support in `torch`'''						)(A_						)






def 	snake_case_  (				A_ :		Optional[int]						):


							'''simple docstring'''





							return unittest.skipUnless(
							    is_transformers_available() and is_datasets_available(),    '''test requires the Hugging Face suite'''						)(A_						)






def 	snake_case_  (				A_ :		Dict						):


							'''simple docstring'''





							return unittest.skipUnless(is_bnb_available(),    '''test requires the bitsandbytes library'''						)(A_						)






def 	snake_case_  (				A_ :		Any						):


							'''simple docstring'''





							return unittest.skipUnless(is_tpu_available(),    '''test requires TPU'''						)(A_						)






def 	snake_case_  (				A_ :		Tuple						):


							'''simple docstring'''





							return unittest.skipUnless(torch.cuda.device_count() == 1,    '''test requires a GPU'''						)(A_						)






def 	snake_case_  (				A_ :		str						):


							'''simple docstring'''





							return unittest.skipUnless(torch.xpu.device_count() == 1,    '''test requires a XPU'''						)(A_						)






def 	snake_case_  (				A_ :		Optional[Any]						):


							'''simple docstring'''





							return unittest.skipUnless(torch.cuda.device_count() > 1,    '''test requires multiple GPUs'''						)(A_						)






def 	snake_case_  (				A_ :		Any						):


							'''simple docstring'''





							return unittest.skipUnless(torch.xpu.device_count() > 1,    '''test requires multiple XPUs'''						)(A_						)






def 	snake_case_  (				A_ :		List[str]						):


							'''simple docstring'''





							return unittest.skipUnless(is_safetensors_available(),    '''test requires safetensors'''						)(A_						)






def 	snake_case_  (				A_ :		Optional[int]						):


							'''simple docstring'''





							return unittest.skipUnless(is_deepspeed_available(),    '''test requires DeepSpeed'''						)(A_						)






def 	snake_case_  (				A_ :		Union[str, Any]						):


							'''simple docstring'''





							return unittest.skipUnless(is_torch_version('''>=''',    '''1.12.0'''						),    '''test requires torch version >= 1.12.0'''						)(A_						)






def 	snake_case_  (				A_ :		str=None,    A_ :		Any=None						):


							'''simple docstring'''





							if test_case is None:
														return partial(A_,    version=A_						)
							return unittest.skipUnless(is_torch_version('''>=''',    A_						),    F'''test requires torch version >= {version}'''						)(A_						)






def 	snake_case_  (				A_ :		Optional[Any]						):


							'''simple docstring'''





							return unittest.skipUnless(is_tensorboard_available(),    '''test requires Tensorboard'''						)(A_						)






def 	snake_case_  (				A_ :		Any						):


							'''simple docstring'''





							return unittest.skipUnless(is_wandb_available(),    '''test requires wandb'''						)(A_						)






def 	snake_case_  (				A_ :		Any						):


							'''simple docstring'''





							return unittest.skipUnless(is_comet_ml_available(),    '''test requires comet_ml'''						)(A_						)


lowerCAmelCase__      =    (
    any([is_wandb_available(), is_tensorboard_available()]) and not is_comet_ml_available()
)






def 	snake_case_  (				A_ :		List[Any]						):


							'''simple docstring'''





							return unittest.skipUnless(
							    _atleast_one_tracker_available,    '''test requires at least one tracker to be available and for `comet_ml` to not be installed''',    )(A_						)






class 	__snake_case	(     unittest.TestCase):
		snake_case__    :       List[str]        =						True




		@classmethod
		def 						SCREAMING_SNAKE_CASE    (			cls					:						List[Any]		):






									"""simple docstring"""






									_lowerCamelCase						:    List[Any]         =			tempfile.mkdtemp()




		@classmethod
		def 						SCREAMING_SNAKE_CASE    (			cls					:						Tuple		):






									"""simple docstring"""






									if os.path.exists(cls.tmpdir		):
																shutil.rmtree(cls.tmpdir		)




		def 						SCREAMING_SNAKE_CASE    (			self					:						Optional[Any]		):






									"""simple docstring"""






									if self.clear_on_setup:
																for path in Path(self.tmpdir		).glob('''**/*'''		):
																							if path.is_file():
																														path.unlink()
																							elif path.is_dir():
																														shutil.rmtree(__lowerCAmelCase		)






class 	__snake_case	(     unittest.TestCase):




		def 						SCREAMING_SNAKE_CASE    (			self					:						Dict		):






									"""simple docstring"""






									super().tearDown()
									# Reset the state of the AcceleratorState singleton.
									AcceleratorState._reset_state()
									PartialState._reset_state()






class 	__snake_case	(     unittest.TestCase):




		def 						SCREAMING_SNAKE_CASE    (			self					:						str						, __lowerCAmelCase					:						Union[mock.Mock, List[mock.Mock]]		):






									"""simple docstring"""






									_lowerCamelCase						:    Optional[Any]         =			mocks if isinstance(__lowerCAmelCase						, (tuple, list)		) else [mocks]
									for m in self.mocks:
																m.start()
																self.addCleanup(m.stop		)






def 	snake_case_  (				A_ :		Tuple						):


							'''simple docstring'''





							_lowerCamelCase						:    Any         =			AcceleratorState()
							_lowerCamelCase						:    List[Any]         =			tensor[None].clone().to(state.device						)
							_lowerCamelCase						:    Union[str, Any]         =			gather(A_						).cpu()
							_lowerCamelCase						:    List[str]         =			tensor[0].cpu()
							for i in range(tensors.shape[0]						):
														if not torch.equal(tensors[i],    A_						):
																					return False
							return True






class 	__snake_case	:




		def __init__(			self					:						Union[str, Any]						, __lowerCAmelCase					:						Union[str, Any]						, __lowerCAmelCase					:						List[str]						, __lowerCAmelCase					:						Tuple		):






									"""simple docstring"""






									_lowerCamelCase						:    Optional[int]         =			returncode
									_lowerCamelCase						:    int         =			stdout
									_lowerCamelCase						:    Union[str, Any]         =			stderr






async def 	snake_case_  (				A_ :		List[str],    A_ :		int						):


							'''simple docstring'''





							while True:
														_lowerCamelCase						:    Dict         =			await stream.readline()
														if line:
																					callback(A_						)
														else:
																					break






async def 	snake_case_  (				A_ :		str,    A_ :		Tuple=None,    A_ :		Optional[int]=None,    A_ :		Any=None,    A_ :		Union[str, Any]=False,    A_ :		Dict=False						):


							'''simple docstring'''





							if echo:
														print('''\nRunning: ''',    ''' '''.join(A_						)						)

							_lowerCamelCase						:    Tuple         =			await asyncio.create_subprocess_exec(
							    cmd[0],    *cmd[1:],    stdin=A_,    stdout=asyncio.subprocess.PIPE,    stderr=asyncio.subprocess.PIPE,    env=A_,    )

							# 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						:    Any         =			[]
							_lowerCamelCase						:    Tuple         =			[]

							def tee(A_ :		str,    A_ :		int,    A_ :		Dict,    A_ :		Any=""						):
														_lowerCamelCase						:    int         =			line.decode('''utf-8'''						).rstrip()
														sink.append(A_						)
														if not quiet:
																					print(A_,    A_,    file=A_						)

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






def 	snake_case_  (				A_ :		List[Any],    A_ :		Tuple=None,    A_ :		int=None,    A_ :		Any=1_80,    A_ :		int=False,    A_ :		List[str]=True						):


							'''simple docstring'''





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

							_lowerCamelCase						:    Tuple         =			''' '''.join(A_						)
							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}'''						)

							return result






class 	__snake_case	(     _lowercase):
		pass






def 	snake_case_  (				A_ :		List[str],    A_ :		Optional[Any]=False						):


							'''simple docstring'''





							try:
														_lowerCamelCase						:    Tuple         =			subprocess.check_output(A_,    stderr=subprocess.STDOUT						)
														if return_stdout:
																					if hasattr(A_,    '''decode'''						):
																												_lowerCamelCase						:    int         =			output.decode('''utf-8'''						)
																					return output
							except subprocess.CalledProcessError as e:
														raise SubprocessCallException(
														    F'''Command `{" ".join(A_						)}` failed with the following error:\n\n{e.output.decode()}'''						) from e







"""simple docstring"""






from itertools import permutations






def 	snake_case_  (				A_ :		tuple						):


       '''simple docstring'''





       if num[3] % 2 != 0:
              return False

       if (num[2] + num[3] + num[4]) % 3 != 0:
              return False

       if num[5] % 5 != 0:
              return False

       _lowerCamelCase						:    Any         =			[7, 11, 13, 17]
       for i, test in enumerate(A_						):
              if (num[i + 4] * 1_00 + num[i + 5] * 10 + num[i + 6]) % test != 0:
                     return False
       return True






def 	snake_case_  (				A_ :		int = 10						):


       '''simple docstring'''





       return sum(
           int(''''''.join(map(A_,    A_						)						)						)
           for num in permutations(range(A_						)						)
           if is_substring_divisible(A_						)						)


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


