



'''simple docstring'''

import inspect
import tempfile
from collections import OrderedDict, UserDict
from collections.abc import MutableMapping
from contextlib import ExitStack, contextmanager
from dataclasses import fields
from enum import Enum
from typing import Any, ContextManager, List, Tuple

import numpy as np

from .import_utils import is_flax_available, is_tf_available, is_torch_available, is_torch_fx_proxy


if is_flax_available():
							import jax.numpy as jnp

class 	__magic_name__						(    __lowerCamelCase   ):







							def __get__(							self					:       int	,_UpperCAmelCase					:       str	,_UpperCAmelCase					:       str=None		):
									# See docs.python.org/3/howto/descriptor.html#properties
									if obj is None:
											return self
									if self.fget is None:
											raise AttributeError('unreadable attribute'		)
									_a     :      Optional[Any]        =							'''__cached_''' + self.fget.__name__
									_a     :      List[str]        =							getattr(_UpperCAmelCase	,_UpperCAmelCase	,_UpperCAmelCase		)
									if cached is None:
											_a     :      Dict        =							self.fget(_UpperCAmelCase		)
											setattr(_UpperCAmelCase	,_UpperCAmelCase	,_UpperCAmelCase		)
									return cached



def      __lowerCamelCase     (      lowerCAmelCase_  )			->      Dict:
		_a     :      Optional[int]        =							val.lower()
		if val in {"y", "yes", "t", "true", "on", "1"}:
				return 1
		if val in {"n", "no", "f", "false", "off", "0"}:
				return 0
		raise ValueError(f"""invalid truth value {val!r}"""  )



def      __lowerCamelCase     (      lowerCAmelCase_  )			->      int:
		if is_torch_fx_proxy(__UpperCAmelCase  ):
				return True
		if is_torch_available():
				import torch

				if isinstance(__UpperCAmelCase						,			torch.Tensor  ):
						return True
		if is_tf_available():
				import tensorflow as tf

				if isinstance(__UpperCAmelCase						,			tf.Tensor  ):
						return True

		if is_flax_available():
				import jax.numpy as jnp
				from jax.core import Tracer

				if isinstance(__UpperCAmelCase						,			(jnp.ndarray, Tracer)  ):
						return True

		return isinstance(__UpperCAmelCase						,			np.ndarray  )



def      __lowerCamelCase     (      lowerCAmelCase_  )			->      List[str]:
		return isinstance(__UpperCAmelCase						,			np.ndarray  )



def      __lowerCamelCase     (      lowerCAmelCase_  )			->      str:
		return _is_numpy(__UpperCAmelCase  )



def      __lowerCamelCase     (      lowerCAmelCase_  )			->      Optional[Any]:
		import torch

		return isinstance(__UpperCAmelCase						,			torch.Tensor  )



def      __lowerCamelCase     (      lowerCAmelCase_  )			->      Tuple:
		return False if not is_torch_available() else _is_torch(__UpperCAmelCase  )



def      __lowerCamelCase     (      lowerCAmelCase_  )			->      List[Any]:
		import torch

		return isinstance(__UpperCAmelCase						,			torch.device  )



def      __lowerCamelCase     (      lowerCAmelCase_  )			->      Optional[int]:
		return False if not is_torch_available() else _is_torch_device(__UpperCAmelCase  )



def      __lowerCamelCase     (      lowerCAmelCase_  )			->      str:
		import torch

		if isinstance(__UpperCAmelCase						,			__UpperCAmelCase  ):
				if hasattr(__UpperCAmelCase						,			__UpperCAmelCase  ):
						_a     :      Union[str, Any]        =							getattr(__UpperCAmelCase						,			__UpperCAmelCase  )
				else:
						return False
		return isinstance(__UpperCAmelCase						,			torch.dtype  )



def      __lowerCamelCase     (      lowerCAmelCase_  )			->      Optional[Any]:
		return False if not is_torch_available() else _is_torch_dtype(__UpperCAmelCase  )



def      __lowerCamelCase     (      lowerCAmelCase_  )			->      List[str]:
		import tensorflow as tf

		return isinstance(__UpperCAmelCase						,			tf.Tensor  )



def      __lowerCamelCase     (      lowerCAmelCase_  )			->      Tuple:
		return False if not is_tf_available() else _is_tensorflow(__UpperCAmelCase  )



