Ejemplo n.º 1
0
class Plan(Model):
    author = FK(to=Profile, related_name='plans', on_delete=CASCADE)
    text = TextField()
    inform_gm = BooleanField(default=False)
    date_created = DateTimeField(auto_now_add=True)
    image = ImageField(upload_to='contact_pics', blank=True, null=True)

    class Meta:
        ordering = ['-date_created']

    def __str__(self):
        text = self.text
        return f'{text[0:100] + "..." if len(str(text)) > 100 else text}'

    def save(self, *args, **kwargs):
        first_save = True if not self.pk else False
        super().save(*args, **kwargs)

        if first_save and self.image:
            img = Image.open(self.image.path)
            if img.height > 700 or img.width > 700:
                output_size = (700, 700)
                img.thumbnail(output_size)
                img.save(self.image.path)
Ejemplo n.º 2
0
def get_problematic_tweet_relations(annotator_id:int):
    from django.db.models import Case, When, Value,  BooleanField

    IN_PROGRESS_IDS = get_ids_in_cache('RESOLVE_TWEET_RELATION')

    subquery_ = Annotation.objects.filter(
        tweet_relation=OuterRef('id'),
        annotator=annotator_id
    )
    queryset = TweetRelation.objects \
        .filter(relevant=True, problematic=True) \
        .exclude(id__in=IN_PROGRESS_IDS) \
        .annotate(
            is_skipped_ANNOTATED=Case(
                When(revision__skipped=True, then=Value(True)),
                default=Value(False),
                output_field=BooleanField()
            ),
            has_been_annotated_by_user_ANNOTATED=Exists(
                subquery_
            ),
            has_revision_ANNOTATED=Exists(
                Revision.objects.filter(
                    tweet_relation=OuterRef('id'),
                )  
            ),
            has_revision_without_annotation_ANNOTATED=Exists(
                Revision.objects.filter(
                    tweet_relation=OuterRef('id'),
                    annotation=None
                )  
            )
        ) \
        .only('id')

    return list(queryset)
Ejemplo n.º 3
0
class User(BaseUser, ClassStr):
    company = ForeignKey('Company',
                         on_delete=models.CASCADE,
                         null=True,
                         blank=True)
    is_admin = BooleanField(default=False)
    email = CIEmailField('email', unique=True, blank=False)

    objects = BaseUserManager()

    def clean(self, *args, **kwargs):
        super().clean()
        # Validate company and is_admin not both set
        if self.company and self.is_admin:
            raise ValidationError("Company and is_admin cannot set both")

    def save(self, *args, **kwargs):
        # If this is a new user
        if not self.pk and not self.password:
            password = User.objects.make_random_password()
            self.set_password(password)

        self.full_clean()
        super().save(*args, **kwargs)
Ejemplo n.º 4
0
class Conference(Model):
    conference_name = CharField(max_length=128)
    conference_slug = SlugField()
    status = CharField(choices=conference_statuses,
                       max_length=50,
                       default='upcoming')
    accepting_bids = BooleanField(default=False)
    act_style = CharField(choices=act_format, max_length=50, default='normal')

    def __unicode__(self):
        return self.conference_name

    @classmethod
    def current_conf(cls):
        return cls.objects.filter(status__in=('upcoming', 'ongoing')).first()

    @classmethod
    def by_slug(cls, slug):
        try:
            return cls.objects.get(conference_slug=slug)
        except cls.DoesNotExist:
            return cls.current_conf()

    @classmethod
    def all_slugs(cls):
        return cls.objects.order_by('-conference_slug').values_list(
            'conference_slug', flat=True)

    def windows(self):
        from gbe.models import VolunteerWindow
        return VolunteerWindow.objects.filter(day__conference=self)

    class Meta:
        verbose_name = "conference"
        verbose_name_plural = "conferences"
        app_label = "gbe"
