python类choices()的实例源码

factories.py 文件源码 项目:MishMash 作者: nicfit 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def id3_date(self):
     d = self._fake.date_object()
     full_date = random.choices(["y", "n"], cum_weights=[15, 85]) == "y"
     return Date(year=d.year,
                 month=d.month if full_date else None,
                 day=d.day if full_date else None)
factories.py 文件源码 项目:pycon2017 作者: kennethlove 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def categories(self, create, extracted, **kwargs):
        categories = models.Category.objects.all()
        for category in random.choices(categories, k=random.randint(1, len(categories))):
            self.categories.add(category)
create_dummy_data.py 文件源码 项目:ablator 作者: ablator 项目源码 文件源码 阅读 17 收藏 0 点赞 0 评论 0
def random_user_name():
    return ''.join(random.choices(string.ascii_uppercase + string.digits, k=8))
saomd.py 文件源码 项目:yui 作者: item4 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def get_record_crystal(scout: Scout, seed: int=None) -> int:
    record_crystal = 0

    if scout.record_crystal:
        cases: List[int] = []
        chances: List[float] = []
        random.seed(seed)
        for case, chance in scout.record_crystal:
            cases.append(case)
            chances.append(chance)
        record_crystal = random.choices(cases, chances)[0]
        random.seed(None)

    return record_crystal
test_subvoat.py 文件源码 项目:voat 作者: Cightline 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def test_new_subvoat_creation():
    api_token = get_api_token()


    result = requests.post('%s/create_subvoat' % (base_address), {'username':'test_username', 
                                                                  'api_token':api_token,
                                                                  'subvoat_name':'test_%s' % (''.join(random.choices(string.ascii_letters, k=10)))})

    print(result.json())


# Try to create the same subvoat that already exists
test_subvoat.py 文件源码 项目:voat 作者: Cightline 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def test_posting():
    api_token = get_api_token()

    body  = ''.join(random.choices(string.ascii_letters, k=100))
    title = ''.join(random.choices(string.ascii_letters, k=10))

    print(requests.post('%s/submit_thread' % (base_address), {'username':'test_username', 
                                                            'api_token':api_token, 
                                                            'subvoat_name':'test_exists',
                                                            'title':title,
                                                            'body':body}).json())
test_subvoat.py 文件源码 项目:voat 作者: Cightline 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def test_posting_comment():
    api_token = get_api_token()
    body  = ''.join(random.choices(string.ascii_letters, k=100))

    data = requests.post('%s/get_threads' % (base_address), {'subvoat_name':'test_exists'}).json()

    thread_uuid = data['result'][0]['uuid']

    print(requests.post('%s/submit_comment' % (base_address), {'thread_uuid':thread_uuid, 
                                                              'username':'test_username', 
                                                              'api_token':api_token,
                                                              'body':body}).text)
performance_test.py 文件源码 项目:voat 作者: Cightline 项目源码 文件源码 阅读 45 收藏 0 点赞 0 评论 0
def generate_threads(self, count):
        api_token = self.get_api_token()

        for x in range(count):

            title = ''.join(random.choices(string.ascii_letters, k=10))
            body  = ''.join(random.choices(string.ascii_letters, k=100))


            result = requests.post('%s/submit_thread' % (self.base_address), {'username':'test_username',
                                                                              'api_token':api_token,
                                                                              'subvoat_name':'test_exists',
                                                                              'title':title,
                                                                              'body':body}).json()
test_utils.py 文件源码 项目:sparsereg 作者: Ohjeah 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def choices(l, k):
        for _ in range(k):
            yield random.choice(l)
run.py 文件源码 项目:pydantic 作者: samuelcolvin 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def rand_string(min_length, max_length, corpus=ALL):
    return ''.join(random.choices(corpus, k=random.randrange(min_length, max_length)))
numberwang.py 文件源码 项目:steely 作者: sentriz 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def numberwang():
    return random.choices(STRINGS, weights=WEIGHTS)
shout.py 文件源码 项目:steely 作者: sentriz 项目源码 文件源码 阅读 16 收藏 0 点赞 0 评论 0
def shout(message):
    parts = message.split('.')
    out = ''
    for part in parts:
        out += part.upper() + ''.join(random.choices(['!', '1'], weights=[5, 1], k=random.randint(2, 8)))
    return out
test_population.py 文件源码 项目:evol 作者: godatadriven 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def pick_n_random_parents(population, n_parents=2):
        return choices(population, k=n_parents)
