<commit_before>import cgi
from datetime import datetime

from pylons.i18n import _

from adhocracy.lib.base import *
import adhocracy.lib.text as text
import adhocracy.model.forms as forms
from adhocracy.lib.tiles.proposal_tiles import ProposalTile

log = logging.getLogger(__name__)

class ProposalCreateForm(formencode.Schema):
    allow_extra_fields = True
    label = validators.String(max=255, min=4, not_empty=True)
    text = validators.String(max=10000, min=4, not_empty=True)
    #issue = forms.ValidIssue()
    
class ProposalEditForm(formencode.Schema):
    allow_extra_fields = True
    label = validators.String(max=255, min=4, not_empty=True)
    issue = forms.ValidIssue(not_empty=True)

class ProposalDecisionsFilterForm(formencode.Schema):
    allow_extra_fields = True
    result = validators.Int(not_empty=False, if_empty=None, min=-1, max=1)


class ProposalController(BaseController):
    
    
    def _parse_relations(self, proposal=None):
        types_val = formencode.ForEach(validators.OneOf(['a', 'd', 'n'], not_empty=True), 
                                              convert_to_list=True)
        proposals_val = formencode.ForEach(forms.ValidProposal(if_empty=None, if_invalid=None), 
                                        convert_to_list=True)
        
        #print "REL_PROPOSALS", request.params.getall('rel_proposal')
        
        types = types_val.to_python(request.params.getall('rel_type'))
        proposals = proposals_val.to_python(request.params.getall('rel_proposal'))
        if len(types) != len(proposals):
            raise formencode.Invalid("", type, None,
                        error_dict={'rel_error': _("Input error while applying relations.")})
        
        #print "PROPOSALS ", proposals
        
        c.relations = dict()
        for type, other in zip(types, proposals):
            if not other:
                continue
            if (proposal and other == proposal) and type in ['a', 'd']:
                raise formencode.Invalid("", type, None,
                        error_dict={
                        'rel_error': _("A proposal cannot have a relation with itself.")})
            if other in c.relations.keys() and c.relations[other] != type:
                raise formencode.Invalid("", type, None,
                        error_dict={
                        'rel_error': _("A proposal can either contradict " + 
                                       "or require another, not both.")})
            c.relations[other] = type
    
    @RequireInstance
    @RequireInternalRequest(methods=['POST'])
    @ActionProtector(has_permission("proposal.create"))
    #@validate(schema=ProposalCreateForm(), form="create", post_only=True)
    def create(self):
        try:
            c.issue = forms.ValidIssue(not_empty=True).to_python(request.params.get('issue'))
        except formencode.Invalid:
            h.flash(_("Cannot identify the parent issue."))
            redirect_to("/")
        c.canonicals = ["", ""]
        c.relations = dict(map(lambda m: (m, 'a'), c.issue.proposals))
        c.proposals = model.Proposal.all(instance=c.instance)
        
        if request.method == "POST":
            try:
                # if the remaining validation fails, we'll still want this to execute
                canonicals_val = formencode.ForEach(validators.String(), 
                                                    convert_to_list=True)
                c.canonicals = filter(lambda p: p != None and len(p), 
                                      canonicals_val.to_python(request.params.getall('canonicals')))
                
                self._parse_relations()
                form_result = ProposalCreateForm().to_python(request.params)
                proposal = model.Proposal(c.instance, 
                                      form_result.get("label"),
                                      c.user)
                proposal.issue = c.issue
                comment = model.Comment(proposal, c.user)
                rev = model.Revision(comment, c.user, 
                                     text.cleanup(form_result.get("text")))
                comment.latest = rev
                model.meta.Session.add(proposal)
                model.meta.Session.add(comment)
                model.meta.Session.add(rev)
                
                for c_text in c.canonicals:
                    canonical = model.Comment(proposal, c.user)
                    canonical.canonical = True
                    c_rev = model.Revision(canonical, c.user, 
                                           text.cleanup(c_text))
                    canonical.latest = c_rev
                    model.meta.Session.add(canonical)
                    model.meta.Session.add(c_rev)
                    
                for r_proposal, type in c.relations.items():
                    if type=='a':
                        alternative = model.Alternative(proposal, r_proposal)
                        model.meta.Session.add(alternative)
                    elif type=='d':
                        dependency = model.Dependency(proposal, r_proposal)
                        model.meta.Session.add(dependency)
                
                model.meta.Session.commit()
                proposal.comment = comment
                model.meta.Session.add(proposal)
                model.meta.Session.commit()
                <commit_msg>[svn r580] trial and error debugging<commit_after>import cgi
from datetime import datetime

from pylons.i18n import _

