






import argparse
import collections
import json
import os
import re
import string
import sys

import numpy as np


__UpperCAmelCase							:   Optional[int]							=  re.compile(R"\b(a|an|the)\b", re.UNICODE)

__UpperCAmelCase							:   List[Any]							=  None





def 					lowercase_ (    )     -> Any:





				'''simple docstring'''


				snake_case__      :List[Any]         =   argparse.ArgumentParser("Official evaluation script for SQuAD version 2.0."      )
				parser.add_argument("data_file"	,	metavar="data.json"	,	help="Input data JSON file."      )
				parser.add_argument("pred_file"	,	metavar="pred.json"	,	help="Model predictions."      )
				parser.add_argument(
				    "--out-file"	,	"-o"	,	metavar="eval.json"	,	help="Write accuracy metrics to file (default is stdout)."      )
				parser.add_argument(
				    "--na-prob-file"	,	"-n"	,	metavar="na_prob.json"	,	help="Model estimates of probability of no answer."      )
				parser.add_argument(
				    "--na-prob-thresh"	,	"-t"	,	type=a__	,	default=1.0	,	help="Predict \"\" if no-answer probability exceeds this (default = 1.0)."	,	)
				parser.add_argument(
				    "--out-image-dir"	,	"-p"	,	metavar="out_images"	,	default=a__	,	help="Save precision-recall curves to directory."      )
				parser.add_argument("--verbose"	,	"-v"	,	action="store_true"      )
				if len(sys.argv      ) == 1:
								parser.print_help()
								sys.exit(1      )
				return parser.parse_args()





def 					lowercase_ (    __snake_case     :							Optional[Any]      )     -> int:





				'''simple docstring'''


				snake_case__      :Optional[int]         =   {}
				for article in dataset:
								for p in article["paragraphs"]:
												for qa in p["qas"]:
																snake_case__      :Dict         =   bool(qa["answers"]["text"]      )
				return qid_to_has_ans





def 					lowercase_ (    __snake_case     :							int      )     -> int:





				'''simple docstring'''


				def remove_articles(__snake_case     :							Optional[int]      ):
								return ARTICLES_REGEX.sub(" "	,	a__      )

				def white_space_fix(__snake_case     :							List[Any]      ):
								return " ".join(text.split()      )

				def remove_punc(__snake_case     :							Union[str, Any]      ):
								snake_case__      :Dict         =   set(string.punctuation      )
								return "".join(ch for ch in text if ch not in exclude      )

				def lower(__snake_case     :							List[Any]      ):
								return text.lower()

				return white_space_fix(remove_articles(remove_punc(lower(a__      )      )      )      )





def 					lowercase_ (    __snake_case     :							Dict      )     -> List[Any]:





				'''simple docstring'''


				if not s:
								return []
				return normalize_answer(a__      ).split()





def 					lowercase_ (    __snake_case     :							Optional[int]	,	__snake_case     :							int      )     -> Union[str, Any]:





				'''simple docstring'''


				return int(normalize_answer(a__      ) == normalize_answer(a__      )      )





def 					lowercase_ (    __snake_case     :							List[str]	,	__snake_case     :							Optional[int]      )     -> str:





				'''simple docstring'''


				snake_case__      :Dict         =   get_tokens(a__      )
				snake_case__      :Dict         =   get_tokens(a__      )
				snake_case__      :Tuple         =   collections.Counter(a__      ) & collections.Counter(a__      )
				snake_case__      :List[Any]         =   sum(common.values()      )
				if len(a__      ) == 0 or len(a__      ) == 0:
								# If either is no-answer, then F1 is 1 if they agree, 0 otherwise
								return int(gold_toks == pred_toks      )
				if num_same == 0:
								return 0
				snake_case__      :Dict         =   1.0 * num_same / len(a__      )
				snake_case__      :Union[str, Any]         =   1.0 * num_same / len(a__      )
				snake_case__      :List[Any]         =   (2 * precision * recall) / (precision + recall)
				return fa





