





"""simple docstring"""



import copy
import os
import tempfile
from unittest import TestCase
from unittest.mock import patch

import numpy as np
import pyarrow as pa
import pyarrow.parquet as pq
import pytest

from datasets.arrow_writer import ArrowWriter, OptimizedTypedSequence, ParquetWriter, TypedSequence
from datasets.features import ArrayaD, ClassLabel, Features, Image, Value
from datasets.features.features import ArrayaDExtensionType, cast_to_python_objects
from datasets.keyhash import DuplicatedKeysError, InvalidKeyError

from .utils import require_pil






class 		__snake_case (		SCREAMING_SNAKE_CASE__					):





 """simple docstring"""


 def  UpperCamelCase__(   self  ):



     '''simple docstring'''




     __A   :						Any									=					pa.array(TypedSequence([1, 2, 3]  )  )
     self.assertEqual(arr.type ,						pa.intaa()  )

 def  UpperCamelCase__(   self  ):



     '''simple docstring'''




     with self.assertRaises(__lowerCamelCase  ):
         __A   :						int									=					pa.array(TypedSequence([1, 2, 3]  ) ,						type=pa.intaa()  )

 def  UpperCamelCase__(   self  ):



     '''simple docstring'''




     with self.assertRaises(__lowerCamelCase  ):
         __A   :						List[str]									=					pa.array(TypedSequence([1, 2, 3] ,						try_type=Value('''bool'''  ) ,						type=Value('''int64'''  )  )  )

 def  UpperCamelCase__(   self  ):



     '''simple docstring'''




     __A   :						Any									=					pa.array(TypedSequence([1, 2, 3] ,						type=Value('''int32'''  )  )  )
     self.assertEqual(arr.type ,						pa.intaa()  )

 def  UpperCamelCase__(   self  ):



     '''simple docstring'''




     with self.assertRaises((TypeError, pa.lib.ArrowInvalid)  ):
         __A   :						Optional[Any]									=					pa.array(TypedSequence(['''foo''', '''bar'''] ,						type=Value('''int64'''  )  )  )

 def  UpperCamelCase__(   self  ):



     '''simple docstring'''




     __A   :						int									=					pa.array(TypedSequence([1, 2, 3] ,						try_type=Value('''int32'''  )  )  )
     self.assertEqual(arr.type ,						pa.intaa()  )

 def  UpperCamelCase__(   self  ):



     '''simple docstring'''




     __A   :						Any									=					pa.array(TypedSequence(['''foo''', '''bar'''] ,						try_type=Value('''int64'''  )  )  )
     self.assertEqual(arr.type ,						pa.string()  )

 def  UpperCamelCase__(   self  ):



     '''simple docstring'''




     __A   :						Optional[int]									=					pa.array(TypedSequence([[[1, 2, 3]]] ,						type=ArrayaD((1, 3) ,						'''int64'''  )  )  )
     self.assertEqual(arr.type ,						ArrayaDExtensionType((1, 3) ,						'''int64'''  )  )

 def  UpperCamelCase__(   self  ):



     '''simple docstring'''




     with self.assertRaises((TypeError, pa.lib.ArrowInvalid)  ):
         __A   :						Any									=					pa.array(TypedSequence(['''foo''', '''bar'''] ,						type=ArrayaD((1, 3) ,						'''int64'''  )  )  )

 def  UpperCamelCase__(   self  ):



     '''simple docstring'''




     __A   :						Tuple									=					pa.array(TypedSequence([[[1, 2, 3]]] ,						try_type=ArrayaD((1, 3) ,						'''int64'''  )  )  )
     self.assertEqual(arr.type ,						ArrayaDExtensionType((1, 3) ,						'''int64'''  )  )

 def  UpperCamelCase__(   self  ):



     '''simple docstring'''




     __A   :						Optional[int]									=					pa.array(TypedSequence(['''foo''', '''bar'''] ,						try_type=ArrayaD((1, 3) ,						'''int64'''  )  )  )
     self.assertEqual(arr.type ,						pa.string()  )







 @require_pil
 def  UpperCamelCase__(   self  ):



     '''simple docstring'''




     import PIL.Image

     __A   :						str									=					PIL.Image.fromarray(np.arange(10 ,						dtype=np.uinta  ).reshape(2 ,						5  )  )
     with patch(
         '''datasets.arrow_writer.cast_to_python_objects''' ,						side_effect=__lowerCamelCase  ) as mock_cast_to_python_objects:
         __A   :						Union[str, Any]									=					pa.array(TypedSequence([{'''path''': None, '''bytes''': B'''image_bytes'''}, pil_image] ,						type=Image()  )  )
         __A			,	__A   :						Any									=					mock_cast_to_python_objects.call_args_list[-1]
         self.assertIn('''optimize_list_casting''' ,						__lowerCamelCase  )
         self.assertFalse(kwargs['''optimize_list_casting''']  )







