



"""simple docstring"""







import copy
import fnmatch
import json
import os
import pickle as pkl
import shutil
import sys
import tarfile
import tempfile
from collections import OrderedDict
from contextlib import contextmanager
from functools import partial
from hashlib import shaaaa
from io import BytesIO
from pathlib import Path
from urllib.parse import urlparse
from zipfile import ZipFile, is_zipfile

import cva
import numpy as np
import requests
import wget
from filelock import FileLock
from PIL import Image
from tqdm.auto import tqdm
from yaml import Loader, dump, load


try:
							import torch

							A     =      True
except ImportError:
							A     =      False


try:
							from torch.hub import _get_torch_home

							A     =      _get_torch_home()
except ImportError:
							A     =      os.path.expanduser(
							    os.getenv('TORCH_HOME', os.path.join(os.getenv('XDG_CACHE_HOME', '~/.cache'), 'torch'))
							)

A     =      os.path.join(torch_cache_home, 'transformers')

A     =      '''https://cdn.huggingface.co'''
A     =      '''https://s3.amazonaws.com/models.huggingface.co/bert'''
A     =      '''/'''.join(str(Path(__file__).resolve()).split('/')[:-1])
A     =      os.path.join(PATH, 'config.yaml')
A     =      os.path.join(PATH, 'attributes.txt')
A     =      os.path.join(PATH, 'objects.txt')
A     =      os.getenv('PYTORCH_PRETRAINED_BERT_CACHE', default_cache_path)
A     =      os.getenv('PYTORCH_TRANSFORMERS_CACHE', PYTORCH_PRETRAINED_BERT_CACHE)
A     =      os.getenv('TRANSFORMERS_CACHE', PYTORCH_TRANSFORMERS_CACHE)
A     =      '''pytorch_model.bin'''
A     =      '''config.yaml'''

def 	lowerCAmelCase__      (  lowerCamelCase__=OBJECTS					,   lowerCamelCase__=ATTRIBUTES      )			->				Union[str, Any]:
							A    =       []
							with open(A__      ) as f:
														for object in f.readlines():
																					vg_classes.append(object.split(','      )[0].lower().strip()      )

							A    =       []
							with open(A__      ) as f:
														for object in f.readlines():
																					vg_attrs.append(object.split(','      )[0].lower().strip()      )
							return vg_classes, vg_attrs

def 	lowerCAmelCase__      (  lowerCamelCase__      )			->				List[Any]:
							A    =       OrderedDict()
							with open(A__					,   'rb'      ) as f:
														A    =       pkl.load(A__      )['model']
							for k in copy.deepcopy(list(ckp.keys()      )      ):
														A    =       ckp.pop(A__      )
														if isinstance(A__					,   np.ndarray      ):
																					A    =       torch.tensor(A__      )
														else:
																					assert isinstance(A__					,   torch.tensor      ), type(A__      )
														A    =       v
							return r






