



from __future__ import annotations

import inspect
import unittest

from transformers import MobileViTConfig
from transformers.file_utils import is_tf_available, is_vision_available
from transformers.testing_utils import require_tf, slow

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


if is_tf_available():
				import numpy as np
				import tensorflow as tf

				from transformers import TFMobileViTForImageClassification, TFMobileViTForSemanticSegmentation, TFMobileViTModel
				from transformers.models.mobilevit.modeling_tf_mobilevit import TF_MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
				from PIL import Image

				from transformers import MobileViTImageProcessor

class 						UpperCAmelCase__     (     __UpperCamelCase  ):




			'''simple docstring'''






			def 					snake_case__	(  self				:					int					):
					'''simple docstring'''





					__UpperCAmelCase       :	Any						=      self.config_class(**self.inputs_dict					)
					self.parent.assertTrue(hasattr(a_			,			'''hidden_sizes'''					)					)
					self.parent.assertTrue(hasattr(a_			,			'''neck_hidden_sizes'''					)					)
					self.parent.assertTrue(hasattr(a_			,			'''num_attention_heads'''					)					)

class 						UpperCAmelCase__     :




			'''simple docstring'''






			def __init__(  self				:					Union[str, Any]			,			a_				:					Tuple			,			a_				:					Dict=13			,			a_				:					Dict=32			,			a_				:					List[str]=2			,			a_				:					Dict=3			,			a_				:					str=6_40			,			a_				:					str=4			,			a_				:					List[str]="silu"			,			a_				:					Tuple=3			,			a_				:					List[str]=32			,			a_				:					List[Any]=0.1			,			a_				:					Optional[Any]=0.1			,			a_				:					int=0.1			,			a_				:					Dict=0.0_2			,			a_				:					str=True			,			a_				:					Union[str, Any]=True			,			a_				:					int=10			,			a_				:					Dict=None			,			):
					'''simple docstring'''





					__UpperCAmelCase       :	Union[str, Any]						=      parent
					__UpperCAmelCase       :	Dict						=      batch_size
					__UpperCAmelCase       :	int						=      image_size
					__UpperCAmelCase       :	Any						=      patch_size
					__UpperCAmelCase       :	str						=      num_channels
					__UpperCAmelCase       :	Dict						=      last_hidden_size
					__UpperCAmelCase       :	int						=      num_attention_heads
					__UpperCAmelCase       :	int						=      hidden_act
					__UpperCAmelCase       :	List[Any]						=      conv_kernel_size
					__UpperCAmelCase       :	Optional[int]						=      output_stride
					__UpperCAmelCase       :	Dict						=      hidden_dropout_prob
					__UpperCAmelCase       :	int						=      attention_probs_dropout_prob
					__UpperCAmelCase       :	Optional[Any]						=      classifier_dropout_prob
					__UpperCAmelCase       :	List[str]						=      use_labels
					__UpperCAmelCase       :	str						=      is_training
					__UpperCAmelCase       :	Tuple						=      num_labels
					__UpperCAmelCase       :	str						=      initializer_range
					__UpperCAmelCase       :	str						=      scope




			def 					snake_case__	(  self				:					Optional[int]					):
					'''simple docstring'''





					__UpperCAmelCase       :	Dict						=      floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]					)

					__UpperCAmelCase       :	Union[str, Any]						=      None
					__UpperCAmelCase       :	List[Any]						=      None
					if self.use_labels:
							__UpperCAmelCase       :	Any						=      ids_tensor([self.batch_size]			,			self.num_labels					)
							__UpperCAmelCase       :	Optional[Any]						=      ids_tensor([self.batch_size, self.image_size, self.image_size]			,			self.num_labels					)

					__UpperCAmelCase       :	Any						=      self.get_config()

					return config, pixel_values, labels, pixel_labels




			def 					snake_case__	(  self				:					str					):
					'''simple docstring'''





					return MobileViTConfig(
					    image_size=self.image_size			,			patch_size=self.patch_size			,			num_channels=self.num_channels			,			num_attention_heads=self.num_attention_heads			,			hidden_act=self.hidden_act			,			conv_kernel_size=self.conv_kernel_size			,			output_stride=self.output_stride			,			hidden_dropout_prob=self.hidden_dropout_prob			,			attention_probs_dropout_prob=self.attention_probs_dropout_prob			,			classifier_dropout_prob=self.classifier_dropout_prob			,			initializer_range=self.initializer_range			,			)




			def 					snake_case__	(  self				:					Any			,			a_				:					Union[str, Any]			,			a_				:					Dict			,			a_				:					Optional[Any]			,			a_				:					str					):
					'''simple docstring'''





					__UpperCAmelCase       :	Optional[int]						=      TFMobileViTModel(config=a_					)
					__UpperCAmelCase       :	Optional[Any]						=      model(a_			,			training=a_					)
					__UpperCAmelCase       :	Any						=      self.image_size // self.output_stride
					self.parent.assertEqual(
					    result.last_hidden_state.shape			,			(self.batch_size, self.last_hidden_size, expected_height, expected_width)					)




			def 					snake_case__	(  self				:					List[Any]			,			a_				:					List[Any]			,			a_				:					str			,			a_				:					Optional[Any]			,			a_				:					Dict					):
					'''simple docstring'''





					__UpperCAmelCase       :	Optional[int]						=      self.num_labels
					__UpperCAmelCase       :	Dict						=      TFMobileViTForImageClassification(a_					)
					__UpperCAmelCase       :	Union[str, Any]						=      model(a_			,			labels=a_			,			training=a_					)
					self.parent.assertEqual(result.logits.shape			,			(self.batch_size, self.num_labels)					)




			def 					snake_case__	(  self				:					List[Any]			,			a_				:					List[Any]			,			a_				:					List[str]			,			a_				:					Tuple			,			a_				:					Optional[Any]					):
					'''simple docstring'''





					__UpperCAmelCase       :	List[Any]						=      self.num_labels
					__UpperCAmelCase       :	int						=      TFMobileViTForSemanticSegmentation(a_					)
					__UpperCAmelCase       :	int						=      self.image_size // self.output_stride

					__UpperCAmelCase       :	List[str]						=      model(a_			,			training=a_					)
					self.parent.assertEqual(
					    result.logits.shape			,			(self.batch_size, self.num_labels, expected_height, expected_width)					)

					__UpperCAmelCase       :	List[str]						=      model(a_			,			labels=a_			,			training=a_					)
					self.parent.assertEqual(
					    result.logits.shape			,			(self.batch_size, self.num_labels, expected_height, expected_width)					)




			def 					snake_case__	(  self				:					List[Any]					):
					'''simple docstring'''





					__UpperCAmelCase       :	Dict						=      self.prepare_config_and_inputs()
					__UpperCAmelCase				,   __UpperCAmelCase				,   __UpperCAmelCase				,   __UpperCAmelCase       :	Union[str, Any]						=      config_and_inputs
					__UpperCAmelCase       :	Any						=      {'''pixel_values''': pixel_values}
					return config, inputs_dict

