



import itertools
from dataclasses import dataclass
from typing import Any, Callable, Dict, List, Optional, 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
from datasets.utils.py_utils import Literal


_lowerCamelCase    :		Optional[Any]		      =    datasets.utils.logging.get_logger(__name__)

_lowerCamelCase    :		List[str]		      =    ["""names""", """prefix"""]
_lowerCamelCase    :		List[Any]		      =    ["""warn_bad_lines""", """error_bad_lines""", """mangle_dupe_cols"""]
_lowerCamelCase    :		str		      =    ["""encoding_errors""", """on_bad_lines"""]
_lowerCamelCase    :		int		      =    ["""date_format"""]


@dataclass
class 						lowercase    (							datasets.BuilderConfig):
						'''simple docstring'''


						UpperCAmelCase			:		str		=		","
						UpperCAmelCase			:		Optional[str]		=		None
						UpperCAmelCase			:		Optional[Union[int, List[int], str]]		=		"infer"
						UpperCAmelCase			:		Optional[List[str]]		=		None
						UpperCAmelCase			:		Optional[List[str]]		=		None
						UpperCAmelCase			:		Optional[Union[int, str, List[int], List[str]]]		=		None
						UpperCAmelCase			:		Optional[Union[List[int], List[str]]]		=		None
						UpperCAmelCase			:		Optional[str]		=		None
						UpperCAmelCase			:		bool		=		True
						UpperCAmelCase			:		Optional[Literal["c", "python", "pyarrow"]]		=		None
						UpperCAmelCase			:		Dict[Union[int, str], Callable[[Any], Any]]		=		None
						UpperCAmelCase			:		Optional[list]		=		None
						UpperCAmelCase			:		Optional[list]		=		None
						UpperCAmelCase			:		bool		=		False
						UpperCAmelCase			:		Optional[Union[int, List[int]]]		=		None
						UpperCAmelCase			:		Optional[int]		=		None
						UpperCAmelCase			:		Optional[Union[str, List[str]]]		=		None
						UpperCAmelCase			:		bool		=		True
						UpperCAmelCase			:		bool		=		True
						UpperCAmelCase			:		bool		=		False
						UpperCAmelCase			:		bool		=		True
						UpperCAmelCase			:		Optional[str]		=		None
						UpperCAmelCase			:		str		=		"."
						UpperCAmelCase			:		Optional[str]		=		None
						UpperCAmelCase			:		str		=		'"'
						UpperCAmelCase			:		int		=		0
						UpperCAmelCase			:		Optional[str]		=		None
						UpperCAmelCase			:		Optional[str]		=		None
						UpperCAmelCase			:		Optional[str]		=		None
						UpperCAmelCase			:		Optional[str]		=		None
						UpperCAmelCase			:		bool		=		True
						UpperCAmelCase			:		bool		=		True
						UpperCAmelCase			:		int		=		0
						UpperCAmelCase			:		bool		=		True
						UpperCAmelCase			:		bool		=		False
						UpperCAmelCase			:		Optional[str]		=		None
						UpperCAmelCase			:		int		=		1_0000
						UpperCAmelCase			:		Optional[datasets.Features]		=		None
						UpperCAmelCase			:		Optional[str]		=		"strict"
						UpperCAmelCase			:		Literal["error", "warn", "skip"]		=		"error"
						UpperCAmelCase			:		Optional[str]		=		None







						def       lowerCamelCase_				(  self    :				Tuple	):



											'''simple docstring'''


											if self.delimiter is not None:
																SCREAMING_SNAKE_CASE							:     List[str]						=				self.delimiter
											if self.column_names is not None:
																SCREAMING_SNAKE_CASE							:     str						=				self.column_names







						@property
						def       lowerCamelCase_				(  self    :				List[str]	):



											'''simple docstring'''


											SCREAMING_SNAKE_CASE							:     List[Any]						=				{
											    'sep': self.sep,
											    'header': self.header,
											    'names': self.names,
											    'index_col': self.index_col,
											    'usecols': self.usecols,
											    'prefix': self.prefix,
											    'mangle_dupe_cols': self.mangle_dupe_cols,
											    'engine': self.engine,
											    'converters': self.converters,
											    'true_values': self.true_values,
											    'false_values': self.false_values,
											    'skipinitialspace': self.skipinitialspace,
											    'skiprows': self.skiprows,
											    'nrows': self.nrows,
											    'na_values': self.na_values,
											    'keep_default_na': self.keep_default_na,
											    'na_filter': self.na_filter,
											    'verbose': self.verbose,
											    'skip_blank_lines': self.skip_blank_lines,
											    'thousands': self.thousands,
											    'decimal': self.decimal,
											    'lineterminator': self.lineterminator,
											    'quotechar': self.quotechar,
											    'quoting': self.quoting,
											    'escapechar': self.escapechar,
											    'comment': self.comment,
											    'encoding': self.encoding,
											    'dialect': self.dialect,
											    'error_bad_lines': self.error_bad_lines,
											    'warn_bad_lines': self.warn_bad_lines,
											    'skipfooter': self.skipfooter,
											    'doublequote': self.doublequote,
											    'memory_map': self.memory_map,
											    'float_precision': self.float_precision,
											    'chunksize': self.chunksize,
											    'encoding_errors': self.encoding_errors,
											    'on_bad_lines': self.on_bad_lines,
											    'date_format': self.date_format,
											}

											# some kwargs must not be passed if they don't have a default value
											# some others are deprecated and we can also not pass them if they are the default value
											for pd_read_csv_parameter in _PANDAS_READ_CSV_NO_DEFAULT_PARAMETERS + _PANDAS_READ_CSV_DEPRECATED_PARAMETERS:
																if pd_read_csv_kwargs[pd_read_csv_parameter] == getattr(CsvConfig()       ,	snake_case	):
																					del pd_read_csv_kwargs[pd_read_csv_parameter]

        # Remove 2.0 new arguments
											if not (datasets.config.PANDAS_VERSION.major >= 2):
																for pd_read_csv_parameter in _PANDAS_READ_CSV_NEW_2_0_0_PARAMETERS:
																					del pd_read_csv_kwargs[pd_read_csv_parameter]

        # Remove 1.3 new arguments
											if not (datasets.config.PANDAS_VERSION.major >= 1 and datasets.config.PANDAS_VERSION.minor >= 3):
																for pd_read_csv_parameter in _PANDAS_READ_CSV_NEW_1_3_0_PARAMETERS:
																					del pd_read_csv_kwargs[pd_read_csv_parameter]

											return pd_read_csv_kwargs