def 					lowercase_ (    __snake_case     :							Optional[int]	,	__snake_case     :							str      )     -> Optional[int]:





				'''simple docstring'''


				snake_case__      :int         =   {}
				snake_case__      :Dict         =   {}
				for article in dataset:
								for p in article["paragraphs"]:
												for qa in p["qas"]:
																snake_case__      :str         =   qa["id"]
																snake_case__      :Tuple         =   [t for t in qa["answers"]["text"] if normalize_answer(a__      )]
																if not gold_answers:
																				# For unanswerable questions, only correct answer is empty string
																				snake_case__      :Dict         =   [""]
																if qid not in preds:
																				print(F'Missing prediction for {qid}'      )
																				continue
																snake_case__      :List[Any]         =   preds[qid]
																# Take max over all gold answers
																snake_case__      :List[Any]         =   max(compute_exact(a__	,	a__      ) for a in gold_answers      )
																snake_case__      :Any         =   max(compute_fa(a__	,	a__      ) for a in gold_answers      )
				return exact_scores, fa_scores





def 					lowercase_ (    __snake_case     :							List[str]	,	__snake_case     :							Optional[int]	,	__snake_case     :							Optional[Any]	,	__snake_case     :							Optional[int]      )     -> Tuple:





				'''simple docstring'''


				snake_case__      :List[str]         =   {}
				for qid, s in scores.items():
								snake_case__      :Tuple         =   na_probs[qid] > na_prob_thresh
								if pred_na:
												snake_case__      :Optional[Any]         =   float(not qid_to_has_ans[qid]      )
								else:
												snake_case__      :int         =   s
				return new_scores





def 					lowercase_ (    __snake_case     :							Optional[Any]	,	__snake_case     :							Tuple	,	__snake_case     :							Dict=None      )     -> Tuple:





				'''simple docstring'''


				if not qid_list:
								snake_case__      :List[Any]         =   len(a__      )
								return collections.OrderedDict(
								    [
								        ("exact", 1_0_0.0 * sum(exact_scores.values()      ) / total),
								        ("f1", 1_0_0.0 * sum(fa_scores.values()      ) / total),
								        ("total", total),
								    ]      )
				else:
								snake_case__      :Optional[int]         =   len(a__      )
								return collections.OrderedDict(
								    [
								        ("exact", 1_0_0.0 * sum(exact_scores[k] for k in qid_list      ) / total),
								        ("f1", 1_0_0.0 * sum(fa_scores[k] for k in qid_list      ) / total),
								        ("total", total),
								    ]      )





def 					lowercase_ (    __snake_case     :							str	,	__snake_case     :							Any	,	__snake_case     :							List[Any]      )     -> Union[str, Any]:





				'''simple docstring'''


				for k in new_eval:
								snake_case__      :Dict         =   new_eval[k]





def 					lowercase_ (    __snake_case     :							Optional[int]	,	__snake_case     :							List[Any]	,	__snake_case     :							Optional[Any]	,	__snake_case     :							str      )     -> str:





				'''simple docstring'''


				plt.step(a__	,	a__	,	color="b"	,	alpha=0.2	,	where="post"      )
				plt.fill_between(a__	,	a__	,	step="post"	,	alpha=0.2	,	color="b"      )
				plt.xlabel("Recall"      )
				plt.ylabel("Precision"      )
				plt.xlim([0.0, 1.0_5]      )
				plt.ylim([0.0, 1.0_5]      )
				plt.title(a__      )
				plt.savefig(a__      )
				plt.clf()





def 					lowercase_ (    __snake_case     :							Tuple	,	__snake_case     :							Union[str, Any]	,	__snake_case     :							Dict	,	__snake_case     :							List[Any]	,	__snake_case     :							Optional[Any]=None	,	__snake_case     :							Optional[Any]=None      )     -> List[Any]:





				'''simple docstring'''


				snake_case__      :Dict         =   sorted(a__	,	key=lambda __snake_case      : na_probs[k]      )
				snake_case__      :Optional[Any]         =   0.0
				snake_case__      :Optional[Any]         =   1.0
				snake_case__      :List[str]         =   0.0
				snake_case__      :Optional[Any]         =   [1.0]
				snake_case__      :Tuple         =   [0.0]
				snake_case__      :Union[str, Any]         =   0.0
				for i, qid in enumerate(a__      ):
								if qid_to_has_ans[qid]:
												true_pos += scores[qid]
								snake_case__      :int         =   true_pos / float(i + 1      )
								snake_case__      :Union[str, Any]         =   true_pos / float(a__      )
								if i == len(a__      ) - 1 or na_probs[qid] != na_probs[qid_list[i + 1]]:
												# i.e., if we can put a threshold after this point
												avg_prec += cur_p * (cur_r - recalls[-1])
												precisions.append(a__      )
												recalls.append(a__      )
				if out_image:
								plot_pr_curve(a__	,	a__	,	a__	,	a__      )
				return {"ap": 1_0_0.0 * avg_prec}