@require_tf
class 						UpperCAmelCase__     (     __UpperCamelCase		,__UpperCamelCase		,unittest.TestCase  ):




			'''simple docstring'''






			UpperCamelCase     		=			(
			    (TFMobileViTModel, TFMobileViTForImageClassification, TFMobileViTForSemanticSegmentation)
			    if is_tf_available()
			    else ()
			)
			UpperCamelCase     		=			(
			    {"""feature-extraction""": TFMobileViTModel, """image-classification""": TFMobileViTForImageClassification}
			    if is_tf_available()
			    else {}
			)

			UpperCamelCase     		=			False
			UpperCamelCase     		=			False
			UpperCamelCase     		=			False
			UpperCamelCase     		=			False
			UpperCamelCase     		=			False




			def 					snake_case__	(  self				:					Tuple					):
					'''simple docstring'''





					__UpperCAmelCase       :	str						=      TFMobileViTModelTester(self					)
					__UpperCAmelCase       :	str						=      TFMobileViTConfigTester(self			,			config_class=a_			,			has_text_modality=a_					)




			def 					snake_case__	(  self				:					List[str]					):
					'''simple docstring'''





					self.config_tester.run_common_tests()




			@unittest.skip(reason='''MobileViT does not use inputs_embeds'''					)
			def 					snake_case__	(  self				:					int					):
					'''simple docstring'''





					pass




			@unittest.skip(reason='''MobileViT does not support input and output embeddings'''					)
			def 					snake_case__	(  self				:					str					):
					'''simple docstring'''





					pass




			@unittest.skip(reason='''MobileViT does not output attentions'''					)
			def 					snake_case__	(  self				:					Optional[int]					):
					'''simple docstring'''





					pass




			def 					snake_case__	(  self				:					int					):
					'''simple docstring'''





					__UpperCAmelCase				,   __UpperCAmelCase       :	List[Any]						=      self.model_tester.prepare_config_and_inputs_for_common()

					for model_class in self.all_model_classes:
							__UpperCAmelCase       :	Any						=      model_class(a_					)
							__UpperCAmelCase       :	Any						=      inspect.signature(model.call					)
							# signature.parameters is an OrderedDict => so arg_names order is deterministic
							__UpperCAmelCase       :	int						=      [*signature.parameters.keys()]

							__UpperCAmelCase       :	List[Any]						=      ['''pixel_values''']
							self.assertListEqual(arg_names[:1]			,			a_					)




			def 					snake_case__	(  self				:					str					):
					'''simple docstring'''





					__UpperCAmelCase       :	Dict						=      self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_model(*a_					)




			def 					snake_case__	(  self				:					Dict					):
					'''simple docstring'''





					def check_hidden_states_output(a_				:					Optional[int]			,			a_				:					int			,			a_				:					Any					):
							__UpperCAmelCase       :	List[str]						=      model_class(a_					)

							__UpperCAmelCase       :	List[Any]						=      model(**self._prepare_for_class(a_			,			a_					)					)

							__UpperCAmelCase       :	Tuple						=      outputs.hidden_states

							__UpperCAmelCase       :	List[str]						=      5
							self.assertEqual(len(a_					)			,			a_					)

							# MobileViT's feature maps are of shape (batch_size, num_channels, height, width)
							# with the width and height being successively divided by 2.
							__UpperCAmelCase       :	Any						=      2
							for i in range(len(a_					)					):
									self.assertListEqual(
									    list(hidden_states[i].shape[-2:]					)			,			[self.model_tester.image_size // divisor, self.model_tester.image_size // divisor]			,			)
									divisor *= 2

							self.assertEqual(self.model_tester.output_stride			,			divisor // 2					)

					__UpperCAmelCase				,   __UpperCAmelCase       :	int						=      self.model_tester.prepare_config_and_inputs_for_common()

					for model_class in self.all_model_classes:
							__UpperCAmelCase       :	Dict						=      True
							check_hidden_states_output(a_			,			a_			,			a_					)

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

							check_hidden_states_output(a_			,			a_			,			a_					)




			def 					snake_case__	(  self				:					Dict					):
					'''simple docstring'''





					__UpperCAmelCase       :	List[Any]						=      self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_for_image_classification(*a_					)




			def 					snake_case__	(  self				:					List[str]					):
					'''simple docstring'''





					__UpperCAmelCase       :	Union[str, Any]						=      self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_for_semantic_segmentation(*a_					)




			@unittest.skipIf(
			    not is_tf_available() or len(tf.config.list_physical_devices('''GPU'''					)					) == 0			,			reason='''TF does not support backprop for grouped convolutions on CPU.'''			,			)
			def 					snake_case__	(  self				:					Union[str, Any]					):
					'''simple docstring'''





					super().test_dataset_conversion()




			def 					snake_case__	(  self				:					List[Any]			,			a_				:					int			,			a_				:					int			,			a_				:					Dict=2e-1			,			a_				:					Optional[Any]=2e-1					):
					'''simple docstring'''





					self.assertTrue(np.allclose(a_			,			a_			,			atol=a_			,			rtol=a_					)					)




			@unittest.skipIf(
			    not is_tf_available() or len(tf.config.list_physical_devices('''GPU'''					)					) == 0			,			reason='''TF does not support backprop for grouped convolutions on CPU.'''			,			)
			@slow
			def 					snake_case__	(  self				:					Tuple					):
					'''simple docstring'''





					__UpperCAmelCase				,   __UpperCAmelCase       :	Tuple						=      self.model_tester.prepare_config_and_inputs_for_common()

					for model_class in self.all_model_classes:
							# Since `TFMobileViTModel` cannot operate with the default `fit()` method.
							if model_class.__name__ != "TFMobileViTModel":
									__UpperCAmelCase       :	Any						=      model_class(a_					)
									if getattr(a_			,			'''hf_compute_loss'''			,			a_					):
											super().test_keras_fit()




			def 					snake_case__	(  self				:					Tuple					):
					'''simple docstring'''





					__UpperCAmelCase				,   __UpperCAmelCase       :	List[str]						=      self.model_tester.prepare_config_and_inputs_for_common()
					for model_class in self.all_model_classes:
							# set an ignore index to correctly test the masked loss used in
							# `TFMobileViTForSemanticSegmentation`.
							if model_class.__name__ != "TFMobileViTForSemanticSegmentation":
									__UpperCAmelCase       :	List[str]						=      5

							__UpperCAmelCase       :	List[Any]						=      model_class(a_					)
							if getattr(a_			,			'''hf_compute_loss'''			,			a_					):
									# The number of elements in the loss should be the same as the number of elements in the label
									__UpperCAmelCase       :	Optional[int]						=      self._prepare_for_class(inputs_dict.copy()			,			a_			,			return_labels=a_					)
									__UpperCAmelCase       :	Union[str, Any]						=      prepared_for_class[
									    sorted(prepared_for_class.keys() - inputs_dict.keys()			,			reverse=a_					)[0]
									]
									__UpperCAmelCase       :	List[str]						=      added_label.shape.as_list()[:1]

									# Test that model correctly compute the loss with kwargs
									__UpperCAmelCase       :	Optional[Any]						=      self._prepare_for_class(inputs_dict.copy()			,			a_			,			return_labels=a_					)
									__UpperCAmelCase       :	List[str]						=      {'''input_ids''', '''pixel_values''', '''input_features'''}
									__UpperCAmelCase       :	int						=      possible_input_names.intersection(set(a_					)					).pop()
									__UpperCAmelCase       :	Dict						=      prepared_for_class.pop(a_					)

									__UpperCAmelCase       :	str						=      model(a_			,			**a_					)[0]
									self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1]					)

									# Test that model correctly compute the loss when we mask some positions
									__UpperCAmelCase       :	List[str]						=      self._prepare_for_class(inputs_dict.copy()			,			a_			,			return_labels=a_					)
									__UpperCAmelCase       :	List[Any]						=      {'''input_ids''', '''pixel_values''', '''input_features'''}
									__UpperCAmelCase       :	Dict						=      possible_input_names.intersection(set(a_					)					).pop()
									__UpperCAmelCase       :	Optional[Any]						=      prepared_for_class.pop(a_					)
									if "labels" in prepared_for_class:
											__UpperCAmelCase       :	str						=      prepared_for_class['''labels'''].numpy()
											if len(labels.shape					) > 1 and labels.shape[1] != 1:
													# labels[0] = -100
													__UpperCAmelCase       :	Any						=      tf.convert_to_tensor(a_					)
													__UpperCAmelCase       :	Optional[Any]						=      model(a_			,			**a_					)[0]
													self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1]					)
													self.assertTrue(not np.any(np.isnan(loss.numpy()					)					)					)

                # Test that model correctly compute the loss with a dict
									__UpperCAmelCase       :	Tuple						=      self._prepare_for_class(inputs_dict.copy()			,			a_			,			return_labels=a_					)
									__UpperCAmelCase       :	str						=      model(a_					)[0]
									self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1]					)

									# Test that model correctly compute the loss with a tuple
									__UpperCAmelCase       :	str						=      self._prepare_for_class(inputs_dict.copy()			,			a_			,			return_labels=a_					)

									# Get keys that were added with the _prepare_for_class function
									__UpperCAmelCase       :	str						=      prepared_for_class.keys() - inputs_dict.keys()
									__UpperCAmelCase       :	Dict						=      inspect.signature(model.call					).parameters
									__UpperCAmelCase       :	Dict						=      list(signature.keys()					)

									# Create a dictionary holding the location of the tensors in the tuple
									__UpperCAmelCase       :	Tuple						=      {0: input_name}
									for label_key in label_keys:
											__UpperCAmelCase       :	List[Any]						=      signature_names.index(a_					)
											__UpperCAmelCase       :	Union[str, Any]						=      label_key
									__UpperCAmelCase       :	List[str]						=      sorted(tuple_index_mapping.items()					)
									# Initialize a list with their default values, update the values and convert to a tuple
									__UpperCAmelCase       :	Union[str, Any]						=      []

									for name in signature_names:
											if name != "kwargs":
													list_input.append(signature[name].default					)

									for index, value in sorted_tuple_index_mapping:
											__UpperCAmelCase       :	str						=      prepared_for_class[value]

									__UpperCAmelCase       :	List[str]						=      tuple(a_					)

									# Send to model
									__UpperCAmelCase       :	Any						=      model(tuple_input[:-1]					)[0]

									self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1]					)




			@slow
			def 					snake_case__	(  self				:					Optional[int]					):
					'''simple docstring'''





					for model_name in TF_MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
							__UpperCAmelCase       :	Any						=      TFMobileViTModel.from_pretrained(a_					)
							self.assertIsNotNone(a_					)