class   UpperCAmelCase__		:
		lowerCAmelCase_							:						List[str]							=  {}



		def __init__(			self	:     Dict   ,				snake_case	:     Optional[Any]   ,				snake_case	:     int = "root"   ,				snake_case	:     Dict=0					)      ->    int:






									'''simple docstring'''

									A    =       name
									A    =       level
									A    =       {}
									for k, v in dictionary.items():
																if v is None:
																							raise ValueError()
																A    =       copy.deepcopy(SCREAMING_SNAKE_CASE__					)
																A    =       copy.deepcopy(SCREAMING_SNAKE_CASE__					)
																if isinstance(SCREAMING_SNAKE_CASE__   ,				SCREAMING_SNAKE_CASE__					):
																							A    =       Config(SCREAMING_SNAKE_CASE__   ,				name=SCREAMING_SNAKE_CASE__   ,				level=level + 1					)
																A    =       v
																setattr(self   ,				SCREAMING_SNAKE_CASE__   ,				SCREAMING_SNAKE_CASE__					)

									A    =       d



		def __repr__(			self	:     int					)      ->    Tuple:






									'''simple docstring'''

									return str(list((self._pointer.keys())					)					)



		def __setattr__(			self	:     Union[str, Any]   ,				snake_case	:     Dict   ,				snake_case	:     Tuple					)      ->    int:






									'''simple docstring'''

									A    =       val
									A    =       val
									A    =       key.split('.'					)
									A    =       len(SCREAMING_SNAKE_CASE__					) - 1
									A    =       self._pointer
									if len(SCREAMING_SNAKE_CASE__					) > 1:
																for i, l in enumerate(SCREAMING_SNAKE_CASE__					):
																							if hasattr(self   ,				SCREAMING_SNAKE_CASE__					) and isinstance(getattr(self   ,				SCREAMING_SNAKE_CASE__					)   ,				SCREAMING_SNAKE_CASE__					):
																														setattr(getattr(self   ,				SCREAMING_SNAKE_CASE__					)   ,				'.'.join(levels[i:]					)   ,				SCREAMING_SNAKE_CASE__					)
																							if l == last_level:
																														A    =       val
																							else:
																														A    =       pointer[l]



		def        A_		(			self	:     Union[str, Any]					)      ->    Optional[int]:






									'''simple docstring'''

									return self._pointer



		def        A_		(			self	:     Dict   ,				snake_case	:     List[str]   ,				snake_case	:     Tuple					)      ->    Optional[int]:






									'''simple docstring'''

									with open(f"""{file_name}"""   ,				'w'					) as stream:
																dump(SCREAMING_SNAKE_CASE__   ,				SCREAMING_SNAKE_CASE__					)



		def        A_		(			self	:     Dict   ,				snake_case	:     List[str]   ,				snake_case	:     List[str]					)      ->    Optional[Any]:






									'''simple docstring'''

									with open(f"""{file_name}"""   ,				'w'					) as stream:
																json.dump(SCREAMING_SNAKE_CASE__   ,				SCREAMING_SNAKE_CASE__					)



		@staticmethod
		def        A_		(			snake_case	:     Dict					)      ->    int:






									'''simple docstring'''

									with open(SCREAMING_SNAKE_CASE__					) as stream:
																A    =       load(SCREAMING_SNAKE_CASE__   ,				Loader=SCREAMING_SNAKE_CASE__					)
									return data



		def __str__(			self	:     Union[str, Any]					)      ->    Optional[int]:






									'''simple docstring'''

									A    =       '    '
									if self._name != "root":
																A    =       f"""{t * (self._level-1)}{self._name}:\n"""
									else:
																A    =       ''
									A    =       self._level
									for i, (k, v) in enumerate(self._pointer.items()					):
																if isinstance(SCREAMING_SNAKE_CASE__   ,				SCREAMING_SNAKE_CASE__					):
																							r += f"""{t * (self._level)}{v}\n"""
																							self._level += 1
																else:
																							r += f"""{t * (self._level)}{k}: {v} ({type(SCREAMING_SNAKE_CASE__					).__name__})\n"""
																A    =       level
									return r[:-1]



		@classmethod
		def        A_		(			cls	:     int   ,				snake_case	:     int   ,				**snake_case	:     str					)      ->    Tuple:






									'''simple docstring'''

									A   ,	A    =       cls.get_config_dict(SCREAMING_SNAKE_CASE__   ,				**SCREAMING_SNAKE_CASE__					)
									return cls(SCREAMING_SNAKE_CASE__					)



		@classmethod
		def        A_		(			cls	:     Tuple   ,				snake_case	:     Optional[Any]   ,				**snake_case	:     Any					)      ->    Tuple:






									'''simple docstring'''

									A    =       kwargs.pop('cache_dir'   ,				SCREAMING_SNAKE_CASE__					)
									A    =       kwargs.pop('force_download'   ,				SCREAMING_SNAKE_CASE__					)
									A    =       kwargs.pop('resume_download'   ,				SCREAMING_SNAKE_CASE__					)
									A    =       kwargs.pop('proxies'   ,				SCREAMING_SNAKE_CASE__					)
									A    =       kwargs.pop('local_files_only'   ,				SCREAMING_SNAKE_CASE__					)

									if os.path.isdir(SCREAMING_SNAKE_CASE__					):
																A    =       os.path.join(SCREAMING_SNAKE_CASE__   ,				SCREAMING_SNAKE_CASE__					)
									elif os.path.isfile(SCREAMING_SNAKE_CASE__					) or is_remote_url(SCREAMING_SNAKE_CASE__					):
																A    =       pretrained_model_name_or_path
									else:
																A    =       hf_bucket_url(SCREAMING_SNAKE_CASE__   ,				filename=SCREAMING_SNAKE_CASE__   ,				use_cdn=SCREAMING_SNAKE_CASE__					)

									try:
																# Load from URL or cache if already cached
																A    =       cached_path(
																    SCREAMING_SNAKE_CASE__   ,				cache_dir=SCREAMING_SNAKE_CASE__   ,				force_download=SCREAMING_SNAKE_CASE__   ,				proxies=SCREAMING_SNAKE_CASE__   ,				resume_download=SCREAMING_SNAKE_CASE__   ,				local_files_only=SCREAMING_SNAKE_CASE__   ,				)
																# Load config dict
																if resolved_config_file is None:
																							raise EnvironmentError

																A    =       Config.load_yaml(SCREAMING_SNAKE_CASE__					)

									except EnvironmentError:
																A    =       'Can\'t load config for'
																raise EnvironmentError(SCREAMING_SNAKE_CASE__					)

									if resolved_config_file == config_file:
																print('loading configuration file from path'					)
									else:
																print('loading configuration file cache'					)

									return Config.load_yaml(SCREAMING_SNAKE_CASE__					), kwargs