Ejemplo n.º 5
0
class Role(CoreModel):
    DATASCOPE_CHOICES = (
        ('1', "全部数据权限"),
        ('2', "自定数据权限"),
        ('3', "本部门数据权限"),
        ('4', "本部门及以下数据权限"),
        ('5', "仅本人数据权限"),
    )
    roleName = CharField(max_length=64, verbose_name="角色名称")
    roleKey = CharField(max_length=64, verbose_name="权限字符")
    roleSort = IntegerField(verbose_name="角色顺序")
    status = CharField(max_length=8, verbose_name="角色状态")
    admin = BooleanField(default=False, verbose_name="是否为admin")
    dataScope = CharField(max_length=8,default='1', choices=DATASCOPE_CHOICES, verbose_name="权限范围",)
    remark = TextField(verbose_name="备注", help_text="备注", null=True, blank=True)
    dept = ManyToManyField(to='permission.Dept', verbose_name='数据权限-关联部门', db_constraint=False)
    menu = ManyToManyField(to='permission.Menu', verbose_name='关联菜单权限', db_constraint=False)

    class Meta:
        verbose_name = '角色管理'
        verbose_name_plural = verbose_name

    def __str__(self):
        return f"{self.roleName}"
Ejemplo n.º 6
0
class LoginInfor(CoreModel):
    session_id = CharField(max_length=64,
                           verbose_name="会话标识",
                           null=True,
                           blank=True)
    browser = CharField(max_length=64, verbose_name="浏览器")
    ipaddr = CharField(max_length=32,
                       verbose_name="ip地址",
                       null=True,
                       blank=True)
    loginLocation = CharField(max_length=64,
                              verbose_name="登录位置",
                              null=True,
                              blank=True)
    msg = TextField(verbose_name="操作信息", null=True, blank=True)
    os = CharField(max_length=64, verbose_name="操作系统", null=True, blank=True)
    status = BooleanField(default=False, verbose_name="登录状态")

    class Meta:
        verbose_name = '登录日志'
        verbose_name_plural = verbose_name

    def __str__(self):
        return f"{self.creator and self.creator.name}"
Ejemplo n.º 7
0
class Message(Model):
    class Meta:
        ordering = ['-created']

    id = UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    thread = ForeignKey(Thread, related_name="messages", on_delete=CASCADE)
    alias = OneToOneField("Message",
                          null=True,
                          related_name="related_message",
                          on_delete=CASCADE)
    sender = ForeignKey(User,
                        verbose_name="Author",
                        related_name="messages",
                        on_delete=CASCADE)
    public_key_owner = ForeignKey(User,
                                  verbose_name="Public Key Owner",
                                  related_name="messages_by_pb_key",
                                  on_delete=CASCADE)
    text = TextField(verbose_name="Message text", max_length=4096)
    read = BooleanField(verbose_name="Read", default=False)
    created = DateTimeField(auto_now_add=True)

    def __str__(self):
        return str(self.id)
Ejemplo n.º 8
0
class Paper(Model):
    #latest_version = ForeignKey('PaperVersion', related_name='latest_version_of', null=True)
    # add this below because of cyclic dependency; awkward hack
    # (limitation of JeevesModel not ordinary Model)
    author = ForeignKey(UserProfile, null=True)
    accepted = BooleanField()

    @staticmethod
    def jeeves_get_private_author(paper):
        return None

    @staticmethod
    @label_for('author')
    @jeeves
    def jeeves_restrict_paperlabel(paper, ctxt):
        if phase == 'final':
            return True
        else:
            return (paper != None
                    and paper.author == ctxt) or (ctxt != None
                                                  and ctxt.level == 'chair')

    class Meta:
        db_table = 'papers'
Ejemplo n.º 9
0
class Post(Model):
    id = UUIDField(primary_key=True, default=uuid.uuid4, editable=False, unique=True)
    post_type = CharField(max_length=10, choices=PostType.CHOICES, default=PostType.TEXT)
    text = TextField(default='', null=True, blank=True)
    youtube_link = TextField(null=True, blank=True)
    image = ImageField(upload_to='photos', max_length=254, null=True)
    creator = ForeignKey(UserProfile, on_delete=CASCADE, related_name='created_by')
    created_at = DateTimeField(auto_now_add=True, editable=False)
    is_active = BooleanField(default=True)

    objects = Manager()
    active = ActiveObjectManager()

    class Meta:
        verbose_name = 'Wall Post'
        ordering = ('-created_at',)

    def __str__(self):
        return str(self.id)

    def get_like(self, user_profile):
        is_liked_by_user = Like.objects.filter(creator=user_profile, user_id=user_profile.id, post=self.id).exists()
        count = Like.objects.filter(creator=user_profile, post=self.id).count()
        return {'liked_by_user': is_liked_by_user, 'count': count}