def 			a		( ):







		'''simple docstring'''





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

@require_tf
class 						UpperCAmelCase__     (     unittest.TestCase  ):




			'''simple docstring'''






			@slow
			def 					snake_case__	(  self				:					Union[str, Any]					):
					'''simple docstring'''





					__UpperCAmelCase       :	List[Any]						=      TFMobileViTForImageClassification.from_pretrained('''apple/mobilevit-xx-small'''					)

					__UpperCAmelCase       :	Union[str, Any]						=      MobileViTImageProcessor.from_pretrained('''apple/mobilevit-xx-small'''					)
					__UpperCAmelCase       :	List[Any]						=      prepare_img()
					__UpperCAmelCase       :	Any						=      image_processor(images=a_			,			return_tensors='''tf'''					)

					# forward pass
					__UpperCAmelCase       :	str						=      model(**a_			,			training=a_					)

					# verify the logits
					__UpperCAmelCase       :	Dict						=      tf.TensorShape((1, 10_00)					)
					self.assertEqual(outputs.logits.shape			,			a_					)

					__UpperCAmelCase       :	Dict						=      tf.constant([-1.9_3_6_4, -1.2_3_2_7, -0.4_6_5_3]					)

					tf.debugging.assert_near(outputs.logits[0, :3]			,			a_			,			atol=1e-4			,			rtol=1e-04					)




			@slow
			def 					snake_case__	(  self				:					Optional[Any]					):
					'''simple docstring'''





					__UpperCAmelCase       :	Union[str, Any]						=      TFMobileViTForSemanticSegmentation.from_pretrained('''apple/deeplabv3-mobilevit-xx-small'''					)

					__UpperCAmelCase       :	Tuple						=      MobileViTImageProcessor.from_pretrained('''apple/deeplabv3-mobilevit-xx-small'''					)

					__UpperCAmelCase       :	Tuple						=      prepare_img()
					__UpperCAmelCase       :	List[Any]						=      image_processor(images=a_			,			return_tensors='''tf'''					)

					# forward pass
					__UpperCAmelCase       :	List[Any]						=      model(inputs.pixel_values			,			training=a_					)
					__UpperCAmelCase       :	int						=      outputs.logits

					# verify the logits
					__UpperCAmelCase       :	str						=      tf.TensorShape((1, 21, 32, 32)					)
					self.assertEqual(logits.shape			,			a_					)

					__UpperCAmelCase       :	List[str]						=      tf.constant(
					    [
					        [[6.9_7_1_3, 6.9_7_8_6, 7.2_4_2_2], [7.2_8_9_3, 7.2_8_2_5, 7.4_4_4_6], [7.6_5_8_0, 7.8_7_9_7, 7.9_4_2_0]],
					        [[-1_0.6_8_6_9, -1_0.3_2_5_0, -1_0.3_4_7_1], [-1_0.4_2_2_8, -9.9_8_6_8, -9.7_1_3_2], [-1_1.0_4_0_5, -1_1.0_2_2_1, -1_0.7_3_1_8]],
					        [[-3.3_0_8_9, -2.8_5_3_9, -2.6_7_4_0], [-3.2_7_0_6, -2.5_6_2_1, -2.5_1_0_8], [-3.2_5_3_4, -2.6_6_1_5, -2.6_6_5_1]],
					    ]					)

					tf.debugging.assert_near(logits[0, :3, :3, :3]			,			a_			,			rtol=1e-4			,			atol=1e-4					)