def 	lowerCAmelCase__      (  lowerCamelCase__      )			->				Dict:
							A    =       torch.load('dump.pt'					,   map_location=in_tensor.device      )
							A    =       in_tensor.numpy()
							A    =       out_tensor.numpy()[0]
							print(na.shape					,   na[0, 0, :5]      )
							print(na.shape					,   na[0, 0, :5]      )
							assert np.allclose(A__					,   A__					,   rtol=0.01					,   atol=0.1      ), (
							    f"""{sum([1 for x in np.isclose(A__					,   A__					,   rtol=0.01					,   atol=0.1      ).flatten() if x is False]      )/len(na.flatten()      )*100:.4f} %"""
							    " element-wise mismatch"
							)
							raise Exception('tensors are all good'      )

							# Hugging face functions below

def 	lowerCAmelCase__      (  lowerCamelCase__      )			->				Optional[Any]:
							A    =       urlparse(A__      )
							return parsed.scheme in ("http", "https")

def 	lowerCAmelCase__      (  lowerCamelCase__					,   lowerCamelCase__					,   lowerCamelCase__=True      )			->				str:
							A    =       CLOUDFRONT_DISTRIB_PREFIX if use_cdn else S3_BUCKET_PREFIX
							A    =       '/' not in model_id
							if legacy_format:
														return f"""{endpoint}/{model_id}-{filename}"""
							else:
														return f"""{endpoint}/{model_id}/{filename}"""

