コード例 #1
0
def resetPass(customCommand,test=False):
	from random import sample as randomize
	from random import random
	from os.path import exists
	# Opens the Adj, Adv, and Noun files as arrays
	av = open(sys.path[0]+"/Adv").read().splitlines()
	aj = open(sys.path[0]+"/Adj").read().splitlines()
	nn = open(sys.path[0]+"/Noun").read().splitlines()
	# Just for fun, some statistics!
	totalCombos = len(av)*len(aj)*len(nn)
	combosFormatted = "{:,}".format(totalCombos)
	avLengths=[]
	for item in av:
		avLengths.append(len(item))
	ajLengths=[]
	for item in aj:
		ajLengths.append(len(item))
	nnLengths=[]
	for item in nn:
		nnLengths.append(len(item))
	from statistics import mean,median,mode
	print("-"*25+"\n"+
		  "Total adverbs: "+str(len(av))+"\n"+
		  "Total adjectives: "+str(len(aj))+"\n"+
		  "Total nouns: "+str(len(nn))+"\n"+
		  "Total possible combinations: "+combosFormatted+" (not factoring in numbers)\n"+
		  "Shortest possible passphrase length: "+str(min(avLengths)+min(ajLengths)+min(nnLengths))+"\n"+
		  "Longest possible passphrase length: "+str(max(avLengths)+max(ajLengths)+max(nnLengths)+5)+"\n"+
		  "Mean passphrase length: "+str(int(mean(avLengths)+mean(ajLengths)+mean(nnLengths)+4))+"\n"+
		  "Median passphrase length: "+str(int(median(avLengths)+median(ajLengths)+median(nnLengths))+4)+"\n"+
		  "Mode passphrase length: "+str(int(mode(avLengths)+mode(ajLengths)+mode(nnLengths))+4)+"\n"+
		  "-"*25)
	# Randomize the order of the arrays
	av = randomize(av,len(av))
	aj = randomize(aj,len(aj))
	nn = randomize(nn,len(nn))
	# Pick a random word from each randomized array
	newAdverb = av[int(random()*len(av))].capitalize()
	newAdjective = aj[int(random()*len(aj))].capitalize()
	newNoun = nn[int(random()*len(nn))].capitalize()
	# Possibly add a random number from 1 to 10,000
	if maybeNumber():
		from math import ceil
		number = str(ceil(random()*10000))
	else:
		number = ''
	# Assemble the passphrase
	newPassphrase = number+newAdverb+newAdjective+newNoun
	#################################################################### Needs attention
	print("The new passphrase will be: "+newPassphrase)
	print("Total entropy: ~"+str(int(entropy(newPassphrase))))
	if customCommand == ' {PASSPHRASE}':
		print("Password display command not found. Aborting.")
		exit()
	if not test:
		import RouterPasswording
		RouterPasswording.newPassphrase(newPassphrase)
	from os import system as execute
	execute(customCommand.replace("{password}",newPassphrase).replace("{passphrase}",newPassphrase))
コード例 #2
0
 def __prune(self, i):
     if i and i % self.prune_at:
         return
     for w, cc in tqdm(self.cc_by_w.items()):
         if len(cc) < self.n * 2:
             continue
         randomize(cc)
         self.cc_by_w[w] = cc[:self.n]
コード例 #3
0
 def __subsample(self, n):
     all = zip(self.documents, self.tags)
     randomize(all)
     pos, neg = [], []
     for doc, tag in all:
         if tag == 'positive' and len(pos) < n:
             pos.append((doc, tag))
         elif tag == 'negative' and len(neg) < n:
             neg.append((doc, tag))
     sample = pos + neg
     self.documents, self.tags = zip(*sample)
     self.paths = range(n * 2)
コード例 #4
0
    def trackArp(self, nn, offset):
        """ Special trackbar() for arpeggiator. """

        if self.drumType:
            error("%s Arpeggiate: Incompatible with DRUMTYPE. Try MALLET?" % self.name)

        notes = [[self.adjustNote(x.pitch), x.velocity] for x in nn]
        notes.sort()

        random = self.direction == 'RANDOM'

        if self.arpDirection == "DOWN":
            notes.reverse()

        elif self.arpDirection == "BOTH":
            z = notes[:]
            z.reverse()
            notes.extend(z[1:-1])

        duration = self.arpRate             # duration of each note
        count = nn[0].duration // duration   # total number to play
        if count < 1:
            count = 1

        while 1:
            nn = range(len(notes))
            if random:
                random.randomize(nn)
            for i in nn:
                n = notes[i]

                self.sendNote(offset,
                              self.getDur(duration), n[0],
                              self.adjustVolume(n[1], offset))
                count -= 1
                if not count:
                    break

                offset += duration

                if self.arpDecay:
                    n[1] = int(n[1] + (n[1] * self.arpDecay))
                    if n[1] < 1:
                        n[1] = 1
                    if n[1] > 127:
                        n[1] = 127

            if not count:
                break
