コード例 #1
0
class View(Model):

    table_name = "views"

    id = Field(int, modifiable=False)
    date = Field(datetime, default=datetime.now())
    viewer_id = Field(int)
    viewee_id = Field(int)

    @staticmethod
    def get_viewed_by(self, user_id):
        connection = pool.get_conn()
        with connection.cursor() as c:
            date_format = '%e %b %Y'
            c.execute(
                """
                SELECT
                    v.id, 
                    v.viewer_id,
                    u.fname AS 'viewer_first_name', 
                    u.lname AS 'viewer_last_name',
                    u.username AS 'viewer_username',
                    v.viewee_id,
                    DATE_FORMAT(v.date, %s) as date
                FROM views v
                INNER JOIN users u
                ON v.viewer_id = u.id
                WHERE v.viewee_id = %s AND v.viewer_id <> %s
            """, (date_format, user_id, user_id))
            pool.release(connection)
            return c.fetchall()
        pool.release(connection)
        return None

    @staticmethod
    def get_views(self, user_id):
        connection = pool.get_conn()
        with connection.cursor() as c:
            date_format = '%e %b %Y'
            c.execute(
                """
                SELECT
                    v.id, 
                    v.viewer_id,
                    v.viewee_id, 
                    u.fname AS 'viewee_first_name', 
                    u.lname AS 'viewee_last_name',
                    u.username AS 'viewee_username',
                    DATE_FORMAT(v.date, %s) as date
                FROM views v
                INNER JOIN users u
                ON v.viewee_id = u.id
                WHERE v.viewer_id = %s AND v.viewee_id <> %s
            """, (date_format, user_id, user_id))
            pool.release(connection)
            return c.fetchall()
        pool.release(connection)
        return None
コード例 #2
0
 def get_primary_image(self):
     if self.id:
         try:
             connection = pool.get_conn()
             with connection.cursor() as c:
                 c.execute("""SELECT image64, image_type FROM images WHERE user_id=%s ORDER BY id DESC LIMIT 1""", (self.id,))
                 result = c.fetchone()
                 image64 = None if not result else result["image64"]
                 image_type = None if not result else result["image_type"]
                 self.append_field("image64", Field(str, image64))
                 self.append_field("image_type", Field(str, image_type))
         except Exception as e:
             raise
         finally:
             pool.release(connection)
コード例 #3
0
ファイル: frames.py プロジェクト: Devkalion/ssu-cloud
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.field = Field()
        self.buttons = {}
        self.next_btn = None

        self.init_visual()
コード例 #4
0
ファイル: manage.py プロジェクト: Omonroy36/api-playAt
def data(id=None):
    if request.method == "GET":

        fields = Field.query.all()

        json_lists = [field.serialize() for field in fields]

        return jsonify(json_lists), 200

    if request.method == "POST":

        field = Field()
        field.title = request.json.get("title")
        field.price = request.json.get("price")
        field.address = request.json.get("address")
        field.players_capacity = request.json.get("players_capacity")
        field.type_of_soil = request.json.get("type_of_soil")
        field.type_of_sport = request.json.get("type_of_sport")
        field.description = request.json.get("description")
        field.schedule = request.json.get("schedule")
        field.service_selected = request.json.get("service_selected")

        db.session.add(field)

        db.session.commit()

        return jsonify(field.serialize()), 201

    if request.method == "DELETE":
        if id is not None:
            field = Field.query.get(id)
            db.session.delete(field)
            db.session.commit()
            return jsonify({"msg": "Field has been deleted"}), 201
