

from __future__ import annotations

import unittest

from transformers import 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 numpy
    import tensorflow as tf

    from transformers import (
        TF_DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST,
        TF_DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST,
        TF_DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST,
        BertConfig,
        DPRConfig,
        TFDPRContextEncoder,
        TFDPRQuestionEncoder,
        TFDPRReader,
    )
class  _A		:

      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=512 ,					_SCREAMING_SNAKE_CASE=16 ,					_SCREAMING_SNAKE_CASE=2 ,					_SCREAMING_SNAKE_CASE=0.02 ,					_SCREAMING_SNAKE_CASE=3 ,					_SCREAMING_SNAKE_CASE=4 ,					_SCREAMING_SNAKE_CASE=None ,					_SCREAMING_SNAKE_CASE=0 ,					):





            """simple docstring"""







            SCREAMING_SNAKE_CASE_				:  Union[str, Any]           =     parent
            SCREAMING_SNAKE_CASE_				:  Any           =     batch_size
            SCREAMING_SNAKE_CASE_				:  str           =     seq_length
            SCREAMING_SNAKE_CASE_				:  Optional[Any]           =     is_training
            SCREAMING_SNAKE_CASE_				:  Union[str, Any]           =     use_input_mask
            SCREAMING_SNAKE_CASE_				:  Any           =     use_token_type_ids
            SCREAMING_SNAKE_CASE_				:  List[str]           =     use_labels
            SCREAMING_SNAKE_CASE_				:  Dict           =     vocab_size
            SCREAMING_SNAKE_CASE_				:  List[Any]           =     hidden_size
            SCREAMING_SNAKE_CASE_				:  str           =     num_hidden_layers
            SCREAMING_SNAKE_CASE_				:  Optional[int]           =     num_attention_heads
            SCREAMING_SNAKE_CASE_				:  Union[str, Any]           =     intermediate_size
            SCREAMING_SNAKE_CASE_				:  Dict           =     hidden_act
            SCREAMING_SNAKE_CASE_				:  Dict           =     hidden_dropout_prob
            SCREAMING_SNAKE_CASE_				:  Union[str, Any]           =     attention_probs_dropout_prob
            SCREAMING_SNAKE_CASE_				:  int           =     max_position_embeddings
            SCREAMING_SNAKE_CASE_				:  Optional[Any]           =     type_vocab_size
            SCREAMING_SNAKE_CASE_				:  Optional[int]           =     type_sequence_label_size
            SCREAMING_SNAKE_CASE_				:  Optional[int]           =     initializer_range
            SCREAMING_SNAKE_CASE_				:  List[str]           =     num_labels
            SCREAMING_SNAKE_CASE_				:  str           =     num_choices
            SCREAMING_SNAKE_CASE_				:  List[Any]           =     scope
            SCREAMING_SNAKE_CASE_				:  Union[str, Any]           =     projection_dim

      def  UpperCAmelCase    (				self					):





            """simple docstring"""







            SCREAMING_SNAKE_CASE_				:  int           =     ids_tensor([self.batch_size, self.seq_length] ,					self.vocab_size					)

            SCREAMING_SNAKE_CASE_				:  int           =     None
            if self.use_input_mask:
                  # follow test_modeling_tf_ctrl.py
                  SCREAMING_SNAKE_CASE_				:  Optional[int]           =     random_attention_mask([self.batch_size, self.seq_length]					)

            SCREAMING_SNAKE_CASE_				:  Optional[Any]           =     None
            if self.use_token_type_ids:
                  SCREAMING_SNAKE_CASE_				:  Any           =     ids_tensor([self.batch_size, self.seq_length] ,					self.type_vocab_size					)

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

            SCREAMING_SNAKE_CASE_				:  Optional[int]           =     BertConfig(
                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 ,					is_decoder=_SCREAMING_SNAKE_CASE ,					initializer_range=self.initializer_range ,					)
            SCREAMING_SNAKE_CASE_				:  Tuple           =     DPRConfig(projection_dim=self.projection_dim ,					**config.to_dict()					)

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

      def  UpperCAmelCase    (				self ,					_SCREAMING_SNAKE_CASE ,					_SCREAMING_SNAKE_CASE ,					_SCREAMING_SNAKE_CASE ,					_SCREAMING_SNAKE_CASE ,					_SCREAMING_SNAKE_CASE ,					_SCREAMING_SNAKE_CASE ,					_SCREAMING_SNAKE_CASE					):





            """simple docstring"""







            SCREAMING_SNAKE_CASE_				:  str           =     TFDPRContextEncoder(config=_SCREAMING_SNAKE_CASE					)
            SCREAMING_SNAKE_CASE_				:  List[Any]           =     model(_SCREAMING_SNAKE_CASE ,					attention_mask=_SCREAMING_SNAKE_CASE ,					token_type_ids=_SCREAMING_SNAKE_CASE					)
            SCREAMING_SNAKE_CASE_				:  Dict           =     model(_SCREAMING_SNAKE_CASE ,					token_type_ids=_SCREAMING_SNAKE_CASE					)
            SCREAMING_SNAKE_CASE_				:  Dict           =     model(_SCREAMING_SNAKE_CASE					)
            self.parent.assertEqual(result.pooler_output.shape ,					(self.batch_size, self.projection_dim or self.hidden_size)					)

      def  UpperCAmelCase    (				self ,					_SCREAMING_SNAKE_CASE ,					_SCREAMING_SNAKE_CASE ,					_SCREAMING_SNAKE_CASE ,					_SCREAMING_SNAKE_CASE ,					_SCREAMING_SNAKE_CASE ,					_SCREAMING_SNAKE_CASE ,					_SCREAMING_SNAKE_CASE					):





            """simple docstring"""







            SCREAMING_SNAKE_CASE_				:  str           =     TFDPRQuestionEncoder(config=_SCREAMING_SNAKE_CASE					)
            SCREAMING_SNAKE_CASE_				:  List[str]           =     model(_SCREAMING_SNAKE_CASE ,					attention_mask=_SCREAMING_SNAKE_CASE ,					token_type_ids=_SCREAMING_SNAKE_CASE					)
            SCREAMING_SNAKE_CASE_				:  Any           =     model(_SCREAMING_SNAKE_CASE ,					token_type_ids=_SCREAMING_SNAKE_CASE					)
            SCREAMING_SNAKE_CASE_				:  int           =     model(_SCREAMING_SNAKE_CASE					)
            self.parent.assertEqual(result.pooler_output.shape ,					(self.batch_size, self.projection_dim or self.hidden_size)					)

      def  UpperCAmelCase    (				self ,					_SCREAMING_SNAKE_CASE ,					_SCREAMING_SNAKE_CASE ,					_SCREAMING_SNAKE_CASE ,					_SCREAMING_SNAKE_CASE ,					_SCREAMING_SNAKE_CASE ,					_SCREAMING_SNAKE_CASE ,					_SCREAMING_SNAKE_CASE					):





            """simple docstring"""







            SCREAMING_SNAKE_CASE_				:  Any           =     TFDPRReader(config=_SCREAMING_SNAKE_CASE					)
            SCREAMING_SNAKE_CASE_				:  List[Any]           =     model(_SCREAMING_SNAKE_CASE ,					attention_mask=_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)					)
            self.parent.assertEqual(result.relevance_logits.shape ,					(self.batch_size,)					)



      def  UpperCAmelCase    (				self					):





            """simple docstring"""







            SCREAMING_SNAKE_CASE_				:  Any           =     self.prepare_config_and_inputs()
            (
                SCREAMING_SNAKE_CASE_						
            )				:  Tuple           =     config_and_inputs
            SCREAMING_SNAKE_CASE_				:  List[Any]           =     {'input_ids': input_ids}
            return config, inputs_dict

