Python sqlalchemy.sql.expression.func.random() Examples

The following are 30 code examples of sqlalchemy.sql.expression.func.random(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module sqlalchemy.sql.expression.func , or try the search function .
Example #1
Source File: views.py    From website with MIT License 6 votes vote down vote up
def index():
    sorter = request.args.get("sorter", None)
    if sorter is None:
        sorter = "random"
        initial_sorting = True
    else:
        initial_sorting = False
    order = request.args.get("order", None)
    criterion = SORTER.get(sorter, DEFAULT_SORTER)
    if order == DEFAULT_ORDER:
        criterion = desc(criterion)

    projects = Project.query.filter(Project.is_active.is_(True)).order_by(
        nullslast(criterion)
    )
    return {
        "projects": projects,
        "sorter": sorter,
        "initial_sorting": initial_sorting,
        "order": order,
        "DEFAULT_ORDER": DEFAULT_ORDER,
    } 
Example #2
Source File: models.py    From SubredditSimulator with MIT License 6 votes vote down vote up
def post_comment_on(self, submission):
        comment = self.build_comment()

        # decide if we're going to post top-level or reply
        if (submission.num_comments == 0 or
                random.random() < 0.5):
            submission.add_comment(comment)
        else:
            comments = praw.helpers.flatten_tree(submission.comments)
            reply_to = random.choice(comments)
            reply_to.reply(comment)

        # update the database
        self.last_commented = datetime.now(pytz.utc)
        self.num_comments += 1
        db.add(self)
        db.commit() 
Example #3
Source File: models.py    From SubredditSimulator with MIT License 6 votes vote down vote up
def build_comment(self):
        comment = ""
        while True:
            # For each sentence, check how close to the average comment length
            # we are, then use the remaining percentage as the chance of
            # adding another sentence. For example, if we're at 70% of the
            # average comment length, there will be a 30% chance of adding
            # another sentence. We're also adding a fixed 10% on top of that
            # just to increase the length a little, and have some chance of
            # continuing once we're past the average.
            portion_done = len(comment) / float(self.avg_comment_len)
            continue_chance = 1.0 - portion_done
            continue_chance = max(0, continue_chance)
            continue_chance += 0.1
            if random.random() > continue_chance:
                break

            new_sentence = self.make_comment_sentence()
            comment += " " + new_sentence

        comment = comment.strip()
        
        return comment 
Example #4
Source File: dotabase.py    From MangoByte with MIT License 6 votes vote down vote up
def hello(self, ctx):
		"""Says hello

		WHAT MORE DO YOU NEED TO KNOW!?!?!? IS 'Says hello' REALLY NOT CLEAR ENOUGH FOR YOU!?!!11?!!?11!!?!??"""
		dota_hellos = [
			"slark_attack_11",
			"kunk_thanks_02",
			"meepo_scepter_06",
			"puck_ability_orb_03",
			"tink_spawn_07",
			"treant_ally_08",
			"wraith_lasthit_02",
			"timb_deny_08",
			"tech_pain_39",
			"meepo_attack_08",
			"slark_lasthit_02"
		]
		dota_response = random.choice(dota_hellos)
		response = session.query(Response).filter(Response.name == dota_response).first()
		print("hello: " + response.name)
		await self.play_response(response, ctx)

	# Plays the correct command for the given keyphrase and hero, if a valid one is given 
Example #5
Source File: random_data.py    From flask-shop with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def create_order_line(order, discounts):
    product = Product.query.order_by(func.random()).first()
    variant = product.variant[0]
    quantity = random.randrange(1, 5)
    variant.quantity += quantity
    variant.save()
    return OrderLine.create(
        order_id=order.id,
        product_name=variant.display_product(),
        product_sku=variant.sku,
        product_id=variant.sku.split("-")[0],
        is_shipping_required=variant.is_shipping_required,
        quantity=quantity,
        variant_id=variant.id,
        unit_price_net=variant.price,
    )


# step27 
Example #6
Source File: web.py    From calibre-web with GNU General Public License v3.0 6 votes vote down vote up
def render_archived_books(page, order):
    order = order or []
    archived_books = (
        ub.session.query(ub.ArchivedBook)
        .filter(ub.ArchivedBook.user_id == int(current_user.id))
        .filter(ub.ArchivedBook.is_archived == True)
        .all()
    )
    archived_book_ids = [archived_book.book_id for archived_book in archived_books]

    archived_filter = db.Books.id.in_(archived_book_ids)

    entries, random, pagination = calibre_db.fill_indexpage_with_archived_books(page,
                                                                                db.Books,
                                                                                archived_filter,
                                                                                order,
                                                                                allow_show_archived=True)

    name = _(u'Archived Books') + ' (' + str(len(archived_book_ids)) + ')'
    pagename = "archived"
    return render_title_template('index.html', random=random, entries=entries, pagination=pagination,
                                 title=name, page=pagename)

# ################################### Download/Send ################################################################## 
Example #7
Source File: api.py    From senlin with Apache License 2.0 6 votes vote down vote up
def action_acquire_random_ready(context, owner, timestamp):
    with session_for_write() as session:
        action = (session.query(models.Action).
                  filter_by(status=consts.ACTION_READY).
                  filter_by(owner=None).
                  order_by(func.random()).
                  with_for_update().first())

        if action:
            action.owner = owner
            action.start_time = timestamp
            action.status = consts.ACTION_RUNNING
            action.status_reason = 'The action is being processed.'
            action.save(session)

            return action 
Example #8
Source File: corpuses.py    From clgen with GNU General Public License v3.0 6 votes vote down vote up
def GetTextCorpus(self, shuffle: bool) -> str:
    """Concatenate the entire corpus into a string.

    Args:
      shuffle: If true, randomize order of contentfiles.

    Returns:
      A concatenated corpus string.
    """
    with self.preprocessed.Session() as session:
      query = session.query(preprocessed.PreprocessedContentFile.text).filter(
        preprocessed.PreprocessedContentFile.preprocessing_succeeded == True
      )
      if shuffle:
        query = query.order_by(func.random())
      return self.config.contentfile_separator.join([x[0] for x in query]) 
Example #9
Source File: random_data.py    From flask-shop with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def set_product_attributes(product, product_type):
    attr_dict = {}
    for product_attribute in product_type.product_attributes:
        value = random.choice(product_attribute.values)
        attr_dict[str(product_attribute.id)] = str(value.id)

    product.attributes = attr_dict
    product.save()


# step9 
Example #10
Source File: postgresql_specific.py    From SecuML with GNU General Public License v2.0 5 votes vote down vote up
def random_order(query):
    return query.order_by(func.random()) 
Example #11
Source File: corpuses.py    From clgen with GNU General Public License v3.0 5 votes vote down vote up
def GetTrainingData(self, shuffle: bool) -> np.ndarray:
    """Concatenate the entire encoded corpus into an array.

    Args:
      shuffle: If true, randomize order of encoded contentfiles.

    Returns:
      The encoded corpus.
    """
    with prof.Profile("GetTrainingData()"):
      # Load all indices from the database into memory, and keep them there.
      # This is to remove the latency from reading the contents from a
      # database.
      #
      # TODO(https://github.com/ChrisCummins/clgen/issues/128): Storing the
      # entire corpus in memory like this prevents training on corpuses larger
      # than system memory. Replace this method with an interface for streaming
      # data from the encoded database.
      if not self._indices_arrays:
        with self.encoded.Session() as session:
          query = session.query(encoded.EncodedContentFile)
          self._indices_arrays = [x.indices_array for x in query]

      if shuffle:
        random.shuffle(self._indices_arrays)

      return np.concatenate(self._indices_arrays) 
Example #12
Source File: models.py    From SubredditSimulator with MIT License 5 votes vote down vote up
def pick_submission_type(self):
        if not self.link_submissions:
            return "text"

        if random.random() < self.link_submission_chance:
            return "link"
        else:
            return "text" 
Example #13
Source File: models.py    From SubredditSimulator with MIT License 5 votes vote down vote up
def post_submission(self, subreddit, type=None):
        subreddit = self.session.get_subreddit(subreddit)

        title = self.title_model.make_short_sentence(300, tries=10000,
                max_overlap_total=MAX_OVERLAP_TOTAL,
                max_overlap_ratio=MAX_OVERLAP_RATIO)
        title = title.rstrip(".")

        if not type:
            type = self.pick_submission_type()

        if type == "link":
            url_source = random.choice(self.link_submissions)

            if url_source.over_18:
                title = "[NSFW] " + title

            subreddit.submit(title, url=url_source.url, send_replies=False)
        else:
            selftext = ""
            while len(selftext) < self.avg_selftext_len:
                new_sentence = self.make_selftext_sentence()
                if not new_sentence:
                    break
                selftext += " " + new_sentence
            selftext = selftext.strip()

            # need to do this to be able to submit an empty self-post
            if len(selftext) == 0:
                selftext = " "

            subreddit.submit(title, text=selftext, send_replies=False)

        # update the database
        self.last_submitted = datetime.now(pytz.utc)
        self.num_submissions += 1
        db.add(self)
        db.commit() 
Example #14
Source File: random_data.py    From flask-shop with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def shipping_method(self):
        return random.choice(ShippingMethod.query.all()) 
Example #15
Source File: random_data.py    From flask-shop with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def create_products_by_type(
    product_type, schema, placeholder_dir, how_many=10, create_images=True, stdout=None
):
    category = get_or_create_category(schema["category"], placeholder_dir)

    for dummy in range(how_many):
        product = create_product(
            product_type_id=product_type.id, category_id=category.id
        )
        set_product_attributes(product, product_type)
        if create_images:
            type_placeholders = placeholder_dir / schema["images_dir"]
            create_product_images(product, random.randrange(1, 5), type_placeholders)
        variant_combinations = get_variant_combinations(product)

        prices = get_price_override(schema, len(variant_combinations), product.price)
        variants_with_prices = itertools.zip_longest(variant_combinations, prices)

        for i, variant_price in enumerate(variants_with_prices, start=1337):
            attr_combination, price = variant_price
            sku = f"{product.id}-{i}"
            create_variant(
                product, attributes=attr_combination, sku=sku, price_override=price
            )

        if not variant_combinations:
            # Create min one variant for products without variant level attrs
            sku = f"{product.id}-{fake.random_int(1000, 100000)}"
            create_variant(product, sku=sku)


# step6 
Example #16
Source File: random_data.py    From flask-shop with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def create_product(**kwargs):
    description = fake.paragraphs(5)
    defaults = {
        "title": fake.company(),
        "basic_price": fake.pydecimal(2, 2, positive=True),
        "description": "\n\n".join(description),
        "is_featured": random.choice([0, 1]),
    }
    defaults.update(kwargs)
    return Product.create(**defaults)


# step8 
Example #17
Source File: random_data.py    From flask-shop with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def create_product_images(product, how_many, placeholder_dir):
    placeholder_root = Config.STATIC_DIR / placeholder_dir
    for dummy in range(how_many):
        image_name = random.choice(list(placeholder_root.iterdir()))
        image = str(image_name.relative_to(Config.STATIC_DIR))
        ProductImage.get_or_create(image=image, product_id=product.id)


# step10 
Example #18
Source File: server.py    From ComicStreamer with Apache License 2.0 5 votes vote down vote up
def get(self):
        session = self.application.dm.Session()
        stats=dict()
        stats['total'] = session.query(Comic).count()
        dt = session.query(DatabaseInfo).first().last_updated
        stats['last_updated'] = utils.utc_to_local(dt).strftime("%Y-%m-%d %H:%M:%S")
        dt = session.query(DatabaseInfo).first().created
        stats['created'] = utils.utc_to_local(dt).strftime("%Y-%m-%d %H:%M:%S")
        
        stats['series'] = len(set(session.query(Comic.series)))
        stats['persons'] = session.query(Person).count()
        
        recently_added_comics = session.query(Comic).order_by(Comic.added_ts.desc()).limit(10)
        recently_read_comics = session.query(Comic).filter(Comic.lastread_ts != "").order_by(Comic.lastread_ts.desc()).limit(10)
        
        roles_query = session.query(Role.name)
        roles_list = [i[0] for i in list(roles_query)]

        # SQLite specific random call
        random_comic = session.query(Comic).order_by(func.random()).first()
        if random_comic is None:
            random_comic = type('fakecomic', (object,), 
             {'id':0, 'series':'No Comics', 'issue':0})()
        self.render("index.html", stats=stats,
                    random_comic=random_comic,
                    recently_added = list(recently_added_comics),
                    recently_read = list(recently_read_comics),
                    roles = roles_list,
                    server_time =  int(time.mktime(datetime.utcnow().timetuple()) * 1000),
                    api_key = self.application.config['security']['api_key']
                ) 
Example #19
Source File: models.py    From SubredditSimulator with MIT License 5 votes vote down vote up
def get_comments_for_training(self, limit=None):
        comments = (db.query(Comment)
            .filter_by(subreddit=self.subreddit)
            .order_by(func.random())
            .limit(Settings["max corpus size"])
        )
        valid_comments = [comment for comment in comments
            if self.should_include_comment(comment)]
        return valid_comments 
Example #20
Source File: random_data.py    From flask-shop with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def create_payment(order):
    status = random.choice(list(PaymentStatusKinds)).value
    payment = OrderPayment.create(
        order_id=order.id,
        status=status,
        total=order.total_net,
        delivery=order.shipping_price_net,
        customer_ip_address=fake.ipv4(),
    )
    return payment 
Example #21
Source File: api.py    From senlin with Apache License 2.0 5 votes vote down vote up
def action_acquire_first_ready(context, owner, timestamp):
    with session_for_write() as session:
        action = session.query(models.Action).filter_by(
            status=consts.ACTION_READY).filter_by(
            owner=None).order_by(
            consts.ACTION_CREATED_AT or func.random()).first()
    if action:
        return action_acquire(context, action.id, owner, timestamp) 
Example #22
Source File: random_data.py    From flask-shop with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def create_fake_sale():
    sale = Sale.create(
        title=f"Happy {fake.word()} day!",
        discount_value_type=DiscountValueTypeKinds.percent.value,
        discount_value=random.choice([10, 20, 30, 40, 50]),
    )
    for product in Product.query.order_by(func.random()).all()[:4]:
        SaleProduct.create(sale_id=sale.id, product_id=product.id)
    return sale


# step30 
Example #23
Source File: main.py    From gmemegen with Apache License 2.0 5 votes vote down vote up
def view_random():
    meme = Meme.query.order_by(func.random()).first()
    return redirect(url_for('view_meme', meme_id=meme.id)) 
Example #24
Source File: web.py    From calibre-web with GNU General Public License v3.0 5 votes vote down vote up
def render_hot_books(page):
    if current_user.check_visibility(constants.SIDEBAR_HOT):
        if current_user.show_detail_random():
            random = calibre_db.session.query(db.Books).filter(calibre_db.common_filters()) \
                .order_by(func.random()).limit(config.config_random_books)
        else:
            random = false()
        off = int(int(config.config_books_per_page) * (page - 1))
        all_books = ub.session.query(ub.Downloads, func.count(ub.Downloads.book_id)).order_by(
            func.count(ub.Downloads.book_id).desc()).group_by(ub.Downloads.book_id)
        hot_books = all_books.offset(off).limit(config.config_books_per_page)
        entries = list()
        for book in hot_books:
            downloadBook = calibre_db.session.query(db.Books).filter(calibre_db.common_filters()).filter(
                db.Books.id == book.Downloads.book_id).first()
            if downloadBook:
                entries.append(downloadBook)
            else:
                ub.delete_download(book.Downloads.book_id)
                # ub.session.query(ub.Downloads).filter(book.Downloads.book_id == ub.Downloads.book_id).delete()
                # ub.session.commit()
        numBooks = entries.__len__()
        pagination = Pagination(page, config.config_books_per_page, numBooks)
        return render_title_template('index.html', random=random, entries=entries, pagination=pagination,
                                     title=_(u"Hot Books (Most Downloaded)"), page="hot")
    else:
        abort(404) 
Example #25
Source File: dotabase.py    From MangoByte with MIT License 5 votes vote down vote up
def thanks(self, ctx, *, hero=None):
		"""Gives thanks

		Thanks are given by a random dota hero in their own special way"""
		await self.hero_keyphrase_command(";thanks", hero, ctx) 
Example #26
Source File: dotabase.py    From MangoByte with MIT License 5 votes vote down vote up
def play_response_query(self, query, ctx):
		await self.play_response(query.order_by(func.random()).first(), ctx) 
Example #27
Source File: dotabase.py    From MangoByte with MIT License 5 votes vote down vote up
def get_response(self, responsename):
		response = session.query(Response).filter(Response.fullname == responsename).first()
		if response:
			return response
		# to support legacy clips that used name instead of fullname
		return session.query(Response).filter(Response.name == responsename).first()

	# Plays a random response from a query 
Example #28
Source File: views.py    From website with MIT License 5 votes vote down vote up
def index():
    return {"members": User.active_members().order_by(func.random())} 
Example #29
Source File: opds.py    From calibre-web with GNU General Public License v3.0 5 votes vote down vote up
def feed_discover():
    entries = calibre_db.session.query(db.Books).filter(calibre_db.common_filters()).order_by(func.random())\
        .limit(config.config_books_per_page)
    pagination = Pagination(1, config.config_books_per_page, int(config.config_books_per_page))
    return render_xml_template('feed.xml', entries=entries, pagination=pagination) 
Example #30
Source File: web.py    From calibre-web with GNU General Public License v3.0 5 votes vote down vote up
def index(page):
    entries, random, pagination = calibre_db.fill_indexpage(page, db.Books, True, [db.Books.timestamp.desc()])
    return render_title_template('index.html', random=random, entries=entries, pagination=pagination,
                                 title=_(u"Recently Added Books"), page="root")