예제 #1
0
파일: phq9.py 프로젝트: tarun911/camcops
 def get_summaries(self, req: CamcopsRequest) -> List[SummaryElement]:
     return self.standard_task_summary_fields() + [
         SummaryElement(name="total",
                        coltype=Integer(),
                        value=self.total_score(),
                        comment="Total score (/{})".format(
                            self.MAX_SCORE_MAIN)),
         SummaryElement(name="n_core",
                        coltype=Integer(),
                        value=self.n_core(),
                        comment="Number of core symptoms"),
         SummaryElement(name="n_other",
                        coltype=Integer(),
                        value=self.n_other(),
                        comment="Number of other symptoms"),
         SummaryElement(name="n_total",
                        coltype=Integer(),
                        value=self.n_total(),
                        comment="Total number of symptoms"),
         SummaryElement(name="is_mds",
                        coltype=Boolean(),
                        value=self.is_mds(),
                        comment="PHQ9 major depressive syndrome?"),
         SummaryElement(name="is_ods",
                        coltype=Boolean(),
                        value=self.is_ods(),
                        comment="PHQ9 other depressive syndrome?"),
         SummaryElement(name="severity",
                        coltype=SummaryCategoryColType,
                        value=self.severity(req),
                        comment="PHQ9 depression severity"),
     ]
class AccountDbo(EntityManager.get_base()):
    """
    The Account Database Object
    """
    __tablename__ = 'accounts'
    id = Column(Integer, primary_key=True)
    name = Column(String(50), unique=True)
    description = Column(String(250))
    transactions = relationship('TransactionDbo', backref='account')
    color = Column(String(50))
    notify = Column(Boolean())
    active = Column(Boolean())
    status = relationship('StatusDbo', backref='account')

    def __init__(self, id=None,  name=None, description=None, color=None, notify=None, active=None):
        """Constructor"""
        self.id = id
        self.name = name
        self.description = description
        self.color = color
        self.notify = notify
        self.active = active

    def __repr__(self):
        """String representation"""
        return '<AccountDbo %r, %r>' % (self.id, self.name)
예제 #3
0
class TicketMessage(ModifiedMixin, PaginationMixin, DeclarativeBase):
    __tablename__ = 'ticket_message'

    id = Field(Integer(), primary_key=True)
    ticket_id = Field(Integer(), ForeignKey(Ticket.id))
    member_id = Field(Integer(), ForeignKey('member.id'))
    text = Field(Unicode())

    is_answer = Field(Boolean(), default=False)

    _attachment = Field(TicketAttachment.as_mutable(JSON), nullable=True, protected=True)

    ticket = relationship(Ticket, lazy='select', uselist=False, protected=True)

    @property
    def attachment(self):
        return self._attachment.locate() if self._attachment else None

    @attachment.setter
    def attachment(self, value):
        if value is not None:
            self._attachment = TicketAttachment.create_from(value)
        else:
            self._attachment = None

    def to_dict(self):
        result = super().to_dict()
        result['attachment'] = self.attachment
        return result
예제 #4
0
 def get_summaries(self, req: CamcopsRequest) -> List[SummaryElement]:
     return self.standard_task_summary_fields() + [
         SummaryElement(name="meets_criteria",
                        coltype=Boolean(),
                        value=self.meets_criteria(),
                        comment="Meets criteria for schizotypal disorder?"),
     ]
예제 #5
0
    def default_attr(self,comp_cls, results_table = None):
        '''we make the default entries for a components primary table'''

        table_abrv = self.component_table_abrv
        if issubclass(comp_cls, Analysis): table_abrv = self.analysis_table_abrv

        name = comp_cls.__name__.lower()
        #TODO: Add mapping __init__ method
        default_attr = {'__tablename__': f'{table_abrv}{name}' ,
                        #'id': Column(Integer, primary_key=True),
                        '__table_args__': self.default_args,
                        '__abstract__': False,
                        '_mapped_component': comp_cls,
                        'attr_store': None
                        }

        if results_table is not None:
            tbl_name = f'{results_table}_{table_abrv}{name}'
            backref_name = f'db_comp_{name}'
            root_obj,_ = self.mapped_tables[results_table]
            default_attr['__tablename__'] = f'{results_table}_{table_abrv}{name}' 
            default_attr['result_id'] = Column(Integer, ForeignKey(f'{results_table}.id') ,primary_key=True)
            default_attr['analysis'] = relationship(root_obj.__name__,backref = backref(backref_name,lazy='noload'))

        else: #its an analysis
            default_attr['created'] = Column(DateTime, server_default=func.now())
            default_attr['active'] = Column(Boolean(), server_default = 't')
            default_attr['run_id'] = Column(String(36)) #corresponds to uuid set in analysis
            default_attr['id']: Column(Integer, primary_key=True)
            #default_attr['components'] = relationship(TableBase, back_populates= "analysis")

        return default_attr