from adhocracy.lib.base import *
import adhocracy.lib.text as text
import adhocracy.model.forms as forms
from adhocracy.lib.tiles.proposal_tiles import ProposalTile

log = logging.getLogger(__name__)

class ProposalCreateForm(formencode.Schema):
    allow_extra_fields = True
    label = validators.String(max=255, min=4, not_empty=True)
    text = validators.String(max=10000, min=4, not_empty=True)
    #issue = forms.ValidIssue()
    
class ProposalEditForm(formencode.Schema):
    allow_extra_fields = True
    label = validators.String(max=255, min=4, not_empty=True)
    issue = forms.ValidIssue(not_empty=True)

class ProposalDecisionsFilterForm(formencode.Schema):
    allow_extra_fields = True
    result = validators.Int(not_empty=False, if_empty=None, min=-1, max=1)


class ProposalController(BaseController):
    
    
    def _parse_relations(self, proposal=None):
        types_val = formencode.ForEach(validators.OneOf(['a', 'd', 'n'], not_empty=True), 
                                              convert_to_list=True)
        proposals_val = formencode.ForEach(forms.ValidProposal(if_empty=None, if_invalid=None), 
                                        convert_to_list=True)
        
        #print "REL_PROPOSALS", request.params.getall('rel_proposal')
        
        types = types_val.to_python(request.params.getall('rel_type'))
        proposals = proposals_val.to_python(request.params.getall('rel_proposal'))
        if len(types) != len(proposals):
            raise formencode.Invalid("", type, None,
                        error_dict={'rel_error': _("Input error while applying relations.")})
        
        #print "PROPOSALS ", proposals
        
        c.relations = dict()
        for type, other in zip(types, proposals):
            if not other:
                continue
            if (proposal and other == proposal) and type in ['a', 'd']:
                raise formencode.Invalid("", type, None,
                        error_dict={
                        'rel_error': _("A proposal cannot have a relation with itself.")})
            if other in c.relations.keys() and c.relations[other] != type:
                raise formencode.Invalid("", type, None,
                        error_dict={
                        'rel_error': _("A proposal can either contradict " + 
                                       "or require another, not both.")})
            c.relations[other] = type
    
    @RequireInstance
    @RequireInternalRequest(methods=['POST'])
    @ActionProtector(has_permission("proposal.create"))
    #@validate(schema=ProposalCreateForm(), form="create", post_only=True)
    def create(self):
        try:
            c.issue = forms.ValidIssue(not_empty=True).to_python(request.params.get('issue'))
        except formencode.Invalid:
            h.flash(_("Cannot identify the parent issue."))
            redirect_to("/")
        c.canonicals = ["", ""]
        c.relations = dict(map(lambda m: (m, 'a'), c.issue.proposals))
        c.proposals = model.Proposal.all(instance=c.instance)
        
        if request.method == "POST":
            try:
                # if the remaining validation fails, we'll still want this to execute
                canonicals_val = formencode.ForEach(validators.String(), 
                                                    convert_to_list=True)
                c.canonicals = filter(lambda p: p != None and len(p), 
                                      canonicals_val.to_python(request.params.getall('canonicals')))
                
                self._parse_relations()
                form_result = ProposalCreateForm().to_python(request.params)
                proposal = model.Proposal(c.instance, 
                                      form_result.get("label"),
                                      c.user)
                proposal.issue = c.issue
                comment = model.Comment(proposal, c.user)
                rev = model.Revision(comment, c.user, 
                                     text.cleanup(form_result.get("text")))
                comment.latest = rev
                model.meta.Session.add(proposal)
                model.meta.Session.add(comment)
                model.meta.Session.add(rev)
                model.meta.Session.flush()
                
                for c_text in c.canonicals:
                    canonical = model.Comment(proposal, c.user)
                    canonical.canonical = True
                    c_rev = model.Revision(canonical, c.user, 
                                           text.cleanup(c_text))
                    canonical.latest = c_rev
                    model.meta.Session.add(canonical)
                    model.meta.Session.add(c_rev)
                    
                for r_proposal, type in c.relations.items():
                    if type=='a':
                        alternative = model.Alternative(proposal, r_proposal)
                        model.meta.Session.add(alternative)
                    elif type=='d':
                        dependency = model.Dependency(proposal, r_proposal)
                        model.meta.Session.add(dependency)
                
                model.meta.Session.commit()
                proposal.comment = comment
                model.meta.Session.add(proposal)
                model.meta.Session.commit()
                
{'fraction_non_alphanumeric': 0.10058791107844939, 'fraction_numerical': 0.003582583134300937, 'mean_word_length': 1.7001488095238095, 'pattern_counts': {'":': 2, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 26, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4419182', 'n_tokens_mistral': 2955, 'n_tokens_neox': 2774, 'n_words': 552}