def 		__lowercase					(       snake_case_  :  List[str]    ,snake_case_  :  int						)       ->int:



    '''simple docstring'''







    __A   :						Tuple									=					pa.BufferReader(snake_case_						) if isinstance(snake_case_    ,pa.Buffer						) else pa.memory_map(snake_case_						)
    __A   :						Optional[int]									=					pa.ipc.open_stream(snake_case_						)
    __A   :						pa.Table									=					f.read_all()
    assert len(pa_table.to_batches()						) == expected_num_chunks
    assert pa_table.to_pydict() == {"col_1": ["foo", "bar"], "col_2": [1, 2]}
    del pa_table







@pytest.mark.parametrize('''writer_batch_size'''    ,[None, 1, 10]						)
@pytest.mark.parametrize(
    '''fields'''    ,[None, {'''col_1''': pa.string(), '''col_2''': pa.intaa()}, {'''col_1''': pa.string(), '''col_2''': pa.intaa()}]						)
def 		__lowercase					(       snake_case_  :  List[str]    ,snake_case_  :  List[str]						)       ->Optional[Any]:



    '''simple docstring'''







    __A   :						Dict									=					pa.BufferOutputStream()
    __A   :						int									=					pa.schema(snake_case_						) if fields else None
    with ArrowWriter(stream=snake_case_    ,schema=snake_case_    ,writer_batch_size=snake_case_						) as writer:
        writer.write({'''col_1''': '''foo''', '''col_2''': 1}						)
        writer.write({'''col_1''': '''bar''', '''col_2''': 2}						)
        __A			,	__A   :						Optional[Any]									=					writer.finalize()
    assert num_examples == 2
    assert num_bytes > 0
    if not fields:
        __A   :						List[Any]									=					{'''col_1''': pa.string(), '''col_2''': pa.intaa()}
    assert writer._schema == pa.schema(snake_case_    ,metadata=writer._schema.metadata						)
    _check_output(output.getvalue()    ,expected_num_chunks=num_examples if writer_batch_size == 1 else 1						)







def 		__lowercase					(       )       ->Optional[int]:



    '''simple docstring'''







    __A   :						Optional[int]									=					pa.BufferOutputStream()
    __A   :						Optional[int]									=					Features({'''labels''': ClassLabel(names=['''neg''', '''pos''']						)}						)
    with ArrowWriter(stream=snake_case_    ,features=snake_case_						) as writer:
        writer.write({'''labels''': 0}						)
        writer.write({'''labels''': 1}						)
        __A			,	__A   :						str									=					writer.finalize()
    assert num_examples == 2
    assert num_bytes > 0
    assert writer._schema == features.arrow_schema
    assert writer._schema.metadata == features.arrow_schema.metadata
    __A   :						Union[str, Any]									=					pa.BufferReader(output.getvalue()						)
    __A   :						Optional[int]									=					pa.ipc.open_stream(snake_case_						)
    __A   :						pa.Table									=					f.read_all()
    __A   :						Tuple									=					pa_table.schema
    assert pa_table.num_rows == 2
    assert schema == features.arrow_schema
    assert schema.metadata == features.arrow_schema.metadata
    assert features == Features.from_arrow_schema(snake_case_						)