@require_tf
class  _A		(  __magic_name__   ,     __magic_name__   ,     unittest.TestCase):
      SCREAMING_SNAKE_CASE    :      str       =  (
          (
              TFDPRContextEncoder,
              TFDPRQuestionEncoder,
              TFDPRReader,
          )
          if is_tf_available()
          else ()
      )
      SCREAMING_SNAKE_CASE    :      List[Any]       =  {'''feature-extraction''': TFDPRQuestionEncoder} if is_tf_available() else {}

      SCREAMING_SNAKE_CASE    :      Dict       =  False
      SCREAMING_SNAKE_CASE    :      int       =  False
      SCREAMING_SNAKE_CASE    :      str       =  False
      SCREAMING_SNAKE_CASE    :      Tuple       =  False
      SCREAMING_SNAKE_CASE    :      Any       =  False

      def  UpperCAmelCase    (				self					):





            """simple docstring"""







            SCREAMING_SNAKE_CASE_				:  Tuple           =     TFDPRModelTester(self					)
            SCREAMING_SNAKE_CASE_				:  Optional[int]           =     ConfigTester(self ,					config_class=_SCREAMING_SNAKE_CASE ,					hidden_size=37					)

      def  UpperCAmelCase    (				self					):





            """simple docstring"""







            self.config_tester.run_common_tests()

      def  UpperCAmelCase    (				self					):





            """simple docstring"""







            SCREAMING_SNAKE_CASE_				:  Union[str, Any]           =     self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_dpr_context_encoder(*_SCREAMING_SNAKE_CASE					)

      def  UpperCAmelCase    (				self					):





            """simple docstring"""







            SCREAMING_SNAKE_CASE_				:  List[Any]           =     self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_dpr_question_encoder(*_SCREAMING_SNAKE_CASE					)

      def  UpperCAmelCase    (				self					):





            """simple docstring"""







            SCREAMING_SNAKE_CASE_				:  List[Any]           =     self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_dpr_reader(*_SCREAMING_SNAKE_CASE					)



      @slow
      def  UpperCAmelCase    (				self					):





            """simple docstring"""







            for model_name in TF_DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                  SCREAMING_SNAKE_CASE_				:  Tuple           =     TFDPRContextEncoder.from_pretrained(_SCREAMING_SNAKE_CASE					)
                  self.assertIsNotNone(_SCREAMING_SNAKE_CASE					)

            for model_name in TF_DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                  SCREAMING_SNAKE_CASE_				:  List[str]           =     TFDPRContextEncoder.from_pretrained(_SCREAMING_SNAKE_CASE					)
                  self.assertIsNotNone(_SCREAMING_SNAKE_CASE					)

            for model_name in TF_DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                  SCREAMING_SNAKE_CASE_				:  str           =     TFDPRQuestionEncoder.from_pretrained(_SCREAMING_SNAKE_CASE					)
                  self.assertIsNotNone(_SCREAMING_SNAKE_CASE					)

            for model_name in TF_DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                  SCREAMING_SNAKE_CASE_				:  Dict           =     TFDPRReader.from_pretrained(_SCREAMING_SNAKE_CASE					)
                  self.assertIsNotNone(_SCREAMING_SNAKE_CASE					)

