Exemplo n.º 1
0
class Card(AutoSave, Document):
    '''
    A reference document for a card. This should contain only one isntance of every card in the game.
    '''

    name = StringField()
    cost = IntField()
    buys = IntField(default=0)
    actions = IntField(default=0)
    cards = IntField(default=0)
    money = IntField(default=0)
    victory = IntField(default=0)
    type = StringField()
    has_script = BooleanField(default=False)

    function = None

    def __repr__(self):
        '''
        To String.
        '''
        return '<Card %s>' % self.name

    @untested
    def playout(self):
        '''
        Plays out the actual contens of the card.
        '''
        pass

    '''    
Exemplo n.º 2
0
class LayerUserSettings(Document):
    meta = {
        "collection": "noc.layerusersettings",
        "strict": False,
        "auto_create_index": False
    }
    # User Id
    user = IntField()
    # Layer Id
    layer = ObjectIdField()
    # Visibility
    is_visible = BooleanField(default=True)

    @classmethod
    def is_visible_by_user(cls, user, layer):
        s = LayerUserSettings.objects.filter(user=user.id,
                                             layer=layer.id).first()
        if s:
            return s.is_visible
        return True

    @classmethod
    def set_layer_visibility(cls, user, layer, status):
        s = LayerUserSettings.objects.filter(user=user.id,
                                             layer=layer.id).first()
        if not s:
            s = LayerUserSettings(user=user.id, layer=layer.id)
        s.is_visible = status
        s.save()
Exemplo n.º 3
0
class Supplier(Document):
    meta = {
        "collection": "noc.suppliers",
        "indexes": ["name"],
        "strict": False,
        "auto_create_index": False,
    }

    name = StringField()
    description = StringField()
    is_affilated = BooleanField(default=False)
    profile = PlainReferenceField(SupplierProfile)
    state = PlainReferenceField(State)
    project = ForeignKeyField(Project)
    # Integration with external NRI and TT systems
    # Reference to remote system object has been imported from
    remote_system = PlainReferenceField(RemoteSystem)
    # Object id in remote system
    remote_id = StringField()
    # Object id in BI
    bi_id = LongField(unique=True)

    tags = ListField(StringField())

    _id_cache = cachetools.TTLCache(maxsize=100, ttl=60)

    def __str__(self):
        return self.name

    @classmethod
    @cachetools.cachedmethod(operator.attrgetter("_id_cache"),
                             lock=lambda _: id_lock)
    def get_by_id(cls, id):
        return Supplier.objects.filter(id=id).first()
Exemplo n.º 4
0
class Playing(Document):
    """
    At a given time, a media source could play multiple Campaigns.
    The time is captured as start and end, where the relationship is valid.
    This class realizes a  relationship.

    If the media owner decides to abrupt the campaign, he sets the flag
    is_valid to False through Media dash-board. deletion_date will be updated
    for records.
    """
    # for e.g. Mall's default source
    primary_media_source = ReferenceField('MediaSource', required=False)
    playing_content = ReferenceField('Campaign', default=None, required=False)
    # for e.g. VOD, OOH, Sensor etc.
    source_type = StringField()
    # official start-end date
    start_date = DateTimeField(default=datetime.now())
    end_date = DateTimeField()
    # forceful setting of the play flag
    pause_playing = BooleanField(default=False)
    # book-keeping entries
    creation_date = DateTimeField(default=datetime.now())
    deletion_date = DateTimeField()

    # Status
    state = StringField(required=False)

    # vendor book-keeping (campaign-id, sensor-id, zone-id etc.)
    playing_vendor_attributes = DictField(required=False)

    def get_absolute_url(self):
        return "/mediacontent/playing/%i/" % self.id
class SuperAdmin(db.Document):
    email = EmailField(required=True, primary_key=True)
    password = StringField(required=True)
    approved = BooleanField(default=False)

    def format(self):
        return {"email": self.email, "approved": self.approved}
Exemplo n.º 6
0
class OPDServiceExtension(AmenityExtension):
    """
    This extension adds an OPD department to be part of the
    amenity.
    """
    ex_name = StringField(default='OPD Services', required=False)
    ex_type = StringField(default='opdservice')
    brand_name = StringField(required=True)
    brand_description = StringField(required=True)
    brand_url = StringField(required=True)
    # floor, shop number etc.
    outlet_address1 = StringField(required=True)
    outlet_address2 = StringField(required=True)
    treatment_services = ListField()
    # e.g. dialysis, neurosurgery, transplant etc.
    service_condition = StringField()
    appointment_facility = BooleanField()
    average_price = IntegerField()
    open_days = StringField()
    open_timings = StringField()
    # Internal data, Stored in ad-wise
    # not to be serialized
    _meta = DictField(required=False)

    def get_absolute_url(self):
        return "/mediacontent/extension/opd/%i/" % self.id
Exemplo n.º 7
0
class StayingExtension(AmenityExtension):
    """
    This extension adds an adventure sport to be part of the
    amenity.
    """
    ex_name = StringField(default='Staying', required=False)
    ex_type = StringField(default='staying')
    brand_name = StringField(required=True)
    brand_description = StringField(required=True)
    brand_url = StringField(required=True)
    # floor, shop number etc.
    outlet_address1 = StringField(required=True)
    outlet_address2 = StringField(required=True)
    # > 400
    capacity = StringField()
    # e.g. precaution etc.
    service_condition = StringField()
    reservation_facility = BooleanField()
    reservation_number = StringField()
    average_price = StringField()
    # Internal data, Stored in ad-wise
    # not to be serialized
    _meta = DictField(required=False)

    def get_absolute_url(self):
        return "/mediacontent/extension/staying/%i/" % self.id
Exemplo n.º 8
0
class Process(ModelBase, Document):
    aysdomain = StringField(default='')
    aysname = StringField(default='')
    pname = StringField(default='')  # process name
    sname = StringField(default='')  # name as specified in startup manager
    ports = ListField(IntField())
    instance = StringField(default='')
    systempid = ListField(IntField())  # system process id (PID) at this point
    epochstart = IntField()
    epochstop = IntField()
    active = BooleanField()
    lastcheck = IntField(default=j.data.time.getTimeEpoch())
    cmd = StringField(default='')
    workingdir = StringField(default='')
    parent = StringField(default='')
    type = StringField(default='')
    statkey = StringField(default='')
    nr_file_descriptors = FloatField()
    nr_ctx_switches_voluntary = FloatField()
    nr_ctx_switches_involuntary = FloatField()
    nr_threads = FloatField()
    cpu_time_user = FloatField()
    cpu_time_system = FloatField()
    cpu_percent = FloatField()
    mem_vms = FloatField()
    mem_rss = FloatField()
    io_read_count = FloatField()
    io_write_count = FloatField()
    io_read_bytes = FloatField()
    io_write_bytes = FloatField()
    nr_connections_in = FloatField()
    nr_connections_out = FloatField()
Exemplo n.º 9
0
class User(ModelBase, Document):
    name = StringField(default='')
    domain = StringField(default='')
    passwd = StringField(default='')  # stored hashed
    roles = ListField(StringField())
    active = BooleanField()
    description = StringField(default='')
    emails = ListField(StringField())
    xmpp = ListField(StringField())
    mobile = ListField(StringField())
    # epoch of last time the info updated
    lastcheck = IntField(default=j.data.time.getTimeEpoch())
    groups = ListField(StringField())
    authkey = StringField(default='')
    data = StringField(default='')
    authkeys = ListField(StringField())

    def authenticate(username, passwd):
        for user in User.find({'name': username}):
            if hmac.compare_digest(user.passwd,
                                   j.sal.unix.crypt(passwd, user.passwd)):
                return True
        return False

    def save(user):
        if not user.id:
            user.passwd = j.sal.unix.crypt(user.passwd)
        else:
            olduser = User.get(user.id)
            if olduser.passwd != user.passwd:  # change passwd
                user.passwd = j.sal.unix.crypt(user.passwd)
        super(ModelBase, user).save()
Exemplo n.º 10
0
class User(Document, UserMixin):
    login = StringField(**default_params, unique=True, validate_rule='string')
    password_hash = StringField(**default_params)
    authenticated = BooleanField(default=False)

    def change_password(self, old_password, new_password) -> bool:
        if self.check_password(old_password):
            self.set_password(new_password)
            self.save()
            return True
        return False

    def set_password(self, password):
        self.password_hash = generate_password_hash(password)

    def check_password(self, password) -> bool:
        return check_password_hash(self.password_hash, password)

    def is_active(self):  # All users are active
        return True

    def get_id(self):
        return self.login

    def is_authenticated(self):
        return self.authenticated

    def is_anonymous(self):
        return False

    meta = {'collection': 'Users'}
Exemplo n.º 11
0
class Nic(ModelBase, Document):
    name = StringField(default='')
    mac = StringField(default='')
    ipaddr = ListField(StringField())
    active = BooleanField(default=True)
    # poch of last time the info was checked from reality
    lastcheck = IntField(default=j.data.time.getTimeEpoch())
Exemplo n.º 12
0
class ActionParameter(EmbeddedDocument):
    name = StringField()
    type = StringField(choices=[
        ("int", "int"),
        ("float", "float"),
        ("str", "str"),
        ("interface", "interface"),
        ("ip", "ip"),
        ("vrf", "vrf"),
    ])
    description = StringField()
    is_required = BooleanField(default=True)
    default = StringField()

    def __str__(self):
        return self.name

    @property
    def json_data(self):
        r = {
            "name": self.name,
            "type": self.type,
            "description": self.description,
            "is_required": self.is_required,
        }
        if self.default is not None:
            r["default"] = self.default
        return r
Exemplo n.º 13
0
class OpenHours(EmbeddedDocument):
    """Hours Embedded Document Schema"""

    start = StringField(required=True)
    end = StringField(required=True)
    is_overnight = BooleanField(required=True)
    day = IntField(required=True)
Exemplo n.º 14
0
class Credential(Document):
    """
    This class represents a set of credentials for the target system.
    """

    meta = {
        "collection": COLLECTION_TARGET_CREDS,
        "indexes": [{
            "fields": ["target_name"]
        }]
    }
    target_name = StringField(max_length=MAX_STR_LEN)
    user = StringField(max_length=MAX_STR_LEN)
    key = StringField(max_length=MAX_BIGSTR_LEN)
    service = StringField(max_length=MAX_STR_LEN)
    valid = BooleanField(null=False, default=True)

    @property
    def document(self):
        """
        Return as formatted JSON.
        """
        return {
            "target_name": self.target_name,
            "user": self.user,
            "key": self.key,
            "service": self.service,
            "valid": self.valid,
        }
Exemplo n.º 15
0
class SpecialityClinicExtension(AmenityExtension):
    """
    This extension adds a specialty clinic to be part of the
    amenity.
    """
    ex_name = StringField(default='Speciality Clinic', required=False)
    ex_type = StringField(default='specialityclinic')
    brand_name = StringField(required=True)
    brand_description = StringField(required=True)
    brand_url = StringField(required=True)
    # floor, shop number etc.
    outlet_address1 = StringField(required=True)
    outlet_address2 = StringField(required=True)
    treatment_services = ListField()
    # > 400
    number_of_beds = StringField()
    # e.g. Religare, Mediassist etc.
    insurance_partners = ListField()
    # e.g. dialysis, neurosurgery, transplant etc.
    service_condition = StringField()
    appointment_facility = BooleanField()
    average_price = IntegerField()
    open_days = StringField()
    open_timings = StringField()
    # Internal data, Stored in ad-wise
    # not to be serialized
    _meta = DictField(required=False)

    def get_absolute_url(self):
        return "/mediacontent/extension/clinic/%i/" % self.id
Exemplo n.º 16
0
class BlackboxModel(Document):
    """A class which describes the model of a Blackbox inside MongoDB."""

    model_id = StringField(unique=True, required=True)
    creation_date = DateTimeField(default=datetime.datetime.utcnow())
    last_update_date = DateTimeField()
    models = ListField(StringField(), required=True)
    columns = ListField(StringField(), required=True)
    trained = BooleanField(default=False)
    saved = FileField()

    meta = {"allow_inheritance": True}

    def to_dict(self):
        return {
            "model_id": self.model_id,
            "creation_date": self.creation_date.isoformat(),
            "last_update_date": self.last_update_date.isoformat(),
            "models": self.models,
            "columns": self.columns,
            "trained": self.trained,
        }

    def clean(self):
        if not all(model in AVAILABLE_MODELS for model in self.models):
            raise ValidationError(
                f"There is at least one model in the list of models that does not "
                f"exist. Passed models: {', '.join(self.models)}. "
                f"Available models: {', '.join(AVAILABLE_MODELS)} ")

    @classmethod
    def pre_save(cls, sender, document, **kwargs):
        document.last_update_date = datetime.datetime.utcnow()
Exemplo n.º 17
0
class DoctorExtension(AmenityExtension):
    """
    This extension adds doctors to be part of the
    amenity.
    """
    ex_name = StringField(default='Doctor', required=False)
    ex_type = StringField(default='doctor')
    name = StringField(required=True)
    description = StringField(required=True)
    url = StringField(required=True)
    # e.g. MD-General Medicine
    subscripts = StringField(required=True)
    experience = StringField(required=True)
    # Achievements - Award, Gold Medalist etc.
    accolades = ListField()
    avg_consultation_charge = StringField()
    appointment_facility = BooleanField()
    available_days = StringField()
    available_timings = StringField()
    # Internal data, Stored in ad-wise
    # not to be serialized
    _meta = DictField(required=False)

    def get_absolute_url(self):
        return "/mediacontent/extension/doctor/%i/" % self.id
Exemplo n.º 18
0
class AccessProtocol(EmbeddedDocument):
    protocol = StringField()
    base_url = StringField()
    is_active = BooleanField(default=True)

    def __unicode__(self):
        return self.base_url
Exemplo n.º 19
0
class AdventureSportExtension(AmenityExtension):
    """
    This extension adds an adventure sport to be part of the
    amenity.
    """
    ex_name = StringField(default='Adventure', required=False)
    ex_type = StringField(default='adventuresport')
    brand_name = StringField(required=True)
    brand_description = StringField(required=True)
    brand_url = StringField(required=True)
    # floor, shop number etc.
    outlet_address1 = StringField(required=True)
    outlet_address2 = StringField(required=True)
    # Elephant ride, Water ride etc.
    sport_name = StringField()
    sport_description = StringField()
    # > 400
    capacity = StringField()
    target_age_group = StringField()
    # e.g. Decathlon etc.
    brand_partners = ListField()
    # e.g. precaution etc.
    service_condition = StringField()
    reservation_facility = BooleanField()
    reservation_number = StringField()
    average_price = StringField()
    open_days = StringField()
    open_timings = StringField()
    # Internal data, Stored in ad-wise
    # not to be serialized
    _meta = DictField(required=False)

    def get_absolute_url(self):
        return "/mediacontent/extension/sport/%i/" % self.id
Exemplo n.º 20
0
class Credential(Document):
    """
    This class represents a set of credentials for the target system.
    """
    meta = {
        'collection': COLLECTION_TARGET_CREDS,
        'indexes': [
            {
                'fields': ['target_name'],
            },
        ]
    }
    target_name = StringField(max_length=MAX_STR_LEN)
    user = StringField(max_length=MAX_STR_LEN)
    key = StringField(max_length=MAX_BIGSTR_LEN)
    service = StringField(max_length=MAX_STR_LEN)
    valid = BooleanField(null=False, default=True)

    @property
    def document(self):
        """
        Return as formatted JSON.
        """
        return {
            'target_name': self.target_name,
            'user': self.user,
            'key': self.key,
            'service': self.service,
            'valid': self.valid,
        }
Exemplo n.º 21
0
class MultiplexExtension(AmenityExtension):
    """
    This extension adds a multi-plex to be part of the
    amenity.
    """
    ex_name = StringField(default='Multiplex', required=False)
    ex_type = StringField(default='moviemultiplex')
    brand_name = StringField(required=True)
    brand_description = StringField(required=True)
    brand_url = StringField(required=True)
    # floor, shop number etc.
    outlet_address1 = StringField(required=True)
    outlet_address2 = StringField(required=True)
    # > 400
    audis = StringField()
    capacity_per_audi = StringField()
    # e.g. precaution etc.
    service_condition = StringField()
    reservation_facility = BooleanField()
    reservation_number = StringField()
    rservation_url = StringField()
    average_price = StringField()
    open_days = StringField()
    # [9:30-12:30, 12:45-2:30]
    show_timings = ListField()
    # Internal data, Stored in ad-wise
    # not to be serialized
    _meta = DictField(required=False)

    def get_absolute_url(self):
        return "/mediacontent/extension/movie/%i/" % self.id
Exemplo n.º 22
0
class PlayerReplay(Document):
    player = ReferenceField(Player, required=True)
    replay = ReferenceField(Replay, required=True)
    is_winner = BooleanField(required=True)
    player_hero = ReferenceField(PlayerHero, required=True)
    hero_level = IntField(required=True)
    mmr_before = IntField(required=True)
    mmr_after = IntField()
    talents = ListField(ReferenceField(Talent))
    kills = IntField()
    assists = IntField()
    deaths = IntField()
    time_dead = IntField()
    hero_damage = IntField()
    siege_damage = IntField()
    healing = IntField()
    self_healing = IntField()
    damage_taken = IntField()
    experience_earned = IntField()
    meta = {
        'indexes': [
            'player_hero',
            'replay',
            ('player_hero', 'replay')
        ]
    }
Exemplo n.º 23
0
class Subscription(Document):
    meta = {"collection": "subscriptions"}
    ID = ObjectIdField()
    stripeCustomerPlan = StringField()
    stripeCustomerId = StringField()
    stripeCustomerSubscriptionId = StringField()
    active = BooleanField()
Exemplo n.º 24
0
class Street(Document):
    meta = {
        "collection": "noc.streets",
        "strict": False,
        "auto_create_index": False,
        "indexes": ["parent", "data"],
    }
    #
    parent = PlainReferenceField(Division)
    # Normalized name
    name = StringField()
    # street/town/city, etc
    short_name = StringField()
    #
    is_active = BooleanField(default=True)
    # Additional data
    # Depends on importer
    data = DictField()
    #
    start_date = DateTimeField()
    end_date = DateTimeField()

    def __str__(self):
        if self.short_name:
            return "%s, %s" % (self.name, self.short_name)
        else:
            return self.name

    @property
    def full_path(self):
        if not self.parent:
            return ""
        r = [self.parent.full_path, smart_text(self)]
        return " | ".join(r)
class Appointment(db.Document):
    creationDate = DateTimeField(required=True)
    closedDate = DateTimeField()
    nextAppointment = DateTimeField(required=True)
    hospital = ReferenceField(Hospital, required=True)
    patient = ReferenceField(User, required=True)
    closed = BooleanField(default=False)
    appointments = EmbeddedDocumentListField(AppointmentDetail, default=[])

    def format(self):
        response = {
            "id":
            str(self.id),
            "creationDate":
            datetime.strftime(self.creationDate, '%d/%m/%Y %H:%M'),
            "nextAppointment":
            datetime.strftime(self.nextAppointment, '%d/%m/%Y %H:%M'),
            "hospital":
            self.hospital.get_obj(),
            "patient":
            self.patient.format(),
            "closed":
            self.closed,
            "visits":
            [appointment.format() for appointment in self.appointments],
            "cancellable":
            len(self.appointments) == 0
        }
        if self.closedDate:
            response["closedDate"] = datetime.strftime(self.closedDate,
                                                       '%d/%m/%Y %H:%M')
        return response
Exemplo n.º 26
0
class Structures(DynamicDocument):
    contribution = LazyReferenceField(
        Contributions,
        passthrough=True,
        reverse_delete_rule=CASCADE,
        required=True,
        help_text="contribution this structure belongs to",
    )
    is_public = BooleanField(
        required=True, default=False, help_text="public/private structure"
    )
    name = StringField(required=True, help_text="structure name")
    label = StringField(required=True, help_text="structure label")
    lattice = DictField(required=True, help_text="lattice")
    sites = ListField(DictField(), required=True, help_text="sites")
    charge = FloatField(null=True, help_text="charge")
    klass = StringField(help_text="@class")
    module = StringField(help_text="@module")
    meta = {
        "collection": "structures",
        "indexes": ["contribution", "is_public", "name", "label"],
    }

    @classmethod
    def post_save(cls, sender, document, **kwargs):
        set_root_keys = set(k.split(".", 1)[0] for k in document._delta()[0].keys())
        cid = document.contribution.id
        nbs = Notebooks.objects(pk=cid)
        if not set_root_keys or set_root_keys == {"is_public"}:
            nbs.update(set__is_public=document.is_public)
        else:
            nbs.delete()
            document.update(unset__cif=True)
            Contributions.objects(pk=cid).update(unset__structures=True)
Exemplo n.º 27
0
class Tables(Document):
    contribution = LazyReferenceField(
        Contributions,
        passthrough=True,
        reverse_delete_rule=CASCADE,
        required=True,
        help_text="contribution this table belongs to",
    )
    is_public = BooleanField(
        required=True, default=False, help_text="public/private table"
    )
    name = StringField(required=True, help_text="table name")
    columns = ListField(StringField(), required=True, help_text="column names")
    data = ListField(ListField(StringField()), required=True, help_text="table rows")
    config = DictField(help_text="graph config")
    meta = {
        "collection": "tables",
        "indexes": [
            "contribution",
            "is_public",
            "name",
            "columns",
            {"fields": ("contribution", "name"), "unique": True},
        ],
    }

    @classmethod
    def post_save(cls, sender, document, **kwargs):
        Notebooks.objects(pk=document.contribution.id).delete()
Exemplo n.º 28
0
class Overlay(Document):
    meta = {
        "collection": "noc.gis.overlays",
        "strict": False,
        "auto_create_index": False
    }

    name = StringField(required=True)
    gate_id = StringField(unique=True)
    is_active = BooleanField(required=True, default=True)
    permission_name = StringField(required=True)
    overlay = StringField(required=True)
    config = DictField()

    _overlay_cache = {}  # name -> Overlay

    def __str__(self):
        return self.name

    def get_overlay(self):
        if self.overlay not in self._overlay_cache:
            from noc.gis.overlays.base import OverlayHandler

            m = __import__("noc.gis.overlays.%s" % self.overlay, {}, {}, "*")
            for n in dir(m):
                o = getattr(m, n)
                if inspect.isclass(o) and o != OverlayHandler and issubclass(
                        o, OverlayHandler):
                    self._overlay_cache[self.overlay] = o
                    break
        h = self._overlay_cache[self.overlay]
        return h(**self.config)
Exemplo n.º 29
0
class Propuesta(Document):

    meta = {'collection': 'propuesta'}
    nombre = StringField()
    tipo_negocio = ReferenceField(TipoNegocio)
    nro_trabajadores = IntField()
    esta_en_sunat = BooleanField()
Exemplo n.º 30
0
class NumberCategory(Document):
    meta = {"collection": "noc.numbercategories", "strict": False, "auto_create_index": False}

    name = StringField(unique=True)
    is_active = BooleanField()
    description = StringField()
    order = IntField(default=1000)
    rules = ListField(EmbeddedDocumentField(NumberCategoryRule))

    _id_cache = cachetools.TTLCache(100, ttl=60)
    _rule_cache = cachetools.TTLCache(100, ttl=60)

    def __str__(self):
        return self.name

    @classmethod
    @cachetools.cachedmethod(operator.attrgetter("_id_cache"), lock=lambda _: id_lock)
    def get_by_id(cls, id):
        return NumberCategory.objects.filter(id=id).first()

    @classmethod
    @cachetools.cachedmethod(operator.attrgetter("_rule_cache"), lock=lambda _: id_lock)
    def get_rules(cls):
        r = []
        for nc in NumberCategory.objects.filter(is_active=True).order_by("order"):
            for rule in nc.rules:
                if not rule.is_active:
                    continue
                r += [(rule.dialplan, re.compile(rule.mask), nc)]
        return r