Ejemplo n.º 10
0
class Evaluation(Model):
    # Students, Classes, Teachers and Evaluations should never be deleted. Only marked as is_deleted.
    # We don't ever want to lose information about an evaluation, and what student/class/teacher it was related to.
    student = ForeignKey(Student, on_delete=PROTECT, related_name='evaluations')
    evaluated_class = ForeignKey(Class, on_delete=PROTECT)
    evaluation_text = TextField(default='', blank=True)
    hebrew_year = IntegerField()
    trimester = CharField(choices=TrimesterType.get_choices(), max_length=20)
    is_submitted = BooleanField(default=False)  # An evaluation that isn't submitted is considered a draft

    class Meta:
        unique_together = ['student', 'evaluated_class', 'trimester']

    def clean(self):
        if self.is_submitted and self.is_empty:
            raise ValidationError("Empty evaluation can not be submitted")

    @property
    def is_student_in_class(self):
        return self.student in self.evaluated_class.students.all()

    @property
    def is_empty(self):
        return not self.evaluation_text or self.evaluation_text.isspace()
Ejemplo n.º 11
0
class LandType(Model):
    """
    Table 1.1
    Has yaml
    """

    name = CharField(max_length=20, null=True, blank=True, verbose_name=_("Name"))
    statuses = ManyToManyField(
        "surveys20.LandStatus",
        blank=True,
        related_name="land_type",
        verbose_name=_("Land Statuses"),
    )
    unit = ForeignKey(
        "surveys20.Unit",
        related_name="land_type",
        null=True,
        on_delete=CASCADE,
        blank=True,
        verbose_name=_("Unit"),
    )
    has_land = BooleanField(default=True, verbose_name=_("Has Land"))
    update_time = DateTimeField(
        auto_now=True,
        auto_now_add=False,
        null=True,
        blank=True,
        verbose_name=_("Updated"),
    )

    class Meta:
        verbose_name = _("LandType")
        verbose_name_plural = _("LandType")

    def __str__(self):
        return self.name
Ejemplo n.º 12
0
    def download_csv(self, request, queryset):
        """
        Generates CSV report of all suppliers, with company details included.
        """
        response = HttpResponse(content_type='text/csv')
        response['Content-Disposition'] = (
            'attachment; filename="find-a-buyer_suppliers_{}.csv"'.format(
                datetime.datetime.now().strftime("%Y%m%d%H%M%S")))

        fieldnames = [
            field.name for field in Supplier._meta.get_fields()
            if field.name not in self.csv_excluded_fields
        ]
        fieldnames += [
            'company__' + field.name for field in Company._meta.get_fields()
            if 'company__' + field.name not in self.csv_excluded_fields
        ]
        fieldnames.append('company__has_case_study')
        fieldnames.append('company__number_of_case_studies')
        fieldnames = sorted(fieldnames)

        suppliers = queryset.select_related('company').all().annotate(
            company__has_case_study=Case(
                When(company__supplier_case_studies__isnull=False,
                     then=Value(True)),
                default=Value(False),
                output_field=BooleanField()),
            company__number_of_case_studies=Count(
                'company__supplier_case_studies')).values(*fieldnames)
        writer = csv.DictWriter(response, fieldnames=fieldnames)
        writer.writeheader()

        for supplier in suppliers:
            writer.writerow(supplier)

        return response
Ejemplo n.º 13
0
    def get_queryset(self):
        profile = self.request.user.user_profile

        school_filter = {}
        if profile.user_role == UserProfile.UserRoles.ADMINISTRATOR:
            user_roles = [
                UserProfile.UserRoles.ADMINISTRATOR,
                UserProfile.UserRoles.PRINCIPAL
            ]
        else:
            user_roles = [
                UserProfile.UserRoles.TEACHER, UserProfile.UserRoles.PARENT,
                UserProfile.UserRoles.STUDENT
            ]
            school_filter['school_unit'] = profile.school_unit_id

        return UserProfile.objects.select_related('user') \
            .prefetch_related('labels') \
            .filter(user_role__in=user_roles, user__is_staff=False, **school_filter) \
            .exclude(id=profile.id) \
            .annotate(is_inactive=Case(When(last_online__isnull=True, then=True),
                                       default=False,
                                       output_field=BooleanField())) \
            .order_by('-is_active', 'is_inactive', Lower('full_name'))
