






"""simple docstring"""







import tempfile
import unittest

import numpy as np
from huggingface_hub import HfFolder, delete_repo
from requests.exceptions import HTTPError

from transformers import BertConfig, is_flax_available
from transformers.testing_utils import TOKEN, USER, is_staging_test, require_flax


if is_flax_available():
				import os

				from flax.core.frozen_dict import unfreeze
				from flax.traverse_util import flatten_dict

				from transformers import FlaxBertModel

				_lowerCAmelCase            =	'0.12'  # assumed parallelism: 8


@require_flax
@is_staging_test
class      UpperCamelCase		(unittest.TestCase     ):






						@classmethod
						def      __snake_case      (		cls  :Optional[int]				)      ->Optional[int]:
										lowercase    :      str       = TOKEN
										HfFolder.save_token(__magic_name__				)






						@classmethod
						def      __snake_case      (		cls  :Tuple				)      ->str:
										try:
														delete_repo(token=cls._token			, repo_id="""test-model-flax"""				)
										except HTTPError:
														pass

										try:
														delete_repo(token=cls._token			, repo_id="""valid_org/test-model-flax-org"""				)
										except HTTPError:
														pass






						def      __snake_case      (		self  :List[str]				)      ->Tuple:
										lowercase    :      List[Any]       = BertConfig(
										    vocab_size=99			, hidden_size=32			, num_hidden_layers=5			, num_attention_heads=4			, intermediate_size=37				)
										lowercase    :      List[str]       = FlaxBertModel(__magic_name__				)
										model.push_to_hub("""test-model-flax"""			, use_auth_token=self._token				)

										lowercase    :      int       = FlaxBertModel.from_pretrained(f"""{USER}/test-model-flax"""				)

										lowercase    :      Dict       = flatten_dict(unfreeze(model.params				)				)
										lowercase    :      str       = flatten_dict(unfreeze(new_model.params				)				)

										for key in base_params.keys():
														lowercase    :      int       = (base_params[key] - new_params[key]).sum().item()
														self.assertLessEqual(__magic_name__			, 1E-3			, msg=f"""{key} not identical"""				)

										# Reset repo
										delete_repo(token=self._token			, repo_id="""test-model-flax"""				)

										# Push to hub via save_pretrained
										with tempfile.TemporaryDirectory() as tmp_dir:
														model.save_pretrained(__magic_name__			, repo_id="""test-model-flax"""			, push_to_hub=__magic_name__			, use_auth_token=self._token				)

										lowercase    :      List[Any]       = FlaxBertModel.from_pretrained(f"""{USER}/test-model-flax"""				)

										lowercase    :      str       = flatten_dict(unfreeze(model.params				)				)
										lowercase    :      Optional[int]       = flatten_dict(unfreeze(new_model.params				)				)

										for key in base_params.keys():
														lowercase    :      str       = (base_params[key] - new_params[key]).sum().item()
														self.assertLessEqual(__magic_name__			, 1E-3			, msg=f"""{key} not identical"""				)






						def      __snake_case      (		self  :Optional[int]				)      ->List[Any]:
										lowercase    :      Optional[int]       = BertConfig(
										    vocab_size=99			, hidden_size=32			, num_hidden_layers=5			, num_attention_heads=4			, intermediate_size=37				)
										lowercase    :      Optional[Any]       = FlaxBertModel(__magic_name__				)
										model.push_to_hub("""valid_org/test-model-flax-org"""			, use_auth_token=self._token				)

										lowercase    :      str       = FlaxBertModel.from_pretrained("""valid_org/test-model-flax-org"""				)

										lowercase    :      Dict       = flatten_dict(unfreeze(model.params				)				)
										lowercase    :      int       = flatten_dict(unfreeze(new_model.params				)				)

										for key in base_params.keys():
														lowercase    :      Dict       = (base_params[key] - new_params[key]).sum().item()
														self.assertLessEqual(__magic_name__			, 1E-3			, msg=f"""{key} not identical"""				)

										# Reset repo
										delete_repo(token=self._token			, repo_id="""valid_org/test-model-flax-org"""				)

										# Push to hub via save_pretrained
										with tempfile.TemporaryDirectory() as tmp_dir:
														model.save_pretrained(
														    __magic_name__			, repo_id="""valid_org/test-model-flax-org"""			, push_to_hub=__magic_name__			, use_auth_token=self._token				)

										lowercase    :      Any       = FlaxBertModel.from_pretrained("""valid_org/test-model-flax-org"""				)

										lowercase    :      List[str]       = flatten_dict(unfreeze(model.params				)				)
										lowercase    :      int       = flatten_dict(unfreeze(new_model.params				)				)

										for key in base_params.keys():
														lowercase    :      List[Any]       = (base_params[key] - new_params[key]).sum().item()
														self.assertLessEqual(__magic_name__			, 1E-3			, msg=f"""{key} not identical"""				)


