Beispiel #1
0
class Disciplina(Base):
    __tablename__ = 'disciplinas'
    id = Column(Integer, primary_key=True)
    nome = Column(String(100), unique=True)
    creditos = Column(Integer, unique=False)
    codigo = Column(String(6), unique=True)
    vagas = Column(Integer, unique=False)
    horario = Column(Integer, unique=False)
    dias = Column(MutableList.as_mutable(PickleType), unique=False)
    requisito = Column(Integer, unique=False)
    inscritos = Column(MutableList.as_mutable(PickleType), unique=False)

    def __init__(self, id, nome, creditos, codigo, vagas, horario, dias, requisito, inscritos):
        self.id = id
        self.nome = nome
        self.creditos = creditos
        self.codigo = codigo
        self.vagas = vagas
        self.horario = horario
        self.dias = dias
        self.requisito = requisito
        self.inscritos = inscritos

    def __repr__(self):
        return '<Disciplina %r>' % (self.nome)
Beispiel #2
0
 def __init__(self, parent, stypename, birthdate=None):
     # If it is an original sample then sample should be set to the species name
     try:
         stype = Sample.Type[stypename]
     except KeyError:
         raise KeyError('Sample type, {0}, is not valid'.format(stypename))
     self.type = stype.value
     if (isinstance(parent, list) and isinstance(parent[0], Sample)):
         self.parent = parent
         self.species = parent[0].species
     elif isinstance(parent, str):
         self.parent = []
         self.species = parent
     else:
         raise TypeError("Type of parent, {0}, is not valid".format(
             type(parent)))
     self.notes = MutableList()
     self.images = MutableList()
     if birthdate:
         if isinstance(birthdate, str):
             self.birthDate = datetime.datetime.strftime(
                 datetime.datetime.strptime(birthdate, '%d-%m-%Y'),
                 '%d-%m-%Y')
         elif isinstance(birthdate, datetime.datetime):
             self.birthDate = datetime.datetime.strftime(
                 birthdate, '%d-%m-%Y')
         else:
             raise TypeError('birthdate is not of a valid type')
     else:
         self.birthDate = datetime.datetime.strftime(
             datetime.datetime.now(datetime.timezone.utc), '%d-%m-%Y')
Beispiel #3
0
class UserModel(db.Model, Model):
    __tablename__ = 'user'

    profile_id = db.Column(UUID(as_uuid=True), db.ForeignKey(ProfileModel.id), nullable=False)
    name = db.Column(db.VARCHAR(100), nullable=False)
    email = db.Column(db.VARCHAR(100), nullable=False)
    salt = db.Column(db.VARCHAR(32), nullable=False)
    password = db.Column(db.VARCHAR(32), nullable=False)
    password_recovery = db.Column(db.VARCHAR(32), nullable=True)
    password_history = db.Column(JSON, nullable=True)
    permission = db.Column(MutableList.as_mutable(ARRAY(db.String)), nullable=False)
    token = db.Column(MutableList.as_mutable(ARRAY(db.String)), nullable=True)
Beispiel #4
0
class Pclass(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(40))
    hp = db.Column(db.Integer)
    sp = db.Column(db.Integer)
    key_ability = db.Column(db.Integer)
    gbab = db.Column(db.Boolean)
    gfort = db.Column(db.Boolean)
    gref = db.Column(db.Boolean)
    gwill = db.Column(db.Boolean)
    armor_prof = db.Column(MutableList.as_mutable(PickleType))
    wp_prof = db.Column(MutableList.as_mutable(PickleType))
    c_skills = db.Column(MutableList.as_mutable(PickleType))
Beispiel #5
0
class User(CustomBase, UserMixin):

    __tablename__ = 'User'

    id = Column(Integer, primary_key=True)
    type = Column(String, default='admin')
    email = Column(String)
    name = Column(String, unique=True)
    permissions = Column(MutableList.as_mutable(PickleType), default=[])
    password = Column(String)
    tasks = relationship('Task', back_populates='user')

    def update(self, **kwargs):
        if app.config['USE_VAULT']:
            data = {'password': kwargs.pop('password')}
            vault_helper(app, f'user/{kwargs["name"]}', data)
        super().update(**kwargs)

    @property
    def is_admin(self):
        return 'Admin' in self.permissions

    def allowed(self, permission):
        return self.is_admin or permission in self.permissions

    def __repr__(self):
        return self.name