예제 #6
0
 def get_summaries(self, req: CamcopsRequest) -> List[SummaryElement]:
     return self.standard_task_summary_fields() + [
         SummaryElement(name="depression_risk",
                        coltype=Boolean(),
                        value=self.has_depression_risk(),
                        comment="Has depression or at risk of depression"),
     ]
예제 #7
0
 def get_summaries(self, req: CamcopsRequest) -> List[SummaryElement]:
     return self.standard_task_summary_fields() + [
         SummaryElement(name="n_core",
                        coltype=Integer(),
                        value=self.n_core(),
                        comment="Number of core diagnostic symptoms (/3)"),
         SummaryElement(
             name="n_additional",
             coltype=Integer(),
             value=self.n_additional(),
             comment="Number of additional diagnostic symptoms (/7)"),
         SummaryElement(
             name="n_total",
             coltype=Integer(),
             value=self.n_total(),
             comment="Total number of diagnostic symptoms (/10)"),
         SummaryElement(name="n_somatic",
                        coltype=Integer(),
                        value=self.n_somatic(),
                        comment="Number of somatic syndrome symptoms (/8)"),
         SummaryElement(name="category",
                        coltype=SummaryCategoryColType,
                        value=self.get_full_description(req),
                        comment="Diagnostic category"),
         SummaryElement(name="psychosis_or_stupor",
                        coltype=Boolean(),
                        value=self.is_psychotic_or_stupor(),
                        comment="Psychotic symptoms or stupor present?"),
     ]
예제 #8
0
class ContentType(Base):
    __tablename__ = "content_type"

    id = Column(BigInteger, primary_key=True, autoincrement=True)

    name = Column(String)
    color = Column(String(7))
    active = Column(Boolean(), default=True, nullable=False)

    deleted = Column(Boolean(), default=False, nullable=False)

    @staticmethod
    def get_by_id(id):
        return ContentType.query.filter(
            ContentType.id == id,
            ContentType.deleted.is_(False)).one_or_none()
예제 #9
0
class HospitalToken(ModelsBase):

    __tablename__ = 'hospital_tokens'

    id = Column(UUID(as_uuid=True), primary_key=True,default=uuid.uuid4)
    hospital_id = Column(UUID(as_uuid=True),nullable=False)
    token = Column(String(),nullable=False)
    is_valid = Column(Boolean(),default=True)
예제 #10
0
 def get_summaries(self, req: CamcopsRequest) -> List[SummaryElement]:
     return self.standard_task_summary_fields() + [
         SummaryElement(
             name="meets_general_criteria",
             coltype=Boolean(),
             value=self.has_pd(),
             comment="Meets general criteria for personality disorder?"),
         SummaryElement(name="paranoid_pd",
                        coltype=Boolean(),
                        value=self.has_paranoid_pd(),
                        comment="Meets criteria for paranoid PD?"),
         SummaryElement(name="schizoid_pd",
                        coltype=Boolean(),
                        value=self.has_schizoid_pd(),
                        comment="Meets criteria for schizoid PD?"),
         SummaryElement(name="dissocial_pd",
                        coltype=Boolean(),
                        value=self.has_dissocial_pd(),
                        comment="Meets criteria for dissocial PD?"),
         SummaryElement(
             name="eupd_i",
             coltype=Boolean(),
             value=self.has_eupd_i(),
             comment="Meets criteria for EUPD (impulsive type)?"),
         SummaryElement(
             name="eupd_b",
             coltype=Boolean(),
             value=self.has_eupd_b(),
             comment="Meets criteria for EUPD (borderline type)?"),
         SummaryElement(name="histrionic_pd",
                        coltype=Boolean(),
                        value=self.has_histrionic_pd(),
                        comment="Meets criteria for histrionic PD?"),
         SummaryElement(name="anankastic_pd",
                        coltype=Boolean(),
                        value=self.has_anankastic_pd(),
                        comment="Meets criteria for anankastic PD?"),
         SummaryElement(name="anxious_pd",
                        coltype=Boolean(),
                        value=self.has_anxious_pd(),
                        comment="Meets criteria for anxious PD?"),
         SummaryElement(name="dependent_pd",
                        coltype=Boolean(),
                        value=self.has_dependent_pd(),
                        comment="Meets criteria for dependent PD?"),
     ]
