<commit_before>import sys
import os
from os.path import join, abspath, dirname

# PATH vars

here = lambda *x: join(abspath(dirname(__file__)), *x)
PROJECT_ROOT = here("..")
root = lambda *x: join(abspath(PROJECT_ROOT), *x)

sys.path.insert(0, root('apps'))
sys.path.insert(0, root('libs'))

# ENVIRON values

from django.core.exceptions import ImproperlyConfigured

# .env_values.py contains secrets and host config values usually stored
# in a different place
try:
    import env_values
except ImportError:
    env_values = None

def get_env_value(var_name):
    """ Get the env value `var_name` or return exception """
    try:
        return getattr(env_values, var_name)
    except AttributeError:
        raise ImproperlyConfigured("Environment value %s not found" % var_name)

DEBUG = True
TEMPLATE_DEBUG = DEBUG

ADMINS = ()

MANAGERS = ADMINS

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'cla_backend',
        'USER': 'postgres',
        'PASSWORD': '',
        'HOST': '',                      # Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP.
        'PORT': '',                      # Set to empty string for default.
    }
}

# Hosts/domain names that are valid for this site; required if DEBUG is False
# See https://docs.djangoproject.com/en/1.5/ref/settings/#allowed-hosts
ALLOWED_HOSTS = []

# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# In a Windows environment this must be set to your system time zone.
TIME_ZONE = 'Europe/London'

# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-gb'

SITE_ID = 1

# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = False

# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale.
USE_L10N = True

# If you set this to False, Django will not use timezone-aware datetimes.
USE_TZ = True

# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/var/www/example.com/media/"
MEDIA_ROOT = root('assets', 'uploads')

# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://media.lawrence.com/media/", "http://example.com/media/"
MEDIA_URL = '/media/'

# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/home/media/media.lawrence.com/static/"
STATIC_ROOT = root('static')

# URL prefix for static files.
# Example: "http://media.lawrence.com/static/"
STATIC_URL = '/static/'

# Additional locations of static files
STATICFILES_DIRS = (
    root('assets'),
)

# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)

# Make this unique, and don't share it with anybody.
SECRET_KEY = 'o=>4$)9?38N@^}d&pj,VL9^{r][xM9L.9cfE:xZZNk(N?v27+i'

# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
    'django.template.loaders.filesystem.Loader',
    'django.template.loaders.app_directories.Loader',
)

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
)

ROOT_URLCONF = 'cla_backend.urls'

# Python dotted path to the WSGI application used by Django's runserver.
WSGI_APPLICATION = 'cla_backend.wsgi.application'

TEMPLATE_DIRS = (
    root('templates'),
)

INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.contrib.admin',
    'south',
    'rest_framework',
    'pagedown',
    'provider',
    'provider.oauth2'
)

PROJECT_APPS = (
    'core',
    'legalaid',
    'cla_provider',
    'call_centre',
    'cla_eventlog',
    'reports',
    'knowledgebase',
    'timer',
    'diagnosis'
)

INSTALLED_APPS += PROJECT_APPS

# DIAGNOSIS

DIAGNOSIS_FILE_NAME = 'graph-2014.07.21.graphml'

# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error when DEBUG=False.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'verbose': {
            'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s'
        },
        'simple': {
            'format': '%(levelname)s %(message)s'
        },
    },
    'filters': {
        'require_debug_false': {
            '()': 'django.utils.log.RequireDebugFalse'
        },
        'require_debug_true': {
            '()': 'django.utils.log.RequireDebugTrue'
        }
    },
    'handlers': {
        'production_file':{
            'level' : 'INFO',
            'class' : 'logging.handlers.RotatingFileHandler',
            'filename' : '/var/log/wsgi/app.log',
            'maxBytes': 1024*1024*5, # 5 MB
            'backupCount' : 7,
            'formatter': 'verbose',
            'filters': ['require_debug_false'],
        },
        'debug_file':{
            'level' : 'DEBUG',
            'class' : 'logging.handlers.RotatingFileHandler',
            'filename' : '/var/log/wsgi/debug.log',
            'maxBytes': 1024*1024*5, # 5 MB
            'backupCount' : 7,
            'formatter': 'verbose',
            'filters': ['require_debug_true'],
        },
        'mail_admins': {
            'level': 'ERROR',
            'filters': ['require_debug_false'],
            'class': 'django.utils.log.AdminEmailHandler'
        }
    },
    'loggers': {
        'django.request': {
            'handlers': ['mail_admins'],
            'level': 'ERROR',
            'propagate': True,
        },
        '': {
            'handlers': ['production_file', 'debug_file'],
            'level': "DEBUG",
        },
    }
}

if 'RAVEN_CONFIG_DSN' in os.environ:
    RAVEN_CONFIG = {
        'dsn': os.environ.get('RAVEN_CONFIG_DSN'),
        'site': os.environ.get('RAVEN_CONFIG_SITE')
    }

    INSTALLED_APPS += (
        'raven.contrib.django.raven_compat',
    )

    MIDDLEWARE_CLASSES = (
        'raven.contrib.django.raven_compat.middleware.SentryResponseErrorIdMiddleware',
        'raven.contrib.django.raven_compat.middleware.Sentry404CatchMiddleware',
    ) + MIDDLEWARE_CLASSES

# EMAILS

# .local.py overrides all the common settings.
try:
    from .local import *
except ImportError:
    pass

# importing test settings file if necessary (TODO chould be done better)
if len(sys.argv) > 1 and 'test' == sys.argv[1]:
    from .testing import *

# Django rest-framework-auth
REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.OAuth2Authentication',
    ),
    'DEFAULT_PERMISSION_CLASSES': (
        'core.permissions.AllowNone',
    ),
}

# the start number of the LAA reference, must be 7 digit number and must
# not clash with existing - generated references so we are starting at 3million
LAA_REFERENCE_SEED = 3000000
<commit_msg>Disabled Sentry 404 middleware.<commit_after>import sys
import os
from os.path import join, abspath, dirname

# PATH vars

here = lambda *x: join(abspath(dirname(__file__)), *x)
PROJECT_ROOT = here("..")
root = lambda *x: join(abspath(PROJECT_ROOT), *x)

sys.path.insert(0, root('apps'))
sys.path.insert(0, root('libs'))

# ENVIRON values

from django.core.exceptions import ImproperlyConfigured

# .env_values.py contains secrets and host config values usually stored
# in a different place
try:
    import env_values
except ImportError:
    env_values = None

def get_env_value(var_name):
    """ Get the env value `var_name` or return exception """
    try:
        return getattr(env_values, var_name)
    except AttributeError:
        raise ImproperlyConfigured("Environment value %s not found" % var_name)

DEBUG = True
TEMPLATE_DEBUG = DEBUG

ADMINS = ()

MANAGERS = ADMINS

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'cla_backend',
        'USER': 'postgres',
        'PASSWORD': '',
        'HOST': '',                      # Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP.
        'PORT': '',                      # Set to empty string for default.
    }
}

# Hosts/domain names that are valid for this site; required if DEBUG is False
# See https://docs.djangoproject.com/en/1.5/ref/settings/#allowed-hosts
ALLOWED_HOSTS = []

# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# In a Windows environment this must be set to your system time zone.
TIME_ZONE = 'Europe/London'

# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-gb'

SITE_ID = 1

# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = False

# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale.
USE_L10N = True

# If you set this to False, Django will not use timezone-aware datetimes.
USE_TZ = True

# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/var/www/example.com/media/"
MEDIA_ROOT = root('assets', 'uploads')

# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://media.lawrence.com/media/", "http://example.com/media/"
MEDIA_URL = '/media/'

# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/home/media/media.lawrence.com/static/"
STATIC_ROOT = root('static')

# URL prefix for static files.
# Example: "http://media.lawrence.com/static/"
STATIC_URL = '/static/'

# Additional locations of static files
STATICFILES_DIRS = (
    root('assets'),
)

# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)

# Make this unique, and don't share it with anybody.
SECRET_KEY = 'o=>4$)9?38N@^}d&pj,VL9^{r][xM9L.9cfE:xZZNk(N?v27+i'

# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
    'django.template.loaders.filesystem.Loader',
    'django.template.loaders.app_directories.Loader',
)

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
)

ROOT_URLCONF = 'cla_backend.urls'

# Python dotted path to the WSGI application used by Django's runserver.
WSGI_APPLICATION = 'cla_backend.wsgi.application'

TEMPLATE_DIRS = (
    root('templates'),
)

INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.contrib.admin',
    'south',
    'rest_framework',
    'pagedown',
    'provider',
    'provider.oauth2'
)

PROJECT_APPS = (
    'core',
    'legalaid',
    'cla_provider',
    'call_centre',
    'cla_eventlog',
    'reports',
    'knowledgebase',
    'timer',
    'diagnosis'
)

INSTALLED_APPS += PROJECT_APPS

# DIAGNOSIS

DIAGNOSIS_FILE_NAME = 'graph-2014.07.21.graphml'

# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error when DEBUG=False.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'verbose': {
            'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s'
        },
        'simple': {
            'format': '%(levelname)s %(message)s'
        },
    },
    'filters': {
        'require_debug_false': {
            '()': 'django.utils.log.RequireDebugFalse'
        },
        'require_debug_true': {
            '()': 'django.utils.log.RequireDebugTrue'
        }
    },
    'handlers': {
        'production_file':{
            'level' : 'INFO',
            'class' : 'logging.handlers.RotatingFileHandler',
            'filename' : '/var/log/wsgi/app.log',
            'maxBytes': 1024*1024*5, # 5 MB
            'backupCount' : 7,
            'formatter': 'verbose',
            'filters': ['require_debug_false'],
        },
        'debug_file':{
            'level' : 'DEBUG',
            'class' : 'logging.handlers.RotatingFileHandler',
            'filename' : '/var/log/wsgi/debug.log',
            'maxBytes': 1024*1024*5, # 5 MB
            'backupCount' : 7,
            'formatter': 'verbose',
            'filters': ['require_debug_true'],
        },
        'mail_admins': {
            'level': 'ERROR',
            'filters': ['require_debug_false'],
            'class': 'django.utils.log.AdminEmailHandler'
        }
    },
    'loggers': {
        'django.request': {
            'handlers': ['mail_admins'],
            'level': 'ERROR',
            'propagate': True,
        },
        '': {
            'handlers': ['production_file', 'debug_file'],
            'level': "DEBUG",
        },
    }
}

if 'RAVEN_CONFIG_DSN' in os.environ:
    RAVEN_CONFIG = {
        'dsn': os.environ.get('RAVEN_CONFIG_DSN'),
        'site': os.environ.get('RAVEN_CONFIG_SITE')
    }

    INSTALLED_APPS += (
        'raven.contrib.django.raven_compat',
    )

    MIDDLEWARE_CLASSES = (
        'raven.contrib.django.raven_compat.middleware.SentryResponseErrorIdMiddleware',
        #'raven.contrib.django.raven_compat.middleware.Sentry404CatchMiddleware',
    ) + MIDDLEWARE_CLASSES

# EMAILS

# .local.py overrides all the common settings.
try:
    from .local import *
except ImportError:
    pass

# importing test settings file if necessary (TODO chould be done better)
if len(sys.argv) > 1 and 'test' == sys.argv[1]:
    from .testing import *

# Django rest-framework-auth
REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.OAuth2Authentication',
    ),
    'DEFAULT_PERMISSION_CLASSES': (
        'core.permissions.AllowNone',
    ),
}

# the start number of the LAA reference, must be 7 digit number and must
# not clash with existing - generated references so we are starting at 3million
LAA_REFERENCE_SEED = 3000000
<|endoftext|>


<commit_before>from django.core.urlresolvers import resolve
from django.test import TestCase
from django.http import HttpRequest
from django.test import LiveServerTestCase
from django.contrib.auth.models import User
from book.views import *
from book.models import Book
import os

class IndexPageTest(TestCase):

    def test_root_url_resolves_to_index_page_view(self):
        found = resolve('/')
        self.assertEqual(found.func, index)

    def test_uses_login_template(self):
        response = self.client.get('/')
        self.assertTemplateUsed(response, 'login.html')<commit_msg>added new tests<commit_after>from django.core.urlresolvers import resolve
from django.test import TestCase, TransactionTestCase
from django.http import HttpRequest
from django.core.files import File
from django.core.files.storage import Storage
from django.contrib.auth.models import User
from book.views import *
from book.models import Book
import mock

class ModelTest(TransactionTestCase):
    reset_sequences = True

    def setUp(self):
        # https://joeray.me/mocking-files-and-file-storage-for-testing-django-models.html
        # file_mock = mock.MagicMock(spec=File, name='FileMock')
        # file_mock.name = 'Hiren.pdf'

        # storage_mock = mock.MagicMock(spec=Storage, name='StorageMock')
        # storage_mock.url = mock.MagicMock(name='url')
        # storage_mock.url.return_value = '/tmp/Hiren.pdf'

        obj = Book()
        obj.note = 'Test note'
        # obj.pdf = file_mock
        # with mock.patch('django.core.files.storage.default_storage._wrapped', storage_mock):
            # The asset is saved to the database but our mock storage
            # system is used so we don't touch the filesystem
        #    obj.save()
        obj.save()

    def test_book_model(self):
        books = Book.objects.all()
        self.assertEqual(books[0].note, 'Test note')
        self.assertEqual(books.count(), 1)

class IndexPageTest(TestCase):

    def test_root_url_resolves_to_index_page_view(self):
        found = resolve('/')
        self.assertEqual(found.func, index)

    def test_uses_login_template(self):
        response = self.client.get('/')
        self.assertTemplateUsed(response, 'login.html')<|endoftext|>


<commit_before>#!/usr/bin/env python3
#
# Author    : Manuel Bernal Llinares
# Project   : trackhub-creator
# Timestamp : 29-06-2017 11:47
# ---
# © 2017 Manuel Bernal Llinares <mbdebian@gmail.com>
# All rights reserved.
#

"""
Pipeline Runner - Main Application
"""

import nose
import argparse
import unittest
# Modules from package
import config_manager
import ensembl.service
import ensembl.data_downloader

__DEFAULT_CONFIG_FILE = "config_default.json"

# Running mode
__run_test_mode = False
__logger = None
__args = None

def get_cmdl():
    cmdl_version = '2017.06.29'
    parser = argparse.ArgumentParser()
    parser.add_argument('-c', "--config_file",
                        help='Application configuration file')
    parser.add_argument('-p', '--pipeline_config_file',
                        help='Configuration file for the pipeline that is going to be run')
    parser.add_argument('-v', '--version',
                        help='display version information',
                        action='version',
                        version=cmdl_version + ' %(prog)s ')
    parser.add_argument('pipeline_name',
                        help='Module Name that contains the director of the pipeline to run')
    args = parser.parse_args()
    return args

def app_bootstrap():
    global __run_test_mode
    global __logger
    global __args
    __args = get_cmdl()
    if __args.config_file:
        config_manager.set_application_config_file(__args.config_file)
    else:
        config_manager.set_application_config_file(__DEFAULT_CONFIG_FILE)
    if __args.pipeline_name:
        config_manager.set_pipeline_name(__args.pipeline_name)
        if __args.pipeline_name == 'test':
            __run_test_mode = True
    __logger = config_manager.get_app_config_manager().get_logger_for(__name__)
    if __run_test_mode:
        __logger.info(
            "Session '{}' STARTED, RUNNING UNIT TESTS".format(config_manager.get_app_config_manager().get_session_id()))
    else:
        __logger.info(
            "Session '{}' STARTED, pipeline '{}'".format(config_manager.get_app_config_manager().get_session_id(),
                                                         __args.pipeline_name))

def modules_bootstrap():
    ensembl_config_file = config_manager.get_app_config_manager().get_file_name_config_modules_ensembl_service()
    __logger.debug("Setting Ensembl configuration file -- {}".format(ensembl_config_file))
    ensembl.service.set_configuration_file(ensembl_config_file)
    # TODO - Should I delegate this to a main entry point for every module?.
    # TODO - REFACTOR THIS IN THE FUTURE, WHEN MODULE FUNCTIONALITY HAS BEEN TESTED
    __logger.debug("Setting Ensembl Data Downloader configuration file -- {}"
                   .format(config_manager
                           .get_app_config_manager()
                           .get_file_name_config_modules_ensembl_data_downloader()))
    ensembl.data_downloader.set_configuration_file(
        config_manager
            .get_app_config_manager()
            .get_file_name_config_modules_ensembl_data_downloader())

def run_unit_tests():
    __logger.debug("Running Unit Tests")
    test_loader = unittest.TestLoader()
    test_suite = test_loader.discover('.')
    nose.run(suite=test_suite)

def main():
    app_bootstrap()
    modules_bootstrap()
    if __run_test_mode:
        run_unit_tests()
    else:
        pass

if __name__ == "__main__":
    main()
<commit_msg>pipeline_arguments, Comma separated of pipeline command line arguments (key=value pairs)<commit_after>#!/usr/bin/env python3
#
# Author    : Manuel Bernal Llinares
# Project   : trackhub-creator
# Timestamp : 29-06-2017 11:47
# ---
# © 2017 Manuel Bernal Llinares <mbdebian@gmail.com>
# All rights reserved.
#

"""
Pipeline Runner - Main Application
"""

import nose
import argparse
import unittest
# Modules from package
import config_manager
import ensembl.service
import ensembl.data_downloader

__DEFAULT_CONFIG_FILE = "config_default.json"

# Running mode
__run_test_mode = False
__logger = None
__args = None

def get_cmdl():
    cmdl_version = '2017.06.29'
    parser = argparse.ArgumentParser()
    parser.add_argument('-c', "--config_file",
                        help='Application configuration file')
    parser.add_argument('-p', '--pipeline_config_file',
                        help='Configuration file for the pipeline that is going to be run')
    parser.add_argument('-a', '--pipeline_arguments',
                        help='Comma separated of pipeline command line arguments (key=value pairs)')
    parser.add_argument('-v', '--version',
                        help='display version information',
                        action='version',
                        version=cmdl_version + ' %(prog)s ')
    parser.add_argument('pipeline_name',
                        help='Module Name that contains the director of the pipeline to run')
    args = parser.parse_args()
    return args

