


'''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__					:Optional[Any]			,  lowerCAmelCase__					:Optional[Any]=False						)				->					Dict:




     '''simple docstring'''



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


a_   :      int				    =      parse_flag_from_env("RUN_SLOW", default=False)
a_   :      Union[str, Any]				    =      parse_flag_from_env("RUN_REMOTE", default=False)
a_   :      Dict				    =      parse_flag_from_env("RUN_LOCAL", default=True)
a_   :      Optional[int]				    =      parse_flag_from_env("RUN_PACKAGED", default=True)

# Compression
a_   :      int				    =      pytest.mark.skipif(not config.LZ4_AVAILABLE, reason="test requires lz4")
a_   :      Optional[Any]				    =      pytest.mark.skipif(not config.PY7ZR_AVAILABLE, reason="test requires py7zr")
a_   :      List[Any]				    =      pytest.mark.skipif(not config.ZSTANDARD_AVAILABLE, reason="test requires zstandard")

# Audio
a_   :      List[Any]				    =      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
a_   :      List[str]				    =      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
a_   :      str				    =      pytest.mark.skipif(
    config.DILL_VERSION <= version.parse("0.3.2"),
    reason="test requires dill>0.3.2 for cloudpickle compatibility",
)

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






def 		_A			(lowerCAmelCase__					:List[Any]						)				->					List[Any]:




     '''simple docstring'''



     try:
          import faiss  # noqa
     except ImportError:
          _a      =							unittest.skip('test requires faiss'						)(lowerCAmelCase__						)
     return test_case






def 		_A			(lowerCAmelCase__					:List[Any]						)				->					Optional[int]:




     '''simple docstring'''



     try:
          import regex  # noqa
     except ImportError:
          _a      =							unittest.skip('test requires regex'						)(lowerCAmelCase__						)
     return test_case






def 		_A			(lowerCAmelCase__					:str						)				->					Dict:




     '''simple docstring'''



     try:
          import elasticsearch  # noqa
     except ImportError:
          _a      =							unittest.skip('test requires elasticsearch'						)(lowerCAmelCase__						)
     return test_case






def 		_A			(lowerCAmelCase__					:Any						)				->					List[str]:




     '''simple docstring'''



     try:
          import sqlalchemy  # noqa
     except ImportError:
          _a      =							unittest.skip('test requires sqlalchemy'						)(lowerCAmelCase__						)
     return test_case






def 		_A			(lowerCAmelCase__					:Union[str, Any]						)				->					List[Any]:




     '''simple docstring'''



     if not config.TORCH_AVAILABLE:
          _a      =							unittest.skip('test requires PyTorch'						)(lowerCAmelCase__						)
     return test_case






def 		_A			(lowerCAmelCase__					:Optional[int]						)				->					Dict:




     '''simple docstring'''



     if not config.TF_AVAILABLE:
          _a      =							unittest.skip('test requires TensorFlow'						)(lowerCAmelCase__						)
     return test_case






def 		_A			(lowerCAmelCase__					:str						)				->					int:




     '''simple docstring'''



     if not config.JAX_AVAILABLE:
          _a      =							unittest.skip('test requires JAX'						)(lowerCAmelCase__						)
     return test_case






def 		_A			(lowerCAmelCase__					:Dict						)				->					Dict:




     '''simple docstring'''



     if not config.PIL_AVAILABLE:
          _a      =							unittest.skip('test requires Pillow'						)(lowerCAmelCase__						)
     return test_case






def 		_A			(lowerCAmelCase__					:str						)				->					Optional[Any]:




     '''simple docstring'''



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






def 		_A			(lowerCAmelCase__					:Any						)				->					str:




     '''simple docstring'''



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






def 		_A			(lowerCAmelCase__					:Optional[Any]						)				->					Union[str, Any]:




     '''simple docstring'''



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






def 		_A			(lowerCAmelCase__					:Tuple						)				->					Optional[Any]:




     '''simple docstring'''



     def _require_spacy_model(lowerCAmelCase__					:Dict						):
          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__					:Optional[int]						)				->					List[str]:




     '''simple docstring'''



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






def 		_A			(lowerCAmelCase__					:Optional[int]						)				->					List[str]:




     '''simple docstring'''



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






def 		_A			(lowerCAmelCase__					:Tuple						)				->					Any:




     '''simple docstring'''



     if not _run_slow_tests or _run_slow_tests == 0:
          _a      =							unittest.skip('test is slow'						)(lowerCAmelCase__						)
     return test_case






def 		_A			(lowerCAmelCase__					:Optional[Any]						)				->					int:




     '''simple docstring'''



     if not _run_local_tests or _run_local_tests == 0:
          _a      =							unittest.skip('test is local'						)(lowerCAmelCase__						)
     return test_case






def 		_A			(lowerCAmelCase__					:List[Any]						)				->					str:




     '''simple docstring'''



     if not _run_packaged_tests or _run_packaged_tests == 0:
          _a      =							unittest.skip('test is packaged'						)(lowerCAmelCase__						)
     return test_case






def 		_A			(lowerCAmelCase__					:Any						)				->					Tuple:




     '''simple docstring'''



     if not _run_remote_tests or _run_remote_tests == 0:
          _a      =							unittest.skip('test requires remote'						)(lowerCAmelCase__						)
     return test_case






def 		_A			(*lowerCAmelCase__					:List[str]						)				->					str:




     '''simple docstring'''



     def decorate(cls					:Dict						):
          for name, fn in cls.__dict__.items():
               if callable(lowerCAmelCase__						) and name.startswith('test'						):
                    for decorator in decorators:
                         _a      =							decorator(lowerCAmelCase__						)
                    setattr(cls			,  lowerCAmelCase__			,  lowerCAmelCase__						)
          return cls

     return decorate




class 	a       (       _SCREAMING_SNAKE_CASE    ):
 pass





class 	a       (       _SCREAMING_SNAKE_CASE    ):
 _lowerCAmelCase	   =		0
 _lowerCAmelCase	   =		1
 _lowerCAmelCase	   =		2






@contextmanager
def 		_A			(lowerCAmelCase__					:List[Any]=OfflineSimulationMode.CONNECTION_FAILS			,  lowerCAmelCase__					:Optional[int]=1E-16						)				->					List[str]:




     '''simple docstring'''



     _a      =							requests.Session().request

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

     def raise_connection_error(lowerCAmelCase__					:Optional[Any]			,  lowerCAmelCase__					:Any			,  **lowerCAmelCase__					:Optional[Any]						):
          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__					:Optional[Any]			,  **lowerCAmelCase__					:Dict						)				->					Optional[int]:




     '''simple docstring'''



     _a      =							str(Path().resolve()						)
     with tempfile.TemporaryDirectory(*lowerCAmelCase__			,  **lowerCAmelCase__						) as tmp_dir:
          try:
               os.chdir(lowerCAmelCase__						)
               yield
          finally:
               os.chdir(lowerCAmelCase__						)






@contextmanager
def 		_A			()				->					Any:




     '''simple docstring'''



     import gc

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






@contextmanager
def 		_A			()				->					Dict:




     '''simple docstring'''



     import gc

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






def 		_A			(lowerCAmelCase__					:Tuple			,  lowerCAmelCase__					:Dict						)				->					Dict:




     '''simple docstring'''



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






def 		_A			(lowerCAmelCase__					:List[str]						)				->					List[str]:




     '''simple docstring'''



     import decorator
     from requests.exceptions import HTTPError

     def _wrapper(lowerCAmelCase__					:int			,  *lowerCAmelCase__					:Tuple			,  **lowerCAmelCase__					:Union[str, Any]						):
          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 	a       :
 def __init__(	self ,			__magic_name__ ,			__magic_name__ ,			__magic_name__  )   ->							int:
      _a      =							returncode
      _a      =							stdout
      _a      =							stderr






async def 		_A			(lowerCAmelCase__					:List[Any]			,  lowerCAmelCase__					:str						)				->					Dict:




     '''simple docstring'''



     while True:
          _a      =							await stream.readline()
          if line:
               callback(lowerCAmelCase__						)
          else:
               break






async def 		_A			(lowerCAmelCase__					:int			,  lowerCAmelCase__					:Optional[Any]=None			,  lowerCAmelCase__					:str=None			,  lowerCAmelCase__					:List[str]=None			,  lowerCAmelCase__					:Optional[Any]=False			,  lowerCAmelCase__					:int=False						)				->					Optional[Any]:




     '''simple docstring'''



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

     _a      =							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      =							[]
     _a      =							[]

     def tee(lowerCAmelCase__					:Tuple			,  lowerCAmelCase__					:str			,  lowerCAmelCase__					:Tuple			,  lowerCAmelCase__					:Optional[Any]=""						):
          _a      =							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__					:str			,  lowerCAmelCase__					:List[str]=None			,  lowerCAmelCase__					:str=None			,  lowerCAmelCase__					:Any=1_80			,  lowerCAmelCase__					:List[Any]=False			,  lowerCAmelCase__					:Optional[int]=True						)				->					List[Any]:




     '''simple docstring'''



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

     _a      =							''' '''.join(lowerCAmelCase__						)
     if result.returncode > 0:
          _a      =							'''\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			()				->					int:




     '''simple docstring'''



     _a      =							os.environ.get('PYTEST_XDIST_WORKER'			,  'gw0'						)
     _a      =							re.sub(r'^gw'			,  ''			,  lowerCAmelCase__			,  0			,  re.M						)
     return int(lowerCAmelCase__						)