Beispiel #6
0
class LocalSampleMetrics(db2.Model):
    __bind_key__ = 'local'
    __tablename__ = "sample_metrics"

    id = db.Column(db.Integer, primary_key=True)
    sample_id = db.Column(db.String(5),
                          db.ForeignKey("samples.id"),
                          nullable=False,
                          unique=True)
    created_at = db.Column(db.DateTime(timezone=True),
                           default=utcnow_datetime_aware,
                           nullable=False)
    last_updated_at = db.Column(db.DateTime(timezone=True),
                                default=utcnow_datetime_aware,
                                onupdate=utcnow_datetime_aware,
                                nullable=False)

    wellness_score = db.Column(db.Float, nullable=False)
    diversity_index = db.Column(db.Float, nullable=False)
    evenness = db.Column(db.Float, nullable=False)
    richness = db.Column(db.Integer, nullable=False)
    total_species_count = db.Column(db.Integer, nullable=False)
    ecosystem = db.Column(MutableDict.as_mutable(postgresql.JSONB),
                          nullable=False)
    growth = db.Column(MutableDict.as_mutable(postgresql.JSONB),
                       nullable=False)
    probiotics = db.Column(MutableList.as_mutable(postgresql.JSONB),
                           nullable=False)
    recommendations = db.Column(MutableDict.as_mutable(postgresql.JSONB),
                                nullable=False)
    symptoms = db.Column(MutableDict.as_mutable(postgresql.JSONB),
                         nullable=False)

    def __repr__(self):
        return f"<[LOCAL]SampleMetrics id:{self.id!r} sample_id={self.sample_id!r}>"
Beispiel #7
0
class AvailableOSUpdate(db.Model):
    """This table holds the results of `AvailableOSUpdates` commands."""
    __tablename__ = 'available_os_updates'

    id = db.Column(db.Integer, primary_key=True)

    device_id = db.Column(db.ForeignKey('devices.id'), nullable=True)
    """(int): Device foreign key ID."""
    device = db.relationship('Device', backref='available_os_updates')
    """(db.relationship): Device relationship"""

    # Common to all platforms
    allows_install_later = db.Column(db.Boolean)
    human_readable_name = db.Column(db.String)
    is_critical = db.Column(db.Boolean)
    product_key = db.Column(db.String)
    restart_required = db.Column(db.Boolean)
    version = db.Column(db.String)

    # macOS Only
    app_identifiers_to_close = db.Column(
        MutableList.as_mutable(JSONEncodedDict))
    human_readable_name_locale = db.Column(db.String)
    is_config_data_update = db.Column(db.Boolean)
    """(bool): This update is a config data update eg. for XProtect or Gatekeeper. These arent normally shown"""
    is_firmware_update = db.Column(db.Boolean)
    metadata_url = db.Column(db.String)

    # iOS Only
    product_name = db.Column(db.String)
    build = db.Column(db.String)
    download_size = db.Column(db.BigInteger)
    install_size = db.Column(db.BigInteger)
Beispiel #8
0
class User(Base, UserMixin):

    __tablename__ = type = "User"
    id = Column(Integer, primary_key=True)
    email = Column(String(255), default="")
    jobs = relationship("Job", back_populates="creator")
    name = Column(String(255), unique=True)
    permissions = Column(MutableList.as_mutable(PickleType), default=[])
    pools = relationship("Pool", secondary=pool_user_table, back_populates="users")
    password = Column(String(255), default="")

    def __init__(self, **kwargs: Any) -> None:
        super().__init__(**kwargs)

    def generate_row(self, table: str) -> List[str]:
        return [
            f"""<button type="button" class="btn btn-primary btn-xs"
            onclick="showTypeModal('user', '{self.id}')">Edit</button>""",
            f"""<button type="button" class="btn btn-primary btn-xs"
            onclick="showTypeModal('user', '{self.id}', true)">
            Duplicate</button>""",
            f"""<button type="button" class="btn btn-danger btn-xs"
            onclick="confirmDeletion('user', '{self.id}')">Delete</button>""",
        ]

    @property
    def is_admin(self) -> bool:
        return "Admin" in self.permissions

    def allowed(self, permission: str) -> bool:
        return self.is_admin or permission in self.permissions