def app_bootstrap():
    global __run_test_mode
    global __logger
    global __args
    __args = get_cmdl()
    if __args.config_file:
        config_manager.set_application_config_file(__args.config_file)
    else:
        config_manager.set_application_config_file(__DEFAULT_CONFIG_FILE)
    if __args.pipeline_name:
        config_manager.set_pipeline_name(__args.pipeline_name)
        if __args.pipeline_name == 'test':
            __run_test_mode = True
    __logger = config_manager.get_app_config_manager().get_logger_for(__name__)
    if __run_test_mode:
        __logger.info(
            "Session '{}' STARTED, RUNNING UNIT TESTS".format(config_manager.get_app_config_manager().get_session_id()))
    else:
        __logger.info(
            "Session '{}' STARTED, pipeline '{}'".format(config_manager.get_app_config_manager().get_session_id(),
                                                         __args.pipeline_name))

def modules_bootstrap():
    ensembl_config_file = config_manager.get_app_config_manager().get_file_name_config_modules_ensembl_service()
    __logger.debug("Setting Ensembl configuration file -- {}".format(ensembl_config_file))
    ensembl.service.set_configuration_file(ensembl_config_file)
    # TODO - Should I delegate this to a main entry point for every module?.
    # TODO - REFACTOR THIS IN THE FUTURE, WHEN MODULE FUNCTIONALITY HAS BEEN TESTED
    __logger.debug("Setting Ensembl Data Downloader configuration file -- {}"
                   .format(config_manager
                           .get_app_config_manager()
                           .get_file_name_config_modules_ensembl_data_downloader()))
    ensembl.data_downloader.set_configuration_file(
        config_manager
            .get_app_config_manager()
            .get_file_name_config_modules_ensembl_data_downloader())

def run_unit_tests():
    __logger.debug("Running Unit Tests")
    test_loader = unittest.TestLoader()
    test_suite = test_loader.discover('.')
    nose.run(suite=test_suite)

def main():
    app_bootstrap()
    modules_bootstrap()
    if __run_test_mode:
        run_unit_tests()
    else:
        pass

if __name__ == "__main__":
    main()
<|endoftext|>


<commit_before>"""
The test and clean code is shamelessly stolen from
http://da44en.wordpress.com/2002/11/22/using-distutils/
"""

from distutils.core import Command, setup
from distutils import log
from distutils.fancy_getopt import fancy_getopt
from unittest import TextTestRunner, TestLoader
from glob import glob
from os.path import splitext, basename, join as pjoin, walk
from warnings import warn
import os
import time

class TestCommand(Command):
    user_options = [('verbose', 'v', "produce verbose output", 1)]

    def initialize_options(self):
        self._dir = os.getcwd()

    def finalize_options(self):
        args, obj = fancy_getopt(self.user_options, {}, None, None)
        # Ugly as sin, but distutils forced me to do it :(
        # All I wanted was this command to default to quiet...
        if "--verbose" not in args and "-v" not in args:
            self.verbose = 0

    def run(self):
        '''
        Finds all the tests modules in tests/, and runs them, exiting after they are all done
        '''

        log.set_verbosity(self.verbose)

        testfiles = [ ]
        for t in glob(pjoin(self._dir, 'tests', 'test*.py')):
            if not t.endswith('__init__.py'):
                testfiles.append('.'.join(
                    ['tests', splitext(basename(t))[0]])
                )

        self.announce("Test files:" + str(testfiles), level=2)
        tests = TestLoader().loadTestsFromNames(testfiles)
        t = TextTestRunner(verbosity = self.verbose)
        t.run(tests)
        exit()

class CleanCommand(Command):
    """
    Remove all build files and all compiled files
    =============================================

    Remove everything from build, including that
    directory, and all .pyc files
    """
    user_options = [('verbose', 'v', "produce verbose output", 1)]

    def initialize_options(self):
        self._files_to_delete = [ ]
        self._dirs_to_delete = [ ]

        for root, dirs, files in os.walk('.'):
            for f in files:
                if f.endswith('.pyc') or f.endswith('.class'):
                    self._files_to_delete.append(pjoin(root, f))
        for root, dirs, files in os.walk(pjoin('build')):
            for f in files:
                self._files_to_delete.append(pjoin(root, f))
            for d in dirs:
                self._dirs_to_delete.append(pjoin(root, d))
        # reverse dir list to only get empty dirs
        self._dirs_to_delete.reverse()
        self._dirs_to_delete.append('build')

    def finalize_options(self):
        args, obj = fancy_getopt(self.user_options, {}, None, None)
        # Ugly as sin, but distutils forced me to do it :(
        # All I wanted was this command to default to quiet...
        if "--verbose" not in args and "-v" not in args:
            self.verbose = 0

    def run(self):
        for clean_me in self._files_to_delete:
            if self.dry_run:
                log.info("Would have unlinked " + clean_me)
            else:
                try:
                    self.announce("Deleting " + clean_me, level=2)
                    os.unlink(clean_me)
                except Exception, e:
                    message = " ".join(["Failed to delete file", clean_me, str(e)])
                    log.warn(message)
        for clean_me in self._dirs_to_delete:
            if self.dry_run:
                log.info("Would have rmdir'ed " + clean_me)
            else:
                if os.path.exists(clean_me):
                    try:
                        self.announce("Going to remove " + clean_me, level=2)
                        os.rmdir(clean_me)
                    except Exception, e:
                        message = " ".join(
                                ["Failed to delete dir", clean_me, str(e)])
                        log.warn(message)
                elif clean_me != "build":
                    log.warn(clean_me + " does not exist")

setup(
        name = "intermine-bio",
        packages = ["interminebio"],
        cmdclass = { 'test': TestCommand, 'clean': CleanCommand },
        version = "0.98.00",
        description = "Biological Extensions to the InterMine WebService client",
        author = "Alex Kalderimis",
        author_email = "dev@intermine.org",
        url = "http://www.intermine.org",
        download_url = "http://www.intermine.org/lib/python-webservice-client-0.98.02.tar.gz",
        keywords = ["webservice", "genomic", "bioinformatics"],
        install_requires=["intermine"],
        classifiers = [
            "Programming Language :: Python",
            "Development Status :: 4 - Beta",
            "Intended Audience :: Science/Research",
            "Intended Audience :: Developers",
            "License :: OSI Approved :: GNU Library or Lesser General Public License (LGPL)",
            "Topic :: Software Development :: Libraries :: Python Modules",
            "Topic :: Internet :: WWW/HTTP",
            "Topic :: Scientific/Engineering :: Bio-Informatics",
            "Topic :: Scientific/Engineering :: Information Analysis",
            "Operating System :: OS Independent",
            ],
        license = "LGPL",
        long_description = """\
Biological Extensions to the InterMine Webservice Client
--------------------------------------------------------

Provides access routines to datawarehouses powered
by InterMine technology.

""",
)
<commit_msg>Version, and requirements<commit_after>"""
The test and clean code is shamelessly stolen from
http://da44en.wordpress.com/2002/11/22/using-distutils/
"""

from distutils.core import Command, setup
from distutils import log
from distutils.fancy_getopt import fancy_getopt
from unittest import TextTestRunner, TestLoader
from glob import glob
from os.path import splitext, basename, join as pjoin, walk
from warnings import warn
import os
import time

class TestCommand(Command):
    user_options = [('verbose', 'v', "produce verbose output", 1)]

    def initialize_options(self):
        self._dir = os.getcwd()

    def finalize_options(self):
        args, obj = fancy_getopt(self.user_options, {}, None, None)
        # Ugly as sin, but distutils forced me to do it :(
        # All I wanted was this command to default to quiet...
        if "--verbose" not in args and "-v" not in args:
            self.verbose = 0

    def run(self):
        '''
        Finds all the tests modules in tests/, and runs them, exiting after they are all done
        '''

        log.set_verbosity(self.verbose)

        testfiles = [ ]
        for t in glob(pjoin(self._dir, 'tests', 'test*.py')):
            if not t.endswith('__init__.py'):
                testfiles.append('.'.join(
                    ['tests', splitext(basename(t))[0]])
                )

        self.announce("Test files:" + str(testfiles), level=2)
        tests = TestLoader().loadTestsFromNames(testfiles)
        t = TextTestRunner(verbosity = self.verbose)
        t.run(tests)
        exit()

class CleanCommand(Command):
    """
    Remove all build files and all compiled files
    =============================================

    Remove everything from build, including that
    directory, and all .pyc files
    """
    user_options = [('verbose', 'v', "produce verbose output", 1)]

    def initialize_options(self):
        self._files_to_delete = [ ]
        self._dirs_to_delete = [ ]

        for root, dirs, files in os.walk('.'):
            for f in files:
                if f.endswith('.pyc') or f.endswith('.class'):
                    self._files_to_delete.append(pjoin(root, f))
        for root, dirs, files in os.walk(pjoin('build')):
            for f in files:
                self._files_to_delete.append(pjoin(root, f))
            for d in dirs:
                self._dirs_to_delete.append(pjoin(root, d))
        # reverse dir list to only get empty dirs
        self._dirs_to_delete.reverse()
        self._dirs_to_delete.append('build')

    def finalize_options(self):
        args, obj = fancy_getopt(self.user_options, {}, None, None)
        # Ugly as sin, but distutils forced me to do it :(
        # All I wanted was this command to default to quiet...
        if "--verbose" not in args and "-v" not in args:
            self.verbose = 0

    def run(self):
        for clean_me in self._files_to_delete:
            if self.dry_run:
                log.info("Would have unlinked " + clean_me)
            else:
                try:
                    self.announce("Deleting " + clean_me, level=2)
                    os.unlink(clean_me)
                except Exception, e:
                    message = " ".join(["Failed to delete file", clean_me, str(e)])
                    log.warn(message)
        for clean_me in self._dirs_to_delete:
            if self.dry_run:
                log.info("Would have rmdir'ed " + clean_me)
            else:
                if os.path.exists(clean_me):
                    try:
                        self.announce("Going to remove " + clean_me, level=2)
                        os.rmdir(clean_me)
                    except Exception, e:
                        message = " ".join(
                                ["Failed to delete dir", clean_me, str(e)])
                        log.warn(message)
                elif clean_me != "build":
                    log.warn(clean_me + " does not exist")

