






import time
from dataclasses import dataclass
from multiprocessing import Pool
from unittest import TestCase
from unittest.mock import patch

import multiprocess
import numpy as np
import pytest

from datasets.utils.py_utils import (
    NestedDataStructure,
    asdict,
    iflatmap_unordered,
    map_nested,
    temp_seed,
    temporary_assignment,
    zip_dict,
)

from .utils import require_tf, require_torch


def __A    (      __lowerCAmelCase	)->  Any:  # picklable for multiprocessing





						"""simple docstring"""



						return x.sum()


def __A    (      __lowerCAmelCase	)->  List[str]:  # picklable for multiprocessing





						"""simple docstring"""



						return i + 1





@dataclass
class __lowerCamelCase :





	"""simple docstring"""






	UpperCamelCase__								=      42
	UpperCamelCase__								=      42





class __lowerCamelCase (      __lowercase):





	"""simple docstring"""






	def        UpperCamelCase    (							self    ):
							"""simple docstring"""







							_UpperCAmelCase									=			{}
							_UpperCAmelCase									=			[]
							_UpperCAmelCase									=			1
							_UpperCAmelCase									=			[1, 2]
							_UpperCAmelCase									=			{'''a''': 1, '''b''': 2}
							_UpperCAmelCase									=			{'''a''': [1, 2], '''b''': [3, 4]}
							_UpperCAmelCase									=			{'''a''': {'''1''': 1}, '''b''': 2}
							_UpperCAmelCase									=			{'''a''': 1, '''b''': 2, '''c''': 3, '''d''': 4}
							_UpperCAmelCase									=			{}
							_UpperCAmelCase									=			[]
							_UpperCAmelCase									=			2
							_UpperCAmelCase									=			[2, 3]
							_UpperCAmelCase									=			{'''a''': 2, '''b''': 3}
							_UpperCAmelCase									=			{'''a''': [2, 3], '''b''': [4, 5]}
							_UpperCAmelCase									=			{'''a''': {'''1''': 2}, '''b''': 3}
							_UpperCAmelCase									=			{'''a''': 2, '''b''': 3, '''c''': 4, '''d''': 5}
							self.assertEqual(map_nested(_a       ,    _a    )       ,    _a    )
							self.assertEqual(map_nested(_a       ,    _a    )       ,    _a    )
							self.assertEqual(map_nested(_a       ,    _a    )       ,    _a    )
							self.assertEqual(map_nested(_a       ,    _a    )       ,    _a    )
							self.assertEqual(map_nested(_a       ,    _a    )       ,    _a    )
							self.assertEqual(map_nested(_a       ,    _a    )       ,    _a    )
							self.assertEqual(map_nested(_a       ,    _a    )       ,    _a    )
							self.assertEqual(map_nested(_a       ,    _a    )       ,    _a    )

							_UpperCAmelCase									=			2
							self.assertEqual(map_nested(_a       ,    _a       ,    num_proc=_a    )       ,    _a    )
							self.assertEqual(map_nested(_a       ,    _a       ,    num_proc=_a    )       ,    _a    )
							self.assertEqual(map_nested(_a       ,    _a       ,    num_proc=_a    )       ,    _a    )
							self.assertEqual(map_nested(_a       ,    _a       ,    num_proc=_a    )       ,    _a    )
							self.assertEqual(map_nested(_a       ,    _a       ,    num_proc=_a    )       ,    _a    )
							self.assertEqual(map_nested(_a       ,    _a       ,    num_proc=_a    )       ,    _a    )
							self.assertEqual(map_nested(_a       ,    _a       ,    num_proc=_a    )       ,    _a    )
							self.assertEqual(map_nested(_a       ,    _a       ,    num_proc=_a    )       ,    _a    )

							_UpperCAmelCase									=			{'''a''': np.eye(2    ), '''b''': np.zeros(3    ), '''c''': np.ones(2    )}
							_UpperCAmelCase									=			{'''a''': 2, '''b''': 0, '''c''': 2}
							_UpperCAmelCase									=			{
							    '''a''': np.eye(2    ).astype(_a    ),
							    '''b''': np.zeros(3    ).astype(_a    ),
							    '''c''': np.ones(2    ).astype(_a    ),
							}
							self.assertEqual(map_nested(_a       ,    _a       ,    map_numpy=_a    )       ,    _a    )
							self.assertEqual(
							    {k: v.tolist() for k, v in map_nested(_a       ,    _a       ,    map_numpy=_a    ).items()}       ,    {k: v.tolist() for k, v in expected_map_nested_sna_int.items()}       ,    )
							self.assertEqual(map_nested(_a       ,    _a       ,    map_numpy=_a       ,    num_proc=_a    )       ,    _a    )
							self.assertEqual(
							    {k: v.tolist() for k, v in map_nested(_a       ,    _a       ,    map_numpy=_a       ,    num_proc=_a    ).items()}       ,    {k: v.tolist() for k, v in expected_map_nested_sna_int.items()}       ,    )
							with self.assertRaises(_a    ):  # can't pickle a local lambda
													map_nested(lambda UpperCAmelCase    : x + 1       ,    _a       ,    num_proc=_a    )

	def        UpperCamelCase    (							self    ):
							"""simple docstring"""







							_UpperCAmelCase									=			{'''a''': 1, '''b''': 2}
							_UpperCAmelCase									=			{'''a''': 3, '''b''': 4}
							_UpperCAmelCase									=			{'''a''': 5, '''b''': 6}
							_UpperCAmelCase									=			sorted([('a', (1, 3, 5)), ('b', (2, 4, 6))]    )
							self.assertEqual(sorted(zip_dict(_a       ,    _a       ,    _a    )    )       ,    _a    )

	def        UpperCamelCase    (							self    ):
							"""simple docstring"""







							class __lowerCamelCase :





								"""simple docstring"""






								UpperCamelCase__								=      "bar"



							_UpperCAmelCase									=			Foo()
							self.assertEqual(foo.my_attr       ,    'bar'    )
							with temporary_assignment(_a       ,    'my_attr'       ,    'BAR'    ):
													self.assertEqual(foo.my_attr       ,    'BAR'    )
							self.assertEqual(foo.my_attr       ,    'bar'    )



