

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

       _SCREAMING_SNAKE_CASE  :						Optional[int]         =    True
except ImportError:
       _SCREAMING_SNAKE_CASE  :						List[str]         =    False


try:
       from torch.hub import _get_torch_home

       _SCREAMING_SNAKE_CASE  :						Optional[int]         =    _get_torch_home()
except ImportError:
       _SCREAMING_SNAKE_CASE  :						Optional[int]         =    os.path.expanduser(
           os.getenv('''TORCH_HOME''', os.path.join(os.getenv('''XDG_CACHE_HOME''', '''~/.cache'''), '''torch'''))
       )

_SCREAMING_SNAKE_CASE  :						List[Any]         =    os.path.join(torch_cache_home, '''transformers''')

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





     '''simple docstring'''




     SCREAMING_SNAKE_CASE__					=					[]
     with open(_A       ) as f:
          for object in f.readlines():
               vg_classes.append(object.split(''','''       )[0].lower().strip()       )

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





     '''simple docstring'''




     SCREAMING_SNAKE_CASE__					=					OrderedDict()
     with open(_A   ,	'''rb'''       ) as f:
          SCREAMING_SNAKE_CASE__					=					pkl.load(_A       )['''model''']
     for k in copy.deepcopy(list(ckp.keys()       )       ):
          SCREAMING_SNAKE_CASE__					=					ckp.pop(_A       )
          if isinstance(_A   ,	np.ndarray       ):
               SCREAMING_SNAKE_CASE__					=					torch.tensor(_A       )
          else:
               assert isinstance(_A   ,	torch.tensor       ), type(_A       )
          SCREAMING_SNAKE_CASE__					=					v
     return r






class  UpperCAmelCase__	:






  """simple docstring"""


  a     =      {}






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

       SCREAMING_SNAKE_CASE__					=					d






  def __repr__(							self		:	List[Any]      )	->							Optional[int]:
       return str(list((self._pointer.keys())      )      )






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






  def    lowercase_	(							self		:	Optional[int]      )	->							List[str]:
       return self._pointer






  def    lowercase_	(							self		:	Union[str, Any]			,     __lowerCamelCase		:	int			,     __lowerCamelCase		:	int      )	->							Tuple:
       with open(f'''{file_name}'''			,     '''w'''      ) as stream:
            dump(__lowerCamelCase			,     __lowerCamelCase      )






  def    lowercase_	(							self		:	List[Any]			,     __lowerCamelCase		:	Optional[Any]			,     __lowerCamelCase		:	Optional[Any]      )	->							List[Any]:
       with open(f'''{file_name}'''			,     '''w'''      ) as stream:
            json.dump(__lowerCamelCase			,     __lowerCamelCase      )






  @staticmethod
  def    lowercase_	(							__lowerCamelCase		:	Any      )	->							Tuple:
       with open(__lowerCamelCase      ) as stream:
            SCREAMING_SNAKE_CASE__					=					load(__lowerCamelCase			,     Loader=__lowerCamelCase      )
       return data






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






  @classmethod
  def    lowercase_	(							cls		:	Optional[Any]			,     __lowerCamelCase		:	str			,     **__lowerCamelCase		:	List[str]      )	->							Union[str, Any]:
       SCREAMING_SNAKE_CASE__,SCREAMING_SNAKE_CASE__					=					cls.get_config_dict(__lowerCamelCase			,     **__lowerCamelCase      )
       return cls(__lowerCamelCase      )







  @classmethod
  def    lowercase_	(							cls		:	List[str]			,     __lowerCamelCase		:	str			,     **__lowerCamelCase		:	Union[str, Any]      )	->							List[Any]:
       SCREAMING_SNAKE_CASE__					=					kwargs.pop('''cache_dir'''			,     __lowerCamelCase      )
       SCREAMING_SNAKE_CASE__					=					kwargs.pop('''force_download'''			,     __lowerCamelCase      )
       SCREAMING_SNAKE_CASE__					=					kwargs.pop('''resume_download'''			,     __lowerCamelCase      )
       SCREAMING_SNAKE_CASE__					=					kwargs.pop('''proxies'''			,     __lowerCamelCase      )
       SCREAMING_SNAKE_CASE__					=					kwargs.pop('''local_files_only'''			,     __lowerCamelCase      )

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

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

            SCREAMING_SNAKE_CASE__					=					Config.load_yaml(__lowerCamelCase      )

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

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

       return Config.load_yaml(__lowerCamelCase      ), kwargs