def 					lowercase_ (    __snake_case     :							Any	,	__snake_case     :							Optional[int]	,	__snake_case     :							Tuple	,	__snake_case     :							Optional[int]	,	__snake_case     :							Tuple	,	__snake_case     :							Optional[int]      )     -> Any:





				'''simple docstring'''


				if out_image_dir and not os.path.exists(a__      ):
								os.makedirs(a__      )
				snake_case__      :int         =   sum(1 for v in qid_to_has_ans.values() if v      )
				if num_true_pos == 0:
								return
				snake_case__      :Tuple         =   make_precision_recall_eval(
				    a__	,	a__	,	a__	,	a__	,	out_image=os.path.join(a__	,	"pr_exact.png"      )	,	title="Precision-Recall curve for Exact Match score"	,	)
				snake_case__      :Any         =   make_precision_recall_eval(
				    a__	,	a__	,	a__	,	a__	,	out_image=os.path.join(a__	,	"pr_f1.png"      )	,	title="Precision-Recall curve for F1 score"	,	)
				snake_case__      :Tuple         =   {k: float(a__      ) for k, v in qid_to_has_ans.items()}
				snake_case__      :str         =   make_precision_recall_eval(
				    a__	,	a__	,	a__	,	a__	,	out_image=os.path.join(a__	,	"pr_oracle.png"      )	,	title="Oracle Precision-Recall curve (binary task of HasAns vs. NoAns)"	,	)
				merge_eval(a__	,	a__	,	"pr_exact"      )
				merge_eval(a__	,	a__	,	"pr_f1"      )
				merge_eval(a__	,	a__	,	"pr_oracle"      )





def 					lowercase_ (    __snake_case     :							Dict	,	__snake_case     :							List[Any]	,	__snake_case     :							List[str]	,	__snake_case     :							Any      )     -> Optional[int]:





				'''simple docstring'''


				if not qid_list:
								return
				snake_case__      :Any         =   [na_probs[k] for k in qid_list]
				snake_case__      :int         =   np.ones_like(a__      ) / float(len(a__      )      )
				plt.hist(a__	,	weights=a__	,	bins=20	,	range=(0.0, 1.0)      )
				plt.xlabel("Model probability of no-answer"      )
				plt.ylabel("Proportion of dataset"      )
				plt.title(F'Histogram of no-answer probability: {name}'      )
				plt.savefig(os.path.join(a__	,	F'na_prob_hist_{name}.png'      )      )
				plt.clf()





def 					lowercase_ (    __snake_case     :							List[str]	,	__snake_case     :							Dict	,	__snake_case     :							Dict	,	__snake_case     :							Optional[Any]      )     -> List[str]:





				'''simple docstring'''


				snake_case__      :Union[str, Any]         =   sum(1 for k in qid_to_has_ans if not qid_to_has_ans[k]      )
				snake_case__      :Optional[Any]         =   num_no_ans
				snake_case__      :Tuple         =   cur_score
				snake_case__      :int         =   0.0
				snake_case__      :List[str]         =   sorted(a__	,	key=lambda __snake_case      : na_probs[k]      )
				for i, qid in enumerate(a__      ):
								if qid not in scores:
												continue
								if qid_to_has_ans[qid]:
												snake_case__      :List[str]         =   scores[qid]
								else:
												if preds[qid]:
																snake_case__      :Tuple         =   -1
												else:
																snake_case__      :int         =   0
								cur_score += diff
								if cur_score > best_score:
												snake_case__      :Any         =   cur_score
												snake_case__      :str         =   na_probs[qid]
				return 1_0_0.0 * best_score / len(a__      ), best_thresh





def 					lowercase_ (    __snake_case     :							List[str]	,	__snake_case     :							List[Any]	,	__snake_case     :							List[str]	,	__snake_case     :							Optional[Any]	,	__snake_case     :							str	,	__snake_case     :							Any      )     -> Optional[Any]:





				'''simple docstring'''


				snake_case__    ,						snake_case__      :Optional[Any]         =   find_best_thresh(a__	,	a__	,	a__	,	a__      )
				snake_case__    ,						snake_case__      :str         =   find_best_thresh(a__	,	a__	,	a__	,	a__      )
				snake_case__      :str         =   best_exact
				snake_case__      :Optional[int]         =   exact_thresh
				snake_case__      :Tuple         =   best_fa
				snake_case__      :Dict         =   fa_thresh