@pytest.mark.parametrize('''writer_batch_size'''    ,[None, 1, 10]						)
def 		__lowercase					(       snake_case_  :  int						)       ->str:



    '''simple docstring'''







    __A   :						List[Any]									=					pa.BufferOutputStream()
    with ArrowWriter(
        stream=snake_case_    ,writer_batch_size=snake_case_    ,hash_salt='''split_name'''    ,check_duplicates=snake_case_    ,) as writer:
        with pytest.raises(snake_case_						):
            writer.write({'''col_1''': '''foo''', '''col_2''': 1}    ,key=[1, 2]						)
            __A			,	__A   :						Any									=					writer.finalize()







@pytest.mark.parametrize('''writer_batch_size'''    ,[None, 2, 10]						)
def 		__lowercase					(       snake_case_  :  Tuple						)       ->Dict:



    '''simple docstring'''







    __A   :						int									=					pa.BufferOutputStream()
    with ArrowWriter(
        stream=snake_case_    ,writer_batch_size=snake_case_    ,hash_salt='''split_name'''    ,check_duplicates=snake_case_    ,) as writer:
        with pytest.raises(snake_case_						):
            writer.write({'''col_1''': '''foo''', '''col_2''': 1}    ,key=10						)
            writer.write({'''col_1''': '''bar''', '''col_2''': 2}    ,key=10						)
            __A			,	__A   :						Optional[int]									=					writer.finalize()







@pytest.mark.parametrize('''writer_batch_size'''    ,[None, 2, 10]						)
def 		__lowercase					(       snake_case_  :  List[Any]						)       ->int:



    '''simple docstring'''







    __A   :						Any									=					pa.BufferOutputStream()
    with ArrowWriter(
        stream=snake_case_    ,writer_batch_size=snake_case_    ,hash_salt='''split_name'''    ,check_duplicates=snake_case_    ,) as writer:
        writer.write({'''col_1''': '''foo''', '''col_2''': 1}    ,key=1						)
        writer.write({'''col_1''': '''bar''', '''col_2''': 2}    ,key=2						)
        __A			,	__A   :						List[str]									=					writer.finalize()
    assert num_examples == 2
    assert num_bytes > 0
    _check_output(output.getvalue()    ,expected_num_chunks=num_examples if writer_batch_size == 1 else 1						)







@pytest.mark.parametrize('''writer_batch_size'''    ,[None, 1, 10]						)
@pytest.mark.parametrize(
    '''fields'''    ,[None, {'''col_1''': pa.string(), '''col_2''': pa.intaa()}, {'''col_1''': pa.string(), '''col_2''': pa.intaa()}]						)
def 		__lowercase					(       snake_case_  :  str    ,snake_case_  :  Optional[int]						)       ->Any:



    '''simple docstring'''







    __A   :						Any									=					pa.BufferOutputStream()
    __A   :						Union[str, Any]									=					pa.schema(snake_case_						) if fields else None
    with ArrowWriter(stream=snake_case_    ,schema=snake_case_    ,writer_batch_size=snake_case_						) as writer:
        writer.write_batch({'''col_1''': ['''foo''', '''bar'''], '''col_2''': [1, 2]}						)
        writer.write_batch({'''col_1''': [], '''col_2''': []}						)
        __A			,	__A   :						Optional[Any]									=					writer.finalize()
    assert num_examples == 2
    assert num_bytes > 0
    if not fields:
        __A   :						Tuple									=					{'''col_1''': pa.string(), '''col_2''': pa.intaa()}
    assert writer._schema == pa.schema(snake_case_    ,metadata=writer._schema.metadata						)
    _check_output(output.getvalue()    ,expected_num_chunks=num_examples if writer_batch_size == 1 else 1						)