def      __lowerCamelCase     (      lowerCAmelCase_  )			->      Any:
		import tensorflow as tf

		# the `is_symbolic_tensor` predicate is only available starting with TF 2.14
		if hasattr(__UpperCAmelCase						,			'is_symbolic_tensor'  ):
				return tf.is_symbolic_tensor(__UpperCAmelCase  )
		return type(__UpperCAmelCase  ) == tf.Tensor



def      __lowerCamelCase     (      lowerCAmelCase_  )			->      int:
		return False if not is_tf_available() else _is_tf_symbolic_tensor(__UpperCAmelCase  )



def      __lowerCamelCase     (      lowerCAmelCase_  )			->      Optional[int]:
		import jax.numpy as jnp  # noqa: F811

		return isinstance(__UpperCAmelCase						,			jnp.ndarray  )



def      __lowerCamelCase     (      lowerCAmelCase_  )			->      Dict:
		return False if not is_flax_available() else _is_jax(__UpperCAmelCase  )



def      __lowerCamelCase     (      lowerCAmelCase_  )			->      List[Any]:
		if isinstance(__UpperCAmelCase						,			(dict, UserDict)  ):
				return {k: to_py_obj(__UpperCAmelCase  ) for k, v in obj.items()}
		elif isinstance(__UpperCAmelCase						,			(list, tuple)  ):
				return [to_py_obj(__UpperCAmelCase  ) for o in obj]
		elif is_tf_tensor(__UpperCAmelCase  ):
				return obj.numpy().tolist()
		elif is_torch_tensor(__UpperCAmelCase  ):
				return obj.detach().cpu().tolist()
		elif is_jax_tensor(__UpperCAmelCase  ):
				return np.asarray(__UpperCAmelCase  ).tolist()
		elif isinstance(__UpperCAmelCase						,			(np.ndarray, np.number)  ):  # tolist also works on 0d np arrays
				return obj.tolist()
		else:
				return obj



def      __lowerCamelCase     (      lowerCAmelCase_  )			->      Tuple:
		if isinstance(__UpperCAmelCase						,			(dict, UserDict)  ):
				return {k: to_numpy(__UpperCAmelCase  ) for k, v in obj.items()}
		elif isinstance(__UpperCAmelCase						,			(list, tuple)  ):
				return np.array(__UpperCAmelCase  )
		elif is_tf_tensor(__UpperCAmelCase  ):
				return obj.numpy()
		elif is_torch_tensor(__UpperCAmelCase  ):
				return obj.detach().cpu().numpy()
		elif is_jax_tensor(__UpperCAmelCase  ):
				return np.asarray(__UpperCAmelCase  )
		else:
				return obj

