



import collections
import json
import math
import os
import re
import time
from fnmatch import fnmatch
from typing import Dict

import requests
from slack_sdk import WebClient


lowerCAmelCase__       =  WebClient(token=os.environ['''CI_SLACK_BOT_TOKEN'''])


def 					__lowerCamelCase					(   lowerCamelCase__						):

				"""simple docstring"""


				lowercase__     :    Optional[Any]													=     test_results.split(" "						)

				lowercase__     :    Any													=     0
				lowercase__     :    List[Any]													=     0

				# When the output is short enough, the output is surrounded by = signs: "== OUTPUT =="
				# When it is too long, those signs are not present.
				lowercase__     :    Dict													=     expressions[-2] if "=" in expressions[-1] else expressions[-1]

				for i, expression in enumerate(_snake_case						):
								if "failed" in expression:
												failed += int(expressions[i - 1]						)
								if "passed" in expression:
												success += int(expressions[i - 1]						)

				return failed, success, time_spent


def 					__lowerCamelCase					(   lowerCamelCase__						):

				"""simple docstring"""


				lowercase__     :    Optional[Any]													=     {}
				lowercase__     :    List[Any]													=     None
				lowercase__     :    Dict													=     False
				for line in failures_short_lines.split("\n"						):
								if re.search(R"_ \[doctest\]"     , _snake_case						):
												lowercase__     :    str													=     True
												lowercase__     :    Optional[int]													=     line.split(" "						)[2]
								elif in_error and not line.split(" "						)[0].isdigit():
												lowercase__     :    Optional[Any]													=     line
												lowercase__     :    Any													=     False

				return failures