Beispiel #9
0
class User(AbstractBase, UserMixin):

    __tablename__ = type = "User"
    id = Column(Integer, primary_key=True)
    email = Column(String(SMALL_STRING_LENGTH))
    name = Column(String(SMALL_STRING_LENGTH))
    permissions = Column(MutableList.as_mutable(PickleType), default=[])
    pools = relationship("Pool",
                         secondary=pool_user_table,
                         back_populates="users")
    password = Column(String(SMALL_STRING_LENGTH))

    def generate_row(self, table: str) -> List[str]:
        return [
            f"""<button type="button" class="btn btn-primary btn-xs"
            onclick="showTypePanel('user', '{self.id}')">Edit</button>""",
            f"""<button type="button" class="btn btn-primary btn-xs"
            onclick="showTypePanel('user', '{self.id}', true)">
            Duplicate</button>""",
            f"""<button type="button" class="btn btn-danger btn-xs"
            onclick="showDeletionPanel('user', '{self.id}', '{self.name}')">
            Delete</button>""",
        ]

    @property
    def is_admin(self) -> bool:
        return "Admin" in self.permissions

    def allowed(self, permission: str) -> bool:
        return self.is_admin or permission in self.permissions
Beispiel #10
0
class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True, nullable=False)
    money = db.Column(db.Integer, default=True, nullable=False)
    field = db.Column(MutableList.as_mutable(db.PickleType))

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        if 'field' not in kwargs:
            self.field = [Plant().info] * (TILE_NUM**2)

    def get_plant(self, col, row):
        if row >= TILE_NUM or col >= TILE_NUM:
            raise AttributeError("Plant {} {} doesn't exist".format(col, row))
        return Plant(self.field[row * TILE_NUM + col])

    def set_plant(self, col, row, plant: Plant):
        if row >= TILE_NUM or col >= TILE_NUM:
            raise AttributeError("Plant {} {} doesn't exist".format(col, row))
        self.field[row * TILE_NUM + col] = plant.info

    def get_snapshot(self):
        return {'money': self.money, 'field': self.field}

    def __repr__(self):
        return "<User {} with field {} and money {}>".format(
            self.username, self.field, self.money)
Beispiel #11
0
class NapalmGettersScript(Script):

    __tablename__ = 'NapalmGettersScript'

    id = Column(Integer, ForeignKey('Script.id'), primary_key=True)
    getters = Column(MutableList.as_mutable(PickleType), default=[])
    content_match = Column(String)
    content_match_regex = Column(Boolean)
    device_multiprocessing = True

    __mapper_args__ = {
        'polymorphic_identity': 'napalm_getters',
    }

    @multiprocessing
    def job(self, task, device, results, payloads):
        result = {}
        results['expected'] = self.content_match
        try:
            napalm_driver = napalm_connection(device)
            napalm_driver.open()
            for getter in self.getters:
                try:
                    result[getter] = getattr(napalm_driver, getter)()
                except Exception as e:
                    result[getter] = f'{getter} failed because of {e}'
            if self.content_match_regex:
                success = bool(search(self.content_match, str_dict(result)))
            else:
                success = self.content_match in str_dict(result)
            napalm_driver.close()
        except Exception as e:
            result = f'script did not work:\n{e}'
            success = False
        return success, result, result
Beispiel #12
0
class InventoryEntry(Base):
    """
    An inventory class
    """
    __tablename__ = 'inventory_items'
    entry_id = Column(INTEGER, autoincrement=True, primary_key=True)
    owner = Column(BigInteger, ForeignKey('accounts.id'))
    item_type = Column(types.Enum(ItemType))
    item_info = Column(MutableList.as_mutable(JSON), server_default='[]')
    owner_acc = relationship("Account")

    def _create_item(self, args):
        return item_class_map[self.item_type](**args)

    def get_items(self):
        return [self._create_item(i) for i in self.item_info]

    def add_item(self, item):
        logger.info(f"added {item} to <@{self.owner}>'s inventory")
        self.item_info.append(item.to_json())

    def remove_item(self, index=0):
        logger.info(
            f"Removed {self._create_item(**self.item_info[index])} from <@{self.owner}>'s inventory"
        )
        self.item_info.pop(index)

    def equip_item(self, index=0):
        logger.info(f"Equipped {self.item_info[index]} to <@{self.owner}>")
        self.owner_acc.equip(self._create_item(self.item_info[index]))

    def update_item(self, item):
        assert reversed_class_map[type(item)] == item_class_map[
            self.item_type.value]
        self.item_info = item.to_json()