import numpy as np

def 			a		( _UpperCAmelCase				:   str					,  _UpperCAmelCase				:   Any="utf-8"					,  _UpperCAmelCase				:   List[Any]="surrogatepass"		):







		'''simple docstring'''





		__UpperCAmelCase       :	Union[str, Any]						=      bin(int.from_bytes(text.encode(_UpperCAmelCase					,  _UpperCAmelCase		)					,  '''big'''		)		)[2:]
		return bits.zfill(8 * ((len(_UpperCAmelCase		) + 7) // 8)		)

def 			a		( _UpperCAmelCase				:   Dict					,  _UpperCAmelCase				:   Any="utf-8"					,  _UpperCAmelCase				:   str="surrogatepass"		):







		'''simple docstring'''





		__UpperCAmelCase       :	List[str]						=      int(_UpperCAmelCase					,  2		)
		return n.to_bytes((n.bit_length() + 7) // 8					,  '''big'''		).decode(_UpperCAmelCase					,  _UpperCAmelCase		) or "\0"

def 			a		( _UpperCAmelCase				:   List[Any]					,  _UpperCAmelCase				:   List[str]		):







		'''simple docstring'''





		if size_par + len(_UpperCAmelCase		) <= 2**size_par - (len(_UpperCAmelCase		) - 1):
				raise ValueError('''size of parity don\'t match with size of data'''		)

		__UpperCAmelCase       :	str						=      []
		__UpperCAmelCase       :	Any						=      []
		__UpperCAmelCase       :	Any						=      [bin(_UpperCAmelCase		)[2:] for x in range(1					,  size_par + len(_UpperCAmelCase		) + 1		)]

		# sorted information data for the size of the output data
		__UpperCAmelCase       :	Optional[Any]						=      []
		# data position template + parity
		__UpperCAmelCase       :	Any						=      []
		# parity bit counter
		__UpperCAmelCase       :	Tuple						=      0
		# counter position of data bits
		__UpperCAmelCase       :	Optional[int]						=      0

		for x in range(1					,  size_par + len(_UpperCAmelCase		) + 1		):
				# Performs a template of bit positions - who should be given,
				# and who should be parity
				if qtd_bp < size_par:
						if (np.log(_UpperCAmelCase		) / np.log(2		)).is_integer():
								data_out_gab.append('''P'''		)
								__UpperCAmelCase       :	Union[str, Any]						=      qtd_bp + 1
						else:
								data_out_gab.append('''D'''		)
				else:
						data_out_gab.append('''D'''		)

				# Sorts the data to the new output size
				if data_out_gab[-1] == "D":
						data_ord.append(data[cont_data]		)
						cont_data += 1
				else:
						data_ord.append(_UpperCAmelCase		)

    # Calculates parity
		__UpperCAmelCase       :	Union[str, Any]						=      0  # parity bit counter
		for bp in range(1					,  size_par + 1		):
				# Bit counter one for a given parity
				__UpperCAmelCase       :	List[str]						=      0
				# counter to control the loop reading
				__UpperCAmelCase       :	str						=      0
				for x in data_ord:
						if x is not None:
								try:
										__UpperCAmelCase       :	Tuple						=      (bin_pos[cont_loop])[-1 * (bp)]
								except IndexError:
										__UpperCAmelCase       :	List[str]						=      '''0'''
								if aux == "1" and x == "1":
										cont_bo += 1
						cont_loop += 1
				parity.append(cont_bo % 2		)

				qtd_bp += 1

		# Mount the message
		__UpperCAmelCase       :	int						=      0  # parity bit counter
		for x in range(0					,  size_par + len(_UpperCAmelCase		)		):
				if data_ord[x] is None:
						data_out.append(str(parity[cont_bp]		)		)
						cont_bp += 1
				else:
						data_out.append(data_ord[x]		)

		return data_out

def 			a		( _UpperCAmelCase				:   List[str]					,  _UpperCAmelCase				:   str		):







		'''simple docstring'''





		__UpperCAmelCase       :	str						=      []
		# Parity bit counter
		__UpperCAmelCase       :	List[str]						=      0
		# Counter p data bit reading
		__UpperCAmelCase       :	int						=      0
		# list of parity received
		__UpperCAmelCase       :	int						=      []
		__UpperCAmelCase       :	List[Any]						=      []

		for x in range(1					,  len(_UpperCAmelCase		) + 1		):
				# Performs a template of bit positions - who should be given,
				#  and who should be parity
				if qtd_bp < size_par and (np.log(_UpperCAmelCase		) / np.log(2		)).is_integer():
						data_out_gab.append('''P'''		)
						__UpperCAmelCase       :	Union[str, Any]						=      qtd_bp + 1
				else:
						data_out_gab.append('''D'''		)

				# Sorts the data to the new output size
				if data_out_gab[-1] == "D":
						data_output.append(data[cont_data]		)
				else:
						parity_received.append(data[cont_data]		)
				cont_data += 1

		# -----------calculates the parity with the data
		__UpperCAmelCase       :	Optional[int]						=      []
		__UpperCAmelCase       :	Dict						=      []
		__UpperCAmelCase       :	Union[str, Any]						=      [bin(_UpperCAmelCase		)[2:] for x in range(1					,  size_par + len(_UpperCAmelCase		) + 1		)]

		#  sorted information data for the size of the output data
		__UpperCAmelCase       :	str						=      []
		# Data position feedback + parity
		__UpperCAmelCase       :	Any						=      []
		# Parity bit counter
		__UpperCAmelCase       :	int						=      0
		# Counter p data bit reading
		__UpperCAmelCase       :	List[Any]						=      0

		for x in range(1					,  size_par + len(_UpperCAmelCase		) + 1		):
				# Performs a template position of bits - who should be given,
				# and who should be parity
				if qtd_bp < size_par and (np.log(_UpperCAmelCase		) / np.log(2		)).is_integer():
						data_out_gab.append('''P'''		)
						__UpperCAmelCase       :	Dict						=      qtd_bp + 1
				else:
						data_out_gab.append('''D'''		)

				# Sorts the data to the new output size
				if data_out_gab[-1] == "D":
						data_ord.append(data_output[cont_data]		)
						cont_data += 1
				else:
						data_ord.append(_UpperCAmelCase		)

    # Calculates parity
		__UpperCAmelCase       :	Union[str, Any]						=      0  # parity bit counter
		for bp in range(1					,  size_par + 1		):
				# Bit counter one for a certain parity
				__UpperCAmelCase       :	Union[str, Any]						=      0
				# Counter to control loop reading
				__UpperCAmelCase       :	Optional[Any]						=      0
				for x in data_ord:
						if x is not None:
								try:
										__UpperCAmelCase       :	int						=      (bin_pos[cont_loop])[-1 * (bp)]
								except IndexError:
										__UpperCAmelCase       :	int						=      '''0'''
								if aux == "1" and x == "1":
										cont_bo += 1
						cont_loop += 1
				parity.append(str(cont_bo % 2		)		)

				qtd_bp += 1

		# Mount the message
		__UpperCAmelCase       :	Any						=      0  # Parity bit counter
		for x in range(0					,  size_par + len(_UpperCAmelCase		)		):
				if data_ord[x] is None:
						data_out.append(str(parity[cont_bp]		)		)
						cont_bp += 1
				else:
						data_out.append(data_ord[x]		)

		__UpperCAmelCase       :	Optional[Any]						=      parity_received == parity
		return data_output, ack





