<commit_before>from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division

import string

import urllib
import json
import locale
import hashlib
from PIL import Image

from django.core.exceptions import ValidationError
from django.core.urlresolvers import reverse
from django.shortcuts import get_object_or_404
from django.http import (HttpResponse, HttpResponseRedirect,
                         HttpResponseForbidden, Http404)
from django.views.decorators.http import etag
from django.conf import settings
from django.contrib.gis.geos.point import Point
from django.utils.translation import ugettext as trans
from django.db import transaction
from django.db.models import Q

from treemap.util import (json_api_call, render_template, instance_request,
                          require_http_method)
from treemap.search import create_filter
from treemap.audit import Audit
from treemap.models import (Plot, Tree, User, Species, Instance,
                            BenefitCurrencyConversion)

from ecobenefits.models import ITreeRegion
from ecobenefits.views import _benefits_for_trees

from opentreemap.util import json_from_request


def _plot_hash(request, instance, plot_id):
    instance_plots = instance.scope_model(Plot)
    return get_object_or_404(instance_plots, pk=plot_id).hash


def _search_hash(request, instance):
    audits = instance.scope_model(Audit)\
                     .order_by('-updated')

    try:
        audit_id_str = str(audits[0].pk)
    except IndexError:
        audit_id_str = 'none'

    eco_conversion = instance.eco_benefits_conversion

    if eco_conversion:
        eco_str = eco_conversion.hash
    else:
        eco_str = 'none'

    string_to_hash = audit_id_str + ":" + eco_str

    return hashlib.md5(string_to_hash).hexdigest()


def add_tree_photo(request, instance, plot_id, tree_id=None):
    plot = get_object_or_404(Plot, pk=plot_id, instance=instance)
    tree_ids = [t.pk for t in plot.tree_set.all()]

    if int(tree_id) in tree_ids:
        tree = Tree.objects.get(pk=tree_id)
    elif tree_id is None:
        # See if a tree already exists on this plot
        tree = plot.current_tree()

        if tree is None:
            # A tree doesn't exist, create a new tree create a
            # new tree, and attach it to this plot
            tree = Tree(plot=plot, instance=instance)

            # TODO: it is possible that a user has the ability to
            # 'create tree photos' but not trees. In this case we
            # raise an authorization exception here.
            # It is, however, possible to have both a pending
            # tree and a pending tree photo
            # This will be added later, when auth/admin work
            # correctly with this system
            tree.save_with_user(request.user)

    else:
        # Tree id is invalid or not in this plot
        raise Http404('Tree id %s not found on plot %s' % (tree_id, plot_id))

    #TODO: Validation Error
    #TODO: Auth Error
    if 'file' in request.FILES:
        #TODO: Check size before reading
        data = request.FILES['file'].file
    else:<commit_msg>Guard against null tree_ids<commit_after>from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division

import string

import urllib
import json
import locale
import hashlib
from PIL import Image

from django.core.exceptions import ValidationError
from django.core.urlresolvers import reverse
from django.shortcuts import get_object_or_404
from django.http import (HttpResponse, HttpResponseRedirect,
                         HttpResponseForbidden, Http404)
from django.views.decorators.http import etag
from django.conf import settings
from django.contrib.gis.geos.point import Point
from django.utils.translation import ugettext as trans
from django.db import transaction
from django.db.models import Q

from treemap.util import (json_api_call, render_template, instance_request,
                          require_http_method)
from treemap.search import create_filter
from treemap.audit import Audit
from treemap.models import (Plot, Tree, User, Species, Instance,
                            BenefitCurrencyConversion)

from ecobenefits.models import ITreeRegion
from ecobenefits.views import _benefits_for_trees

from opentreemap.util import json_from_request


def _plot_hash(request, instance, plot_id):
    instance_plots = instance.scope_model(Plot)
    return get_object_or_404(instance_plots, pk=plot_id).hash


def _search_hash(request, instance):
    audits = instance.scope_model(Audit)\
                     .order_by('-updated')

    try:
        audit_id_str = str(audits[0].pk)
    except IndexError:
        audit_id_str = 'none'

    eco_conversion = instance.eco_benefits_conversion

    if eco_conversion:
        eco_str = eco_conversion.hash
    else:
        eco_str = 'none'

    string_to_hash = audit_id_str + ":" + eco_str

    return hashlib.md5(string_to_hash).hexdigest()


def add_tree_photo(request, instance, plot_id, tree_id=None):
    plot = get_object_or_404(Plot, pk=plot_id, instance=instance)
    tree_ids = [t.pk for t in plot.tree_set.all()]

    if tree_id and int(tree_id) in tree_ids:
        tree = Tree.objects.get(pk=tree_id)
    elif tree_id is None:
        # See if a tree already exists on this plot
        tree = plot.current_tree()

        if tree is None:
            # A tree doesn't exist, create a new tree create a
            # new tree, and attach it to this plot
            tree = Tree(plot=plot, instance=instance)

            # TODO: it is possible that a user has the ability to
            # 'create tree photos' but not trees. In this case we
            # raise an authorization exception here.
            # It is, however, possible to have both a pending
            # tree and a pending tree photo
            # This will be added later, when auth/admin work
            # correctly with this system
            tree.save_with_user(request.user)

    else:
        # Tree id is invalid or not in this plot
        raise Http404('Tree id %s not found on plot %s' % (tree_id, plot_id))

    #TODO: Validation Error
    #TODO: Auth Error
    if 'file' in request.FILES:
        #TODO: Check size before reading
        data = request.FILES['file'].file
    else:
{'fraction_non_alphanumeric': 0.06500473335437046, 'fraction_numerical': 0.005364468286525718, 'mean_word_length': 2.937267080745342, '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': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3801944', 'n_tokens_mistral': 1908, 'n_tokens_neox': 1821, 'n_words': 598}