コード例 #5
0
ファイル: main.py プロジェクト: vodopyanovas/hw
def start_game():
    os.system('cls' if os.name == 'nt' else 'clear')
    print('\nHello my friend! Let\'s play a game!')
    field = Field('new')

    print(
        'So, to play a game you need to call your friend and say me your names!\n'
    )
    p1_name = input('Tell me the name of the first player: ')
    p2_name = input('Tell me the name of the second player: ')
    player1 = Player(p1_name, 1)
    player2 = Player(p2_name, 1)

    os.system('cls' if os.name == 'nt' else 'clear')
    # turn = get_turn(player1,player2)

    print(
        '\nNow it\'s time to place your ships on a game field! And the first player will be {}\n'
        .format(player1.name))
    os.system('cls' if os.name == 'nt' else 'clear')
    #field.print_field('')
    p1_ships = create_ships(field)

    os.system('cls' if os.name == 'nt' else 'clear')
    print(
        '\nNow it\'s time to place its ships For the second player {}'.format(
            player2.name))
    input('\n\npress Enter to continue...')

    os.system('cls' if os.name == 'nt' else 'clear')
    field.print_field('')
    p2_ships = create_ships(field)
コード例 #6
0
ファイル: parse_svd.py プロジェクト: LibreUCpp/LibreUCpp
def parse_field(f):
    name = f.name.strip('_')
    description = ' '.join(f.description.split()) if f.description else ''
    return Field(name=name,
                 bit_offset=f.bit_offset,
                 bit_width=f.bit_width,
                 description=description)
コード例 #7
0
def New_form():
    if request.method == 'POST':
        nameF = request.form['form_name']
        nameA = request.form['area']
        print(nameF)
        print(nameA)
        #f = Form(name=request.form['form_name'],detail=request.form['area'])
        f = Form(name=request.form['form_name'],
                 detail=request.form['detail'],
                 estatus="I")
        db.session.add(f)
        db.session.commit()

        datos = request.form['area']
        print(datos)
        campos = datos.split(';')
        for campo in campos:
            info = campo.split(':')
            if len(info) > 1:
                listado = f.id
                camp = Field(form_id=f.id,
                             name=info[0].replace(' ', '_'),
                             tipe=info[1],
                             label=info[2],
                             detail=info[3].replace(' ', '_'))
                db.session.add(camp)
                db.session.commit()

        return redirect('/plantilla')
コード例 #8
0
def register(FieldID):
    field = FieldID
    datapoints = []
    timestamps = []
    entry = Field(number=field, datapoints=datapoints, timestamps=timestamps)
    db.session.add(entry)
    db.session.commit()
    return {"Status": f"Successfully created {field} channel"}
コード例 #9
0
ファイル: main.py プロジェクト: alexei-alexov/minesweeper
def main():
    pygame.init()
    screen = pygame.display.set_mode((800, 600))
    pygame.display.set_caption("Minesweeper")
    surface = pygame.display.get_surface()

    clock = pygame.time.Clock()
    field = Field()
    screen = pygame.display.set_mode(field.bound[2:])

    mouse = (0, 0, 0)
    game_over = False
    while 1:
        clock.tick(60)

        surface.fill((255, 255, 255))
        field.render(surface)
        pygame.display.flip()

        for event in pygame.event.get():
            if event.type == QUIT:
                return
            elif event.type == KEYDOWN and event.key == K_ESCAPE:
                return
            elif event.type == KEYDOWN and event.key == K_r:
                field = Field()
                game_over = False
            elif event.type == KEYDOWN:
                mx, my = pygame.mouse.get_pos()
                if event.key == K_q:
                    game_over = field.handle_open_left(mx, my)
                elif event.key == K_z:
                    game_over = field.handle_press(mx, my)
            elif game_over:
                continue
            elif event.type == MOUSEBUTTONDOWN:
                mouse = pygame.mouse.get_pressed()
            elif event.type == MOUSEBUTTONUP:
                mx, my = pygame.mouse.get_pos()
                if mouse[0] and mouse[2]:
                    mouse = (0, 0, 0)
                    game_over = field.handle_open_left(mx, my)
                elif mouse[0]:
                    game_over = field.handle_press(mx, my)
                elif mouse[2]:
                    field.handle_flag(mx, my)