test_population.py 文件源码 项目:evol 作者: godatadriven 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def test_breed_amount_works(self):
        pop1 = Population(chromosomes=self.chromosomes, eval_function=self.eval_func)
        pop1.survive(n=50).breed(parent_picker=lambda population: choices(population, k=2),
                                 combiner=lambda mom, dad: (mom + dad) / 2)
        assert len(pop1) == 200
        pop2 = Population(chromosomes=self.chromosomes, eval_function=self.eval_func)
        pop2.survive(n=50).breed(parent_picker=lambda population: choices(population, k=2),
                                 combiner=lambda mom, dad: (mom + dad) / 2, population_size=400)
        assert len(pop2) == 400
        assert pop2.intended_size == 400
population.py 文件源码 项目:evol 作者: godatadriven 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def survive(self, fraction=None, n=None, luck=False) -> 'Population':
        """Let part of the population survive.

        Remove part of the population. If both fraction and n are specified,
        the minimum resulting population size is taken.

        :param fraction: Fraction of the original population that survives.
            Defaults to None.
        :type fraction: float/None
        :param n: Number of individuals of the population that survive.
            Defaults to None.
        :type n: int/None
        :param luck: If True, individuals randomly survive (with replacement!)
            with chances proportional to their fitness. Defaults to False.
        :type luck: bool
        :return: self
        """
        if fraction is None:
            if n is None:
                raise ValueError('everyone survives! must provide either "fraction" and/or "n".')
            resulting_size = n
        elif n is None:
            resulting_size = round(fraction*len(self.individuals))
        else:
            resulting_size = min(round(fraction*len(self.individuals)), n)
        self.evaluate(lazy=True)
        if resulting_size == 0:
            raise RuntimeError('no one survived!')
        if resulting_size > len(self.individuals):
            raise ValueError('everyone survives! must provide "fraction" and/or "n" < population size')
        if luck:
            self.individuals = choices(self.individuals, k=resulting_size,
                                       weights=[individual.fitness for individual in self.individuals])
        else:
            sorted_individuals = sorted(self.individuals, key=lambda x: x.fitness, reverse=self.maximize)
            self.individuals = sorted_individuals[:resulting_size]
        return self
util.py 文件源码 项目:paneity 作者: reed-college 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
def random_string(n):
    return ''.join(random.choices(string.ascii_uppercase + string.ascii_lowercase + string.digits, k=n))
occupytenter.py 文件源码 项目:ababe 作者: unkcpz 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def run(self):
        # Create directory contain POSCARs
        import random
        import string
        import tempfile

        rd_suffix = ''.join(random.choices(string.ascii_uppercase
                                           + string.digits, k=5))
        working_path = os.getcwd()
        poscars_dir = os.path.join(working_path,
                                   'STRUCTURES_{0:}_{1:}'.format(self.comment,
                                                              rd_suffix))
        if not os.path.exists(poscars_dir):
            os.makedirs(poscars_dir)
        else:
            shutil.rmtree(poscars_dir)
            os.makedirs(poscars_dir)

        ogg = OccupyGenerator(self.cell)
        g = ogg.gen_nodup_trinary_alloy(Specie(self.s1), self.n1,
                                        Specie(self.s2), self.n2)

        if self.tr is not None:
            tr = (Specie(self.tr[0]), self.tr[1])
            applied_restriction = MinDistanceRestriction(tr)

        # For diff outmode
        if self.outmode == 'vasp':
            Output = VaspPOSCAR
            prefix = 'POSCAR_A{:}B{:}C{:}_'
            suffix = '.vasp'
        else:
            Output = YamlOutput
            prefix = 'STRUCTURE_A{:}B{:}C{:}_'
            suffix = '.yaml'

        for n_count, c in enumerate(g):
            if self.mpr:
                if self.tr is not None:
                    condition = c.is_primitive() and applied_restriction.is_satisfied(c)
                else:
                    condition = c.is_primitive()
            else:
                if self.tr is not None:
                    condition = applied_restriction.is_satisfied(c)
                else:
                    condition = True

            if condition:
                if self.refined:
                    c = c.get_refined_pcell()
                poscar = Output(c, 1)
                tf = tempfile.NamedTemporaryFile(mode='w+b', dir=poscars_dir,
                                                 prefix=prefix.format(self.n0, self.n1, self.n2),
                                                 suffix=suffix, delete=False)
                poscar.write(tf.name)