@require_tf
class  _A		(  unittest.TestCase):

      @slow
      def  UpperCAmelCase    (				self					):





            """simple docstring"""







            SCREAMING_SNAKE_CASE_				:  List[str]           =     TFDPRQuestionEncoder.from_pretrained('facebook/dpr-question_encoder-single-nq-base'					)

            SCREAMING_SNAKE_CASE_				:  List[str]           =     tf.constant(
                [[101, 7592, 1010, 2003, 2026, 3899, 1_0140, 1029, 102]]					)  # [CLS] hello, is my dog cute? [SEP]
            SCREAMING_SNAKE_CASE_				:  str           =     model(_SCREAMING_SNAKE_CASE					)[0]  # embedding shape = (1, 768)
            # compare the actual values for a slice.
            SCREAMING_SNAKE_CASE_				:  List[str]           =     tf.constant(
                [
                    [
                        0.03236253,
                        0.12753335,
                        0.16818509,
                        0.00279786,
                        0.3896933,
                        0.24264945,
                        0.2178971,
                        -0.02335227,
                        -0.08481959,
                        -0.14324117,
                    ]
                ]					)
            self.assertTrue(numpy.allclose(output[:, :10].numpy() ,					expected_slice.numpy() ,					atol=1e-4					)					)









def    A_  (							a					,   a					,   a  ):

      """simple docstring"""



      if len(a  ) != len(a  ):
            raise ValueError('The length of profit and weight must be same.'  )
      if max_weight <= 0:
            raise ValueError('max_weight must greater than zero.'  )
      if any(p < 0 for p in profit  ):
            raise ValueError('Profit can not be negative.'  )
      if any(w < 0 for w in weight  ):
            raise ValueError('Weight can not be negative.'  )

      # List created to store profit gained for the 1kg in case of each weight
      # respectively.  Calculate and append profit/weight for each element.
      SCREAMING_SNAKE_CASE_				:  Tuple           =     [p / w for p, w in zip(a					,   a  )]

      # Creating a copy of the list and sorting profit/weight in ascending order
      SCREAMING_SNAKE_CASE_				:  List[Any]           =     sorted(a  )

      # declaring useful variables
      SCREAMING_SNAKE_CASE_				:  List[Any]           =     len(a  )
      SCREAMING_SNAKE_CASE_				:  str           =     0
      SCREAMING_SNAKE_CASE_				:  List[str]           =     0
      SCREAMING_SNAKE_CASE_				:  Any           =     0

      # loop till the total weight do not reach max limit e.g. 15 kg and till i<length
      while limit <= max_weight and i < length:
            # flag value for encountered greatest element in sorted_profit_by_weight
            SCREAMING_SNAKE_CASE_				:  Optional[Any]           =     sorted_profit_by_weight[length - i - 1]
            SCREAMING_SNAKE_CASE_				:  Union[str, Any]           =     profit_by_weight.index(a  )
            SCREAMING_SNAKE_CASE_				:  Dict           =     -1

            # check if the weight encountered is less than the total weight
            # encountered before.
            if max_weight - limit >= weight[index]:
                  limit += weight[index]
                  # Adding profit gained for the given weight 1 ===
                  # weight[index]/weight[index]
                  gain += 1 * profit[index]
            else:
                  # Since the weight encountered is greater than limit, therefore take the
                  # required number of remaining kgs and calculate profit for it.
                  # weight remaining / weight[index]
                  gain += (max_weight - limit) / weight[index] * profit[index]
                  break
            i += 1
      return gain


if __name__ == "__main__":
    print(
        'Input profits, weights, and then max_weight (all positive ints) separated by '
        'spaces.'
    )

    lowerCAmelCase     :   Tuple						     =  [int(x) for x in input('Input profits separated by spaces: ').split()]
    lowerCAmelCase     :   Union[str, Any]						     =  [int(x) for x in input('Input weights separated by spaces: ').split()]
    lowerCAmelCase     :   Dict						     =  int(input('Max weight allowed: '))

    # Function Call
    calc_profit(profit, weight, max_weight)