Beispiel #13
0
    def configure_columns(self):
        class CustomPickleType(PickleType):
            if self.dialect == "mysql":
                impl = MSMediumBlob

        self.Dict = MutableDict.as_mutable(CustomPickleType)
        self.List = MutableList.as_mutable(CustomPickleType)
        if self.dialect == "postgresql":
            self.LargeString = Text
        else:
            self.LargeString = Text(
                self.columns["length"]["large_string_length"])
        self.SmallString = String(
            self.columns["length"]["small_string_length"])
        self.TinyString = String(self.columns["length"]["tiny_string_length"])

        default_ctypes = {
            self.Dict: {},
            self.List: [],
            self.LargeString: "",
            self.SmallString: "",
            self.TinyString: "",
            Text: "",
        }

        class CustomColumn(Column):
            def __init__(self, ctype, *args, **kwargs):
                if "default" not in kwargs and ctype in default_ctypes:
                    kwargs["default"] = default_ctypes[ctype]
                super().__init__(ctype, *args, **kwargs)

        self.Column = CustomColumn
class User(db.Model, RoleFreeUserMixin):
    __tablename__ = "users"

    id = db.Column(db.Integer, primary_key=True)
    email = db.Column(db.String(255))
    password = db.Column(db.String(255))
    active = db.Column(db.Boolean(), default=False)
    confirmed_at = db.Column(db.DateTime())
    user_type = db.Column(db.Enum(TypeOfUser, name="type_of_user_types"), nullable=False)
    capabilities = db.Column(MutableList.as_mutable(ARRAY(db.String)), default=[])
    last_login_at = db.Column(db.DateTime())
    current_login_at = db.Column(db.DateTime())
    last_login_ip = db.Column(db.String(16))
    current_login_ip = db.Column(db.String(16))
    login_count = db.Column(db.Integer)
    failed_login_count = db.Column(db.Integer, default=0)

    # relationships
    measures = db.relationship(
        "Measure",
        lazy="subquery",
        secondary="user_measure",
        primaryjoin="User.id == user_measure.columns.user_id",
        secondaryjoin="Measure.id == user_measure.columns.measure_id",
        back_populates="shared_with",
    )

    __table_args__ = (UniqueConstraint(email, name="uq_users_email"),)

    def user_name(self):
        return self.email.split("@")[0]

    def is_departmental_user(self):
        return self.user_type == TypeOfUser.DEPT_USER

    def is_rdu_user(self):
        return self.user_type == TypeOfUser.RDU_USER

    def is_admin_user(self):
        return self.user_type == TypeOfUser.ADMIN_USER

    def can(self, capability):
        return capability in self.capabilities

    def can_access_measure(self, measure):
        if self.user_type != TypeOfUser.DEPT_USER:
            return True
        else:
            return self in measure.shared_with

    # DEPRECATED: use `can_access_measure` method instead.
    def can_access(self, measure_slug):
        if self.user_type != TypeOfUser.DEPT_USER:
            return True
        else:
            if any(measure.slug == measure_slug for measure in self.measures):
                return True
            else:
                return False
Beispiel #15
0
class DiscordServer(db.Model):
    __tablename__ = "discordserver"
    id = db.Column(BIGINT, primary_key=True, autoincrement=False)
    server_group_id = db.Column(db.Integer, db.ForeignKey("servergroup.id"))
    name = db.Column(db.String, nullable=False)
    command_prefixes = db.Column(MutableList.as_mutable(ARRAY(db.String)),
                                 nullable=True)
    # a message prefix is a regex string that would be applied to the message
    # before being processed. The regex would just be the prefix to the message
    # so whatever is matched would be removed.
    # its undefined what regex would be applied
    # if two regexes match the same message
    message_prefixes = db.Column(MutableList.as_mutable(ARRAY(db.String)),
                                 nullable=True)
    admin_role = db.Column(BIGINT, nullable=True)

    server_group = db.relationship("ServerGroup")
class Ordinals(Base):
    """Class to represent a list of ordinals in some language or other."""

    id = Column(Integer, primary_key=True, index=True)
    content = Column(MutableList.as_mutable(PickleType), default=[])
    language = Column(String())
    owner_id = Column(Integer, ForeignKey("user.id"))
    owner = relationship("User", back_populates="ordinals")
Beispiel #17
0
class Chat(Base):
    __tablename__ = 'chats'

    chat_id = Column(Integer(), primary_key=True)
    chat_type = Column(Enum(ChatType), nullable=False)
    description = Column(String(255))
    tags = Column(MutableList.as_mutable(ARRAY(String(100))))
    chat_status = Column(Enum(ChatStatus), nullable=False)
    aspiring_professionals = Column(MutableList.as_mutable(ARRAY(String(100))))
    senior_executive = Column(String(100), nullable=False)
    fixed_date = Column(DateTime())
    expiry_date = Column(DateTime())

    created_on = Column(DateTime(), default=datetime.now)
    updated_on = Column(DateTime(),
                        default=datetime.now,
                        onupdate=datetime.now)
