
'''simple docstring'''

import hashlib
import importlib.util
import json
import os
import pathlib
from types import ModuleType

import pytest
import requests

UpperCamelCase_     			=       pathlib.Path.cwd().joinpath("""project_euler""")
UpperCamelCase_     			=       pathlib.Path.cwd().joinpath(
    """scripts""", """project_euler_answers.json"""
)

with open(PROJECT_EULER_ANSWERS_PATH) as file_handle:
     UpperCamelCase_     			=       json.load(file_handle)


def 	_UpperCAmelCase				(  _lowerCamelCase						:       pathlib.Path		)    ->						ModuleType:
  _lowerCAmelCase       :  List[Any]   				=					importlib.util.spec_from_file_location(file_path.name  ,      str(_lowerCamelCase		)		)
  _lowerCAmelCase       :  Union[str, Any]   				=					importlib.util.module_from_spec(_lowerCamelCase		)  # type: ignore
  spec.loader.exec_module(_lowerCamelCase		)  # type: ignore
  return module


def 	_UpperCAmelCase				(  )    ->						list[pathlib.Path]:
  _lowerCAmelCase       :  str   				=					[]
  for problem_dir_path in PROJECT_EULER_DIR_PATH.iterdir():
    if problem_dir_path.is_file() or problem_dir_path.name.startswith("""_"""		):
      continue
    for file_path in problem_dir_path.iterdir():
      if file_path.suffix != ".py" or file_path.name.startswith(("""_""", """test""")		):
        continue
      solution_file_paths.append(_lowerCamelCase		)
  return solution_file_paths


def 	_UpperCAmelCase				(  )    ->						str:
  with open(os.environ["""GITHUB_EVENT_PATH"""]		) as file:
    _lowerCAmelCase       :  List[str]   				=					json.load(_lowerCamelCase		)
  return event["pull_request"]["url"] + "/files"


def 	_UpperCAmelCase				(  )    ->						list[pathlib.Path]:
  _lowerCAmelCase       :  str   				=					[]
  _lowerCAmelCase       :  List[Any]   				=					{
      """Accept""": """application/vnd.github.v3+json""",
      """Authorization""": """token """ + os.environ["""GITHUB_TOKEN"""],
  }
  _lowerCAmelCase       :  int   				=					requests.get(get_files_url()  ,      headers=_lowerCamelCase		).json()
  for file in files:
    _lowerCAmelCase       :  Any   				=					pathlib.Path.cwd().joinpath(file["""filename"""]		)
    if (
        filepath.suffix != ".py"
        or filepath.name.startswith(("""_""", """test""")		)
        or not filepath.name.startswith("""sol"""		)
    ):
      continue
    solution_file_paths.append(_lowerCamelCase		)
  return solution_file_paths


def 	_UpperCAmelCase				(  )    ->						list[pathlib.Path]:
  if os.environ.get("""CI"""		) and os.environ.get("""GITHUB_EVENT_NAME"""		) == "pull_request":
    # Return only if there are any, otherwise default to all solutions
    if filepaths := added_solution_file_path():
      return filepaths
  return all_solution_file_paths()



@pytest.mark.parametrize(
    """solution_path"""  ,      collect_solution_file_paths()  ,      ids=lambda _lowerCamelCase		: f'{path.parent.name}/{path.name}'  ,      )
def 	_UpperCAmelCase				(  _lowerCamelCase						:       pathlib.Path		)    ->						None:
  _lowerCAmelCase       :  str   				=					solution_path.parent.name[8:].zfill(3		)
  _lowerCAmelCase       :  str   				=					PROBLEM_ANSWERS[problem_number]
  _lowerCAmelCase       :  List[Any]   				=					convert_path_to_module(_lowerCamelCase		)
  _lowerCAmelCase       :  str   				=					str(solution_module.solution()		)  # type: ignore
  _lowerCAmelCase       :  Optional[Any]   				=					hashlib.shaaaa(answer.encode()		).hexdigest()
  assert (
      answer == expected
  ), f'Expected solution to {problem_number} to have hash {expected}, got {answer}'




