


import logging
import os
import threading
import time


try:
   import warnings
except ImportError:
   UpperCAmelCase      =   None

try:
   import msvcrt
except ImportError:
   UpperCAmelCase      =   None

try:
   import fcntl
except ImportError:
   UpperCAmelCase      =   None


# Backward compatibility
# ------------------------------------------------
try:
   TimeoutError
except NameError:
   UpperCAmelCase      =   OSError


# Data
# ------------------------------------------------
UpperCAmelCase      =   [
    """Timeout""",
    """BaseFileLock""",
    """WindowsFileLock""",
    """UnixFileLock""",
    """SoftFileLock""",
    """FileLock""",
]

UpperCAmelCase      =   """3.0.12"""


UpperCAmelCase      =   None






def 	__lowerCAmelCase   ()->  List[Any]:




      """simple docstring"""

      global _logger
      snake_case_	=				_logger or logging.getLogger(__name__ )
      return _logger







class lowerCAmelCase_						(			lowerCamelCase__	):

 '''simple docstring'''

 def __init__(     self		,				_UpperCAmelCase ):
       snake_case_	=				lock_file
       return None





 def __str__(     self ):
       snake_case_	=				F'''The file lock \'{self.lock_file}\' could not be acquired.'''
       return temp







class lowerCAmelCase_						:

 '''simple docstring'''

 def __init__(     self		,				_UpperCAmelCase ):
       snake_case_	=				lock
       return None



 def __enter__(     self ):
       return self.lock





 def __exit__(     self		,				_UpperCAmelCase		,				_UpperCAmelCase		,				_UpperCAmelCase ):
       self.lock.release()
       return None







class lowerCAmelCase_						:

 '''simple docstring'''

 def __init__(     self		,				_UpperCAmelCase		,				_UpperCAmelCase=-1		,				_UpperCAmelCase=None ):
       snake_case_	=				max_filename_length if max_filename_length is not None else 2_55
       # Hash the filename if it's too long
       snake_case_	=				self.hash_filename_if_too_long(_UpperCAmelCase		,				_UpperCAmelCase )
       # The path to the lock file.
       snake_case_	=				lock_file

       # The file descriptor for the *_lock_file* as it is returned by the
       # os.open() function.
       # This file lock is only NOT None, if the object currently holds the
       # lock.
       snake_case_	=				None

       # The default timeout value.
       snake_case_	=				timeout

       # We use this lock primarily for the lock counter.
       snake_case_	=				threading.Lock()

       # The lock counter is used for implementing the nested locking
       # mechanism. Whenever the lock is acquired, the counter is increased and
       # the lock is only released, when this value is 0 again.
       snake_case_	=				0
       return None



 @property
 def 						UpperCamelCase__					(     self ):
       return self._lock_file



 @property
 def 						UpperCamelCase__					(     self ):
       return self._timeout



 @timeout.setter
 def 						UpperCamelCase__					(     self		,				_UpperCAmelCase ):
       snake_case_	=				float(_UpperCAmelCase )
       return None



 def 						UpperCamelCase__					(     self ):
       raise NotImplementedError()



 def 						UpperCamelCase__					(     self ):
       raise NotImplementedError()



 @property
 def 						UpperCamelCase__					(     self ):
       return self._lock_file_fd is not None



 def 						UpperCamelCase__					(     self		,				_UpperCAmelCase=None		,				_UpperCAmelCase=0.05 ):
       # Use the default timeout, if no timeout is provided.
       if timeout is None:
             snake_case_	=				self.timeout

       # Increment the number right at the beginning.
       # We can still undo it, if something fails.
       with self._thread_lock:
             self._lock_counter += 1

       snake_case_	=				id(self )
       snake_case_	=				self._lock_file
       snake_case_	=				time.time()
       try:
             while True:
                   with self._thread_lock:
                         if not self.is_locked:
                               logger().debug(F'''Attempting to acquire lock {lock_id} on {lock_filename}''' )
                               self._acquire()

                   if self.is_locked:
                         logger().debug(F'''Lock {lock_id} acquired on {lock_filename}''' )
                         break
                   elif timeout >= 0 and time.time() - start_time > timeout:
                         logger().debug(F'''Timeout on acquiring lock {lock_id} on {lock_filename}''' )
                         raise Timeout(self._lock_file )
                   else:
                         logger().debug(
                             F'''Lock {lock_id} not acquired on {lock_filename}, waiting {poll_intervall} seconds ...''' )
                         time.sleep(_UpperCAmelCase )
       except:  # noqa
             # Something did go wrong, so decrement the counter.
             with self._thread_lock:
                   snake_case_	=				max(0		,				self._lock_counter - 1 )

             raise
       return _Acquire_ReturnProxy(lock=self )



 def 						UpperCamelCase__					(     self		,				_UpperCAmelCase=False ):
       with self._thread_lock:
             if self.is_locked:
                   self._lock_counter -= 1

                   if self._lock_counter == 0 or force:
                         snake_case_	=				id(self )
                         snake_case_	=				self._lock_file

                         logger().debug(F'''Attempting to release lock {lock_id} on {lock_filename}''' )
                         self._release()
                         snake_case_	=				0
                         logger().debug(F'''Lock {lock_id} released on {lock_filename}''' )

       return None



 def __enter__(     self ):
       self.acquire()
       return self



 def __exit__(     self		,				_UpperCAmelCase		,				_UpperCAmelCase		,				_UpperCAmelCase ):
       self.release()
       return None



 def __del__(     self ):
       self.release(force=_UpperCAmelCase )
       return None





 def 						UpperCamelCase__					(     self		,				_UpperCAmelCase		,				_UpperCAmelCase ):
       snake_case_	=				os.path.basename(_UpperCAmelCase )
       if len(_UpperCAmelCase ) > max_length and max_length > 0:
             snake_case_	=				os.path.dirname(_UpperCAmelCase )
             snake_case_	=				str(hash(_UpperCAmelCase ) )
             snake_case_	=				filename[: max_length - len(_UpperCAmelCase ) - 8] + '''...''' + hashed_filename + '''.lock'''
             return os.path.join(_UpperCAmelCase		,				_UpperCAmelCase )
       else:
             return path