Beispiel #18
0
class NapalmGettersService(Service):

    __tablename__ = 'NapalmGettersService'

    id = Column(Integer, ForeignKey('Service.id'), primary_key=True)
    has_targets = True
    content_match = Column(String)
    content_match_textarea = True
    content_match_regex = Column(Boolean)
    negative_logic = Column(Boolean)
    delete_spaces_before_matching = Column(Boolean)
    driver = Column(String)
    driver_values = NAPALM_DRIVERS
    getters = Column(MutableList.as_mutable(PickleType), default=[])
    getters_values = (('get_arp_table',
                       'ARP table'), ('get_interfaces_counters',
                                      'Interfaces counters'), ('get_facts',
                                                               'Facts'),
                      ('get_environment', 'Environment'), ('get_config',
                                                           'Configuration'),
                      ('get_interfaces', 'Interfaces'), ('get_interfaces_ip',
                                                         'Interface IP'),
                      ('get_lldp_neighbors',
                       'LLDP neighbors'), ('get_lldp_neighbors_detail',
                                           'LLDP neighbors detail'),
                      ('get_mac_address_table',
                       'MAC address'), ('get_ntp_servers', 'NTP servers'),
                      ('get_ntp_stats', 'NTP statistics'), ('get_optics',
                                                            'Transceivers'),
                      ('get_snmp_information', 'SNMP'), ('get_users', 'Users'),
                      ('get_network_instances', 'Network instances (VRF)'),
                      ('get_ntp_peers', 'NTP peers'), ('get_bgp_config',
                                                       'BGP configuration'),
                      ('get_bgp_neighbors',
                       'BGP neighbors'), ('get_ipv6_neighbors_table',
                                          'IPv6'), ('is_alive', 'Is alive'))
    optional_args = Column(MutableDict.as_mutable(PickleType), default={})

    __mapper_args__ = {
        'polymorphic_identity': 'NapalmGettersService',
    }

    def job(self, device, _):
        napalm_driver, result = napalm_connection(self, device), {}
        napalm_driver.open()
        for getter in self.getters:
            try:
                result[getter] = getattr(napalm_driver, getter)()
            except Exception as e:
                result[getter] = f'{getter} failed because of {e}'
        match = substitute(self.content_match, locals())
        napalm_driver.close()
        return {
            'expected': match,
            'negative_logic': self.negative_logic,
            'result': result,
            'success': self.match_content(str(result), match)
        }
Beispiel #19
0
class ExampleService(Service):

    __tablename__ = "ExampleService"

    id = Column(Integer, ForeignKey("Service.id"), primary_key=True)
    # the "string1" property will be displayed as a drop-down list, because
    # there is an associated "string1_values" property in the class.
    string1 = Column(String(255), default="")
    # the "string2" property will be displayed as a text area.
    string2 = Column(String(255), default="")
    string2_name = "String 2 !"
    string2_length = 5
    # Text area
    an_integer = Column(Integer, default=0)
    # Text area
    a_float = Column(Float, default=0.0)
    # the "a_list" property will be displayed as a multiple selection list
    # list, with the values contained in "a_list_values".
    a_list = Column(MutableList.as_mutable(PickleType))
    # Text area where a python dictionnary is expected
    a_dict = Column(MutableDict.as_mutable(PickleType))
    # "boolean1" and "boolean2" will be displayed as tick boxes in the GUI.
    boolean1 = Column(Boolean, default=False)
    boolean1_name = "Boolean N°1"
    boolean2 = Column(Boolean, default=False)

    # these values will be displayed in a single selection drop-down list,
    # for the property "a_list".
    string1_values = [("cisco", "Cisco"), ("juniper", "Juniper"),
                      ("arista", "Arista")]

    # these values will be displayed in a multiple selection list,
    # for the property "a_list".
    a_list_values = [
        ("value1", "Value 1"),
        ("value2", "Value 2"),
        ("value3", "Value 3"),
    ]

    __mapper_args__ = {"polymorphic_identity": "ExampleService"}

    # Some services will take action or interrogate a device. The job method
    # can also take device as a parameter for these types of services.
    # def job(self, device, payload):
    def job(self, payload: dict) -> dict:
        self.logs.append(
            f"Real-time logs displayed when the service is running.")
        # The "job" function is called when the service is executed.
        # The parameters of the service can be accessed with self (self.string1,
        # self.boolean1, etc)
        # You can look at how default services (netmiko, napalm, etc.) are
        # implemented in the /services subfolders (/netmiko, /napalm, etc).
        # "results" is a dictionnary that will be displayed in the logs.
        # It must contain at least a key "success" that indicates whether
        # the execution of the service was a success or a failure.
        # In a workflow, the "success" value will determine whether to move
        # forward with a "Success" edge or a "Failure" edge.
        return {"success": True, "result": "example"}