setup(
        name = "intermine-bio",
        packages = ["interminebio"],
        cmdclass = { 'test': TestCommand, 'clean': CleanCommand },
        version = "0.98.01",
        description = "Biological Extensions to the InterMine WebService client",
        author = "Alex Kalderimis",
        author_email = "dev@intermine.org",
        url = "http://www.intermine.org",
        download_url = "http://www.intermine.org/lib/python-webservice-client-0.98.02.tar.gz",
        keywords = ["webservice", "genomic", "bioinformatics"],
        requires=["intermine"],
        classifiers = [
            "Programming Language :: Python",
            "Development Status :: 4 - Beta",
            "Intended Audience :: Science/Research",
            "Intended Audience :: Developers",
            "License :: OSI Approved :: GNU Library or Lesser General Public License (LGPL)",
            "Topic :: Software Development :: Libraries :: Python Modules",
            "Topic :: Internet :: WWW/HTTP",
            "Topic :: Scientific/Engineering :: Bio-Informatics",
            "Topic :: Scientific/Engineering :: Information Analysis",
            "Operating System :: OS Independent",
            ],
        license = "LGPL",
        long_description = """\
Biological Extensions to the InterMine Webservice Client
--------------------------------------------------------

Provides access routines to datawarehouses powered
by InterMine technology.

""",
)
<|endoftext|>


<commit_before># Copyright 2014-2016 Therp BV <http://therp.nl>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
# pylint: disable=consider-merging-classes-inherited
from odoo import _, api, fields, models
from odoo.exceptions import UserError
from ..identifier_adapter import IdentifierAdapter

class CleanupPurgeLineColumn(models.TransientModel):
    _inherit = 'cleanup.purge.line'
    _name = 'cleanup.purge.line.column'
    _description = 'Purge Column Wizard Lines'

    model_id = fields.Many2one('ir.model', 'Model', required=True,
                               ondelete='CASCADE')
    wizard_id = fields.Many2one(
        'cleanup.purge.wizard.column', 'Purge Wizard', readonly=True)

    @api.multi
    def purge(self):
        """
        Unlink columns upon manual confirmation.
        """
        if self:
            objs = self
        else:
            objs = self.env['cleanup.purge.line.column']\
                .browse(self._context.get('active_ids'))
        for line in objs:
            if line.purged:
                continue
            model_pool = self.env[line.model_id.model]
            # Check whether the column actually still exists.
            # Inheritance such as stock.picking.in from stock.picking
            # can lead to double attempts at removal
            self.env.cr.execute(
                'SELECT count(attname) FROM pg_attribute '
                'WHERE attrelid = '
                '( SELECT oid FROM pg_class WHERE relname = %s ) '
                'AND attname = %s',
                (model_pool._table, line.name))
            if not self.env.cr.fetchone()[0]:
                continue

            self.logger.info(
                'Dropping column %s from table %s',
                line.name, model_pool._table)
            self.env.cr.execute(
                'ALTER TABLE %s DROP COLUMN %s',
                (
                    IdentifierAdapter(model_pool._table),
                    IdentifierAdapter(line.name)
                ))
            line.write({'purged': True})
            # we need this commit because the ORM will deadlock if
            # we still have a pending transaction
            self.env.cr.commit()  # pylint: disable=invalid-commit
        return True

class CleanupPurgeWizardColumn(models.TransientModel):
    _inherit = 'cleanup.purge.wizard'
    _name = 'cleanup.purge.wizard.column'
    _description = 'Purge columns'

    # List of known columns in use without corresponding fields
    # Format: {table: [fields]}
    blacklist = {
        'wkf_instance': ['uid'],  # lp:1277899
    }

    @api.model
    def get_orphaned_columns(self, model_pools):
        """
        From openobject-server/openerp/osv/orm.py
        Iterate on the database columns to identify columns
        of fields which have been removed
        """
        columns = list(set([
            column.name
            for model_pool in model_pools
            for column in model_pool._fields.values()
            if not (column.compute is not None and not column.store)
        ]))
        columns += models.MAGIC_COLUMNS
        columns += self.blacklist.get(model_pools[0]._table, [])

        self.env.cr.execute(
            "SELECT a.attname FROM pg_class c, pg_attribute a "
            "WHERE c.relname=%s AND c.oid=a.attrelid AND a.attisdropped=False "
            "AND pg_catalog.format_type(a.atttypid, a.atttypmod) "
            "NOT IN ('cid', 'tid', 'oid', 'xid') "
            "AND a.attname NOT IN %s",
            (model_pools[0]._table, tuple(columns)))
        return [column for column, in self.env.cr.fetchall()]

    @api.model
    def find(self):
        """
        Search for columns that are not in the corresponding model.

        Group models by table to prevent false positives for columns
        that are only in some of the models sharing the same table.
        Example of this is 'sale_id' not being a field of stock.picking.in
        """
        res = []

        # mapping of tables to tuples (model id, [pool1, pool2, ...])
        table2model = {}

        for model in self.env['ir.model'].search([]):
            if model.model not in self.env:
                continue
            model_pool = self.env[model.model]
            if not model_pool._auto:
                continue
            table2model.setdefault(
                model_pool._table, (model.id, [])
            )[1].append(model_pool)

        for table, model_spec in table2model.items():
            for column in self.get_orphaned_columns(model_spec[1]):
                res.append((0, 0, {
                            'name': column,
                            'model_id': model_spec[0]}))
        if not res:
            raise UserError(_('No orphaned columns found'))
        return res

    purge_line_ids = fields.One2many(
        'cleanup.purge.line.column', 'wizard_id', 'Columns to purge')
<commit_msg>[FIX] database_cleanup: exclude password fields<commit_after># Copyright 2014-2016 Therp BV <http://therp.nl>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
# pylint: disable=consider-merging-classes-inherited
from odoo import _, api, fields, models
from odoo.exceptions import UserError
from ..identifier_adapter import IdentifierAdapter

class CleanupPurgeLineColumn(models.TransientModel):
    _inherit = 'cleanup.purge.line'
    _name = 'cleanup.purge.line.column'
    _description = 'Purge Column Wizard Lines'

    model_id = fields.Many2one('ir.model', 'Model', required=True,
                               ondelete='CASCADE')
    wizard_id = fields.Many2one(
        'cleanup.purge.wizard.column', 'Purge Wizard', readonly=True)

    @api.multi
    def purge(self):
        """
        Unlink columns upon manual confirmation.
        """
        if self:
            objs = self
        else:
            objs = self.env['cleanup.purge.line.column']\
                .browse(self._context.get('active_ids'))
        for line in objs:
            if line.purged:
                continue
            model_pool = self.env[line.model_id.model]
            # Check whether the column actually still exists.
            # Inheritance such as stock.picking.in from stock.picking
            # can lead to double attempts at removal
            self.env.cr.execute(
                'SELECT count(attname) FROM pg_attribute '
                'WHERE attrelid = '
                '( SELECT oid FROM pg_class WHERE relname = %s ) '
                'AND attname = %s',
                (model_pool._table, line.name))
            if not self.env.cr.fetchone()[0]:
                continue

            self.logger.info(
                'Dropping column %s from table %s',
                line.name, model_pool._table)
            self.env.cr.execute(
                'ALTER TABLE %s DROP COLUMN %s',
                (
                    IdentifierAdapter(model_pool._table),
                    IdentifierAdapter(line.name)
                ))
            line.write({'purged': True})
            # we need this commit because the ORM will deadlock if
            # we still have a pending transaction
            self.env.cr.commit()  # pylint: disable=invalid-commit
        return True