class 	__magic_name__						(    __lowerCamelCase   ):







							def 							__lowercase			(							self					:       Optional[int]		):
									_a     :      Tuple        =							fields(self		)

									# Safety and consistency checks
									if not len(_UpperCAmelCase		):
											raise ValueError(F"""{self.__class__.__name__} has no fields."""		)
									if not all(field.default is None for field in class_fields[1:]		):
											raise ValueError(F"""{self.__class__.__name__} should not have more than one required field."""		)

									_a     :      List[Any]        =							getattr(self	,class_fields[0].name		)
									_a     :      Dict        =							all(getattr(self	,field.name		) is None for field in class_fields[1:]		)

									if other_fields_are_none and not is_tensor(_UpperCAmelCase		):
											if isinstance(_UpperCAmelCase	,_UpperCAmelCase		):
													_a     :      List[str]        =							first_field.items()
													_a     :      Optional[int]        =							True
											else:
													try:
															_a     :      List[str]        =							iter(_UpperCAmelCase		)
															_a     :      int        =							True
													except TypeError:
															_a     :      Union[str, Any]        =							False

            # if we provided an iterator as first field and the iterator is a (key, value) iterator
            # set the associated fields
											if first_field_iterator:
													for idx, element in enumerate(_UpperCAmelCase		):
															if (
															    not isinstance(_UpperCAmelCase	,(list, tuple)		)
															    or not len(_UpperCAmelCase		) == 2
															    or not isinstance(element[0]	,_UpperCAmelCase		)
															):
																	if idx == 0:
																			# If we do not have an iterator of key/values, set it as attribute
																			_a     :      Tuple        =							first_field
																	else:
																			# If we have a mixed iterator, raise an error
																			raise ValueError(
																			    F"""Cannot set key/value for {element}. It needs to be a tuple (key, value)."""		)
																	break
															setattr(self	,element[0]	,element[1]		)
															if element[1] is not None:
																	_a     :      str        =							element[1]
											elif first_field is not None:
													_a     :      Tuple        =							first_field
									else:
											for field in class_fields:
													_a     :      List[str]        =							getattr(self	,field.name		)
													if v is not None:
															_a     :      List[str]        =							v







							def __delitem__(							self					:       List[str]	,*_UpperCAmelCase					:       Optional[int]	,**_UpperCAmelCase					:       int		):
									raise Exception(F"""You cannot use ``__delitem__`` on a {self.__class__.__name__} instance."""		)







							def 							__lowercase			(							self					:       Optional[Any]	,*_UpperCAmelCase					:       Union[str, Any]	,**_UpperCAmelCase					:       str		):
									raise Exception(F"""You cannot use ``setdefault`` on a {self.__class__.__name__} instance."""		)







							def 							__lowercase			(							self					:       Tuple	,*_UpperCAmelCase					:       Dict	,**_UpperCAmelCase					:       Union[str, Any]		):
									raise Exception(F"""You cannot use ``pop`` on a {self.__class__.__name__} instance."""		)







							def 							__lowercase			(							self					:       Tuple	,*_UpperCAmelCase					:       List[str]	,**_UpperCAmelCase					:       List[str]		):
									raise Exception(F"""You cannot use ``update`` on a {self.__class__.__name__} instance."""		)







							def __getitem__(							self					:       Union[str, Any]	,_UpperCAmelCase					:       List[Any]		):
									if isinstance(_UpperCAmelCase	,_UpperCAmelCase		):
											_a     :      Tuple        =							dict(self.items()		)
											return inner_dict[k]
									else:
											return self.to_tuple()[k]







							def __setattr__(							self					:       Optional[Any]	,_UpperCAmelCase					:       Optional[Any]	,_UpperCAmelCase					:       List[str]		):
									if name in self.keys() and value is not None:
											# Don't call self.__setitem__ to avoid recursion errors
											super().__setitem__(_UpperCAmelCase	,_UpperCAmelCase		)
									super().__setattr__(_UpperCAmelCase	,_UpperCAmelCase		)







							def __setitem__(							self					:       List[Any]	,_UpperCAmelCase					:       Optional[int]	,_UpperCAmelCase					:       str		):
									super().__setitem__(_UpperCAmelCase	,_UpperCAmelCase		)
									# Don't call self.__setattr__ to avoid recursion errors
									super().__setattr__(_UpperCAmelCase	,_UpperCAmelCase		)







							def 							__lowercase			(							self					:       int		):
									return tuple(self[k] for k in self.keys()		)

class 	__magic_name__						(    __lowerCamelCase			,						__lowerCamelCase   ):







							@classmethod
							def 							__lowercase			(							cls					:       Any	,_UpperCAmelCase					:       Dict		):
									raise ValueError(
									    F"""{value} is not a valid {cls.__name__}, please select one of {list(cls._valueamember_map_.keys()		)}"""		)

class 	__magic_name__						(    __lowerCamelCase   ):
							lowerCAmelCase       :    Any   				=					"longest"
							lowerCAmelCase       :    Optional[int]   				=					"max_length"
							lowerCAmelCase       :    Any   				=					"do_not_pad"

class 	__magic_name__						(    __lowerCamelCase   ):
							lowerCAmelCase       :    str   				=					"pt"
							lowerCAmelCase       :    str   				=					"tf"
							lowerCAmelCase       :    List[Any]   				=					"np"
							lowerCAmelCase       :    Any   				=					"jax"

class 	__magic_name__						:







							def __init__(							self					:       Optional[Any]	,_UpperCAmelCase					:       Union[str, Any]		):
									_a     :      List[Any]        =							context_managers
									_a     :      List[Any]        =							ExitStack()







							def __enter__(							self					:       Optional[int]		):
									for context_manager in self.context_managers:
											self.stack.enter_context(_UpperCAmelCase		)







							def __exit__(							self					:       Tuple	,*_UpperCAmelCase					:       Optional[Any]	,**_UpperCAmelCase					:       Any		):
									self.stack.__exit__(*_UpperCAmelCase	,**_UpperCAmelCase		)



