Best Python code snippet using ATX
gen_password.py
Source:gen_password.py  
1from patalib import Antonym, Synonym, Syzygy, Anomaly, Clinamen2class PasswordGenerator:3    bio_data = {}4    key = ""5    password_mappings = {}6    encryption_dict = {}7    substitutors_dict = {}8    words = []9    def __init__(10            self,11            key,12            words,13            bio_data,14            encryption_dict,15            substitutors_dict):16        """17        Store list of biographical data18        """19        self.key = key20        self.words = words21        self.bio_data = bio_data22        self.encryption_dict = encryption_dict23        self.substitutors_dict = substitutors_dict24    def process_individual(self):25        """26        Process an individuals data27        to generate a list of potential28        passwords29        """30        individual = {}31        count = 032        for k, v in self.bio_data.items():33            individual[self.key] = k34            if not isinstance(v, list):35                individual[k] = self.gen_pata_data(str(v))36            else:37                list_vals_to_process = []38                for listval in v:39                    list_vals_to_process.append(40                        self.gen_pata_data(str(listval)))41                individual[k] = list_vals_to_process42        return individual43    def gen_pata_data(self, bio_val):44        """45        Generate Pata Data46        """47        pata_data = []48        pata_data.append({'original': bio_val})49        pata_data.append(self.synonyms(bio_val))50        pata_data.append(self.antonym(bio_val))51        pata_data.append(self.syzygy(bio_val))52        pata_data.append(self.anomaly(bio_val))53        pata_data.append(self.clinamen(bio_val))54        return pata_data55    def gen_enc_list(self, clear_text):56        """57        Generate a list of encrypted58        items59        """60        encrypted = {}61        temp_enc_list = []62        for e in self.encryption_dict:63            for p in clear_text:64                temp_enc_list.append(self.encryption_dict[e]().hash(p))65            encrypted[e] = temp_enc_list66            temp_enc_list = []67        return encrypted68    def synonyms(self, bio_val):69        """70        Generate synonyms of input data71        """72        synonyms = Synonym().generate_synonym(bio_val)73        synonyms = list(set(synonyms['results']))74        new_synonyms = []75        clear_text = []76        encrypted = {}77        for i in synonyms:78            new_synonyms = new_synonyms + self.subsitutor(i)79        clear_text = list(set(new_synonyms + synonyms))80        encrypted = self.gen_enc_list(clear_text)81        return {'synonym': {'clear_text': clear_text, 'encrypted': encrypted}}82    def antonym(self, bio_val):83        """84        Generate antonyms of input data85        """86        antonyms = Antonym().generate_antonym(bio_val)87        antonyms = list(set(antonyms['results']))88        new_antonyms = []89        clear_text = []90        encrypted = {}91        for i in antonyms:92            new_antonyms = new_antonyms + self.subsitutor(i)93        clear_text = list(set(new_antonyms + antonyms))94        encrypted = self.gen_enc_list(clear_text)95        return {'antonyms': {'clear_text': clear_text, 'encrypted': encrypted}}96    def syzygy(self, bio_val):97        """98        Generate syzygy of input data99        """100        syzygys = Syzygy().generate_syzygy(bio_val)101        syzygys = list(set(syzygys['results']))102        new_syzygys = []103        clear_text = []104        encrypted = {}105        for i in syzygys:106            new_syzygys = new_syzygys + self.subsitutor(i)107        clear_text = list(set(new_syzygys + syzygys))108        encrypted = self.gen_enc_list(clear_text)109        return {'syzygys': {'clear_text': clear_text, 'encrypted': encrypted}}110    def anomaly(self, bio_val):111        """112        Generate anomaly of input data113        """114        anomalies = Anomaly().generate_anomaly(bio_val, self.words, 1)115        anomalies = list(set(anomalies['results']))116        new_anomalies = []117        clear_text = []118        encrypted = {}119        for i in anomalies:120            new_anomalies = new_anomalies + self.subsitutor(i)121        clear_text = list(set(new_anomalies + anomalies))122        encrypted = self.gen_enc_list(clear_text)123        return {124            'anomalies': {125                'clear_text': clear_text,126                'encrypted': encrypted}}127    def clinamen(self, bio_val):128        """129        Generate clinamen of input data130        """131        clinamen = Clinamen().generate_clinamen(bio_val, self.words, 1)132        clinamen = list(set(clinamen['results']))133        new_clinamen = []134        clear_text = []135        encrypted = {}136        for i in clinamen:137            new_clinamen = new_clinamen + self.subsitutor(i)138        clear_text = list(set(new_clinamen + clinamen))139        encrypted = self.gen_enc_list(clear_text)140        return {'clinamen': {'clear_text': clear_text, 'encrypted': encrypted}}141    def subsitutor(self, pwd):142        """143        Generate common character144        substitutions145        """146        new_pwds = []147        for s in self.substitutors_dict:148            generator_class = self.substitutors_dict[s]()149            new_pwds.append(generator_class.substitute(pwd))150        #mung_it = MungSubstitutor()151        # new_pwds.append(mung_it.total_mung_simple(pwd))152        # new_pwds.append(mung_it.random_mung_simple(pwd))...test.py
Source:test.py  
1from unittest import TestCase2from project.caesar_cipher import rot133from project.caesar_cipher import encrypt as caesar_cipher_encrypt4from project.caesar_cipher import decrypt as caesar_cipher_decrypt5from project.crack_caesar_cipher import crack_caesar_cipher6from project.plaintext_recogniser import PlaintextRecogniser7class CaesarCipherTests(TestCase):8	'''Tests the Caesar Cipher (& ROT13) encryption and decryption9	as some properties of those functions like that ROT13 is10	commutitive.11	'''12	def test_rot13(self):13		clear_text = "The brown fox jumped over the cow in the dark field."14		self.assertEqual(rot13(clear_text), "GUROEBJASBKWHZCRQBIREGURPBJVAGURQNEXSVRYQ")15	def test_rot13_communtivity(self):16		'''Tests that that this ROT13 implemention is commutitive'''17		clear_text = "Hello world! Goodbye world!"18		# the returned decrypted text will be uppercase and contain no spaces/puncuation19		self.assertEqual(decrypted_text(clear_text), rot13(rot13(clear_text)))20	def test_encrpyt(self):21		'''Tests that you can do a caesar cipher with an arbitary shift value'''22		clear_text = "Hello world!"23		cipher_text = caesar_cipher_encrypt(clear_text, 3)24		self.assertEqual(cipher_text, "KHOORZRUOG")25	def test_encrpyt_2(self):26		'''Tests that you can do a caesar cipher with an arbitary shift value'''27		clear_text = "Hello world!"28		cipher_text = caesar_cipher_encrypt(clear_text, 5)29		self.assertEqual(cipher_text, "MJQQTBTWQI")30	def test_decrypt(self):31		clear_text = "Hello world!"32		decryption = caesar_cipher_decrypt(caesar_cipher_encrypt(clear_text, 3), 3)33		self.assertEqual(decryption, decrypted_text(clear_text))34	def test_encrpyt_with_large_shift(self):35		'''Tests that the caesar cipher works when given a shift value greater than 25'''36		clear_text = "Hello World!"37		cipher_text = caesar_cipher_encrypt(clear_text, 29)38		self.assertEqual(cipher_text, "KHOORZRUOG")39	def test_encrypt_with_negative_shift(self):40		'''Tests that the caesar cipher is implmented correctly if given a41		negative shift value, i.e. we want to shift the characters X place42		to the left.43		'''44		clear_text = "Hello world"45		self.assertEqual(caesar_cipher_encrypt(clear_text, -3), "EBIILTLOIA")46	def test_encrpyt_with_large_negative_shift(self):47		'''Tests that the if we give the caesar cipher function a shift48		less than -26 we still get the expected result49		'''50		clear_text = "Hello World"51		self.assertEqual(caesar_cipher_encrypt(clear_text, -29), "EBIILTLOIA")52class PlaintextRecogniserTest(TestCase):53	ptr = PlaintextRecogniser()54	def test_unigram_entropy(self):55		'''Simple bog standard test of relative entropy measurer'''56		clear_text = "THIS IS SOME SAMPLE TEXT HERE."57		result = self.ptr._measure_relative_unigram_entropy(clear_text, self.ptr.frequencies['letters'])58		self.assertAlmostEqual(result, 2.0202, places=4)59	def test_unigram_entropy_empty_string(self):60		'''Tests that if we give it an empty string it doesn't die '''61		clear_text = ""62		result = self.ptr._measure_relative_unigram_entropy(clear_text, self.ptr.frequencies['letters'])63		self.assertEqual(result, 0.0)64class CrackingCaesarCipherTest(TestCase):65	def test_crack_rot13(self):66		clear_text = "This is some sample text here."67		shift, decryption = crack_caesar_cipher(rot13(clear_text))68		self.assertEqual(shift, 13)69		self.assertEqual(decryption, "THISISSOMESAMPLETEXTHERE")70	def test_crack_caesar_cipher(self):71		clear_text = "Mr. Obama, seeking to address an outcry."72		shift, decryption = crack_caesar_cipher(caesar_cipher_encrypt(clear_text, 16))73		self.assertEqual(shift, 16)74		self.assertEqual(decryption, decrypted_text(clear_text))75	def test_crack_long_string(self):76		clear_text = "Mr. Obama, seeking to address an outcry that has shaken public confidence in \77		the new health law, told reporters at the White House that the changes should allow most people\78		to retain."79		shift, decryption = crack_caesar_cipher(caesar_cipher_encrypt(clear_text, 5))80		self.assertEqual(shift, 5)81		self.assertEqual(decryption, decrypted_text(clear_text))82def decrypted_text(clear_text):83	'''Were we to decrpyt encrpyted text we would expect84	all the puncuation to be removed and all the characters85	to be uppercase.86	'''87	unencrypted_clear_text = ""88	for c in clear_text.upper():89		if c.isupper():90			unencrypted_clear_text += c...plaintext_recogniser.py
Source:plaintext_recogniser.py  
1import json2import math3class PlaintextRecogniser(object):4    frequencies = {} # dictionary of frequency statistics for a given language5    def __init__(self, language='EN'):6        if language == 'EN':7            self._get_frequency_data('project/frequencies.json') # TODO: tidy this shit up8        else:9            raise Exception("Unknown language - we have no frequency data on that language")10    def measure_similarity(self, clear_text):11        unigrams = self._measure_relative_unigram_entropy(clear_text, self.frequencies['letters'])12        digraphs = self._measure_relative_digraph_entropy(clear_text, self.frequencies['digraphs'])13        return unigrams + digraphs14    def _measure_relative_unigram_entropy(self, clear_text, letter_frequencies):15        '''This function measures the relative entropy (sometimes called the16        Kullback-Leibler divergence) of a string relative to the standard17        distribution of letters in the english language.18        '''19        if len(clear_text) is 0:20            return 0.021        sum_ = 0.022        for c in clear_text:23            if c.isupper():24                sum_ += math.log(letter_frequencies[c])25        return sum_ / math.log(2) / len(clear_text)26    def _measure_relative_digraph_entropy(self, clear_text, diagraph_frequencies):27        '''Uses known common diagraph (two character pairs) in the english 28        language to better predict the correct crack29        '''30        sum_ = 0.031        length = len(clear_text)32        if length is 0:33            return 0.034        for i in range(0, length-2):35            try:36                diagraph = clear_text[i] + clear_text[i+1]37                sum_ += math.log(diagraph_frequencies[diagraph])38            except KeyError:39                pass # we have no data on this possible diagraph - ignore40        return sum_ / math.log(2) / len(clear_text) # bits of entropy per character41    def _get_frequency_data(self, filename):42        '''Loads in the letter/diagram/etc. frequency data from43        the JSON file into the class44        Returns: None45        '''46        # get the frequencies data loaded in from the JSON file47        json_data = open(filename)48        self.frequencies = json.load(json_data)...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
