<commit_before>import threading
import json
from datetime import timedelta, datetime

from django.core.exceptions import ValidationError
from django.db import models, transaction
from django.db.models import SET_NULL
from django.utils.timezone import now as django_now
from django.utils.translation import ugettext_lazy
from django.db.models.deletion import PROTECT

# import a definition from a module at runtime
from django_workflow.utils import import_from, import_from_path


class WorkflowManager(models.Manager):
    def get_by_natural_key(self, name):
        return self.get(name=name)


class Workflow(models.Model):
    objects = WorkflowManager()

    name = models.CharField(max_length=50, unique=True, verbose_name=ugettext_lazy("Name"))
    object_type = models.CharField(max_length=200, verbose_name=ugettext_lazy("Object_Type"))
    initial_prefetch = models.CharField(max_length=4000, null=True, blank=True, verbose_name=ugettext_lazy("Object_Type"))

    @property
    def initial_prefetch_dict(self):
        dict = json.loads(self.initial_prefetch) if self.initial_prefetch else None
        for k,v in dict.items():
            if "today" in v:
                sum_operands = [x.strip() for x in v.split("+")]
                res = None
                for sum_op in sum_operands:
                    sub_operands = [x.strip() for x in sum_op.split("-")]
                    sub_res = None
                    for sub_op in sub_operands:
                        mul_operands = [x.strip() for x in sub_op.split("*")]
                        mul_res = None
                        for mul_op in mul_operands:
                            div_res = None
                            div_operands = [x.strip() for x in mul_op.split("/")]
                            for op in div_operands:
                                if div_res is None:
                                    div_res = datetime.now().date() if op == "today" else float(op)
                                else:
                                    div_res = div_res / float(op) #you cannot divide by today
                            if mul_res is None:
                                mul_res = div_res
                            else:
                                mul_res = mul_res * div_res
                        # perform multiplications and divisions in float, then convert to timedelta for the rest
                        if isinstance(mul_res, float):
                            mul_res = timedelta(seconds=mul_res)
                        if sub_res is None:
                            sub_res = mul_res
                        else:
                            sub_res = sub_res - mul_res
                    if res is None:
                        res = sub_res
                    else:
                        res = res + sub_res
                res = res.strftime("%Y-%m-%dT%H:%M:%SZ")
                dict.update({k:res})
        return dict



    @property
    def initial_state(self):
        return State.objects.get(workflow=self, initial=True)

    @property
    def initial_transition(self):
        return Transition.objects.filter(workflow=self, initial_state=None, final_state=self.initial_state).first()

    def prefetch_initial_objects(self):
        objects = self\
            .object_class().objects.filter(**self.initial_prefetch_dict)\
            .exclude(id__in=CurrentObjectState.objects.filter(workflow=self).values_list("object_id", flat=True)) if self.initial_prefetch else []
        return objects

    def __unicode__(self):
        return self.name

    def is_initial_transition_available(self, user, object_id, object_state_id=None, automatic=False):
        if object_state_id:
            return not CurrentObjectState.objects.filter(id=object_state_id, workflow=self).exists()
        else:
            last = CurrentObjectState.objects.filter(object_id=object_id, workflow=self).order_by('-id').first()
            if last and last.state.active:
                return False
            else:
                conditions = self.initial_transition.condition_set.all()
                if len(conditions) == 0:
                    if automatic:
                        return self.initial_transition.automatic
                    else:
                        return not self.initial_transition.automatic
                else:
                    root_condition = conditions.first()
                    if root_condition.check_condition(user, object_id):
                        if automatic:
                            return self.initial_transition.automatic
                        else:
                            return not self.initial_transition.automatic
                    else:
                        return False

    def natural_key(self):
        return (self.name,)

    def add_object(self, object_id, async=True):
        process = CurrentObjectState.objects.create(object_id=object_id, state=self.initial_state)
        _execute_atomatic_transitions(self.initial_state, object_id, process, async=async)
        return process

    def object_class(self):
        return import_from_path(self.object_type)

    def transition_by_name(self, name):
        transition = Transition.objects.filter(workflow=self, name__iexact=name)
        if len(transition) > 0:
            return transition.first()
        return None


class StateManager(models.Manager):
    def get_by_natural_key(self, name, workflow):
        return self.get(name=name, workflow__name=workflow)


class State(models.Model):
    objects = StateManager()

    workflow = models.ForeignKey(Workflow, on_delete=PROTECT, verbose_name=ugettext_lazy("Workflow"))
    name = models.CharField(max_length=200, verbose_name=ugettext_lazy("Name"))
    active = models.BooleanField(verbose_name=ugettext_lazy("Active"))<commit_msg>bugfix<commit_after>import threading
import json
from datetime import timedelta, datetime