Ejemplo n.º 14
0
class likedStream(Model):
    user = ForeignKey(user_details, on_delete=CASCADE, verbose_name='user', null=True, blank=True , db_index=True)
    state = BooleanField(default=False)
    message = ForeignKey(MessageModel, on_delete=CASCADE, verbose_name='message', db_index=True)
    timestamp = DateTimeField('timestamp', auto_now_add=True, editable=False, db_index=True)
    
    def __str__(self):
        return str(self.message)


    def notify_ws_clients(self):
        """
        Inform client there is a message is liked.
        """
        notification = {
            'type': 'push_liked',
            'liked': self.state,
            'message': '{}'.format(self.message.id)
        }

        channel_layer = get_channel_layer()
        #print("user.id {}".format(self.message.user.username))
        #print("user.id {}".format(self.message.recipient.username))

        async_to_sync(channel_layer.group_send)("{}".format(self.message.user.username), notification)
        async_to_sync(channel_layer.group_send)("{}".format(self.message.recipient.username), notification)

    def save(self, *args, **kwargs):
        """
        Trims white spaces, saves the message and notifies the recipient via WS
        if the message is new.
        """
        new = self.id
        super(likedStream, self).save(*args, **kwargs)
        #if new is None: #send websoked even if message is disliked. 
        self.notify_ws_clients()
Ejemplo n.º 15
0
class UserChannel(Model):
    """
    This class represents a chat message. It has a owner (user), timestamp and
    the message body.

    """
    user = ForeignKey(get_user_model(), on_delete=CASCADE,
                      verbose_name='user', db_index=True)
    channel = CharField(max_length=150)
    room = CharField(max_length=150, null=True, blank=True)
    created = DateTimeField(auto_now_add=True,
                            editable=False,
                            db_index=True)
    last_seen = DateTimeField(auto_now=True)
    status = BooleanField(default=True)

    def change_status(self):
        self.status = not self.status
        self.save(update_fields=['status'])

        # Inform client there is a new message.
        notification = {
            'type': 'operator_status_changed',
            'user': self.user.pk,
            'status': self.status
        }
        channel_layer = get_channel_layer()
        async_to_sync(channel_layer.group_send)(self.room,
                                                notification)


    # Meta
    class Meta:
        verbose_name = 'Canale Utente'
        verbose_name_plural = 'Canali Utenti'
        ordering = ('-created',)
Ejemplo n.º 16
0
class Client(Resource):
    """
    使用此评测端的用户端。
    """
    # 编号
    id = BigAutoField(primary_key=True)
    # 绑定的用户(用于进行身份识别)
    user = OneToOneField(User, related_name='client')

    # 名称
    name = CharField(max_length=128)
    # 简介
    introduction = TextField()
    # 是否允许使用本端全部题库及题目
    allow_all = BooleanField(default=False)

    # 可用的题库数量
    number_category = IntegerField(default=0)
    # 可用的题目数量
    number_problem = IntegerField(default=0)

    # 允许此用户端使用的题库
    categories = ManyToManyField(Category, related_name='clients',
                                 through='ClientCategory', through_fields=('client', 'category'))
Ejemplo n.º 17
0
class JNF(Model):
    class Meta:
        permissions = [
            ('apply_jnf', 'Can apply for the job notified by jnf'),
            ('approve_jnf', 'Can approve jnf'),
        ]

    company = ForeignKey(Company,
                         on_delete=PROTECT,
                         related_name='jnf',
                         related_query_name='jnf')
    min_ctc = CharField("Minimum CTC offered (annual)",
                        null=True,
                        blank=True,
                        max_length=32)
    city = CharField("City(Cities) of Posting", max_length=40)
    designation = CharField(max_length=20)
    job_description = CharField(
        max_length=1000,
        null=True,
        blank=True,
    )
    skills_required = CharField(
        max_length=255,
        null=True,
        blank=True,
    )
    remarks = CharField(
        max_length=255,
        null=True,
        blank=True,
    )
    approved = BooleanField(null=False, default=False, blank=True)

    def get_absolute_url(self):
        return reverse("recruiters:jnf_detail", kwargs={'pk': self.pk})