class lowerCAmelCase_						(			lowerCamelCase__	):

 '''simple docstring'''

 def __init__(     self		,				_UpperCAmelCase		,				_UpperCAmelCase=-1		,				_UpperCAmelCase=None ):
       from .file_utils import relative_to_absolute_path

       super().__init__(_UpperCAmelCase		,				timeout=_UpperCAmelCase		,				max_filename_length=_UpperCAmelCase )
       snake_case_	=				'''\\\\?\\''' + relative_to_absolute_path(self.lock_file )



 def 						UpperCamelCase__					(     self ):
       snake_case_	=				os.O_RDWR | os.O_CREAT | os.O_TRUNC

       try:
             snake_case_	=				os.open(self._lock_file		,				_UpperCAmelCase )
       except OSError:
             pass
       else:
             try:
                   msvcrt.locking(_UpperCAmelCase		,				msvcrt.LK_NBLCK		,				1 )
             except OSError:
                   os.close(_UpperCAmelCase )
             else:
                   snake_case_	=				fd
       return None





 def 						UpperCamelCase__					(     self ):
       snake_case_	=				self._lock_file_fd
       snake_case_	=				None
       msvcrt.locking(_UpperCAmelCase		,				msvcrt.LK_UNLCK		,				1 )
       os.close(_UpperCAmelCase )

       try:
             os.remove(self._lock_file )
       # Probably another instance of the application
       # that acquired the file lock.
       except OSError:
             pass
       return None