class       snake_case__:

					"""simple docstring"""






					def __init__(							self					:	int      ,   SCREAMING_SNAKE_CASE					:	Any      ,   SCREAMING_SNAKE_CASE					:	List[str]     ):
									lowercase__     :    int													=     title

									lowercase__     :    str													=     doc_test_results["time_spent"].split(","     )[0]
									lowercase__     :    Optional[Any]													=     doc_test_results["success"]
									lowercase__     :    List[str]													=     doc_test_results["failures"]
									lowercase__     :    List[str]													=     self.n_success + self.n_failures

									# Failures and success of the modeling tests
									lowercase__     :    str													=     doc_test_results







					@property
					def  snake_case     (							self					:	Optional[int]     ):
									lowercase__     :    str													=     [self._time_spent]
									lowercase__     :    Union[str, Any]													=     0

									for time in time_spent:
													lowercase__     :    Tuple													=     time.split(":"     )

													# Time can be formatted as xx:xx:xx, as .xx, or as x.xx if the time spent was less than a minute.
													if len(__snake_case     ) == 1:
																	lowercase__     :    Dict													=     [0, 0, time_parts[0]]

													lowercase__							,							lowercase__							,							lowercase__     :    List[Any]													=     int(time_parts[0]     ), int(time_parts[1]     ), float(time_parts[2]     )
													total_secs += hours * 3_600 + minutes * 60 + seconds

									lowercase__							,							lowercase__							,							lowercase__     :    str													=     total_secs // 3_600, (total_secs % 3_600) // 60, total_secs % 60
									return f"""{int(__snake_case     )}h{int(__snake_case     )}m{int(__snake_case     )}s"""







					@property
					def  snake_case     (							self					:	int     ):
									return {"type": "header", "text": {"type": "plain_text", "text": self.title}}







					@property
					def  snake_case     (							self					:	Any     ):
									return {
									    "type": "section",
									    "text": {
									        "type": "plain_text",
									        "text": f"""🌞 There were no failures: all {self.n_tests} tests passed. The suite ran in {self.time}.""",
									        "emoji": True,
									    },
									    "accessory": {
									        "type": "button",
									        "text": {"type": "plain_text", "text": "Check Action results", "emoji": True},
									        "url": f"""https://github.com/huggingface/transformers/actions/runs/{os.environ["GITHUB_RUN_ID"]}""",
									    },
									}







					@property
					def  snake_case     (							self					:	int     ):
									return {
									    "type": "section",
									    "text": {
									        "type": "plain_text",
									        "text": (
									            f"""There were {self.n_failures} failures, out of {self.n_tests} tests.\nThe suite ran in"""
									            f""" {self.time}."""
									        ),
									        "emoji": True,
									    },
									    "accessory": {
									        "type": "button",
									        "text": {"type": "plain_text", "text": "Check Action results", "emoji": True},
									        "url": f"""https://github.com/huggingface/transformers/actions/runs/{os.environ["GITHUB_RUN_ID"]}""",
									    },
									}







					@property
					def  snake_case     (							self					:	str     ):
									lowercase__     :    Optional[int]													=     40
									lowercase__     :    int													=     {k: v["failed"] for k, v in doc_test_results.items() if isinstance(__snake_case      ,   __snake_case     )}

									lowercase__     :    Any													=     ""
									for category, failures in category_failures.items():
													if len(__snake_case     ) == 0:
																	continue

													if report != "":
																	report += "\n\n"

													report += f"""*{category} failures*:""".ljust(line_length // 2     ).rjust(line_length // 2     ) + "\n"
													report += "`"
													report += "`\n`".join(__snake_case     )
													report += "`"

									return {
									    "type": "section",
									    "text": {
									        "type": "mrkdwn",
									        "text": f"""The following examples had failures:\n\n\n{report}\n""",
									    },
									}







					@property
					def  snake_case     (							self					:	Union[str, Any]     ):
									lowercase__     :    List[Any]													=     [self.header]

									if self.n_failures > 0:
													blocks.append(self.failures     )

									if self.n_failures > 0:
													blocks.extend([self.category_failures]     )

									if self.n_failures == 0:
													blocks.append(self.no_failures     )

									return json.dumps(__snake_case     )







					@staticmethod
					def  snake_case     (							):
									lowercase__     :    Optional[Any]													=     [
									    {
									        "type": "section",
									        "text": {
									            "type": "plain_text",
									            "text": "There was an issue running the tests.",
									        },
									        "accessory": {
									            "type": "button",
									            "text": {"type": "plain_text", "text": "Check Action results", "emoji": True},
									            "url": f"""https://github.com/huggingface/transformers/actions/runs/{os.environ["GITHUB_RUN_ID"]}""",
									        },
									    }
									]

									print("Sending the following payload"     )
									print(json.dumps({"blocks": json.loads(__snake_case     )}     )     )

									client.chat_postMessage(
									    channel=os.environ["CI_SLACK_CHANNEL_ID_DAILY"]      ,   text="There was an issue running the tests."      ,   blocks=__snake_case      ,   )







					def  snake_case     (							self					:	int     ):
									print("Sending the following payload"     )
									print(json.dumps({"blocks": json.loads(self.payload     )}     )     )

									lowercase__     :    Optional[Any]													=     f"""{self.n_failures} failures out of {self.n_tests} tests,""" if self.n_failures else "All tests passed."

									lowercase__     :    List[str]													=     client.chat_postMessage(
									    channel=os.environ["CI_SLACK_CHANNEL_ID_DAILY"]      ,   blocks=self.payload      ,   text=__snake_case      ,   )







					def  snake_case     (							self					:	str      ,   SCREAMING_SNAKE_CASE					:	List[str]      ,   SCREAMING_SNAKE_CASE					:	Dict      ,   SCREAMING_SNAKE_CASE					:	Dict      ,   SCREAMING_SNAKE_CASE					:	Any     ):
									lowercase__     :    Optional[int]													=     ""
									for key, value in failures.items():
													lowercase__     :    Any													=     value[:200] + " [Truncated]" if len(__snake_case     ) > 250 else value
													failures_text += f"""*{key}*\n_{value}_\n\n"""

									lowercase__     :    Optional[int]													=     job_name
									lowercase__     :    List[Any]													=     {"type": "section", "text": {"type": "mrkdwn", "text": text}}

									if job_link is not None:
													lowercase__     :    List[str]													=     {
													    "type": "button",
													    "text": {"type": "plain_text", "text": "GitHub Action job", "emoji": True},
													    "url": job_link,
													}

									return [
									    {"type": "header", "text": {"type": "plain_text", "text": title.upper(), "emoji": True}},
									    content,
									    {"type": "section", "text": {"type": "mrkdwn", "text": failures_text}},
									]







					def  snake_case     (							self					:	Optional[Any]     ):
									if self.thread_ts is None:
													raise ValueError("Can only post reply if a post has been made."     )

									lowercase__     :    Optional[int]													=     self.doc_test_results.pop("job_link"     )
									self.doc_test_results.pop("failures"     )
									self.doc_test_results.pop("success"     )
									self.doc_test_results.pop("time_spent"     )

									lowercase__     :    Any													=     sorted(self.doc_test_results.items()      ,   key=lambda SCREAMING_SNAKE_CASE     : t[0]     )
									for job, job_result in sorted_dict:
													if len(job_result["failures"]     ):
																	lowercase__     :    Tuple													=     f"""*Num failures* :{len(job_result["failed"]     )} \n"""
																	lowercase__     :    Any													=     job_result["failures"]
																	lowercase__     :    Any													=     self.get_reply_blocks(__snake_case      ,   __snake_case      ,   __snake_case      ,   text=__snake_case     )

																	print("Sending the following reply"     )
																	print(json.dumps({"blocks": blocks}     )     )

																	client.chat_postMessage(
																	    channel=os.environ["CI_SLACK_CHANNEL_ID_DAILY"]      ,   text=f"""Results for {job}"""      ,   blocks=__snake_case      ,   thread_ts=self.thread_ts["ts"]      ,   )

																	time.sleep(1     )






def 					__lowerCamelCase					(   ):

				"""simple docstring"""


				lowercase__     :    Optional[Any]													=     os.environ["GITHUB_RUN_ID"]
				lowercase__     :    Union[str, Any]													=     F"""https://api.github.com/repos/huggingface/transformers/actions/runs/{run_id}/jobs?per_page=100"""
				lowercase__     :    Optional[int]													=     requests.get(_snake_case						).json()
				lowercase__     :    Any													=     {}

				try:
								jobs.update({job["name"]: job["html_url"] for job in result["jobs"]}						)
								lowercase__     :    Tuple													=     math.ceil((result["total_count"] - 100) / 100						)

								for i in range(_snake_case						):
												lowercase__     :    Tuple													=     requests.get(url + F"""&page={i + 2}"""						).json()
												jobs.update({job["name"]: job["html_url"] for job in result["jobs"]}						)

								return jobs
				except Exception as e:
								print("Unknown error, could not fetch links."     , _snake_case						)

				return {}


def 					__lowerCamelCase					(   lowerCamelCase__						):

				"""simple docstring"""


				lowercase__     :    Dict													=     {}

				if os.path.exists(_snake_case						):
								lowercase__     :    Optional[Any]													=     os.listdir(_snake_case						)
								for file in files:
												try:
																with open(os.path.join(_snake_case     , _snake_case						)     , encoding="utf-8"						) as f:
																				lowercase__     :    List[str]													=     f.read()
												except UnicodeDecodeError as e:
																raise ValueError(F"""Could not open {os.path.join(_snake_case     , _snake_case						)}."""						) from e

				return _artifact


def 					__lowerCamelCase					(   ):

				"""simple docstring"""


				class       snake_case__:

									"""simple docstring"""






									def __init__(							self					:	Union[str, Any]      ,   SCREAMING_SNAKE_CASE					:	List[Any]     ):
													lowercase__     :    Dict													=     name
													lowercase__     :    List[str]													=     []







									def __str__(							self					:	int     ):
													return self.name







									def  snake_case     (							self					:	Optional[int]      ,   SCREAMING_SNAKE_CASE					:	Tuple     ):
													self.paths.append({"name": self.name, "path": path}     )






				lowercase__     :    Union[str, Any]													=     {}

				lowercase__     :    Tuple													=     filter(os.path.isdir     , os.listdir()						)
				for directory in directories:
								lowercase__     :    Optional[Any]													=     directory
								if artifact_name not in _available_artifacts:
												lowercase__     :    int													=     Artifact(_snake_case						)

												_available_artifacts[artifact_name].add_path(_snake_case						)

				return _available_artifacts


if __name__ == "__main__":
				lowerCAmelCase__       =  get_job_links()
				lowerCAmelCase__       =  retrieve_available_artifacts()

				lowerCAmelCase__       =  collections.OrderedDict(
				    [
				        ('''*.py''', '''API Examples'''),
				        ('''*.md''', '''MD Examples'''),
				    ]
				)

				# This dict will contain all the information relative to each doc test category:
				# - failed: list of failed tests
				# - failures: dict in the format 'test': 'error_message'
				lowerCAmelCase__       =  {
				    v: {
				        "failed": [],
				        "failures": {},
				    }
				    for v in docs.values()
				}

				# Link to the GitHub Action job
				lowerCAmelCase__       =  github_actions_job_links.get('''run_doctests''')

				lowerCAmelCase__       =  available_artifacts["doc_tests_gpu_test_reports"].paths[0]
				lowerCAmelCase__       =  retrieve_artifact(artifact_path['''name'''])
				if "stats" in artifact:
								lowerCAmelCase__       =  handle_test_results(artifact['''stats'''])
								lowerCAmelCase__       =  failed
								lowerCAmelCase__       =  success
								lowerCAmelCase__       =  time_spent[1:-1] + ", "

								lowerCAmelCase__       =  extract_first_line_failure(artifact['''failures_short'''])
								for line in artifact["summary_short"].split('''\n'''):
												if re.search('''FAILED''', line):
																lowerCAmelCase__       =  line.replace('''FAILED ''', '''''')
																lowerCAmelCase__       =  line.split()[0].replace('''\n''', '''''')

																if "::" in line:
																				lowerCAmelCase__       =  line.split('''::''')
																else:
																				lowerCAmelCase__       =  line, line

																for file_regex in docs.keys():
																				if fnmatch(file_path, file_regex):
																								lowerCAmelCase__       =  docs[file_regex]
																								doc_test_results[category]["failed"].append(test)

																								lowerCAmelCase__       =  all_failures[test] if test in all_failures else "N/A"
																								lowerCAmelCase__       =  failure
																								break

				lowerCAmelCase__       =  Message('''🤗 Results of the doc tests.''', doc_test_results)
				message.post()
				message.post_reply()







from multiprocessing import Lock, Pipe, Process

# lock used to ensure that two processes do not access a pipe at the same time
_lowerCAmelCase					:			Optional[Any]  				=			Lock()






def        UpperCamelCase_(							_snake_case   :  List[str]       ,     _snake_case   :  Optional[int]       ,     _snake_case   :  Dict       ,     _snake_case   :  Any       ,     _snake_case   :  List[str]       ,     _snake_case   :  Tuple       ,     _snake_case   :  List[str]	):




			"""simple docstring"""






			global process_lock

			# we perform n swaps since after n swaps we know we are sorted
			# we *could* stop early if we are sorted already, but it takes as long to
			# find out we are sorted as it does to sort the list with this algorithm
			for i in range(0       ,     10	):
						if (i + position) % 2 == 0 and r_send is not None:
									# send your value to your right neighbor
									process_lock.acquire()
									r_send[1].send(_snake_case	)
									process_lock.release()

									# receive your right neighbor's value
									process_lock.acquire()
									__a        =rr_cv[0].recv()
									process_lock.release()

									# take the lower value since you are on the left
									__a        =min(_snake_case       ,     _snake_case	)
						elif (i + position) % 2 != 0 and l_send is not None:
									# send your value to your left neighbor
									process_lock.acquire()
									l_send[1].send(_snake_case	)
									process_lock.release()

									# receive your left neighbor's value
									process_lock.acquire()
									__a        =lr_cv[0].recv()
									process_lock.release()

									# take the higher value since you are on the right
									__a        =max(_snake_case       ,     _snake_case	)
    # after all swaps are performed, send the values back to main
			result_pipe[1].send(_snake_case	)






def        UpperCamelCase_(							_snake_case   :  List[str]	):




			"""simple docstring"""






			__a        =[]
			__a        =[]
			# initialize the list of pipes where the values will be retrieved
			for _ in arr:
						result_pipe.append(Pipe()	)
			# creates the processes
			# the first and last process only have one neighbor so they are made outside
			# of the loop
			__a        =Pipe()
			__a        =Pipe()
			process_array_.append(
			    Process(
			        target=_snake_case       ,     args=(0, arr[0], None, temp_rs, None, temp_rr, result_pipe[0])       ,     )	)
			__a        =temp_rs
			__a        =temp_rr

			for i in range(1       ,     len(_snake_case	) - 1	):
						__a        =Pipe()
						__a        =Pipe()
						process_array_.append(
						    Process(
						        target=_snake_case       ,     args=(i, arr[i], temp_ls, temp_rs, temp_lr, temp_rr, result_pipe[i])       ,     )	)
						__a        =temp_rs
						__a        =temp_rr

			process_array_.append(
			    Process(
			        target=_snake_case       ,     args=(
			            len(_snake_case	) - 1,
			            arr[len(_snake_case	) - 1],
			            temp_ls,
			            None,
			            temp_lr,
			            None,
			            result_pipe[len(_snake_case	) - 1],
			        )       ,     )	)

			# start the processes
			for p in process_array_:
						p.start()

			# wait for the processes to end and write their values to the list
			for p in range(0       ,     len(_snake_case	)	):
						__a        =result_pipe[p][0].recv()
						process_array_[p].join()
			return arr






def        UpperCamelCase_(							):




			"""simple docstring"""






			__a        =list(range(10       ,     0       ,     -1	)	)
			print('Initial List'	)
			print(*_snake_case	)
			__a        =odd_even_transposition(_snake_case	)
			print('Sorted List\n'	)
			print(*_snake_case	)


if __name__ == "__main__":
						main()