Ejemplo n.º 18
0
def notes(request, category_id=None):
    context = {}
    categories = Category.objects.all()
    notes_qs = (Note.objects.filter(status=Note.STATUS_PUBLISHED).annotate(
        is_favorite=Case(
            When(favorites__user__id=request.user.id, then=Value(True)),
            default=Value(False),
            output_field=BooleanField(),
        )).values('slug', 'title', 'is_favorite'))

    if category_id:
        category = get_object_or_404(Category, id=category_id)
        notes_qs = notes_qs.filter(category=category)
        context['category_id'] = int(category_id)

    notes_list = list(notes_qs)
    notes_draft = DraftNote.objects.filter(user=request.user)
    context.update({
        'notes': json.dumps(notes_list),
        'notes_draft': notes_draft,
        'categories': categories,
    })

    return render(request, template_name='notes/notes.html', context=context)
Ejemplo n.º 19
0
class OverviewPage(TitleSlugDescriptionModel, UUIDModel):
    """
    An overview page shows up as a main item in the top navigation menu and
    allows linking together of other objects.
    """

    detail_page_markdown = TextField(blank=True)

    algorithms = ManyToManyField("algorithms.Algorithm", blank=True)
    archives = ManyToManyField("archives.Archive", blank=True)
    challenges = ManyToManyField("challenges.Challenge", blank=True)
    reader_studies = ManyToManyField("reader_studies.ReaderStudy", blank=True)

    published = BooleanField(default=False)

    class Meta(TitleSlugDescriptionModel.Meta, UUIDModel.Meta):
        ordering = ("-created", )
        indexes = (Index(fields=["published"]), )

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return reverse("overview-pages:detail", kwargs={"slug": self.slug})
Ejemplo n.º 20
0
class Project(models.Model):

    # Fields
    name = CharField(max_length=255)
    slug = AutoSlugField(populate_from='name', blank=True)
    created = DateTimeField(auto_now_add=True, editable=False)
    last_updated = DateTimeField(auto_now=True, editable=False)
    date_started = DateField()
    date_ended = DateField(null=True, blank=True)
    description = TextField(blank=True, null=True)
    url = CharField(max_length=255, null=True, blank=True)
    is_current = BooleanField()

    class Meta:
        ordering = ('-created', )

    def __unicode__(self):
        return u'%s' % self.slug

    def get_absolute_url(self):
        return reverse('resume_project_detail', args=(self.slug, ))

    def get_update_url(self):
        return reverse('resume_project_update', args=(self.slug, ))
Ejemplo n.º 21
0
class HLSPlaybackEnabledFlag(ConfigurationModel):
    """
    Enables HLS Playback across the platform.
    When this feature flag is set to true, individual courses
    must also have HLS Playback enabled for this feature to
    take effect.
    """
    # this field overrides course-specific settings
    enabled_for_all_courses = BooleanField(default=False)

    @classmethod
    def feature_enabled(cls, course_id):
        """
        Looks at the currently active configuration model to determine whether
        the HLS Playback feature is available.

        If the feature flag is not enabled, the feature is not available.
        If the flag is enabled for all the courses, feature is available.
        If the flag is enabled and the provided course_id is for an course
            with HLS Playback enabled, the feature is available.

        Arguments:
            course_id (CourseKey): course id for whom feature will be checked.
        """
        if not HLSPlaybackEnabledFlag.is_enabled():
            return False
        elif not HLSPlaybackEnabledFlag.current().enabled_for_all_courses:
            feature = (CourseHLSPlaybackEnabledFlag.objects.filter(
                course_id=course_id).order_by('-change_date').first())
            return feature.enabled if feature else False
        return True

    def __unicode__(self):
        current_model = HLSPlaybackEnabledFlag.current()
        return u"HLSPlaybackEnabledFlag: enabled {is_enabled}".format(
            is_enabled=current_model.is_enabled())
Ejemplo n.º 22
0
class Dog(Model):

    MALE = "m"
    FEMALE = "f"

    name        = CharField(max_length=256, null=False)
    sex         = CharField(max_length=1, choices=(
                                    (MALE, "Male"),
                                    (FEMALE, "Female")
                                ), null=False)
    age         = IntegerField(null=False)
    breed       = CharField(max_length=256, null=True)
    bio         = TextField(null=True)

    location    = ForeignKey(Location, on_delete=CASCADE, null=False)
    personality = ForeignKey(PersonalityQualities, on_delete=CASCADE, null=False)
    physical    = ForeignKey(PhysicalQualities, on_delete=CASCADE, null=False)
    
    has_shelter = BooleanField(default=False, null=False)
    owner       = ForeignKey(UserProfile, on_delete=CASCADE, null=True, blank=True)
    shelter     = ForeignKey(Shelter, on_delete=CASCADE, null=True, blank=True)

    def __str__(self):
        return 'Dog: {}, {}, {}, {}'.format(self.name, self.sex, self.age, self.breed)