'''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   a_  (TensorFormatter[Mapping, np.ndarray, Mapping]    ):




       def __init__(     self   ,   snake_case_=None   ,   **snake_case_  ):
         super().__init__(features=snake_case_  )
         _lowerCAmelCase       :  Any   				=					np_array_kwargs




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




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

         _lowerCAmelCase       :  List[Any]   				=					{}

         if isinstance(snake_case_   ,   np.ndarray  ) and np.issubdtype(value.dtype   ,   np.integer  ):
           _lowerCAmelCase       :  Union[str, Any]   				=					{"""dtype""": np.intaa}
         elif isinstance(snake_case_   ,   np.ndarray  ) and np.issubdtype(value.dtype   ,   np.floating  ):
           _lowerCAmelCase       :  Tuple   				=					{"""dtype""": np.floataa}
         elif config.PIL_AVAILABLE and "PIL" in sys.modules:
           import PIL.Image

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

         return np.asarray(snake_case_   ,   **{**default_dtype, **self.np_array_kwargs}  )




       def 							__UpperCamelCase       (     self   ,   snake_case_  ):
         # support for torch, tf, jax etc.
         if config.TORCH_AVAILABLE and "torch" in sys.modules:
           import torch

           if isinstance(snake_case_   ,   torch.Tensor  ):
             return self._tensorize(data_struct.detach().cpu().numpy()[()]  )
         if hasattr(snake_case_   ,   """__array__"""  ) and not isinstance(snake_case_   ,   (np.ndarray, np.character, np.number)  ):
           _lowerCAmelCase       :  List[Any]   				=					data_struct.__array__()
         # support for nested types like struct of list of struct
         if isinstance(snake_case_   ,   np.ndarray  ):
           if data_struct.dtype == object:
             return self._consolidate([self.recursive_tensorize(snake_case_  ) for substruct in data_struct]  )
         if isinstance(snake_case_   ,   (list, tuple)  ):
           return self._consolidate([self.recursive_tensorize(snake_case_  ) for substruct in data_struct]  )
         return self._tensorize(snake_case_  )




       def 							__UpperCamelCase       (     self   ,   snake_case_  ):
         return map_nested(self._recursive_tensorize   ,   snake_case_   ,   map_list=snake_case_  )




       def 							__UpperCamelCase       (     self   ,   snake_case_  ):
         _lowerCAmelCase       :  Optional[Any]   				=					self.numpy_arrow_extractor().extract_row(snake_case_  )
         _lowerCAmelCase       :  Any   				=					self.python_features_decoder.decode_row(snake_case_  )
         return self.recursive_tensorize(snake_case_  )




       def 							__UpperCamelCase       (     self   ,   snake_case_  ):
         _lowerCAmelCase       :  List[Any]   				=					self.numpy_arrow_extractor().extract_column(snake_case_  )
         _lowerCAmelCase       :  Tuple   				=					self.python_features_decoder.decode_column(snake_case_   ,   pa_table.column_names[0]  )
         _lowerCAmelCase       :  Optional[int]   				=					self.recursive_tensorize(snake_case_  )
         _lowerCAmelCase       :  Optional[Any]   				=					self._consolidate(snake_case_  )
         return column







       def 							__UpperCamelCase       (     self   ,   snake_case_  ):
         _lowerCAmelCase       :  List[Any]   				=					self.numpy_arrow_extractor().extract_batch(snake_case_  )
         _lowerCAmelCase       :  str   				=					self.python_features_decoder.decode_batch(snake_case_  )
         _lowerCAmelCase       :  Dict   				=					self.recursive_tensorize(snake_case_  )
         for column_name in batch:
           _lowerCAmelCase       :  int   				=					self._consolidate(batch[column_name]  )
         return batch