def 					lowercase_ (    )     -> List[Any]:





				'''simple docstring'''


				with open(OPTS.data_file      ) as f:
								snake_case__      :int         =   json.load(a__      )
								snake_case__      :Any         =   dataset_json["data"]
				with open(OPTS.pred_file      ) as f:
								snake_case__      :Union[str, Any]         =   json.load(a__      )
				if OPTS.na_prob_file:
								with open(OPTS.na_prob_file      ) as f:
												snake_case__      :Any         =   json.load(a__      )
				else:
								snake_case__      :int         =   {k: 0.0 for k in preds}
				snake_case__      :Tuple         =   make_qid_to_has_ans(a__      )  # maps qid to True/False
				snake_case__      :Optional[int]         =   [k for k, v in qid_to_has_ans.items() if v]
				snake_case__      :Dict         =   [k for k, v in qid_to_has_ans.items() if not v]
				snake_case__    ,						snake_case__      :int         =   get_raw_scores(a__	,	a__      )
				snake_case__      :List[str]         =   apply_no_ans_threshold(a__	,	a__	,	a__	,	OPTS.na_prob_thresh      )
				snake_case__      :Union[str, Any]         =   apply_no_ans_threshold(a__	,	a__	,	a__	,	OPTS.na_prob_thresh      )
				snake_case__      :Any         =   make_eval_dict(a__	,	a__      )
				if has_ans_qids:
								snake_case__      :List[Any]         =   make_eval_dict(a__	,	a__	,	qid_list=a__      )
								merge_eval(a__	,	a__	,	"HasAns"      )
				if no_ans_qids:
								snake_case__      :Optional[int]         =   make_eval_dict(a__	,	a__	,	qid_list=a__      )
								merge_eval(a__	,	a__	,	"NoAns"      )
				if OPTS.na_prob_file:
								find_all_best_thresh(a__	,	a__	,	a__	,	a__	,	a__	,	a__      )
				if OPTS.na_prob_file and OPTS.out_image_dir:
								run_precision_recall_analysis(a__	,	a__	,	a__	,	a__	,	a__	,	OPTS.out_image_dir      )
								histogram_na_prob(a__	,	a__	,	OPTS.out_image_dir	,	"hasAns"      )
								histogram_na_prob(a__	,	a__	,	OPTS.out_image_dir	,	"noAns"      )
				if OPTS.out_file:
								with open(OPTS.out_file	,	"w"      ) as f:
												json.dump(a__	,	a__      )
				else:
								print(json.dumps(a__	,	indent=2      )      )


if __name__ == "__main__":
	__UpperCAmelCase							:   Optional[int]							=  parse_args()
	if OPTS.out_image_dir:
		import matplotlib

		matplotlib.use("Agg")
		import matplotlib.pyplot as plt
	main()







def 					lowercase_ (    __snake_case     :							Tuple	,	__snake_case     :							Optional[int]      )     -> List[Any]:





				'''simple docstring'''


				snake_case__      :Dict         =   ""
				for i in table:
								res += inp[i - 1]
				return res





def 					lowercase_ (    __snake_case     :							List[str]      )     -> int:





				'''simple docstring'''


				return data[1:] + data[0]





def 					lowercase_ (    __snake_case     :							int	,	__snake_case     :							Union[str, Any]      )     -> Union[str, Any]:





				'''simple docstring'''


				snake_case__      :Union[str, Any]         =   ""
				for i in range(len(__snake_case      )      ):
								if a[i] == b[i]:
												res += "0"
								else:
												res += "1"
				return res





def 					lowercase_ (    __snake_case     :							Optional[int]	,	__snake_case     :							Dict      )     -> Union[str, Any]:





				'''simple docstring'''


				snake_case__      :int         =   int("0b" + data[0] + data[-1]	,	2      )
				snake_case__      :Union[str, Any]         =   int("0b" + data[1:3]	,	2      )
				return bin(s[row][col]      )[2:]