class CleanupPurgeWizardColumn(models.TransientModel):
    _inherit = 'cleanup.purge.wizard'
    _name = 'cleanup.purge.wizard.column'
    _description = 'Purge columns'

    # List of known columns in use without corresponding fields
    # Format: {table: [fields]}
    blacklist = {
        'wkf_instance': ['uid'],  # lp:1277899
        'res_users': ['password', 'password_crypt'],
    }

    @api.model
    def get_orphaned_columns(self, model_pools):
        """
        From openobject-server/openerp/osv/orm.py
        Iterate on the database columns to identify columns
        of fields which have been removed
        """
        columns = list(set([
            column.name
            for model_pool in model_pools
            for column in model_pool._fields.values()
            if not (column.compute is not None and not column.store)
        ]))
        columns += models.MAGIC_COLUMNS
        columns += self.blacklist.get(model_pools[0]._table, [])

        self.env.cr.execute(
            "SELECT a.attname FROM pg_class c, pg_attribute a "
            "WHERE c.relname=%s AND c.oid=a.attrelid AND a.attisdropped=False "
            "AND pg_catalog.format_type(a.atttypid, a.atttypmod) "
            "NOT IN ('cid', 'tid', 'oid', 'xid') "
            "AND a.attname NOT IN %s",
            (model_pools[0]._table, tuple(columns)))
        return [column for column, in self.env.cr.fetchall()]

    @api.model
    def find(self):
        """
        Search for columns that are not in the corresponding model.

        Group models by table to prevent false positives for columns
        that are only in some of the models sharing the same table.
        Example of this is 'sale_id' not being a field of stock.picking.in
        """
        res = []

        # mapping of tables to tuples (model id, [pool1, pool2, ...])
        table2model = {}

        for model in self.env['ir.model'].search([]):
            if model.model not in self.env:
                continue
            model_pool = self.env[model.model]
            if not model_pool._auto:
                continue
            table2model.setdefault(
                model_pool._table, (model.id, [])
            )[1].append(model_pool)

        for table, model_spec in table2model.items():
            for column in self.get_orphaned_columns(model_spec[1]):
                res.append((0, 0, {
                            'name': column,
                            'model_id': model_spec[0]}))
        if not res:
            raise UserError(_('No orphaned columns found'))
        return res

    purge_line_ids = fields.One2many(
        'cleanup.purge.line.column', 'wizard_id', 'Columns to purge')
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
from django.shortcuts import render
from django.core.urlresolvers import reverse
from django.views.generic.base import TemplateView
from django.views.generic.edit import CreateView
from django.conf import settings

from paypal.standard.forms import PayPalPaymentsForm
from braces.views import LoginRequiredMixin

from .models import (Plans, UserPlanData, PaymentMethods)
from accounts.models import TimtecUser

from django.forms import ModelForm

from paypal.standard.ipn.signals import (payment_was_successful, subscription_signup,
                        payment_was_flagged, payment_was_refunded,
                        payment_was_reversed)
from django.core.mail import send_mail

class AccountPaymentView(LoginRequiredMixin, TemplateView):
    template_name = "payment.html"
    context_object_name = 'context'
    base_url = "https://escolamupi.com.br"

    if settings.DEBUG:
        base_url = "http://localhost:8000"

    def get(self, request, **kwargs):
        # Se chegou aqui, o cara tem plano, entao, vamo renderizar o que ele
        # pode usar pra pagar:
        # ~~Get all possible providers~~ In context
        # Create forms for each provider
        # Render to response

        ## por enquanto, so paypal

        return super(AccountPaymentView,
                        self).get(request, **kwargs)

    def get_context_data(self, **kwargs):
        context = super(AccountPaymentView, self).get_context_data(**kwargs)
        upd = UserPlanData.objects.get(user=self.request.user)
        pm_list = PaymentMethods.objects.filter(plans=upd.plan)

        ## For each payment method, creates payment form. For now, just paypal

        import ast
        for pm in pm_list:
            # TODO: test payment_method type. (for now, all paypal)
            # make the form creation a function for each payment type
            try:
                data = ast.literal_eval(pm.data)
            except:
                pass
            else:
                pm.data = data
                u = self.request.user

                pm.data['custom'] = "user_mail=" + u.email + "&user_id=" + str(u.id)
                pm.data['notify_url'] = settings.SITE_URL + reverse('paypal-ipn')
                pm.data['return_url'] = settings.SITE_URL + "/my-courses/"
                pm.data['cancel_return'] = settings.SITE_URL + "/accounts/payment"
                pm.data['business'] = settings.PAYPAL_RECEIVER_EMAIL

                form = PayPalPaymentsForm(initial=pm.data)

                if settings.DEBUG:
                    context = { "form" : form.sandbox(), }
                    pm.form = form.sandbox()
                else:
                    context = { "form" : form.sandbox(), }
                    pm.form = form.sandbox()

        context['payment_methods'] = pm_list
        return context

    def dispatch(self, *args, **kwargs):
        from django.shortcuts import redirect
        try:
            upd = UserPlanData.objects.get(user_id=self.request.user.id)
        except:
            return redirect('/accounts/plans', *args, **kwargs)
        else:
            if upd.user_status:
                return redirect('/my-courses', *args, **kwargs)
            else:
                return super(AccountPaymentView,
                        self).dispatch(*args, **kwargs)

class PlansView(LoginRequiredMixin, CreateView):
    template_name = "plans.html"
    model = UserPlanData
    fields = ['plan']
    success_url = '/accounts/payment'

    def get_context_data(self, **kwargs):
        context = super(PlansView, self).get_context_data(**kwargs)
        plans = Plans.objects.all()
        context['plans'] = plans
        return context

    def form_valid(self, form):
        from datetime import datetime
        import time

        dt = datetime.now()
        p = Plans.objects.get(id=form.data["plan"])
        dt = datetime.fromtimestamp(int(time.mktime(dt.timetuple()))
                        + p.period)
        form.instance.user_id = self.request.user.id
        form.instance.expiration_date = dt
        form.instance.user_status = False

        return super(PlansView, self).form_valid(form)

    def dispatch(self, *args, **kwargs):
        try:
            upd = UserPlanData.objects.get(user_id=self.request.user.id)
        except:
            pass
        else:
            from django.shortcuts import redirect
            if upd.user_status:
                return redirect('/my-courses', *args, **kwargs)
            else:
                return redirect('/accounts/payment', *args, **kwargs)

        return super(PlansView, self).dispatch(*args, **kwargs)

def paypal_signal_was_successful(sender, **kwargs):
    # Verify if the message is from paypal
    # https://www.paypal.com/cgi-bin/webscr?cmd=_notify-validate&mc_gross=19.95&protection_eligibility=Eligible
    # if yes, it will return VERIFIED

    # Verify if the message does not exist already txn_id = 61E67681CH3238416

    send_mail("Uepa", "=)", "contato@mupi.me", ["virgilio.santos@gmail.com"])
    from urlparse import parse_qs
    custom = parse_qs(sender.custom)
    print custom
    print sender.txn_type + " -- " + custom['user_id'][0] + " -- " + custom['user_mail'][0]
    user = TimtecUser.objects.get(id=custom['user_id'][0])
    print user.email + "--" + custom['user_mail'][0]
    if sender.payment_status == "Completed":
        user.is_staff = True
        user.save()

def paypal_signal_subscription_signup(sender, **kwargs):
    print 'oe'
    send_mail("Uepa subscription!", "=)", "contato@mupi.me", ["virgilio.santos@gmail.com"])

payment_was_successful.connect(paypal_signal_was_successful)
subscription_signup.connect(paypal_signal_subscription_signup)
payment_was_flagged.connect(paypal_signal_was_successful)
#payment_was_refunded.connect(paypal_signal_was_successful)
#payment_was_reversed.connect(paypal_signal_was_successful)

<commit_msg>Payment: improving payment emails and logic<commit_after># -*- coding: utf-8 -*-
from django.shortcuts import render
from django.core.urlresolvers import reverse
from django.views.generic.base import TemplateView
from django.views.generic.edit import CreateView
from django.conf import settings

from paypal.standard.forms import PayPalPaymentsForm
from braces.views import LoginRequiredMixin

from .models import (Plans, UserPlanData, PaymentMethods)
from accounts.models import TimtecUser

from django.forms import ModelForm

from paypal.standard.ipn.signals import (payment_was_successful, subscription_signup,
                        payment_was_flagged, payment_was_refunded,
                        payment_was_reversed)
from django.core.mail import send_mail

class AccountPaymentView(LoginRequiredMixin, TemplateView):
    template_name = "payment.html"
    context_object_name = 'context'
    base_url = "https://escolamupi.com.br"

    if settings.DEBUG:
        base_url = "http://localhost:8000"

    def get(self, request, **kwargs):
        # Se chegou aqui, o cara tem plano, entao, vamo renderizar o que ele
        # pode usar pra pagar:
        # ~~Get all possible providers~~ In context
        # Create forms for each provider
        # Render to response

        ## por enquanto, so paypal

        return super(AccountPaymentView,
                        self).get(request, **kwargs)

    def get_context_data(self, **kwargs):
        context = super(AccountPaymentView, self).get_context_data(**kwargs)
        upd = UserPlanData.objects.get(user=self.request.user)
        pm_list = PaymentMethods.objects.filter(plans=upd.plan)

        ## For each payment method, creates payment form. For now, just paypal

        import ast
        for pm in pm_list:
            # TODO: test payment_method type. (for now, all paypal)
            # make the form creation a function for each payment type
            try:
                data = ast.literal_eval(pm.data)
            except:
                pass
            else:
                pm.data = data
                u = self.request.user

                pm.data['custom'] = "user_mail=" + u.email + "&user_id=" + str(u.id)
                pm.data['notify_url'] = settings.SITE_URL + reverse('paypal-ipn')
                pm.data['return_url'] = settings.SITE_URL + "/my-courses/"
                pm.data['cancel_return'] = settings.SITE_URL + "/accounts/payment"
                pm.data['business'] = settings.PAYPAL_RECEIVER_EMAIL

                form = PayPalPaymentsForm(initial=pm.data)

                if settings.DEBUG:
                    context = { "form" : form.sandbox(), }
                    pm.form = form.sandbox()
                else:
                    context = { "form" : form.sandbox(), }
                    pm.form = form.sandbox()

        context['payment_methods'] = pm_list
        return context

    def dispatch(self, *args, **kwargs):
        from django.shortcuts import redirect
        try:
            upd = UserPlanData.objects.get(user_id=self.request.user.id)
        except:
            return redirect('/accounts/plans', *args, **kwargs)
        else:
            if upd.user_status:
                return redirect('/my-courses', *args, **kwargs)
            else:
                return super(AccountPaymentView,
                        self).dispatch(*args, **kwargs)

