<commit_before>from django.conf import settings
from django.template import Context, Library, Node, NodeList, Template, Variable
from django.utils.encoding import smart_str, smart_unicode

register = Library()

def _merge(view, args, kwargs):
    """Merge arguments with PartialResolveNode's"""
    # If view is a PartialResolveNode update arguments with its args and kwargs
    if isinstance(view, PartialResolveNode):
        args_ = view.args[:]
        args_.extend(args)
        args = args_
        kwargs_ = view.kwargs.copy()
        kwargs_.update(kwargs)
        kwargs = kwargs_
        # the "real" view is inside the PartialResolveNode's view attribute
        view = view.view
    return view, args, kwargs



class ResolveNode(Node):
    """Represents a to-be-resolved url"""
    def __init__(self, view, args, kwargs, asvar):
        self.view = view
        self.args = args
        self.kwargs = kwargs
        self.asvar = asvar
    
    def render(self, context):
        view = self.view.resolve(context)
        args = self.args
        kwargs = self.kwargs

        args = [arg.resolve(context) for arg in args]
        kwargs = dict([(smart_str(k,'ascii'), v.resolve(context))
                       for k, v in kwargs.items()])

        view, args, kwargs = _merge(view, args, kwargs)

        from django.core.urlresolvers import reverse, NoReverseMatch
        # Try to look up the URL twice: once given the view name, and again
        # relative to what we guess is the "main" app. If they both fail, 
        # re-raise the NoReverseMatch unless we're using the 
        # {% resolve ... as var %} construct in which cause return nothing.
        url = ''
        try:
            url = reverse(view, args=args, kwargs=kwargs)
        except NoReverseMatch, exc:
            project_name = settings.SETTINGS_MODULE.split('.')[0]
            try:
                url = reverse(project_name + '.' + view,
                              args=args, kwargs=kwargs)
            except NoReverseMatch:
                if self.asvar is None:
                    # reraise the original NoReverseMatch since the above is 
                    # just a (failed, if we reach here) attempt to fix things.
                    raise exc
                    
        if self.asvar:
            context[self.asvar] = url
            return ''
        else:
            return url


class PartialResolveNode(Node):
    """Represents a partial to-be-resolved url"""
    def __init__(self, view, args, kwargs, asvar):
        # Store in "private" attributes so we can re-resolve variables in loops
        self._view = view
        self._args = args
        self._kwargs = kwargs

        self.asvar = asvar

    def render(self, context):
        self.view = self._view.resolve(context)
        self.args = [arg.resolve(context) for arg in self._args]
        self.kwargs = dict([(smart_str(k,'ascii'), v.resolve(context))
                            for k, v in self._kwargs.items()])

        self.view, self.args, self.kwargs = _merge(self.view, self.args, self.kwargs)
        
        if self.asvar:
            context[self.asvar] = self
            return ''
        else:
            raise TemplateSyntaxError("When using 'partial' the 'resolve' tag"
                                      " requires 'as varname' argument")

    def __unicode__(self):
        # don't output partially resolved urls
        if settings.TEMPLATE_DEBUG:
            return "[Cannot render: %s. You have to use it through " \
                   "the 'resolve' tag.]" % repr(self)
        else:
            return '' # fail silently

    def __repr__(self):
        return "Partialy resolved url for view: %s with args %s " \
               "and kwargs %s" % (self.view, self.args, self.kwargs)

@register.tag
def resolve(parser, token):
    """
    Returns an absolute URL matching given view with its parameters.

    This is a way to define links that aren't tied to a particular URL
    configuration::

        {% resolve "path.to.some_view" "arg1","arg2" [as varname] %}
    or:
        {% resolve "path.to.some_view" name1="value1" [as varname] %}

    The first argument is a path to a view or a view name. It can be an 
    absolute python path or just ``app_name.view_name`` without the project 
    name if the view is located inside the project.  Other arguments are 
    comma-separated values that will be filled in place of positional and 
    keyword arguments in the URL. All arguments for the URL must be present 
    unless you use the ``partial`` form of ``resolve`` which is described 
    below.
    If you'd like to store the url in a ``context`` variable instead of 
    directly displaying it you can use the optional ``as varname`` argument.

    For example if you have a view ``app_name.client`` taking client's id and
    the corresponding line in a URLconf looks like this::

        ('^client/(\d+)/$', 'app_name.client')
<commit_msg>Added more error handling<commit_after>from django.conf import settings
from django.template import Context, Library, Node, NodeList, Template, Variable
from django.utils.encoding import smart_str, smart_unicode

register = Library()

def _merge(view, args, kwargs):
    """Merge arguments with PartialResolveNode's"""
    # If view is a PartialResolveNode update arguments with its args and kwargs
    if isinstance(view, PartialResolveNode):
        args_ = view.args[:]
        args_.extend(args)
        args = args_
        kwargs_ = view.kwargs.copy()
        kwargs_.update(kwargs)
        kwargs = kwargs_
        # the "real" view is inside the PartialResolveNode's view attribute
        view = view.view
    return view, args, kwargs