def 		_A			()				->					Optional[int]:




     '''simple docstring'''



     _a      =							2_95_00
     _a      =							pytest_xdist_worker_id()
     return port + uniq_delta





'''simple docstring'''






from __future__ import annotations

from sys import maxsize
from typing import Generic, TypeVar

a_   :      Optional[Any]				    =      TypeVar("T")






def 		_A			(lowerCAmelCase__					:int						)				->					int:




     '''simple docstring'''



     return (position - 1) // 2






def 		_A			(lowerCAmelCase__					:int						)				->					int:




     '''simple docstring'''



     return (2 * position) + 1






def 		_A			(lowerCAmelCase__					:int						)				->					int:




     '''simple docstring'''



     return (2 * position) + 2




class 	a       (       Generic[T]    ):
 def __init__(	self  )   ->							None:
      _a      =							[]
      _a      =							{}
      _a      =							0
 def __len__(	self  )   ->							int:
      return self.elements
 def __repr__(	self  )   ->							str:
      return str(self.heap  )
 def 							__UpperCAmelCase						(	self  )   ->							bool:
      # Check if the priority queue is empty
      return self.elements == 0
 def 							__UpperCAmelCase						(	self ,			__magic_name__ ,			__magic_name__  )   ->							None:
      # Add an element with given priority to the queue
      self.heap.append((elem, weight)  )
      _a      =							self.elements
      self.elements += 1
      self._bubble_up(__magic_name__  )
 def 							__UpperCAmelCase						(	self  )   ->							T:
      # Remove and return the element with lowest weight (highest priority)
      if self.elements > 1:
           self._swap_nodes(0 ,			self.elements - 1  )
      _a ,				_a      =							self.heap.pop()
      del self.position_map[elem]
      self.elements -= 1
      if self.elements > 0:
           _a ,				_a      =							self.heap[0]
           self._bubble_down(__magic_name__  )
      return elem
 def 							__UpperCAmelCase						(	self ,			__magic_name__ ,			__magic_name__  )   ->							None:
      # Update the weight of the given key
      _a      =							self.position_map[elem]
      _a      =							(elem, weight)
      if position > 0:
           _a      =							get_parent_position(__magic_name__  )
           _a ,				_a      =							self.heap[parent_position]
           if parent_weight > weight:
                self._bubble_up(__magic_name__  )
           else:
                self._bubble_down(__magic_name__  )
      else:
           self._bubble_down(__magic_name__  )
 def 							__UpperCAmelCase						(	self ,			__magic_name__  )   ->							None:
      # Place a node at the proper position (upward movement) [to be used internally
      # only]
      _a      =							self.position_map[elem]
      if curr_pos == 0:
           return None
      _a      =							get_parent_position(__magic_name__  )
      _a ,				_a      =							self.heap[curr_pos]
      _a ,				_a      =							self.heap[parent_position]
      if parent_weight > weight:
           self._swap_nodes(__magic_name__ ,			__magic_name__  )
           return self._bubble_up(__magic_name__  )
      return None
 def 							__UpperCAmelCase						(	self ,			__magic_name__  )   ->							None:
      # Place a node at the proper position (downward movement) [to be used
      # internally only]
      _a      =							self.position_map[elem]
      _a ,				_a      =							self.heap[curr_pos]
      _a      =							get_child_left_position(__magic_name__  )
      _a      =							get_child_right_position(__magic_name__  )
      if child_left_position < self.elements and child_right_position < self.elements:
           _a ,				_a      =							self.heap[child_left_position]
           _a ,				_a      =							self.heap[child_right_position]
           if child_right_weight < child_left_weight and child_right_weight < weight:
                self._swap_nodes(__magic_name__ ,			__magic_name__  )
                return self._bubble_down(__magic_name__  )
      if child_left_position < self.elements:
           _a ,				_a      =							self.heap[child_left_position]
           if child_left_weight < weight:
                self._swap_nodes(__magic_name__ ,			__magic_name__  )
                return self._bubble_down(__magic_name__  )
      else:
           return None
      if child_right_position < self.elements:
           _a ,				_a      =							self.heap[child_right_position]
           if child_right_weight < weight:
                self._swap_nodes(__magic_name__ ,			__magic_name__  )
                return self._bubble_down(__magic_name__  )
      return None




 def 							__UpperCAmelCase						(	self ,			__magic_name__ ,			__magic_name__  )   ->							None:
      # Swap the nodes at the given positions
      _a      =							self.heap[nodea_pos][0]
      _a      =							self.heap[nodea_pos][0]
      _a ,				_a      =							(
          self.heap[nodea_pos],
          self.heap[nodea_pos],
      )
      _a      =							nodea_pos
      _a      =							nodea_pos