Beispiel #20
0
class ExampleService(Service):

    __tablename__ = 'ExampleService'

    id = Column(Integer, ForeignKey('Service.id'), primary_key=True)
    # see eNMS documentation section on Workflow devices for a description of
    # the multiprocessing property and its expected behavior
    multiprocessing = False
    # the "string1" property will be displayed as a drop-down list, because
    # there is an associated "string1_values" property in the class.
    string1 = Column(String)
    # the "string2" property will be displayed as a text area.
    string2 = Column(String)
    # Text area
    an_integer = Column(Integer)
    # Text area
    a_float = Column(Float)
    # the "a_list" property will be displayed as a multiple selection list
    # list, with the values contained in "a_list_values".
    a_list = Column(MutableList.as_mutable(PickleType))
    # Text area where a python dictionnary is expected
    a_dict = Column(MutableDict.as_mutable(PickleType))
    # "boolean1" and "boolean2" will be displayed as tick boxes in the GUI.
    boolean1 = Column(Boolean)
    boolean2 = Column(Boolean)

    # these values will be displayed in a single selection drop-down list,
    # for the property "a_list".
    string1_values = [
        ('cisco', 'Cisco'),
        ('juniper', 'Juniper'),
        ('arista', 'Arista')
    ]

    # these values will be displayed in a multiple selection list,
    # for the property "a_list".
    a_list_values = [
        ('value1', 'Value 1'),
        ('value2', 'Value 2'),
        ('value3', 'Value 3')
    ]

    __mapper_args__ = {
        'polymorphic_identity': 'example_service',
    }

    def job(self, payload):
        # The "job" function is called when the service is executed.
        # The parameters of the service can be accessed with self (self.string1,
        # self.boolean1, etc)
        # You can look at how default services (netmiko, napalm, etc.) are
        # implemented in the /services subfolders (/netmiko, /napalm, etc).
        # "results" is a dictionnary that will be displayed in the logs.
        # It must contain at least a key "success" that indicates whether
        # the execution of the service was a success or a failure.
        # In a workflow, the "success" value will determine whether to move
        # forward with a "Success" edge or a "Failure" edge.
        return {'success': True, 'result': 'example'}
Beispiel #21
0
class Updates(db.Model):
    __tablename__ = "updates"
    id = db.Column(db.Integer, primary_key=True)
    client_id = db.Column(db.Integer)
    data = db.Column(MutableList.as_mutable(db.PickleType))

    def __init__(self, client_id=None, data=None):
        self.client_id = client_id
        self.data = data
Beispiel #22
0
class Session(db.Model):
    __tablename__ = 'session'

    id = db.Column(db.Integer, primary_key=True)
    status = db.Column(db.String(25), nullable=False, default='initialised')
    app_id = db.Column(db.Integer,
                       db.ForeignKey('application.id',
                                     use_alter=True,
                                     name='fk_app_id'),
                       nullable=False)
    creation_date = db.Column(db.TIMESTAMP,
                              server_default=db.func.current_timestamp(),
                              nullable=False)
    expected_emotions = db.Column(db.JSON, nullable=False)
    questionnaire_id = db.Column(db.Integer,
                                 db.ForeignKey('questionnaire.id',
                                               use_alter=True,
                                               name='fk_questionnaire_id'),
                                 nullable=False)
    cssi_score = db.Column(db.Float, nullable=False, default=0)
    latency_scores = db.Column(MutableList.as_mutable(db.JSON),
                               nullable=False,
                               default=[])
    total_latency_score = db.Column(db.Float, nullable=False, default=0)
    sentiment_scores = db.Column(MutableList.as_mutable(db.JSON),
                                 nullable=False,
                                 default=[])
    plugin_scores = db.Column(MutableDict.as_mutable(db.JSON),
                              nullable=False,
                              default={})
    total_plugin_scores = db.Column(MutableDict.as_mutable(db.JSON),
                                    nullable=False,
                                    default={})
    total_sentiment_score = db.Column(db.Float, nullable=False, default=0)
    questionnaire_scores = db.Column(db.JSON, nullable=True, default={})
    total_questionnaire_score = db.Column(db.Float, nullable=False, default=0)

    def __init__(self, app, expected_emotions, questionnaire):
        self.app = app
        self.expected_emotions = expected_emotions
        self.questionnaire = questionnaire

    def __repr__(self):
        return '<Session %r>' % self.id