def 	lowerCAmelCase__      (  lowerCamelCase__					,   lowerCamelCase__					,   lowerCamelCase__=None					,   lowerCamelCase__=0					,   lowerCamelCase__=None					,   )			->				Any:
							A    =       'python/{}'.format(sys.version.split()[0]      )
							if _torch_available:
														ua += "; torch/{}".format(torch.__version__      )
							if isinstance(A__					,   A__      ):
														ua += "; " + "; ".join('{}/{}'.format(A__					,   A__      ) for k, v in user_agent.items()      )
							elif isinstance(A__					,   A__      ):
														ua += "; " + user_agent
							A    =       {'user-agent': ua}
							if resume_size > 0:
														A    =       'bytes=%d-' % (resume_size,)
							A    =       requests.get(A__					,   stream=A__					,   proxies=A__					,   headers=A__      )
							if response.status_code == 416:  # Range not satisfiable
														return
							A    =       response.headers.get('Content-Length'      )
							A    =       resume_size + int(A__      ) if content_length is not None else None
							A    =       tqdm(
							    unit='B'					,   unit_scale=A__					,   total=A__					,   initial=A__					,   desc='Downloading'					,   )
							for chunk in response.iter_content(chunk_size=1024      ):
														if chunk:  # filter out keep-alive new chunks
																					progress.update(len(A__      )      )
																					temp_file.write(A__      )
							progress.close()

def 	lowerCAmelCase__      (  lowerCamelCase__					,   lowerCamelCase__=None					,   lowerCamelCase__=False					,   lowerCamelCase__=None					,   lowerCamelCase__=10					,   lowerCamelCase__=False					,   lowerCamelCase__=None					,   lowerCamelCase__=False					,   )			->				Dict:
							if cache_dir is None:
														A    =       TRANSFORMERS_CACHE
							if isinstance(A__					,   A__      ):
														A    =       str(A__      )

							os.makedirs(A__					,   exist_ok=A__      )

							A    =       None
							if not local_files_only:
														try:
																					A    =       requests.head(A__					,   allow_redirects=A__					,   proxies=A__					,   timeout=A__      )
																					if response.status_code == 200:
																												A    =       response.headers.get('ETag'      )
														except (EnvironmentError, requests.exceptions.Timeout):
																					# etag is already None
																					pass

							A    =       url_to_filename(A__					,   A__      )

							# get cache path to put the file
							A    =       os.path.join(A__					,   A__      )

							# etag is None = we don't have a connection, or url doesn't exist, or is otherwise inaccessible.
							# try to get the last downloaded one
							if etag is None:
														if os.path.exists(A__      ):
																					return cache_path
														else:
																					A    =       [
																					    file
																					    for file in fnmatch.filter(os.listdir(A__      )					,   filename + '.*'      )
																					    if not file.endswith('.json'      ) and not file.endswith('.lock'      )
																					]
																					if len(A__      ) > 0:
																												return os.path.join(A__					,   matching_files[-1]      )
																					else:
																												# If files cannot be found and local_files_only=True,
																												# the models might've been found if local_files_only=False
																												# Notify the user about that
																												if local_files_only:
																																			raise ValueError(
																																			    'Cannot find the requested files in the cached path and outgoing traffic has been'
																																			    ' disabled. To enable model look-ups and downloads online, set \'local_files_only\''
																																			    ' to False.'      )
																												return None

    # From now on, etag is not None.
							if os.path.exists(A__      ) and not force_download:
														return cache_path

							# Prevent parallel downloads of the same file with a lock.
							A    =       cache_path + '.lock'
							with FileLock(A__      ):
														# If the download just completed while the lock was activated.
														if os.path.exists(A__      ) and not force_download:
																					# Even if returning early like here, the lock will be released.
																					return cache_path

														if resume_download:
																					A    =       cache_path + '.incomplete'

																					@contextmanager
																					def _resumable_file_manager():
																												with open(A__					,   'a+b'      ) as f:
																																			yield f

																					A    =       _resumable_file_manager
																					if os.path.exists(A__      ):
																												A    =       os.stat(A__      ).st_size
																					else:
																												A    =       0
														else:
																					A    =       partial(tempfile.NamedTemporaryFile					,   dir=A__					,   delete=A__      )
																					A    =       0

														# Download to temporary file, then copy to cache dir once finished.
														# Otherwise you get corrupt cache entries if the download gets interrupted.
														with temp_file_manager() as temp_file:
																					print(
																					    '%s not found in cache or force_download set to True, downloading to %s'					,   A__					,   temp_file.name					,   )

																					http_get(
																					    A__					,   A__					,   proxies=A__					,   resume_size=A__					,   user_agent=A__					,   )

														os.replace(temp_file.name					,   A__      )

														A    =       {'url': url, 'etag': etag}
														A    =       cache_path + '.json'
														with open(A__					,   'w'      ) as meta_file:
																					json.dump(A__					,   A__      )

							return cache_path

