<commit_before># -*- coding: iso8859-1 -*-
#
# Copyright (C) 2004, 2005 Edgewall Software
# Copyright (C) 2004, 2005 <NAME> <<EMAIL>>
#
# Trac is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# Trac is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
#
# Author: <NAME> <<EMAIL>>

from trac import perm
from trac.Module import Module
from trac.Ticket import get_custom_fields, Ticket
from trac.WikiFormatter import wiki_to_html
from trac.util import *

import time


def get_tickets_for_milestone(env, db, milestone, field='component'):
    custom = field not in Ticket.std_fields
    cursor = db.cursor()
    sql = "SELECT ticket.id AS id, ticket.status AS status, "
    if custom:
        sql += "ticket_custom.value AS %s " \
               "FROM ticket LEFT OUTER JOIN ticket_custom ON id=ticket " \
               "WHERE name='%s' AND milestone='%s'" % (
               sql_escape(field), sql_escape(field), sql_escape(milestone))
    else:
        sql += "ticket.%s AS %s FROM ticket WHERE milestone='%s'" % (
               field, field, sql_escape(milestone))
    sql += " ORDER BY %s" % field

    cursor.execute(sql)
    tickets = []
    while 1:
        row = cursor.fetchone()
        if not row:
            break
        ticket = {
            'id': int(row['id']),
            'status': row['status'],
            field: row[field]
        }
        tickets.append(ticket)
    return tickets


def get_query_links(env, milestone, grouped_by='component', group=None):
    queries = {}
    if not group:
        queries['all_tickets'] = env.href.query({'milestone': milestone})
        queries['active_tickets'] = env.href.query({
            'milestone': milestone, 'status': ['new', 'assigned', 'reopened']
        })
        queries['closed_tickets'] = env.href.query({
            'milestone': milestone, 'status': 'closed'
        })
    else:
        queries['all_tickets'] = env.href.query({
            'milestone': milestone, grouped_by: group
        })
        queries['active_tickets'] = env.href.query({
            'milestone': milestone, grouped_by: group,
            'status': ['new', 'assigned', 'reopened']
        })
        queries['closed_tickets'] = env.href.query({
            'milestone': milestone, grouped_by: group,
            'status': 'closed'
        })
    return queries


def calc_ticket_stats(tickets):
    total_cnt = len(tickets)
    active = [ticket for ticket in tickets if ticket['status'] != 'closed']
    active_cnt = len(active)
    closed_cnt = total_cnt - active_cnt

    percent_active, percent_closed = 0, 0
    if total_cnt > 0:
        percent_active = round(float(active_cnt) / float(total_cnt) * 100)
        percent_closed = round(float(closed_cnt) / float(total_cnt) * 100)
        if percent_active + percent_closed > 100:
            percent_closed -= 1

    return {
        'total_tickets': total_cnt,
        'active_tickets': active_cnt,
        'percent_active': percent_active,
        'closed_tickets': closed_cnt,
        'percent_closed': percent_closed
    }