class PlansView(LoginRequiredMixin, CreateView):
    template_name = "plans.html"
    model = UserPlanData
    fields = ['plan']
    success_url = '/accounts/payment'

    def get_context_data(self, **kwargs):
        context = super(PlansView, self).get_context_data(**kwargs)
        plans = Plans.objects.all()
        context['plans'] = plans
        return context

    def form_valid(self, form):
        from datetime import datetime
        import time

        dt = datetime.now()
        p = Plans.objects.get(id=form.data["plan"])
        dt = datetime.fromtimestamp(int(time.mktime(dt.timetuple()))
                        + p.period)
        form.instance.user_id = self.request.user.id
        form.instance.expiration_date = dt
        form.instance.user_status = False

        return super(PlansView, self).form_valid(form)

    def dispatch(self, *args, **kwargs):
        try:
            upd = UserPlanData.objects.get(user_id=self.request.user.id)
        except:
            pass
        else:
            from django.shortcuts import redirect
            if upd.user_status:
                return redirect('/my-courses', *args, **kwargs)
            else:
                return redirect('/accounts/payment', *args, **kwargs)

        return super(PlansView, self).dispatch(*args, **kwargs)

def paypal_signal_was_successful(sender, **kwargs):
    # Verify if the message is from paypal
    # https://www.paypal.com/cgi-bin/webscr?cmd=_notify-validate&mc_gross=19.95&protection_eligibility=Eligible
    # if yes, it will return VERIFIED

    # Verify if the message does not exist already txn_id = 61E67681CH3238416

    if sender.payment_status == "Completed":
        from urlparse import parse_qs

        custom = parse_qs(sender.custom)
        user = TimtecUser.objects.get(id=custom['user_id'][0])

        message = " \
                    O usuario " + user.username + " realizou pagamento \
                    do tipo: " + str(sender.txn_type) + " \
                  "

        send_mail("[Mupi] Pagamento Realizado",
                    message,
                    "contato@mupi.me", ["virgilio.santos@gmail.com"])

        from payments.models import UserPlanData
        upd = UserPlanData.objects.get(user=user)

        upd.user_status = True
        upd.save()

def paypal_signal_subscription_signup(sender, **kwargs):
    custom = parse_qs(sender.custom)
    user = TimtecUser.objects.get(id=custom['user_id'][0])

    message = " \
                    O usuario " + user() + " realizou pagamento \
                    do tipo: " + str(sender.txn_type) + " \
                  "
    send_mail("[Mupi] Nova assinatura",
                message, "contato@mupi.me", ["virgilio.santos@gmail.com"])

payment_was_successful.connect(paypal_signal_was_successful)
subscription_signup.connect(paypal_signal_subscription_signup)
payment_was_flagged.connect(paypal_signal_was_successful)
#payment_was_refunded.connect(paypal_signal_was_successful)
#payment_was_reversed.connect(paypal_signal_was_successful)

<|endoftext|>


