

# This code is adapted from OpenAI's release
# https://github.com/openai/human-eval/blob/master/human_eval/execution.py

import contextlib
import faulthandler
import io
import multiprocessing
import os
import platform
import signal
import tempfile






def    SCREAMING_SNAKE_CASE__       (  lowerCamelCase__	, lowerCamelCase__	, lowerCamelCase__	, lowerCamelCase__			)  ->     str:
	__lowerCamelCase				:				Optional[Any]					       = multiprocessing.Manager()
	__lowerCamelCase				:				str					       = manager.list()

	__lowerCamelCase				:				str					       = multiprocessing.Process(target=a__	, args=(check_program, result, timeout)			)
	p.start()
	p.join(timeout=timeout + 1			)
	if p.is_alive():
		p.kill()

	if not result:
		result.append('timed out'			)

	return {
	    "task_id": task_id,
	    "passed": result[0] == "passed",
	    "result": result[0],
	    "completion_id": completion_id,
	}






def    SCREAMING_SNAKE_CASE__       (  lowerCamelCase__	, lowerCamelCase__	, lowerCamelCase__			)  ->     List[Any]:
	with create_tempdir():
		# These system calls are needed when cleaning up tempdir.
		import os
		import shutil

		__lowerCamelCase				:				Optional[Any]					       = shutil.rmtree
		__lowerCamelCase				:				Union[str, Any]					       = os.rmdir
		__lowerCamelCase				:				Optional[int]					       = os.chdir

		# Disable functionalities that can make destructive changes to the test.
		reliability_guard()

		# Run program.
		try:
			__lowerCamelCase				:				Tuple					       = {}
			with swallow_io():
				with time_limit(a__			):
					exec(a__	, a__			)
			result.append('passed'			)
		except TimeoutException:
			result.append('timed out'			)
		except BaseException as e:
			result.append(F"failed: {e}"			)

		# Needed for cleaning up.
		__lowerCamelCase				:				int					       = rmtree
		__lowerCamelCase				:				Optional[Any]					       = rmdir
		__lowerCamelCase				:				str					       = chdir






@contextlib.contextmanager
def    SCREAMING_SNAKE_CASE__       (  lowerCamelCase__			)  ->     str:
	def signal_handler(lowerCamelCase__	, lowerCamelCase__			):
		raise TimeoutException('Timed out!'			)

	signal.setitimer(signal.ITIMER_REAL	, a__			)
	signal.signal(signal.SIGALRM	, a__			)
	try:
		yield
	finally:
		signal.setitimer(signal.ITIMER_REAL	, 0			)






@contextlib.contextmanager
def    SCREAMING_SNAKE_CASE__       (  )  ->     Tuple:
	__lowerCamelCase				:				str					       = WriteOnlyStringIO()
	with contextlib.redirect_stdout(a__			):
		with contextlib.redirect_stderr(a__			):
			with redirect_stdin(a__			):
				yield






@contextlib.contextmanager
def    SCREAMING_SNAKE_CASE__       (  )  ->     Tuple:
	with tempfile.TemporaryDirectory() as dirname:
		with chdir(a__			):
			yield dirname






class        A_		(       SCREAMING_SNAKE_CASE				):
							pass






class        A_		(       io.StringIO				):
							def     lowerCAmelCase     (		self		:			Any   ,*SCREAMING_SNAKE_CASE__		:			Optional[Any]   ,**SCREAMING_SNAKE_CASE__		:			List[str]):
								raise OSError
							def     lowerCAmelCase     (		self		:			List[str]   ,*SCREAMING_SNAKE_CASE__		:			Union[str, Any]   ,**SCREAMING_SNAKE_CASE__		:			str):
								raise OSError
							def     lowerCAmelCase     (		self		:			int   ,*SCREAMING_SNAKE_CASE__		:			List[str]   ,**SCREAMING_SNAKE_CASE__		:			int):
								raise OSError


							def     lowerCAmelCase     (		self		:			Dict   ,*SCREAMING_SNAKE_CASE__		:			Optional[Any]   ,**SCREAMING_SNAKE_CASE__		:			Optional[Any]):
								return False