コード例 #10
0
ファイル: main.py プロジェクト: ptsypyshev/todo
def create_field():
    while True:
        # user_input = input('Введите размеры игрового поля через пробел или нажмите Enter для поля 10x10: ')
        user_input = '10 10'
        if not user_input:
            return Field()
        else:
            try:
                x, y = (int(i) for i in user_input.split())
                if x > 20 or y > 20:
                    print('Слишком большой размер поля. Попробуйте ещё раз')
                    continue
                break
            except ValueError:
                print('Введите целые числа для длины и ширины игрового поля, например 10 10')

    return Field(x, y)
コード例 #11
0
ファイル: models.py プロジェクト: equinor/volumetric
def step_impl(context):
    context.fields = {}
    for row in context.table:
        name = row['name']
        field = Field(name=name, )
        context.fields[name] = field
        db.session.add(field)
    db.session.commit()
コード例 #12
0
def get_full_user(user_id):
    user = User.get(id=user_id)

    images = Image.get_many(user_id=user_id)

    # Get the images for that user
    user.append_field("images", Field(list, images))

    return user
コード例 #13
0
    def _add_fields(self, table, schema):
        """adds fields to the table"""

        for schema_info in schema:
            field = Field(schema_info)
            arcpy.AddField_management(table.location,
                                      field.field_name,
                                      field.field_type,
                                      field_length=field.field_length,
                                      field_alias=field.field_alias)
コード例 #14
0
    def __init__(self, target=None, observer=None):

        self._sql = SQLInsertRequest()
        self._db = Database()
        self._convert = Convert()
        if target:
            self._entry = TableEntry(target)
        if observer:
            self._observer = observer
        self._field = Field()
コード例 #15
0
    def _getFields(self, xml):
        if xml.nodeName != "table":
            raise ValueError("Is not a table")

        fields = []
        for field in xml.getElementsByTagName("field"):
            tmp = Field()
            domain = Domain()
            for attributeName, attributeValue in field.attributes.items():
                if attributeName.lower() == "name":
                    tmp.name = attributeValue
                elif attributeName.lower() == "rname":
                    tmp.rname = attributeValue
                elif attributeName == "domain":
                    tmp.domain = attributeValue
                elif attributeName.lower() == "domain.name":
                    domain.name = attributeValue
                elif attributeName.lower() == "domain.char_length":
                    domain.char_length = attributeValue
                elif attributeName.lower() == "domain.precision":
                    domain.precision = attributeValue
                elif attributeName.lower() == "domain.scale":
                    domain.scale = attributeValue
                elif attributeName.lower() == "domain.type":
                    domain.type = attributeValue
                elif attributeName.lower() == "description":
                    tmp.description = attributeValue
                elif attributeName.lower() == "props":
                    for prop in attributeValue.split(", "):
                        if prop == "input":
                            tmp.input = True
                        elif prop == "edit":
                            tmp.edit = True
                        elif prop == "show_in_grid":
                            tmp.show_in_grid = True
                        elif prop == "show_in_details":
                            tmp.show_in_details = True
                        elif prop == "is_mean":
                            tmp.is_mean = True
                        elif prop == "autocalculated":
                            tmp.autocalculated = True
                        elif prop == "required":
                            tmp.required = True
                        else:
                            raise ValueError(
                                "Invalid format of props string: {}".format(
                                    attributeValue))
                else:
                    raise ValueError(
                        "Incorrect attribute name \"{}\" in tag \"{}\" ".
                        format(attributeName, field.nodeName))
            if tmp.domain is None:
                tmp.domain = domain
            fields.append(tmp)
        return fields
コード例 #16
0
ファイル: app.py プロジェクト: CourtneyStaunton/CropPortal
def addField(user):
    is_valid = True
    if len(request.form['newfield']) < 1:
        is_valid = False
        flash("Please enter a field!")
    if not is_valid:
        return redirect("/addtoDB")
    if is_valid:
        new_field = Field(field_name=request.form['newfield'])
        db.session.add(new_field)
        db.session.commit()
        return redirect("/addtoDB")