def      __lowerCamelCase     (      lowerCAmelCase_  )			->      Any:
		_a     :      int        =							infer_framework(__UpperCAmelCase  )
		if framework == "tf":
				_a     :      List[Any]        =							inspect.signature(model_class.call  )  # TensorFlow models
		elif framework == "pt":
				_a     :      List[str]        =							inspect.signature(model_class.forward  )  # PyTorch models
		else:
				_a     :      Union[str, Any]        =							inspect.signature(model_class.__call__  )  # Flax models

		for p in signature.parameters:
				if p == "return_loss" and signature.parameters[p].default is True:
						return True

		return False



def      __lowerCamelCase     (      lowerCAmelCase_  )			->      int:
		_a     :      Optional[Any]        =							model_class.__name__
		_a     :      List[str]        =							infer_framework(__UpperCAmelCase  )
		if framework == "tf":
				_a     :      List[str]        =							inspect.signature(model_class.call  )  # TensorFlow models
		elif framework == "pt":
				_a     :      Any        =							inspect.signature(model_class.forward  )  # PyTorch models
		else:
				_a     :      List[Any]        =							inspect.signature(model_class.__call__  )  # Flax models

		if "QuestionAnswering" in model_name:
				return [p for p in signature.parameters if "label" in p or p in ("start_positions", "end_positions")]
		else:
				return [p for p in signature.parameters if "label" in p]



def      __lowerCamelCase     (      lowerCAmelCase_						,			lowerCAmelCase_ = ""						,			lowerCAmelCase_ = "."  )			->      int:

		def _flatten_dict(lowerCAmelCase_						,			lowerCAmelCase_=""						,			lowerCAmelCase_="."  ):
				for k, v in d.items():
						_a     :      List[Any]        =							str(__UpperCAmelCase  ) + delimiter + str(__UpperCAmelCase  ) if parent_key else k
						if v and isinstance(__UpperCAmelCase						,			__UpperCAmelCase  ):
								yield from flatten_dict(__UpperCAmelCase						,			__UpperCAmelCase						,			delimiter=__UpperCAmelCase  ).items()
						else:
								yield key, v

		return dict(_flatten_dict(__UpperCAmelCase						,			__UpperCAmelCase						,			__UpperCAmelCase  )  )



@contextmanager
def      __lowerCamelCase     (      lowerCAmelCase_						,			lowerCAmelCase_ = False  )			->      Dict:
		if use_temp_dir:
				with tempfile.TemporaryDirectory() as tmp_dir:
						yield tmp_dir
		else:
				yield working_dir



def      __lowerCamelCase     (      lowerCAmelCase_						,			lowerCAmelCase_=None  )			->      Optional[int]:
		if is_numpy_array(__UpperCAmelCase  ):
				return np.transpose(__UpperCAmelCase						,			axes=__UpperCAmelCase  )
		elif is_torch_tensor(__UpperCAmelCase  ):
				return array.T if axes is None else array.permute(*__UpperCAmelCase  )
		elif is_tf_tensor(__UpperCAmelCase  ):
				import tensorflow as tf

				return tf.transpose(__UpperCAmelCase						,			perm=__UpperCAmelCase  )
		elif is_jax_tensor(__UpperCAmelCase  ):
				return jnp.transpose(__UpperCAmelCase						,			axes=__UpperCAmelCase  )
		else:
				raise ValueError(f"""Type not supported for transpose: {type(__UpperCAmelCase  )}."""  )



def      __lowerCamelCase     (      lowerCAmelCase_						,			lowerCAmelCase_  )			->      int:
		if is_numpy_array(__UpperCAmelCase  ):
				return np.reshape(__UpperCAmelCase						,			__UpperCAmelCase  )
		elif is_torch_tensor(__UpperCAmelCase  ):
				return array.reshape(*__UpperCAmelCase  )
		elif is_tf_tensor(__UpperCAmelCase  ):
				import tensorflow as tf

				return tf.reshape(__UpperCAmelCase						,			__UpperCAmelCase  )
		elif is_jax_tensor(__UpperCAmelCase  ):
				return jnp.reshape(__UpperCAmelCase						,			__UpperCAmelCase  )
		else:
				raise ValueError(f"""Type not supported for reshape: {type(__UpperCAmelCase  )}."""  )