def 	lowerCAmelCase__      (  lowerCamelCase__					,   lowerCamelCase__=None      )			->				List[Any]:
							A    =       url.encode('utf-8'      )
							A    =       shaaaa(A__      )
							A    =       url_hash.hexdigest()

							if etag:
														A    =       etag.encode('utf-8'      )
														A    =       shaaaa(A__      )
														filename += "." + etag_hash.hexdigest()

							if url.endswith('.h5'      ):
														filename += ".h5"

							return filename

def 	lowerCAmelCase__      (  lowerCamelCase__					,   lowerCamelCase__=None					,   lowerCamelCase__=False					,   lowerCamelCase__=None					,   lowerCamelCase__=False					,   lowerCamelCase__=None					,   lowerCamelCase__=False					,   lowerCamelCase__=False					,   lowerCamelCase__=False					,   )			->				Dict:
							if cache_dir is None:
														A    =       TRANSFORMERS_CACHE
							if isinstance(A__					,   A__      ):
														A    =       str(A__      )
							if isinstance(A__					,   A__      ):
														A    =       str(A__      )

							if is_remote_url(A__      ):
														# URL, so get it from the cache (downloading if necessary)
														A    =       get_from_cache(
														    A__					,   cache_dir=A__					,   force_download=A__					,   proxies=A__					,   resume_download=A__					,   user_agent=A__					,   local_files_only=A__					,   )
							elif os.path.exists(A__      ):
														# File, and it exists.
														A    =       url_or_filename
							elif urlparse(A__      ).scheme == "":
														# File, but it doesn't exist.
														raise EnvironmentError('file {} not found'.format(A__      )      )
							else:
														# Something unknown
														raise ValueError('unable to parse {} as a URL or as a local path'.format(A__      )      )

							if extract_compressed_file:
														if not is_zipfile(A__      ) and not tarfile.is_tarfile(A__      ):
																					return output_path

														# Path where we extract compressed archives
														# We avoid '.' in dir name and add "-extracted" at the end: "./model.zip" => "./model-zip-extracted/"
														A   ,	A    =       os.path.split(A__      )
														A    =       output_file.replace('.'					,   '-'      ) + '-extracted'
														A    =       os.path.join(A__					,   A__      )

														if os.path.isdir(A__      ) and os.listdir(A__      ) and not force_extract:
																					return output_path_extracted

														# Prevent parallel extractions
														A    =       output_path + '.lock'
														with FileLock(A__      ):
																					shutil.rmtree(A__					,   ignore_errors=A__      )
																					os.makedirs(A__      )
																					if is_zipfile(A__      ):
																												with ZipFile(A__					,   'r'      ) as zip_file:
																																			zip_file.extractall(A__      )
																																			zip_file.close()
																					elif tarfile.is_tarfile(A__      ):
																												A    =       tarfile.open(A__      )
																												tar_file.extractall(A__      )
																												tar_file.close()
																					else:
																												raise EnvironmentError('Archive format of {} could not be identified'.format(A__      )      )

														return output_path_extracted

							return output_path

def 	lowerCAmelCase__      (  lowerCamelCase__					,   lowerCamelCase__=","      )			->				Optional[int]:
							assert isinstance(A__					,   A__      )
							if os.path.isfile(A__      ):
														with open(A__      ) as f:
																					A    =       eval(f.read()      )
							else:
														A    =       requests.get(A__      )
														try:
																					A    =       requests.json()
														except Exception:
																					A    =       req.content.decode()
																					assert data is not None, "could not connect"
																					try:
																												A    =       eval(A__      )
																					except Exception:
																												A    =       data.split('\n'      )
														req.close()
							return data