예제 #11
0
 def get_summaries(self, req: CamcopsRequest) -> List[SummaryElement]:
     return self.standard_task_summary_fields() + [
         SummaryElement(
             name="meets_criteria",
             coltype=Boolean(),
             value=self.meets_criteria(),
             comment="Meets criteria for a mixed affective episode?"),
     ]
예제 #12
0
 def get_summaries(self, req: CamcopsRequest) -> List[SummaryElement]:
     return self.standard_task_summary_fields() + [
         SummaryElement(
             name="meets_general_criteria",
             coltype=Boolean(),
             value=self.meets_general_criteria(),
             comment="Meets general criteria for paranoid/hebephrenic/"
             "catatonic/undifferentiated schizophrenia "
             "(F20.0-F20.3)?"),
     ]
예제 #13
0
class Service(ModelsBase):

    __tablename__ = 'services'

    id = Column(UUID(as_uuid=True), primary_key=True,default=uuid.uuid4)
    hospital_id = Column(UUID(as_uuid=True),nullable=False)
    name =  Column(String(),nullable=False)
    description =  Column(String(),nullable=False)
    is_free = Column(Boolean(),nullable=False)
    cost = Column(String(),nullable=False)
예제 #14
0
class MappedItem(ReportBase):
    __abstract__ = True

    _mapped_component = None

    id = Column( Integer, primary_key = True)
    tablename = Column(String(DEFAULT_STRING_LENGTH))
    attrtable = Column(String(DEFAULT_STRING_LENGTH))
    classname = Column(String(DEFAULT_STRING_LENGTH))
    mro_inheritance = Column(String(1200))

    active = Column(Boolean(), default=True )

    def __init__(self,tablerep, mapped_class):
        self.classname = mapped_class.__name__
        self.tablename = tablerep.__tablename__

        if issubclass(mapped_class,Analysis):
            self.attrtable = f'anly_attr_{tablerep.__tablename__}'
        else:
            self.attrtable = tablerep.__tablename__.replace('tbl','attr')
        
        self._mapped_component = mapped_class

        distinct =mapped_class.mro()
        if mapped_class in distinct:
            distinct.remove(mapped_class)
        comp_inx = distinct.index(Component)
        self.mro_inheritance = '.'.join([cls.__name__ for cls in distinct[0:comp_inx+1]])    

    @classmethod
    def db_columns(cls):
        if '__table__' in cls.__dict__ and cls.__table__ is not None:
            return set(list(cls.__table__.c.keys()))

    @classmethod
    def all_fields(cls):
        all_table_fields = set([ attr.lower() for attr in cls._mapped_component.cls_all_property_labels() ])
        all_attr_fields = set([ attr.lower() for attr in cls._mapped_component.cls_all_attrs_fields().keys() ])
        all_fields = set.union(all_table_fields,all_attr_fields)
        return set(list(all_fields))

    @classmethod
    def dynamic_columns(cls):
        if cls._mapped_component is None:
            return []

        return set.difference(cls.all_fields(), cls.db_columns())

    @classmethod
    def tablenames(cls,db):
        #rr = ResultsRegistry()
        with db.session_scope() as sesh:
            results = list( sesh.query(cls.tablename).all())
        return flatten(results)
예제 #15
0
 def get_summaries(self, req: CamcopsRequest) -> List[SummaryElement]:
     return self.standard_task_summary_fields() + [
         SummaryElement(name="category",
                        coltype=SummaryCategoryColType,
                        value=self.get_description(req),
                        comment="Diagnostic category"),
         SummaryElement(name="psychotic_symptoms",
                        coltype=Boolean(),
                        value=self.psychosis_present(),
                        comment="Psychotic symptoms present?"),
     ]
예제 #16
0
파일: fast.py 프로젝트: tarun911/camcops
 def get_summaries(self, req: CamcopsRequest) -> List[SummaryElement]:
     return self.standard_task_summary_fields() + [
         SummaryElement(name="total",
                        coltype=Integer(),
                        value=self.total_score(),
                        comment="Total score (/{})".format(self.MAX_SCORE)),
         SummaryElement(name="positive",
                        coltype=Boolean(),
                        value=self.is_positive(),
                        comment="FAST positive?"),
     ]