@pytest.mark.parametrize(
    'iterable_length, num_proc, expected_num_proc' ,		[
        (1, None, 1),
        (1, 1, 1),
        (2, None, 1),
        (2, 1, 1),
        (2, 2, 1),
        (2, 3, 1),
        (3, 2, 1),
        (16, 16, 16),
        (16, 17, 16),
        (17, 16, 16),
    ] ,		)
def __A    (      __lowerCAmelCase ,		__lowerCAmelCase ,		__lowerCAmelCase	)->  int:





						"""simple docstring"""



						with patch('datasets.utils.py_utils._single_map_nested'	) as mock_single_map_nested, patch(
						    'datasets.parallel.parallel.Pool'	) as mock_multiprocessing_pool:
												_UpperCAmelCase									=			{F"""{i}""": i for i in range(__a	)}
												_UpperCAmelCase									=			map_nested(lambda __lowerCAmelCase	: x + 10 ,		__a ,		num_proc=__a ,		parallel_min_length=16	)
												if expected_num_proc == 1:
																		assert mock_single_map_nested.called
																		assert not mock_multiprocessing_pool.called
												else:
																		assert not mock_single_map_nested.called
																		assert mock_multiprocessing_pool.called
																		assert mock_multiprocessing_pool.call_args[0][0] == expected_num_proc





