<commit_before># -*- coding: utf-8 -*-

"""
Kay utilities.

:copyright: (c) 2009 by Kay Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""

import os
import logging
from datetime import datetime

from google.appengine.api import users
from google.appengine.api import memcache

from werkzeug import (
  Local, LocalManager, Response
)
from werkzeug.exceptions import NotFound
from pytz import timezone, UTC

from kay.conf import settings
from kay.utils.importlib import import_module

local = Local()
local_manager = LocalManager([local])

_translations_cache = {}
_default_translations = None
_standard_context_processors = None


def get_project_path():
  return os.path.dirname(os.path.dirname(os.path.dirname(__file__)))


def get_kay_locale_path():
  return os.path.join(get_project_path(), 'kay', 'i18n')


def get_timezone(tzname):
  """
  Method to get timezone with memcached enhancement.
  """
  try:
    tz = memcache.get("tz:%s" % tzname)
  except:
    tz = None
    logging.debug("timezone get failed: %s" % tzname)
  if tz is None:
    tz = timezone(tzname)
    memcache.add("tz:%s" % tzname, tz, 86400)
    logging.debug("timezone memcache added: %s" % tzname)
  else:
    logging.debug("timezone memcache hit: %s" % tzname)

  return tz


def raise_on_dev():
  if 'SERVER_SOFTWARE' in os.environ and \
        os.environ['SERVER_SOFTWARE'].startswith('Dev'):
    raise RuntimeError("Just for debugging.")
  else:
    pass


def get_request():
  return local.request


def url_for(endpoint, **args):
  """Get the URL to an endpoint.  The keyword arguments provided are used
  as URL values.  Unknown URL values are used as keyword argument.
  Additionally there are some special keyword arguments:

  `_anchor`
    This string is used as URL anchor.

  `_external`
    If set to `True` the URL will be generated with the full server name
    and `http://` prefix.
  """
  if hasattr(endpoint, 'get_url_values'):
    rv = endpoint.get_url_values()
    if rv is not None:
      if isinstance(rv, basestring):
        return make_external_url(rv)
      endpoint, updated_args = rv
      args.update(updated_args)
  anchor = args.pop('_anchor', None)
  external = args.pop('_external', False)
  rv = local.url_adapter.build(endpoint, args,
                               force_external=external)
  if anchor is not None:
    rv += '#' + url_quote(anchor)
  return rv


def create_logout_url(request=None):
  """
  An utilyty function for jinja2.
  """
  # TODO: Change implementation according to auth backend settings.
  from google.appengine.api import users
  if request is None:
    request = local.request
  return users.create_logout_url(request.url)


def create_login_url(request=None):
  """
  An utilyty function for jinja2.
  """
  # TODO: Change implementation according to auth backend settings.
  from google.appengine.api import users
  if request is None:
    request = local.request
  return users.create_login_url(request.url)


def reverse(endpoint, _external=False, method='GET', **values):
  """
  An utility function for jinja2.
  """
  return local.url_adapter.build(endpoint, values, method=method,
      force_external=_external)


def render_to_string(template, context={}):
  """
  A function for template rendering.
  """
  template = local.jinja2_env.get_template(template)
  return template.render(context)


def render_to_response(template, context, mimetype='text/html',
                       processors=None):
  """
  A function for adding useful variables to context automatically,
  according to the CONTEXT_PROCESSORS settings.
  """
  if processors is None:
    processors = ()
  else:
    processors = tuple(processors)
  for processor in get_standard_processors() + processors:
    context.update(processor(get_request()))
  return Response(render_to_string(template, context), mimetype=mimetype)

def get_standard_processors():
  from kay.conf import settings
  global _standard_context_processors
  if _standard_context_processors is None:
    processors = []
    for path in settings.CONTEXT_PROCESSORS:
      i = path.rfind('.')<commit_msg>Changed where to process context.<commit_after># -*- coding: utf-8 -*-

"""
Kay utilities.

:copyright: (c) 2009 by Kay Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""

import os
import logging
from datetime import datetime