コード例 #17
0
ファイル: images.py プロジェクト: gwasserfall/matcha-api
class Image(Model):

    table_name = "images"

    id = Field(int, modifiable=False)
    user_id = Field(int)
    image64 = Field(str)
    is_primary = Field(bool)
    image_type = Field(str)

    def before_save(self):
        connection = self.pool.get_conn()
        with connection.cursor() as c:
            c.execute(
                """SELECT COUNT(*) as image_count FROM images WHERE user_id=%s""",
                (self.user_id))
            result = c.fetchone()
            if result.get("image_count", 0) >= 5 and not self.id:
                self.pool.release(connection)
                raise Exception(
                    "Cannot upload image, you already have 5. Please delete an image and reupload."
                )
        self.pool.release(connection)

    @classmethod
    def check_images(cls, user_id):
        temp = cls()

        connection = temp.pool.get_conn()
        with connection.cursor() as c:
            c.execute(
                """
              SELECT
                EXISTS(SELECT * FROM images WHERE user_id=%s AND image64!=%s) AS has_images
              from images
            """, (user_id, "&nbsp"))
            temp.pool.release(connection)
            return c.fetchone()
        temp.pool.release(connection)
        return None
コード例 #18
0
ファイル: post.py プロジェクト: c4pt0r/atomic
class Post(Model):
    title = Field("")
    content = Field("")
    channel = Field("")
    create_ts = Field(0)
    view_num = Field(0)
    upvote = Field(0)
コード例 #19
0
    def build_schema_map(schema):
        schema_index_items = OrderedDict()

        if isinstance(schema, basestring):
            if schema == 'Stations':
                schema = Schema().station
            elif schema == 'Results':
                schema = Schema().result

        for item in schema:
            schema_index_items.update({item['destination']: Field(item)})

        return OrderedDict(schema_index_items)
コード例 #20
0
class Message(Model):
    table_name = "messages"

    id = Field(int, modifiable=False)
    to_id = Field(int)
    from_id = Field(int)
    timestamp = Field(datetime, default=datetime.now())
    message = Field(str)
    seen = Field(bool)
コード例 #21
0
    def _getDbFields(self, cur, table_id):
        fields = []

        db_fields = cur.execute(
            """ SELECT * from dbd$fields
                                    WHERE table_id = :id""", {
                "id": table_id
            }).fetchall()
        field_metadata = self._getMetadata(cur, "dbd$fields")
        for field in db_fields:
            field_dictionary = dict(zip(field_metadata, list(field)))
            tmp = Field(field_dictionary)

            if field_dictionary["domain_id"] is not None:
                tmp.domain = self._getDbDomainName(
                    cur, domain_id=field_dictionary["domain_id"])

            fields.append(tmp)

        return fields
コード例 #22
0
ファイル: game.py プロジェクト: kevasesk/python_chess
    global tmp_point
    tmp_figure = fieldModel.field[point['x']][
        point['y']]  # remember it and make it active
    tmp_point = {'x': point['x'], 'y': point['y']}
    print('aval moves:')
    print(tmp_figure.getAvaliableMoves(tmp_point, fieldModel.field))
    print(tmp_point)


def drawPeshkaPicker(tmp_figure):
    picker = Picker(CANVAS)
    picker.drawSelecterBackground()
    images = picker.drawPeshkaOptions(tmp_figure.color)

    mainloop()


tk = tkinter.Tk()
tk.title("Chess")
tk.bind("<Button-1>", click_field)

canvas = Canvas(width=CANVAS_WIDTH, height=CANVAS_HEIGHT)
canvas.pack(expand=YES, fill=BOTH)
CANVAS = canvas

