'''simple docstring'''




import inspect
import unittest

from transformers import ConvNextConfig
from transformers.testing_utils import require_torch, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available

from ...test_backbone_common import BackboneTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
  import torch

  from transformers import ConvNextBackbone, ConvNextForImageClassification, ConvNextModel
  from transformers.models.convnext.modeling_convnext import CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
  from PIL import Image

  from transformers import AutoImageProcessor

class 	lowerCamelCase_	:
      '''simple docstring'''

      def __init__(       self						:				Optional[int]						,					A						:				int						,					A						:				List[str]=13						,					A						:				Dict=32						,					A						:				Any=3						,					A						:				Union[str, Any]=4						,					A						:				Optional[Any]=[10, 20, 30, 40]						,					A						:				List[str]=[2, 2, 3, 2]						,					A						:				str=True						,					A						:				Dict=True						,					A						:				Tuple=37						,					A						:				Optional[int]="gelu"						,					A						:				Tuple=10						,					A						:				int=0.02						,					A						:				List[Any]=["stage2", "stage3", "stage4"]						,					A						:				List[Any]=[2, 3, 4]						,					A						:				List[Any]=None						,					):
             _UpperCAmelCase     :  Dict							      =    parent
             _UpperCAmelCase     :  Dict							      =    batch_size
             _UpperCAmelCase     :  List[Any]							      =    image_size
             _UpperCAmelCase     :  Optional[int]							      =    num_channels
             _UpperCAmelCase     :  List[str]							      =    num_stages
             _UpperCAmelCase     :  Any							      =    hidden_sizes
             _UpperCAmelCase     :  Any							      =    depths
             _UpperCAmelCase     :  Dict							      =    is_training
             _UpperCAmelCase     :  int							      =    use_labels
             _UpperCAmelCase     :  Dict							      =    intermediate_size
             _UpperCAmelCase     :  int							      =    hidden_act
             _UpperCAmelCase     :  Optional[int]							      =    num_labels
             _UpperCAmelCase     :  Optional[int]							      =    initializer_range
             _UpperCAmelCase     :  Tuple							      =    out_features
             _UpperCAmelCase     :  List[Any]							      =    out_indices
             _UpperCAmelCase     :  Optional[Any]							      =    scope




      def      _A	(       self						:				Optional[int]       ):
             _UpperCAmelCase     :  Any							      =    floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]       )

             _UpperCAmelCase     :  str							      =    None
             if self.use_labels:
                    _UpperCAmelCase     :  Any							      =    ids_tensor([self.batch_size]						,					self.num_labels       )

             _UpperCAmelCase     :  Optional[Any]							      =    self.get_config()
             return config, pixel_values, labels




      def      _A	(       self						:				Optional[Any]       ):
             return ConvNextConfig(
                 num_channels=self.num_channels						,					hidden_sizes=self.hidden_sizes						,					depths=self.depths						,					num_stages=self.num_stages						,					hidden_act=self.hidden_act						,					is_decoder=A						,					initializer_range=self.initializer_range						,					out_features=self.out_features						,					out_indices=self.out_indices						,					num_labels=self.num_labels						,					)




      def      _A	(       self						:				Dict						,					A						:				Any						,					A						:				List[str]						,					A						:				Optional[Any]       ):
             _UpperCAmelCase     :  Optional[int]							      =    ConvNextModel(config=A       )
             model.to(A       )
             model.eval()
             _UpperCAmelCase     :  Tuple							      =    model(A       )
             # expected last hidden states: B, C, H // 32, W // 32
             self.parent.assertEqual(
                 result.last_hidden_state.shape						,					(self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32)						,					)




      def      _A	(       self						:				List[Any]						,					A						:				Tuple						,					A						:				int						,					A						:				int       ):
             _UpperCAmelCase     :  int							      =    ConvNextForImageClassification(A       )
             model.to(A       )
             model.eval()
             _UpperCAmelCase     :  List[str]							      =    model(A						,					labels=A       )
             self.parent.assertEqual(result.logits.shape						,					(self.batch_size, self.num_labels)       )




      def      _A	(       self						:				Union[str, Any]						,					A						:				Optional[int]						,					A						:				List[Any]						,					A						:				str       ):
             _UpperCAmelCase     :  List[str]							      =    ConvNextBackbone(config=A       )
             model.to(A       )
             model.eval()
             _UpperCAmelCase     :  Union[str, Any]							      =    model(A       )

             # verify hidden states
             self.parent.assertEqual(len(result.feature_maps       )						,					len(config.out_features       )       )
             self.parent.assertListEqual(list(result.feature_maps[0].shape       )						,					[self.batch_size, self.hidden_sizes[1], 4, 4]       )

             # verify channels
             self.parent.assertEqual(len(model.channels       )						,					len(config.out_features       )       )
             self.parent.assertListEqual(model.channels						,					config.hidden_sizes[1:]       )

             # verify backbone works with out_features=None
             _UpperCAmelCase     :  List[str]							      =    None
             _UpperCAmelCase     :  Dict							      =    ConvNextBackbone(config=A       )
             model.to(A       )
             model.eval()
             _UpperCAmelCase     :  List[str]							      =    model(A       )

             # verify feature maps
             self.parent.assertEqual(len(result.feature_maps       )						,					1       )
             self.parent.assertListEqual(list(result.feature_maps[0].shape       )						,					[self.batch_size, self.hidden_sizes[-1], 1, 1]       )

             # verify channels
             self.parent.assertEqual(len(model.channels       )						,					1       )
             self.parent.assertListEqual(model.channels						,					[config.hidden_sizes[-1]]       )





      def      _A	(       self						:				Dict       ):
             _UpperCAmelCase     :  Tuple							      =    self.prepare_config_and_inputs()
             _UpperCAmelCase      ,  _UpperCAmelCase      ,  _UpperCAmelCase     :  int							      =    config_and_inputs
             _UpperCAmelCase     :  Optional[int]							      =    {"pixel_values": pixel_values}
             return config, inputs_dict