class 						lowercase    (							datasets.ArrowBasedBuilder):
						'''simple docstring'''


						UpperCAmelCase			:		Optional[int]		=		CsvConfig







						def       lowerCamelCase_				(  self    :				Dict	):



											'''simple docstring'''


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







						def       lowerCamelCase_				(  self    :				Any       ,	snake_case    :				Union[str, Any]	):



											'''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}'''	)
											SCREAMING_SNAKE_CASE							:     str						=				dl_manager.download_and_extract(self.config.data_files	)
											if isinstance(snake_case       ,	(str, list, tuple)	):
																SCREAMING_SNAKE_CASE							:     Optional[Any]						=				data_files
																if isinstance(snake_case       ,	snake_case	):
																					SCREAMING_SNAKE_CASE							:     Optional[Any]						=				[files]
																SCREAMING_SNAKE_CASE							:     List[Any]						=				[dl_manager.iter_files(snake_case	) for file in files]
																return [datasets.SplitGenerator(name=datasets.Split.TRAIN       ,	gen_kwargs={'files': files}	)]
											SCREAMING_SNAKE_CASE							:     Any						=				[]
											for split_name, files in data_files.items():
																if isinstance(snake_case       ,	snake_case	):
																					SCREAMING_SNAKE_CASE							:     List[Any]						=				[files]
																SCREAMING_SNAKE_CASE							:     Any						=				[dl_manager.iter_files(snake_case	) for file in files]
																splits.append(datasets.SplitGenerator(name=snake_case       ,	gen_kwargs={'files': files}	)	)
											return splits







						def       lowerCamelCase_				(  self    :				List[Any]       ,	snake_case    :				pa.Table	):



											'''simple docstring'''


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







						def       lowerCamelCase_				(  self    :				Optional[Any]       ,	snake_case    :				List[str]	):



											'''simple docstring'''


											SCREAMING_SNAKE_CASE							:     Any						=				self.config.features.arrow_schema if self.config.features else None
											# dtype allows reading an int column as str
											SCREAMING_SNAKE_CASE							:     str						=				(
											    {
											        name: dtype.to_pandas_dtype() if not require_storage_cast(snake_case	) else object
											        for name, dtype, feature in zip(schema.names       ,	schema.types       ,	self.config.features.values()	)
											    }
											    if schema is not None
											    else None
											)
											for file_idx, file in enumerate(itertools.chain.from_iterable(snake_case	)	):
																SCREAMING_SNAKE_CASE							:     str						=				pd.read_csv(snake_case       ,	iterator=snake_case       ,	dtype=snake_case       ,	**self.config.pd_read_csv_kwargs	)
																try:
																					for batch_idx, df in enumerate(snake_case	):
																										SCREAMING_SNAKE_CASE							:     Any						=				pa.Table.from_pandas(snake_case	)
																										# 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(snake_case	)
																except ValueError as e:
																					logger.error(f'''Failed to read file \'{file}\' with error {type(snake_case	)}: {e}'''	)
																					raise