class        A_		(       contextlib._RedirectStream				):  # type: ignore
							_UpperCAmelCase    :  Optional[Any]						      =      '''stdin'''






@contextlib.contextmanager
def    SCREAMING_SNAKE_CASE__       (  lowerCamelCase__			)  ->     List[Any]:
	if root == ".":
		yield
		return
	__lowerCamelCase				:				Optional[Any]					       = os.getcwd()
	os.chdir(a__			)
	try:
		yield
	except BaseException as exc:
		raise exc
	finally:
		os.chdir(a__			)






def    SCREAMING_SNAKE_CASE__       (  lowerCamelCase__=None			)  ->     Union[str, Any]:

	if maximum_memory_bytes is not None:
		import resource

		resource.setrlimit(resource.RLIMIT_AS	, (maximum_memory_bytes, maximum_memory_bytes)			)
		resource.setrlimit(resource.RLIMIT_DATA	, (maximum_memory_bytes, maximum_memory_bytes)			)
		if not platform.uname().system == "Darwin":
			resource.setrlimit(resource.RLIMIT_STACK	, (maximum_memory_bytes, maximum_memory_bytes)			)

	faulthandler.disable()

	import builtins

	__lowerCamelCase				:				Optional[Any]					       = None
	__lowerCamelCase				:				List[str]					       = None

	import os

	__lowerCamelCase				:				str					       = '1'

	__lowerCamelCase				:				Optional[int]					       = None
	__lowerCamelCase				:				Optional[int]					       = None
	__lowerCamelCase				:				Dict					       = None
	__lowerCamelCase				:				str					       = None
	__lowerCamelCase				:				Any					       = None
	__lowerCamelCase				:				Any					       = None
	__lowerCamelCase				:				Optional[Any]					       = None
	__lowerCamelCase				:				Any					       = None
	__lowerCamelCase				:				str					       = None
	__lowerCamelCase				:				str					       = None
	__lowerCamelCase				:				List[str]					       = None
	__lowerCamelCase				:				List[str]					       = None
	__lowerCamelCase				:				Dict					       = None
	__lowerCamelCase				:				int					       = None
	__lowerCamelCase				:				Optional[int]					       = None
	__lowerCamelCase				:				Optional[int]					       = None
	__lowerCamelCase				:				Union[str, Any]					       = None
	__lowerCamelCase				:				int					       = None
	__lowerCamelCase				:				int					       = None
	__lowerCamelCase				:				Tuple					       = None
	__lowerCamelCase				:				List[str]					       = None
	__lowerCamelCase				:				List[Any]					       = None
	__lowerCamelCase				:				Dict					       = None
	__lowerCamelCase				:				List[Any]					       = None
	__lowerCamelCase				:				List[str]					       = None
	__lowerCamelCase				:				List[Any]					       = None
	__lowerCamelCase				:				List[Any]					       = None

	import shutil

	__lowerCamelCase				:				Optional[int]					       = None
	__lowerCamelCase				:				Optional[int]					       = None
	__lowerCamelCase				:				List[Any]					       = None

	import subprocess

	__lowerCamelCase				:				Any					       = None  # type: ignore

	__lowerCamelCase				:				Optional[Any]					       = None

	import sys

	__lowerCamelCase				:				str					       = None
	__lowerCamelCase				:				Dict					       = None
	__lowerCamelCase				:				List[str]					       = None
	__lowerCamelCase				:				int					       = None
	__lowerCamelCase				:				Optional[Any]					       = None






import html

from ...feature_extraction_utils import BatchFeature, FeatureExtractionMixin
from ...utils import is_bsa_available, logging, requires_backends


if is_bsa_available():
					import bsa
					from bsa import BeautifulSoup


A     :	str    = logging.get_logger(__name__)







