



'''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        _SCREAMING_SNAKE_CASE  (	UpperCamelCase							,   UpperCamelCase=False      ):



    """simple docstring"""





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



    """simple docstring"""





    return unittest.skip("""Test was skipped"""      )(UpperCamelCase      )
def        _SCREAMING_SNAKE_CASE  (	UpperCamelCase      ):



    """simple docstring"""





    return unittest.skipUnless(_run_slow_tests							,   """test is slow"""      )(UpperCamelCase      )
def        _SCREAMING_SNAKE_CASE  (	UpperCamelCase      ):



    """simple docstring"""





    return unittest.skipUnless(not torch.cuda.is_available()							,   """test requires only a CPU"""      )(UpperCamelCase      )
def        _SCREAMING_SNAKE_CASE  (	UpperCamelCase      ):



    """simple docstring"""





    return unittest.skipUnless(torch.cuda.is_available()							,   """test requires a GPU"""      )(UpperCamelCase      )
def        _SCREAMING_SNAKE_CASE  (	UpperCamelCase      ):



    """simple docstring"""





    return unittest.skipUnless(is_xpu_available()							,   """test requires a XPU"""      )(UpperCamelCase      )
def        _SCREAMING_SNAKE_CASE  (	UpperCamelCase      ):



    """simple docstring"""





    return unittest.skipUnless(is_mps_available()							,   """test requires a `mps` backend support in `torch`"""      )(UpperCamelCase      )
def        _SCREAMING_SNAKE_CASE  (	UpperCamelCase      ):



    """simple docstring"""





    return unittest.skipUnless(
        is_transformers_available() and is_datasets_available()							,   """test requires the Hugging Face suite"""      )(UpperCamelCase      )
def        _SCREAMING_SNAKE_CASE  (	UpperCamelCase      ):



    """simple docstring"""





    return unittest.skipUnless(is_bnb_available()							,   """test requires the bitsandbytes library"""      )(UpperCamelCase      )
def        _SCREAMING_SNAKE_CASE  (	UpperCamelCase      ):



    """simple docstring"""





    return unittest.skipUnless(is_tpu_available()							,   """test requires TPU"""      )(UpperCamelCase      )
def        _SCREAMING_SNAKE_CASE  (	UpperCamelCase      ):



    """simple docstring"""





    return unittest.skipUnless(torch.cuda.device_count() == 1							,   """test requires a GPU"""      )(UpperCamelCase      )
def        _SCREAMING_SNAKE_CASE  (	UpperCamelCase      ):



    """simple docstring"""





    return unittest.skipUnless(torch.xpu.device_count() == 1							,   """test requires a XPU"""      )(UpperCamelCase      )
def        _SCREAMING_SNAKE_CASE  (	UpperCamelCase      ):



    """simple docstring"""





    return unittest.skipUnless(torch.cuda.device_count() > 1							,   """test requires multiple GPUs"""      )(UpperCamelCase      )
def        _SCREAMING_SNAKE_CASE  (	UpperCamelCase      ):



    """simple docstring"""





    return unittest.skipUnless(torch.xpu.device_count() > 1							,   """test requires multiple XPUs"""      )(UpperCamelCase      )
def        _SCREAMING_SNAKE_CASE  (	UpperCamelCase      ):



    """simple docstring"""





    return unittest.skipUnless(is_safetensors_available()							,   """test requires safetensors"""      )(UpperCamelCase      )
def        _SCREAMING_SNAKE_CASE  (	UpperCamelCase      ):



    """simple docstring"""





    return unittest.skipUnless(is_deepspeed_available()							,   """test requires DeepSpeed"""      )(UpperCamelCase      )
def        _SCREAMING_SNAKE_CASE  (	UpperCamelCase      ):



    """simple docstring"""





    return unittest.skipUnless(is_torch_version(""">="""							,   """1.12.0"""      )							,   """test requires torch version >= 1.12.0"""      )(UpperCamelCase      )
def        _SCREAMING_SNAKE_CASE  (	UpperCamelCase=None							,   UpperCamelCase=None      ):



    """simple docstring"""





    if test_case is None:
        return partial(UpperCamelCase							,   version=UpperCamelCase      )
    return unittest.skipUnless(is_torch_version(""">="""							,   UpperCamelCase      )							,   f"""test requires torch version >= {version}"""      )(UpperCamelCase      )
def        _SCREAMING_SNAKE_CASE  (	UpperCamelCase      ):



    """simple docstring"""





    return unittest.skipUnless(is_tensorboard_available()							,   """test requires Tensorboard"""      )(UpperCamelCase      )
def        _SCREAMING_SNAKE_CASE  (	UpperCamelCase      ):



    """simple docstring"""





    return unittest.skipUnless(is_wandb_available()							,   """test requires wandb"""      )(UpperCamelCase      )
def        _SCREAMING_SNAKE_CASE  (	UpperCamelCase      ):



    """simple docstring"""





    return unittest.skipUnless(is_comet_ml_available()							,   """test requires comet_ml"""      )(UpperCamelCase      )


_lowerCAmelCase										=     (
    any([is_wandb_available(), is_tensorboard_available()]) and not is_comet_ml_available()
)
def        _SCREAMING_SNAKE_CASE  (	UpperCamelCase      ):



    """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"""							,   )(UpperCamelCase      )






class 	lowerCAmelCase_(    unittest.TestCase					):
  '''simple docstring'''




  __lowercase							:				List[str]           =				True




  @classmethod
  def 							UpperCAmelCase_     (   cls				)   ->		Optional[Any]:
      lowerCAmelCase__			:  str											= tempfile.mkdtemp()




  @classmethod
  def 							UpperCAmelCase_     (   cls				)   ->		str:
      if os.path.exists(cls.tmpdir				):
          shutil.rmtree(cls.tmpdir				)






  def 							UpperCAmelCase_     (   self				)   ->		Optional[int]:
      if self.clear_on_setup:
          for path in Path(self.tmpdir				).glob("""**/*"""				):
              if path.is_file():
                  path.unlink()
              elif path.is_dir():
                  shutil.rmtree(__UpperCAmelCase				)







class 	lowerCAmelCase_(    unittest.TestCase					):
  '''simple docstring'''




  def 							UpperCAmelCase_     (   self				)   ->		str:
      super().tearDown()
      # Reset the state of the AcceleratorState singleton.
      AcceleratorState._reset_state()
      PartialState._reset_state()







class 	lowerCAmelCase_(    unittest.TestCase					):
  '''simple docstring'''




  def 							UpperCAmelCase_     (   self  ,__UpperCAmelCase				)   ->		List[Any]:
      lowerCAmelCase__			:  Tuple											= mocks if isinstance(__UpperCAmelCase  ,(tuple, list)				) else [mocks]
      for m in self.mocks:
          m.start()
          self.addCleanup(m.stop				)







def        _SCREAMING_SNAKE_CASE  (	UpperCamelCase      ):



    """simple docstring"""





    lowerCAmelCase__			:  Optional[int]											= AcceleratorState()
    lowerCAmelCase__			:  Any											= tensor[None].clone().to(state.device      )
    lowerCAmelCase__			:  Dict											= gather(UpperCamelCase      ).cpu()
    lowerCAmelCase__			:  Tuple											= tensor[0].cpu()
    for i in range(tensors.shape[0]      ):
        if not torch.equal(tensors[i]							,   UpperCamelCase      ):
            return False
    return True






class 	lowerCAmelCase_:
  '''simple docstring'''




  def __init__(   self  ,__UpperCAmelCase  ,__UpperCAmelCase  ,__UpperCAmelCase				)   ->		Dict:
      lowerCAmelCase__			:  Optional[Any]											= returncode
      lowerCAmelCase__			:  Optional[Any]											= stdout
      lowerCAmelCase__			:  List[str]											= stderr







async def        _SCREAMING_SNAKE_CASE  (	UpperCamelCase							,   UpperCamelCase      ):



    """simple docstring"""





    while True:
        lowerCAmelCase__			:  str											= await stream.readline()
        if line:
            callback(UpperCamelCase      )
        else:
            break
async def        _SCREAMING_SNAKE_CASE  (	UpperCamelCase							,   UpperCamelCase=None							,   UpperCamelCase=None							,   UpperCamelCase=None							,   UpperCamelCase=False							,   UpperCamelCase=False      ):



    """simple docstring"""





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

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

    # 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__			:  Union[str, Any]											= []
    lowerCAmelCase__			:  Any											= []

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

    # XXX: the timeout doesn't seem to make any difference here
    await asyncio.wait(
        [
            asyncio.create_task(_read_stream(p.stdout							,   lambda UpperCamelCase      : tee(UpperCamelCase							,   UpperCamelCase							,   sys.stdout							,   label="""stdout:"""      )      )      ),
            asyncio.create_task(_read_stream(p.stderr							,   lambda UpperCamelCase      : tee(UpperCamelCase							,   UpperCamelCase							,   sys.stderr							,   label="""stderr:"""      )      )      ),
        ]							,   timeout=UpperCamelCase							,   )
    return _RunOutput(await p.wait()							,   UpperCamelCase							,   UpperCamelCase      )
def        _SCREAMING_SNAKE_CASE  (	UpperCamelCase							,   UpperCamelCase=None							,   UpperCamelCase=None							,   UpperCamelCase=180							,   UpperCamelCase=False							,   UpperCamelCase=True      ):



    """simple docstring"""





    lowerCAmelCase__			:  Dict											= asyncio.get_event_loop()
    lowerCAmelCase__			:  Dict											= loop.run_until_complete(
        _stream_subprocess(UpperCamelCase							,   env=UpperCamelCase							,   stdin=UpperCamelCase							,   timeout=UpperCamelCase							,   quiet=UpperCamelCase							,   echo=UpperCamelCase      )      )

    lowerCAmelCase__			:  Dict											= """ """.join(UpperCamelCase      )
    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 	lowerCAmelCase_(    SCREAMING_SNAKE_CASE_					):
  '''simple docstring'''




  pass







def        _SCREAMING_SNAKE_CASE  (	UpperCamelCase							,   UpperCamelCase=False      ):



    """simple docstring"""





    try:
        lowerCAmelCase__			:  List[Any]											= subprocess.check_output(UpperCamelCase							,   stderr=subprocess.STDOUT      )
        if return_stdout:
            if hasattr(UpperCamelCase							,   """decode"""      ):
                lowerCAmelCase__			:  List[str]											= output.decode("""utf-8"""      )
            return output
    except subprocess.CalledProcessError as e:
        raise SubprocessCallException(
            f"""Command `{' '.join(UpperCamelCase      )}` failed with the following error:\n\n{e.output.decode()}"""      ) from e







'''simple docstring'''





def        _SCREAMING_SNAKE_CASE  (	UpperCamelCase = 1000      ):



    """simple docstring"""





    lowerCAmelCase__			:  Union[str, Any]											= -1
    lowerCAmelCase__			:  Optional[Any]											= 0
    for a in range(1							,   n // 3      ):
        # Solving the two equations a**2+b**2=c**2 and a+b+c=N eliminating c
        lowerCAmelCase__			:  Optional[Any]											= (n * n - 2 * a * n) // (2 * n - 2 * a)
        lowerCAmelCase__			:  Tuple											= n - a - b
        if c * c == (a * a + b * b):
            lowerCAmelCase__			:  int											= a * b * c
            if candidate >= product:
                lowerCAmelCase__			:  Any											= candidate
    return product


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