from django.core.exceptions import ValidationError
from django.db import models, transaction
from django.db.models import SET_NULL
from django.utils.timezone import now as django_now
from django.utils.translation import ugettext_lazy
from django.db.models.deletion import PROTECT

# import a definition from a module at runtime
from django_workflow.utils import import_from, import_from_path


class WorkflowManager(models.Manager):
    def get_by_natural_key(self, name):
        return self.get(name=name)


class Workflow(models.Model):
    objects = WorkflowManager()

    name = models.CharField(max_length=50, unique=True, verbose_name=ugettext_lazy("Name"))
    object_type = models.CharField(max_length=200, verbose_name=ugettext_lazy("Object_Type"))
    initial_prefetch = models.CharField(max_length=4000, null=True, blank=True, verbose_name=ugettext_lazy("Object_Type"))

    @property
    def initial_prefetch_dict(self):
        dict = json.loads(self.initial_prefetch) if self.initial_prefetch else None
        for k,v in dict.items():
            if "today" in v:
                sum_operands = [x.strip() for x in v.split("+")]
                res = None
                for sum_op in sum_operands:
                    sub_operands = [x.strip() for x in sum_op.split("-")]
                    sub_res = None
                    for sub_op in sub_operands:
                        mul_operands = [x.strip() for x in sub_op.split("*")]
                        mul_res = None
                        for mul_op in mul_operands:
                            div_res = None
                            div_operands = [x.strip() for x in mul_op.split("/")]
                            for op in div_operands:
                                if div_res is None:
                                    div_res = datetime.now().date() if op == "today" else float(op)
                                else:
                                    div_res = div_res / float(op) #you cannot divide by today
                            if mul_res is None:
                                mul_res = div_res
                            else:
                                mul_res = mul_res * div_res
                        # perform multiplications and divisions in float, then convert to timedelta for the rest
                        if isinstance(mul_res, float):
                            mul_res = timedelta(seconds=mul_res)
                        if sub_res is None:
                            sub_res = mul_res
                        else:
                            sub_res = sub_res - mul_res
                    if res is None:
                        res = sub_res
                    else:
                        res = res + sub_res
                res = res.strftime("%Y-%m-%dT%H:%M:%SZ")
                dict.update({k:res})
        return dict



    @property
    def initial_state(self):
        return State.objects.get(workflow=self, initial=True)

    @property
    def initial_transition(self):
        return Transition.objects.filter(workflow=self, initial_state=None, final_state=self.initial_state).first()

    def prefetch_initial_objects(self):
        objects = self\
            .object_class().objects.filter(**self.initial_prefetch_dict)\
            .exclude(id__in=CurrentObjectState.objects.filter(workflow=self).values_list("object_id", flat=True)) if self.initial_prefetch else []
        return objects

    def __unicode__(self):
        return self.name

    def is_initial_transition_available(self, user, object_id, object_state_id=None, automatic=False):
        if object_state_id:
            return not CurrentObjectState.objects.filter(id=object_state_id, workflow=self).exists()
        else:
            last = CurrentObjectState.objects.filter(object_id=object_id, workflow=self).order_by('-id').first()
            if last and last.state.active:
                return False
            elif self.initial_transition is not None:
                conditions = self.initial_transition.condition_set.all()
                if len(conditions) == 0:
                    if automatic:
                        return self.initial_transition.automatic
                    else:
                        return not self.initial_transition.automatic
                else:
                    root_condition = conditions.first()
                    if root_condition.check_condition(user, object_id):
                        if automatic:
                            return self.initial_transition.automatic
                        else:
                            return not self.initial_transition.automatic
                    else:
                        return False
            else:
                return False

    def natural_key(self):
        return (self.name,)

    def add_object(self, object_id, async=True):
        process = CurrentObjectState.objects.create(object_id=object_id, state=self.initial_state)
        _execute_atomatic_transitions(self.initial_state, object_id, process, async=async)
        return process

    def object_class(self):
        return import_from_path(self.object_type)

    def transition_by_name(self, name):
        transition = Transition.objects.filter(workflow=self, name__iexact=name)
        if len(transition) > 0:
            return transition.first()
        return None


class StateManager(models.Manager):
    def get_by_natural_key(self, name, workflow):
        return self.get(name=name, workflow__name=workflow)


class State(models.Model):
    objects = StateManager()

    workflow = models.ForeignKey(Workflow, on_delete=PROTECT, verbose_name=ugettext_lazy("Workflow"))
    name = models.CharField(max_length=200, verbose_name=ugettext_lazy("Name"))
    active = models.BooleanField(verbose_name=ugettext_lazy("Active"))
{'fraction_non_alphanumeric': 0.08006119326874044, 'fraction_numerical': 0.0023797382287948326, 'mean_word_length': 1.8876073619631901, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 6, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '207428', 'n_tokens_mistral': 3203, 'n_tokens_neox': 3013, 'n_words': 704}