@pytest.mark.parametrize('''writer_batch_size'''    ,[None, 1, 10]						)
@pytest.mark.parametrize(
    '''fields'''    ,[None, {'''col_1''': pa.string(), '''col_2''': pa.intaa()}, {'''col_1''': pa.string(), '''col_2''': pa.intaa()}]						)
def 		__lowercase					(       snake_case_  :  Tuple    ,snake_case_  :  Union[str, Any]						)       ->Dict:



    '''simple docstring'''







    __A   :						Union[str, Any]									=					pa.BufferOutputStream()
    __A   :						Union[str, Any]									=					pa.schema(snake_case_						) if fields else None
    with ArrowWriter(stream=snake_case_    ,schema=snake_case_    ,writer_batch_size=snake_case_						) as writer:
        writer.write_table(pa.Table.from_pydict({'''col_1''': ['''foo''', '''bar'''], '''col_2''': [1, 2]}						)						)
        __A			,	__A   :						int									=					writer.finalize()
    assert num_examples == 2
    assert num_bytes > 0
    if not fields:
        __A   :						Union[str, Any]									=					{'''col_1''': pa.string(), '''col_2''': pa.intaa()}
    assert writer._schema == pa.schema(snake_case_    ,metadata=writer._schema.metadata						)
    _check_output(output.getvalue()    ,expected_num_chunks=num_examples if writer_batch_size == 1 else 1						)







@pytest.mark.parametrize('''writer_batch_size'''    ,[None, 1, 10]						)
@pytest.mark.parametrize(
    '''fields'''    ,[None, {'''col_1''': pa.string(), '''col_2''': pa.intaa()}, {'''col_1''': pa.string(), '''col_2''': pa.intaa()}]						)
def 		__lowercase					(       snake_case_  :  Optional[Any]    ,snake_case_  :  str						)       ->Dict:



    '''simple docstring'''







    __A   :						str									=					pa.BufferOutputStream()
    __A   :						Any									=					pa.schema(snake_case_						) if fields else None
    with ArrowWriter(stream=snake_case_    ,schema=snake_case_    ,writer_batch_size=snake_case_						) as writer:
        writer.write_row(pa.Table.from_pydict({'''col_1''': ['''foo'''], '''col_2''': [1]}						)						)
        writer.write_row(pa.Table.from_pydict({'''col_1''': ['''bar'''], '''col_2''': [2]}						)						)
        __A			,	__A   :						Dict									=					writer.finalize()
    assert num_examples == 2
    assert num_bytes > 0
    if not fields:
        __A   :						str									=					{'''col_1''': pa.string(), '''col_2''': pa.intaa()}
    assert writer._schema == pa.schema(snake_case_    ,metadata=writer._schema.metadata						)
    _check_output(output.getvalue()    ,expected_num_chunks=num_examples if writer_batch_size == 1 else 1						)







def 		__lowercase					(       )       ->Optional[Any]:



    '''simple docstring'''







    with tempfile.TemporaryDirectory() as tmp_dir:
        __A   :						Any									=					{'''col_1''': pa.string(), '''col_2''': pa.intaa()}
        __A   :						str									=					os.path.join(snake_case_    ,'''test.arrow'''						)
        with ArrowWriter(path=snake_case_    ,schema=pa.schema(snake_case_						)						) as writer:
            writer.write_batch({'''col_1''': ['''foo''', '''bar'''], '''col_2''': [1, 2]}						)
            __A			,	__A   :						int									=					writer.finalize()
        assert num_examples == 2
        assert num_bytes > 0
        assert writer._schema == pa.schema(snake_case_    ,metadata=writer._schema.metadata						)
        _check_output(snake_case_    ,1						)