class ResolveNode(Node):
    """Represents a to-be-resolved url"""
    def __init__(self, view, args, kwargs, asvar):
        self.view = view
        self.args = args
        self.kwargs = kwargs
        self.asvar = asvar
    
    def render(self, context):
        view = self.view.resolve(context)
        args = [arg.resolve(context) for arg in self.args]
        kwargs = dict([(smart_str(k,'ascii'), v.resolve(context))
                       for k, v in self.kwargs.items()])

        if not view:
            # variable not in context
            if settings.TEMPLATE_DEBUG:
                return "[Missing %r. Cannot resolve.]" % self.view.var
            return ""

        view, args, kwargs = _merge(view, args, kwargs)

        from django.core.urlresolvers import reverse, NoReverseMatch
        # Try to look up the URL twice: once given the view name, and again
        # relative to what we guess is the "main" app. If they both fail, 
        # re-raise the NoReverseMatch unless we're using the 
        # {% resolve ... as var %} construct in which cause return nothing.
        url = ''
        try:
            url = reverse(view, args=args, kwargs=kwargs)
        except NoReverseMatch, exc:
            project_name = settings.SETTINGS_MODULE.split('.')[0]
            try:
                url = reverse(project_name + '.' + view,
                              args=args, kwargs=kwargs)
            except NoReverseMatch:
                if self.asvar is None:
                    # reraise the original NoReverseMatch since the above is 
                    # just a (failed, if we reach here) attempt to fix things.
                    raise exc
                    
        if self.asvar:
            context[self.asvar] = url
            return ''
        else:
            return url
    
    def __repr__(self):
        return "<ResolveNode: resolve %r with args %r and kwargs %r>" % \
            (self.view.var, (a.var for a in self.args), dict((k,v.var) for k,v in self.kwargs.iteritems()))


class PartialResolveNode(Node):
    """Represents a partial to-be-resolved url"""
    def __init__(self, view, args, kwargs, asvar):
        # Store in "private" attributes so we can re-resolve variables in loops
        self._view = view
        self._args = args
        self._kwargs = kwargs

        self.asvar = asvar

    def render(self, context):
        self.view = self._view.resolve(context)
        self.args = [arg.resolve(context) for arg in self._args]
        self.kwargs = dict([(smart_str(k,'ascii'), v.resolve(context))
                            for k, v in self._kwargs.items()])

        if not self.view:
            # variable not in context
            if settings.TEMPLATE_DEBUG:
                return "[Missing %r. Cannot resolve.]" % self.view
            return ""

        self.view, self.args, self.kwargs = _merge(self.view, self.args, self.kwargs)
        
        if self.asvar:
            context[self.asvar] = self
            return ''
        else:
            raise TemplateSyntaxError("When using 'partial' the 'resolve' tag"
                                      " requires 'as varname' argument")

    def __unicode__(self):
        # don't output partially resolved urls
        if settings.TEMPLATE_DEBUG:
            return "[Cannot render: %r. You have to use it through " \
                   "the 'resolve' tag.]" % self
        else:
            return '' # fail silently

    def __repr__(self):
        return "<PartialResolveNode: resolve %r with args %r " \
               "and kwargs %r>" % (self._view.var, (a.var for a in self._args), dict((k,v.var) for k,v in self._kwargs.iteritems()))

@register.tag
def resolve(parser, token):
    """
    Returns an absolute URL matching given view with its parameters.

    This is a way to define links that aren't tied to a particular URL
    configuration::

        {% resolve "path.to.some_view" "arg1","arg2" [as varname] %}
    or:
        {% resolve "path.to.some_view" name1="value1" [as varname] %}

    The first argument is a path to a view or a view name. It can be an 
    absolute python path or just ``app_name.view_name`` without the project 
    name if the view is located inside the project.  Other arguments are 
    comma-separated values that will be filled in place of positional and 
    keyword arguments in the URL. All arguments for the URL must be present 
    unless you use the ``partial`` form of ``resolve`` which is described 
    below.
    If you'd like to store the url in a ``context`` variable instead of 
    directly displaying it you can use the optional ``as varname`` argument.

    For example if you have a view ``app_name.client`` taking client's id and
    the corresponding line in a URLconf looks like this::

        ('^client/(\d+)/$', 'app_name.client')

{'fraction_non_alphanumeric': 0.093340922026181, 'fraction_numerical': 0.0009485866059571238, 'mean_word_length': 2.106364172068356, 'pattern_counts': {'":': 0, '<': 5, '<?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': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5884383', 'n_tokens_mistral': 2910, 'n_tokens_neox': 2823, 'n_words': 1057}