



'''simple docstring'''


import numpy as np
import qiskit






def  UpperCAmelCase_       (		lowercase__ = 8       ,	lowercase__ = None       ):


     '''simple docstring'''







     a_       		=np.random.default_rng(seed=lowercase__       )

     # Roughly 25% of the qubits will contribute to the key.
     # So we take more than we need.
     a_       		=6 * key_len
     # Measurement basis for Alice's qubits.
     a_       		=rng.integers(2       ,	size=lowercase__       )
     # The set of states Alice will prepare.
     a_       		=rng.integers(2       ,	size=lowercase__       )
     # Measurement basis for Bob's qubits.
     a_       		=rng.integers(2       ,	size=lowercase__       )

     # Quantum Circuit to simulate BB84
     a_       		=qiskit.QuantumCircuit(lowercase__       ,	name="BB84"       )

     # Alice prepares her qubits according to rules above.
     for index, _ in enumerate(lowercase__       ):
          if alice_state[index] == 1:
               bbaa_circ.x(lowercase__       )
          if alice_basis[index] == 1:
               bbaa_circ.h(lowercase__       )
     bbaa_circ.barrier()

     # Bob measures the received qubits according to rules above.
     for index, _ in enumerate(lowercase__       ):
          if bob_basis[index] == 1:
               bbaa_circ.h(lowercase__       )

     bbaa_circ.barrier()
     bbaa_circ.measure_all()

     # Simulate the quantum circuit.
     a_       		=qiskit.Aer.get_backend("aer_simulator"       )
     # We only need to run one shot because the key is unique.
     # Multiple shots will produce the same key.
     a_       		=qiskit.execute(lowercase__       ,	lowercase__       ,	shots=1       ,	seed_simulator=lowercase__       )
     # Returns the result of measurement.
     a_       		=job.result().get_counts(lowercase__       ).most_frequent()

     # Extracting the generated key from the simulation results.
     # Only keep measurement results where Alice and Bob chose the same basis.
     a_       		="".join(
         [
             result_bit
             for alice_basis_bit, bob_basis_bit, result_bit in zip(
                 lowercase__       ,	lowercase__       ,	lowercase__       )
             if alice_basis_bit == bob_basis_bit
         ]       )

     # Get final key. Pad with 0 if too short, otherwise truncate.
     a_       		=gen_key[:key_len] if len(lowercase__       ) >= key_len else gen_key.ljust(lowercase__       ,	"0"       )
     return key


if __name__ == "__main__":
  print(F"""The generated key is : {bbaa(8, seed=0)}""")
  from doctest import testmod

  testmod()







'''simple docstring'''


import json
import logging
import os
import sys
from time import time
from unittest.mock import patch

from transformers.testing_utils import TestCasePlus, require_torch_tpu


logging.basicConfig(level=logging.DEBUG)

lowercase							       =			logging.getLogger()






def  UpperCAmelCase_       (		lowercase__       ):


     '''simple docstring'''







     a_       		={}
     a_       		=os.path.join(lowercase__       ,	"all_results.json"       )
     if os.path.exists(lowercase__       ):
          with open(lowercase__       ,	"r"       ) as f:
               a_       		=json.load(lowercase__       )
     else:
          raise ValueError(F"""can't find {path}"""       )
     return results


lowercase							       =			logging.StreamHandler(sys.stdout)
logger.addHandler(stream_handler)







@require_torch_tpu
class 	UpperCAmelCase	(		__a):


 '''simple docstring'''




 def       lowercase_  (   self) ->      List[Any]:



      """simple docstring"""







      import xla_spawn

      a_       		=self.get_auto_remove_tmp_dir()
      a_       		=f"""
            ./examples/pytorch/text-classification/run_glue.py
            --num_cores=8
            ./examples/pytorch/text-classification/run_glue.py
            --model_name_or_path distilbert-base-uncased
            --output_dir {tmp_dir}
            --overwrite_output_dir
            --train_file ./tests/fixtures/tests_samples/MRPC/train.csv
            --validation_file ./tests/fixtures/tests_samples/MRPC/dev.csv
            --do_train
            --do_eval
            --debug tpu_metrics_debug
            --per_device_train_batch_size=2
            --per_device_eval_batch_size=1
            --learning_rate=1e-4
            --max_steps=10
            --warmup_steps=2
            --seed=42
            --max_seq_length=128
            """.split()

      with patch.object(lowerCAmelCase_							,  "argv"							,  lowerCAmelCase_):
           a_       		=time()
           xla_spawn.main()
           a_       		=time()

           a_       		=get_results(lowerCAmelCase_)
           self.assertGreaterEqual(result["eval_accuracy"]							,  0.7_5)

           # Assert that the script takes less than 500 seconds to make sure it doesn't hang.
           self.assertLess(end - start							,  5_0_0)




 def       lowercase_  (   self) ->      Tuple:



      """simple docstring"""







      import xla_spawn

      a_       		="\n            ./tests/test_trainer_tpu.py\n            --num_cores=8\n            ./tests/test_trainer_tpu.py\n            ".split()
      with patch.object(lowerCAmelCase_							,  "argv"							,  lowerCAmelCase_):
           xla_spawn.main()


