def generate_diceware_password(word_count=6): import random passphrase = [] if quantum: if verbose: print("|Gathering quantum data...".ljust(38) + "|") data_count = word_count * 5 quantum_data = quantumrandom.uint16(data_count) dice = (int("".join([str(y) for y in (quantum_data % 6) + 1]))) roll = [str(dice)[i:i+5] for i in range(0, len(str(dice)), 5)] if verbose: print("|" + str(dice).ljust(37) + "|") for i in roll: passphrase.append(word_dict[int(i)]) else: for words in range(0, word_count): this_index = 0 for position in range(0, 5): digit = random.randint(1, 6) this_index += digit * pow(10, position) passphrase.append(word_dict[this_index]) if verbose: print(this_index) return ' '.join(passphrase)
def quantum_random(): """ returns a 32 bit unsigned integer quantum random number """ import quantumrandom data16 = quantumrandom.uint16(array_length=2) assert data16.flags['C_CONTIGUOUS'] data32 = data16.view(np.dtype('uint32'))[0] return data32
def _roll_dice(largestKey): final = None while (final == None) or (final > largestKey): dice = quantumrandom.uint16(ID_LEN) final = int("".join([str(y) for y in (dice % MAX_DIE_VALUE) + 1])) return str(final)
async def roll(self, ctx, dice: str): if not await channelcheck(ctx): return try: dicesplit = dice.split('d', 1) if len(dicesplit) == 2: try: amount = int(dicesplit[0]) size = int(dicesplit[1]) if amount <= 0 or size <= 0: raise ValueError('Invalid dice defined!') print(f'amount: {amount} | size: {size}') except ValueError as ex: err = f'Invalid dice defined!' await ctx.channel.send(err) return str_list = [] total = 0 embed = discord.Embed(title=f'{dice} Dice Roll', color=int(os.getenv("DEFAULT_COLOR"))) for count in range(0, amount): seed = quantumrandom.uint16(array_length=1)[0] random.seed(seed) val = random.randint(1, size) str_list.append(val) total += val if len(str_list) > 15: desc = '(' for i in range(0, 15): if (str_list[i] == 1 or str_list[i] == size): desc += f' **{str_list[i]}**,' else: desc += f' {str_list[i]},' desc = desc[:-1] + ' ...)' embed.set_footer( text='Results have been trimmed for formatting.') else: desc = '(' for i in range(0, len(str_list)): if (str_list[i] == 1 or str_list[i] == size): desc += f' **{str_list[i]}**,' else: desc += f' {str_list[i]},' desc = desc[:-1] + ')' embed.add_field(name='Result', value=desc, inline=False) embed.add_field(name='Total', value=str(total), inline=False) await ctx.channel.send(embed=embed) except Exception as ex: err = f'Error Rolling the dice' logger.error( f'Time: {datetime.now()} | From User: {ctx.author.name} | Command: {ctx.command} | Error: {ex} | Info: {err} | Trace: {traceback.format_exc()}' ) await ctx.channel.send(err)
def main(): args = sys.argv[1:] usage = "diceware.py number_of_words [path_to_wordfile]\n" if (len(args) != 1) and (len(args) != 2): print usage exit(1) if len(args) > 1: if os.path.exists(args[1]): worddict = _wordlist_to_dict(args[1]) else: worddict = _wordlist_to_dict( resource_filename(Requirement.parse("quantum_diceware"), "quantum_diceware/wordlists/english.asc")) numbers = [] for i in xrange(0, int(args[0])): numbers.append(quantumrandom.uint16(ID_LEN)) lookups = map(lambda x: "".join([str(y) for y in (x % MAX_DIE_VALUE) + 1]), numbers) print[worddict[x] for x in lookups]
def quantum_random(pure=False): """ Returns a quantum random number as a 32 bit unsigned integer. Does this by making a network request to the ANU Quantum Random Number Generator web service, so an internet connection is required. Args: pure (bool): if False, mixes this data with pseudorandom data for security. Otherwise returns the raw quantum numbers that were sent over the web (i.e. subject to MitM attacks). Requirements: quantumrandom >= 1.9.0 Returns: numpy.uint32: the random number """ import numpy as np import os import quantumrandom # Data was sent over a network qr_data16 = quantumrandom.uint16(array_length=2) nbytes = qr_data16.size * qr_data16.dtype.itemsize if pure: data16 = qr_data16 else: # Cryptographically generated buf = memoryview(os.urandom(nbytes)) pr_data16 = np.frombuffer(buf, dtype=qr_data16.dtype) # xor to mix data data16 = (pr_data16 ^ qr_data16) assert data16.flags['C_CONTIGUOUS'] data32 = data16.view(np.dtype('uint32'))[0] return data32
async def coinflip(self, ctx, typestr: str, opponent: discord.User = None): if not await channelcheck(ctx): return try: timeout = 60 if typestr is None or (typestr.lower() != 'heads' and typestr.lower() != 'tails'): return if opponent is not None: if opponent.id == ctx.author.id or opponent.id == self.bot.user.id: return def check(reaction, user): if opponent is None: return ((user.id != ctx.author.id and user.id != self.bot.user.id) and str(reaction.emoji) == '✔') or (user.id == ctx.author.id and str(reaction.emoji) == '❌') else: return user.id == opponent.id and (str( reaction.emoji) == '✔' or str(reaction.emoji) == '❌') seed = quantumrandom.uint16(array_length=1)[0] hashval = hashlib.sha256(str(seed).encode()).hexdigest() embedobj = discord.Embed( title=f'Coin Flip', description='Please react to this message to participate in the ' 'coinflip!', color=int(os.getenv("DEFAULT_COLOR"))) embedobj.set_footer( text= 'The user who initiated the flip can cancel by reacting with \'❌\' before' f' it has been accepted.\nNote this request will timeout after {timeout} seconds.' ) embedobj.add_field(name='Requested By', value=f'<@{ctx.author.id}>') embedobj.add_field(name='Choice', value=typestr.lower()) if opponent is None: embedobj.add_field(name='Opponent', value='Anyone') else: embedobj.add_field(name='Opponent', value=f'<@{opponent.id}>') embedobj.add_field(name='Hashed Seed', value=hashval) messageobj = await ctx.channel.send(embed=embedobj) await messageobj.add_reaction("✔") await messageobj.add_reaction("❌") try: reactionObj, userObj = await self.bot.wait_for("reaction_add", timeout=timeout, check=check) if str(reactionObj.emoji) == "✔": await performflip(ctx, userObj, typestr, seed) else: try: await ctx.message.delete() finally: await messageobj.delete() except asyncio.TimeoutError as error: print(f'Coin Flip from {ctx.author.name} has timed out') try: await ctx.message.delete() finally: await messageobj.delete() except Exception as ex: err = f'Error flipping the coin.' logger.error( f'Time: {datetime.now()} | From User: {ctx.author.name} | Command: {ctx.command} | Choice: {typestr} | Opponent: {opponent.name} | Error: {ex} | Info: {err} | Trace: {traceback.format_exc()}' ) await ctx.channel.send(err)
def test_uint16(self): ints = quantumrandom.uint16() assert len(ints) == 100 assert len(ints.data) == 200
def ggr_random_name_splits(): """ CommandLine: python -m wbia.viz.viz_graph2 ggr_random_name_splits --show Ignore: sshfs -o idmap=user lev:/ ~/lev Example: >>> # DISABLE_DOCTEST >>> from wbia.viz.viz_graph2 import * # NOQA >>> ggr_random_name_splits() """ import wbia.guitool as gt gt.ensure_qtapp() # nid_list = ibs.get_valid_nids(filter_empty=True) import wbia dbdir = '/media/danger/GGR/GGR-IBEIS' dbdir = (dbdir if ut.checkpath(dbdir) else ut.truepath('~/lev/media/danger/GGR/GGR-IBEIS')) ibs = wbia.opendb(dbdir=dbdir, allow_newdir=False) import datetime day1 = datetime.date(2016, 1, 30) day2 = datetime.date(2016, 1, 31) orig_filter_kw = { 'multiple': None, # 'view': ['right'], # 'minqual': 'good', 'is_known': True, 'min_pername': 2, } orig_aids = ibs.filter_annots_general(filter_kw=ut.dict_union( orig_filter_kw, { 'min_unixtime': ut.datetime_to_posixtime(ut.date_to_datetime(day1, 0.0)), 'max_unixtime': ut.datetime_to_posixtime(ut.date_to_datetime(day2, 1.0)), }, )) orig_all_annots = ibs.annots(orig_aids) orig_unique_nids, orig_grouped_annots_ = orig_all_annots.group( orig_all_annots.nids) # Ensure we get everything orig_grouped_annots = [ ibs.annots(aids_) for aids_ in ibs.get_name_aids(orig_unique_nids) ] # pip install quantumrandom if False: import quantumrandom data = quantumrandom.uint16() seed = data.sum() print('seed = %r' % (seed, )) # import Crypto.Random # from Crypto import Random # quantumrandom.get_data() # StrongRandom = Crypto.Random.random.StrongRandom # aes.reseed(3340258) # chars = [str(chr(x)) for x in data.view(np.uint8)] # aes_seed = str('').join(chars) # aes = Crypto.Random.Fortuna.FortunaGenerator.AESGenerator() # aes.reseed(aes_seed) # aes.pseudo_random_data(10) orig_rand_idxs = ut.random_indexes(len(orig_grouped_annots), seed=3340258) orig_sample_size = 75 random_annot_groups = ut.take(orig_grouped_annots, orig_rand_idxs) orig_annot_sample = random_annot_groups[:orig_sample_size] # OOOPS MADE ERROR REDO ---- filter_kw = { 'multiple': None, 'view': ['right'], 'minqual': 'good', 'is_known': True, 'min_pername': 2, } filter_kw_ = ut.dict_union( filter_kw, { 'min_unixtime': ut.datetime_to_posixtime(ut.date_to_datetime(day1, 0.0)), 'max_unixtime': ut.datetime_to_posixtime(ut.date_to_datetime(day2, 1.0)), }, ) refiltered_sample = [ ibs.filter_annots_general(annot.aids, filter_kw=filter_kw_) for annot in orig_annot_sample ] is_ok = np.array(ut.lmap(len, refiltered_sample)) >= 2 ok_part_orig_sample = ut.compress(orig_annot_sample, is_ok) ok_part_orig_nids = [x.nids[0] for x in ok_part_orig_sample] # Now compute real sample aids = ibs.filter_annots_general(filter_kw=filter_kw_) all_annots = ibs.annots(aids) unique_nids, grouped_annots_ = all_annots.group(all_annots.nids) grouped_annots = grouped_annots_ # Ensure we get everything # grouped_annots = [ibs.annots(aids_) for aids_ in ibs.get_name_aids(unique_nids)] pop = len(grouped_annots) pername_list = ut.lmap(len, grouped_annots) groups = wbia.annots.AnnotGroups(grouped_annots, ibs) match_tags = [ut.unique(ut.flatten(t)) for t in groups.match_tags] tag_case_hist = ut.dict_hist(ut.flatten(match_tags)) print('name_pop = %r' % (pop, )) print('Annots per Multiton Name' + ut.repr3(ut.get_stats(pername_list, use_median=True))) print('Name Tag Hist ' + ut.repr3(tag_case_hist)) print('Percent Photobomb: %.2f%%' % (tag_case_hist['photobomb'] / pop * 100)) print('Percent Split: %.2f%%' % (tag_case_hist['splitcase'] / pop * 100)) # Remove the ok part from this sample remain_unique_nids = ut.setdiff(unique_nids, ok_part_orig_nids) remain_grouped_annots = [ ibs.annots(aids_) for aids_ in ibs.get_name_aids(remain_unique_nids) ] sample_size = 75 import vtool as vt vt.calc_sample_from_error_bars(0.05, pop, conf_level=0.95, prior=0.05) remain_rand_idxs = ut.random_indexes(len(remain_grouped_annots), seed=3340258) remain_sample_size = sample_size - len(ok_part_orig_nids) remain_random_annot_groups = ut.take(remain_grouped_annots, remain_rand_idxs) remain_annot_sample = remain_random_annot_groups[:remain_sample_size] annot_sample_nofilter = ok_part_orig_sample + remain_annot_sample # Filter out all bad parts annot_sample_filter = [ ibs.annots(ibs.filter_annots_general(annot.aids, filter_kw=filter_kw_)) for annot in annot_sample_nofilter ] annot_sample = annot_sample_filter win = None from wbia.viz import viz_graph2 for annots in ut.InteractiveIter(annot_sample): if win is not None: win.close() win = viz_graph2.make_qt_graph_interface(ibs, aids=annots.aids, init_mode='rereview') print(win) sample_groups = wbia.annots.AnnotGroups(annot_sample, ibs) flat_tags = [ut.unique(ut.flatten(t)) for t in sample_groups.match_tags] print('Using Split and Photobomb') is_positive = ['photobomb' in t or 'splitcase' in t for t in flat_tags] num_positive = sum(is_positive) vt.calc_error_bars_from_sample(sample_size, num_positive, pop, conf_level=0.95) print('Only Photobomb') is_positive = ['photobomb' in t for t in flat_tags] num_positive = sum(is_positive) vt.calc_error_bars_from_sample(sample_size, num_positive, pop, conf_level=0.95) print('Only SplitCase') is_positive = ['splitcase' in t for t in flat_tags] num_positive = sum(is_positive) vt.calc_error_bars_from_sample(sample_size, num_positive, pop, conf_level=0.95)