class 	a       (       Generic[T]    ):
 def __init__(	self  )   ->							None:
      _a      =							{}
      _a      =							0
 def __repr__(	self  )   ->							str:
      return str(self.connections  )
 def __len__(	self  )   ->							int:
      return self.nodes
 def 							__UpperCAmelCase						(	self ,			__magic_name__  )   ->							None:
      # Add a node in the graph if it is not in the graph
      if node not in self.connections:
           _a      =							{}
           self.nodes += 1




 def 							__UpperCAmelCase						(	self ,			__magic_name__ ,			__magic_name__ ,			__magic_name__  )   ->							None:
      # Add an edge between 2 nodes in the graph
      self.add_node(__magic_name__  )
      self.add_node(__magic_name__  )
      _a      =							weight
      _a      =							weight






def 		_A			(lowerCAmelCase__					:GraphUndirectedWeighted[T]			,  )				->					tuple[dict[T, int], dict[T, T | None]]:




     '''simple docstring'''



     _a      =							{node: maxsize for node in graph.connections}
     _a      =							{node: None for node in graph.connections}

     _a      =							MinPriorityQueue()
     for node, weight in dist.items():
          priority_queue.push(lowerCAmelCase__			,  lowerCAmelCase__						)

     if priority_queue.is_empty():
          return dist, parent

     # initialization
     _a      =							priority_queue.extract_min()
     _a      =							0
     for neighbour in graph.connections[node]:
          if dist[neighbour] > dist[node] + graph.connections[node][neighbour]:
               _a      =							dist[node] + graph.connections[node][neighbour]
               priority_queue.update_key(lowerCAmelCase__			,  dist[neighbour]						)
               _a      =							node

    # running prim's algorithm
     while not priority_queue.is_empty():
          _a      =							priority_queue.extract_min()
          for neighbour in graph.connections[node]:
               if dist[neighbour] > dist[node] + graph.connections[node][neighbour]:
                    _a      =							dist[node] + graph.connections[node][neighbour]
                    priority_queue.update_key(lowerCAmelCase__			,  dist[neighbour]						)
                    _a      =							node
     return dist, parent