コード例 #5
0
    def trackArp(self, nn, offset):
        """ Special trackbar() for arpeggiator. """

        if self.drumType:
            error("%s Arpeggiate: Incompatible with DRUMTYPE. Try MALLET?" % self.name)

        notes = [[self.adjustNote(x.pitch), x.velocity] for x in nn]
        notes.sort()

        random = self.direction == 'RANDOM'

        if self.arpDirection == "DOWN":
            notes.reverse()

        elif self.arpDirection == "BOTH":
            z = notes[:]
            z.reverse()
            notes.extend(z[1:-1])

        duration = self.arpRate             # duration of each note
        count = nn[0].duration // duration   # total number to play
        if count < 1:
            count = 1

        while 1:
            nn = range(len(notes))
            if random:
                random.randomize(nn)
            for i in nn:
                n = notes[i]

                self.sendNote(offset,
                              self.getDur(duration), n[0],
                              self.adjustVolume(n[1], offset))
                count -= 1
                if not count:
                    break

                offset += duration

                if self.arpDecay:
                    n[1] = int(n[1] + (n[1] * self.arpDecay))
                    if n[1] < 1:
                        n[1] = 1
                    if n[1] > 127:
                        n[1] = 127

            if not count:
                break
コード例 #6
0
ファイル: generate.py プロジェクト: slosar/randomfield
    def generate_delta_field(self,
                             smoothing_length_Mpc_h=0.,
                             seed=None,
                             save_potential=True,
                             show_plot=False,
                             save_plot_name=None):
        """
        Generate a delta-field realization.

        The delta field is calculated at redshift zero and sampled from a
        distribution with mean zero and k-space variance proportional to
        the smoothed power spectrum.

        No new memory is allocated unless the ``save_potential`` option is
        selected.

        Parameters
        ----------
        smoothing_length : float, optional
            Length scale on which to smooth the generated delta field in Mpc/h.
            If not specified, no smoothing will be applied.
        seed : int, optional
            Random number seed to use. Specifying an explicit seed enables you
            to generate a reproducible delta field.  If no seed is specified,
            a randomized seed will be used.
        save_potential : bool, optional
            Save the k-space field delta(kx,ky,kz) / k**2 so that it can be
            used for later calculations of the lensing potential or the
            bulk velocity vector field. The first time this option is used,
            additional memory is allocated, approximately doubling the total
            memory usage.
        show_plot : bool, optional
            Show a (y,z) slice through the generated delta field using the
            optional matplotlib library. The plot will need to be dismissed
            after it displays before the program continues.  Use the
            ``save_plot_name`` option to generate and save the plot without
            requiring any user interaction.
        save_plot_name : str, optional
            Name of a file where the generated delta field slice plot should
            be saved.  The file extension provided determines the image file
            format that will be used. This option can be used with ``show_plot``
            either ``True`` or ``False``.

        Returns
        -------
        numpy.narray
            3D numpy array of delta field values. The returned array is a
            view into our internal memory buffer and will be overwritten by
            subsequent operations.
        """
        powertools.fill_with_log10k(self.plan_c2r.data_in,
                                    spacing=self.grid_spacing_Mpc_h,
                                    packed=True)
        self.smoothed_power = powertools.filter_power(self.power,
                                                      smoothing_length_Mpc_h)
        powertools.tabulate_sigmas(self.plan_c2r.data_in,
                                   power=self.smoothed_power,
                                   spacing=self.grid_spacing_Mpc_h,
                                   packed=True)
        random.randomize(self.plan_c2r.data_in, seed=seed)
        transform.symmetrize(self.plan_c2r.data_in, packed=True)
        if save_potential:
            # Fill self.potential with values of k**2.
            if self.potential is None:
                self.potential = np.empty_like(self.plan_c2r.data_in)
            self.potential.imag = 0.
            kx2_grid, ky2_grid, kz2_grid = powertools.create_ksq_grids(
                self.potential, spacing=self.grid_spacing_Mpc_h, packed=True)
            np.add(kx2_grid, ky2_grid, out=self.potential.real)
            self.potential.real += kz2_grid
            # Replace k**2 with 1 / k**2 except at k=0.
            old_settings = np.seterr(divide='ignore')
            np.reciprocal(self.potential.real, out=self.potential.real)
            np.seterr(**old_settings)
            self.potential[0, 0, 0] = 0.
            # Multiply by delta(k).
            self.potential *= self.plan_c2r.data_in
        else:
            self.potential = None
        delta = self.plan_c2r.execute()
        self.delta_field_rms = np.std(delta.flat)
        if self.verbose:
            print('Delta field has standard deviation {0:.3f}.'.format(
                self.delta_field_rms))

        if show_plot or save_plot_name is not None:
            self.plot_slice(
                show_plot=show_plot, save_plot_name=save_plot_name,
                clip_symmetric=True, label='Matter inhomogeneity ' +\
                    '$\delta(r) = \\rho(r)/\overline{\\rho} - 1$')

        return delta