def      __lowerCamelCase     (      lowerCAmelCase_						,			lowerCAmelCase_=None  )			->      int:
		if is_numpy_array(__UpperCAmelCase  ):
				return np.squeeze(__UpperCAmelCase						,			axis=__UpperCAmelCase  )
		elif is_torch_tensor(__UpperCAmelCase  ):
				return array.squeeze() if axis is None else array.squeeze(dim=__UpperCAmelCase  )
		elif is_tf_tensor(__UpperCAmelCase  ):
				import tensorflow as tf

				return tf.squeeze(__UpperCAmelCase						,			axis=__UpperCAmelCase  )
		elif is_jax_tensor(__UpperCAmelCase  ):
				return jnp.squeeze(__UpperCAmelCase						,			axis=__UpperCAmelCase  )
		else:
				raise ValueError(f"""Type not supported for squeeze: {type(__UpperCAmelCase  )}."""  )



def      __lowerCamelCase     (      lowerCAmelCase_						,			lowerCAmelCase_  )			->      Any:
		if is_numpy_array(__UpperCAmelCase  ):
				return np.expand_dims(__UpperCAmelCase						,			__UpperCAmelCase  )
		elif is_torch_tensor(__UpperCAmelCase  ):
				return array.unsqueeze(dim=__UpperCAmelCase  )
		elif is_tf_tensor(__UpperCAmelCase  ):
				import tensorflow as tf

				return tf.expand_dims(__UpperCAmelCase						,			axis=__UpperCAmelCase  )
		elif is_jax_tensor(__UpperCAmelCase  ):
				return jnp.expand_dims(__UpperCAmelCase						,			axis=__UpperCAmelCase  )
		else:
				raise ValueError(f"""Type not supported for expand_dims: {type(__UpperCAmelCase  )}."""  )



def      __lowerCamelCase     (      lowerCAmelCase_  )			->      List[str]:
		if is_numpy_array(__UpperCAmelCase  ):
				return np.size(__UpperCAmelCase  )
		elif is_torch_tensor(__UpperCAmelCase  ):
				return array.numel()
		elif is_tf_tensor(__UpperCAmelCase  ):
				import tensorflow as tf

				return tf.size(__UpperCAmelCase  )
		elif is_jax_tensor(__UpperCAmelCase  ):
				return array.size
		else:
				raise ValueError(f"""Type not supported for expand_dims: {type(__UpperCAmelCase  )}."""  )



def      __lowerCamelCase     (      lowerCAmelCase_						,			lowerCAmelCase_  )			->      Tuple:
		for key, value in auto_map.items():
				if isinstance(__UpperCAmelCase						,			(tuple, list)  ):
						_a     :      Optional[Any]        =							[f"""{repo_id}--{v}""" if (v is not None and '''--''' not in v) else v for v in value]
				elif value is not None and "--" not in value:
						_a     :      Tuple        =							f"""{repo_id}--{value}"""

		return auto_map



def      __lowerCamelCase     (      lowerCAmelCase_  )			->      Union[str, Any]:
		for base_class in inspect.getmro(__UpperCAmelCase  ):
				_a     :      Tuple        =							base_class.__module__
				_a     :      List[Any]        =							base_class.__name__
				if module.startswith('tensorflow'  ) or module.startswith('keras'  ) or name == "TFPreTrainedModel":
						return "tf"
				elif module.startswith('torch'  ) or name == "PreTrainedModel":
						return "pt"
				elif module.startswith('flax'  ) or module.startswith('jax'  ) or name == "FlaxPreTrainedModel":
						return "flax"
		else:
				raise TypeError(f"""Could not infer framework from class {model_class}."""  )











from math import factorial




def 		lowerCAmelCase_    (  __UpperCAmelCase:			int		,   __UpperCAmelCase:			int      )      ->	int:

    # If either of the conditions are true, the function is being asked
    # to calculate a factorial of a negative number, which is not possible
    if n < k or k < 0:
        raise ValueError('''Please enter positive integers for n and k where n >= k'''      )
    return factorial(__UpperCAmelCase      ) // (factorial(__UpperCAmelCase      ) * factorial(n - k      ))


if __name__ == "__main__":
  print(
      'The number of five-card hands possible from a standard',
      F'''fifty-two card deck is: {combinations(52, 5)}\n''',
  )

  print(
      'If a class of 40 students must be arranged into groups of',
      F'''4 for group projects, there are {combinations(40, 4)} ways''',
      'to arrange them.\n',
  )

  print(
      'If 10 teams are competing in a Formula One race, there',
      F'''are {combinations(10, 3)} ways that first, second and''',
      'third place can be awarded.',
  )

