<commit_before>from flask import abort, flash, redirect, render_template, url_for
from flask.ext.login import login_required
from sqlalchemy.exc import IntegrityError
from wtforms.fields import SelectMultipleField, TextAreaField

from . import single_resource
from .. import db
from ..models import Descriptor, OptionAssociation, Resource, TextAssociation
from .forms import SingleResourceForm


@single_resource.route('/')
@login_required
def index():
    """View resources in a list."""
    resources = Resource.query.all()
    return render_template('single_resource/index.html', resources=resources)


@single_resource.route('/<query_name>')
@login_required
def search_resources(query_name):
    resources = Resource.query.filter(Resource.name.contains(query_name))
    return render_template(
        'single_resource/index.html', resources=resources, query=query_name)


@single_resource.route('/create', methods=['GET', 'POST'])
@login_required
def create():
    """Add a resource."""
    descriptors = Descriptor.query.all()
    for descriptor in descriptors:
        if descriptor.values:  # Fields for option descriptors.
            choices = [(str(i), v) for i, v in enumerate(descriptor.values)]
            setattr(
                SingleResourceForm,
                descriptor.name,
                SelectMultipleField(choices=choices))
        else:  # Fields for text descriptors
            setattr(SingleResourceForm, descriptor.name, TextAreaField())
    form = SingleResourceForm()
    if form.validate_on_submit():
        new_resource = Resource(
            name=form.name.data,
            address=form.address.data,
            latitude=form.latitude.data,
            longitude=form.longitude.data)
        db.session.add(new_resource)
        save_associations(
            resource=new_resource,
            form=form,
            descriptors=descriptors,
            resource_existed=False)
        try:
            db.session.commit()
            flash('Resource added', 'form-success')
            return redirect(url_for('single_resource.index'))
        except IntegrityError:
            db.session.rollback()
            flash('Error: failed to save resource. Please try again.',
                  'form-error')
    return render_template('single_resource/create.html', form=form)


@single_resource.route('/<int:resource_id>', methods=['GET', 'POST'])
@login_required
def edit(resource_id):
    """Edit a resource."""
    resource = Resource.query.get(resource_id)
    if resource is None:
        abort(404)
    resource_field_names = Resource.__table__.columns.keys()
    descriptors = Descriptor.query.all()
    for descriptor in descriptors:
        if descriptor.values:  # Fields for option descriptors.
            choices = [(str(i), v) for i, v in enumerate(descriptor.values)]
            default = None
            option_associations = OptionAssociation.query.filter_by(
                resource_id=resource_id, descriptor_id=descriptor.id).first()
            if option_associations is not None:
                default = [assoc.option for assoc in option_associations]
            setattr(
                SingleResourceForm,
                descriptor.name,
                SelectMultipleField(
                    choices=choices, default=default))
        else:  # Fields for text descriptors.<commit_msg>removed .first() from option_associations<commit_after>from flask import abort, flash, redirect, render_template, url_for
from flask.ext.login import login_required
from sqlalchemy.exc import IntegrityError
from wtforms.fields import SelectMultipleField, TextAreaField

from . import single_resource
from .. import db
from ..models import Descriptor, OptionAssociation, Resource, TextAssociation
from .forms import SingleResourceForm


@single_resource.route('/')
@login_required
def index():
    """View resources in a list."""
    resources = Resource.query.all()
    return render_template('single_resource/index.html', resources=resources)


@single_resource.route('/<query_name>')
@login_required
def search_resources(query_name):
    resources = Resource.query.filter(Resource.name.contains(query_name))
    return render_template(
        'single_resource/index.html', resources=resources, query=query_name)


@single_resource.route('/create', methods=['GET', 'POST'])
@login_required
def create():
    """Add a resource."""
    descriptors = Descriptor.query.all()
    for descriptor in descriptors:
        if descriptor.values:  # Fields for option descriptors.
            choices = [(str(i), v) for i, v in enumerate(descriptor.values)]
            setattr(
                SingleResourceForm,
                descriptor.name,
                SelectMultipleField(choices=choices))
        else:  # Fields for text descriptors
            setattr(SingleResourceForm, descriptor.name, TextAreaField())
    form = SingleResourceForm()
    if form.validate_on_submit():
        new_resource = Resource(
            name=form.name.data,
            address=form.address.data,
            latitude=form.latitude.data,
            longitude=form.longitude.data)
        db.session.add(new_resource)
        save_associations(
            resource=new_resource,
            form=form,
            descriptors=descriptors,
            resource_existed=False)
        try:
            db.session.commit()
            flash('Resource added', 'form-success')
            return redirect(url_for('single_resource.index'))
        except IntegrityError:
            db.session.rollback()
            flash('Error: failed to save resource. Please try again.',
                  'form-error')
    return render_template('single_resource/create.html', form=form)


@single_resource.route('/<int:resource_id>', methods=['GET', 'POST'])
@login_required
def edit(resource_id):
    """Edit a resource."""
    resource = Resource.query.get(resource_id)
    if resource is None:
        abort(404)
    resource_field_names = Resource.__table__.columns.keys()
    descriptors = Descriptor.query.all()
    for descriptor in descriptors:
        if descriptor.values:  # Fields for option descriptors.
            choices = [(str(i), v) for i, v in enumerate(descriptor.values)]
            default = None
            option_associations = OptionAssociation.query.filter_by(
                resource_id=resource_id, descriptor_id=descriptor.id)
            if option_associations is not None:
                default = [assoc.option for assoc in option_associations]
            setattr(
                SingleResourceForm,
                descriptor.name,
                SelectMultipleField(
                    choices=choices, default=default))
        else:  # Fields for text descriptors.
{'fraction_non_alphanumeric': 0.09762611275964392, 'fraction_numerical': 0.0008902077151335311, 'mean_word_length': 2.778587443946188, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 7, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3192989', 'n_tokens_mistral': 1782, 'n_tokens_neox': 1726, 'n_words': 418}