






'''simple docstring'''






import io
import itertools
import json
from dataclasses import dataclass
from typing import Optional

import pyarrow as pa
import pyarrow.json as paj

import datasets
from datasets.table import table_cast
from datasets.utils.file_utils import readline


__A    	=   datasets.utils.logging.get_logger(__name__)




@dataclass
class a_    (    datasets.BuilderConfig							):
   _snake_case        =							None
   _snake_case        =							"utf-8"
   _snake_case        =							None
   _snake_case        =							None
   _snake_case        =							True  # deprecated
   _snake_case        =							None  # deprecated
   _snake_case        =							10 << 20  # 10MB
   _snake_case        =							None




class a_    (    datasets.ArrowBasedBuilder							):
   _snake_case        =							JsonConfig







   def     SCREAMING_SNAKE_CASE__					(self)			->      List[Any]:
      """simple docstring"""






      if self.config.block_size is not None:
         logger.warning('The JSON loader parameter `block_size` is deprecated. Please use `chunksize` instead')
         __snake_case				:      Tuple     							= self.config.block_size
      if self.config.use_threads is not True:
         logger.warning(
             'The JSON loader parameter `use_threads` is deprecated and doesn\'t have any effect anymore.')
      if self.config.newlines_in_values is not None:
         raise ValueError('The JSON loader parameter `newlines_in_values` is no longer supported')
      return datasets.DatasetInfo(features=self.config.features)







   def     SCREAMING_SNAKE_CASE__					(self					,   __a)			->      List[str]:
      """simple docstring"""






      if not self.config.data_files:
         raise ValueError(F"""At least one data file must be specified, but got data_files={self.config.data_files}""")
      __snake_case				:      Optional[int]     							= dl_manager.download_and_extract(self.config.data_files)
      if isinstance(__a					,   (str, list, tuple)):
         __snake_case				:      Tuple     							= data_files
         if isinstance(__a					,   __a):
            __snake_case				:      Tuple     							= [files]
         __snake_case				:      Optional[int]     							= [dl_manager.iter_files(__a) for file in files]
         return [datasets.SplitGenerator(name=datasets.Split.TRAIN					,   gen_kwargs={'files': files})]
      __snake_case				:      Dict     							= []
      for split_name, files in data_files.items():
         if isinstance(__a					,   __a):
            __snake_case				:      List[str]     							= [files]
         __snake_case				:      Any     							= [dl_manager.iter_files(__a) for file in files]
         splits.append(datasets.SplitGenerator(name=__a					,   gen_kwargs={'files': files}))
      return splits







   def     SCREAMING_SNAKE_CASE__					(self					,   __a)			->      pa.Table:
      """simple docstring"""






      if self.config.features is not None:
         # adding missing columns
         for column_name in set(self.config.features) - set(pa_table.column_names):
            __snake_case				:      Any     							= self.config.features.arrow_schema.field(__a).type
            __snake_case				:      Any     							= pa_table.append_column(__a					,   pa.array([None] * len(__a)					,   type=__a))
         # more expensive cast to support nested structures with keys in a different order
         # allows str <-> int/float or str to Audio for example
         __snake_case				:      Optional[Any]     							= table_cast(__a					,   self.config.features.arrow_schema)
      return pa_table







   def     SCREAMING_SNAKE_CASE__					(self					,   __a)			->      Tuple:
      """simple docstring"""






      for file_idx, file in enumerate(itertools.chain.from_iterable(__a)):
         # If the file is one json object and if we need to look at the list of items in one specific field
         if self.config.field is not None:
            with open(__a					,   encoding=self.config.encoding					,   errors=self.config.encoding_errors) as f:
               __snake_case				:      Union[str, Any]     							= json.load(__a)

            # We keep only the field we are interested in
            __snake_case				:      Tuple     							= dataset[self.config.field]

            # We accept two format: a list of dicts or a dict of lists
            if isinstance(__a					,   (list, tuple)):
               __snake_case				:      Optional[Any]     							= set().union(*[row.keys() for row in dataset])
               __snake_case				:      List[str]     							= {col: [row.get(__a) for row in dataset] for col in keys}
            else:
               __snake_case				:      Tuple     							= dataset
            __snake_case				:      Optional[int]     							= pa.Table.from_pydict(__a)
            yield file_idx, self._cast_table(__a)

         # If the file has one json object per line
         else:
            with open(__a					,   'rb') as f:
               __snake_case				:      Any     							= 0
               # Use block_size equal to the chunk size divided by 32 to leverage multithreading
               # Set a default minimum value of 16kB if the chunk size is really small
               __snake_case				:      List[Any]     							= max(self.config.chunksize // 3_2					,   1_6 << 1_0)
               __snake_case				:      Union[str, Any]     							= (
                   self.config.encoding_errors if self.config.encoding_errors is not None else 'strict'
               )
               while True:
                  __snake_case				:      str     							= f.read(self.config.chunksize)
                  if not batch:
                     break
                  # Finish current line
                  try:
                     batch += f.readline()
                  except (AttributeError, io.UnsupportedOperation):
                     batch += readline(__a)
                  # PyArrow only accepts utf-8 encoded bytes
                  if self.config.encoding != "utf-8":
                     __snake_case				:      int     							= batch.decode(self.config.encoding					,   errors=__a).encode('utf-8')
                  try:
                     while True:
                        try:
                           __snake_case				:      Tuple     							= paj.read_json(
                               io.BytesIO(__a)					,   read_options=paj.ReadOptions(block_size=__a))
                           break
                        except (pa.ArrowInvalid, pa.ArrowNotImplementedError) as e:
                           if (
                               isinstance(__a					,   pa.ArrowInvalid)
                               and "straddling" not in str(__a)
                               or block_size > len(__a)
                           ):
                              raise
                           else:
                              # Increase the block size in case it was too small.
                              # The block size will be reset for the next file.
                              logger.debug(
                                  F"""Batch of {len(__a)} bytes couldn't be parsed with block_size={block_size}. Retrying with block_size={block_size * 2}.""")
                              block_size *= 2
                  except pa.ArrowInvalid as e:
                     try:
                        with open(
                            __a					,   encoding=self.config.encoding					,   errors=self.config.encoding_errors) as f:
                           __snake_case				:      str     							= json.load(__a)
                     except json.JSONDecodeError:
                        logger.error(F"""Failed to read file '{file}' with error {type(__a)}: {e}""")
                        raise e
                     # If possible, parse the file as a list of json objects and exit the loop
                     if isinstance(__a					,   __a):  # list is the only sequence type supported in JSON
                        try:
                           __snake_case				:      List[Any]     							= set().union(*[row.keys() for row in dataset])
                           __snake_case				:      Union[str, Any]     							= {col: [row.get(__a) for row in dataset] for col in keys}
                           __snake_case				:      List[Any]     							= pa.Table.from_pydict(__a)
                        except (pa.ArrowInvalid, AttributeError) as e:
                           logger.error(F"""Failed to read file '{file}' with error {type(__a)}: {e}""")
                           raise ValueError(F"""Not able to read records in the JSON file at {file}.""") from None
                        yield file_idx, self._cast_table(__a)
                        break
                     else:
                        logger.error(F"""Failed to read file '{file}' with error {type(__a)}: {e}""")
                        raise ValueError(
                            F"""Not able to read records in the JSON file at {file}. """
                            F"""You should probably indicate the field of the JSON file containing your records. """
                            F"""This JSON file contain the following fields: {str(list(dataset.keys()))}. """
                            F"""Select the correct one and provide it as `field='XXX'` to the dataset loading method. """) from None
                        # Uncomment for debugging (will print the Arrow table size and elements)
                        # logger.warning(f"pa_table: {pa_table} num rows: {pa_table.num_rows}")
                        # logger.warning('\n'.join(str(pa_table.slice(i, 1).to_pydict()) for i in range(pa_table.num_rows)))
                  yield (file_idx, batch_idx), self._cast_table(__a)
                  batch_idx += 1







'''simple docstring'''






from __future__ import annotations

import math
import random
from collections.abc import Collection
from typing import overload




class a_    :







   def __init__(self					,   __a = None)			->      None:
      """simple docstring"""






      if components is None:
         __snake_case				:      List[str]     							= []
      __snake_case				:      Optional[int]     							= list(__a)







   def __len__(self)			->      int:
      """simple docstring"""






      return len(self.__components)







   def __str__(self)			->      str:
      """simple docstring"""






      return "(" + ",".join(map(__a					,   self.__components)) + ")"







   def __add__(self					,   __a)			->      Vector:
      """simple docstring"""






      __snake_case				:      Optional[Any]     							= len(self)
      if size == len(__a):
         __snake_case				:      Optional[int]     							= [self.__components[i] + other.component(__a) for i in range(__a)]
         return Vector(__a)
      else:
         raise Exception('must have the same size')







   def __sub__(self					,   __a)			->      Vector:
      """simple docstring"""






      __snake_case				:      Optional[Any]     							= len(self)
      if size == len(__a):
         __snake_case				:      Optional[int]     							= [self.__components[i] - other.component(__a) for i in range(__a)]
         return Vector(__a)
      else:  # error case
         raise Exception('must have the same size')







   @overload
   def __mul__(self					,   __a)			->      Vector:
      """simple docstring"""






      ...







   @overload
   def __mul__(self					,   __a)			->      float:
      """simple docstring"""






      ...







   def __mul__(self					,   __a)			->      float | Vector:
      """simple docstring"""






      if isinstance(__a					,   (float, int)):
         __snake_case				:      str     							= [c * other for c in self.__components]
         return Vector(__a)
      elif isinstance(__a					,   __a) and len(self) == len(__a):
         __snake_case				:      List[Any]     							= len(self)
         __snake_case				:      Dict     							= [self.__components[i] * other.component(__a) for i in range(__a)]
         return sum(__a)
      else:  # error case
         raise Exception('invalid operand!')







   def     SCREAMING_SNAKE_CASE__					(self)			->      Vector:
      """simple docstring"""






      return Vector(self.__components)







   def     SCREAMING_SNAKE_CASE__					(self					,   __a)			->      float:
      """simple docstring"""






      if isinstance(__a					,   __a) and -len(self.__components) <= i < len(self.__components):
         return self.__components[i]
      else:
         raise Exception('index out of range')







   def     SCREAMING_SNAKE_CASE__					(self					,   __a					,   __a)			->      None:
      """simple docstring"""






      assert -len(self.__components) <= pos < len(self.__components)
      __snake_case				:      int     							= value







   def     SCREAMING_SNAKE_CASE__					(self)			->      float:
      """simple docstring"""






      if len(self.__components) == 0:
         raise Exception('Vector is empty')
      __snake_case				:      Tuple     							= [c**2 for c in self.__components]
      return math.sqrt(sum(__a))







   def     SCREAMING_SNAKE_CASE__					(self					,   __a					,   __a = False)			->      float:
      """simple docstring"""






      __snake_case				:      Tuple     							= self * other
      __snake_case				:      Optional[int]     							= self.euclidean_length() * other.euclidean_length()
      if deg:
         return math.degrees(math.acos(num / den))
      else:
         return math.acos(num / den)




def        _SCREAMING_SNAKE_CASE  (				A  :       int  )    -> Vector:







   """simple docstring"""
   assert isinstance(A  ,		A  )
   return Vector([0] * dimension  )




def        _SCREAMING_SNAKE_CASE  (				A  :       int  ,		A  :       int  )    -> Vector:







   """simple docstring"""
   assert isinstance(A  ,		A  ) and (isinstance(A  ,		A  ))
   __snake_case				:      Any     							= [0] * dimension
   __snake_case				:      int     							= 1
   return Vector(A  )




def        _SCREAMING_SNAKE_CASE  (				A  :       float  ,		A  :       Vector  ,		A  :       Vector  )    -> Vector:







   """simple docstring"""
   assert (
       isinstance(A  ,		A  )
       and isinstance(A  ,		A  )
       and (isinstance(A  ,		(int, float)  ))
   )
   return x * scalar + y




def        _SCREAMING_SNAKE_CASE  (				A  :       int  ,		A  :       int  ,		A  :       int  )    -> Vector:







   """simple docstring"""
   random.seed(A  )
   __snake_case				:      List[Any]     							= [random.randint(A  ,		A  ) for _ in range(A  )]
   return Vector(A  )




class a_    :







   def __init__(self					,   __a					,   __a					,   __a)			->      None:
      """simple docstring"""






      __snake_case				:      Union[str, Any]     							= matrix
      __snake_case				:      int     							= w
      __snake_case				:      str     							= h







   def __str__(self)			->      str:
      """simple docstring"""






      __snake_case				:      Dict     							= ''
      for i in range(self.__height):
         ans += "|"
         for j in range(self.__width):
            if j < self.__width - 1:
               ans += str(self.__matrix[i][j]) + ","
            else:
               ans += str(self.__matrix[i][j]) + "|\n"
      return ans







   def __add__(self					,   __a)			->      Matrix:
      """simple docstring"""






      if self.__width == other.width() and self.__height == other.height():
         __snake_case				:      Tuple     							= []
         for i in range(self.__height):
            __snake_case				:      List[Any]     							= [
                self.__matrix[i][j] + other.component(__a					,   __a)
                for j in range(self.__width)
            ]
            matrix.append(__a)
         return Matrix(__a					,   self.__width					,   self.__height)
      else:
         raise Exception('matrix must have the same dimension!')







   def __sub__(self					,   __a)			->      Matrix:
      """simple docstring"""






      if self.__width == other.width() and self.__height == other.height():
         __snake_case				:      str     							= []
         for i in range(self.__height):
            __snake_case				:      List[str]     							= [
                self.__matrix[i][j] - other.component(__a					,   __a)
                for j in range(self.__width)
            ]
            matrix.append(__a)
         return Matrix(__a					,   self.__width					,   self.__height)
      else:
         raise Exception('matrices must have the same dimension!')







   @overload
   def __mul__(self					,   __a)			->      Matrix:
      """simple docstring"""






      ...







   @overload
   def __mul__(self					,   __a)			->      Vector:
      """simple docstring"""






      ...







   def __mul__(self					,   __a)			->      Vector | Matrix:
      """simple docstring"""






      if isinstance(__a					,   __a):  # matrix-vector
         if len(__a) == self.__width:
            __snake_case				:      Tuple     							= zero_vector(self.__height)
            for i in range(self.__height):
               __snake_case				:      Union[str, Any]     							= [
                   self.__matrix[i][j] * other.component(__a)
                   for j in range(self.__width)
               ]
               ans.change_component(__a					,   sum(__a))
            return ans
         else:
            raise Exception(
                'vector must have the same size as the '
                'number of columns of the matrix!')
      elif isinstance(__a					,   (int, float)):  # matrix-scalar
         __snake_case				:      str     							= [
             [self.__matrix[i][j] * other for j in range(self.__width)]
             for i in range(self.__height)
         ]
         return Matrix(__a					,   self.__width					,   self.__height)
      return None







   def     SCREAMING_SNAKE_CASE__					(self)			->      int:
      """simple docstring"""






      return self.__height







   def     SCREAMING_SNAKE_CASE__					(self)			->      int:
      """simple docstring"""






      return self.__width







   def     SCREAMING_SNAKE_CASE__					(self					,   __a					,   __a)			->      float:
      """simple docstring"""






      if 0 <= x < self.__height and 0 <= y < self.__width:
         return self.__matrix[x][y]
      else:
         raise Exception('change_component: indices out of bounds')







   def     SCREAMING_SNAKE_CASE__					(self					,   __a					,   __a					,   __a)			->      None:
      """simple docstring"""






      if 0 <= x < self.__height and 0 <= y < self.__width:
         __snake_case				:      List[Any]     							= value
      else:
         raise Exception('change_component: indices out of bounds')







   def     SCREAMING_SNAKE_CASE__					(self					,   __a					,   __a)			->      float:
      """simple docstring"""






      if self.__height != self.__width:
         raise Exception('Matrix is not square')
      __snake_case				:      List[Any]     							= self.__matrix[:x] + self.__matrix[x + 1 :]
      for i in range(len(__a)):
         __snake_case				:      Tuple     							= minor[i][:y] + minor[i][y + 1 :]
      return Matrix(__a					,   self.__width - 1					,   self.__height - 1).determinant()







   def     SCREAMING_SNAKE_CASE__					(self					,   __a					,   __a)			->      float:
      """simple docstring"""






      if self.__height != self.__width:
         raise Exception('Matrix is not square')
      if 0 <= x < self.__height and 0 <= y < self.__width:
         return (-1) ** (x + y) * self.minor(__a					,   __a)
      else:
         raise Exception('Indices out of bounds')







   def     SCREAMING_SNAKE_CASE__					(self)			->      float:
      """simple docstring"""






      if self.__height != self.__width:
         raise Exception('Matrix is not square')
      if self.__height < 1:
         raise Exception('Matrix has no element')
      elif self.__height == 1:
         return self.__matrix[0][0]
      elif self.__height == 2:
         return (
             self.__matrix[0][0] * self.__matrix[1][1]
             - self.__matrix[0][1] * self.__matrix[1][0]
         )
      else:
         __snake_case				:      Any     							= [
             self.__matrix[0][y] * self.cofactor(0					,   __a) for y in range(self.__width)
         ]
         return sum(__a)




def        _SCREAMING_SNAKE_CASE  (				A  :       int  )    -> Matrix:







   """simple docstring"""
   __snake_case				:      list[list[float]]     							= [[0] * n for _ in range(A  )]
   return Matrix(A  ,		A  ,		A  )





def        _SCREAMING_SNAKE_CASE  (				A  :       int  ,		A  :       int  ,		A  :       int  ,		A  :       int  )    -> Matrix:







   """simple docstring"""
   random.seed(A  )
   __snake_case				:      list[list[float]]     							= [
       [random.randint(A  ,		A  ) for _ in range(A  )] for _ in range(A  )
   ]
   return Matrix(A  ,		A  ,		A  )