fieldModel = Field()
Field.newGame(fieldModel)
Field.drawField(fieldModel, fieldModel.field, tk, canvas)

#TODO 1: improve transform peshka fuctionality (add for BLACK part)
コード例 #23
0
ファイル: matches.py プロジェクト: gwasserfall/matcha-api
class Match(Model):

    table_name = "matches"

    id = Field(int, modifiable=False)
    date = Field(datetime, default=datetime.now())
    matchee_id = Field(int)
    matcher_id = Field(int)
    rating = Field(int, default=0)

    @staticmethod
    def get_likes(self, user_id):
        connection = pool.get_conn()
        with connection.cursor() as c:
            date_format = '%e %b %Y'
            c.execute(
                """
                SELECT
                    m.id, 
                    m.matcher_id,
                    m.matchee_id, 
                    u.fname AS 'matchee_first_name', 
                    u.lname AS 'matchee_last_name',
                    u.username AS 'matchee_username',
                    DATE_FORMAT(m.date, %s) as date
                FROM matches m
                INNER JOIN users u
                ON m.matchee_id = u.id
                WHERE m.matcher_id = %s
            """, (
                    date_format,
                    user_id,
                ))
            pool.release(connection)
            return c.fetchall()
        pool.release(connection)
        return None

    @staticmethod
    def get_liked_by(self, user_id):
        connection = pool.get_conn()
        with connection.cursor() as c:
            date_format = '%e %b %Y'
            c.execute(
                """
                SELECT
                    m.id, 
                    m.matcher_id,
                    u.fname AS 'matcher_first_name', 
                    u.lname AS 'matcher_last_name',
                    u.username AS 'matcher_username',
                    m.matchee_id,
                    DATE_FORMAT(m.date, %s) as date
                FROM matches m
                INNER JOIN users u
                ON m.matcher_id = u.id
                WHERE m.matchee_id = %s
            """, (
                    date_format,
                    user_id,
                ))
            pool.release(connection)
            return c.fetchall()
        pool.release(connection)
        return None

    @classmethod
    def check_match(cls, matcher_id, matchee_id):
        temp = cls()

        connection = temp.pool.get_conn()
        with connection.cursor() as c:
            c.execute(
                """
              SELECT
                EXISTS(SELECT * FROM matches WHERE matcher_id=%s and matchee_id=%s) as liked,
                EXISTS(SELECT * FROM matches WHERE matcher_id=%s and matchee_id=%s and liked=1) as matched
              from matches
            """, [matcher_id, matchee_id, matchee_id, matcher_id])
            temp.pool.release(connection)
            return c.fetchone()
        temp.pool.release(connection)
        return None
コード例 #24
0
        (table.__tablename__,
         DBSession.query(func.max(table.id).label("id")).one().id + 1))