<commit_before>{
  'variables': {
    # The libraries brightray will be compiled to.
    'linux_system_libraries': 'gtk+-2.0 libnotify dbus-1 x11 xi xcursor xdamage xrandr xcomposite xext xfixes xrender xtst gconf-2.0 gmodule-2.0 nss'
  },
  'includes': [
    'filenames.gypi',
  ],
  'targets': [
    {
      'target_name': 'brightray',
      'type': 'static_library',
      'include_dirs': [
        '.',
        '<(libchromiumcontent_src_dir)',
        '<(libchromiumcontent_src_dir)/skia/config',
        '<(libchromiumcontent_src_dir)/third_party/skia/include/core',
        '<(libchromiumcontent_src_dir)/third_party/mojo/src',
        '<(libchromiumcontent_src_dir)/third_party/WebKit',
        '<(libchromiumcontent_dir)/gen',
      ],
      'direct_dependent_settings': {
        'include_dirs': [
          '.',
          '..',
          '<(libchromiumcontent_src_dir)',
          '<(libchromiumcontent_src_dir)/skia/config',
          '<(libchromiumcontent_src_dir)/third_party/skia/include/core',
          '<(libchromiumcontent_src_dir)/third_party/icu/source/common',
          '<(libchromiumcontent_src_dir)/third_party/mojo/src',
          '<(libchromiumcontent_src_dir)/third_party/WebKit',
          '<(libchromiumcontent_dir)/gen',
        ],
      },
      'sources': [ '<@(brightray_sources)' ],
      'conditions': [
        # Link with libraries of libchromiumcontent.
        ['OS=="linux" and libchromiumcontent_component==0', {
          # On Linux we have to use "--whole-archive" to force executable
          # to include all symbols, otherwise we will have plenty of
          # unresolved symbols errors.
          'direct_dependent_settings': {
            'ldflags': [
              '-Wl,--whole-archive',
              '<@(libchromiumcontent_libraries)',
              '-Wl,--no-whole-archive',
            ],
          }
        }, {  # (Release build on Linux)
          'link_settings': {
            'libraries': [ '<@(libchromiumcontent_libraries)' ]
          },
        }],  # (Normal builds)
        # Linux specific link settings.
        ['OS=="linux"', {
          'link_settings': {
            'ldflags': [
              '<!@(pkg-config --libs-only-L --libs-only-other <(linux_system_libraries))',
            ],
            'libraries': [
              '-lpthread',
              '<!@(pkg-config --libs-only-l <(linux_system_libraries))',
            ],
          },
          'cflags': [
            '<!@(pkg-config --cflags <(linux_system_libraries))',
            # Needed by using libgtk2ui:
            '-Wno-deprecated-register',
            '-Wno-sentinel',
          ],
          'cflags_cc': [
            '-Wno-reserved-user-defined-literal',
          ],
          'direct_dependent_settings': {
            'cflags': [
              '<!@(pkg-config --cflags <(linux_system_libraries))',
              '-Wno-deprecated-register',
              '-Wno-sentinel',
            ],
          },
          'conditions': [
            ['libchromiumcontent_component', {
              'link_settings': {
                'libraries': [
                  # Following libraries are always linked statically.
                  '<(libchromiumcontent_dir)/libgtk2ui.a',
                  '<(libchromiumcontent_dir)/libdevtools_discovery.a',
                  '<(libchromiumcontent_dir)/libdevtools_http_handler.a',
                  '<(libchromiumcontent_dir)/libhttp_server.a',
                  '<(libchromiumcontent_dir)/libdesktop_capture.a',
                  '<(libchromiumcontent_dir)/libdesktop_capture_differ_sse2.a',
                  '<(libchromiumcontent_dir)/libsystem_wrappers.a',
                  '<(libchromiumcontent_dir)/librtc_base.a',
                  '<(libchromiumcontent_dir)/librtc_base_approved.a',
                  '<(libchromiumcontent_dir)/libwebrtc_common.a',
                  '<(libchromiumcontent_dir)/libyuv.a',
                  '<(libchromiumcontent_dir)/libcdm_renderer.a',
                  '<(libchromiumcontent_dir)/libcomponent_updater.a',
                ],
              },
            }, {
              'link_settings': {
                'libraries': [
                  # Following libraries are required by libchromiumcontent:
                  '-lasound',
                  '-lcap',
                  '-lcups',
                  '-lrt',
                  '-ldl',
                  '-lresolv',
                  '-lfontconfig',
                  '-lfreetype',
                  '-lexpat',
                ],
              },
            }],
            ['target_arch=="arm"', {
              'link_settings': {
                'libraries': [
                  '<(libchromiumcontent_dir)/libyuv_neon.a',
                ],
                'libraries!': [
                  '<(libchromiumcontent_dir)/libdesktop_capture_differ_sse2.a',
                ],
              },
            }],
          ],
        }],  # OS=="linux"
        ['OS=="mac"', {
          'link_settings': {
            'libraries': [
              '$(SDKROOT)/System/Library/Frameworks/AppKit.framework',
              # Required by webrtc:
              '$(SDKROOT)/System/Library/Frameworks/OpenGL.framework',
              '$(SDKROOT)/System/Library/Frameworks/IOKit.framework',
            ],
          },
          'conditions':  [
            ['libchromiumcontent_component', {
              'link_settings': {
                'libraries': [
                  # Following libraries are always linked statically.
                  '<(libchromiumcontent_dir)/libdevtools_discovery.a',
                  '<(libchromiumcontent_dir)/libdevtools_http_handler.a',
                  '<(libchromiumcontent_dir)/libhttp_server.a',
                  '<(libchromiumcontent_dir)/libdesktop_capture.a',
                  '<(libchromiumcontent_dir)/libdesktop_capture_differ_sse2.a',
                  '<(libchromiumcontent_dir)/librtc_base.a',
                  '<(libchromiumcontent_dir)/librtc_base_approved.a',
                  '<(libchromiumcontent_dir)/libsystem_wrappers.a',
                  '<(libchromiumcontent_dir)/libwebrtc_common.a',
                  '<(libchromiumcontent_dir)/libyuv.a',
                  '<(libchromiumcontent_dir)/libcdm_renderer.a',
                  '<(libchromiumcontent_dir)/libcomponent_updater.a',
                ],
              },
            }, {
              'link_settings': {
                'libraries': [
                  # Link with system frameworks.
                  # ui_base.gypi:
                  '$(SDKROOT)/System/Library/Frameworks/Accelerate.framework',
                  # net.gypi:
                  '$(SDKROOT)/System/Library/Frameworks/Foundation.framework',
                  '$(SDKROOT)/System/Library/Frameworks/Security.framework',
                  '$(SDKROOT)/System/Library/Frameworks/SystemConfiguration.framework',
                  '-lresolv',
                  # media.gyp:
                  '$(SDKROOT)/System/Library/Frameworks/AudioToolbox.framework',
                  '$(SDKROOT)/System/Library/Frameworks/AudioUnit.framework',
                  '$(SDKROOT)/System/Library/Frameworks/CoreAudio.framework',
                  '$(SDKROOT)/System/Library/Frameworks/CoreMIDI.framework',
                  '$(SDKROOT)/System/Library/Frameworks/CoreVideo.framework',
                  # surface.gyp:
                  '$(SDKROOT)/System/Library/Frameworks/IOSurface.framework',
                  # content_common.gypi:
                  '$(SDKROOT)/System/Library/Frameworks/QuartzCore.framework',
                  # base.gyp:
                  '$(SDKROOT)/System/Library/Frameworks/ApplicationServices.framework',
                  '$(SDKROOT)/System/Library/Frameworks/Carbon.framework',
                  '$(SDKROOT)/System/Library/Frameworks/CoreFoundation.framework',
                  # content_browser.gypi:
                  '-lbsm',
                  # content_common.gypi:
                  '-lsandbox',
                  # bluetooth.gyp:
                  '$(SDKROOT)/System/Library/Frameworks/IOBluetooth.framework',
                ],
              },
            }],
          ]
        }],  # OS=="mac"
        ['OS=="win"', {
          'conditions': [
            ['libchromiumcontent_component', {
              # sandbox, base_static, devtools_discovery, devtools_http_handler,
              # http_server are always linked statically.
              'link_settings': {
                'libraries': [
                  '<(libchromiumcontent_dir)/base_static.lib',
                  '<(libchromiumcontent_dir)/sandbox.lib',
                  '<(libchromiumcontent_dir)/devtools_discovery.lib',
                  '<(libchromiumcontent_dir)/devtools_http_handler.lib',
                  '<(libchromiumcontent_dir)/http_server.lib',
                  '<(libchromiumcontent_dir)/desktop_capture.lib',
                  '<(libchromiumcontent_dir)/desktop_capture_differ_sse2.lib',
                  '<(libchromiumcontent_dir)/rtc_base.lib',
                  '<(libchromiumcontent_dir)/rtc_base_approved.lib',
                  '<(libchromiumcontent_dir)/system_wrappers.lib',
                  '<(libchromiumcontent_dir)/webrtc_common.lib',
                  '<(libchromiumcontent_dir)/libyuv.lib',
                  '<(libchromiumcontent_dir)/cdm_renderer.lib',
                  '<(libchromiumcontent_dir)/component_updater.lib',
                ],
              },
            }, {
              # Link with system libraries.
              'link_settings': {
                'libraries': [
                  # content_browser.gypi:
                  '-lsensorsapi.lib',
                  '-lportabledeviceguids.lib',
                  # content_common.gypi:
                  '-ld3d9.lib',
                  '-ld3d11.lib',
                  '-ldxva2.lib',
                  '-lstrmiids.lib',
                  '-lmf.lib',
                  '-lmfplat.lib',
                  '-lmfuuid.lib',
                  # media.gyp:
                  '-lmfreadwrite.lib',
                ],
                'msvs_settings': {
                  'VCLinkerTool': {
                    'AdditionalDependencies': [
                      'advapi32.lib',
                      'dbghelp.lib',
                      'delayimp.lib',
                      'dwmapi.lib',
                      'gdi32.lib',
                      'netapi32.lib',
                      'oleacc.lib',
                      'powrprof.lib',
                      'user32.lib',
                      'usp10.lib',
                      'version.lib',
                      'winspool.lib',
                    ],
                    'DelayLoadDLLs': [
                      # content_common.gypi:
                      'd3d9.dll',
                      'dxva2.dll',
                      # media.gyp:
                      'mf.dll',
                      'mfplat.dll',
                      'mfreadwrite.dll',
                      # bluetooth.gyp:
                      'BluetoothApis.dll',
                      'Bthprops.cpl',
                      'setupapi.dll',
                      # windows runtime
                      'API-MS-WIN-CORE-WINRT-L1-1-0.DLL',
                      'API-MS-WIN-CORE-WINRT-STRING-L1-1-0.DLL',
                    ],
                  },
                },
              },
            }],  # libchromiumcontent_component
          ],
        }],  # OS=="win"
      ],
    },
  ],
}
<commit_msg>componenet_updater is not needed<commit_after>{
  'variables': {
    # The libraries brightray will be compiled to.
    'linux_system_libraries': 'gtk+-2.0 libnotify dbus-1 x11 xi xcursor xdamage xrandr xcomposite xext xfixes xrender xtst gconf-2.0 gmodule-2.0 nss'
  },
  'includes': [
    'filenames.gypi',
  ],
  'targets': [
    {
      'target_name': 'brightray',
      'type': 'static_library',
      'include_dirs': [
        '.',
        '<(libchromiumcontent_src_dir)',
        '<(libchromiumcontent_src_dir)/skia/config',
        '<(libchromiumcontent_src_dir)/third_party/skia/include/core',
        '<(libchromiumcontent_src_dir)/third_party/mojo/src',
        '<(libchromiumcontent_src_dir)/third_party/WebKit',
        '<(libchromiumcontent_dir)/gen',
      ],
      'direct_dependent_settings': {
        'include_dirs': [
          '.',
          '..',
          '<(libchromiumcontent_src_dir)',
          '<(libchromiumcontent_src_dir)/skia/config',
          '<(libchromiumcontent_src_dir)/third_party/skia/include/core',
          '<(libchromiumcontent_src_dir)/third_party/icu/source/common',
          '<(libchromiumcontent_src_dir)/third_party/mojo/src',
          '<(libchromiumcontent_src_dir)/third_party/WebKit',
          '<(libchromiumcontent_dir)/gen',
        ],
      },
      'sources': [ '<@(brightray_sources)' ],
      'conditions': [
        # Link with libraries of libchromiumcontent.
        ['OS=="linux" and libchromiumcontent_component==0', {
          # On Linux we have to use "--whole-archive" to force executable
          # to include all symbols, otherwise we will have plenty of
          # unresolved symbols errors.
          'direct_dependent_settings': {
            'ldflags': [
              '-Wl,--whole-archive',
              '<@(libchromiumcontent_libraries)',
              '-Wl,--no-whole-archive',
            ],
          }
        }, {  # (Release build on Linux)
          'link_settings': {
            'libraries': [ '<@(libchromiumcontent_libraries)' ]
          },
        }],  # (Normal builds)
        # Linux specific link settings.
        ['OS=="linux"', {
          'link_settings': {
            'ldflags': [
              '<!@(pkg-config --libs-only-L --libs-only-other <(linux_system_libraries))',
            ],
            'libraries': [
              '-lpthread',
              '<!@(pkg-config --libs-only-l <(linux_system_libraries))',
            ],
          },
          'cflags': [
            '<!@(pkg-config --cflags <(linux_system_libraries))',
            # Needed by using libgtk2ui:
            '-Wno-deprecated-register',
            '-Wno-sentinel',
          ],
          'cflags_cc': [
            '-Wno-reserved-user-defined-literal',
          ],
          'direct_dependent_settings': {
            'cflags': [
              '<!@(pkg-config --cflags <(linux_system_libraries))',
              '-Wno-deprecated-register',
              '-Wno-sentinel',
            ],
          },
          'conditions': [
            ['libchromiumcontent_component', {
              'link_settings': {
                'libraries': [
                  # Following libraries are always linked statically.
                  '<(libchromiumcontent_dir)/libgtk2ui.a',
                  '<(libchromiumcontent_dir)/libdevtools_discovery.a',
                  '<(libchromiumcontent_dir)/libdevtools_http_handler.a',
                  '<(libchromiumcontent_dir)/libhttp_server.a',
                  '<(libchromiumcontent_dir)/libdesktop_capture.a',
                  '<(libchromiumcontent_dir)/libdesktop_capture_differ_sse2.a',
                  '<(libchromiumcontent_dir)/libsystem_wrappers.a',
                  '<(libchromiumcontent_dir)/librtc_base.a',
                  '<(libchromiumcontent_dir)/librtc_base_approved.a',
                  '<(libchromiumcontent_dir)/libwebrtc_common.a',
                  '<(libchromiumcontent_dir)/libyuv.a',
                  '<(libchromiumcontent_dir)/libcdm_renderer.a',
                ],
              },
            }, {
              'link_settings': {
                'libraries': [
                  # Following libraries are required by libchromiumcontent:
                  '-lasound',
                  '-lcap',
                  '-lcups',
                  '-lrt',
                  '-ldl',
                  '-lresolv',
                  '-lfontconfig',
                  '-lfreetype',
                  '-lexpat',
                ],
              },
            }],
            ['target_arch=="arm"', {
              'link_settings': {
                'libraries': [
                  '<(libchromiumcontent_dir)/libyuv_neon.a',
                ],
                'libraries!': [
                  '<(libchromiumcontent_dir)/libdesktop_capture_differ_sse2.a',
                ],
              },
            }],
          ],
        }],  # OS=="linux"
        ['OS=="mac"', {
          'link_settings': {
            'libraries': [
              '$(SDKROOT)/System/Library/Frameworks/AppKit.framework',
              # Required by webrtc:
              '$(SDKROOT)/System/Library/Frameworks/OpenGL.framework',
              '$(SDKROOT)/System/Library/Frameworks/IOKit.framework',
            ],
          },
          'conditions':  [
            ['libchromiumcontent_component', {
              'link_settings': {
                'libraries': [
                  # Following libraries are always linked statically.
                  '<(libchromiumcontent_dir)/libdevtools_discovery.a',
                  '<(libchromiumcontent_dir)/libdevtools_http_handler.a',
                  '<(libchromiumcontent_dir)/libhttp_server.a',
                  '<(libchromiumcontent_dir)/libdesktop_capture.a',
                  '<(libchromiumcontent_dir)/libdesktop_capture_differ_sse2.a',
                  '<(libchromiumcontent_dir)/librtc_base.a',
                  '<(libchromiumcontent_dir)/librtc_base_approved.a',
                  '<(libchromiumcontent_dir)/libsystem_wrappers.a',
                  '<(libchromiumcontent_dir)/libwebrtc_common.a',
                  '<(libchromiumcontent_dir)/libyuv.a',
                  '<(libchromiumcontent_dir)/libcdm_renderer.a',
                ],
              },
            }, {
              'link_settings': {
                'libraries': [
                  # Link with system frameworks.
                  # ui_base.gypi:
                  '$(SDKROOT)/System/Library/Frameworks/Accelerate.framework',
                  # net.gypi:
                  '$(SDKROOT)/System/Library/Frameworks/Foundation.framework',
                  '$(SDKROOT)/System/Library/Frameworks/Security.framework',
                  '$(SDKROOT)/System/Library/Frameworks/SystemConfiguration.framework',
                  '-lresolv',
                  # media.gyp:
                  '$(SDKROOT)/System/Library/Frameworks/AudioToolbox.framework',
                  '$(SDKROOT)/System/Library/Frameworks/AudioUnit.framework',
                  '$(SDKROOT)/System/Library/Frameworks/CoreAudio.framework',
                  '$(SDKROOT)/System/Library/Frameworks/CoreMIDI.framework',
                  '$(SDKROOT)/System/Library/Frameworks/CoreVideo.framework',
                  # surface.gyp:
                  '$(SDKROOT)/System/Library/Frameworks/IOSurface.framework',
                  # content_common.gypi:
                  '$(SDKROOT)/System/Library/Frameworks/QuartzCore.framework',
                  # base.gyp:
                  '$(SDKROOT)/System/Library/Frameworks/ApplicationServices.framework',
                  '$(SDKROOT)/System/Library/Frameworks/Carbon.framework',
                  '$(SDKROOT)/System/Library/Frameworks/CoreFoundation.framework',
                  # content_browser.gypi:
                  '-lbsm',
                  # content_common.gypi:
                  '-lsandbox',
                  # bluetooth.gyp:
                  '$(SDKROOT)/System/Library/Frameworks/IOBluetooth.framework',
                ],
              },
            }],
          ]
        }],  # OS=="mac"
        ['OS=="win"', {
          'conditions': [
            ['libchromiumcontent_component', {
              # sandbox, base_static, devtools_discovery, devtools_http_handler,
              # http_server are always linked statically.
              'link_settings': {
                'libraries': [
                  '<(libchromiumcontent_dir)/base_static.lib',
                  '<(libchromiumcontent_dir)/sandbox.lib',
                  '<(libchromiumcontent_dir)/devtools_discovery.lib',
                  '<(libchromiumcontent_dir)/devtools_http_handler.lib',
                  '<(libchromiumcontent_dir)/http_server.lib',
                  '<(libchromiumcontent_dir)/desktop_capture.lib',
                  '<(libchromiumcontent_dir)/desktop_capture_differ_sse2.lib',
                  '<(libchromiumcontent_dir)/rtc_base.lib',
                  '<(libchromiumcontent_dir)/rtc_base_approved.lib',
                  '<(libchromiumcontent_dir)/system_wrappers.lib',
                  '<(libchromiumcontent_dir)/webrtc_common.lib',
                  '<(libchromiumcontent_dir)/libyuv.lib',
                  '<(libchromiumcontent_dir)/cdm_renderer.lib',
                ],
              },
            }, {
              # Link with system libraries.
              'link_settings': {
                'libraries': [
                  # content_browser.gypi:
                  '-lsensorsapi.lib',
                  '-lportabledeviceguids.lib',
                  # content_common.gypi:
                  '-ld3d9.lib',
                  '-ld3d11.lib',
                  '-ldxva2.lib',
                  '-lstrmiids.lib',
                  '-lmf.lib',
                  '-lmfplat.lib',
                  '-lmfuuid.lib',
                  # media.gyp:
                  '-lmfreadwrite.lib',
                ],
                'msvs_settings': {
                  'VCLinkerTool': {
                    'AdditionalDependencies': [
                      'advapi32.lib',
                      'dbghelp.lib',
                      'delayimp.lib',
                      'dwmapi.lib',
                      'gdi32.lib',
                      'netapi32.lib',
                      'oleacc.lib',
                      'powrprof.lib',
                      'user32.lib',
                      'usp10.lib',
                      'version.lib',
                      'winspool.lib',
                    ],
                    'DelayLoadDLLs': [
                      # content_common.gypi:
                      'd3d9.dll',
                      'dxva2.dll',
                      # media.gyp:
                      'mf.dll',
                      'mfplat.dll',
                      'mfreadwrite.dll',
                      # bluetooth.gyp:
                      'BluetoothApis.dll',
                      'Bthprops.cpl',
                      'setupapi.dll',
                      # windows runtime
                      'API-MS-WIN-CORE-WINRT-L1-1-0.DLL',
                      'API-MS-WIN-CORE-WINRT-STRING-L1-1-0.DLL',
                    ],
                  },
                },
              },
            }],  # libchromiumcontent_component
          ],
        }],  # OS=="win"
      ],
    },
  ],
}
<|endoftext|>