@require_torch
class 	lowerCamelCase_	(snake_case__							, snake_case__							, unittest.TestCase    ):
      '''simple docstring'''

      __UpperCamelCase:  List[str]						=						(
          (
              ConvNextModel,
              ConvNextForImageClassification,
              ConvNextBackbone,
          )
          if is_torch_available()
          else ()
      )
      __UpperCamelCase:  List[Any]						=						(
          {"feature-extraction": ConvNextModel, "image-classification": ConvNextForImageClassification}
          if is_torch_available()
          else {}
      )

      __UpperCamelCase:  str						=						True
      __UpperCamelCase:  List[Any]						=						False
      __UpperCamelCase:  str						=						False
      __UpperCamelCase:  Optional[int]						=						False
      __UpperCamelCase:  List[Any]						=						False




      def      _A	(       self						:				Optional[int]       ):
             _UpperCAmelCase     :  int							      =    ConvNextModelTester(self       )
             _UpperCAmelCase     :  str							      =    ConfigTester(self						,					config_class=A						,					has_text_modality=A						,					hidden_size=37       )




      def      _A	(       self						:				List[str]       ):
             self.create_and_test_config_common_properties()
             self.config_tester.create_and_test_config_to_json_string()
             self.config_tester.create_and_test_config_to_json_file()
             self.config_tester.create_and_test_config_from_and_save_pretrained()
             self.config_tester.create_and_test_config_with_num_labels()
             self.config_tester.check_config_can_be_init_without_params()
             self.config_tester.check_config_arguments_init()




      def      _A	(       self						:				Tuple       ):
             return




      @unittest.skip(reason="ConvNext does not use inputs_embeds"       )
      def      _A	(       self						:				str       ):
             pass




      @unittest.skip(reason="ConvNext does not support input and output embeddings"       )
      def      _A	(       self						:				Dict       ):
             pass




      @unittest.skip(reason="ConvNext does not use feedforward chunking"       )
      def      _A	(       self						:				List[Any]       ):
             pass




      def      _A	(       self						:				Any       ):
             _UpperCAmelCase      ,  _UpperCAmelCase     :  Optional[int]							      =    self.model_tester.prepare_config_and_inputs_for_common()

             for model_class in self.all_model_classes:
                    _UpperCAmelCase     :  int							      =    model_class(A       )
                    _UpperCAmelCase     :  List[str]							      =    inspect.signature(model.forward       )
                    # signature.parameters is an OrderedDict => so arg_names order is deterministic
                    _UpperCAmelCase     :  Dict							      =    [*signature.parameters.keys()]

                    _UpperCAmelCase     :  Tuple							      =    ["pixel_values"]
                    self.assertListEqual(arg_names[:1]						,					A       )




      def      _A	(       self						:				Optional[int]       ):
             _UpperCAmelCase     :  int							      =    self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_model(*A       )




      def      _A	(       self						:				int       ):
             _UpperCAmelCase     :  Dict							      =    self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_backbone(*A       )




      def      _A	(       self						:				int       ):
             def check_hidden_states_output(A						:				Dict						,					A						:				Optional[Any]						,					A						:				str       ):
                    _UpperCAmelCase     :  List[Any]							      =    model_class(A       )
                    model.to(A       )
                    model.eval()

                    with torch.no_grad():
                           _UpperCAmelCase     :  Any							      =    model(**self._prepare_for_class(A						,					A       )       )

                    _UpperCAmelCase     :  List[Any]							      =    outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

                    _UpperCAmelCase     :  List[str]							      =    self.model_tester.num_stages
                    self.assertEqual(len(A       )						,					expected_num_stages + 1       )

                    # ConvNext's feature maps are of shape (batch_size, num_channels, height, width)
                    self.assertListEqual(
                        list(hidden_states[0].shape[-2:]       )						,					[self.model_tester.image_size // 4, self.model_tester.image_size // 4]						,					)

             _UpperCAmelCase      ,  _UpperCAmelCase     :  str							      =    self.model_tester.prepare_config_and_inputs_for_common()

             for model_class in self.all_model_classes:
                    _UpperCAmelCase     :  List[str]							      =    True
                    check_hidden_states_output(A						,					A						,					A       )

                    # check that output_hidden_states also work using config
                    del inputs_dict["output_hidden_states"]
                    _UpperCAmelCase     :  int							      =    True

                    check_hidden_states_output(A						,					A						,					A       )




      def      _A	(       self						:				Dict       ):
             _UpperCAmelCase     :  Optional[Any]							      =    self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_for_image_classification(*A       )





      @slow
      def      _A	(       self						:				str       ):
             for model_name in CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                    _UpperCAmelCase     :  str							      =    ConvNextModel.from_pretrained(A       )
                    self.assertIsNotNone(A       )

def 	UpperCamelCase_							(					)    ->    Union[str, Any]:


       """simple docstring"""







       _UpperCAmelCase     :  List[str]							      =    Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"    )
       return image

@require_torch
@require_vision
class 	lowerCamelCase_	(unittest.TestCase    ):
      '''simple docstring'''

      @cached_property
      def      _A	(       self						:				Optional[Any]       ):
             return AutoImageProcessor.from_pretrained("facebook/convnext-tiny-224"       ) if is_vision_available() else None





      @slow
      def      _A	(       self						:				int       ):
             _UpperCAmelCase     :  int							      =    ConvNextForImageClassification.from_pretrained("facebook/convnext-tiny-224"       ).to(A       )

             _UpperCAmelCase     :  List[str]							      =    self.default_image_processor
             _UpperCAmelCase     :  Tuple							      =    prepare_img()
             _UpperCAmelCase     :  List[Any]							      =    image_processor(images=A						,					return_tensors="pt"       ).to(A       )

             # forward pass
             with torch.no_grad():
                    _UpperCAmelCase     :  List[str]							      =    model(**A       )

             # verify the logits
             _UpperCAmelCase     :  Union[str, Any]							      =    torch.Size((1, 1000)       )
             self.assertEqual(outputs.logits.shape						,					A       )

             _UpperCAmelCase     :  Any							      =    torch.tensor([-0.0_260, -0.4_739, 0.1_911]       ).to(A       )

             self.assertTrue(torch.allclose(outputs.logits[0, :3]						,					A						,					atol=1E-4       )       )

@require_torch
class 	lowerCamelCase_	(unittest.TestCase							, snake_case__    ):
      '''simple docstring'''

      __UpperCamelCase:  Optional[Any]						=						(ConvNextBackbone,) if is_torch_available() else ()
      __UpperCamelCase:  int						=						ConvNextConfig

      __UpperCamelCase:  Any						=						False




      def      _A	(       self						:				Optional[int]       ):
             _UpperCAmelCase     :  Optional[Any]							      =    ConvNextModelTester(self       )


'''simple docstring'''




def 	UpperCamelCase_							(					_UpperCAmelCase  :      int			,	_UpperCAmelCase  :      int    )    ->    int:


       """simple docstring"""







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

def 	UpperCamelCase_							(					_UpperCAmelCase  :      int    )    ->    int:


       """simple docstring"""







       return binomial_coefficient(2 * node_count			,	_UpperCAmelCase    ) // (node_count + 1)

def 	UpperCamelCase_							(					_UpperCAmelCase  :      int    )    ->    int:


       """simple docstring"""







       if n < 0:
              raise ValueError("factorial() not defined for negative values"    )
       _UpperCAmelCase     :  List[str]							      =    1
       for i in range(1			,	n + 1    ):
              result *= i
       return result

def 	UpperCamelCase_							(					_UpperCAmelCase  :      int    )    ->    int:


       """simple docstring"""







       return catalan_number(_UpperCAmelCase    ) * factorial(_UpperCAmelCase    )


if __name__ == "__main__":
  __SCREAMING_SNAKE_CASE       :     Dict     =  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.'
  )