def 		__lowercase					(       snake_case_  :  Optional[int]						)       ->Optional[int]:



    '''simple docstring'''







    if pa.types.is_list(snake_case_						):
        return get_base_dtype(arr_type.value_type						)
    else:
        return arr_type







def 		__lowercase					(       snake_case_  :  Dict    ,snake_case_  :  str						)       ->str:



    '''simple docstring'''







    if isinstance(lst[0]    ,snake_case_						):
        change_first_primitive_element_in_list(lst[0]    ,snake_case_						)
    else:
        __A   :						str									=					value







@pytest.mark.parametrize('''optimized_int_type, expected_dtype'''    ,[(None, pa.intaa()), (Value('''int32'''						), pa.intaa())]						)
@pytest.mark.parametrize('''sequence'''    ,[[1, 2, 3], [[1, 2, 3]], [[[1, 2, 3]]]]						)
def 		__lowercase					(       snake_case_  :  Dict    ,snake_case_  :  str    ,snake_case_  :  str						)       ->List[str]:



    '''simple docstring'''







    __A   :						List[Any]									=					pa.array(TypedSequence(snake_case_    ,optimized_int_type=snake_case_						)						)
    assert get_base_dtype(arr.type						) == expected_dtype







@pytest.mark.parametrize(
    '''col, expected_dtype'''    ,[
        ('''attention_mask''', pa.inta()),
        ('''special_tokens_mask''', pa.inta()),
        ('''token_type_ids''', pa.inta()),
        ('''input_ids''', pa.intaa()),
        ('''other''', pa.intaa()),
    ]    ,)
@pytest.mark.parametrize('''sequence'''    ,[[1, 2, 3], [[1, 2, 3]], [[[1, 2, 3]]]]						)
def 		__lowercase					(       snake_case_  :  List[Any]    ,snake_case_  :  Optional[Any]    ,snake_case_  :  List[str]						)       ->Union[str, Any]:



    '''simple docstring'''







    __A   :						Optional[int]									=					pa.array(OptimizedTypedSequence(snake_case_    ,col=snake_case_						)						)
    assert get_base_dtype(arr.type						) == expected_dtype

    # not in range
    if col != "other":
        # avoids errors due to in-place modifications
        __A   :						Optional[Any]									=					copy.deepcopy(snake_case_						)
        __A   :						Tuple									=					np.iinfo(expected_dtype.to_pandas_dtype()						).max + 1
        change_first_primitive_element_in_list(snake_case_    ,snake_case_						)
        __A   :						int									=					pa.array(OptimizedTypedSequence(snake_case_    ,col=snake_case_						)						)
        assert get_base_dtype(arr.type						) == pa.intaa()







@pytest.mark.parametrize('''raise_exception'''    ,[False, True]						)
def 		__lowercase					(       snake_case_  :  str    ,snake_case_  :  List[str]						)       ->List[Any]:



    '''simple docstring'''







    __A   :						Optional[int]									=					str(tmp_path / '''dataset-train.arrow'''						)
    try:
        with ArrowWriter(path=snake_case_						) as writer:
            if raise_exception:
                raise pa.lib.ArrowInvalid()
            else:
                writer.stream.close()
    except pa.lib.ArrowInvalid:
        pass
    finally:
        assert writer.stream.closed







def 		__lowercase					(       snake_case_  :  Union[str, Any]						)       ->List[Any]:



    '''simple docstring'''







    __A   :						int									=					'''mock://dataset-train.arrow'''
    with ArrowWriter(path=snake_case_    ,storage_options=mockfs.storage_options						) as writer:
        assert isinstance(writer._fs    ,type(snake_case_						)						)
        assert writer._fs.storage_options == mockfs.storage_options
        writer.write({'''col_1''': '''foo''', '''col_2''': 1}						)
        writer.write({'''col_1''': '''bar''', '''col_2''': 2}						)
        __A			,	__A   :						Dict									=					writer.finalize()
    assert num_examples == 2
    assert num_bytes > 0
    assert mockfs.exists(snake_case_						)