Beispiel #23
0
class Game(db.Model):
    __tablename__ = 'games'
    __table_args__ = {
        'mysql_engine': 'InnoDB',
        'mysql_charset': 'utf8',
        'mysql_collate': 'utf8_general_ci'
    }
    gid = db.Column(db.Integer, primary_key=True, autoincrement=True)
    host_uid = db.Column(db.Integer, nullable=False)
    status = db.Column(EnumType, nullable=False)
    victory_mode = db.Column(EnumType, nullable=False)
    captain_mode = db.Column(EnumType, nullable=False)
    witch_mode = db.Column(EnumType, nullable=False)
    wolf_mode = db.Column(EnumType, nullable=False)
    end_time = db.Column(db.DateTime, nullable=False)
    updated_on = db.Column(db.DateTime,
                           nullable=False,
                           default=datetime.utcnow,
                           onupdate=datetime.utcnow)
    players = db.Column(MutableList.as_mutable(JSONEncodedType(225)),
                        nullable=False)
    cards = db.Column(MutableList.as_mutable(JSONEncodedType(1023)),
                      nullable=False)
    days = db.Column(db.Integer, nullable=False)
    now_index = db.Column(db.Integer, nullable=False)
    step_cnt = db.Column(db.Integer, nullable=False)
    steps = db.Column(MutableList.as_mutable(JSONEncodedType(1023)),
                      nullable=False)
    history = db.Column(MutableDict.as_mutable(JSONEncodedType(1023)),
                        nullable=False)
    captain_pos = db.Column(db.Integer, nullable=False)

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        db.session.commit()
        return True if exc_type is None else False

    def get_seats_cnt(self):
        cnt = len(self.cards)
        if GameEnum.ROLE_TYPE_THIEF in self.cards:
            cnt -= 2
        return cnt
Beispiel #24
0
class Quiz(db.Model):
    """
    Create a Quiz table
    """

    __tablename__ = "quizzes"

    id = db.Column(db.Integer, primary_key=True)
    questions = db.Column(MutableList.as_mutable(PickleType), default=[])
    user_id = db.Column(db.Integer, db.ForeignKey("users.id"))
Beispiel #25
0
class Favorite(db.Model):
    __tablename__ = 'favorites'
    id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(db.Integer, db.ForeignKey('users.id'))
    url = db.Column(db.String(1000), nullable=False)
    categories = db.Column('categories', MutableList.as_mutable(ARRAY(db.String(100))))

    def __init__(self, user_id, url):
        self.user_id = user_id
        self.url = url
Beispiel #26
0
class Task(db.Model, DomainObject):
    '''An individual Task which can be performed by a user. A Task is
    associated to a project.
    '''
    __tablename__ = 'task'

    #: Task.ID
    id = Column(Integer, primary_key=True)
    #: UTC timestamp when the task was created.
    created = Column(Text, default=make_timestamp)
    #: Project.ID that this task is associated with.
    project_id = Column(Integer,
                        ForeignKey('project.id', ondelete='CASCADE'),
                        nullable=False)
    #: Task.state: ongoing or completed.
    state = Column(UnicodeText, default=u'ongoing')
    quorum = Column(Integer, default=0)
    #: If the task is a calibration task
    calibration = Column(Integer, default=0)
    #: Priority of the task from 0.0 to 1.0
    priority_0 = Column(Float, default=0)
    #: Task.info field in JSONB with the data for the task.
    info = Column(JSONB)
    #: Number of answers to collect for this task.
    n_answers = Column(Integer, default=1)
    #: Array of User IDs that favorited this task
    fav_user_ids = Column(MutableList.as_mutable(ARRAY(Integer)))
    #: completed task can be marked as exported=True after its exported
    exported = Column(Boolean, default=False)
    #: Task.user_pref field in JSONB with user preference data for the task.
    user_pref = Column(JSONB)
    #: Task.worker_pref field in JSONB with worker preference data for the task.
    worker_pref = Column(JSONB)
    #: Task.worker_filter field in JSONB with worker filter data for the task.
    worker_filter = Column(JSONB)
    #: Task.gold_answers field in JSONB to record golden answers for fields under Task.info.
    gold_answers = Column(JSONB)
    #: Task.expiration field to determine when a task should no longer be scheduled. As UTC timestamp without timezone
    expiration = Column(DateTime, nullable=True)

    task_runs = relationship(TaskRun,
                             cascade='all, delete, delete-orphan',
                             backref='task')

    def pct_status(self):
        """Returns the percentage of Tasks that are completed"""
        if self.n_answers != 0 and self.n_answers is not None:
            return float(len(self.task_runs)) / self.n_answers
        else:  # pragma: no cover
            return float(0)

    __table_args__ = (Index('task_info_idx',
                            sqlalchemy.text('md5(info::text)')), )
    __mapper_args__ = {"order_by": id}
