



"""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				):
      try:
            UpperCAmelCase_      			=							os.environ[key]
      except KeyError:
            # KEY isn't set, default to `default`.
            UpperCAmelCase_      			=							default
      else:
            # KEY is set, convert it to True or False.
            try:
                  UpperCAmelCase_      			=							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       	=						parse_flag_from_env("""RUN_SLOW""", default=False)
lowerCamelCase       	=						parse_flag_from_env("""RUN_REMOTE""", default=False)
lowerCamelCase       	=						parse_flag_from_env("""RUN_LOCAL""", default=True)
lowerCamelCase       	=						parse_flag_from_env("""RUN_PACKAGED""", default=True)

# Compression
lowerCamelCase       	=						pytest.mark.skipif(not config.LZ4_AVAILABLE, reason="""test requires lz4""")
lowerCamelCase       	=						pytest.mark.skipif(not config.PY7ZR_AVAILABLE, reason="""test requires py7zr""")
lowerCamelCase       	=						pytest.mark.skipif(not config.ZSTANDARD_AVAILABLE, reason="""test requires zstandard""")

# Audio
lowerCamelCase       	=						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       	=						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       	=						pytest.mark.skipif(
    config.DILL_VERSION <= version.parse("""0.3.2"""),
    reason="""test requires dill>0.3.2 for cloudpickle compatibility""",
)

# Windows
lowerCamelCase       	=						pytest.mark.skipif(
    sys.platform == """win32""",
    reason="""test should not be run on Windows""",
)
def        a__     (				lowerCAmelCase__				):
      try:
            import faiss  # noqa
      except ImportError:
            UpperCAmelCase_      			=							unittest.skip("test requires faiss"				)(lowerCAmelCase__				)
      return test_case
def        a__     (				lowerCAmelCase__				):
      try:
            import regex  # noqa
      except ImportError:
            UpperCAmelCase_      			=							unittest.skip("test requires regex"				)(lowerCAmelCase__				)
      return test_case
def        a__     (				lowerCAmelCase__				):
      try:
            import elasticsearch  # noqa
      except ImportError:
            UpperCAmelCase_      			=							unittest.skip("test requires elasticsearch"				)(lowerCAmelCase__				)
      return test_case
def        a__     (				lowerCAmelCase__				):
      try:
            import sqlalchemy  # noqa
      except ImportError:
            UpperCAmelCase_      			=							unittest.skip("test requires sqlalchemy"				)(lowerCAmelCase__				)
      return test_case
def        a__     (				lowerCAmelCase__				):
      if not config.TORCH_AVAILABLE:
            UpperCAmelCase_      			=							unittest.skip("test requires PyTorch"				)(lowerCAmelCase__				)
      return test_case
def        a__     (				lowerCAmelCase__				):
      if not config.TF_AVAILABLE:
            UpperCAmelCase_      			=							unittest.skip("test requires TensorFlow"				)(lowerCAmelCase__				)
      return test_case
def        a__     (				lowerCAmelCase__				):
      if not config.JAX_AVAILABLE:
            UpperCAmelCase_      			=							unittest.skip("test requires JAX"				)(lowerCAmelCase__				)
      return test_case
def        a__     (				lowerCAmelCase__				):
      if not config.PIL_AVAILABLE:
            UpperCAmelCase_      			=							unittest.skip("test requires Pillow"				)(lowerCAmelCase__				)
      return test_case
def        a__     (				lowerCAmelCase__				):
      try:
            import transformers  # noqa F401
      except ImportError:
            return unittest.skip("test requires transformers"				)(lowerCAmelCase__				)
      else:
            return test_case
def        a__     (				lowerCAmelCase__				):
      try:
            import tiktoken  # noqa F401
      except ImportError:
            return unittest.skip("test requires tiktoken"				)(lowerCAmelCase__				)
      else:
            return test_case
def        a__     (				lowerCAmelCase__				):
      try:
            import spacy  # noqa F401
      except ImportError:
            return unittest.skip("test requires spacy"				)(lowerCAmelCase__				)
      else:
            return test_case
def        a__     (				lowerCAmelCase__				):

      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__				):
      try:
            import pyspark  # noqa F401
      except ImportError:
            return unittest.skip("test requires pyspark"				)(lowerCAmelCase__				)
      else:
            return test_case
def        a__     (				lowerCAmelCase__				):
      try:
            import joblibspark  # noqa F401
      except ImportError:
            return unittest.skip("test requires joblibspark"				)(lowerCAmelCase__				)
      else:
            return test_case
def        a__     (				lowerCAmelCase__				):
      if not _run_slow_tests or _run_slow_tests == 0:
            UpperCAmelCase_      			=							unittest.skip("test is slow"				)(lowerCAmelCase__				)
      return test_case
def        a__     (				lowerCAmelCase__				):
      if not _run_local_tests or _run_local_tests == 0:
            UpperCAmelCase_      			=							unittest.skip("test is local"				)(lowerCAmelCase__				)
      return test_case
def        a__     (				lowerCAmelCase__				):
      if not _run_packaged_tests or _run_packaged_tests == 0:
            UpperCAmelCase_      			=							unittest.skip("test is packaged"				)(lowerCAmelCase__				)
      return test_case
def        a__     (				lowerCAmelCase__				):
      if not _run_remote_tests or _run_remote_tests == 0:
            UpperCAmelCase_      			=							unittest.skip("test requires remote"				)(lowerCAmelCase__				)
      return test_case
def        a__     (				*lowerCAmelCase__				):
      def decorate(cls				):
            for name, fn in cls.__dict__.items():
                  if callable(lowerCAmelCase__				) and name.startswith("test"				):
                        for decorator in decorators:
                              UpperCAmelCase_      			=							decorator(lowerCAmelCase__				)
                        setattr(cls     ,      lowerCAmelCase__     ,      lowerCAmelCase__				)
            return cls

      return decorate
class 				lowercase__       (   SCREAMING_SNAKE_CASE				):







       '''simple docstring'''


       pass



class 				lowercase__       (   SCREAMING_SNAKE_CASE				):







       '''simple docstring'''


       UpperCamelCase						=					0
       UpperCamelCase						=					1
       UpperCamelCase						=					2



@contextmanager
def        a__     (				lowerCAmelCase__=OfflineSimulationMode.CONNECTION_FAILS     ,      lowerCAmelCase__=1e-16				):
      UpperCAmelCase_      			=							requests.Session().request

      def timeout_request(lowerCAmelCase__     ,      lowerCAmelCase__     ,      lowerCAmelCase__     ,      **lowerCAmelCase__				):
            # Change the url to an invalid url so that the connection hangs
            UpperCAmelCase_      			=							"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_      			=							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
                  UpperCAmelCase_      			=							url
                  UpperCAmelCase_      			=							e.args[0]
                  UpperCAmelCase_      			=							(max_retry_error.args[0].replace("10.255.255.1"     ,      f"""OfflineMock[{url}]"""				),)
                  UpperCAmelCase_      			=							(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__				):
      UpperCAmelCase_      			=							str(Path().resolve()				)
      with tempfile.TemporaryDirectory(*lowerCAmelCase__     ,      **lowerCAmelCase__				) as tmp_dir:
            try:
                  os.chdir(lowerCAmelCase__				)
                  yield
            finally:
                  os.chdir(lowerCAmelCase__				)
@contextmanager
def        a__     (				):
      import gc

      gc.collect()
      UpperCAmelCase_      			=							pa.total_allocated_bytes()
      yield
      assert pa.total_allocated_bytes() - previous_allocated_memory > 0, "Arrow memory didn't increase."
@contextmanager
def        a__     (				):
      import gc

      gc.collect()
      UpperCAmelCase_      			=							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__				):
      return deepcopy(lowerCAmelCase__				).integers(0     ,      100     ,      10				).tolist() == deepcopy(lowerCAmelCase__				).integers(0     ,      100     ,      10				).tolist()
def        a__     (				lowerCAmelCase__				):
      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 				lowercase__       :







       '''simple docstring'''


       def __init__(							self      :  Optional[Any]		,    _UpperCAmelCase      :  Any		,    _UpperCAmelCase      :  str		,    _UpperCAmelCase      :  Optional[Any]   )			->						Any:


             '''simple docstring'''




             UpperCAmelCase_      			=							returncode
             UpperCAmelCase_      			=							stdout
             UpperCAmelCase_      			=							stderr



async def        a__     (				lowerCAmelCase__     ,      lowerCAmelCase__				):
      while True:
            UpperCAmelCase_      			=							await stream.readline()
            if line:
                  callback(lowerCAmelCase__				)
            else:
                  break
async def        a__     (				lowerCAmelCase__     ,      lowerCAmelCase__=None     ,      lowerCAmelCase__=None     ,      lowerCAmelCase__=None     ,      lowerCAmelCase__=False     ,      lowerCAmelCase__=False				):
      if echo:
            print("\nRunning: "     ,      " ".join(lowerCAmelCase__				)				)

      UpperCAmelCase_      			=							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)

      UpperCAmelCase_      			=							[]
      UpperCAmelCase_      			=							[]

      def tee(lowerCAmelCase__     ,      lowerCAmelCase__     ,      lowerCAmelCase__     ,      lowerCAmelCase__=""				):
            UpperCAmelCase_      			=							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__=180     ,      lowerCAmelCase__=False     ,      lowerCAmelCase__=True				):
      UpperCAmelCase_      			=							asyncio.get_event_loop()
      UpperCAmelCase_      			=							loop.run_until_complete(
          _stream_subprocess(lowerCAmelCase__     ,      env=lowerCAmelCase__     ,      stdin=lowerCAmelCase__     ,      timeout=lowerCAmelCase__     ,      quiet=lowerCAmelCase__     ,      echo=lowerCAmelCase__				)				)

      UpperCAmelCase_      			=							" ".join(lowerCAmelCase__				)
      if result.returncode > 0:
            UpperCAmelCase_      			=							"\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__     (				):
      UpperCAmelCase_      			=							os.environ.get("PYTEST_XDIST_WORKER"     ,      "gw0"				)
      UpperCAmelCase_      			=							re.sub(r"^gw"     ,      ""     ,      lowerCAmelCase__     ,      0     ,      re.M				)
      return int(lowerCAmelCase__				)


def        a__     (				):
      UpperCAmelCase_      			=							29500
      UpperCAmelCase_      			=							pytest_xdist_worker_id()
      return port + uniq_delta









"""simple docstring"""





from __future__ import annotations

from collections import namedtuple
from dataclasses import dataclass
@dataclass
class 				lowercase__       :







       '''simple docstring'''


       UpperCamelCase						=					42
       UpperCamelCase						=					None
       UpperCamelCase						=					None



lowerCamelCase       	=						namedtuple("""CoinsDistribResult""", """moves excess""")
def        a__     (				lowerCAmelCase__				):

      if root is None:
            return 0

      # Validation
      def count_nodes(lowerCAmelCase__				) -> int:
            if node is None:
                  return 0

            return count_nodes(node.left				) + count_nodes(node.right				) + 1

      def count_coins(lowerCAmelCase__				) -> int:
            if node is None:
                  return 0

            return count_coins(node.left				) + count_coins(node.right				) + node.data

      if count_nodes(lowerCAmelCase__				) != count_coins(lowerCAmelCase__				):
            raise ValueError("The nodes number should be same as the number of coins"				)

      # Main calculation
      def get_distrib(lowerCAmelCase__				) -> CoinsDistribResult:

            if node is None:
                  return CoinsDistribResult(0     ,      1				)

            UpperCAmelCase_			,   UpperCAmelCase_      			=							get_distrib(node.left				)
            UpperCAmelCase_			,   UpperCAmelCase_      			=							get_distrib(node.right				)

            UpperCAmelCase_      			=							1 - left_distrib_excess
            UpperCAmelCase_      			=							1 - right_distrib_excess

            UpperCAmelCase_      			=							(
                left_distrib_moves
                + right_distrib_moves
                + abs(lowerCAmelCase__				)
                + abs(lowerCAmelCase__				)
            )
            UpperCAmelCase_      			=							node.data - coins_to_left - coins_to_right

            return CoinsDistribResult(lowerCAmelCase__     ,      lowerCAmelCase__				)

      return get_distrib(lowerCAmelCase__				)[0]


if __name__ == "__main__":
  import doctest

  doctest.testmod()