def        UpperCAmelCase_     (		_A       ):





     '''simple docstring'''




     SCREAMING_SNAKE_CASE__					=					torch.load('''dump.pt'''   ,	map_location=in_tensor.device       )
     SCREAMING_SNAKE_CASE__					=					in_tensor.numpy()
     SCREAMING_SNAKE_CASE__					=					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.0_1   ,	atol=0.1       ), (
         F'''{sum([1 for x in np.isclose(_A   ,	_A   ,	rtol=0.0_1   ,	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        UpperCAmelCase_     (		_A       ):





     '''simple docstring'''




     SCREAMING_SNAKE_CASE__					=					urlparse(_A       )
     return parsed.scheme in ("http", "https")
def        UpperCAmelCase_     (		_A   ,	_A   ,	_A=True       ):





     '''simple docstring'''




     SCREAMING_SNAKE_CASE__					=					CLOUDFRONT_DISTRIB_PREFIX if use_cdn else S3_BUCKET_PREFIX
     SCREAMING_SNAKE_CASE__					=					'''/''' not in model_id
     if legacy_format:
          return F'''{endpoint}/{model_id}-{filename}'''
     else:
          return F'''{endpoint}/{model_id}/{filename}'''
def        UpperCAmelCase_     (		_A   ,	_A   ,	_A=None   ,	_A=0   ,	_A=None   ,	):





     '''simple docstring'''




     SCREAMING_SNAKE_CASE__					=					'''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
     SCREAMING_SNAKE_CASE__					=					{'''user-agent''': ua}
     if resume_size > 0:
          SCREAMING_SNAKE_CASE__					=					'''bytes=%d-''' % (resume_size,)
     SCREAMING_SNAKE_CASE__					=					requests.get(_A   ,	stream=_A   ,	proxies=_A   ,	headers=_A       )
     if response.status_code == 4_16:  # Range not satisfiable
          return
     SCREAMING_SNAKE_CASE__					=					response.headers.get('''Content-Length'''       )
     SCREAMING_SNAKE_CASE__					=					resume_size + int(_A       ) if content_length is not None else None
     SCREAMING_SNAKE_CASE__					=					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        UpperCAmelCase_     (		_A   ,	_A=None   ,	_A=False   ,	_A=None   ,	_A=10   ,	_A=False   ,	_A=None   ,	_A=False   ,	):





     '''simple docstring'''




     if cache_dir is None:
          SCREAMING_SNAKE_CASE__					=					TRANSFORMERS_CACHE
     if isinstance(_A   ,	_A       ):
          SCREAMING_SNAKE_CASE__					=					str(_A       )

     os.makedirs(_A   ,	exist_ok=_A       )

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

     SCREAMING_SNAKE_CASE__					=					url_to_filename(_A   ,	_A       )

     # get cache path to put the file
     SCREAMING_SNAKE_CASE__					=					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:
               SCREAMING_SNAKE_CASE__					=					[
                   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.
     SCREAMING_SNAKE_CASE__					=					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:
               SCREAMING_SNAKE_CASE__					=					cache_path + '''.incomplete'''

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

               SCREAMING_SNAKE_CASE__					=					_resumable_file_manager
               if os.path.exists(_A       ):
                    SCREAMING_SNAKE_CASE__					=					os.stat(_A       ).st_size
               else:
                    SCREAMING_SNAKE_CASE__					=					0
          else:
               SCREAMING_SNAKE_CASE__					=					partial(tempfile.NamedTemporaryFile   ,	dir=_A   ,	delete=_A       )
               SCREAMING_SNAKE_CASE__					=					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       )

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

     return cache_path
def        UpperCAmelCase_     (		_A   ,	_A=None       ):





     '''simple docstring'''




     SCREAMING_SNAKE_CASE__					=					url.encode('''utf-8'''       )
     SCREAMING_SNAKE_CASE__					=					shaaaa(_A       )
     SCREAMING_SNAKE_CASE__					=					url_hash.hexdigest()

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

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

     return filename
def        UpperCAmelCase_     (		_A   ,	_A=None   ,	_A=False   ,	_A=None   ,	_A=False   ,	_A=None   ,	_A=False   ,	_A=False   ,	_A=False   ,	):





     '''simple docstring'''




     if cache_dir is None:
          SCREAMING_SNAKE_CASE__					=					TRANSFORMERS_CACHE
     if isinstance(_A   ,	_A       ):
          SCREAMING_SNAKE_CASE__					=					str(_A       )
     if isinstance(_A   ,	_A       ):
          SCREAMING_SNAKE_CASE__					=					str(_A       )

     if is_remote_url(_A       ):
          # URL, so get it from the cache (downloading if necessary)
          SCREAMING_SNAKE_CASE__					=					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.
          SCREAMING_SNAKE_CASE__					=					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/"
          SCREAMING_SNAKE_CASE__,SCREAMING_SNAKE_CASE__					=					os.path.split(_A       )
          SCREAMING_SNAKE_CASE__					=					output_file.replace('''.'''   ,	'''-'''       ) + '''-extracted'''
          SCREAMING_SNAKE_CASE__					=					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
          SCREAMING_SNAKE_CASE__					=					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       ):
                    SCREAMING_SNAKE_CASE__					=					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        UpperCAmelCase_     (		_A   ,	_A=","       ):





     '''simple docstring'''




     assert isinstance(_A   ,	_A       )
     if os.path.isfile(_A       ):
          with open(_A       ) as f:
               SCREAMING_SNAKE_CASE__					=					eval(f.read()       )
     else:
          SCREAMING_SNAKE_CASE__					=					requests.get(_A       )
          try:
               SCREAMING_SNAKE_CASE__					=					requests.json()
          except Exception:
               SCREAMING_SNAKE_CASE__					=					req.content.decode()
               assert data is not None, "could not connect"
               try:
                    SCREAMING_SNAKE_CASE__					=					eval(_A       )
               except Exception:
                    SCREAMING_SNAKE_CASE__					=					data.split('''\n'''       )
          req.close()
     return data