class 			__A( a			):




				def __init__(     self		,     **_snake_case				)    ->      List[Any]:


								'''simple docstring'''




								requires_backends(self		,     ['''bs4''']				)
								super().__init__(**_snake_case				)




				def 				SCREAMING_SNAKE_CASE_		(     self		,     _snake_case				)    ->      int:


								'''simple docstring'''




								__a										=    []
								__a										=    []
								__a										=    element if element.name else element.parent
								for parent in child.parents:  # type: bs4.element.Tag
												__a										=    parent.find_all(child.name		,     recursive=_snake_case				)
												xpath_tags.append(child.name				)
												xpath_subscripts.append(
												    0 if 1 == len(_snake_case				) else next(i for i, s in enumerate(_snake_case		,     1				) if s is child				)				)
												__a										=    parent
								xpath_tags.reverse()
								xpath_subscripts.reverse()
								return xpath_tags, xpath_subscripts




				def 				SCREAMING_SNAKE_CASE_		(     self		,     _snake_case				)    ->      Optional[int]:


								'''simple docstring'''




								__a										=    BeautifulSoup(_snake_case		,     '''html.parser'''				)

								__a										=    []
								__a										=    []
								__a										=    []

								for element in html_code.descendants:
												if type(_snake_case				) == bsa.element.NavigableString:
																if type(element.parent				) != bsa.element.Tag:
																				continue

																__a										=    html.unescape(_snake_case				).strip()
																if not text_in_this_tag:
																				continue

																all_doc_strings.append(_snake_case				)

																__a							,     __a										=    self.xpath_soup(_snake_case				)
																stringaxtag_seq.append(_snake_case				)
																stringaxsubs_seq.append(_snake_case				)

								if len(_snake_case				) != len(_snake_case				):
												raise ValueError('''Number of doc strings and xtags does not correspond'''				)
								if len(_snake_case				) != len(_snake_case				):
												raise ValueError('''Number of doc strings and xsubs does not correspond'''				)

								return all_doc_strings, stringaxtag_seq, stringaxsubs_seq




				def 				SCREAMING_SNAKE_CASE_		(     self		,     _snake_case		,     _snake_case				)    ->      Optional[int]:


								'''simple docstring'''




								__a										=    ''''''
								for tagname, subs in zip(_snake_case		,     _snake_case				):
												xpath += F"""/{tagname}"""
												if subs != 0:
																xpath += F"""[{subs}]"""
								return xpath




				def __call__(     self		,     _snake_case				)    ->      BatchFeature:


								'''simple docstring'''




								__a										=    False

								# Check that strings has a valid type
								if isinstance(_snake_case		,     _snake_case				):
												__a										=    True
								elif isinstance(_snake_case		,     (list, tuple)				):
												if len(_snake_case				) == 0 or isinstance(html_strings[0]		,     _snake_case				):
																__a										=    True

								if not valid_strings:
												raise ValueError(
												    '''HTML strings must of type `str`, `List[str]` (batch of examples), '''
												    F"""but is of type {type(_snake_case				)}."""				)

								__a										=    bool(isinstance(_snake_case		,     (list, tuple)				) and (isinstance(html_strings[0]		,     _snake_case				))				)

								if not is_batched:
												__a										=    [html_strings]

								# Get nodes + xpaths
								__a										=    []
								__a										=    []
								for html_string in html_strings:
												__a							,     __a							,     __a										=    self.get_three_from_single(_snake_case				)
												nodes.append(_snake_case				)
												__a										=    []
												for node, tag_list, sub_list in zip(_snake_case		,     _snake_case		,     _snake_case				):
																__a										=    self.construct_xpath(_snake_case		,     _snake_case				)
																xpath_strings.append(_snake_case				)
												xpaths.append(_snake_case				)

								# return as Dict
								__a										=    {'''nodes''': nodes, '''xpaths''': xpaths}
								__a										=    BatchFeature(data=_snake_case		,     tensor_type=_snake_case				)

								return encoded_inputs