class Milestone(Module):
    template_name = 'milestone.cs'

    def save_milestone(self, req, id):
        self.perm.assert_permission(perm.MILESTONE_MODIFY)
        if req.args.has_key('save'):
            name = req.args.get('name', '')
            if not name:
                raise TracError('You must provide a name for the milestone.',
                                'Required Field Missing')
            due = 0
            due_str = req.args.get('duedate', '')
            if due_str:
                due = self.parse_date(due_str)
            completed = 0
            if req.args.has_key('completed'):
                completed_str = req.args.get('completeddate', '')
                if completed_str:
                    completed = self.parse_date(completed_str)
            description = req.args.get('description', '')
            if not id:
                self.create_milestone(req, name, due, completed, description)
            else:
                self.update_milestone(req, id, name, due, completed, description)
        elif id:
            req.redirect(self.env.href.milestone(id))
        else:
            req.redirect(self.env.href.roadmap())

    def parse_date(self, datestr):
        seconds = None
        datestr = datestr.strip()
        for format in ['%x %X', '%x, %X', '%X %x', '%X, %x', '%x', '%c',
                       '%b %d, %Y']:
            try:
                date = time.strptime(datestr, format)
                seconds = time.mktime(date)
                break
            except ValueError:
                continue
        if seconds == None:
            raise TracError('%s is not a known date format.' % datestr,
                            'Invalid Date Format')
        return seconds

    def create_milestone(self, req, name, due=0, completed=0, description=''):
        self.perm.assert_permission(perm.MILESTONE_CREATE)
        if not name:
            raise TracError('You must provide a name for the milestone.',
                            'Required Field Missing')
        cursor = self.db.cursor()
        self.log.debug("Creating new milestone '%s'" % name)
        cursor.execute("INSERT INTO milestone (name,due,completed,description) "
                       "VALUES (%s,%s,%s,%s)",
                       (name, due, completed, description)
        self.db.commit()
        req.redirect(self.env.href.milestone(name))

    def delete_milestone(self, req, id):
        self.perm.assert_permission(perm.MILESTONE_DELETE)
        self.get_milestone(req, id) # check whether the milestone exists
        if req.args.has_key('delete'):
            cursor = self.db.cursor()
            if req.args.has_key('retarget'):
                target = req.args.get('target')
                if target:
                    self.log.info('Retargeting milestone field of all '
                                  'tickets associated with milestone %s to '
                                  'milestone %s' % (id, target))
                    cursor.execute("UPDATE ticket SET milestone=%s "
                                   "WHERE milestone=%s", (target, id))
                else:
                    self.log.info('Resetting milestone field of all '
                                  'tickets associated with milestone %s' % id)
                    cursor.execute("UPDATE ticket SET milestone=NULL "
                                   "WHERE milestone=%s", (id,))
            self.log.info('Deleting milestone %s' % id)<commit_msg>Fix syntax error introduced in [1324].<commit_after># -*- coding: iso8859-1 -*-
#
# Copyright (C) 2004, 2005 Edgewall Software
# Copyright (C) 2004, 2005 <NAME> <<EMAIL>>
#
# Trac is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# Trac is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
#
# Author: <NAME> <<EMAIL>>

from trac import perm
from trac.Module import Module
from trac.Ticket import get_custom_fields, Ticket
from trac.WikiFormatter import wiki_to_html
from trac.util import *

import time


def get_tickets_for_milestone(env, db, milestone, field='component'):
    custom = field not in Ticket.std_fields
    cursor = db.cursor()
    sql = "SELECT ticket.id AS id, ticket.status AS status, "
    if custom:
        sql += "ticket_custom.value AS %s " \
               "FROM ticket LEFT OUTER JOIN ticket_custom ON id=ticket " \
               "WHERE name='%s' AND milestone='%s'" % (
               sql_escape(field), sql_escape(field), sql_escape(milestone))
    else:
        sql += "ticket.%s AS %s FROM ticket WHERE milestone='%s'" % (
               field, field, sql_escape(milestone))
    sql += " ORDER BY %s" % field

    cursor.execute(sql)
    tickets = []
    while 1:
        row = cursor.fetchone()
        if not row:
            break
        ticket = {
            'id': int(row['id']),
            'status': row['status'],
            field: row[field]
        }
        tickets.append(ticket)
    return tickets


def get_query_links(env, milestone, grouped_by='component', group=None):
    queries = {}
    if not group:
        queries['all_tickets'] = env.href.query({'milestone': milestone})
        queries['active_tickets'] = env.href.query({
            'milestone': milestone, 'status': ['new', 'assigned', 'reopened']
        })
        queries['closed_tickets'] = env.href.query({
            'milestone': milestone, 'status': 'closed'
        })
    else:
        queries['all_tickets'] = env.href.query({
            'milestone': milestone, grouped_by: group
        })
        queries['active_tickets'] = env.href.query({
            'milestone': milestone, grouped_by: group,
            'status': ['new', 'assigned', 'reopened']
        })
        queries['closed_tickets'] = env.href.query({
            'milestone': milestone, grouped_by: group,
            'status': 'closed'
        })
    return queries


def calc_ticket_stats(tickets):
    total_cnt = len(tickets)
    active = [ticket for ticket in tickets if ticket['status'] != 'closed']
    active_cnt = len(active)
    closed_cnt = total_cnt - active_cnt

    percent_active, percent_closed = 0, 0
    if total_cnt > 0:
        percent_active = round(float(active_cnt) / float(total_cnt) * 100)
        percent_closed = round(float(closed_cnt) / float(total_cnt) * 100)
        if percent_active + percent_closed > 100:
            percent_closed -= 1

    return {
        'total_tickets': total_cnt,
        'active_tickets': active_cnt,
        'percent_active': percent_active,
        'closed_tickets': closed_cnt,
        'percent_closed': percent_closed
    }


class Milestone(Module):
    template_name = 'milestone.cs'

    def save_milestone(self, req, id):
        self.perm.assert_permission(perm.MILESTONE_MODIFY)
        if req.args.has_key('save'):
            name = req.args.get('name', '')
            if not name:
                raise TracError('You must provide a name for the milestone.',
                                'Required Field Missing')
            due = 0
            due_str = req.args.get('duedate', '')
            if due_str:
                due = self.parse_date(due_str)
            completed = 0
            if req.args.has_key('completed'):
                completed_str = req.args.get('completeddate', '')
                if completed_str:
                    completed = self.parse_date(completed_str)
            description = req.args.get('description', '')
            if not id:
                self.create_milestone(req, name, due, completed, description)
            else:
                self.update_milestone(req, id, name, due, completed, description)
        elif id:
            req.redirect(self.env.href.milestone(id))
        else:
            req.redirect(self.env.href.roadmap())

    def parse_date(self, datestr):
        seconds = None
        datestr = datestr.strip()
        for format in ['%x %X', '%x, %X', '%X %x', '%X, %x', '%x', '%c',
                       '%b %d, %Y']:
            try:
                date = time.strptime(datestr, format)
                seconds = time.mktime(date)
                break
            except ValueError:
                continue
        if seconds == None:
            raise TracError('%s is not a known date format.' % datestr,
                            'Invalid Date Format')
        return seconds

    def create_milestone(self, req, name, due=0, completed=0, description=''):
        self.perm.assert_permission(perm.MILESTONE_CREATE)
        if not name:
            raise TracError('You must provide a name for the milestone.',
                            'Required Field Missing')
        cursor = self.db.cursor()
        self.log.debug("Creating new milestone '%s'" % name)
        cursor.execute("INSERT INTO milestone (name,due,completed,description) "
                       "VALUES (%s,%s,%s,%s)",
                       (name, due, completed, description))
        self.db.commit()
        req.redirect(self.env.href.milestone(name))

    def delete_milestone(self, req, id):
        self.perm.assert_permission(perm.MILESTONE_DELETE)
        self.get_milestone(req, id) # check whether the milestone exists
        if req.args.has_key('delete'):
            cursor = self.db.cursor()
            if req.args.has_key('retarget'):
                target = req.args.get('target')
                if target:
                    self.log.info('Retargeting milestone field of all '
                                  'tickets associated with milestone %s to '
                                  'milestone %s' % (id, target))
                    cursor.execute("UPDATE ticket SET milestone=%s "
                                   "WHERE milestone=%s", (target, id))
                else:
                    self.log.info('Resetting milestone field of all '
                                  'tickets associated with milestone %s' % id)
                    cursor.execute("UPDATE ticket SET milestone=NULL "
                                   "WHERE milestone=%s", (id,))
            self.log.info('Deleting milestone %s' % id)
{'fraction_non_alphanumeric': 0.11250528690258, 'fraction_numerical': 0.007049203440011279, 'mean_word_length': 2.0372511239563265, 'pattern_counts': {'":': 0, '<': 15, '<?xml version=': 0, '>': 19, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 10, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2594925', 'n_tokens_mistral': 4125, 'n_tokens_neox': 3871, 'n_words': 1120}