




import sys
from dataclasses import dataclass
from typing import TYPE_CHECKING, Dict, List, Optional, Tuple, Union

import pandas as pd
import pyarrow as pa

import datasets
import datasets.config
from datasets.features.features import require_storage_cast
from datasets.table import table_cast


if TYPE_CHECKING:
						import sqlitea

						import sqlalchemy


__a  :		List[Any]		     =   datasets.utils.logging.get_logger(__name__)







@dataclass
class  UpperCAmelCase(					datasets.BuilderConfig					):



	"""simple docstring"""






	a     : Union[str, "sqlalchemy.sql.Selectable"]	  =					None
	a     : Union[str, "sqlalchemy.engine.Connection", "sqlalchemy.engine.Engine", "sqlite3.Connection"]	  =					None
	a     : Optional[Union[str, List[str]]]	  =					None
	a     : bool	  =					True
	a     : Optional[Union[List, Tuple, Dict]]	  =					None
	a     : Optional[Union[List, Dict]]	  =					None
	a     : Optional[List[str]]	  =					None
	a     : Optional[int]	  =					1_0_0_0_0
	a     : Optional[datasets.Features]	  =					None

	def    __a     (					self    ) ->      Optional[Any]:





								"""simple docstring"""


								if self.sql is None:
															raise ValueError("sql must be specified"    )
								if self.con is None:
															raise ValueError("con must be specified"    )

	def    __a     (					self	,				lowerCamelCase	,				lowerCamelCase = None	,				) ->      str:





								"""simple docstring"""


								lowercase__  :	Tuple        =							config_kwargs.copy()
								# We need to stringify the Selectable object to make its hash deterministic

								# The process of stringifying is explained here: http://docs.sqlalchemy.org/en/latest/faq/sqlexpressions.html
								lowercase__  :	int        =							config_kwargs["sql"]
								if not isinstance(lowerCamelCase	,				lowerCamelCase    ):
															if datasets.config.SQLALCHEMY_AVAILABLE and "sqlalchemy" in sys.modules:
																						import sqlalchemy

																						if isinstance(lowerCamelCase	,				sqlalchemy.sql.Selectable    ):
																													lowercase__  :	Any        =							sqlalchemy.create_engine(config_kwargs["con"].split("://"    )[0] + "://"    )
																													lowercase__  :	int        =							str(sql.compile(dialect=engine.dialect    )    )
																													lowercase__  :	int        =							sql_str
																						else:
																													raise TypeError(
																													    f"""Supported types for 'sql' are string and sqlalchemy.sql.Selectable but got {type(lowerCamelCase    )}: {sql}"""    )
															else:
																						raise TypeError(
																						    f"""Supported types for 'sql' are string and sqlalchemy.sql.Selectable but got {type(lowerCamelCase    )}: {sql}"""    )
								lowercase__  :	Optional[int]        =							config_kwargs["con"]
								if not isinstance(lowerCamelCase	,				lowerCamelCase    ):
															lowercase__  :	Dict        =							id(lowerCamelCase    )
															logger.info(
															    f"""SQL connection 'con' of type {type(lowerCamelCase    )} couldn't be hashed properly. To enable hashing, specify 'con' as URI string instead."""    )

								return super().create_config_id(lowerCamelCase	,				custom_features=lowerCamelCase    )







	@property
	def    __a     (					self    ) ->      List[str]:





								"""simple docstring"""


								lowercase__  :	Tuple        =							{
								    "index_col": self.index_col,
								    "columns": self.columns,
								    "params": self.params,
								    "coerce_float": self.coerce_float,
								    "parse_dates": self.parse_dates,
								}
								return pd_read_sql_kwargs