class __lowerCamelCase (      __lowercase):





	"""simple docstring"""






	@require_tf
	def        UpperCamelCase    (							self    ):
							"""simple docstring"""







							import tensorflow as tf
							from tensorflow.keras import layers

							_UpperCAmelCase									=			layers.Dense(2    )

							def gen_random_output():
													_UpperCAmelCase									=			tf.random.uniform((1, 3)    )
													return model(_a    ).numpy()

							with temp_seed(42       ,    set_tensorflow=_a    ):
													_UpperCAmelCase									=			gen_random_output()
							with temp_seed(42       ,    set_tensorflow=_a    ):
													_UpperCAmelCase									=			gen_random_output()
							_UpperCAmelCase									=			gen_random_output()

							np.testing.assert_equal(_a       ,    _a    )
							self.assertGreater(np.abs(outa - outa    ).sum()       ,    0    )

	@require_torch
	def        UpperCamelCase    (							self    ):
							"""simple docstring"""







							import torch

							def gen_random_output():
													_UpperCAmelCase									=			torch.nn.Linear(3       ,    2    )
													_UpperCAmelCase									=			torch.rand(1       ,    3    )
													return model(_a    ).detach().numpy()

							with temp_seed(42       ,    set_pytorch=_a    ):
													_UpperCAmelCase									=			gen_random_output()
							with temp_seed(42       ,    set_pytorch=_a    ):
													_UpperCAmelCase									=			gen_random_output()
							_UpperCAmelCase									=			gen_random_output()

							np.testing.assert_equal(_a       ,    _a    )
							self.assertGreater(np.abs(outa - outa    ).sum()       ,    0    )

	def        UpperCamelCase    (							self    ):
							"""simple docstring"""







							def gen_random_output():
													return np.random.rand(1       ,    3    )

							with temp_seed(42    ):
													_UpperCAmelCase									=			gen_random_output()
							with temp_seed(42    ):
													_UpperCAmelCase									=			gen_random_output()
							_UpperCAmelCase									=			gen_random_output()

							np.testing.assert_equal(_a       ,    _a    )
							self.assertGreater(np.abs(outa - outa    ).sum()       ,    0    )



@pytest.mark.parametrize('input_data' ,		[{}]	)
def __A    (      __lowerCAmelCase	)->  int:





						"""simple docstring"""



						_UpperCAmelCase									=			NestedDataStructure(__a	).data
						assert output_data == input_data


@pytest.mark.parametrize(
    'data, expected_output' ,		[
        ({}, []),
        ([], []),
        ('foo', ['foo']),
        (['foo', 'bar'], ['foo', 'bar']),
        ([['foo', 'bar']], ['foo', 'bar']),
        ([[['foo'], ['bar']]], ['foo', 'bar']),
        ([[['foo'], 'bar']], ['foo', 'bar']),
        ({'a': 1, 'b': 2}, [1, 2]),
        ({'a': [1, 2], 'b': [3, 4]}, [1, 2, 3, 4]),
        ({'a': [[1, 2]], 'b': [[3, 4]]}, [1, 2, 3, 4]),
        ({'a': [[1, 2]], 'b': [3, 4]}, [1, 2, 3, 4]),
        ({'a': [[[1], [2]]], 'b': [[[3], [4]]]}, [1, 2, 3, 4]),
        ({'a': [[[1], [2]]], 'b': [[3, 4]]}, [1, 2, 3, 4]),
        ({'a': [[[1], [2]]], 'b': [3, 4]}, [1, 2, 3, 4]),
        ({'a': [[[1], [2]]], 'b': [3, [4]]}, [1, 2, 3, 4]),
        ({'a': {'1': 1}, 'b': 2}, [1, 2]),
        ({'a': {'1': [1]}, 'b': 2}, [1, 2]),
        ({'a': {'1': [1]}, 'b': [2]}, [1, 2]),
    ] ,		)
def __A    (      __lowerCAmelCase ,		__lowerCAmelCase	)->  List[Any]:





						"""simple docstring"""



						_UpperCAmelCase									=			NestedDataStructure(__a	).flatten()
						assert output == expected_output


