

"""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

							__UpperCamelCase  :      int							      =		True
except ImportError:
							__UpperCamelCase  :      Tuple							      =		False


try:
							from torch.hub import _get_torch_home

							__UpperCamelCase  :      List[str]							      =		_get_torch_home()
except ImportError:
							__UpperCamelCase  :      Tuple							      =		os.path.expanduser(
							    os.getenv('''TORCH_HOME''', os.path.join(os.getenv('''XDG_CACHE_HOME''', '''~/.cache'''), '''torch'''))
							)

__UpperCamelCase  :      Optional[int]							      =		os.path.join(torch_cache_home, '''transformers''')

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

def   __SCREAMING_SNAKE_CASE  (      A_=OBJECTS						,     A_=ATTRIBUTES ):
	lowerCAmelCase__	:						Dict  				=	[]
	with open(A_ ) as f:
		for object in f.readlines():
			vg_classes.append(object.split(''',''' )[0].lower().strip() )

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

def   __SCREAMING_SNAKE_CASE  (      A_ ):
	lowerCAmelCase__	:						str  				=	OrderedDict()
	with open(A_						,     '''rb''' ) as f:
		lowerCAmelCase__	:						List[str]  				=	pkl.load(A_ )['''model''']
	for k in copy.deepcopy(list(ckp.keys() ) ):
		lowerCAmelCase__	:						Dict  				=	ckp.pop(A_ )
		if isinstance(A_						,     np.ndarray ):
			lowerCAmelCase__	:						List[str]  				=	torch.tensor(A_ )
		else:
			assert isinstance(A_						,     torch.tensor ), type(A_ )
		lowerCAmelCase__	:						int  				=	v
	return r







class 				SCREAMING_SNAKE_CASE					:






					"""simple docstring"""



					lowercase__				 =       {}







					def __init__(       self			:				Dict   ,lowercase_			:				dict   ,lowercase_			:				str = "root"   ,lowercase_			:				List[str]=0		):
						lowerCAmelCase__	:						List[Any]  				=	name
						lowerCAmelCase__	:						Optional[int]  				=	level
						lowerCAmelCase__	:						int  				=	{}
						for k, v in dictionary.items():
							if v is None:
								raise ValueError()
							lowerCAmelCase__	:						List[Any]  				=	copy.deepcopy(lowercase_		)
							lowerCAmelCase__	:						Union[str, Any]  				=	copy.deepcopy(lowercase_		)
							if isinstance(lowercase_   ,lowercase_		):
								lowerCAmelCase__	:						str  				=	Config(lowercase_   ,name=lowercase_   ,level=level + 1		)
							lowerCAmelCase__	:						List[Any]  				=	v
							setattr(self   ,lowercase_   ,lowercase_		)

						lowerCAmelCase__	:						int  				=	d







					def __repr__(       self			:				int		):
						return str(list((self._pointer.keys())		)		)







					def __setattr__(       self			:				Any   ,lowercase_			:				Union[str, Any]   ,lowercase_			:				Optional[int]		):
						lowerCAmelCase__	:						List[Any]  				=	val
						lowerCAmelCase__	:						str  				=	val
						lowerCAmelCase__	:						Optional[Any]  				=	key.split('''.'''		)
						lowerCAmelCase__	:						str  				=	len(lowercase_		) - 1
						lowerCAmelCase__	:						List[Any]  				=	self._pointer
						if len(lowercase_		) > 1:
							for i, l in enumerate(lowercase_		):
								if hasattr(self   ,lowercase_		) and isinstance(getattr(self   ,lowercase_		)   ,lowercase_		):
									setattr(getattr(self   ,lowercase_		)   ,'''.'''.join(levels[i:]		)   ,lowercase_		)
								if l == last_level:
									lowerCAmelCase__	:						Union[str, Any]  				=	val
								else:
									lowerCAmelCase__	:						List[Any]  				=	pointer[l]







					def        __lowerCAmelCase (       self			:				List[str]		):
						return self._pointer







					def        __lowerCAmelCase (       self			:				Optional[Any]   ,lowercase_			:				Optional[int]   ,lowercase_			:				Dict		):
						with open(F'{file_name}'   ,'''w'''		) as stream:
							dump(lowercase_   ,lowercase_		)







					def        __lowerCAmelCase (       self			:				Optional[Any]   ,lowercase_			:				str   ,lowercase_			:				List[Any]		):
						with open(F'{file_name}'   ,'''w'''		) as stream:
							json.dump(lowercase_   ,lowercase_		)







					@staticmethod
					def        __lowerCAmelCase (       lowercase_			:				Any		):
						with open(lowercase_		) as stream:
							lowerCAmelCase__	:						int  				=	load(lowercase_   ,Loader=lowercase_		)
						return data







					def __str__(       self			:				Tuple		):
						lowerCAmelCase__	:						List[Any]  				=	'''    '''
						if self._name != "root":
							lowerCAmelCase__	:						Dict  				=	F'{t * (self._level-1)}{self._name}:\n'
						else:
							lowerCAmelCase__	:						Union[str, Any]  				=	''''''
						lowerCAmelCase__	:						List[str]  				=	self._level
						for i, (k, v) in enumerate(self._pointer.items()		):
							if isinstance(lowercase_   ,lowercase_		):
								r += F'{t * (self._level)}{v}\n'
								self._level += 1
							else:
								r += F'{t * (self._level)}{k}: {v} ({type(lowercase_		).__name__})\n'
							lowerCAmelCase__	:						Union[str, Any]  				=	level
						return r[:-1]







					@classmethod
					def        __lowerCAmelCase (       cls			:				Optional[int]   ,lowercase_			:				str   ,**lowercase_			:				str		):
						lowerCAmelCase__				,lowerCAmelCase__	:						Union[str, Any]  				=	cls.get_config_dict(lowercase_   ,**lowercase_		)
						return cls(lowercase_		)







					@classmethod
					def        __lowerCAmelCase (       cls			:				Tuple   ,lowercase_			:				str   ,**lowercase_			:				int		):
						lowerCAmelCase__	:						Union[str, Any]  				=	kwargs.pop('''cache_dir'''   ,lowercase_		)
						lowerCAmelCase__	:						int  				=	kwargs.pop('''force_download'''   ,lowercase_		)
						lowerCAmelCase__	:						Any  				=	kwargs.pop('''resume_download'''   ,lowercase_		)
						lowerCAmelCase__	:						List[Any]  				=	kwargs.pop('''proxies'''   ,lowercase_		)
						lowerCAmelCase__	:						List[str]  				=	kwargs.pop('''local_files_only'''   ,lowercase_		)

						if os.path.isdir(lowercase_		):
							lowerCAmelCase__	:						Optional[Any]  				=	os.path.join(lowercase_   ,lowercase_		)
						elif os.path.isfile(lowercase_		) or is_remote_url(lowercase_		):
							lowerCAmelCase__	:						Tuple  				=	pretrained_model_name_or_path
						else:
							lowerCAmelCase__	:						Dict  				=	hf_bucket_url(lowercase_   ,filename=lowercase_   ,use_cdn=lowercase_		)

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

							lowerCAmelCase__	:						Tuple  				=	Config.load_yaml(lowercase_		)

						except EnvironmentError:
							lowerCAmelCase__	:						Optional[int]  				=	'''Can\'t load config for'''
							raise EnvironmentError(lowercase_		)

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

						return Config.load_yaml(lowercase_		), kwargs

def   __SCREAMING_SNAKE_CASE  (      A_ ):
	lowerCAmelCase__	:						Optional[Any]  				=	torch.load('''dump.pt'''						,     map_location=in_tensor.device )
	lowerCAmelCase__	:						Optional[Any]  				=	in_tensor.numpy()
	lowerCAmelCase__	:						str  				=	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() )*1_00:.4f} %'
	    " element-wise mismatch"
	)
	raise Exception('''tensors are all good''' )

	# Hugging face functions below

def   __SCREAMING_SNAKE_CASE  (      A_ ):
	lowerCAmelCase__	:						Optional[int]  				=	urlparse(A_ )
	return parsed.scheme in ("http", "https")

def   __SCREAMING_SNAKE_CASE  (      A_						,     A_						,     A_=True ):
	lowerCAmelCase__	:						Optional[int]  				=	CLOUDFRONT_DISTRIB_PREFIX if use_cdn else S3_BUCKET_PREFIX
	lowerCAmelCase__	:						Dict  				=	'''/''' not in model_id
	if legacy_format:
		return f'{endpoint}/{model_id}-{filename}'
	else:
		return f'{endpoint}/{model_id}/{filename}'

def   __SCREAMING_SNAKE_CASE  (      A_						,     A_						,     A_=None						,     A_=0						,     A_=None						,     ):
	lowerCAmelCase__	:						Union[str, Any]  				=	'''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
	lowerCAmelCase__	:						int  				=	{'''user-agent''': ua}
	if resume_size > 0:
		lowerCAmelCase__	:						Optional[int]  				=	'''bytes=%d-''' % (resume_size,)
	lowerCAmelCase__	:						Union[str, Any]  				=	requests.get(A_						,     stream=A_						,     proxies=A_						,     headers=A_ )
	if response.status_code == 4_16:  # Range not satisfiable
		return
	lowerCAmelCase__	:						Optional[Any]  				=	response.headers.get('''Content-Length''' )
	lowerCAmelCase__	:						Optional[int]  				=	resume_size + int(A_ ) if content_length is not None else None
	lowerCAmelCase__	:						int  				=	tqdm(
	    unit='''B'''						,     unit_scale=A_						,     total=A_						,     initial=A_						,     desc='''Downloading'''						,     )
	for chunk in response.iter_content(chunk_size=10_24 ):
		if chunk:  # filter out keep-alive new chunks
			progress.update(len(A_ ) )
			temp_file.write(A_ )
	progress.close()

def   __SCREAMING_SNAKE_CASE  (      A_						,     A_=None						,     A_=False						,     A_=None						,     A_=10						,     A_=False						,     A_=None						,     A_=False						,     ):
	if cache_dir is None:
		lowerCAmelCase__	:						List[str]  				=	TRANSFORMERS_CACHE
	if isinstance(A_						,     A_ ):
		lowerCAmelCase__	:						int  				=	str(A_ )

	os.makedirs(A_						,     exist_ok=A_ )

	lowerCAmelCase__	:						Dict  				=	None
	if not local_files_only:
		try:
			lowerCAmelCase__	:						int  				=	requests.head(A_						,     allow_redirects=A_						,     proxies=A_						,     timeout=A_ )
			if response.status_code == 2_00:
				lowerCAmelCase__	:						List[str]  				=	response.headers.get('''ETag''' )
		except (EnvironmentError, requests.exceptions.Timeout):
			# etag is already None
			pass

	lowerCAmelCase__	:						Optional[Any]  				=	url_to_filename(A_						,     A_ )

	# get cache path to put the file
	lowerCAmelCase__	:						str  				=	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:
			lowerCAmelCase__	:						Any  				=	[
			    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.
	lowerCAmelCase__	:						Optional[int]  				=	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:
			lowerCAmelCase__	:						List[str]  				=	cache_path + '''.incomplete'''

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

			lowerCAmelCase__	:						List[Any]  				=	_resumable_file_manager
			if os.path.exists(A_ ):
				lowerCAmelCase__	:						int  				=	os.stat(A_ ).st_size
			else:
				lowerCAmelCase__	:						Optional[int]  				=	0
		else:
			lowerCAmelCase__	:						Optional[Any]  				=	partial(tempfile.NamedTemporaryFile						,     dir=A_						,     delete=A_ )
			lowerCAmelCase__	:						int  				=	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_ )

		lowerCAmelCase__	:						Any  				=	{'''url''': url, '''etag''': etag}
		lowerCAmelCase__	:						Union[str, Any]  				=	cache_path + '''.json'''
		with open(A_						,     '''w''' ) as meta_file:
			json.dump(A_						,     A_ )

	return cache_path

def   __SCREAMING_SNAKE_CASE  (      A_						,     A_=None ):
	lowerCAmelCase__	:						int  				=	url.encode('''utf-8''' )
	lowerCAmelCase__	:						int  				=	shaaaa(A_ )
	lowerCAmelCase__	:						Optional[int]  				=	url_hash.hexdigest()

	if etag:
		lowerCAmelCase__	:						int  				=	etag.encode('''utf-8''' )
		lowerCAmelCase__	:						Dict  				=	shaaaa(A_ )
		filename += "." + etag_hash.hexdigest()

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

	return filename

def   __SCREAMING_SNAKE_CASE  (      A_						,     A_=None						,     A_=False						,     A_=None						,     A_=False						,     A_=None						,     A_=False						,     A_=False						,     A_=False						,     ):
	if cache_dir is None:
		lowerCAmelCase__	:						Optional[Any]  				=	TRANSFORMERS_CACHE
	if isinstance(A_						,     A_ ):
		lowerCAmelCase__	:						List[Any]  				=	str(A_ )
	if isinstance(A_						,     A_ ):
		lowerCAmelCase__	:						str  				=	str(A_ )

	if is_remote_url(A_ ):
		# URL, so get it from the cache (downloading if necessary)
		lowerCAmelCase__	:						Any  				=	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.
		lowerCAmelCase__	:						List[Any]  				=	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/"
		lowerCAmelCase__				,lowerCAmelCase__	:						Optional[int]  				=	os.path.split(A_ )
		lowerCAmelCase__	:						Union[str, Any]  				=	output_file.replace('''.'''						,     '''-''' ) + '''-extracted'''
		lowerCAmelCase__	:						Tuple  				=	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
		lowerCAmelCase__	:						int  				=	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_ ):
				lowerCAmelCase__	:						str  				=	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   __SCREAMING_SNAKE_CASE  (      A_						,     A_="," ):
	assert isinstance(A_						,     A_ )
	if os.path.isfile(A_ ):
		with open(A_ ) as f:
			lowerCAmelCase__	:						Optional[int]  				=	eval(f.read() )
	else:
		lowerCAmelCase__	:						Dict  				=	requests.get(A_ )
		try:
			lowerCAmelCase__	:						List[Any]  				=	requests.json()
		except Exception:
			lowerCAmelCase__	:						Optional[Any]  				=	req.content.decode()
			assert data is not None, "could not connect"
			try:
				lowerCAmelCase__	:						Dict  				=	eval(A_ )
			except Exception:
				lowerCAmelCase__	:						int  				=	data.split('''\n''' )
		req.close()
	return data

def   __SCREAMING_SNAKE_CASE  (      A_ ):
	lowerCAmelCase__	:						Optional[Any]  				=	requests.get(A_ )
	lowerCAmelCase__	:						Union[str, Any]  				=	np.array(Image.open(BytesIO(response.content ) ) )
	return img

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

def   __SCREAMING_SNAKE_CASE  (      ):
	print(f'{os.path.abspath(os.path.join(A_						,     os.pardir ) )}/demo.ipynb' )

def   __SCREAMING_SNAKE_CASE  (      A_						,     A_="RGB" ):
	assert isinstance(A_						,     A_ )
	if os.path.isfile(A_ ):
		lowerCAmelCase__	:						Optional[Any]  				=	cva.imread(A_ )
	else:
		lowerCAmelCase__	:						Union[str, Any]  				=	get_image_from_url(A_ )
		assert img is not None, f'could not connect to: {im}'
	lowerCAmelCase__	:						Union[str, Any]  				=	cva.cvtColor(A_						,     cva.COLOR_BGR2RGB )
	if input_format == "RGB":
		lowerCAmelCase__	:						Optional[int]  				=	img[:, :, ::-1]
	return img





def   __SCREAMING_SNAKE_CASE  (      A_						,     A_=1 ):
	return (images[i : i + batch] for i in range(0						,     len(A_ )						,     A_ ))







"""simple docstring"""





from collections import defaultdict
from math import ceil, sqrt

def   __SCREAMING_SNAKE_CASE  (      A_ = 1_00_00_00						,     A_ = 10 ):
	lowerCAmelCase__	:						defaultdict  				=	defaultdict(A_ )

	for outer_width in range(3						,     (t_limit // 4) + 2 ):
		if outer_width * outer_width > t_limit:
			lowerCAmelCase__	:						int  				=	max(
			    ceil(sqrt(outer_width * outer_width - t_limit ) )						,     1 )
		else:
			lowerCAmelCase__	:						Tuple  				=	1

		hole_width_lower_bound += (outer_width - hole_width_lower_bound) % 2

		for hole_width in range(A_						,     outer_width - 1						,     2 ):
			count[outer_width * outer_width - hole_width * hole_width] += 1

	return sum(1 for n in count.values() if 1 <= n <= 10 )


if __name__ == "__main__":
							print(F'''{solution() = }''')