예제 #17
0
파일: mast.py 프로젝트: tarun911/camcops
 def get_summaries(self, req: CamcopsRequest) -> List[SummaryElement]:
     return self.standard_task_summary_fields() + [
         SummaryElement(name="total",
                        coltype=Integer(),
                        value=self.total_score(),
                        comment="Total score (/{})".format(self.MAX_SCORE)),
         SummaryElement(
             name="exceeds_threshold",
             coltype=Boolean(),
             value=self.exceeds_ross_threshold(),
             comment="Exceeds Ross threshold (total score >= {})".format(
                 self.ROSS_THRESHOLD)),
     ]
예제 #18
0
 def get_summaries(self, req: CamcopsRequest) -> List[SummaryElement]:
     return self.standard_task_summary_fields() + [
         SummaryElement(
             name="total",
             coltype=Integer(),
             value=self.total_score(),
             comment=f"Total score ({self.MIN_SCORE}-{self.MAX_SCORE})",
         ),
         SummaryElement(
             name="num_symptomatic",
             coltype=Integer(),
             value=self.num_symptomatic(),
             comment="Total number of symptoms considered symptomatic "
             "(meaning scoring 2 or more)",
         ),
         SummaryElement(
             name="num_symptomatic_B",
             coltype=Integer(),
             value=self.num_symptomatic_b(),
             comment="Number of group B symptoms considered symptomatic "
             "(meaning scoring 2 or more)",
         ),
         SummaryElement(
             name="num_symptomatic_C",
             coltype=Integer(),
             value=self.num_symptomatic_c(),
             comment="Number of group C symptoms considered symptomatic "
             "(meaning scoring 2 or more)",
         ),
         SummaryElement(
             name="num_symptomatic_D",
             coltype=Integer(),
             value=self.num_symptomatic_d(),
             comment="Number of group D symptoms considered symptomatic "
             "(meaning scoring 2 or more)",
         ),
         SummaryElement(
             name="num_symptomatic_E",
             coltype=Integer(),
             value=self.num_symptomatic_e(),
             comment="Number of group D symptoms considered symptomatic "
             "(meaning scoring 2 or more)",
         ),
         SummaryElement(
             name="ptsd",
             coltype=Boolean(),
             value=self.ptsd(),
             comment="Provisionally meets DSM-5 criteria for PTSD",
         ),
     ]
예제 #19
0
    def test_to_yaml_type(self):
        """Tests the utils.to_yaml_type function"""

        from sqlalchemy.sql.sqltypes import Boolean, Integer, Float, String, \
            Date, Time, DateTime, _Binary

        self.assertEqual('str', utils.to_yaml_type(None))

        self.assertEqual('bool', utils.to_yaml_type(Boolean()))
        self.assertEqual('int', utils.to_yaml_type(Integer()))
        self.assertEqual('float', utils.to_yaml_type(Float()))
        self.assertEqual('str', utils.to_yaml_type(String()))
        self.assertEqual('str', utils.to_yaml_type(Date()))
        self.assertEqual('str', utils.to_yaml_type(Time()))
        self.assertEqual('str', utils.to_yaml_type(DateTime()))
        self.assertEqual('binary', utils.to_yaml_type(_Binary()))
예제 #20
0
class User(db.Model):
    __tablename__ = "users"

    id = Column(Integer, primary_key=True, autoincrement=True)
    username = Column(String(128), nullable=False)
    email = Column(String(128), nullable=False)
    password = Column(String(255), nullable=False)
    active = Column(Boolean(), default=True, nullable=False)
    created_date = Column(DateTime, default=func.now(), nullable=False)

    def __init__(self, username="", email="", password=""):
        self.username = username
        self.email = email
        self.password = bcrypt.generate_password_hash(
            password, current_app.config["BCRYPT_LOG_ROUNDS"]
        ).decode()

    def to_json(self):
        return {
            "id": self.id,
            "username": self.username,
            "email": self.email,
            "active": self.active,
        }

    def encode_token(self, user_id, token_type):
        if token_type == "access":
            seconds = current_app.config.get("ACCESS_TOKEN_EXPIRATION")
        else:
            seconds = current_app.config.get("REFRESH_TOKEN_EXPIRATION")

        # expiration, issued at, subject
        payload = {
            "exp": datetime.datetime.utcnow()
            + datetime.timedelta(days=0, seconds=seconds),
            "iat": datetime.datetime.utcnow(),
            "sub": user_id,
        }
        return jwt.encode(
            payload, current_app.config.get("SECRET_KEY"), algorithm="HS256"
        )

    @staticmethod
    def decode_token(token):
        payload = jwt.decode(token, current_app.config.get("SECRET_KEY"))
        return payload.get("sub")