occupyexch.py 文件源码 项目:ababe 作者: unkcpz 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def run(self):
        # Create directory contain POSCARs
        import random
        import string

        rd_suffix = ''.join(random.choices(string.ascii_uppercase
                                           + string.digits, k=5))
        working_path = os.getcwd()
        out_dir = os.path.join(working_path,
                               'STRUCTURES_{0:}_{1:}'.format(self.comment,
                                                              rd_suffix))
        if not os.path.exists(out_dir):
            os.makedirs(out_dir)
        else:
            shutil.rmtree(out_dir)
            os.makedirs(out_dir)

        ogg = OccupyGenerator(self.cell)
        g = ogg.gen_nodup_exch(Specie(self.exch1), Specie(self.exch2), self.n)

        if self.tr is not None:
            tr = (Specie(self.tr[0]), self.tr[1])
            applied_restriction = MinDistanceRestriction(tr)

        for n_count, c in enumerate(g):
            if self.mpr:
                if self.tr is not None:
                    condition = c.is_primitive() and applied_restriction.is_satisfied(c)
                else:
                    condition = c.is_primitive()
            else:
                if self.tr is not None:
                    condition = applied_restriction.is_satisfied(c)
                else:
                    condition = True

            if condition:
                if self.refined:
                    c = c.get_refined_pcell()
                out = GeneralIO(c)
                f_suffix = ''.join(random.choices(string.ascii_uppercase
                                                 + string.digits, k=4))
                ofname = "STRUCTURE_{:}_{:}.{:}".format(c.comment, f_suffix, self.outmode)
                lastpath = os.path.join(out_dir, ofname)
                out.write_file(lastpath)
occupybiter.py 文件源码 项目:ababe 作者: unkcpz 项目源码 文件源码 阅读 17 收藏 0 点赞 0 评论 0
def run(self):
        # Create directory contain POSCARs
        import random
        import string

        rd_suffix = ''.join(random.choices(string.ascii_uppercase
                                           + string.digits, k=5))
        working_path = os.getcwd()
        out_dir = os.path.join(working_path,
                               'STRUCTURES_{0:}_{1:}'.format(self.comment,
                                                              rd_suffix))
        if not os.path.exists(out_dir):
            os.makedirs(out_dir)
        else:
            shutil.rmtree(out_dir)
            os.makedirs(out_dir)

        ogg = OccupyGenerator(self.cell)
        g = ogg.gen_nodup_of_ele(self.ele, self.n, self.speckle)
        # sym for getting degeneracy
        sym_perm = self.cell.get_symmetry_permutation()

        if self.tr is not None:
            tr = (Specie(self.tr[0]), self.tr[1])
            applied_restriction = MinDistanceRestriction(tr)

        for n_count, c in enumerate(g):
            if self.mpr:
                if self.tr is not None:
                    condition = c.is_primitive() and applied_restriction.is_satisfied(c)
                else:
                    condition = c.is_primitive()
            else:
                if self.tr is not None:
                    condition = applied_restriction.is_satisfied(c)
                else:
                    condition = True

            if condition:
                if self.refined:
                    c = c.get_refined_pcell()
                out = GeneralIO(c)
                f_suffix = ''.join(random.choices(string.ascii_uppercase
                                                 + string.digits, k=4))
                ofname = "STRUCTURE_{:}_D{:}D_{:}.{:}".format(c.comment, c.get_degeneracy(sym_perm),
                                                              f_suffix, self.outmode)
                lastpath = os.path.join(out_dir, ofname)
                out.write_file(lastpath)
occupymakert.py 文件源码 项目:ababe 作者: unkcpz 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def run(self):
        # Create directory contain POSCARs
        import random
        import string

        rd_suffix = ''.join(random.choices(string.ascii_uppercase
                                           + string.digits, k=5))
        working_path = os.getcwd()
        out_dir = os.path.join(working_path,
                                   'STRUCTURES_{0:}_{1:}'.format(self.comment,
                                                              rd_suffix))
        if not os.path.exists(out_dir):
            os.makedirs(out_dir)
        else:
            shutil.rmtree(out_dir)
            os.makedirs(out_dir)

        ogg = OccupyGenerator(self.cell)

        if self.tr is not None:
            tr = (Specie(self.tr[0]), self.tr[1])
            applied_restriction = MinDistanceRestriction(tr)


        for n1 in range(1, self.n - 1):
            for n2 in range(1, self.n - n1):
                g = ogg.gen_nodup_trinary_alloy(Specie(self.s1), n1,
                                                Specie(self.s2), n2)

                for n_count, c in enumerate(g):
                    if self.tr is not None:
                        condition = c.is_primitive() and applied_restriction.is_satisfied(c)
                    else:
                         condition = c.is_primitive()

                    if condition:
                        if self.refined:
                            c = c.get_refined_pcell()
                        out = GeneralIO(c)

                        f_suffix = ''.join(random.choices(string.ascii_uppercase
                                                          + string.digits, k=4))
                        ofname = "STRUCTURE_{:}_{:}.{:}".format(c.comment, f_suffix, self.outmode)
                        lastpath = os.path.join(out_dir, ofname)
                        out.write_file(lastpath)


问题


面经


文章

微信
公众号

扫码关注公众号