class lowerCAmelCase_						(			lowerCamelCase__	):

 '''simple docstring'''

 def __init__(     self		,				_UpperCAmelCase		,				_UpperCAmelCase=-1		,				_UpperCAmelCase=None ):
       snake_case_	=				os.statvfs(os.path.dirname(_UpperCAmelCase ) ).f_namemax
       super().__init__(_UpperCAmelCase		,				timeout=_UpperCAmelCase		,				max_filename_length=_UpperCAmelCase )



 def 						UpperCamelCase__					(     self ):
       snake_case_	=				os.O_RDWR | os.O_CREAT | os.O_TRUNC
       snake_case_	=				os.open(self._lock_file		,				_UpperCAmelCase )

       try:
             fcntl.flock(_UpperCAmelCase		,				fcntl.LOCK_EX | fcntl.LOCK_NB )
       except OSError:
             os.close(_UpperCAmelCase )
       else:
             snake_case_	=				fd
       return None





 def 						UpperCamelCase__					(     self ):
       # Do not remove the lockfile:
       #
       #   https://github.com/benediktschmitt/py-filelock/issues/31
       #   https://stackoverflow.com/questions/17708885/flock-removing-locked-file-without-race-condition
       snake_case_	=				self._lock_file_fd
       snake_case_	=				None
       fcntl.flock(_UpperCAmelCase		,				fcntl.LOCK_UN )
       os.close(_UpperCAmelCase )
       return None







class lowerCAmelCase_						(			lowerCamelCase__	):

 '''simple docstring'''

 def 						UpperCamelCase__					(     self ):
       snake_case_	=				os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_TRUNC
       try:
             snake_case_	=				os.open(self._lock_file		,				_UpperCAmelCase )
       except OSError:
             pass
       else:
             snake_case_	=				fd
       return None





 def 						UpperCamelCase__					(     self ):
       os.close(self._lock_file_fd )
       snake_case_	=				None

       try:
             os.remove(self._lock_file )
       # The file is already deleted and that's what we want.
       except OSError:
             pass
       return None





UpperCAmelCase      =   None

if msvcrt:
   UpperCAmelCase      =   WindowsFileLock
elif fcntl:
   UpperCAmelCase      =   UnixFileLock
else:
   UpperCAmelCase      =   SoftFileLock

   if warnings is not None:
      warnings.warn("""only soft file lock is available""")



from __future__ import annotations

import time

UpperCAmelCase      =   list[tuple[int, int]]

UpperCAmelCase      =   [
    [0, 0, 0, 0, 0, 0, 0],
    [0, 1, 0, 0, 0, 0, 0],  # 0 are free path whereas 1's are obstacles
    [0, 0, 0, 0, 0, 0, 0],
    [0, 0, 1, 0, 0, 0, 0],
    [1, 0, 1, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 1, 0, 0],
]

UpperCAmelCase      =   [[-1, 0], [0, -1], [1, 0], [0, 1]]  # up, left, down, right







class lowerCAmelCase_						:

 '''simple docstring'''

 def __init__(     self		,				_UpperCAmelCase		,				_UpperCAmelCase		,				_UpperCAmelCase		,				_UpperCAmelCase		,				_UpperCAmelCase ):
       snake_case_	=				pos_x
       snake_case_	=				pos_y
       snake_case_	=				(pos_y, pos_x)
       snake_case_	=				goal_x
       snake_case_	=				goal_y
       snake_case_	=				parent







