Beispiel #1
0
 def prune(cls):
     query = cls.select(lambda self: not exists(t for t in Track if t.folder == self) and \
         not exists(f for f in Folder if f.parent == self) and not self.root)
     total = 0
     while True:
         count = query.delete()
         total += count
         if not count:
             return total
Beispiel #2
0
 def prune(cls):
     query = cls.select(lambda self: not exists(t for t in Track if t.folder == self) and \
         not exists(f for f in Folder if f.parent == self) and not self.root)
     total = 0
     while True:
         count = query.delete()
         total += count
         if not count:
             return total
Beispiel #3
0
 def save_or_update(self):
     deps = list()
     if not orm.exists(prod for prod in DB.Game if prod.id == self.game):
         DB.Game(id=self.game)
     if self.dependencies is not None:
         for dep in self.dependencies:
             if orm.exists(d for d in DB.RepositoryV1Dependency if d.name == dep.strip()):
                 deps.append(orm.get(d for d in DB.RepositoryV1Dependency if d.name == dep.strip()))
             else:
                 deps.append(DB.RepositoryV1Dependency(name=dep.strip()))
     dict_data = self.to_dict()
     dict_data['dependencies'] = deps
     return DB.RepositoryProductV1.save_into_db(**dict_data)
Beispiel #4
0
 def get_infohashes(self, tags: Set[str]) -> List[bytes]:
     """Get list of infohashes that belongs to the tag.
     Only tags with condition `_show_condition` will be returned.
     In the case that the tags set contains more than one tag,
     only torrents that contain all `tags` will be returned.
     """
     query_results = select(
         torrent.infohash for torrent in self.instance.Torrent
         if not exists(
             tag for tag in self.instance.Tag
             if tag.name in tags and not exists(
                 torrent_tag for torrent_tag in self.instance.TorrentTag
                 if torrent_tag.torrent == torrent and torrent_tag.tag ==
                 tag and self._show_condition(torrent_tag)))).fetch()
     return query_results
Beispiel #5
0
def show_migrations(db, fail_fast=False):
    '''
    List the migration dir.
    if migration name is specified, print its sql.
    '''
    cmd_exitstack.callback(db.disconnect)
    make_migration_entity(db)
    db.schema = db.generate_schema()
    graph = MigrationGraph()
    leaves = graph.leaves()
    if not leaves:
        print('No migrations')
        return
    if len(leaves) > 1 and not fail_fast:
        # Merge required
        questioner = InteractiveMigrationQuestioner()
        if questioner.ask_merge(leaves):
            # not tested?
            merge(graph=graph, leaves=leaves)
            show_migrations(fail_fast=True)
            return
        return
    leaf = leaves[0]
    migrations = leaf.forwards_list()
    names = [m.name for m in migrations]

    try:
        with orm.db_session:
            orm.exists(m for m in db.Migration)
    except orm.core.DatabaseError as ex:
        print('No Migration table. Please apply the initial migration.')
        return

    saved = orm.select((m.name, m.applied) for m in db.Migration
                       if m.name in names).order_by(2)[:]
    if saved:
        saved, _ = zip(*saved)
    for name in saved:
        print('+ {}'.format(name))
    for name in names:
        if name in saved:
            continue
        print('  {}'.format(name))
Beispiel #6
0
def update_db(period):
    with orm.db_session:
        barton = get_values(period, BARTON, DISCHARGE, GAGE_HEIGHT)
        rainfall = get_values(period, ONION_CREEK, RAINFALL)
        result = {**barton, **rainfall}
        for key in result.keys():
            if key == DISCHARGE:
                for value in result[key]:
                    if not orm.exists(v for v in DischargeRate
                                      if v.time_stamp == value[0]):
                        # Convert to gallons per second
                        gallons = float(value[1]) * 7.48051948
                        DischargeRate(time_stamp=value[0], value=gallons)
            elif key == GAGE_HEIGHT:
                for value in result[key]:
                    if not orm.exists(
                            v for v in GageHeight if v.time_stamp == value[0]):
                        GageHeight(time_stamp=value[0], value=value[1])
            elif key == RAINFALL:
                for value in result[key]:
                    if not orm.exists(
                            v for v in Rainfall if v.time_stamp == value[0]):
                        Rainfall(time_stamp=value[0], value=value[1])
Beispiel #7
0
def get_lan_obj(name, gen):
    if name == 'Neutral' or name == '*':
        try:
            return DB.Language['*']
        except:
            return DB.Language(code='*', name='*')
    if gen == 1:
        if orm.exists(lan for lan in DB.Language if lan.name == name.strip()):
            return orm.get(lan for lan in DB.Language if lan.name == name.strip())
        else:
            return DB.Language(code=name, name=name)
    elif gen == 2:
        try:
            return DB.Language[name]
        except:
            return DB.Language(code=name)