コード例 #7
0
ファイル: generate.py プロジェクト: slosar/randomfield
    def generate_delta_field(self, smoothing_length_Mpc_h=0., seed=None,
                             save_potential=True,
                             show_plot=False, save_plot_name=None):
        """
        Generate a delta-field realization.

        The delta field is calculated at redshift zero and sampled from a
        distribution with mean zero and k-space variance proportional to
        the smoothed power spectrum.

        No new memory is allocated unless the ``save_potential`` option is
        selected.

        Parameters
        ----------
        smoothing_length : float, optional
            Length scale on which to smooth the generated delta field in Mpc/h.
            If not specified, no smoothing will be applied.
        seed : int, optional
            Random number seed to use. Specifying an explicit seed enables you
            to generate a reproducible delta field.  If no seed is specified,
            a randomized seed will be used.
        save_potential : bool, optional
            Save the k-space field delta(kx,ky,kz) / k**2 so that it can be
            used for later calculations of the lensing potential or the
            bulk velocity vector field. The first time this option is used,
            additional memory is allocated, approximately doubling the total
            memory usage.
        show_plot : bool, optional
            Show a (y,z) slice through the generated delta field using the
            optional matplotlib library. The plot will need to be dismissed
            after it displays before the program continues.  Use the
            ``save_plot_name`` option to generate and save the plot without
            requiring any user interaction.
        save_plot_name : str, optional
            Name of a file where the generated delta field slice plot should
            be saved.  The file extension provided determines the image file
            format that will be used. This option can be used with ``show_plot``
            either ``True`` or ``False``.

        Returns
        -------
        numpy.narray
            3D numpy array of delta field values. The returned array is a
            view into our internal memory buffer and will be overwritten by
            subsequent operations.
        """
        powertools.fill_with_log10k(
            self.plan_c2r.data_in, spacing=self.grid_spacing_Mpc_h, packed=True)
        self.smoothed_power = powertools.filter_power(
            self.power, smoothing_length_Mpc_h)
        powertools.tabulate_sigmas(
            self.plan_c2r.data_in, power=self.smoothed_power,
            spacing=self.grid_spacing_Mpc_h, packed=True)
        random.randomize(self.plan_c2r.data_in, seed=seed)
        transform.symmetrize(self.plan_c2r.data_in, packed=True)
        if save_potential:
            # Fill self.potential with values of k**2.
            if self.potential is None:
                self.potential = np.empty_like(self.plan_c2r.data_in)
            self.potential.imag = 0.
            kx2_grid, ky2_grid, kz2_grid = powertools.create_ksq_grids(
                self.potential, spacing=self.grid_spacing_Mpc_h, packed=True)
            np.add(kx2_grid, ky2_grid, out=self.potential.real)
            self.potential.real += kz2_grid
            # Replace k**2 with 1 / k**2 except at k=0.
            old_settings = np.seterr(divide='ignore')
            np.reciprocal(self.potential.real, out=self.potential.real)
            np.seterr(**old_settings)
            self.potential[0, 0, 0] = 0.
            # Multiply by delta(k).
            self.potential *= self.plan_c2r.data_in
        else:
            self.potential = None
        delta = self.plan_c2r.execute()
        self.delta_field_rms = np.std(delta.flat)
        if self.verbose:
            print('Delta field has standard deviation {0:.3f}.'
                  .format(self.delta_field_rms))

        if show_plot or save_plot_name is not None:
            self.plot_slice(
                show_plot=show_plot, save_plot_name=save_plot_name,
                clip_symmetric=True, label='Matter inhomogeneity ' +\
                    '$\delta(r) = \\rho(r)/\overline{\\rho} - 1$')

        return delta