

"""simple docstring"""






import sys
from collections.abc import Mapping

import numpy as np
import pyarrow as pa

from .. import config
from ..utils.py_utils import map_nested
from .formatting import TensorFormatter






class     _UpperCAmelCase			(		TensorFormatter[Mapping, np.ndarray, Mapping]):
			def __init__(		self      ,		_A=None      ,		**_A     )    ->    int:






				'''simple docstring'''







				super().__init__(features=_A     )
				_UpperCAmelCase    :							Dict									=					np_array_kwargs
			def 							__snake_case (		self      ,		_A     )    ->    str:






				'''simple docstring'''







				if isinstance(_A      ,		_A     ):
					if column and all(
					    isinstance(_A      ,		np.ndarray     ) and x.shape == column[0].shape and x.dtype == column[0].dtype for x in column     ):
						return np.stack(_A     )
					else:
						# don't use np.array(column, dtype=object)
						# since it fails in certain cases
						# see https://stackoverflow.com/q/51005699
						_UpperCAmelCase    :							Optional[Any]									=					np.empty(len(_A     )      ,		dtype=_A     )
						_UpperCAmelCase    :							List[str]									=					column
						return out
				return column
			def 							__snake_case (		self      ,		_A     )    ->    str:






				'''simple docstring'''







				if isinstance(_A      ,		(str, bytes, type(_A     ))     ):
					return value
				elif isinstance(_A      ,		(np.character, np.ndarray)     ) and np.issubdtype(value.dtype      ,		np.character     ):
					return value
				elif isinstance(_A      ,		np.number     ):
					return value

				_UpperCAmelCase    :							int									=					{}

				if isinstance(_A      ,		np.ndarray     ) and np.issubdtype(value.dtype      ,		np.integer     ):
					_UpperCAmelCase    :							Tuple									=					{"""dtype""": np.intaa}
				elif isinstance(_A      ,		np.ndarray     ) and np.issubdtype(value.dtype      ,		np.floating     ):
					_UpperCAmelCase    :							Tuple									=					{"""dtype""": np.floataa}
				elif config.PIL_AVAILABLE and "PIL" in sys.modules:
					import PIL.Image

					if isinstance(_A      ,		PIL.Image.Image     ):
						return np.asarray(_A      ,		**self.np_array_kwargs     )

				return np.asarray(_A      ,		**{**default_dtype, **self.np_array_kwargs}     )
			def 							__snake_case (		self      ,		_A     )    ->    Dict:






				'''simple docstring'''







				if config.TORCH_AVAILABLE and "torch" in sys.modules:
					import torch

					if isinstance(_A      ,		torch.Tensor     ):
						return self._tensorize(data_struct.detach().cpu().numpy()[()]     )
				if hasattr(_A      ,		"""__array__"""     ) and not isinstance(_A      ,		(np.ndarray, np.character, np.number)     ):
					_UpperCAmelCase    :							int									=					data_struct.__array__()
				# support for nested types like struct of list of struct
				if isinstance(_A      ,		np.ndarray     ):
					if data_struct.dtype == object:
						return self._consolidate([self.recursive_tensorize(_A     ) for substruct in data_struct]     )
				if isinstance(_A      ,		(list, tuple)     ):
					return self._consolidate([self.recursive_tensorize(_A     ) for substruct in data_struct]     )
				return self._tensorize(_A     )
			def 							__snake_case (		self      ,		_A     )    ->    Optional[int]:






				'''simple docstring'''







				return map_nested(self._recursive_tensorize      ,		_A      ,		map_list=_A     )
			def 							__snake_case (		self      ,		_A     )    ->    Mapping:






				'''simple docstring'''







				_UpperCAmelCase    :							Union[str, Any]									=					self.numpy_arrow_extractor().extract_row(_A     )
				_UpperCAmelCase    :							str									=					self.python_features_decoder.decode_row(_A     )
				return self.recursive_tensorize(_A     )
			def 							__snake_case (		self      ,		_A     )    ->    np.ndarray:






				'''simple docstring'''







				_UpperCAmelCase    :							List[str]									=					self.numpy_arrow_extractor().extract_column(_A     )
				_UpperCAmelCase    :							Optional[int]									=					self.python_features_decoder.decode_column(_A      ,		pa_table.column_names[0]     )
				_UpperCAmelCase    :							Dict									=					self.recursive_tensorize(_A     )
				_UpperCAmelCase    :							str									=					self._consolidate(_A     )
				return column
			def 							__snake_case (		self      ,		_A     )    ->    Mapping:






				'''simple docstring'''







				_UpperCAmelCase    :							Tuple									=					self.numpy_arrow_extractor().extract_batch(_A     )
				_UpperCAmelCase    :							int									=					self.python_features_decoder.decode_batch(_A     )
				_UpperCAmelCase    :							Dict									=					self.recursive_tensorize(_A     )
				for column_name in batch:
					_UpperCAmelCase    :							Optional[int]									=					self._consolidate(batch[column_name]     )
				return batch








"""simple docstring"""






from __future__ import annotations
def       UpperCamelCase					(			_lowerCAmelCase     :						list,  _lowerCAmelCase     :						list )				->			list:
	_UpperCAmelCase    :							List[Any]									=					[None] * (len(_lowerCAmelCase ) + len(_lowerCAmelCase ))

	_UpperCAmelCase    :							Union[str, Any]									=					0  # pointer to current index for left Half
	_UpperCAmelCase    :							str									=					0  # pointer to current index for the right Half
	_UpperCAmelCase    :							Optional[int]									=					0  # pointer to current index for the sorted array Half

	while pointera < len(_lowerCAmelCase ) and pointera < len(_lowerCAmelCase ):
		if left_half[pointera] < right_half[pointera]:
			_UpperCAmelCase    :							Tuple									=					left_half[pointera]
			pointera += 1
			index += 1
		else:
			_UpperCAmelCase    :							int									=					right_half[pointera]
			pointera += 1
			index += 1
	while pointera < len(_lowerCAmelCase ):
		_UpperCAmelCase    :							Tuple									=					left_half[pointera]
		pointera += 1
		index += 1

	while pointera < len(_lowerCAmelCase ):
		_UpperCAmelCase    :							Union[str, Any]									=					right_half[pointera]
		pointera += 1
		index += 1

	return sorted_array
def       UpperCamelCase					(			_lowerCAmelCase     :						list )				->			list:
	if len(_lowerCAmelCase ) <= 1:
		return array
	# the actual formula to calculate the middle element = left + (right - left) // 2
	# this avoids integer overflow in case of large N
	_UpperCAmelCase    :							Any									=					0 + (len(_lowerCAmelCase ) - 0) // 2

	# Split the array into halves till the array length becomes equal to One
	# merge the arrays of single length returned by mergeSort function and
	# pass them into the merge arrays function which merges the array
	_UpperCAmelCase    :							Optional[Any]									=					array[:middle]
	_UpperCAmelCase    :							Optional[int]									=					array[middle:]

	return merge(merge_sort(_lowerCAmelCase ),  merge_sort(_lowerCAmelCase ) )


if __name__ == "__main__":
						import doctest

						doctest.testmod()