Beispiel #8
0
def register():
    req = request.get_json()
    if not exists(u.id for u in User if u.username == req['display_name']):
        now = datetime.datetime.now()
        User(username=req['display_name'],
             gender=req['gender'],
             avatar=req['avatar'],
             age=req['age'],
             user_id=now,
             password=req['password'],
             created_at=now)
        user = User.get(username=req['display_name'])
        return jsonify(
            success=True,
            user=user.describe(),
            access_token=create_access_token(identity=user.describe()))
    else:
        return jsonify(success=False, err='INVAILD_USERNAME')
Beispiel #9
0
def new_project():
    while True:
        name = ui.ask('What project are you planning on taking on?')
        if not name:
            return

        if orm.exists(project for project in db.Project
                      if project.name == name):
            ui.show('A project with this name already exists. '
                    'Please choose another name or leave empty to exit.')
        else:
            break

    project = db.Project(name=name)
    ui.show("If you're finished just say 'ready' :)")
    # Ask for tasks in this project
    while True:
        task = ui.ask('What does this project consist of?')
        if re.match("^|[rR]eady", task) is not None:
            break
        db.Task(content=task, project=project)
Beispiel #10
0
 async def post(self, request):
     user = request['session'].get('user')
     if not user:
         return self.response_status(401)
     req_land = request.args.get('land')
     req = request.form
     try:
         with db_session:
             if not exists(x for x in Land
                           if x.id == req_land and x.user.id == user):
                 return self.response_status(401)
             Crop(**self.not_null_data(
                 id=uuid4().hex,
                 name=req.get('name'),
                 lot_name=req.get('lot_name'),
                 lot_size=req.get('lot_size'),
                 land=Land[req_land],
             ))
     except Exception as e:
         self.response_status(500)
     return self.response_status(201)
Beispiel #11
0
 def prune(cls):
     return cls.select(lambda self: not exists(
         t for t in Track if t.album == self)).delete()
Beispiel #12
0
 def populate(self):
     with db_session:
         if not exists(s for s in Skill):
             for i in self.get_skills():
                 Skill(**i)
Beispiel #13
0
 def prune(cls):
     return cls.select(
         lambda self: not exists(a for a in Album if a.artist == self) and
         not exists(t for t in Track if t.artist == self)).delete()
Beispiel #14
0
 def save_or_update(self):
     if not orm.exists(prod for prod in DB.Game if prod.id == self.product):
         DB.Game(id=self.product)
     return DB.RepositoryProductV2.save_into_db(**self.to_dict())
Beispiel #15
0
 def __contains__(self, name):
     """Return whether this instance contains the named attribute."""
     return exists(attr for attr in self._get_all_attributes()
                   if attr.name == name)
Beispiel #16
0
 def exists(self, **kwargs):
     return exists(s for s in self.model)
Beispiel #17
0
 def prune(cls):
     return cls.select(lambda self: not exists(t for t in Track if t.album == self)).delete()
Beispiel #18
0
 def prune(cls):
     return cls.select(lambda self: not exists(a for a in Album if a.artist == self) and \
         not exists(t for t in Track if t.artist == self)).delete()
Beispiel #19
0
 def __contains__(self, name):
     """Return whether this instance contains the named tag."""
     return exists(link for link in self._get_all_tags()
             if link.tag.name == name)
Beispiel #20
0
def get_users_specific_year_info(
    board_name,
    year,
    articles_total_users,
    comments_total_users,
):

    board_entity = models.Board.get(name=board_name)

    if board_entity is None:
        raise exceptions.NoBoardError(board_name)

    board_year_record_entity = models.BoardYearRecord.get(
        year=year,
        board=board_entity
    )

    if not (
        board_year_record_entity
        and board_year_record_entity.update_time > board_entity.update_time
        and board_year_record_entity.users_total is not None
        and board_year_record_entity.users_comment_or_post is not None
    ):
        update_time = datetime.datetime.now()

        if board_year_record_entity is None:
            board_year_record_entity = models.BoardYearRecord(
                year=year,
                board=board_entity,
                update_time=update_time,
            )

        comment_or_post = {}

        comment_or_post['發文且留言'] = orm.select(
            article.user
            for article in models.Article
            if article.date.year == year
            and article.board.name == board_name
            and orm.exists(
                comment
                for comment in article.user.comments
                if comment.date.year == year
            )
        ).count()

        comment_or_post['只留言'] = (
            comments_total_users - comment_or_post['發文且留言']
        )

        comment_or_post['只發文'] = (
            articles_total_users - comment_or_post['發文且留言']
        )

        total = (
            articles_total_users
            + comments_total_users
            - comment_or_post['發文且留言']
        )

        board_year_record_entity.set(
            users_total=total,
            users_comment_or_post=repr(comment_or_post),
            update_time=update_time,
        )

    users = {
        'total': board_year_record_entity.users_total,
        'comment_or_post': eval(
            board_year_record_entity.users_comment_or_post
        ),
    }

    return users