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

import six
import time
import redis
import urllib2
import logging
import datetime
try:
    import blinker
except:
    blinker = None # NOQA

from mongoengine import Document, signals
from django.conf import settings
from django.template import Context, Template
from django.utils import translation
from django.contrib.auth import get_user_model
from djangojs.utils import ContextSerializer

from sparks.django import mail

from ..landing.models import LandingUser
from .models import EmailContent

LOGGER = logging.getLogger(__name__)
User = get_user_model()

REDIS = redis.StrictRedis(host=getattr(settings, 'MAIN_SERVER',
                                       'localhost'), port=6379,
                          db=getattr(settings, 'REDIS_DB', 0))

now     = datetime.datetime.now
ftstamp = datetime.datetime.fromtimestamp
today   = datetime.date.today

boolcast = {
    'True': True,
    'False': False,
    'None': None,
    # The real None is needed in case of a non-existing key.
    None: None
}


# •••••••••••••••••••••••••••••••••••••••••••••••••••••• utils/helper functions


def connect_mongoengine_signals(module_globals):
    """ Automatically iterate classes of a given module and connect handlers
        to signals, given they follow the name pattern
        ``signal_<signal_name>_handler()``.

        See https://mongoengine-odm.readthedocs.org/en/latest/guide/signals.html#overview # NOQA
        for a list of valid signal names.
    """

    if blinker is None:
        LOGGER.error('blinker module is not installed, '
                     'cannot connect mongoengine signals!')
        return

    connected = 0

    for key, potential_class in module_globals.items():

        # TODO: use ReferenceDocument and other Mongo classes if appropriate?
        try:
            look_for_handlers = issubclass(potential_class, Document)

        except:
            # potential_class is definitely not a class/document ;-)
            continue

        if look_for_handlers:
            for signal_name in ('pre_init', 'post_init', 'pre_save',
                                'pre_save_post_validation', 'post_save',
                                'pre_delete', 'post_delete',
                                'pre_bulk_insert', 'post_bulk_insert'):
                handler_name = 'signal_{0}_handler'.format(signal_name)
                if hasattr(potential_class, handler_name):
                    getattr(signals, signal_name).connect(
                        getattr(potential_class, handler_name),
                        sender=potential_class)
                    connected += 1

    if connected:
        LOGGER.info('Connected %s signal handlers to MongoEngine senders.',
                    connected)


def get_user_and_update_context(context):

    # If there is no new user, it's not a registration, we
    # just get the context user, to fill email fields.
<commit_msg>display the 'connected…' message only if debug.<commit_after># -*- coding: utf-8 -*-

import six
import time
import redis
import urllib2
import logging
import datetime
try:
    import blinker
except:
    blinker = None # NOQA

from mongoengine import Document, signals
from django.conf import settings
from django.template import Context, Template
from django.utils import translation
from django.contrib.auth import get_user_model
from djangojs.utils import ContextSerializer

from sparks.django import mail

from ..landing.models import LandingUser
from .models import EmailContent

LOGGER = logging.getLogger(__name__)
User = get_user_model()

REDIS = redis.StrictRedis(host=getattr(settings, 'MAIN_SERVER',
                                       'localhost'), port=6379,
                          db=getattr(settings, 'REDIS_DB', 0))

now     = datetime.datetime.now
ftstamp = datetime.datetime.fromtimestamp
today   = datetime.date.today

boolcast = {
    'True': True,
    'False': False,
    'None': None,
    # The real None is needed in case of a non-existing key.
    None: None
}


# •••••••••••••••••••••••••••••••••••••••••••••••••••••• utils/helper functions


def connect_mongoengine_signals(module_globals):
    """ Automatically iterate classes of a given module and connect handlers
        to signals, given they follow the name pattern
        ``signal_<signal_name>_handler()``.

        See https://mongoengine-odm.readthedocs.org/en/latest/guide/signals.html#overview # NOQA
        for a list of valid signal names.
    """

    if blinker is None:
        LOGGER.error('blinker module is not installed, '
                     'cannot connect mongoengine signals!')
        return

    if __debug__:
        connected = 0

    for key, potential_class in module_globals.items():

        # TODO: use ReferenceDocument and other Mongo classes if appropriate?
        try:
            look_for_handlers = issubclass(potential_class, Document)

        except:
            # potential_class is definitely not a class/document ;-)
            continue

        if look_for_handlers:
            for signal_name in ('pre_init', 'post_init', 'pre_save',
                                'pre_save_post_validation', 'post_save',
                                'pre_delete', 'post_delete',
                                'pre_bulk_insert', 'post_bulk_insert'):
                handler_name = 'signal_{0}_handler'.format(signal_name)
                if hasattr(potential_class, handler_name):
                    getattr(signals, signal_name).connect(
                        getattr(potential_class, handler_name),
                        sender=potential_class)
                    if __debug__:
                        connected += 1

    if __debug__ and settings.DEBUG and connected:
        LOGGER.debug('Connected %s signal handlers to MongoEngine senders.',
                     connected)


def get_user_and_update_context(context):

    # If there is no new user, it's not a registration, we
    # just get the context user, to fill email fields.

{'fraction_non_alphanumeric': 0.09423300648163536, 'fraction_numerical': 0.0033239155725444574, 'mean_word_length': 2.419318181818182, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 5, 'https://': 2, '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': '4294077', 'n_tokens_mistral': 1749, 'n_tokens_neox': 1659, 'n_words': 480}