Beispiel #27
0
class Chat(Base, Generic):
    __tablename__ = "chat"
    id = Column(BigInteger, primary_key=True)
    chat_type = Column(String)
    title = Column(String)
    timezone = Column(String, default="Europe/Amsterdam")
    days_off = Column(MutableList.as_mutable(ARRAY(String)), default=[])
    main_hours = Column(MutableList.as_mutable(ARRAY(Integer)),
                        default=MAIN_HOURS)
    games = relationship("Game", backref="chat")

    def add_game(self, game):
        self.games.append(game)
        self.save()

    def add_day_off(self, weekday):
        self.days_off.append(weekday)
        self.save()

    def rm_day_off(self, weekday):
        self.days_off.remove(weekday)
        self.save()

    def add_hour(self, hour):
        self.main_hours.append(hour)
        self.save()
        self.reorder_hours()

    def rm_hour(self, hour):
        self.main_hours.remove(hour)
        self.save()

    def reorder_hours(self):
        morning_hours = sorted(i for i in self.main_hours if i < 4)
        day_hours = sorted(i for i in self.main_hours if i > 4)
        self.main_hours = day_hours + morning_hours
        self.save()

    @property
    def timezone_pytz(self):
        return pytz.timezone(self.timezone)
Beispiel #28
0
    def define_tables(cls, metadata):
        MutableList = cls._type_fixture()

        mutable_pickle = MutableList.as_mutable(PickleType)
        Table('foo', metadata,
              Column('id', Integer, primary_key=True,
                     test_needs_autoincrement=True),
              Column('skip', mutable_pickle),
              Column('data', mutable_pickle),
              Column('non_mutable_data', PickleType),
              Column('unrelated_data', String(50))
              )
Beispiel #29
0
    def define_tables(cls, metadata):
        MutableList = cls._type_fixture()

        mutable_pickle = MutableList.as_mutable(PickleType)
        Table(
            "foo",
            metadata,
            Column(
                "id", Integer, primary_key=True, test_needs_autoincrement=True
            ),
            Column("data", mutable_pickle),
        )
Beispiel #30
0
class Podcast(Base):

    __tablename__ = "podcasts"

    id = Column(INTEGER, primary_key=True, unique=True, index=True)
    name = Column(String(100), nullable=False)
    duration = Column(INTEGER, nullable=False)
    uploaded_time = Column(DateTime(),
                           default=datetime.now,
                           onupdate=datetime.now)
    host = Column(String(100), nullable=False)
    participants = Column(MutableList.as_mutable(PickleType), default=[])
Beispiel #31
0
class UserSong(sqldb.Model):
    id = sqldb.Column(sqldb.Integer, primary_key=True)
    desc = sqldb.Column(
        sqldb.String(150))  #TODO: catch error if greater than 150 char
    saved = sqldb.Column(sqldb.Boolean)
    date = sqldb.Column(MutableList.as_mutable(sqldb.ARRAY(sqldb.String(60))))
    plays = sqldb.Column(sqldb.Integer)
    period = sqldb.Column(
        sqldb.Enum('Spring', 'Summer', 'Fall', 'Winter', name='periodenum'))
    year = sqldb.Column(sqldb.Integer)
    song_id = sqldb.Column(sqldb.Integer, sqldb.ForeignKey('song.id'))
    user_id = sqldb.Column(sqldb.Integer, sqldb.ForeignKey('user.id'))
Beispiel #32
0
    def define_tables(cls, metadata):
        MutableList = cls._type_fixture()

        mutable_pickle = MutableList.as_mutable(PickleType)
        Table(
            "foo",
            metadata,
            Column(
                "id", Integer, primary_key=True, test_needs_autoincrement=True
            ),
            Column("skip", mutable_pickle),
            Column("data", mutable_pickle),
            Column("non_mutable_data", PickleType),
            Column("unrelated_data", String(50)),
        )