def      UpperCamelCase       ( _A  ,				_A )     ->       Tuple:
				lowercase    :      Optional[Any]       = True
				lowercase    :      Union[str, Any]       = flatten_dict(modela.params )
				lowercase    :      str       = flatten_dict(modela.params )
				for key in flat_params_a.keys():
								if np.sum(np.abs(flat_params_a[key] - flat_params_a[key] ) ) > 1e-4:
												lowercase    :      Optional[int]       = False

				return models_are_equal


@require_flax
class      UpperCamelCase		(unittest.TestCase     ):






						def      __snake_case      (		self  :Dict				)      ->Union[str, Any]:
										lowercase    :      Optional[int]       = BertConfig.from_pretrained("""hf-internal-testing/tiny-bert-flax-only"""				)
										lowercase    :      Dict       = FlaxBertModel(__magic_name__				)

										lowercase    :      List[Any]       = """bert"""
										with tempfile.TemporaryDirectory() as tmp_dir:
														model.save_pretrained(os.path.join(__magic_name__			, __magic_name__				)				)

														with self.assertRaises(__magic_name__				):
																		lowercase    :      Optional[Any]       = FlaxBertModel.from_pretrained(__magic_name__				)

														lowercase    :      Union[str, Any]       = FlaxBertModel.from_pretrained(__magic_name__			, subfolder=__magic_name__				)

										self.assertTrue(check_models_equal(__magic_name__			, __magic_name__				)				)






						def      __snake_case      (		self  :List[Any]				)      ->List[str]:
										lowercase    :      List[Any]       = BertConfig.from_pretrained("""hf-internal-testing/tiny-bert-flax-only"""				)
										lowercase    :      Optional[int]       = FlaxBertModel(__magic_name__				)

										lowercase    :      Union[str, Any]       = """bert"""
										with tempfile.TemporaryDirectory() as tmp_dir:
														model.save_pretrained(os.path.join(__magic_name__			, __magic_name__				)			, max_shard_size="""10KB"""				)

														with self.assertRaises(__magic_name__				):
																		lowercase    :      List[Any]       = FlaxBertModel.from_pretrained(__magic_name__				)

														lowercase    :      Optional[int]       = FlaxBertModel.from_pretrained(__magic_name__			, subfolder=__magic_name__				)

										self.assertTrue(check_models_equal(__magic_name__			, __magic_name__				)				)






						def      __snake_case      (		self  :Tuple				)      ->Optional[Any]:
										lowercase    :      int       = """bert"""
										lowercase    :      List[Any]       = """hf-internal-testing/tiny-random-bert-subfolder"""

										with self.assertRaises(__magic_name__				):
														lowercase    :      Optional[Any]       = FlaxBertModel.from_pretrained(__magic_name__				)

										lowercase    :      List[Any]       = FlaxBertModel.from_pretrained(__magic_name__			, subfolder=__magic_name__				)

										self.assertIsNotNone(__magic_name__				)






						def      __snake_case      (		self  :List[Any]				)      ->int:
										lowercase    :      str       = """bert"""
										lowercase    :      List[str]       = """hf-internal-testing/tiny-random-bert-sharded-subfolder"""
										with self.assertRaises(__magic_name__				):
														lowercase    :      int       = FlaxBertModel.from_pretrained(__magic_name__				)

										lowercase    :      int       = FlaxBertModel.from_pretrained(__magic_name__			, subfolder=__magic_name__				)

										self.assertIsNotNone(__magic_name__				)








"""simple docstring"""







def      UpperCamelCase       ( _A  ,				_A )     ->       int:
				lowercase    :      int       = 1  # To kept the Calculated Value
				# Since C(n, k) = C(n, n-k)
				if k > (n - k):
								lowercase    :      List[Any]       = n - k
				# Calculate C(n,k)
				for i in range(_A ):
								result *= n - i
								result //= i + 1
				return result


def      UpperCamelCase       ( _A )     ->       int:
				return binomial_coefficient(2 * node_count  ,				_A ) // (node_count + 1)


def      UpperCamelCase       ( _A )     ->       int:
				if n < 0:
								raise ValueError("""factorial() not defined for negative values""" )
				lowercase    :      Union[str, Any]       = 1
				for i in range(1  ,				n + 1 ):
								result *= i
				return result


def      UpperCamelCase       ( _A )     ->       int:
				return catalan_number(_A ) * factorial(_A )


if __name__ == "__main__":
				_lowerCAmelCase            =	int(input('Enter the number of nodes: ').strip() or 0)
				if node_count <= 0:
								raise ValueError('We need some nodes to work with.')
				print(
				    F'Given {node_count} nodes, there are {binary_tree_count(node_count)} '
				    F'binary trees and {catalan_number(node_count)} binary search trees.'
				)
