



"""simple docstring"""





# 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   a__      ( lowerCAmelCase__      ,     lowerCAmelCase__      ,     lowerCAmelCase__      ,     lowerCAmelCase__ ):
      UpperCAmelCase_     					=				multiprocessing.Manager()
      UpperCAmelCase_     					=				manager.list()

      UpperCAmelCase_     					=				multiprocessing.Process(target=lowerCAmelCase__      ,     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   a__      ( lowerCAmelCase__      ,     lowerCAmelCase__      ,     lowerCAmelCase__ ):
      with create_tempdir():
            # These system calls are needed when cleaning up tempdir.
            import os
            import shutil

            UpperCAmelCase_     					=				shutil.rmtree
            UpperCAmelCase_     					=				os.rmdir
            UpperCAmelCase_     					=				os.chdir

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

            # Run program.
            try:
                  UpperCAmelCase_     					=				{}
                  with swallow_io():
                        with time_limit(lowerCAmelCase__ ):
                              exec(lowerCAmelCase__      ,     lowerCAmelCase__ )
                  result.append("passed" )
            except TimeoutException:
                  result.append("timed out" )
            except BaseException as e:
                  result.append(f"""failed: {e}""" )

            # Needed for cleaning up.
            UpperCAmelCase_     					=				rmtree
            UpperCAmelCase_     					=				rmdir
            UpperCAmelCase_     					=				chdir
@contextlib.contextmanager
def   a__      ( lowerCAmelCase__ ):
      def signal_handler(lowerCAmelCase__      ,     lowerCAmelCase__ ):
            raise TimeoutException("Timed out!" )

      signal.setitimer(signal.ITIMER_REAL      ,     lowerCAmelCase__ )
      signal.signal(signal.SIGALRM      ,     lowerCAmelCase__ )
      try:
            yield
      finally:
            signal.setitimer(signal.ITIMER_REAL      ,     0 )
@contextlib.contextmanager
def   a__      ( ):
      UpperCAmelCase_     					=				WriteOnlyStringIO()
      with contextlib.redirect_stdout(lowerCAmelCase__ ):
            with contextlib.redirect_stderr(lowerCAmelCase__ ):
                  with redirect_stdin(lowerCAmelCase__ ):
                        yield
@contextlib.contextmanager
def   a__      ( ):
      with tempfile.TemporaryDirectory() as dirname:
            with chdir(lowerCAmelCase__ ):
                  yield dirname
class  lowercase__  (       SCREAMING_SNAKE_CASE ):







       '''simple docstring'''


       pass



class  lowercase__  (       io.StringIO ):







       '''simple docstring'''


       def 	lowercase__							(				self     :    int						,							*_UpperCAmelCase     :    Any						,							**_UpperCAmelCase     :    int       )					->		Union[str, Any]:


             '''simple docstring'''




             raise OSError



       def 	lowercase__							(				self     :    Any						,							*_UpperCAmelCase     :    int						,							**_UpperCAmelCase     :    List[Any]       )					->		Union[str, Any]:


             '''simple docstring'''




             raise OSError



       def 	lowercase__							(				self     :    Any						,							*_UpperCAmelCase     :    List[Any]						,							**_UpperCAmelCase     :    List[str]       )					->		Tuple:


             '''simple docstring'''




             raise OSError







       def 	lowercase__							(				self     :    str						,							*_UpperCAmelCase     :    Optional[Any]						,							**_UpperCAmelCase     :    Tuple       )					->		Union[str, Any]:


             '''simple docstring'''




             return False



class  lowercase__  (       contextlib._RedirectStream ):  # type: ignore







       '''simple docstring'''


       UpperCamelCase		=	'''stdin'''



@contextlib.contextmanager
def   a__      ( lowerCAmelCase__ ):
      if root == ".":
            yield
            return
      UpperCAmelCase_     					=				os.getcwd()
      os.chdir(lowerCAmelCase__ )
      try:
            yield
      except BaseException as exc:
            raise exc
      finally:
            os.chdir(lowerCAmelCase__ )


def   a__      ( lowerCAmelCase__=None ):

      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

      UpperCAmelCase_     					=				None
      UpperCAmelCase_     					=				None

      import os

      UpperCAmelCase_     					=				"1"

      UpperCAmelCase_     					=				None
      UpperCAmelCase_     					=				None
      UpperCAmelCase_     					=				None
      UpperCAmelCase_     					=				None
      UpperCAmelCase_     					=				None
      UpperCAmelCase_     					=				None
      UpperCAmelCase_     					=				None
      UpperCAmelCase_     					=				None
      UpperCAmelCase_     					=				None
      UpperCAmelCase_     					=				None
      UpperCAmelCase_     					=				None
      UpperCAmelCase_     					=				None
      UpperCAmelCase_     					=				None
      UpperCAmelCase_     					=				None
      UpperCAmelCase_     					=				None
      UpperCAmelCase_     					=				None
      UpperCAmelCase_     					=				None
      UpperCAmelCase_     					=				None
      UpperCAmelCase_     					=				None
      UpperCAmelCase_     					=				None
      UpperCAmelCase_     					=				None
      UpperCAmelCase_     					=				None
      UpperCAmelCase_     					=				None
      UpperCAmelCase_     					=				None
      UpperCAmelCase_     					=				None
      UpperCAmelCase_     					=				None
      UpperCAmelCase_     					=				None

      import shutil

      UpperCAmelCase_     					=				None
      UpperCAmelCase_     					=				None
      UpperCAmelCase_     					=				None

      import subprocess

      UpperCAmelCase_     					=				None  # type: ignore

      UpperCAmelCase_     					=				None

      import sys

      UpperCAmelCase_     					=				None
      UpperCAmelCase_     					=				None
      UpperCAmelCase_     					=				None
      UpperCAmelCase_     					=				None
      UpperCAmelCase_     					=				None






"""simple docstring"""




import logging

import numpy as np
import pytest
from scipy.linalg import eigh

logging.basicConfig(level=logging.INFO, format='%(message)s')



def 							_lowerCamelCase			(			__a     ):
		return input_array.reshape((input_array.size, 1)     )



def 							_lowerCamelCase			(			__a,				__a,				__a     ):
		SCREAMING_SNAKE_CASE_    			=			np.nan
		for i in range(__a     ):
				SCREAMING_SNAKE_CASE_    			=			features[:, labels == i]
				SCREAMING_SNAKE_CASE_    			=			data.mean(1     )
				# Centralize the data of class i
				SCREAMING_SNAKE_CASE_    			=			data - column_reshape(__a     )
				if i > 0:
						# If covariance_sum is not None
						covariance_sum += np.dot(__a,				centered_data.T     )
				else:
						# If covariance_sum is np.nan (i.e. first loop)
						SCREAMING_SNAKE_CASE_    			=			np.dot(__a,				centered_data.T     )

		return covariance_sum / features.shape[1]



def 							_lowerCamelCase			(			__a,				__a,				__a     ):
		SCREAMING_SNAKE_CASE_    			=			features.mean(1     )
		SCREAMING_SNAKE_CASE_    			=			np.nan
		for i in range(__a     ):
				SCREAMING_SNAKE_CASE_    			=			features[:, labels == i]
				SCREAMING_SNAKE_CASE_    			=			data.shape[1]
				SCREAMING_SNAKE_CASE_    			=			data.mean(1     )
				if i > 0:
						# If covariance_sum is not None
						covariance_sum += device_data * np.dot(
						    column_reshape(__a     ) - column_reshape(__a     ),				(column_reshape(__a     ) - column_reshape(__a     )).T,				)
				else:
						# If covariance_sum is np.nan (i.e. first loop)
						SCREAMING_SNAKE_CASE_    			=			device_data * np.dot(
						    column_reshape(__a     ) - column_reshape(__a     ),				(column_reshape(__a     ) - column_reshape(__a     )).T,				)

		return covariance_sum / features.shape[1]



def 							_lowerCamelCase			(			__a,				__a     ):

		# Check if the features have been loaded
		if features.any():
				SCREAMING_SNAKE_CASE_    			=			features.mean(1     )
				# Center the dataset
				SCREAMING_SNAKE_CASE_    			=			features - np.reshape(__a,				(data_mean.size, 1)     )
				SCREAMING_SNAKE_CASE_    			=			np.dot(__a,				centered_data.T     ) / features.shape[1]
				SCREAMING_SNAKE_CASE_			,SCREAMING_SNAKE_CASE_    			=			np.linalg.eigh(__a     )
				# Take all the columns in the reverse order (-1), and then takes only the first
				SCREAMING_SNAKE_CASE_    			=			eigenvectors[:, ::-1][:, 0:dimensions]
				# Project the database on the new space
				SCREAMING_SNAKE_CASE_    			=			np.dot(filtered_eigenvectors.T,				__a     )
				logging.info('''Principal Component Analysis computed'''     )

				return projected_data
		else:
				logging.basicConfig(level=logging.ERROR,				format='''%(message)s''',				force=__a     )
				logging.error('''Dataset empty'''     )
				raise AssertionError



def 							_lowerCamelCase			(			__a,				__a,				__a,				__a     ):
		assert classes > dimensions

		# Check if features have been already loaded
		if features.any:
				SCREAMING_SNAKE_CASE_			,SCREAMING_SNAKE_CASE_    			=			eigh(
				    covariance_between_classes(__a,				__a,				__a     ),				covariance_within_classes(__a,				__a,				__a     ),				)
				SCREAMING_SNAKE_CASE_    			=			eigenvectors[:, ::-1][:, :dimensions]
				SCREAMING_SNAKE_CASE_			,SCREAMING_SNAKE_CASE_			,SCREAMING_SNAKE_CASE_    			=			np.linalg.svd(__a     )
				SCREAMING_SNAKE_CASE_    			=			svd_matrix[:, 0:dimensions]
				SCREAMING_SNAKE_CASE_    			=			np.dot(filtered_svd_matrix.T,				__a     )
				logging.info('''Linear Discriminant Analysis computed'''     )

				return projected_data
		else:
				logging.basicConfig(level=logging.ERROR,				format='''%(message)s''',				force=__a     )
				logging.error('''Dataset empty'''     )
				raise AssertionError



def 							_lowerCamelCase			(			):
		# Create dummy dataset with 2 classes and 3 features
		SCREAMING_SNAKE_CASE_    			=			np.array([[1, 2, 3, 4, 5], [2, 3, 4, 5, 6], [3, 4, 5, 6, 7]]     )
		SCREAMING_SNAKE_CASE_    			=			np.array([0, 0, 0, 1, 1]     )
		SCREAMING_SNAKE_CASE_    			=			2
		SCREAMING_SNAKE_CASE_    			=			2

		# Assert that the function raises an AssertionError if dimensions > classes
		with pytest.raises(__a     ) as error_info:
				SCREAMING_SNAKE_CASE_    			=			linear_discriminant_analysis(
				    __a,				__a,				__a,				__a     )
				if isinstance(__a,				np.ndarray     ):
						raise AssertionError(
						    '''Did not raise AssertionError for dimensions > classes'''     )
				assert error_info.type is AssertionError



def 							_lowerCamelCase			(			):
		SCREAMING_SNAKE_CASE_    			=			np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]     )
		SCREAMING_SNAKE_CASE_    			=			2
		SCREAMING_SNAKE_CASE_    			=			np.array([[6.9_2_8_2_0_3_2_3, 8.6_6_0_2_5_4_0_4, 1_0.3_9_2_3_0_4_8_5], [3.0, 3.0, 3.0]]     )

		with pytest.raises(__a     ) as error_info:
				SCREAMING_SNAKE_CASE_    			=			principal_component_analysis(__a,				__a     )
				if not np.allclose(__a,				__a     ):
						raise AssertionError
				assert error_info.type is AssertionError


if __name__ == "__main__":
						import doctest

						doctest.testmod()