def __A    (      )->  Optional[int]:





						"""simple docstring"""



						_UpperCAmelCase									=			A(x=1 ,		y='foobar'	)
						_UpperCAmelCase									=			{'''x''': 1, '''y''': '''foobar'''}
						assert asdict(__a	) == expected_output

						_UpperCAmelCase									=			{'''a''': {'''b''': A(x=10 ,		y='foo'	)}, '''c''': [A(x=20 ,		y='bar'	)]}
						_UpperCAmelCase									=			{'''a''': {'''b''': {'''x''': 10, '''y''': '''foo'''}}, '''c''': [{'''x''': 20, '''y''': '''bar'''}]}
						assert asdict(__a	) == expected_output

						with pytest.raises(__a	):
												asdict([1, A(x=10 ,		y='foo'	)]	)


def __A    (      __lowerCAmelCase	)->  List[Any]:





						"""simple docstring"""



						return text.split()


def __A    (      __lowerCAmelCase	)->  Optional[Any]:





						"""simple docstring"""



						yield (time.time(), content)
						time.sleep(2	)
						yield (time.time(), content)


def __A    (      )->  List[Any]:





						"""simple docstring"""



						with Pool(2	) as pool:
												_UpperCAmelCase									=			list(iflatmap_unordered(__a ,		_split_text ,		kwargs_iterable=[{'text': 'hello there'}] * 10	)	)
												assert out.count('hello'	) == 10
												assert out.count('there'	) == 10
												assert len(__a	) == 20

						# check multiprocess from pathos (uses dill for pickling)
						with multiprocess.Pool(2	) as pool:
												_UpperCAmelCase									=			list(iflatmap_unordered(__a ,		_split_text ,		kwargs_iterable=[{'text': 'hello there'}] * 10	)	)
												assert out.count('hello'	) == 10
												assert out.count('there'	) == 10
												assert len(__a	) == 20

						# check that we get items as fast as possible
						with Pool(2	) as pool:
												_UpperCAmelCase									=			[]
												for yield_time, content in iflatmap_unordered(
												    __a ,		_aseconds_generator_of_aitems_with_timing ,		kwargs_iterable=[{'content': 'a'}, {'content': 'b'}]	):
																		assert yield_time < time.time() + 0.1, "we should each item directly after it was yielded"
																		out.append(__a	)
												assert out.count('a'	) == 2
												assert out.count('b'	) == 2
												assert len(__a	) == 4



def    __UpperCAmelCase (	__a      :			int		,__a      :			list[int]		,__a      :			int	)			->     int:

					"""simple docstring"""

					def count_of_possible_combinations(__a      :			int	) -> int:
										if target < 0:
															return 0
										if target == 0:
															return 1
										return sum(count_of_possible_combinations(target - item	) for item in array	)

					return count_of_possible_combinations(__a	)



def    __UpperCAmelCase (	__a      :			int		,__a      :			list[int]		,__a      :			int	)			->     int:

					"""simple docstring"""

					def count_of_possible_combinations_with_dp_array(
					    __a      :			int		,__a      :			list[int]	) -> int:
										if target < 0:
															return 0
										if target == 0:
															return 1
										if dp_array[target] != -1:
															return dp_array[target]
										_a	:    Union[str, Any]         =		sum(
										    count_of_possible_combinations_with_dp_array(target - item		,__a	)
										    for item in array	)
										_a	:    Optional[int]         =		answer
										return answer

					_a	:    int         =		[-1] * (target + 1)
					return count_of_possible_combinations_with_dp_array(__a		,__a	)



def    __UpperCAmelCase (	__a      :			int		,__a      :			list[int]		,__a      :			int	)			->     int:

					"""simple docstring"""

					_a	:    str         =		[0] * (target + 1)
					_a	:    Optional[Any]         =		1

					for i in range(1		,target + 1	):
										for j in range(__a	):
															if i - array[j] >= 0:
																				dp_array[i] += dp_array[i - array[j]]

					return dp_array[target]


if __name__ == "__main__":
			import doctest

			doctest.testmod()
			a__				=		3
			a__				=		5
			a__				=		[1, 2, 5]
			print(combination_sum_iv(n, array, target))