from google.appengine.api import users
from google.appengine.api import memcache

from werkzeug import (
  Local, LocalManager, Response
)
from werkzeug.exceptions import NotFound
from pytz import timezone, UTC

from kay.conf import settings
from kay.utils.importlib import import_module

local = Local()
local_manager = LocalManager([local])

_translations_cache = {}
_default_translations = None
_standard_context_processors = None


def get_project_path():
  return os.path.dirname(os.path.dirname(os.path.dirname(__file__)))


def get_kay_locale_path():
  return os.path.join(get_project_path(), 'kay', 'i18n')


def get_timezone(tzname):
  """
  Method to get timezone with memcached enhancement.
  """
  try:
    tz = memcache.get("tz:%s" % tzname)
  except:
    tz = None
    logging.debug("timezone get failed: %s" % tzname)
  if tz is None:
    tz = timezone(tzname)
    memcache.add("tz:%s" % tzname, tz, 86400)
    logging.debug("timezone memcache added: %s" % tzname)
  else:
    logging.debug("timezone memcache hit: %s" % tzname)

  return tz


def raise_on_dev():
  if 'SERVER_SOFTWARE' in os.environ and \
        os.environ['SERVER_SOFTWARE'].startswith('Dev'):
    raise RuntimeError("Just for debugging.")
  else:
    pass


def get_request():
  return local.request


def url_for(endpoint, **args):
  """Get the URL to an endpoint.  The keyword arguments provided are used
  as URL values.  Unknown URL values are used as keyword argument.
  Additionally there are some special keyword arguments:

  `_anchor`
    This string is used as URL anchor.

  `_external`
    If set to `True` the URL will be generated with the full server name
    and `http://` prefix.
  """
  if hasattr(endpoint, 'get_url_values'):
    rv = endpoint.get_url_values()
    if rv is not None:
      if isinstance(rv, basestring):
        return make_external_url(rv)
      endpoint, updated_args = rv
      args.update(updated_args)
  anchor = args.pop('_anchor', None)
  external = args.pop('_external', False)
  rv = local.url_adapter.build(endpoint, args,
                               force_external=external)
  if anchor is not None:
    rv += '#' + url_quote(anchor)
  return rv


def create_logout_url(request=None):
  """
  An utilyty function for jinja2.
  """
  # TODO: Change implementation according to auth backend settings.
  from google.appengine.api import users
  if request is None:
    request = local.request
  return users.create_logout_url(request.url)


def create_login_url(request=None):
  """
  An utilyty function for jinja2.
  """
  # TODO: Change implementation according to auth backend settings.
  from google.appengine.api import users
  if request is None:
    request = local.request
  return users.create_login_url(request.url)


def reverse(endpoint, _external=False, method='GET', **values):
  """
  An utility function for jinja2.
  """
  return local.url_adapter.build(endpoint, values, method=method,
      force_external=_external)


def render_to_string(template, context={}, processors=None):
  """
  A function for template rendering adding useful variables to context
  automatically, according to the CONTEXT_PROCESSORS settings.
  """
  if processors is None:
    processors = ()
  else:
    processors = tuple(processors)
  for processor in get_standard_processors() + processors:
    context.update(processor(get_request()))
  template = local.jinja2_env.get_template(template)
  return template.render(context)


def render_to_response(template, context, mimetype='text/html',
                       processors=None):
  """
  A function for render html pages.
  """
  return Response(render_to_string(template, context, processors),
                  mimetype=mimetype)

def get_standard_processors():
  from kay.conf import settings
  global _standard_context_processors
  if _standard_context_processors is None:
    processors = []
    for path in settings.CONTEXT_PROCESSORS:
      i = path.rfind('.')
{'fraction_non_alphanumeric': 0.09972431978904471, 'fraction_numerical': 0.0038355507611171043, 'mean_word_length': 3.8203350664355864, 'pattern_counts': {'":': 0, '<': 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': '2809967', 'n_tokens_mistral': 2606, 'n_tokens_neox': 2515, 'n_words': 762}