def 		__lowercase					(       )       ->List[Any]:



    '''simple docstring'''







    __A   :						Dict									=					pa.BufferOutputStream()
    with ParquetWriter(stream=snake_case_						) as writer:
        writer.write({'''col_1''': '''foo''', '''col_2''': 1}						)
        writer.write({'''col_1''': '''bar''', '''col_2''': 2}						)
        __A			,	__A   :						Union[str, Any]									=					writer.finalize()
    assert num_examples == 2
    assert num_bytes > 0
    __A   :						str									=					pa.BufferReader(output.getvalue()						)
    __A   :						pa.Table									=					pq.read_table(snake_case_						)
    assert pa_table.to_pydict() == {"col_1": ["foo", "bar"], "col_2": [1, 2]}







@require_pil
@pytest.mark.parametrize('''embed_local_files'''    ,[False, True]						)
def 		__lowercase					(       snake_case_  :  Any    ,snake_case_  :  Dict						)       ->List[str]:



    '''simple docstring'''







    import PIL.Image

    __A   :						str									=					str(tmp_path / '''test_image_rgb.jpg'''						)
    PIL.Image.fromarray(np.zeros((5, 5)    ,dtype=np.uinta						)						).save(snake_case_    ,format='''png'''						)
    __A   :						Dict									=					pa.BufferOutputStream()
    with ParquetWriter(
        stream=snake_case_    ,features=Features({'''image''': Image()}						)    ,embed_local_files=snake_case_						) as writer:
        writer.write({'''image''': image_path}						)
        writer.finalize()
    __A   :						Optional[Any]									=					pa.BufferReader(output.getvalue()						)
    __A   :						pa.Table									=					pq.read_table(snake_case_						)
    __A   :						List[str]									=					pa_table.to_pydict()
    if embed_local_files:
        assert isinstance(out['''image'''][0]['''path''']    ,snake_case_						)
        with open(snake_case_    ,'''rb'''						) as f:
            assert out["image"][0]["bytes"] == f.read()
    else:
        assert out["image"][0]["path"] == image_path
        assert out["image"][0]["bytes"] is None







def 		__lowercase					(       )       ->Optional[Any]:



    '''simple docstring'''







    __A   :						Optional[int]									=					pa.schema([pa.field('''col_1'''    ,pa.string()    ,nullable=snake_case_						)]						)
    __A   :						List[Any]									=					pa.BufferOutputStream()
    with ArrowWriter(stream=snake_case_						) as writer:
        writer._build_writer(inferred_schema=snake_case_						)
        assert writer._schema == pa.schema([pa.field('''col_1'''    ,pa.string()						)]						)











"""simple docstring"""



from decimal import Decimal, getcontext
from math import ceil, factorial







def 		__lowercase					(       snake_case_  :  int						)       ->str:



    '''simple docstring'''







    if not isinstance(snake_case_    ,snake_case_						):
        raise TypeError('''Undefined for non-integers'''						)
    elif precision < 1:
        raise ValueError('''Undefined for non-natural numbers'''						)

    __A   :						int									=					precision
    __A   :						Tuple									=					ceil(precision / 14						)
    __A   :						Dict									=					426880 * Decimal(10005						).sqrt()
    __A   :						Optional[Any]									=					1
    __A   :						int									=					13591409
    __A   :						Optional[int]									=					Decimal(snake_case_						)
    for k in range(1    ,snake_case_						):
        __A   :						int									=					factorial(6 * k						) // (factorial(3 * k						) * factorial(snake_case_						) ** 3)
        linear_term += 545140134
        exponential_term *= -262537412640768000
        partial_sum += Decimal(multinomial_term * linear_term						) / exponential_term
    return str(constant_term / partial_sum						)[:-1]


if __name__ == "__main__":
       a_			=      50
       print(f'''The first {n} digits of pi is: {pi(n)}''')