def 					lowercase_ (    __snake_case     :							Dict	,	__snake_case     :							Optional[Any]	,	__snake_case     :							Dict	,	__snake_case     :							List[Any]	,	__snake_case     :							Optional[int]      )     -> List[str]:





				'''simple docstring'''


				snake_case__      :Tuple         =   message[:4]
				snake_case__      :int         =   message[4:]
				snake_case__      :int         =   apply_table(__snake_case	,	__snake_case      )
				snake_case__      :Union[str, Any]         =   xor(__snake_case	,	__snake_case      )
				snake_case__      :Tuple         =   apply_sbox(__snake_case	,	temp[:4]      )  # noqa: E741
				snake_case__      :List[str]         =   apply_sbox(__snake_case	,	temp[4:]      )
				snake_case__      :int         =   "0" * (2 - len(__snake_case      )) + l  # noqa: E741
				snake_case__      :int         =   "0" * (2 - len(__snake_case      )) + r
				snake_case__      :Optional[Any]         =   apply_table(l + r	,	__snake_case      )
				snake_case__      :Tuple         =   xor(__snake_case	,	__snake_case      )
				return temp + right


if __name__ == "__main__":
	__UpperCAmelCase							:   Dict							=  input("Enter 10 bit key: ")
	__UpperCAmelCase							:   Tuple							=  input("Enter 8 bit message: ")

	__UpperCAmelCase							:   Any							=  [6, 3, 7, 4, 8, 5, 1_0, 9]
	__UpperCAmelCase							:   List[str]							=  [3, 5, 2, 7, 4, 1_0, 1, 9, 8, 6]
	__UpperCAmelCase							:   Tuple							=  [2, 4, 3, 1]
	__UpperCAmelCase							:   List[Any]							=  [2, 6, 3, 1, 4, 8, 5, 7]
	__UpperCAmelCase							:   Optional[Any]							=  [4, 1, 3, 5, 7, 2, 8, 6]
	__UpperCAmelCase							:   Optional[int]							=  [4, 1, 2, 3, 2, 3, 4, 1]
	__UpperCAmelCase							:   List[Any]							=  [[1, 0, 3, 2], [3, 2, 1, 0], [0, 2, 1, 3], [3, 1, 3, 2]]
	__UpperCAmelCase							:   Union[str, Any]							=  [[0, 1, 2, 3], [2, 0, 1, 3], [3, 0, 1, 0], [2, 1, 0, 3]]

	# key generation
	__UpperCAmelCase							:   int							=  apply_table(key, paa_table)
	__UpperCAmelCase							:   Dict							=  temp[:5]
	__UpperCAmelCase							:   Optional[int]							=  temp[5:]
	__UpperCAmelCase							:   Optional[int]							=  left_shift(left)
	__UpperCAmelCase							:   Union[str, Any]							=  left_shift(right)
	__UpperCAmelCase							:   int							=  apply_table(left + right, pa_table)
	__UpperCAmelCase							:   Tuple							=  left_shift(left)
	__UpperCAmelCase							:   Union[str, Any]							=  left_shift(right)
	__UpperCAmelCase							:   Dict							=  left_shift(left)
	__UpperCAmelCase							:   Optional[Any]							=  left_shift(right)
	__UpperCAmelCase							:   Optional[int]							=  apply_table(left + right, pa_table)

	# encryption
	__UpperCAmelCase							:   Tuple							=  apply_table(message, IP)
	__UpperCAmelCase							:   Tuple							=  function(expansion, sa, sa, keya, temp)
	__UpperCAmelCase							:   List[Any]							=  temp[4:] + temp[:4]
	__UpperCAmelCase							:   int							=  function(expansion, sa, sa, keya, temp)
	__UpperCAmelCase							:   Union[str, Any]							=  apply_table(temp, IP_inv)
	print("Cipher text is:", CT)

	# decryption
	__UpperCAmelCase							:   List[Any]							=  apply_table(CT, IP)
	__UpperCAmelCase							:   List[Any]							=  function(expansion, sa, sa, keya, temp)
	__UpperCAmelCase							:   int							=  temp[4:] + temp[:4]
	__UpperCAmelCase							:   Union[str, Any]							=  function(expansion, sa, sa, keya, temp)
	__UpperCAmelCase							:   Union[str, Any]							=  apply_table(temp, IP_inv)
	print("Plain text after decypting is:", PT)