def 	lowerCAmelCase__      (  lowerCamelCase__      )			->				int:
							A    =       requests.get(A__      )
							A    =       np.array(Image.open(BytesIO(response.content      )      )      )
							return img

def 	lowerCAmelCase__      (  lowerCamelCase__      )			->				int:
							A    =       url.split('/'      )[-1]
							if fn not in os.listdir(os.getcwd()      ):
														wget.download(A__      )
							with open(A__					,   'rb'      ) as stream:
														A    =       pkl.load(A__      )
							A    =       weights.pop('model'      )
							A    =       {}
							for k, v in model.items():
														A    =       torch.from_numpy(A__      )
														if "running_var" in k:
																					A    =       torch.tensor([0]      )
																					A    =       k.replace('running_var'					,   'num_batches_tracked'      )
																					A    =       zero
							return new

def 	lowerCAmelCase__      (  )			->				List[Any]:
							print(f"""{os.path.abspath(os.path.join(A__					,   os.pardir      )      )}/demo.ipynb"""      )

def 	lowerCAmelCase__      (  lowerCamelCase__					,   lowerCamelCase__="RGB"      )			->				Any:
							assert isinstance(A__					,   A__      )
							if os.path.isfile(A__      ):
														A    =       cva.imread(A__      )
							else:
														A    =       get_image_from_url(A__      )
														assert img is not None, f"""could not connect to: {im}"""
							A    =       cva.cvtColor(A__					,   cva.COLOR_BGR2RGB      )
							if input_format == "RGB":
														A    =       img[:, :, ::-1]
							return img

def 	lowerCAmelCase__      (  lowerCamelCase__					,   lowerCamelCase__=1      )			->				Optional[int]:
							return (images[i : i + batch] for i in range(0					,   len(A__      )					,   A__      ))






"""simple docstring"""




import math

import qiskit
from qiskit import Aer, ClassicalRegister, QuantumCircuit, QuantumRegister, execute



def 						UpperCAmelCase__ (					A__ = 1						,     A__ = 1 )   ->   qiskit.result.counts.Counts:




   """simple docstring"""
   if isinstance(A__						,     A__ ) or isinstance(A__						,     A__ ):
      raise TypeError("inputs must be integers." )
   if (bit_a < 0) or (bit_a < 0):
      raise ValueError("inputs must be positive." )
   if (math.floor(A__ ) != bit_a) or (math.floor(A__ ) != bit_a):
      raise ValueError("inputs must be exact integers." )
   if (bit_a > 1) or (bit_a > 1):
      raise ValueError("inputs must be less or equal to 1." )

   # build registers
   lowerCamelCase__						       =      QuantumRegister(2						,     "qr" )
   lowerCamelCase__						       =      ClassicalRegister(2						,     "cr" )

   lowerCamelCase__						       =      QuantumCircuit(A__						,     A__ )

   # entanglement the qubits
   quantum_circuit.h(1 )
   quantum_circuit.cx(1						,     0 )

   # send the information
   lowerCamelCase__						       =      str(A__ ) + str(A__ )

   if c_information == "11":
      quantum_circuit.x(1 )
      quantum_circuit.z(1 )
   elif c_information == "10":
      quantum_circuit.z(1 )
   elif c_information == "01":
      quantum_circuit.x(1 )
   else:
      quantum_circuit.i(1 )

   # unentangled the circuit
   quantum_circuit.cx(1						,     0 )
   quantum_circuit.h(1 )

   # measure the circuit
   quantum_circuit.measure(A__						,     A__ )

   lowerCamelCase__						       =      Aer.get_backend("aer_simulator" )
   lowerCamelCase__						       =      execute(A__						,     A__						,     shots=1000 )

   return job.result().get_counts(A__ )


if __name__ == "__main__":
     print(F'''Counts for classical state send: {superdense_coding(1,1)}''')




