'''simple docstring'''




import collections
import types

import numpy as np

from ..utils import (
    add_end_docstrings,
    is_tensorflow_probability_available,
    is_tf_available,
    is_torch_available,
    requires_backends,
)
from .base import PIPELINE_INIT_ARGS, ArgumentHandler, Dataset, Pipeline, PipelineException


if is_torch_available():
  import torch

  from ..models.auto.modeling_auto import (
      MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING,
      MODEL_FOR_TABLE_QUESTION_ANSWERING_MAPPING,
  )

if is_tf_available() and is_tensorflow_probability_available():
  import tensorflow as tf
  import tensorflow_probability as tfp

  from ..models.auto.modeling_tf_auto import (
      TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING,
      TF_MODEL_FOR_TABLE_QUESTION_ANSWERING_MAPPING,
  )




class       __UpperCAmelCase							(							_UpperCamelCase	):





       '''simple docstring'''



       def __call__( self       ,	_SCREAMING_SNAKE_CASE=None       ,	_SCREAMING_SNAKE_CASE=None       ,	**_SCREAMING_SNAKE_CASE					)						->	Tuple:
           # Returns tqa_pipeline_inputs of shape:
           # [
           #   {"table": pd.DataFrame, "query": List[str]},
           #   ...,
           #   {"table": pd.DataFrame, "query" : List[str]}
           # ]
           requires_backends(self       ,	'''pandas'''					)
           import pandas as pd

           if table is None:
               raise ValueError('''Keyword argument `table` cannot be None.'''					)
           elif query is None:
               if isinstance(_SCREAMING_SNAKE_CASE       ,	_SCREAMING_SNAKE_CASE					) and table.get('''query'''					) is not None and table.get('''table'''					) is not None:
                   A_      =  [table]
               elif isinstance(_SCREAMING_SNAKE_CASE       ,	_SCREAMING_SNAKE_CASE					) and len(_SCREAMING_SNAKE_CASE					) > 0:
                   if not all(isinstance(_SCREAMING_SNAKE_CASE       ,	_SCREAMING_SNAKE_CASE					) for d in table					):
                       raise ValueError(
                           F'''Keyword argument `table` should be a list of dict, but is {(type(_SCREAMING_SNAKE_CASE					) for d in table)}'''					)

                   if table[0].get('''query'''					) is not None and table[0].get('''table'''					) is not None:
                       A_      =  table
                   else:
                       raise ValueError(
                           '''If keyword argument `table` is a list of dictionaries, each dictionary should have a `table`'''
                           F''' and `query` key, but only dictionary has keys {table[0].keys()} `table` and `query` keys.'''					)
               elif Dataset is not None and isinstance(_SCREAMING_SNAKE_CASE       ,	_SCREAMING_SNAKE_CASE					) or isinstance(_SCREAMING_SNAKE_CASE       ,	types.GeneratorType					):
                   return table
               else:
                   raise ValueError(
                       '''Invalid input. Keyword argument `table` should be either of type `dict` or `list`, but '''
                       F'''is {type(_SCREAMING_SNAKE_CASE					)})'''					)
           else:
               A_      =  [{'''table''': table, '''query''': query}]

           for tqa_pipeline_input in tqa_pipeline_inputs:
               if not isinstance(tqa_pipeline_input['''table''']       ,	pd.DataFrame					):
                   if tqa_pipeline_input["table"] is None:
                       raise ValueError('''Table cannot be None.'''					)

                   A_      =  pd.DataFrame(tqa_pipeline_input['''table''']					)

           return tqa_pipeline_inputs