for field in old_DBSession.query(old_Field).filter_by(
        marked_for_deletion=False).all():
    parent_ids = perspective_ids.get(
        str(field.parent_client_id) + '_' + str(field.parent_object_id), None)
    if not parent_ids:
        parent_ids = {'client_id': None, 'object_id': None}
        continue
    new_field = fields.get(field.entity_type, None)
    if not new_field:
        new_field = Field(
            client_id=field.client_id,
            translation_gist_client_id=translation_strings[
                field.entity_type]['ids']['client_id'],
            translation_gist_object_id=translation_strings[
                field.entity_type]['ids']['object_id'],
            data_type_translation_gist_client_id=translation_strings[
                field.data_type]['ids']['client_id'],
            data_type_translation_gist_object_id=translation_strings[
                field.data_type]['ids']['object_id'])
        if 'translation' in field.entity_type.lower(
        ) or field.entity_type.lower() == 'text':  # todo: looks too bad
            new_field.is_translatable = True
        DBSession.add(new_field)
        DBSession.flush()
        fields[field.entity_type] = {
            'client_id': new_field.client_id,
            'object_id': new_field.object_id
        }
    else:
        new_field = DBSession.query(Field).filter_by(
コード例 #25
0
class User(Model):

    table_name = "users"

    id = Field(int, modifiable=False)
    fname = Field(str)
    lname = Field(str)
    email = Field(str)
    username = Field(str)
    passhash = Field(str, hidden=True)
    email_verified = Field(bool, default=False)
    bio = Field(str)
    gender = Field(str)
    dob = Field(datetime)
    longitude = Field(float)
    latitude = Field(float)
    heat = Field(Subquery, Subquery("""
        (SELECT 
            IF(COUNT(id) = 0, 3, SUM(rating)) / IF(COUNT(id) = 0, 1, COUNT(id))
         FROM matches WHERE matchee_id = users.id and rating > 0) 
         AS heat
         """
        ))
    online = Field(bool)
    date_lastseen = Field(datetime)
    interests = Field(list)
    preferences = Field(list)
    deleted = Field(bool, modifiable=False, hidden=True)
    is_admin = Field(bool)

    def before_init(self, data):
        if "password" in data:
            self.passhash.value = self.hash_password(data["password"])

    def hash_password(self, password):
        salt = uuid.uuid4().hex
        return hashlib.sha256(salt.encode() + password.encode()).hexdigest() + ':' + salt

    def get_messages(self, from_id):
        try:
            connection = pool.get_conn()

            with connection.cursor() as c:
                c.execute("""SELECT * FROM messages 
                        WHERE 
                            (to_id=%s OR from_id=%s) 
                                AND 
                            (to_id=%s OR from_id=%s)
                        ORDER BY id
                    
                    """, (self.id, self.id, from_id, from_id))
                return c.fetchall()

        except Exception as e:
            print("Could not get messages", str(e))
        finally:
            pool.release(connection)


    def check_password(self, password):
        _hash, salt = self.passhash.split(':')
        return _hash == hashlib.sha256(salt.encode() + password.encode()).hexdigest()

    def get_primary_image(self):
        if self.id:
            try:
                connection = pool.get_conn()
                with connection.cursor() as c:
                    c.execute("""SELECT image64, image_type FROM images WHERE user_id=%s ORDER BY id DESC LIMIT 1""", (self.id,))
                    result = c.fetchone()
                    image64 = None if not result else result["image64"]
                    image_type = None if not result else result["image_type"]
                    self.append_field("image64", Field(str, image64))
                    self.append_field("image_type", Field(str, image_type))
            except Exception as e:
                raise
            finally:
                pool.release(connection)


    def delete(self):

        if self.id:
            connection = self.pool.get_conn()
            with connection.cursor() as c:
                c.execute("""
                        UPDATE {0} SET deleted = 1
                         WHERE id='{1}'
                """.format(self.table_name, self.id))
                connection.commit()
            self.pool.release(connection)
        else:
            raise Exception("User not in database")

    def destroy(self):
        if self.id:
            connection = self.pool.get_conn()
            with connection.cursor() as c:
                c.execute("DELETE FROM users WHERE id=%s", self.id)
                connection.commit()
            self.pool.release(connection)
        else:
            raise Exception("User not in database")
コード例 #26
0
def FieldRegister():
    field = request.get_json()
    db.session.add(Field(name=field['name'], description=field['description']))
    db.session.commit()
    return Response(status=200, mimetype='application/json')
コード例 #27
0
def save_field(name, description):
    field = Field(name=name, description=description)
    field.save()
コード例 #28
0
class User(Model):
    username = Field("")
    password = Field("")
    email = Field("")
コード例 #29
0
    def test_field(self):

        field = Field(name='BMW', number='5544', date='2018-09-17')
        db.session.add(field)
        db.session.commit()
        assert field.name == 'BMW'
コード例 #30
0
ファイル: example.py プロジェクト: fidemin/python-study
class Customer(Model):
    first_name = Field()
    last_name = Field()