Ejemplo n.º 23
0
class Client(Model):
    name = CharField(max_length=255, verbose_name="ScrapydClient")
    ip = CharField(max_length=255, verbose_name="ip地址")
    port = IntegerField(default=6800, verbose_name="端口")
    desc = TextField(blank=True, null=True, verbose_name="说明")
    auth = BooleanField(default=False, verbose_name="是否授权")
    # auth = IntegerField(default=0, blank=True, null=True, verbose_name="授权")
    username = CharField(max_length=255,
                         blank=True,
                         null=True,
                         verbose_name="用户名")
    password = CharField(max_length=255,
                         blank=True,
                         null=True,
                         verbose_name="密码")
    created_at = DateTimeField(auto_now_add=True, verbose_name="创建时间")
    updated_at = DateTimeField(auto_now=True, verbose_name="更新时间")

    class Meta:
        verbose_name = 'Scrapyd客户端'
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.name
Ejemplo n.º 24
0
class RelevancyBaseModel(Model, MessagesMixin):
    is_relevant = BooleanField(default=False)
    relevancy_exception = CharField(blank=True,
                                    max_length=255,
                                    verbose_name='exception')

    @property
    def may_be_relevant(self):
        return True

    @property
    def relevancy_warnings(self):
        return ''

    relevancy_warnings.fget.short_description = 'warnings'

    @property
    def relevancy_errors(self):
        return ''

    relevancy_errors.fget.short_description = 'errors'

    class Meta:
        abstract = True
Ejemplo n.º 25
0
 def board(self):
     Role = apps.get_model("user", "Role")
     return (
         super()
         .get_queryset()
         .annotate(
             role_name=Subquery(
                 Role.objects.filter(
                     user_id=OuterRef("id"), ends_at__isnull=True
                 ).values("division__name")[:1],
                 output_field=CharField(),
             ),
             role_is_head=Subquery(
                 Role.objects.filter(
                     user_id=OuterRef("id"),
                     ends_at__isnull=True,
                     division__name=OuterRef("role_name"),
                 ).values("is_head")[:1],
                 output_field=BooleanField(),
             ),
         )
         .filter(role_name__isnull=False)
         .order_by("name", "surname")
     )
Ejemplo n.º 26
0
def _build_filename_contains_raw_query(field, value):
    # It is not possible to use Django's ORM to query for if one item in a JSONB
    # list has has a key which contains a specified value.
    #
    # The closest thing the Django ORM provides is:
    #   queryset.filter(your_json_field__contains=[{"key":"value"}])
    # However this is an exact match, so in the above example [{"key":"value_etc"}]
    # would not match the filter.
    #
    # Instead we have to resort to RawSQL to use various built in PostgreSQL JSON
    # Array manipulation functions to be able to 'iterate' over a JSONB list
    # performing `like` on individual keys in said list.
    num_files_with_name_like_value = f"""
    EXISTS(
        SELECT attached_files ->> 'visible_name'
        FROM JSONB_ARRAY_ELEMENTS("field_{field.id}") as attached_files
        WHERE UPPER(attached_files ->> 'visible_name') LIKE UPPER(%s)
    )
"""
    return RawSQL(
        num_files_with_name_like_value,
        params=[f"%{value}%"],
        output_field=BooleanField(),
    )