@add_end_docstrings(_UpperCamelCase	)
class       __UpperCAmelCase							(							_UpperCamelCase	):





       '''simple docstring'''



       __lowercase   :   Dict  					=							'table,query'

       def __init__( self       ,	_SCREAMING_SNAKE_CASE=TableQuestionAnsweringArgumentHandler()       ,	*_SCREAMING_SNAKE_CASE       ,	**_SCREAMING_SNAKE_CASE					)						->	Tuple:
           super().__init__(*_SCREAMING_SNAKE_CASE       ,	**_SCREAMING_SNAKE_CASE					)
           A_      =  args_parser

           self.check_model_type(
               dict(
                   TF_MODEL_FOR_TABLE_QUESTION_ANSWERING_MAPPING.items()
                   + TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING.items()					)
               if self.framework == '''tf'''
               else dict(
                   MODEL_FOR_TABLE_QUESTION_ANSWERING_MAPPING.items() + MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING.items()					)					)

           A_      =  bool(getattr(self.model.config       ,	'''aggregation_labels'''       ,	_SCREAMING_SNAKE_CASE					)					) and bool(
               getattr(self.model.config       ,	'''num_aggregation_labels'''       ,	_SCREAMING_SNAKE_CASE					)					)
           A_      =  '''tapas''' if hasattr(self.model.config       ,	'''aggregation_labels'''					) else None

       def    __A			( self       ,	**_SCREAMING_SNAKE_CASE					)						->	Any:
           return self.model(**_SCREAMING_SNAKE_CASE					)

       def    __A			( self       ,	**_SCREAMING_SNAKE_CASE					)						->	Any:
           if self.framework == "pt":
               A_      =  []
               A_      =  []
               A_      =  None
               A_      =  inputs['''input_ids'''].shape[0]

               A_      =  inputs['''input_ids'''].to(self.device					)
               A_      =  inputs['''attention_mask'''].to(self.device					)
               A_      =  inputs['''token_type_ids'''].to(self.device					)
               A_      =  None

               for index in range(_SCREAMING_SNAKE_CASE					):
                   # If sequences have already been processed, the token type IDs will be created according to the previous
                   # answer.
                   if prev_answers is not None:
                       A_      =  token_type_ids_example[:, 3]  # shape (seq_len,)
                       A_      =  np.zeros_like(prev_labels_example.cpu().numpy()					)  # shape (seq_len,)

                       A_      =  token_type_ids[index]  # shape (seq_len, 7)
                       for i in range(model_labels.shape[0]					):
                           A_      =  token_type_ids_example[:, 0].tolist()[i]
                           A_      =  token_type_ids_example[:, 1].tolist()[i] - 1
                           A_      =  token_type_ids_example[:, 2].tolist()[i] - 1

                           if row_id >= 0 and col_id >= 0 and segment_id == 1:
                               A_      =  int(prev_answers[(col_id, row_id)]					)

                       A_      =  torch.from_numpy(_SCREAMING_SNAKE_CASE					).type(torch.long					).to(self.device					)

                   A_      =  input_ids[index]
                   A_      =  attention_mask[index]  # shape (seq_len,)
                   A_      =  token_type_ids[index]  # shape (seq_len, 7)
                   A_      =  self.model(
                       input_ids=input_ids_example.unsqueeze(0					)       ,	attention_mask=attention_mask_example.unsqueeze(0					)       ,	token_type_ids=token_type_ids_example.unsqueeze(0					)       ,	)
                   A_      =  outputs.logits

                   if self.aggregate:
                       all_aggregations.append(outputs.logits_aggregation					)

                   all_logits.append(_SCREAMING_SNAKE_CASE					)

                   A_      =  torch.distributions.Bernoulli(logits=_SCREAMING_SNAKE_CASE					)
                   A_      =  dist_per_token.probs * attention_mask_example.type(torch.floataa					).to(
                       dist_per_token.probs.device					)

                   A_      =  collections.defaultdict(_SCREAMING_SNAKE_CASE					)
                   for i, p in enumerate(probabilities.squeeze().tolist()					):
                       A_      =  token_type_ids_example[:, 0].tolist()[i]
                       A_      =  token_type_ids_example[:, 1].tolist()[i] - 1
                       A_      =  token_type_ids_example[:, 2].tolist()[i] - 1
                       if col >= 0 and row >= 0 and segment_id == 1:
                           coords_to_probs[(col, row)].append(_SCREAMING_SNAKE_CASE					)

                   A_      =  {key: np.array(coords_to_probs[key]					).mean() > 0.5 for key in coords_to_probs}

               A_      =  torch.cat(tuple(_SCREAMING_SNAKE_CASE					)       ,	0					)

               return (logits_batch,) if not self.aggregate else (logits_batch, torch.cat(tuple(_SCREAMING_SNAKE_CASE					)       ,	0					))
           else:
               A_      =  []
               A_      =  []
               A_      =  None
               A_      =  inputs['''input_ids'''].shape[0]

               A_      =  inputs['''input_ids''']
               A_      =  inputs['''attention_mask''']
               A_      =  inputs['''token_type_ids'''].numpy()
               A_      =  None

               for index in range(_SCREAMING_SNAKE_CASE					):
                   # If sequences have already been processed, the token type IDs will be created according to the previous
                   # answer.
                   if prev_answers is not None:
                       A_      =  token_type_ids_example[:, 3]  # shape (seq_len,)
                       A_      =  np.zeros_like(_SCREAMING_SNAKE_CASE       ,	dtype=np.intaa					)  # shape (seq_len,)

                       A_      =  token_type_ids[index]  # shape (seq_len, 7)
                       for i in range(model_labels.shape[0]					):
                           A_      =  token_type_ids_example[:, 0].tolist()[i]
                           A_      =  token_type_ids_example[:, 1].tolist()[i] - 1
                           A_      =  token_type_ids_example[:, 2].tolist()[i] - 1

                           if row_id >= 0 and col_id >= 0 and segment_id == 1:
                               A_      =  int(prev_answers[(col_id, row_id)]					)

                       A_      =  model_labels

                   A_      =  input_ids[index]
                   A_      =  attention_mask[index]  # shape (seq_len,)
                   A_      =  token_type_ids[index]  # shape (seq_len, 7)
                   A_      =  self.model(
                       input_ids=np.expand_dims(_SCREAMING_SNAKE_CASE       ,	axis=0					)       ,	attention_mask=np.expand_dims(_SCREAMING_SNAKE_CASE       ,	axis=0					)       ,	token_type_ids=np.expand_dims(_SCREAMING_SNAKE_CASE       ,	axis=0					)       ,	)
                   A_      =  outputs.logits

                   if self.aggregate:
                       all_aggregations.append(outputs.logits_aggregation					)

                   all_logits.append(_SCREAMING_SNAKE_CASE					)

                   A_      =  tfp.distributions.Bernoulli(logits=_SCREAMING_SNAKE_CASE					)
                   A_      =  dist_per_token.probs_parameter() * tf.cast(_SCREAMING_SNAKE_CASE       ,	tf.floataa					)

                   A_      =  collections.defaultdict(_SCREAMING_SNAKE_CASE					)
                   A_      =  token_type_ids_example
                   for i, p in enumerate(tf.squeeze(_SCREAMING_SNAKE_CASE					).numpy().tolist()					):
                       A_      =  token_type_ids_example[:, 0].tolist()[i]
                       A_      =  token_type_ids_example[:, 1].tolist()[i] - 1
                       A_      =  token_type_ids_example[:, 2].tolist()[i] - 1
                       if col >= 0 and row >= 0 and segment_id == 1:
                           coords_to_probs[(col, row)].append(_SCREAMING_SNAKE_CASE					)

                   A_      =  {key: np.array(coords_to_probs[key]					).mean() > 0.5 for key in coords_to_probs}

               A_      =  tf.concat(tuple(_SCREAMING_SNAKE_CASE					)       ,	0					)

               return (logits_batch,) if not self.aggregate else (logits_batch, tf.concat(tuple(_SCREAMING_SNAKE_CASE					)       ,	0					))

       def __call__( self       ,	*_SCREAMING_SNAKE_CASE       ,	**_SCREAMING_SNAKE_CASE					)						->	List[str]:
           A_      =  self._args_parser(*_SCREAMING_SNAKE_CASE       ,	**_SCREAMING_SNAKE_CASE					)

           A_      =  super().__call__(_SCREAMING_SNAKE_CASE       ,	**_SCREAMING_SNAKE_CASE					)
           if len(_SCREAMING_SNAKE_CASE					) == 1:
               return results[0]
           return results

       def    __A			( self       ,	_SCREAMING_SNAKE_CASE=None       ,	_SCREAMING_SNAKE_CASE=None       ,	_SCREAMING_SNAKE_CASE=None       ,	**_SCREAMING_SNAKE_CASE					)						->	Optional[int]:
           A_      =  {}
           if padding is not None:
               A_      =  padding
           if truncation is not None:
               A_      =  truncation

           A_      =  {}
           if sequential is not None:
               A_      =  sequential
           return preprocess_params, forward_params, {}

       def    __A			( self       ,	_SCREAMING_SNAKE_CASE       ,	_SCREAMING_SNAKE_CASE=None       ,	_SCREAMING_SNAKE_CASE=True       ,	_SCREAMING_SNAKE_CASE=None					)						->	Optional[Any]:
           if truncation is None:
               if self.type == "tapas":
                   A_      =  '''drop_rows_to_fit'''
               else:
                   A_      =  '''do_not_truncate'''

           A_  ,A_      =  pipeline_input['''table'''], pipeline_input['''query''']
           if table.empty:
               raise ValueError('''table is empty'''					)
           if query is None or query == "":
               raise ValueError('''query is empty'''					)
           A_      =  self.tokenizer(_SCREAMING_SNAKE_CASE       ,	_SCREAMING_SNAKE_CASE       ,	return_tensors=self.framework       ,	truncation=_SCREAMING_SNAKE_CASE       ,	padding=_SCREAMING_SNAKE_CASE					)
           A_      =  table
           return inputs

       def    __A			( self       ,	_SCREAMING_SNAKE_CASE       ,	_SCREAMING_SNAKE_CASE=False					)						->	Any:
           A_      =  model_inputs.pop('''table'''					)

           if self.type == "tapas":
               if sequential:
                   A_      =  self.sequential_inference(**_SCREAMING_SNAKE_CASE					)
               else:
                   A_      =  self.batch_inference(**_SCREAMING_SNAKE_CASE					)
           else:
               A_      =  self.model.generate(**_SCREAMING_SNAKE_CASE					)
           A_      =  {'''model_inputs''': model_inputs, '''table''': table, '''outputs''': outputs}
           return model_outputs

       def    __A			( self       ,	_SCREAMING_SNAKE_CASE					)						->	int:
           A_      =  model_outputs['''model_inputs''']
           A_      =  model_outputs['''table''']
           A_      =  model_outputs['''outputs''']
           if self.type == "tapas":
               if self.aggregate:
                   A_  ,A_      =  outputs[:2]
                   A_      =  self.tokenizer.convert_logits_to_predictions(_SCREAMING_SNAKE_CASE       ,	_SCREAMING_SNAKE_CASE       ,	_SCREAMING_SNAKE_CASE					)
                   A_  ,A_      =  predictions
                   A_      =  {i: self.model.config.aggregation_labels[pred] for i, pred in enumerate(_SCREAMING_SNAKE_CASE					)}

                   A_      =  self.model.config.no_aggregation_label_index
                   A_      =  {
                       i: aggregators[i] + ''' > ''' for i, pred in enumerate(_SCREAMING_SNAKE_CASE					) if pred != no_agg_label_index
                   }
               else:
                   A_      =  outputs[0]
                   A_      =  self.tokenizer.convert_logits_to_predictions(_SCREAMING_SNAKE_CASE       ,	_SCREAMING_SNAKE_CASE					)
                   A_      =  predictions[0]
                   A_      =  {}
                   A_      =  {}
               A_      =  []
               for index, coordinates in enumerate(_SCREAMING_SNAKE_CASE					):
                   A_      =  [table.iat[coordinate] for coordinate in coordinates]
                   A_      =  aggregators.get(_SCREAMING_SNAKE_CASE       ,	''''''					)
                   A_      =  aggregators_prefix.get(_SCREAMING_SNAKE_CASE       ,	''''''					)
                   A_      =  {
                       '''answer''': aggregator_prefix + ''', '''.join(_SCREAMING_SNAKE_CASE					),
                       '''coordinates''': coordinates,
                       '''cells''': [table.iat[coordinate] for coordinate in coordinates],
                   }
                   if aggregator:
                       A_      =  aggregator

                   answers.append(_SCREAMING_SNAKE_CASE					)
               if len(_SCREAMING_SNAKE_CASE					) == 0:
                   raise PipelineException('''Empty answer'''					)
           else:
               A_      =  [{'''answer''': answer} for answer in self.tokenizer.batch_decode(_SCREAMING_SNAKE_CASE       ,	skip_special_tokens=_SCREAMING_SNAKE_CASE					)]

           return answers if len(_SCREAMING_SNAKE_CASE					) > 1 else answers[0]







'''simple docstring'''




__snake_case  : str		       =    10**8





def 	_UpperCAmelCase       (				_UpperCamelCase       :      int  )      -> bool:
    if n % 10 == 0:
        return False
    A_      =  str(_UpperCamelCase  )
    return s == s[::-1]





def 	_UpperCAmelCase       (				)      -> int:
    A_      =  set()
    A_      =  1
    A_      =  5
    while sum_squares < LIMIT:
        A_      =  first_square + 1
        while sum_squares < LIMIT:
            if is_palindrome(_UpperCamelCase  ):
                answer.add(_UpperCamelCase  )
            last_square += 1
            sum_squares += last_square**2
        first_square += 1
        A_      =  first_square**2 + (first_square + 1) ** 2

    return sum(_UpperCamelCase  )


if __name__ == "__main__":
  print(solution())