_lowerCamelCase    :		Optional[Any]		      =    256
# Modulus to hash a string
_lowerCamelCase    :		Optional[Any]		      =    1_000_003

def        __a			(   __lowerCAmelCase      ,	__lowerCAmelCase   )     ->     bool:
					SCREAMING_SNAKE_CASE							:     Tuple						=				len(__lowerCAmelCase   )
					SCREAMING_SNAKE_CASE							:     Tuple						=				len(__lowerCAmelCase   )
					if p_len > t_len:
										return False

					SCREAMING_SNAKE_CASE							:     Dict						=				0
					SCREAMING_SNAKE_CASE							:     Tuple						=				0
					SCREAMING_SNAKE_CASE							:     Optional[Any]						=				1

					# Calculating the hash of pattern and substring of text
					for i in range(__lowerCAmelCase   ):
										SCREAMING_SNAKE_CASE							:     Tuple						=				(ord(pattern[i]   ) + p_hash * alphabet_size) % modulus
										SCREAMING_SNAKE_CASE							:     Union[str, Any]						=				(ord(text[i]   ) + text_hash * alphabet_size) % modulus
										if i == p_len - 1:
															continue
										SCREAMING_SNAKE_CASE							:     Optional[Any]						=				(modulus_power * alphabet_size) % modulus

					for i in range(0      ,	t_len - p_len + 1   ):
										if text_hash == p_hash and text[i : i + p_len] == pattern:
															return True
										if i == t_len - p_len:
															continue
										# Calculate the https://en.wikipedia.org/wiki/Rolling_hash
										SCREAMING_SNAKE_CASE							:     int						=				(
										    (text_hash - ord(text[i]   ) * modulus_power) * alphabet_size
										    + ord(text[i + p_len]   )
										) % modulus
					return False

def        __a			(   )     ->     None:
					SCREAMING_SNAKE_CASE							:     Any						=				'abc1abc12'
					SCREAMING_SNAKE_CASE							:     str						=				'alskfjaldsabc1abc1abc12k23adsfabcabc'
					SCREAMING_SNAKE_CASE							:     List[str]						=				'alskfjaldsk23adsfabcabc'
					assert rabin_karp(__lowerCAmelCase      ,	__lowerCAmelCase   ) and not rabin_karp(__lowerCAmelCase      ,	__lowerCAmelCase   )

					# Test 2)
					SCREAMING_SNAKE_CASE							:     List[str]						=				'ABABX'
					SCREAMING_SNAKE_CASE							:     int						=				'ABABZABABYABABX'
					assert rabin_karp(__lowerCAmelCase      ,	__lowerCAmelCase   )

					# Test 3)
					SCREAMING_SNAKE_CASE							:     int						=				'AAAB'
					SCREAMING_SNAKE_CASE							:     Tuple						=				'ABAAAAAB'
					assert rabin_karp(__lowerCAmelCase      ,	__lowerCAmelCase   )

					# Test 4)
					SCREAMING_SNAKE_CASE							:     Tuple						=				'abcdabcy'
					SCREAMING_SNAKE_CASE							:     Optional[Any]						=				'abcxabcdabxabcdabcdabcy'
					assert rabin_karp(__lowerCAmelCase      ,	__lowerCAmelCase   )

					# Test 5)
					SCREAMING_SNAKE_CASE							:     List[Any]						=				'Lü'
					SCREAMING_SNAKE_CASE							:     Optional[Any]						=				'Lüsai'
					assert rabin_karp(__lowerCAmelCase      ,	__lowerCAmelCase   )
					SCREAMING_SNAKE_CASE							:     Union[str, Any]						=				'Lue'
					assert not rabin_karp(__lowerCAmelCase      ,	__lowerCAmelCase   )
					print('Success.'   )


if __name__ == "__main__":
			test_rabin_karp()