예제 #21
0
class BankingId(TimestampMixin, DeclarativeBase):
    __tablename__ = 'banking_id'

    id = Field(Integer(), primary_key=True)
    client_id = Field(Integer(), ForeignKey('client.id'))

    is_verified = Field(Boolean(), default=False)
    error = Field(Unicode(), nullable=True)

    client = relationship('Client', lazy='select', protected=True)

    type = Field(Enum('bank_account', 'bank_card', name='banking_id_type'))

    __mapper_args__ = {
        'polymorphic_identity': __tablename__,
        'polymorphic_on': type
    }
예제 #22
0
def factory(
    *,
    string_types: Strategy[TypeEngine] = strings_factory(),
    binary_string_types: Strategy[TypeEngine] = binary_strings_factory(),
    enum_types: Strategy[TypeEngine] = enums_factory(),
    primary_keys_types: Strategy[TypeEngine] = primary_keys_factory()
) -> Strategy[TypeEngine]:
    extra_types = [
        Float(asdecimal=True),
        Boolean(),
        Date(),
        DateTime(),
        Interval(),
        Time()
    ]
    return strategies.one_of(string_types, binary_string_types, enum_types,
                             primary_keys_types,
                             strategies.sampled_from(extra_types))
예제 #23
0
class Worker(Base):
    __tablename__ = "worker"
    id = Column(BigInteger, primary_key=True, autoincrement=True)

    ean13 = Column(BigInteger, unique=True, nullable=False)
    login = Column(String, unique=True)
    password = Column(String, nullable=False)

    name = Column(String)
    surname = Column(String)
    middle_name = Column(String)

    type = Column(EnumField(WorkerType), nullable=False)

    deleted = Column(Boolean(), default=False, nullable=False)

    @staticmethod
    def get_by_code(code):
        return Worker.query.filter(Worker.ean13 == code,
                                   Worker.deleted.is_(False)).one_or_none()

    def is_password_valid(self, password):
        return str(password) == str(self.password)

    @staticmethod
    def get_by_code_or_not_found(code):
        worker = Worker.get_by_code(code)
        if worker is None:
            raise HTTPNotFound(
                description={
                    "error_code": 201,
                    "error_message": "Рабочий с таким кодом не найден"
                })
        return worker

    @staticmethod
    def generate_worker_password():
        prefix = '299'
        body = randint(000000000, 999999999)
        code = prefix + str(body)
        checksum = calculate_checksum(code)

        return code + str(checksum)
예제 #24
0
class Tweet(Base):
    """[define tweet data table]
    Args:
        Base ([class]): [base class]
    """

    __tablename__ = "tweet_data"

    id = Column(Integer, primary_key=True, autoincrement=True)
    user_name = Column(String(64))
    user_id = Column(String(64))
    following = Column(Integer(), default=0)
    followers = Column(Integer(), default=0)
    date = Column(String(64))
    content = Column(Text)
    reply = Column(Integer(), default=0)
    retweet = Column(Integer(), default=0)
    like = Column(Integer(), default=0)
    modify_tag = Column(Boolean(), default=False)

    def __init__(self,
                 user_name,
                 user_id,
                 date,
                 content,
                 reply=0,
                 retweet=0,
                 like=0,
                 following=0,
                 followers=0,
                 modify_tag=False):
        self.user_name = user_name
        self.user_id = user_id
        self.following = following
        self.followers = followers
        self.date = date
        self.content = content
        self.reply = reply
        self.retweet = retweet
        self.like = like
        self.modify_tag = modify_tag
예제 #25
0
metadata = MetaData()
userinfo = Table(
    'userinfo',
    metadata,
    Column('user_id', String, primary_key=True),
    Column('character_id', Integer, ForeignKey('character_id')),
    Column('fullname', String(50)),
    Column('nickname', String(16)),
    Column('email', String(50)),
)

characterinfo = Table('characterinfo', metadata,
                      Column('user_id', String, ForeignKey('user_id')),
                      Column('character_id', Integer, primary_key=True),
                      Column('is_in_roda', Boolean(1)),
                      Column('is_conscious', Boolean(1)),
                      Column('is_alive', Boolean(1)),
                      Column('char_name', String(25)),
                      Column('exp_total', Integer(7)),
                      Column('exp_current ', Integer(7)),
                      Column('gender_ident', String(15)),
                      Column('size_c', Integer(3)),
                      Column('mestre', String(25)),
                      Column('capoeira_school', String(25)),
                      Column('corda', Integer(2)),
                      Column('predction_ponts', Integer(3)),
                      Column('malicia', Integer(3)),
                      Column('spirit', Integer(3)), Column('swag', Integer(3)),
                      Column('intelegence', Integer(3)),
                      Column('strength', Integer(3)),