def        UpperCAmelCase_     (		_A       ):





     '''simple docstring'''




     SCREAMING_SNAKE_CASE__					=					requests.get(_A       )
     SCREAMING_SNAKE_CASE__					=					np.array(Image.open(BytesIO(response.content       )       )       )
     return img
def        UpperCAmelCase_     (		_A       ):





     '''simple docstring'''




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





     '''simple docstring'''




     print(F'''{os.path.abspath(os.path.join(_A   ,	os.pardir       )       )}/demo.ipynb'''       )
def        UpperCAmelCase_     (		_A   ,	_A="RGB"       ):





     '''simple docstring'''




     assert isinstance(_A   ,	_A       )
     if os.path.isfile(_A       ):
          SCREAMING_SNAKE_CASE__					=					cva.imread(_A       )
     else:
          SCREAMING_SNAKE_CASE__					=					get_image_from_url(_A       )
          assert img is not None, F'''could not connect to: {im}'''
     SCREAMING_SNAKE_CASE__					=					cva.cvtColor(_A   ,	cva.COLOR_BGR2RGB       )
     if input_format == "RGB":
          SCREAMING_SNAKE_CASE__					=					img[:, :, ::-1]
     return img







def        UpperCAmelCase_     (		_A   ,	_A=1       ):





     '''simple docstring'''




     return (images[i : i + batch] for i in range(0   ,	len(_A       )   ,	_A       ))





from collections.abc import Callable

import numpy as np
def        UpperCAmelCase_     (		_A   ,	_A   ,	_A   ,	_A   ,	_A       ):





     '''simple docstring'''




     SCREAMING_SNAKE_CASE__					=					int(np.ceil((x_end - xa) / step_size       )       )
     SCREAMING_SNAKE_CASE__					=					np.zeros((n + 1,)       )
     SCREAMING_SNAKE_CASE__					=					ya
     SCREAMING_SNAKE_CASE__					=					xa

     for k in range(_A       ):
          SCREAMING_SNAKE_CASE__					=					y[k] + step_size * ode_func(_A   ,	y[k]       )
          SCREAMING_SNAKE_CASE__					=					y[k] + (
              (step_size / 2) * (ode_func(_A   ,	y[k]       ) + ode_func(x + step_size   ,	_A       ))
          )
          x += step_size

     return y


if __name__ == "__main__":
       import doctest

       doctest.testmod()