Ejemplo n.º 27
0
    def _try_breadth_first(self, tasks):
        """Try to find tasks with maximum amount of annotations, since we are trying to label tasks as fast as possible
        """

        # =======
        # This commented part is trying to solve breadth-first in a bit different way:
        # it selects first task where any amount of annotations have been already created
        # we've left it here to be able to select it through the project settings later
        # =======
        # annotations = Annotation.objects.filter(task=OuterRef('pk'), ground_truth=False)
        # not_solved_tasks_labeling_started = tasks.annotate(labeling_started=Exists(annotations))
        # not_solved_tasks_labeling_started_true = not_solved_tasks_labeling_started.filter(labeling_started=True)
        # if not_solved_tasks_labeling_started_true.exists():
        #     # try to complete tasks that are already in progress
        #     next_task = self._get_random(not_solved_tasks_labeling_started_true)
        #     return next_task

        tasks = tasks.annotate(annotations_count=Count('annotations'))
        max_annotations_count = tasks.aggregate(
            Max('annotations_count'))['annotations_count__max']
        if max_annotations_count == 0:
            # there is no any labeled tasks found
            return

        # find any task with maximal amount of created annotations
        not_solved_tasks_labeling_started = tasks.annotate(
            reach_max_annotations_count=Case(When(
                annotations_count=max_annotations_count, then=Value(True)),
                                             default=Value(False),
                                             output_field=BooleanField()))
        not_solved_tasks_labeling_with_max_annotations = not_solved_tasks_labeling_started.filter(
            reach_max_annotations_count=True)
        if not_solved_tasks_labeling_with_max_annotations.exists():
            # try to complete tasks that are already in progress
            return self._get_random_unlocked(
                not_solved_tasks_labeling_with_max_annotations)
Ejemplo n.º 28
0
class GraphSession(models.Model):
    created = DateTimeField('created', default=timezone.now)

    listidx = IntegerField(default=0)
    title = CharField(max_length=200, default="", blank=True, null=True)
    description = TextField(blank=True, null=True)
    loglines = TextField(blank=True, null=True)
    logheader = TextField(blank=True, null=True)

    example = BooleanField(default=False)
    excomment = CharField(max_length=200, default="", blank=True, null=True)

    username = CharField(max_length=200)
    quicksaved = DateTimeField('quicksaved', blank=True, null=True)
    stashed = DateTimeField('stashed', blank=True, null=True)

    graphdef = TextField(blank=True)

    # stashed live data on top of quicksave
    stashed_pickle = TextField(blank=True)
    stashed_matfile = CharField(max_length=200, default="", blank=True)

    # restore point / quick save
    quicksave_pickle = TextField(blank=True)
    quicksave_matfile = CharField(max_length=200, default="", blank=True)

    def __str__(self):
        return 'session %s, idx %s, %s' % (self.id, self.listidx, self.title)

    def reset(self):
        self.stashed_pickle = "reset"
        self.quicksave_pickle = "reset"
        self.loglines = ""
        self.logheader = ""
        self.stashed_matfile = ""
        self.quicksave_matfile = ""
Ejemplo n.º 29
0
    def apply(self, tests):
        """
        Convert JSON logic to queryset info, returns an Q object and fills self.annotations
        """
        if not tests:
            return Q()
        if isinstance(tests, bool):
            # not really a legal configuration but used in the test suite
            return Value(tests, output_field=BooleanField())

        operator = list(tests.keys())[0]
        values = tests[operator]

        # Easy syntax for unary operators, like {"var": "x"} instead of strict
        # {"var": ["x"]}
        if not isinstance(values, list) and not isinstance(values, tuple):
            values = [values]

        if operator in self.bool_ops:
            return self.bool_ops[operator](*[self.apply(v) for v in values])
        elif operator in self.comparison_ops:
            return self.comparison_ops[operator](*values)
        else:
            raise ValueError(f'Invalid operator {operator} on first level')
Ejemplo n.º 30
0
class ConceptResource(Model):
    """
    Model to maintain concept specific resources
    NOTE: should use functions to obtain fields
    """
    # ConceptResource specific
    global_resource = ForeignKey(GlobalResource, related_name="cresources")
    id = CharField(max_length=16, primary_key=True)
    concept = ForeignKey(Concept, related_name="concept_resource")
    goals_covered = ManyToManyField(Goal,
                                    related_name="goals_covered",
                                    null=True,
                                    blank=True)
    core = BooleanField(default=False)
    additional_dependencies = CharField(max_length=300, null=True, blank=True)
    edition = CharField(max_length=100, null=True, blank=True)
    version_num = IntegerField(default=0, null=True, blank=True)
    ordering = IntegerField(default=-1)

    # concats GlobalResource field ?
    notes = CharField(max_length=500, null=True, blank=True)

    def editable_by(self, user):
        return self.concept.editable_by(user)