
from __future__ import annotations

import os
import tempfile
import unittest

from transformers import ConvBertConfig, is_tf_available
from transformers.testing_utils import require_tf, slow

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
     import tensorflow as tf

     from transformers import (
         TFConvBertForMaskedLM,
         TFConvBertForMultipleChoice,
         TFConvBertForQuestionAnswering,
         TFConvBertForSequenceClassification,
         TFConvBertForTokenClassification,
         TFConvBertModel,
     )



class       _snake_case   :


 def __init__(					self					,  SCREAMING_SNAKE_CASE_					,  SCREAMING_SNAKE_CASE_=13					,  SCREAMING_SNAKE_CASE_=7					,  SCREAMING_SNAKE_CASE_=True					,  SCREAMING_SNAKE_CASE_=True					,  SCREAMING_SNAKE_CASE_=True					,  SCREAMING_SNAKE_CASE_=True					,  SCREAMING_SNAKE_CASE_=99					,  SCREAMING_SNAKE_CASE_=32					,  SCREAMING_SNAKE_CASE_=2					,  SCREAMING_SNAKE_CASE_=4					,  SCREAMING_SNAKE_CASE_=37					,  SCREAMING_SNAKE_CASE_="gelu"					,  SCREAMING_SNAKE_CASE_=0.1					,  SCREAMING_SNAKE_CASE_=0.1					,  SCREAMING_SNAKE_CASE_=5_12					,  SCREAMING_SNAKE_CASE_=16					,  SCREAMING_SNAKE_CASE_=2					,  SCREAMING_SNAKE_CASE_=0.0_2					,  SCREAMING_SNAKE_CASE_=3					,  SCREAMING_SNAKE_CASE_=4					,  SCREAMING_SNAKE_CASE_=None					,  ):


   '''simple docstring'''




   lowercase__  :   Optional[int]    		=      parent
   lowercase__  :   Union[str, Any]    		=      13
   lowercase__  :   Union[str, Any]    		=      7
   lowercase__  :   List[str]    		=      True
   lowercase__  :   Union[str, Any]    		=      True
   lowercase__  :   Optional[int]    		=      True
   lowercase__  :   List[str]    		=      True
   lowercase__  :   List[Any]    		=      99
   lowercase__  :   Union[str, Any]    		=      3_84
   lowercase__  :   int    		=      2
   lowercase__  :   Dict    		=      4
   lowercase__  :   int    		=      37
   lowercase__  :   Optional[Any]    		=      """gelu"""
   lowercase__  :   Optional[Any]    		=      0.1
   lowercase__  :   Optional[int]    		=      0.1
   lowercase__  :   Dict    		=      5_12
   lowercase__  :   str    		=      16
   lowercase__  :   Any    		=      2
   lowercase__  :   Optional[int]    		=      0.0_2
   lowercase__  :   List[str]    		=      3
   lowercase__  :   List[Any]    		=      4
   lowercase__  :   List[str]    		=      1_28
   lowercase__  :   Optional[int]    		=      2
   lowercase__  :   Tuple    		=      9
   lowercase__  :   List[Any]    		=      1
   lowercase__  :   Tuple    		=      None


 def      lowercase__     (					self):


   '''simple docstring'''




   lowercase__  :   List[str]    		=      ids_tensor([self.batch_size, self.seq_length]					,  self.vocab_size)

   lowercase__  :   Union[str, Any]    		=      None
   if self.use_input_mask:
     lowercase__  :   List[str]    		=      random_attention_mask([self.batch_size, self.seq_length])

   lowercase__  :   List[Any]    		=      None
   if self.use_token_type_ids:
     lowercase__  :   Dict    		=      ids_tensor([self.batch_size, self.seq_length]					,  self.type_vocab_size)

   lowercase__  :   Union[str, Any]    		=      None
   lowercase__  :   List[str]    		=      None
   lowercase__  :   Union[str, Any]    		=      None
   if self.use_labels:
     lowercase__  :   Dict    		=      ids_tensor([self.batch_size]					,  self.type_sequence_label_size)
     lowercase__  :   int    		=      ids_tensor([self.batch_size, self.seq_length]					,  self.num_labels)
     lowercase__  :   Union[str, Any]    		=      ids_tensor([self.batch_size]					,  self.num_choices)

   lowercase__  :   Any    		=      ConvBertConfig(
       vocab_size=self.vocab_size					,  hidden_size=self.hidden_size					,  num_hidden_layers=self.num_hidden_layers					,  num_attention_heads=self.num_attention_heads					,  intermediate_size=self.intermediate_size					,  hidden_act=self.hidden_act					,  hidden_dropout_prob=self.hidden_dropout_prob					,  attention_probs_dropout_prob=self.attention_probs_dropout_prob					,  max_position_embeddings=self.max_position_embeddings					,  type_vocab_size=self.type_vocab_size					,  initializer_range=self.initializer_range					,  return_dict=SCREAMING_SNAKE_CASE_					,  )

   return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels


 def      lowercase__     (					self					,  SCREAMING_SNAKE_CASE_					,  SCREAMING_SNAKE_CASE_					,  SCREAMING_SNAKE_CASE_					,  SCREAMING_SNAKE_CASE_					,  SCREAMING_SNAKE_CASE_					,  SCREAMING_SNAKE_CASE_					,  SCREAMING_SNAKE_CASE_):


   '''simple docstring'''




   lowercase__  :   Dict    		=      TFConvBertModel(config=SCREAMING_SNAKE_CASE_)
   lowercase__  :   List[str]    		=      {"""input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids}

   lowercase__  :   Any    		=      [input_ids, input_mask]
   lowercase__  :   str    		=      model(SCREAMING_SNAKE_CASE_)

   lowercase__  :   Dict    		=      model(SCREAMING_SNAKE_CASE_)

   self.parent.assertEqual(result.last_hidden_state.shape					,  (self.batch_size, self.seq_length, self.hidden_size))


 def      lowercase__     (					self					,  SCREAMING_SNAKE_CASE_					,  SCREAMING_SNAKE_CASE_					,  SCREAMING_SNAKE_CASE_					,  SCREAMING_SNAKE_CASE_					,  SCREAMING_SNAKE_CASE_					,  SCREAMING_SNAKE_CASE_					,  SCREAMING_SNAKE_CASE_):


   '''simple docstring'''




   lowercase__  :   Dict    		=      TFConvBertForMaskedLM(config=SCREAMING_SNAKE_CASE_)
   lowercase__  :   Optional[Any]    		=      {
       """input_ids""": input_ids,
       """attention_mask""": input_mask,
       """token_type_ids""": token_type_ids,
   }
   lowercase__  :   Dict    		=      model(SCREAMING_SNAKE_CASE_)
   self.parent.assertEqual(result.logits.shape					,  (self.batch_size, self.seq_length, self.vocab_size))


 def      lowercase__     (					self					,  SCREAMING_SNAKE_CASE_					,  SCREAMING_SNAKE_CASE_					,  SCREAMING_SNAKE_CASE_					,  SCREAMING_SNAKE_CASE_					,  SCREAMING_SNAKE_CASE_					,  SCREAMING_SNAKE_CASE_					,  SCREAMING_SNAKE_CASE_):


   '''simple docstring'''




   lowercase__  :   Optional[Any]    		=      self.num_labels
   lowercase__  :   int    		=      TFConvBertForSequenceClassification(config=SCREAMING_SNAKE_CASE_)
   lowercase__  :   Optional[Any]    		=      {
       """input_ids""": input_ids,
       """attention_mask""": input_mask,
       """token_type_ids""": token_type_ids,
   }

   lowercase__  :   Any    		=      model(SCREAMING_SNAKE_CASE_)
   self.parent.assertEqual(result.logits.shape					,  (self.batch_size, self.num_labels))


 def      lowercase__     (					self					,  SCREAMING_SNAKE_CASE_					,  SCREAMING_SNAKE_CASE_					,  SCREAMING_SNAKE_CASE_					,  SCREAMING_SNAKE_CASE_					,  SCREAMING_SNAKE_CASE_					,  SCREAMING_SNAKE_CASE_					,  SCREAMING_SNAKE_CASE_):


   '''simple docstring'''




   lowercase__  :   Optional[Any]    		=      self.num_choices
   lowercase__  :   Optional[Any]    		=      TFConvBertForMultipleChoice(config=SCREAMING_SNAKE_CASE_)
   lowercase__  :   List[str]    		=      tf.tile(tf.expand_dims(SCREAMING_SNAKE_CASE_					,  1)					,  (1, self.num_choices, 1))
   lowercase__  :   Tuple    		=      tf.tile(tf.expand_dims(SCREAMING_SNAKE_CASE_					,  1)					,  (1, self.num_choices, 1))
   lowercase__  :   str    		=      tf.tile(tf.expand_dims(SCREAMING_SNAKE_CASE_					,  1)					,  (1, self.num_choices, 1))
   lowercase__  :   int    		=      {
       """input_ids""": multiple_choice_inputs_ids,
       """attention_mask""": multiple_choice_input_mask,
       """token_type_ids""": multiple_choice_token_type_ids,
   }
   lowercase__  :   str    		=      model(SCREAMING_SNAKE_CASE_)
   self.parent.assertEqual(result.logits.shape					,  (self.batch_size, self.num_choices))


 def      lowercase__     (					self					,  SCREAMING_SNAKE_CASE_					,  SCREAMING_SNAKE_CASE_					,  SCREAMING_SNAKE_CASE_					,  SCREAMING_SNAKE_CASE_					,  SCREAMING_SNAKE_CASE_					,  SCREAMING_SNAKE_CASE_					,  SCREAMING_SNAKE_CASE_):


   '''simple docstring'''




   lowercase__  :   Any    		=      self.num_labels
   lowercase__  :   int    		=      TFConvBertForTokenClassification(config=SCREAMING_SNAKE_CASE_)
   lowercase__  :   Optional[Any]    		=      {
       """input_ids""": input_ids,
       """attention_mask""": input_mask,
       """token_type_ids""": token_type_ids,
   }
   lowercase__  :   Tuple    		=      model(SCREAMING_SNAKE_CASE_)
   self.parent.assertEqual(result.logits.shape					,  (self.batch_size, self.seq_length, self.num_labels))


 def      lowercase__     (					self					,  SCREAMING_SNAKE_CASE_					,  SCREAMING_SNAKE_CASE_					,  SCREAMING_SNAKE_CASE_					,  SCREAMING_SNAKE_CASE_					,  SCREAMING_SNAKE_CASE_					,  SCREAMING_SNAKE_CASE_					,  SCREAMING_SNAKE_CASE_):


   '''simple docstring'''




   lowercase__  :   Any    		=      TFConvBertForQuestionAnswering(config=SCREAMING_SNAKE_CASE_)
   lowercase__  :   List[Any]    		=      {
       """input_ids""": input_ids,
       """attention_mask""": input_mask,
       """token_type_ids""": token_type_ids,
   }

   lowercase__  :   int    		=      model(SCREAMING_SNAKE_CASE_)
   self.parent.assertEqual(result.start_logits.shape					,  (self.batch_size, self.seq_length))
   self.parent.assertEqual(result.end_logits.shape					,  (self.batch_size, self.seq_length))



 def      lowercase__     (					self):


   '''simple docstring'''




   lowercase__  :   Any    		=      self.prepare_config_and_inputs()
   (
       (
       lowercase__
   )		,    (
       lowercase__
   )		,    (
       lowercase__
   )		,    (
       lowercase__
   )		,    (
       lowercase__
   )		,    (
       lowercase__
   )		,    (
       lowercase__
   )		,    
   )  :   int    		=      config_and_inputs
   lowercase__  :   int    		=      {"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": input_mask}
   return config, inputs_dict



@require_tf
class       _snake_case   (	UpperCAmelCase_  ,						UpperCAmelCase_  ,						unittest.TestCase							):
 __lowerCAmelCase  :     Optional[int]        =			(
     (
         TFConvBertModel,
         TFConvBertForMaskedLM,
         TFConvBertForQuestionAnswering,
         TFConvBertForSequenceClassification,
         TFConvBertForTokenClassification,
         TFConvBertForMultipleChoice,
     )
     if is_tf_available()
     else ()
 )
 __lowerCAmelCase  :     Dict        =			(
     {
         'feature-extraction': TFConvBertModel,
         'fill-mask': TFConvBertForMaskedLM,
         'question-answering': TFConvBertForQuestionAnswering,
         'text-classification': TFConvBertForSequenceClassification,
         'token-classification': TFConvBertForTokenClassification,
         'zero-shot': TFConvBertForSequenceClassification,
     }
     if is_tf_available()
     else {}
 )
 __lowerCAmelCase  :     int        =			False
 __lowerCAmelCase  :     Optional[int]        =			False
 __lowerCAmelCase  :     int        =			False


 def      lowercase__     (					self):


   '''simple docstring'''




   lowercase__  :   Dict    		=      TFConvBertModelTester(self)
   lowercase__  :   Optional[int]    		=      ConfigTester(self					,  config_class=SCREAMING_SNAKE_CASE_					,  hidden_size=37)


 def      lowercase__     (					self):


   '''simple docstring'''




   self.config_tester.run_common_tests()


 def      lowercase__     (					self):


   '''simple docstring'''




   lowercase__  :   Optional[int]    		=      self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE_)


 def      lowercase__     (					self):


   '''simple docstring'''




   lowercase__  :   List[str]    		=      self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_for_masked_lm(*SCREAMING_SNAKE_CASE_)


 def      lowercase__     (					self):


   '''simple docstring'''




   lowercase__  :   List[Any]    		=      self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_for_multiple_choice(*SCREAMING_SNAKE_CASE_)


 def      lowercase__     (					self):


   '''simple docstring'''




   lowercase__  :   List[str]    		=      self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_for_question_answering(*SCREAMING_SNAKE_CASE_)


 def      lowercase__     (					self):


   '''simple docstring'''




   lowercase__  :   Dict    		=      self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_for_sequence_classification(*SCREAMING_SNAKE_CASE_)


 def      lowercase__     (					self):


   '''simple docstring'''




   lowercase__  :   str    		=      self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_for_token_classification(*SCREAMING_SNAKE_CASE_)


 @slow
 def      lowercase__     (					self):


   '''simple docstring'''




   lowercase__		,    lowercase__  :   Dict    		=      self.model_tester.prepare_config_and_inputs_for_common()
   lowercase__  :   int    		=      True
   lowercase__  :   List[Any]    		=      True

   if hasattr(SCREAMING_SNAKE_CASE_					,  """use_cache"""):
     lowercase__  :   Any    		=      True

   lowercase__  :   Any    		=      getattr(self.model_tester					,  """encoder_seq_length"""					,  self.model_tester.seq_length)
   lowercase__  :   List[str]    		=      getattr(self.model_tester					,  """key_length"""					,  SCREAMING_SNAKE_CASE_)

   for model_class in self.all_model_classes:
     lowercase__  :   int    		=      self._prepare_for_class(SCREAMING_SNAKE_CASE_					,  SCREAMING_SNAKE_CASE_)
     lowercase__  :   Tuple    		=      model_class(SCREAMING_SNAKE_CASE_)
     lowercase__  :   Optional[Any]    		=      len(model(SCREAMING_SNAKE_CASE_))

     with tempfile.TemporaryDirectory() as tmpdirname:
       model.save_pretrained(SCREAMING_SNAKE_CASE_					,  saved_model=SCREAMING_SNAKE_CASE_)
       lowercase__  :   str    		=      os.path.join(SCREAMING_SNAKE_CASE_					,  """saved_model"""					,  """1""")
       lowercase__  :   List[Any]    		=      tf.keras.models.load_model(SCREAMING_SNAKE_CASE_)
       lowercase__  :   List[Any]    		=      model(SCREAMING_SNAKE_CASE_)

       if self.is_encoder_decoder:
         lowercase__  :   Tuple    		=      outputs["""encoder_hidden_states"""]
         lowercase__  :   List[Any]    		=      outputs["""encoder_attentions"""]
       else:
         lowercase__  :   Tuple    		=      outputs["""hidden_states"""]
         lowercase__  :   Any    		=      outputs["""attentions"""]

       self.assertEqual(len(SCREAMING_SNAKE_CASE_)					,  SCREAMING_SNAKE_CASE_)

       lowercase__  :   Optional[Any]    		=      getattr(
           self.model_tester					,  """expected_num_hidden_layers"""					,  self.model_tester.num_hidden_layers + 1)

       self.assertEqual(len(SCREAMING_SNAKE_CASE_)					,  SCREAMING_SNAKE_CASE_)
       self.assertListEqual(
           list(output_hidden_states[0].shape[-2:])					,  [self.model_tester.seq_length, self.model_tester.hidden_size]					,  )

       self.assertEqual(len(SCREAMING_SNAKE_CASE_)					,  self.model_tester.num_hidden_layers)
       self.assertListEqual(
           list(output_attentions[0].shape[-3:])					,  [self.model_tester.num_attention_heads / 2, encoder_seq_length, encoder_key_length]					,  )


 @slow
 def      lowercase__     (					self):


   '''simple docstring'''




   lowercase__  :   Tuple    		=      TFConvBertModel.from_pretrained("""YituTech/conv-bert-base""")
   self.assertIsNotNone(SCREAMING_SNAKE_CASE_)



 def      lowercase__     (					self):


   '''simple docstring'''




   lowercase__		,    lowercase__  :   Optional[int]    		=      self.model_tester.prepare_config_and_inputs_for_common()
   lowercase__  :   List[Any]    		=      True
   lowercase__  :   str    		=      getattr(self.model_tester					,  """decoder_seq_length"""					,  self.model_tester.seq_length)
   lowercase__  :   Union[str, Any]    		=      getattr(self.model_tester					,  """encoder_seq_length"""					,  self.model_tester.seq_length)
   lowercase__  :   Optional[int]    		=      getattr(self.model_tester					,  """key_length"""					,  SCREAMING_SNAKE_CASE_)
   lowercase__  :   Dict    		=      getattr(self.model_tester					,  """key_length"""					,  SCREAMING_SNAKE_CASE_)

   def check_decoder_attentions_output(SCREAMING_SNAKE_CASE_):
     lowercase__  :   int    		=      len(SCREAMING_SNAKE_CASE_)
     self.assertEqual(out_len % 2					,  0)
     lowercase__  :   List[Any]    		=      outputs.decoder_attentions
     self.assertEqual(len(SCREAMING_SNAKE_CASE_)					,  self.model_tester.num_hidden_layers)
     self.assertListEqual(
         list(decoder_attentions[0].shape[-3:])					,  [self.model_tester.num_attention_heads / 2, decoder_seq_length, decoder_key_length]					,  )

   def check_encoder_attentions_output(SCREAMING_SNAKE_CASE_):
     lowercase__  :   List[Any]    		=      [
         t.numpy() for t in (outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions)
     ]
     self.assertEqual(len(SCREAMING_SNAKE_CASE_)					,  self.model_tester.num_hidden_layers)
     self.assertListEqual(
         list(attentions[0].shape[-3:])					,  [self.model_tester.num_attention_heads / 2, encoder_seq_length, encoder_key_length]					,  )

   for model_class in self.all_model_classes:
     lowercase__  :   Optional[int]    		=      True
     lowercase__  :   Union[str, Any]    		=      False
     lowercase__  :   Optional[Any]    		=      model_class(SCREAMING_SNAKE_CASE_)
     lowercase__  :   Dict    		=      model(self._prepare_for_class(SCREAMING_SNAKE_CASE_					,  SCREAMING_SNAKE_CASE_))
     lowercase__  :   int    		=      len(SCREAMING_SNAKE_CASE_)
     self.assertEqual(config.output_hidden_states					,  SCREAMING_SNAKE_CASE_)
     check_encoder_attentions_output(SCREAMING_SNAKE_CASE_)

     if self.is_encoder_decoder:
       lowercase__  :   List[str]    		=      model_class(SCREAMING_SNAKE_CASE_)
       lowercase__  :   Tuple    		=      model(self._prepare_for_class(SCREAMING_SNAKE_CASE_					,  SCREAMING_SNAKE_CASE_))
       self.assertEqual(config.output_hidden_states					,  SCREAMING_SNAKE_CASE_)
       check_decoder_attentions_output(SCREAMING_SNAKE_CASE_)

     # Check that output attentions can also be changed via the config
     del inputs_dict["output_attentions"]
     lowercase__  :   Optional[int]    		=      True
     lowercase__  :   List[str]    		=      model_class(SCREAMING_SNAKE_CASE_)
     lowercase__  :   Any    		=      model(self._prepare_for_class(SCREAMING_SNAKE_CASE_					,  SCREAMING_SNAKE_CASE_))
     self.assertEqual(config.output_hidden_states					,  SCREAMING_SNAKE_CASE_)
     check_encoder_attentions_output(SCREAMING_SNAKE_CASE_)

     # Check attention is always last and order is fine
     lowercase__  :   str    		=      True
     lowercase__  :   List[Any]    		=      True
     lowercase__  :   Dict    		=      model_class(SCREAMING_SNAKE_CASE_)
     lowercase__  :   Any    		=      model(self._prepare_for_class(SCREAMING_SNAKE_CASE_					,  SCREAMING_SNAKE_CASE_))

     self.assertEqual(out_len + (2 if self.is_encoder_decoder else 1)					,  len(SCREAMING_SNAKE_CASE_))
     self.assertEqual(model.config.output_hidden_states					,  SCREAMING_SNAKE_CASE_)
     check_encoder_attentions_output(SCREAMING_SNAKE_CASE_)



@require_tf
class       _snake_case   (	unittest.TestCase							):


 @slow
 def      lowercase__     (					self):


   '''simple docstring'''




   lowercase__  :   Any    		=      TFConvBertModel.from_pretrained("""YituTech/conv-bert-base""")
   lowercase__  :   Optional[int]    		=      tf.constant([[0, 1, 2, 3, 4, 5]])
   lowercase__  :   Any    		=      model(SCREAMING_SNAKE_CASE_)[0]

   lowercase__  :   Union[str, Any]    		=      [1, 6, 7_68]
   self.assertEqual(output.shape					,  SCREAMING_SNAKE_CASE_)

   lowercase__  :   Tuple    		=      tf.constant(
       [
           [
               [-0.0_3_4_7_5_4_9_3, -0.4_6_8_6_0_3_4, -0.3_0_6_3_8_8_3_2],
               [0.2_2_6_3_7_2_4_8, -0.2_6_9_8_8_6_4_6, -0.7_4_2_3_4_2_4],
               [0.1_0_3_2_4_8_6_8, -0.4_5_0_1_3_5_0_8, -0.5_8_2_8_0_7_8_4],
           ]
       ])
   tf.debugging.assert_near(output[:, :3, :3]					,  SCREAMING_SNAKE_CASE_					,  atol=1E-4)








from __future__ import annotations

from collections.abc import Iterator
from typing import Any



class       _snake_case   :


 def __init__(					self					,  SCREAMING_SNAKE_CASE_):


   '''simple docstring'''




   lowercase__  :   Any    		=      data
   lowercase__  :   Node | None    		=      None



class       _snake_case   :


 def __init__(					self):


   '''simple docstring'''




   lowercase__  :   List[Any]    		=      None
   lowercase__  :   int    		=      None


 def __iter__(					self):


   '''simple docstring'''




   lowercase__  :   List[str]    		=      self.head
   while self.head:
     yield node.data
     lowercase__  :   str    		=      node.next
     if node == self.head:
       break


 def __len__(					self):


   '''simple docstring'''




   return sum(1 for _ in self)


 def __repr__(					self):


   '''simple docstring'''




   return "->".join(str(SCREAMING_SNAKE_CASE_) for item in iter(self))


 def      lowercase__     (					self					,  SCREAMING_SNAKE_CASE_):


   '''simple docstring'''




   self.insert_nth(len(self)					,  SCREAMING_SNAKE_CASE_)


 def      lowercase__     (					self					,  SCREAMING_SNAKE_CASE_):


   '''simple docstring'''




   self.insert_nth(0					,  SCREAMING_SNAKE_CASE_)


 def      lowercase__     (					self					,  SCREAMING_SNAKE_CASE_					,  SCREAMING_SNAKE_CASE_):


   '''simple docstring'''




   if index < 0 or index > len(self):
     raise IndexError("""list index out of range.""")
   lowercase__  :   Optional[int]    		=      Node(SCREAMING_SNAKE_CASE_)
   if self.head is None:
     lowercase__  :   Union[str, Any]    		=      new_node  # first node points itself
     lowercase__  :   Dict    		=      new_node
   elif index == 0:  # insert at head
     lowercase__  :   int    		=      self.head
     lowercase__  :   int    		=      new_node
   else:
     lowercase__  :   List[str]    		=      self.head
     for _ in range(index - 1):
       lowercase__  :   Union[str, Any]    		=      temp.next
     lowercase__  :   int    		=      temp.next
     lowercase__  :   Optional[Any]    		=      new_node
     if index == len(self) - 1:  # insert at tail
       lowercase__  :   Union[str, Any]    		=      new_node


 def      lowercase__     (					self):


   '''simple docstring'''




   return self.delete_nth(0)


 def      lowercase__     (					self):


   '''simple docstring'''




   return self.delete_nth(len(self) - 1)


 def      lowercase__     (					self					,  SCREAMING_SNAKE_CASE_ = 0):


   '''simple docstring'''




   if not 0 <= index < len(self):
     raise IndexError("""list index out of range.""")
   lowercase__  :   str    		=      self.head
   if self.head == self.tail:  # just one node
     lowercase__  :   List[Any]    		=      None
   elif index == 0:  # delete head node
     lowercase__  :   str    		=      self.tail.next.next
     lowercase__  :   List[Any]    		=      self.head.next
   else:
     lowercase__  :   Optional[int]    		=      self.head
     for _ in range(index - 1):
       lowercase__  :   List[Any]    		=      temp.next
     lowercase__  :   Optional[Any]    		=      temp.next
     lowercase__  :   Dict    		=      temp.next.next
     if index == len(self) - 1:  # delete at tail
       lowercase__  :   Tuple    		=      temp
   return delete_node.data



 def      lowercase__     (					self):


   '''simple docstring'''




   return len(self) == 0

def 		UpperCamelCase	(      )		->	None:


  '''simple docstring'''






  lowercase__  :   int    		=      CircularLinkedList()
  assert len(lowercase_   ) == 0
  assert circular_linked_list.is_empty() is True
  assert str(lowercase_   ) == ""

  try:
    circular_linked_list.delete_front()
    raise AssertionError  # This should not happen
  except IndexError:
    assert True  # This should happen

  try:
    circular_linked_list.delete_tail()
    raise AssertionError  # This should not happen
  except IndexError:
    assert True  # This should happen

  try:
    circular_linked_list.delete_nth(-1   )
    raise AssertionError
  except IndexError:
    assert True

  try:
    circular_linked_list.delete_nth(0   )
    raise AssertionError
  except IndexError:
    assert True

  assert circular_linked_list.is_empty() is True
  for i in range(5   ):
    assert len(lowercase_   ) == i
    circular_linked_list.insert_nth(lowercase_ , i + 1   )
  assert str(lowercase_   ) == "->".join(str(lowercase_   ) for i in range(1 , 6   )   )

  circular_linked_list.insert_tail(6   )
  assert str(lowercase_   ) == "->".join(str(lowercase_   ) for i in range(1 , 7   )   )
  circular_linked_list.insert_head(0   )
  assert str(lowercase_   ) == "->".join(str(lowercase_   ) for i in range(0 , 7   )   )

  assert circular_linked_list.delete_front() == 0
  assert circular_linked_list.delete_tail() == 6
  assert str(lowercase_   ) == "->".join(str(lowercase_   ) for i in range(1 , 6   )   )
  assert circular_linked_list.delete_nth(2   ) == 3

  circular_linked_list.insert_nth(2 , 3   )
  assert str(lowercase_   ) == "->".join(str(lowercase_   ) for i in range(1 , 6   )   )

  assert circular_linked_list.is_empty() is False


if __name__ == "__main__":
     import doctest

     doctest.testmod()