<commit_before>from django import forms
from django.utils.translation import ugettext_lazy as _

class DynamicChoicesMixin(object):
    """Dynamic choices mixin.

    Add callable functionality to filters that support the ``choices``
    argument. If the ``choices`` is callable, then it **must** accept the
    ``view`` object as a single argument.
    The ``view`` object may be None if the parent FilterSet is not class based.

    This is useful for dymanic ``choices`` determined properties on the
    ``view`` object.
    """

    def __init__(self, *args, **kwargs):
        self.choices = kwargs.pop('choices')
        super().__init__(*args, **kwargs)

    def get_choices(self, view):
        choices = self.choices

        if callable(choices):
            return choices(view)
        return choices

    @property
    def field(self):
        choices = self.get_choices(getattr(self, 'view', None))

        if choices is not None:
            self.extra['choices'] = choices

        return super(DynamicChoicesMixin, self).field

class ImageRightOfUseMixin(forms.ModelForm):
    right_of_use = forms.BooleanField(required=False)

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        if self.instance.image:
            self.initial['right_of_use'] = True

    def clean(self):
        cleaned_data = super().clean()
        image = cleaned_data.get('image')
        right_of_use = cleaned_data.get('right_of_use')
        if image and not right_of_use:
            self.add_error('right_of_use',
                           _("You want to upload an image. "
                             "Please check that you have the "
                             "right of use for the image."))
<commit_msg>add label to chcekbox right_of_use<commit_after>from django import forms
from django.utils.translation import ugettext_lazy as _

RIGHT_OF_USE_LABEL = _('I hereby confirm that the copyrights for this '
                       'photo are with me or that I have received '
                       'rights of use from the author. I also confirm '
                       'that the privacy rights of depicted third persons '
                       'are not violated. ')

class DynamicChoicesMixin(object):
    """Dynamic choices mixin.

    Add callable functionality to filters that support the ``choices``
    argument. If the ``choices`` is callable, then it **must** accept the
    ``view`` object as a single argument.
    The ``view`` object may be None if the parent FilterSet is not class based.

    This is useful for dymanic ``choices`` determined properties on the
    ``view`` object.
    """

    def __init__(self, *args, **kwargs):
        self.choices = kwargs.pop('choices')
        super().__init__(*args, **kwargs)

    def get_choices(self, view):
        choices = self.choices

        if callable(choices):
            return choices(view)
        return choices

    @property
    def field(self):
        choices = self.get_choices(getattr(self, 'view', None))

        if choices is not None:
            self.extra['choices'] = choices

        return super(DynamicChoicesMixin, self).field

class ImageRightOfUseMixin(forms.ModelForm):
    right_of_use = forms.BooleanField(required=False, label=RIGHT_OF_USE_LABEL)

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        if self.instance.image:
            self.initial['right_of_use'] = True

    def clean(self):
        cleaned_data = super().clean()
        image = cleaned_data.get('image')
        right_of_use = cleaned_data.get('right_of_use')
        if image and not right_of_use:
            self.add_error('right_of_use',
                           _("You want to upload an image. "
                             "Please check that you have the "
                             "right of use for the image."))
<|endoftext|>