class  UpperCAmelCase(					datasets.ArrowBasedBuilder					):



	"""simple docstring"""






	a     : Dict	  =					SqlConfig

	def    __a     (					self    ) ->      Optional[int]:





								"""simple docstring"""


								return datasets.DatasetInfo(features=self.config.features    )

	def    __a     (					self	,				lowerCamelCase    ) ->      List[Any]:





								"""simple docstring"""


								return [datasets.SplitGenerator(name=datasets.Split.TRAIN	,				gen_kwargs={}    )]

	def    __a     (					self	,				lowerCamelCase    ) ->      pa.Table:





								"""simple docstring"""


								if self.config.features is not None:
															lowercase__  :	Optional[int]        =							self.config.features.arrow_schema
															if all(not require_storage_cast(lowerCamelCase    ) for feature in self.config.features.values()    ):
																						# cheaper cast
																						lowercase__  :	Union[str, Any]        =							pa.Table.from_arrays([pa_table[field.name] for field in schema]	,				schema=lowerCamelCase    )
															else:
																						# more expensive cast; allows str <-> int/float or str to Audio for example
																						lowercase__  :	str        =							table_cast(lowerCamelCase	,				lowerCamelCase    )
								return pa_table







	def    __a     (					self    ) ->      Optional[int]:





								"""simple docstring"""


								lowercase__  :	Optional[int]        =							self.config.chunksize
								lowercase__  :	int        =							pd.read_sql(
								    self.config.sql	,				self.config.con	,				chunksize=lowerCamelCase	,				**self.config.pd_read_sql_kwargs    )
								lowercase__  :	List[Any]        =							[sql_reader] if chunksize is None else sql_reader
								for chunk_idx, df in enumerate(lowerCamelCase    ):
															lowercase__  :	Any        =							pa.Table.from_pandas(lowerCamelCase    )
															yield chunk_idx, self._cast_table(lowerCamelCase    )





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

import pytest
import requests

__a  :		str		     =   pathlib.Path.cwd().joinpath('''project_euler''')
__a  :		Tuple		     =   pathlib.Path.cwd().joinpath(
    '''scripts''', '''project_euler_answers.json'''
)

with open(PROJECT_EULER_ANSWERS_PATH) as file_handle:
						__a  :		dict[str, str]		     =   json.load(file_handle)
def  snake_case_					(		SCREAMING_SNAKE_CASE_    )      ->			ModuleType:
							lowercase__  :	List[str]        =							importlib.util.spec_from_file_location(file_path.name    ,str(SCREAMING_SNAKE_CASE_    )    )
							lowercase__  :	int        =							importlib.util.module_from_spec(SCREAMING_SNAKE_CASE_    )  # type: ignore
							spec.loader.exec_module(SCREAMING_SNAKE_CASE_    )  # type: ignore
							return module
def  snake_case_					(		)      ->			list[pathlib.Path]:
							lowercase__  :	List[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(SCREAMING_SNAKE_CASE_    )
							return solution_file_paths
def  snake_case_					(		)      ->			str:
							with open(os.environ["GITHUB_EVENT_PATH"]    ) as file:
														lowercase__  :	str        =							json.load(SCREAMING_SNAKE_CASE_    )
							return event["pull_request"]["url"] + "/files"
def  snake_case_					(		)      ->			list[pathlib.Path]:
							lowercase__  :	Optional[Any]        =							[]
							lowercase__  :	Dict        =							{
							    "Accept": "application/vnd.github.v3+json",
							    "Authorization": "token " + os.environ["GITHUB_TOKEN"],
							}
							lowercase__  :	Union[str, Any]        =							requests.get(get_files_url()    ,headers=SCREAMING_SNAKE_CASE_    ).json()
							for file in files:
														lowercase__  :	Optional[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(SCREAMING_SNAKE_CASE_    )
							return solution_file_paths
def  snake_case_					(		)      ->			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 SCREAMING_SNAKE_CASE_    : F"""{path.parent.name}/{path.name}"""    ,)
def  snake_case_					(		SCREAMING_SNAKE_CASE_    )      ->			None:
							lowercase__  :	str        =							solution_path.parent.name[8:].zfill(3    )
							lowercase__  :	str        =							PROBLEM_ANSWERS[problem_number]
							lowercase__  :	Optional[Any]        =							convert_path_to_module(SCREAMING_SNAKE_CASE_    )
							lowercase__  :	str        =							str(solution_module.solution()    )  # type: ignore
							lowercase__  :	List[str]        =							hashlib.shaaaa(answer.encode()    ).hexdigest()
							assert (
							    answer == expected
							), F"""Expected solution to {problem_number} to have hash {expected}, got {answer}"""