class lowerCAmelCase_						:

 '''simple docstring'''

 def __init__(     self		,				_UpperCAmelCase		,				_UpperCAmelCase ):
       snake_case_	=				Node(start[1]		,				start[0]		,				goal[1]		,				goal[0]		,				_UpperCAmelCase )
       snake_case_	=				Node(goal[1]		,				goal[0]		,				goal[1]		,				goal[0]		,				_UpperCAmelCase )

       snake_case_	=				[self.start]
       snake_case_	=				False



 def 						UpperCamelCase__					(     self ):
       while self.node_queue:
             snake_case_	=				self.node_queue.pop(0 )

             if current_node.pos == self.target.pos:
                   snake_case_	=				True
                   return self.retrace_path(_UpperCAmelCase )

             snake_case_	=				self.get_successors(_UpperCAmelCase )

             for node in successors:
                   self.node_queue.append(_UpperCAmelCase )

       if not self.reached:
             return [self.start.pos]
       return None



 def 						UpperCamelCase__					(     self		,				_UpperCAmelCase ):
       snake_case_	=				[]
       for action in delta:
             snake_case_	=				parent.pos_x + action[1]
             snake_case_	=				parent.pos_y + action[0]
             if not (0 <= pos_x <= len(grid[0] ) - 1 and 0 <= pos_y <= len(_UpperCAmelCase ) - 1):
                   continue

             if grid[pos_y][pos_x] != 0:
                   continue

             successors.append(
                 Node(_UpperCAmelCase		,				_UpperCAmelCase		,				self.target.pos_y		,				self.target.pos_x		,				_UpperCAmelCase ) )
       return successors





 def 						UpperCamelCase__					(     self		,				_UpperCAmelCase ):
       snake_case_	=				node
       snake_case_	=				[]
       while current_node is not None:
             path.append((current_node.pos_y, current_node.pos_x) )
             snake_case_	=				current_node.parent
       path.reverse()
       return path







class lowerCAmelCase_						:

 '''simple docstring'''

 def __init__(     self		,				_UpperCAmelCase		,				_UpperCAmelCase ):
       snake_case_	=				BreadthFirstSearch(_UpperCAmelCase		,				_UpperCAmelCase )
       snake_case_	=				BreadthFirstSearch(_UpperCAmelCase		,				_UpperCAmelCase )
       snake_case_	=				False



 def 						UpperCamelCase__					(     self ):
       while self.fwd_bfs.node_queue or self.bwd_bfs.node_queue:
             snake_case_	=				self.fwd_bfs.node_queue.pop(0 )
             snake_case_	=				self.bwd_bfs.node_queue.pop(0 )

             if current_bwd_node.pos == current_fwd_node.pos:
                   snake_case_	=				True
                   return self.retrace_bidirectional_path(
                       _UpperCAmelCase		,				_UpperCAmelCase )

             snake_case_	=				current_bwd_node
             snake_case_	=				current_fwd_node

             snake_case_	=				{
                 self.fwd_bfs: self.fwd_bfs.get_successors(_UpperCAmelCase ),
                 self.bwd_bfs: self.bwd_bfs.get_successors(_UpperCAmelCase ),
             }

             for bfs in [self.fwd_bfs, self.bwd_bfs]:
                   for node in successors[bfs]:
                         bfs.node_queue.append(_UpperCAmelCase )

       if not self.reached:
             return [self.fwd_bfs.start.pos]
       return None





 def 						UpperCamelCase__					(     self		,				_UpperCAmelCase		,				_UpperCAmelCase ):
       snake_case_	=				self.fwd_bfs.retrace_path(_UpperCAmelCase )
       snake_case_	=				self.bwd_bfs.retrace_path(_UpperCAmelCase )
       bwd_path.pop()
       bwd_path.reverse()
       snake_case_	=				fwd_path + bwd_path
       return path


if __name__ == "__main__":
   # all coordinates are given in format [y,x]
   import doctest

   doctest.testmod()
   UpperCAmelCase      =   (0, 0)
   UpperCAmelCase      =   (len(grid) - 1, len(grid[0]) - 1)
   for elem in grid:
      print(elem)

   UpperCAmelCase      =   time.time()
   UpperCAmelCase      =   BreadthFirstSearch(init, goal)
   UpperCAmelCase      =   bfs.search()
   UpperCAmelCase      =   time.time() - start_bfs_time

   print("""Unidirectional BFS computation time : """, bfs_time)

   UpperCAmelCase      =   time.time()
   UpperCAmelCase      =   BidirectionalBreadthFirstSearch(init, goal)
   UpperCAmelCase      =   bd_bfs.search()
   UpperCAmelCase      =   time.time() - start_bd_bfs_time

   print("""Bidirectional BFS computation time : """, bd_bfs_time)