<commit_before>from pathlib import Path
from . import common

base_dir = Path(__file__).absolute().parent.parent.parent.parent

## to enable two-factor authentication:
#INSTALLED_APPS = common.INSTALLED_APPS + (
#    'hoover.contrib.twofactor',
#    'django_otp',
#    'django_otp.plugins.otp_totp',
#)
#MIDDLEWARE_CLASSES = common.MIDDLEWARE_CLASSES + (
#    'django_otp.middleware.OTPMiddleware',
#    'hoover.contrib.twofactor.middleware.AutoLogout',
#    'hoover.contrib.twofactor.middleware.RequireAuth',
#)

## to enable rate limiting for searches and downloads:
#INSTALLED_APPS = common.INSTALLED_APPS + (
#    'hoover.contrib.ratelimit',
#)

SECRET_KEY = 'something random'
DEBUG = True
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'hoover-search',
    },
}
STATIC_ROOT = str(base_dir / 'static')
HOOVER_UPLOADS_ROOT = str(base_dir / 'uploads')
HOOVER_ASSETS = common.cdn_assets
<commit_msg>set a bogus value for SECRET_KEY; no DEBUG<commit_after>from pathlib import Path
from . import common

base_dir = Path(__file__).absolute().parent.parent.parent.parent

## to enable two-factor authentication:
#INSTALLED_APPS = common.INSTALLED_APPS + (
#    'hoover.contrib.twofactor',
#    'django_otp',
#    'django_otp.plugins.otp_totp',
#)
#MIDDLEWARE_CLASSES = common.MIDDLEWARE_CLASSES + (
#    'django_otp.middleware.OTPMiddleware',
#    'hoover.contrib.twofactor.middleware.AutoLogout',
#    'hoover.contrib.twofactor.middleware.RequireAuth',
#)

## to enable rate limiting for searches and downloads:
#INSTALLED_APPS = common.INSTALLED_APPS + (
#    'hoover.contrib.ratelimit',
#)

SECRET_KEY = TODO_generate_random_string
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'hoover-search',
    },
}
STATIC_ROOT = str(base_dir / 'static')
HOOVER_UPLOADS_ROOT = str(base_dir / 'uploads')
HOOVER_ASSETS = common.cdn_assets
<|endoftext|>


<commit_before><commit_msg>Load exam order and question data<commit_after><|endoftext|>


<commit_before>from __future__ import print_function

import os
import sys
import json
import threading

THREADS_SUPPORTED = True
if sys.version_info[0] == 2:
	import urllib2 as urllib_error
	import urllib as urllib_request

	# Avoid threads on py2/win32. This will lockup HexChat
	if sys.platform == 'win32':
		THREADS_SUPPORTED = False
else:
	import urllib.error as urllib_error
	import urllib.request as urllib_request

import hexchat

__module_name__ = 'Script'
__module_author__ = 'TingPing'
__module_version__ = '6'
__module_description__ = 'Manage scripts'

# TODO:
# add preference for adding repos
# search subfolders
# command to refresh cache

script_help = """Script: Valid commands are:
        INSTALL script
        SEARCH word
        EDIT script
        UPDATE script
        REMOVE script"""

addon_dir = os.path.join(hexchat.get_info('configdir'), 'addons')
addon_types = ('py', 'pl', 'lua', 'js') # tcl has no way to unload a single script?
addon_cache = {}
#               User,       Repo,      Folder
addon_sites = (('TingPing', 'plugins', 'HexChat'),
				('Arnavion', 'random', 'hexchat'),
				('Farow', 'hexchat-scripts', ''))

def expand_script(script):
	return os.path.join(addon_dir, script)

def build_url(site, type='', script=''):
	if type == 'raw':
		return 'https://raw.github.com/{1}/{2}/master/{3}/{0}'.format(script, *site)
	elif type == 'api':
		return 'https://api.github.com/repos/{0}/{1}/contents/{2}'.format(*site)
	else:
		return 'https://github.com/{1}/{2}/tree/master/{3}/{0}'.format(script, *site)

def update_addons():
	global addon_cache
	addon_cache = {}

	for site in addon_sites:
		try:
			response = urllib_request.urlopen(build_url(site, type='api'))
			text = response.read().decode('utf-8')
			response.close()
			data = json.loads(text)
			addon_cache[site] = [d['name'] for d in data if d['name'].split('.')[-1] in addon_types]
		except urllib_error.HTTPError: # 403 after rate-limit
			pass

	print('Script: Addon cache updated.')

def download(script, unload):
	for site in addon_cache.keys():
		if script in addon_cache[site]:
			print('Script: Downloading {}...'.format(script))
			try:
				urllib_request.urlretrieve(build_url(site, type='raw', script=script), expand_script(script))
			except urllib_error.HTTPError as err:
				print('Script: Error downloading {} ({})'.format(script, err))
			else:
				print('Script: Download complete, {}...'.format('reloading' if unload else 'loading'))
				if unload: # Updated
					# Threading causes odd timing issues, using timer fixes it.
					hexchat.command('timer .1 unload {}'.format(expand_script(script)))
				hexchat.command('timer .1 load {}'.format(expand_script(script)))

			return

	print('Script: Could not find {}'.format(script))

def install(script, unload):
	if THREADS_SUPPORTED:
		threading.Thread(target=download, args=(script, unload)).start()
	else:
		download(script, unload)

def search(word):
	matches = [(site, script) for site in addon_cache.keys() for script in addon_cache[site] if word in script]

	if not matches:
		print('Script: {} not found.'.format(word))
	else:
		print('Script: {} matches found for {}.'.format(len(matches), word))
		for (site, script) in matches:
			print('\t\t{}: \00318\037{}\017'.format(script, build_url(site, type='', script=script)))

def script_cb(word, word_eol, userdata):
	if len(word) > 2:
		cmd = word[1].lower()
		arg = word[2]
	else:
		hexchat.command('help script')
		return hexchat.EAT_ALL

	if cmd == 'install':
		if os.path.exists(expand_script(arg)):
			print('Script: {} is already installed.'.format(arg))
			return hexchat.EAT_ALL
		else:
			install(arg, False)
	elif cmd == 'update':
		if os.path.exists(expand_script(arg)):
			install(arg, True)
	elif cmd == 'edit':
		if sys.platform.startswith('linux'):
			# This will popup a choose program prompt /url doesn't
			hexchat.command('exec -d gvfs-open {}'.format(expand_script(arg)))
		else:
			hexchat.command('url {}'.format(expand_script(arg)))
	elif cmd == 'search':
		search(arg)
	elif cmd == 'remove':
		if arg == 'script.py':
			print('Script: I refuse.')
			return hexchat.EAT_ALL
		if os.path.exists(expand_script(arg)):
			hexchat.command('unload ' + expand_script(arg))
			os.remove(expand_script(arg))
		else:
			print('Script: {} is not installed.'.format(arg))
	else:
		hexchat.command('help script')

	return hexchat.EAT_ALL

def unload_callback(userdata):
	print(__module_name__, 'version', __module_version__, 'unloaded.')

if THREADS_SUPPORTED:
	threading.Thread(target=update_addons).start()
else:
	update_addons()
hexchat.hook_command('script', script_cb, help=script_help)
hexchat.hook_unload(unload_callback)
print(__module_name__, 'version', __module_version__, 'loaded.')
<commit_msg>Update script.py<commit_after>from __future__ import print_function

import os
import sys
import json
import threading

THREADS_SUPPORTED = True
if sys.version_info[0] == 2:
	import urllib2 as urllib_error
	import urllib as urllib_request

	# Avoid threads on py2/win32. This will lockup HexChat
	if sys.platform == 'win32':
		THREADS_SUPPORTED = False
else:
	import urllib.error as urllib_error
	import urllib.request as urllib_request

import hexchat

__module_name__ = 'Script'
__module_author__ = 'TingPing'
__module_version__ = '6'
__module_description__ = 'Manage scripts'

# TODO:
# add preference for adding repos
# search subfolders
# command to refresh cache

script_help = """Script: Valid commands are:
        INSTALL script
        SEARCH word
        EDIT script
        UPDATE script
        REMOVE script"""

addon_dir = os.path.join(hexchat.get_info('configdir'), 'addons')
addon_types = ('py', 'pl', 'lua', 'js') # tcl has no way to unload a single script?
addon_cache = {}
#               User,       Repo,      Folder
addon_sites = (('TingPing', 'plugins', 'HexChat'),
				('Farow', 'hexchat-scripts', ''))

def expand_script(script):
	return os.path.join(addon_dir, script)

def build_url(site, type='', script=''):
	if type == 'raw':
		return 'https://raw.github.com/{1}/{2}/master/{3}/{0}'.format(script, *site)
	elif type == 'api':
		return 'https://api.github.com/repos/{0}/{1}/contents/{2}'.format(*site)
	else:
		return 'https://github.com/{1}/{2}/tree/master/{3}/{0}'.format(script, *site)

def update_addons():
	global addon_cache
	addon_cache = {}

	for site in addon_sites:
		try:
			response = urllib_request.urlopen(build_url(site, type='api'))
			text = response.read().decode('utf-8')
			response.close()
			data = json.loads(text)
			addon_cache[site] = [d['name'] for d in data if d['name'].split('.')[-1] in addon_types]
		except urllib_error.HTTPError: # 403 after rate-limit
			pass

	print('Script: Addon cache updated.')

def download(script, unload):
	for site in addon_cache.keys():
		if script in addon_cache[site]:
			print('Script: Downloading {}...'.format(script))
			try:
				urllib_request.urlretrieve(build_url(site, type='raw', script=script), expand_script(script))
			except urllib_error.HTTPError as err:
				print('Script: Error downloading {} ({})'.format(script, err))
			else:
				print('Script: Download complete, {}...'.format('reloading' if unload else 'loading'))
				if unload: # Updated
					# Threading causes odd timing issues, using timer fixes it.
					hexchat.command('timer .1 unload {}'.format(expand_script(script)))
				hexchat.command('timer .1 load {}'.format(expand_script(script)))

			return

	print('Script: Could not find {}'.format(script))

def install(script, unload):
	if THREADS_SUPPORTED:
		threading.Thread(target=download, args=(script, unload)).start()
	else:
		download(script, unload)

def search(word):
	matches = [(site, script) for site in addon_cache.keys() for script in addon_cache[site] if word in script]

	if not matches:
		print('Script: {} not found.'.format(word))
	else:
		print('Script: {} matches found for {}.'.format(len(matches), word))
		for (site, script) in matches:
			print('\t\t{}: \00318\037{}\017'.format(script, build_url(site, type='', script=script)))

def script_cb(word, word_eol, userdata):
	if len(word) > 2:
		cmd = word[1].lower()
		arg = word[2]
	else:
		hexchat.command('help script')
		return hexchat.EAT_ALL

	if cmd == 'install':
		if os.path.exists(expand_script(arg)):
			print('Script: {} is already installed.'.format(arg))
			return hexchat.EAT_ALL
		else:
			install(arg, False)
	elif cmd == 'update':
		if os.path.exists(expand_script(arg)):
			install(arg, True)
	elif cmd == 'edit':
		if sys.platform.startswith('linux'):
			# This will popup a choose program prompt /url doesn't
			hexchat.command('exec -d gvfs-open {}'.format(expand_script(arg)))
		else:
			hexchat.command('url {}'.format(expand_script(arg)))
	elif cmd == 'search':
		search(arg)
	elif cmd == 'remove':
		if arg == 'script.py':
			print('Script: I refuse.')
			return hexchat.EAT_ALL
		if os.path.exists(expand_script(arg)):
			hexchat.command('unload ' + expand_script(arg))
			os.remove(expand_script(arg))
		else:
			print('Script: {} is not installed.'.format(arg))
	else:
		hexchat.command('help script')

	return hexchat.EAT_ALL

def unload_callback(userdata):
	print(__module_name__, 'version', __module_version__, 'unloaded.')

if THREADS_SUPPORTED:
	threading.Thread(target=update_addons).start()
else:
	update_addons()
hexchat.hook_command('script', script_cb, help=script_help)
hexchat.hook_unload(unload_callback)
print(__module_name__, 'version', __module_version__, 'loaded.')
<|endoftext|>


<commit_before>#import _yaposib
from _yaposib import *

def vec(listOfPairs):
    vec = CoinPackedVector()
    for pair in listOfPairs:
        vec.insert(pair[0], pair[1])
    return vec

if __name__ == "__main__":
    """
    builds the following problem

    0  <= x <= 4
    -1 <= y <= 1
    0  <= z
    0  <= w

    minimize obj = x + 4*y + 9*z
    such that:
    c1: x+y <= 5
    c2: x+z >= 10
    c3: -y+z == 7
    c4: w >= 0
    """
    prob = Problem("Clp")

    prob.obj.name = "MyProblem"
    prob.obj.maximize = False
    # names
    for i in range(4):
        prob.cols.add(vec([]))
    prob.cols[0].name = "x"
    prob.cols[1].name = "y"
    prob.cols[2].name = "z"
    prob.cols[3].name = "w"
    # lowerbounds
    for col in prob.cols:
        col.lowerbound = 0
    prob.cols[1].lowerbound = -1
    # upperbounds
    prob.cols[0].upperbound = 4
    prob.cols[1].upperbound = 1
    # constraints
    prob.rows.add(vec([(0,1),(1,1)]))
    prob.rows.add(vec([(0,1),(2,1)]))
    prob.rows.add(vec([(1,-1),(2,1)]))
    prob.rows.add(vec([(3,1)]))
    # constraints bounds
    prob.rows[0].upperbound = 5
    prob.rows[1].lowerbound = 10
    prob.rows[2].lowerbound = 7
    prob.rows[2].upperbound = 7
    prob.rows[3].lowerbound = 0
    # constraints names
    prob.rows[0].name = "c1"
    prob.rows[1].name = "c2"
    prob.rows[2].name = "c3"
    prob.rows[3].name = "c4"

    # obj
    prob.obj[0] = 1
    prob.obj[1] = 4
    prob.obj[2] = 9

    prob.solve(False)

    for col in prob.cols:
        print "%s=%s" % (col.name, col.solution)

    print "ok"
<commit_msg>Made the test an explicit function<commit_after>#import _yaposib
from _yaposib import *

def vec(listOfPairs):
    vec = CoinPackedVector()
    for pair in listOfPairs:
        vec.insert(pair[0], pair[1])
    return vec

def test():
    """
    builds the following problem

    0  <= x <= 4
    -1 <= y <= 1
    0  <= z
    0  <= w

    minimize obj = x + 4*y + 9*z
    such that:
    c1: x+y <= 5
    c2: x+z >= 10
    c3: -y+z == 7
    c4: w >= 0
    """
    prob = Problem("Clp")

    prob.obj.name = "MyProblem"
    prob.obj.maximize = False
    # names
    for i in range(4):
        prob.cols.add(vec([]))
    prob.cols[0].name = "x"
    prob.cols[1].name = "y"
    prob.cols[2].name = "z"
    prob.cols[3].name = "w"
    # lowerbounds
    for col in prob.cols:
        col.lowerbound = 0
    prob.cols[1].lowerbound = -1
    # upperbounds
    prob.cols[0].upperbound = 4
    prob.cols[1].upperbound = 1
    # constraints
    prob.rows.add(vec([(0,1),(1,1)]))
    prob.rows.add(vec([(0,1),(2,1)]))
    prob.rows.add(vec([(1,-1),(2,1)]))
    prob.rows.add(vec([(3,1)]))
    # constraints bounds
    prob.rows[0].upperbound = 5
    prob.rows[1].lowerbound = 10
    prob.rows[2].lowerbound = 7
    prob.rows[2].upperbound = 7
    prob.rows[3].lowerbound = 0
    # constraints names
    prob.rows[0].name = "c1"
    prob.rows[1].name = "c2"
    prob.rows[2].name = "c3"
    prob.rows[3].name = "c4"

    # obj
    prob.obj[0] = 1
    prob.obj[1] = 4
    prob.obj[2] = 9

    prob.solve(False)

    for col in prob.cols:
        print "%s=%s" % (col.name, col.solution)

    print "ok"

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


<commit_before>"""
Helper functions.
"""

import os

from appdirs import user_data_dir
from tqdm import tqdm

APP_NAME = "QuiltCli"
APP_AUTHOR = "QuiltData"
BASE_DIR = user_data_dir(APP_NAME, APP_AUTHOR)

class FileWithReadProgress(object):
    """
    Acts like a file with mode='rb', but displays a progress bar while the file is read.
    """
    def __init__(self, path):
        self._fd = open(path, 'rb')
        self._progress = tqdm(
            total=os.path.getsize(path),
            unit='B',
            unit_scale=True
        )

    def read(self, size=None):
        """Read bytes and update the progress bar."""
        buf = self._fd.read(size)
        self._progress.update(len(buf))
        return buf

    def close(self):
        """Close the file and the progress bar."""
        self._progress.close()
        self._fd.close()

    def __enter__(self):
        return self

    def __exit__(self, type, value, traceback):
        self.close()

def file_to_str(fname):
    """
    Read a file into a string
    PRE: fname is a small file (to avoid hogging memory and its discontents)
    """
    data = None
    # rU = read with Universal line terminator
    with open(fname, 'rU') as f:
        data = f.read()
    return data
<commit_msg>Fix building packages in Python2 (#28)<commit_after>"""
Helper functions.
"""

import os

from appdirs import user_data_dir
from tqdm import tqdm

APP_NAME = "QuiltCli"
APP_AUTHOR = "QuiltData"
BASE_DIR = user_data_dir(APP_NAME, APP_AUTHOR)

class FileWithReadProgress(object):
    """
    Acts like a file with mode='rb', but displays a progress bar while the file is read.
    """
    def __init__(self, path):
        self._fd = open(path, 'rb')
        self._progress = tqdm(
            total=os.path.getsize(path),
            unit='B',
            unit_scale=True
        )

    def read(self, size=-1):
        """Read bytes and update the progress bar."""
        buf = self._fd.read(size)
        self._progress.update(len(buf))
        return buf

    def close(self):
        """Close the file and the progress bar."""
        self._progress.close()
        self._fd.close()

    def __enter__(self):
        return self

    def __exit__(self, type, value, traceback):
        self.close()

def file_to_str(fname):
    """
    Read a file into a string
    PRE: fname is a small file (to avoid hogging memory and its discontents)
    """
    data = None
    # rU = read with Universal line terminator
    with open(fname, 'rU') as f:
        data = f.read()
    return data
<|endoftext|>


<commit_before>import os
import dj_database_url

from django.core.exceptions import ImproperlyConfigured
from django.contrib.messages import constants as message_constants

def get_env_variable(var_name):
    """Get the environment variable or return exception"""
    try:
        var = os.environ[var_name]
        # Replace unix strings with Python Booleans
        if var == 'True':
            var = True
        if var == 'False':
            var = False
    except KeyError:
        error_msg = "Set the {var_name} env var".format(var_name=var_name)
        raise ImproperlyConfigured(error_msg)
    return var

DEBUG = get_env_variable("DEBUG")
TEMPLATE_DEBUG = DEBUG

# Globals
PROJECT_ROOT = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
PROJECT_NAME = 'barberscore'
USE_TZ = True
TIME_ZONE = get_env_variable("TZ")
LANGUAGE_CODE = 'en-us'
USE_I18N = False
USE_L10N = True
USE_TZ = True
SECRET_KEY = get_env_variable("SECRET_KEY")
ROOT_URLCONF = 'urls'
WSGI_APPLICATION = 'wsgi.application'
LOGIN_URL = 'website:login'
LOGOUT_URL = 'website:logout'
LOGIN_REDIRECT_URL = 'website:home'
DOMAIN = get_env_variable("DOMAIN")
STATICFILES_DIRS = ()
STATIC_URL = '/static/'
ADMINS = (
    (get_env_variable("FULL_NAME"), get_env_variable("USER_EMAIL")),
)
SERVER_EMAIL = get_env_variable('SERVER_EMAIL')

# Database
DATABASE_URL = get_env_variable("DATABASE_URL")
DATABASES = {'default': dj_database_url.config(default=DATABASE_URL)}

# Auth
AUTH_USER_MODEL = "api.User"
AUTHENTICATION_BACKENDS = (
    'django.contrib.auth.backends.ModelBackend',
)

# Middleware
MIDDLEWARE_CLASSES = (
    'corsheaders.middleware.CorsMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.security.SecurityMiddleware',
    # 'django.middleware.transaction.TransactionMiddleware',
)

# Templating
TEMPLATE_CONTEXT_PROCESSORS = (
    "django.contrib.auth.context_processors.auth",
    "django.core.context_processors.debug",
    "django.core.context_processors.i18n",
    "django.core.context_processors.media",
    "django.core.context_processors.static",
    "django.core.context_processors.tz",
    "django.contrib.messages.context_processors.messages",
    "django.core.context_processors.request",
)

# Bootstrap overwrite
MESSAGE_TAGS = {
    message_constants.ERROR: 'danger',
}

# Phonenumber support
PHONENUMBER_DEFAULT_REGION = 'US'
PHONENUMBER_DEFAULT_FORMAT = 'NATIONAL'

# Rest Framework (default)
# REST_FRAMEWORK = {
#     'DEFAULT_FILTER_BACKENDS': [
#         'apps.api.filters.CoalesceFilterBackend',
#     ],
#     'DEFAULT_AUTHENTICATION_CLASSES': [
#         'rest_framework.authentication.TokenAuthentication',
#         'rest_framework.authentication.BasicAuthentication',
#         'rest_framework.authentication.SessionAuthentication',
#     ],
#     'DEFAULT_PERMISSION_CLASSES': [
#         'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly',
#     ],
#     'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
#     'PAGE_SIZE': 100,
#     'DEFAULT_RENDERER_CLASSES': [
#         'rest_framework.renderers.JSONRenderer',
#         'rest_framework.renderers.BrowsableAPIRenderer',
#     ]
# }

# Rest Framework (JSONAPI)
REST_FRAMEWORK = {
    # DJA settings
    'PAGE_SIZE': 10,
    'EXCEPTION_HANDLER': 'rest_framework_json_api.exceptions.exception_handler',
    'DEFAULT_PAGINATION_CLASS':
        'rest_framework_json_api.pagination.PageNumberPagination',
    'DEFAULT_PARSER_CLASSES': (
        'rest_framework_json_api.parsers.JSONParser',
        'rest_framework.parsers.FormParser',
        'rest_framework.parsers.MultiPartParser'
    ),
    'DEFAULT_RENDERER_CLASSES': (
        'rest_framework_json_api.renderers.JSONRenderer',
        'rest_framework.renderers.BrowsableAPIRenderer',
    ),
    'DEFAULT_METADATA_CLASS': 'rest_framework_json_api.metadata.JSONAPIMetadata',
    # And other DRF settings
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework.authentication.TokenAuthentication',
        'rest_framework.authentication.BasicAuthentication',
        'rest_framework.authentication.SessionAuthentication',
    ],
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly',
    ],
}

# Plus supplementary settings:
JSON_API_FORMAT_KEYS = 'dasherize'
# JSON_API_FORMAT_RELATION_KEYS = 'dasherize'
# JSON_API_PLURALIZE_RELATION_TYPE = False
APPEND_TRAILING_SLASH = False

#  CORS Headers
CORS_ORIGIN_ALLOW_ALL = True

# Easy Select2
SELECT2_USE_BUNDLED_JQUERY = False

# Djoser
DJOSER = {
    'LOGIN_AFTER_REGISTRATION': True,
    'APPEND_USER_DATA': True,
}

# Haystack
# HAYSTACK_CONNECTIONS = {
#     'default': {
#         'ENGINE': 'haystack.backends.elasticsearch_backend.ElasticsearchSearchEngine',
#         'URL': 'http://127.0.0.1:9200',
#         'INDEX_NAME': 'haystack',
#     },
# }

# Grappelli
GRAPPELLI_ADMIN_TITLE = 'Barberscore Admin'
GRAPPELLI_AUTOCOMPLETE_LIMIT = 20
# GRAPPELLI_INDEX_DASHBOARD = 'dashboard.CustomIndexDashboard'

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'filters': {
        'require_debug_false': {
            '()': 'django.utils.log.RequireDebugFalse'
        }
    },
    'handlers': {
        'mail_admins': {
            'level': 'ERROR',
            'filters': ['require_debug_false'],
            'class': 'django.utils.log.AdminEmailHandler'
        }
    },
    'loggers': {
        'django.request': {
            'handlers': ['mail_admins'],
            'level': 'ERROR',
            'propagate': True,
        },
    }
}

# Applications
INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    # 'grappelli.dashboard',
    'super_inlines.grappelli_integration',
    'grappelli',
    'super_inlines',
    'django.contrib.admin',
    'django.contrib.admindocs',
    'django.contrib.humanize',
    'fsm_admin',
    'django_fsm',
    # 'django_fsm_log',
    # 'haystack',
    'easy_pdf',
    'timezone_field',
    'corsheaders',
    'mptt',
    'rest_framework',
    'rest_framework.authtoken',
    'apps.api',
    'apps.website',
)
<commit_msg>Disable pagination<commit_after>import os
import dj_database_url

from django.core.exceptions import ImproperlyConfigured
from django.contrib.messages import constants as message_constants

def get_env_variable(var_name):
    """Get the environment variable or return exception"""
    try:
        var = os.environ[var_name]
        # Replace unix strings with Python Booleans
        if var == 'True':
            var = True
        if var == 'False':
            var = False
    except KeyError:
        error_msg = "Set the {var_name} env var".format(var_name=var_name)
        raise ImproperlyConfigured(error_msg)
    return var

DEBUG = get_env_variable("DEBUG")
TEMPLATE_DEBUG = DEBUG

# Globals
PROJECT_ROOT = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
PROJECT_NAME = 'barberscore'
USE_TZ = True
TIME_ZONE = get_env_variable("TZ")
LANGUAGE_CODE = 'en-us'
USE_I18N = False
USE_L10N = True
USE_TZ = True
SECRET_KEY = get_env_variable("SECRET_KEY")
ROOT_URLCONF = 'urls'
WSGI_APPLICATION = 'wsgi.application'
LOGIN_URL = 'website:login'
LOGOUT_URL = 'website:logout'
LOGIN_REDIRECT_URL = 'website:home'
DOMAIN = get_env_variable("DOMAIN")
STATICFILES_DIRS = ()
STATIC_URL = '/static/'
ADMINS = (
    (get_env_variable("FULL_NAME"), get_env_variable("USER_EMAIL")),
)
SERVER_EMAIL = get_env_variable('SERVER_EMAIL')

# Database
DATABASE_URL = get_env_variable("DATABASE_URL")
DATABASES = {'default': dj_database_url.config(default=DATABASE_URL)}

# Auth
AUTH_USER_MODEL = "api.User"
AUTHENTICATION_BACKENDS = (
    'django.contrib.auth.backends.ModelBackend',
)

# Middleware
MIDDLEWARE_CLASSES = (
    'corsheaders.middleware.CorsMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.security.SecurityMiddleware',
    # 'django.middleware.transaction.TransactionMiddleware',
)

# Templating
TEMPLATE_CONTEXT_PROCESSORS = (
    "django.contrib.auth.context_processors.auth",
    "django.core.context_processors.debug",
    "django.core.context_processors.i18n",
    "django.core.context_processors.media",
    "django.core.context_processors.static",
    "django.core.context_processors.tz",
    "django.contrib.messages.context_processors.messages",
    "django.core.context_processors.request",
)

# Bootstrap overwrite
MESSAGE_TAGS = {
    message_constants.ERROR: 'danger',
}

# Phonenumber support
PHONENUMBER_DEFAULT_REGION = 'US'
PHONENUMBER_DEFAULT_FORMAT = 'NATIONAL'

# Rest Framework (default)
# REST_FRAMEWORK = {
#     'DEFAULT_FILTER_BACKENDS': [
#         'apps.api.filters.CoalesceFilterBackend',
#     ],
#     'DEFAULT_AUTHENTICATION_CLASSES': [
#         'rest_framework.authentication.TokenAuthentication',
#         'rest_framework.authentication.BasicAuthentication',
#         'rest_framework.authentication.SessionAuthentication',
#     ],
#     'DEFAULT_PERMISSION_CLASSES': [
#         'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly',
#     ],
#     'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
#     'PAGE_SIZE': 100,
#     'DEFAULT_RENDERER_CLASSES': [
#         'rest_framework.renderers.JSONRenderer',
#         'rest_framework.renderers.BrowsableAPIRenderer',
#     ]
# }

# Rest Framework (JSONAPI)
REST_FRAMEWORK = {
    # DJA settings
    # 'PAGE_SIZE': 10,
    'EXCEPTION_HANDLER': 'rest_framework_json_api.exceptions.exception_handler',
    'DEFAULT_PAGINATION_CLASS':
        'rest_framework_json_api.pagination.PageNumberPagination',
    'DEFAULT_PARSER_CLASSES': (
        'rest_framework_json_api.parsers.JSONParser',
        'rest_framework.parsers.FormParser',
        'rest_framework.parsers.MultiPartParser'
    ),
    'DEFAULT_RENDERER_CLASSES': (
        'rest_framework_json_api.renderers.JSONRenderer',
        'rest_framework.renderers.BrowsableAPIRenderer',
    ),
    'DEFAULT_METADATA_CLASS': 'rest_framework_json_api.metadata.JSONAPIMetadata',
    # And other DRF settings
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework.authentication.TokenAuthentication',
        'rest_framework.authentication.BasicAuthentication',
        'rest_framework.authentication.SessionAuthentication',
    ],
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly',
    ],
}

# Plus supplementary settings:
JSON_API_FORMAT_KEYS = 'dasherize'
# JSON_API_FORMAT_RELATION_KEYS = 'dasherize'
# JSON_API_PLURALIZE_RELATION_TYPE = False
APPEND_TRAILING_SLASH = False

#  CORS Headers
CORS_ORIGIN_ALLOW_ALL = True

# Easy Select2
SELECT2_USE_BUNDLED_JQUERY = False

# Djoser
DJOSER = {
    'LOGIN_AFTER_REGISTRATION': True,
    'APPEND_USER_DATA': True,
}

# Haystack
# HAYSTACK_CONNECTIONS = {
#     'default': {
#         'ENGINE': 'haystack.backends.elasticsearch_backend.ElasticsearchSearchEngine',
#         'URL': 'http://127.0.0.1:9200',
#         'INDEX_NAME': 'haystack',
#     },
# }

# Grappelli
GRAPPELLI_ADMIN_TITLE = 'Barberscore Admin'
GRAPPELLI_AUTOCOMPLETE_LIMIT = 20
# GRAPPELLI_INDEX_DASHBOARD = 'dashboard.CustomIndexDashboard'

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'filters': {
        'require_debug_false': {
            '()': 'django.utils.log.RequireDebugFalse'
        }
    },
    'handlers': {
        'mail_admins': {
            'level': 'ERROR',
            'filters': ['require_debug_false'],
            'class': 'django.utils.log.AdminEmailHandler'
        }
    },
    'loggers': {
        'django.request': {
            'handlers': ['mail_admins'],
            'level': 'ERROR',
            'propagate': True,
        },
    }
}

# Applications
INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    # 'grappelli.dashboard',
    'super_inlines.grappelli_integration',
    'grappelli',
    'super_inlines',
    'django.contrib.admin',
    'django.contrib.admindocs',
    'django.contrib.humanize',
    'fsm_admin',
    'django_fsm',
    # 'django_fsm_log',
    # 'haystack',
    'easy_pdf',
    'timezone_field',
    'corsheaders',
    'mptt',
    'rest_framework',
    'rest_framework.authtoken',
    'apps.api',
    'apps.website',
)
<|endoftext|>


<commit_before>#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
#

import sqlite3 as lite
import sys

def line1(lines):
    """ convert a string with newlines  to a single line with ; separating lines
    """
    return lines.replace('\n',';')

db1 = sys.argv[1]
if len(sys.argv) > 2:
    disk = sys.argv[2]
else:
    disk = ""

con1 = lite.connect(db1)
cur1 = con1.cursor()
cur1.execute('SELECT * FROM AlbumRoots')
ars = cur1.fetchall()

import os

def uuid_root(uuid):
    """ convert a uuid string to the mount point - only for linux
    """
    #print(uuid)
    idx = uuid.find('=') + 1
    f = os.popen('blkid --uuid %s' % uuid[idx:])
    lines = f.readlines()
    f.close()
    #print(lines)
    dev = lines[0].strip()
    #dev = os.popen('blkid --uuid ' % uuid[idx:]).readlines()[0].strip()
    #print(dev)
    f = open('/etc/mtab')
    lines = f.readlines()
    for line in lines:
        word = line.split()
        if word[0] == dev:
            #print("DEV %s -> %s" % (dev,word[1]))
            return word[1]

albumRootNo = -1
for ar in ars:
    mountPoint =  uuid_root(ar[4])
    print("#old ",ar[0], ar[1], ar[2], ar[3], mountPoint, ar[5])
    if ar[5] == disk:
        albumRootNo = ar[0]
        albumRoot   = mountPoint + '/' + ar[5]

import os.path

if albumRootNo < 1:
    print("No matching path to match for")
    sys.exit(0)
else:
    print("# albumRoot = %d %s" % (albumRootNo,albumRoot))

if True:
    ncapt = 0
    cmd = 'SELECT * FROM Albums where albumRoot == %d AND caption IS NOT NULL' % albumRootNo
    cur1.execute(cmd)
    rows = cur1.fetchall()
    for row in rows:
        ncapt += 1
        dirname = albumRoot + '/' + row[2]
        captionName = "%s/.caption" % dirname
        if not os.path.isfile(captionName):
            print("Going to write ",captionName)
            f = open(captionName,'w')
            f.write(row[4])
            f.close()
        print(row[1],row[2],row[3],line1(row[4]),captionName)
    print("# Found %d albums with a caption" % ncapt)

if True:
    nzero = 0
    cmd = 'SELECT * FROM Albums where albumRoot == %d AND caption IS NULL' % albumRootNo
    cur1.execute(cmd)
    rows = cur1.fetchall()
    for row in rows:
        nzero += 1
        dirname = albumRoot + '/' + row[2]
        captionName = "%s/.caption" % dirname
        if os.path.isfile(captionName):
            print("WARNING: We have a caption in ",captionName)
            if False:
                f = open(captionName,'r')
                f.close()
        #print('CHECK',row[1],row[2],row[3])
        #print('CHECK',dirname)
    print("# Found %d albums with no caption" % nzero)

con1.close()
<commit_msg>keep it working on ubuntu16<commit_after>#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
#

import sqlite3 as lite
import sys

def line1(lines):
    """ convert a string with newlines  to a single line with ; separating lines
    """
    return lines.replace('\n',';')

db1 = sys.argv[1]
if len(sys.argv) > 2:
    disk = sys.argv[2]
else:
    disk = ""

con1 = lite.connect(db1)
cur1 = con1.cursor()
cur1.execute('SELECT * FROM AlbumRoots')
ars = cur1.fetchall()

import os

def uuid_root(uuid):
    """ convert a uuid string to the mount point - only for linux
    """
    #print(uuid)
    idx = uuid.find('=') + 1
    f = os.popen('blkid -U %s' % uuid[idx:])
    lines = f.readlines()
    f.close()
    #print(lines)
    dev = lines[0].strip()
    f = open('/etc/mtab')
    lines = f.readlines()
    for line in lines:
        word = line.split()
        if word[0] == dev:
            #print("DEV %s -> %s" % (dev,word[1]))
            return word[1]

albumRootNo = -1
for ar in ars:
    #print("#old ",ar[0], ar[1], ar[2], ar[3], ar[4], ar[5])
    mountPoint =  uuid_root(ar[4])
    print("#old ",ar[0], ar[1], ar[2], ar[3], mountPoint, ar[5])
    if ar[5] == disk:
        albumRootNo = ar[0]
        albumRoot   = mountPoint + '/' + ar[5]

import os.path

if albumRootNo < 1:
    print("No matching path to match for")
    sys.exit(0)
else:
    print("# albumRoot = %d %s" % (albumRootNo,albumRoot))

if True:
    ncapt = 0
    cmd = 'SELECT * FROM Albums where albumRoot == %d AND caption IS NOT NULL' % albumRootNo
    cur1.execute(cmd)
    rows = cur1.fetchall()
    for row in rows:
        ncapt += 1
        dirname = albumRoot + '/' + row[2]
        captionName = "%s/.caption" % dirname
        if not os.path.isfile(captionName):
            print("Going to write ",captionName)
            f = open(captionName,'w')
            f.write(row[4])
            f.close()
        print(row[1],row[2],row[3],line1(row[4]),captionName)
    print("# Found %d albums with a caption" % ncapt)

if True:
    nzero = 0
    cmd = 'SELECT * FROM Albums where albumRoot == %d AND caption IS NULL' % albumRootNo
    cur1.execute(cmd)
    rows = cur1.fetchall()
    for row in rows:
        nzero += 1
        dirname = albumRoot + '/' + row[2]
        captionName = "%s/.caption" % dirname
        if os.path.isfile(captionName):
            print("WARNING: We have a caption in ",captionName)
            if False:
                f = open(captionName,'r')
                f.close()
        #print('CHECK',row[1],row[2],row[3])
        #print('CHECK',dirname)
    print("# Found %d albums with no caption" % nzero)

con1.close()
<|endoftext|>


<commit_before>#!/usr/bin/python
from __future__ import print_function

import sys
import argparse
try:
    input = raw_input  # Python 2.x
except NameError:
    pass  # Python 3.x
try:
    from urlparse import urlparse
except ImportError:
    from urllib.parse import urlparse

from plugin_manager import generate_script
from url import get_url, check_valid_url

def take_arguments():
    # TODO: Docstring and comments.
    parser = argparse.ArgumentParser(
        description="Request Translator is a standalone tool that can translate "
                    "raw HTTP requests into curl commands or bash/python/php/ruby/PowerShell scripts")
    conflicting_group = parser.add_mutually_exclusive_group()
    parser.add_argument(
        '--output', '-o',
        action='append',
        help="Generates a script for given HTTP request. "
             "If you want to generate multiple scripts, separate the script's name with a <,>")
    parser.add_argument(
        '--proxy',
        nargs='?',
        const='127.0.0.1:8009',
        help='Generates command/script with relevant, specified proxy')
    conflicting_group.add_argument(
        '--stringSearch',
        help='Sends the request and searches for the required string in the response (i.e literal match)')
    conflicting_group.add_argument(
        '--regexSearch',
        help='Sends the request and searches for the required regex in the response (i.e regex match)')
    parser.add_argument(
        '--interactive', '-i',
        action='store_true',
        help="Interactive mode: read raw HTTP request from keyboard, hit enter when ready."
             "Type ':q!' to exit from the interactive mode.")
    parser.add_argument(
        '--data', '-d',
        help='Add the data that you want to send along with the header')
    parser.add_argument(
        '--Request',
        help='Input the HTTP request')
    process_arguments(parser.parse_args())
    return parser.parse_args()

def process_arguments(args):
    """Process the arguments provided to the translator and places values in separate headers and details dictionaries.

    :param class `argparse.Namespace`: `argparse` class object containing arguments passed to the translator.

    :raises ValueError: When proxy provided is invalid.

    :return: A dictionaries of arguments passed.
    :rtype: `dict`
    """
    argdict = vars(args)
    try:
        script_list = argdict['output'][0].split(',')
    except TypeError:
        script_list = []  # If --output option is not used.
    if args.interactive:
        try:
            take_headers(script_list)
        except KeyboardInterrupt:
            print("\nThanks for using the interactive mode! Exiting!")
            sys.exit(0)
    else:
        if not args.Request:
            print("Input a raw HTTP Request and try again.\nElse try using the interactive option")
            sys.exit(-1)
        headers, details = parse_raw_request(args.Request)
        if args.data:
            details['data'] = args.data
        else:
            details['data'] = None
        if args.proxy:
            # If proxy already doesn't starts with http and is like 127.0.0.1:8010
            if not args.proxy.startswith(('http', 'https')):
                proxy = get_url(args.proxy)  # Fix proxy to add appropriate scheme
            else:
                proxy = args.proxy.strip()
            if not check_valid_url(proxy):
                raise ValueError("Proxy provided is invalid.")
            try:
                details['proxy_host'], details['proxy_port'] = proxy.rsplit(":", 1)
            except IndexError:
                raise ValueError("Proxy provided is invalid.")
        if not details['data'] and details['method'].strip().upper() == "POST":
            print("Hi there. Send some data to POST, use --data for sending data.")
            sys.exit(-1)
        arg_option = None
        if args.stringSearch:
            arg_option = args.stringSearch
        elif args.regexSearch:
            arg_option = args.regexSearch
        if len(script_list) == 0:
            # Default curl commands if --output option is not passed
            # Not implemented yet
            pass
        else:
            for script in script_list:
                generated_code = generate_script(script, headers, details, arg_option)
                print(generated_code)

    return argdict

def take_headers(script_list):
    """Takes Request headers while interactive mode is active

    :param list script_list: List of names of the languages for which script is to be generated.

    :return: Raw Request Headers passed in the interactive session.
    :rtype: `str`
    """
    headers = []
    print("Enter request headers (Ctrl+D to finish/Ctrl+C to quit).")
    while True:
        try:
            uentered = input(">>> ")
            headers.append(uentered + "\n")
        except EOFError:
            take_body(headers, script_list)
    return headers

def take_body(headers, script_list):
    """Takes Request body while interactive mode is active.
    Also prints the generated code for languages passed in `script_list` on console.

    :param str headers: Raw request headers feeded in the interactive session.
    :param list script_list: List of names of the languages for which script is to be generated.

    :return: Body for the request passed in interactive session.
    :rtype: `str`
    """
    body = []
    print("\nEnter request body/parameters (Ctrl+D to finish/Ctrl+C to quit).")
    while True:
        try:
            uentered = input(">>> ")
            body.append(uentered + "\n")
        except EOFError:
            try:
                headers, details = parse_raw_request("".join(headers))
                details['data'] = "".join(body).strip()
                if not script_list:
                    # TODO: Default curl commands if --output option is not passed
                    # Not implemented yet
                    pass
                else:
                    for script in script_list:
                        print(generate_script(script, headers, details))
            except ValueError:
                print("Please Enter a Vaild Request!")
            take_headers(script_list)
    return body

def parse_raw_request(request):
    """Parses Raw HTTP request into separate dictionaries for headers and body and other parameters.

    :param str request: Raw HTTP request.

    :raises ValueError: When request passed in malformed.

    :return: Separate dictionaries for headers and body and other parameters.
    :rtype: dict,dict
    """
    try:
        new_request_method, headers = request.split('\n', 1)
    except IndexError:
        raise ValueError("Request Malformed. Please Enter a Valid HTTP request.")

    header_list = []
    for line in headers.splitlines():
        header_list.append(line)
        try:
            header, value = line.split(":", 1)
        except IndexError:
            raise ValueError("Headers Malformed. Please Enter a Valid HTTP request.")
        if header.lower() == "host":
            host = value.strip()  # Keep hostname for further checks

    details_dict = {}
    details_dict['method'] = new_request_method.split(' ', 1)[0].strip()
    details_dict['Host'] = host
    # Not using whatever stored in parsed_request for the reason to keep the request as original as possible
    try:  # try to split the path from request if one is passed.
        proto_ver = new_request_method.split(' ', 2)[2].split('/', 1)
        details_dict['protocol'] = proto_ver[0].strip()
        details_dict['version'] = proto_ver[1].strip()
        details_dict['path'] = new_request_method.split(' ', 2)[1].strip()
    except IndexError:
        details_dict['path'] = ""
        try:
            proto_ver = new_request_method.split(' ', 2)[1].split('/', 1)
        except IndexError:  # Failed to get protocol and version.
            raise ValueError("Request Malformed. Please Enter a Valid HTTP request.")
        details_dict['protocol'] = proto_ver[0].strip()
        details_dict['version'] = proto_ver[1].strip()
    # Parse the GET Path to update it to only contain the relative path and not whole url
    # scheme://netloc/path;parameters?query#fragment
    # Eg: Path=https://google.com/robots.txt to /robots.txt
    scheme, netloc, path, params, query, frag = urlparse(details_dict['path'])
    if params:
        path = path + ";" + params
    if query:
        path = path + "?" + query
    if frag:
        path = path + "#" + frag
    details_dict['path'] = path
    # If scheme is specified in GET Path and Header 'Host' Field doesn't already starts with it
    if scheme and not host.startswith(scheme):
        details_dict['pre_scheme'] = scheme + "://"  # Store the scheme defined in GET path for later checks
    else:
        details_dict['pre_scheme'] = ''
    return header_list, details_dict

def main():
    # TODO: Docstring and comments.
    take_arguments()

if __name__ == '__main__':
    main()
<commit_msg>Modified the translator cli arguments to more standard names<commit_after>#!/usr/bin/python
from __future__ import print_function

import sys
import argparse
try:
    input = raw_input  # Python 2.x
except NameError:
    pass  # Python 3.x
try:
    from urlparse import urlparse
except ImportError:
    from urllib.parse import urlparse

from plugin_manager import generate_script
from url import get_url, check_valid_url

def take_arguments():
    """Entry point for the translator. Parses arguments using `argparse` library.

    :return:`argparse` class object containing arguments passed to the translator.
    :rtype:class `argparse.Namespace`
    """
    parser = argparse.ArgumentParser(
        description="Request Translator is a standalone tool that can translate "
                    "raw HTTP requests into curl commands or bash/python/php/ruby/PowerShell scripts")
    conflicting_group = parser.add_mutually_exclusive_group()
    parser.add_argument(
        '--output', '-o',
        action='append',
        help="Generates a script for given HTTP request. "
             "If you want to generate multiple scripts, separate the script's name with a <,>")
    parser.add_argument(
        '--proxy', '-p',
        nargs='?',
        const='127.0.0.1:8009',
        help='Generates command/script with relevant, specified proxy')
    conflicting_group.add_argument(
        '--string_search', '-s',
        help='Sends the request and searches for the required string in the response (i.e literal match)')
    conflicting_group.add_argument(
        '--regex_search', '-re',
        help='Sends the request and searches for the required regex in the response (i.e regex match)')
    parser.add_argument(
        '--interactive', '-i',
        action='store_true',
        help="Interactive mode: read raw HTTP request from keyboard, hit enter when ready."
             "Type ':q!' to exit from the interactive mode.")
    parser.add_argument(
        '--data', '-d',
        help='Add the data that you want to send along with the header')
    parser.add_argument(
        '--request', '-r',
        help='Input the HTTP request')
    process_arguments(parser.parse_args())
    return parser.parse_args()

def process_arguments(args):
    """Process the arguments provided to the translator and places values in separate headers and details dictionaries.

    :param class `argparse.Namespace`: `argparse` class object containing arguments passed to the translator.

    :raises ValueError: When proxy provided is invalid.

    :return: A dictionaries of arguments passed.
    :rtype: `dict`
    """
    argdict = vars(args)
    try:
        script_list = argdict['output'][0].split(',')
    except TypeError:
        script_list = []  # If --output option is not used.
    if args.interactive:
        try:
            take_headers(script_list)
        except KeyboardInterrupt:
            print("\nThanks for using the interactive mode! Exiting!")
            sys.exit(0)
    else:
        if not args.request:
            print("Input a raw HTTP Request and try again.\nElse try using the interactive option")
            sys.exit(-1)
        headers, details = parse_raw_request(args.request)
        if args.data:
            details['data'] = args.data
        else:
            details['data'] = None
        if args.proxy:
            # If proxy already doesn't starts with http and is like 127.0.0.1:8010
            if not args.proxy.startswith(('http', 'https')):
                proxy = get_url(args.proxy)  # Fix proxy to add appropriate scheme
            else:
                proxy = args.proxy.strip()
            if not check_valid_url(proxy):
                raise ValueError("Proxy provided is invalid.")
            try:
                details['proxy_host'], details['proxy_port'] = proxy.rsplit(":", 1)
            except IndexError:
                raise ValueError("Proxy provided is invalid.")
        if not details['data'] and details['method'].strip().upper() == "POST":
            print("Hi there. Send some data to POST, use --data for sending data.")
            sys.exit(-1)
        arg_option = None
        if args.string_search:
            arg_option = args.string_search
        elif args.regex_search:
            arg_option = args.regex_search
        if len(script_list) == 0:
            # Default curl commands if --output option is not passed
            # Not implemented yet
            pass
        else:
            for script in script_list:
                generated_code = generate_script(script, headers, details, arg_option)
                print(generated_code)

    return argdict

def take_headers(script_list):
    """Takes Request headers while interactive mode is active

    :param list script_list: List of names of the languages for which script is to be generated.

    :return: Raw Request Headers passed in the interactive session.
    :rtype: `str`
    """
    headers = []
    print("Enter request headers (Ctrl+D to finish/Ctrl+C to quit).")
    while True:
        try:
            uentered = input(">>> ")
            headers.append(uentered + "\n")
        except EOFError:
            take_body(headers, script_list)
    return headers

def take_body(headers, script_list):
    """Takes Request body while interactive mode is active.
    Also prints the generated code for languages passed in `script_list` on console.

    :param str headers: Raw request headers feeded in the interactive session.
    :param list script_list: List of names of the languages for which script is to be generated.

    :return: Body for the request passed in interactive session.
    :rtype: `str`
    """
    body = []
    print("\nEnter request body/parameters (Ctrl+D to finish/Ctrl+C to quit).")
    while True:
        try:
            uentered = input(">>> ")
            body.append(uentered + "\n")
        except EOFError:
            try:
                headers, details = parse_raw_request("".join(headers))
                details['data'] = "".join(body).strip()
                if not script_list:
                    # TODO: Default curl commands if --output option is not passed
                    # Not implemented yet
                    pass
                else:
                    for script in script_list:
                        print(generate_script(script, headers, details))
            except ValueError:
                print("Please Enter a Vaild Request!")
            take_headers(script_list)
    return body

def parse_raw_request(request):
    """Parses Raw HTTP request into separate dictionaries for headers and body and other parameters.

    :param str request: Raw HTTP request.

    :raises ValueError: When request passed in malformed.

    :return: Separate dictionaries for headers and body and other parameters.
    :rtype: dict,dict
    """
    try:
        new_request_method, headers = request.split('\n', 1)
    except IndexError:
        raise ValueError("Request Malformed. Please Enter a Valid HTTP request.")

    header_list = []
    for line in headers.splitlines():
        header_list.append(line)
        try:
            header, value = line.split(":", 1)
        except IndexError:
            raise ValueError("Headers Malformed. Please Enter a Valid HTTP request.")
        if header.lower() == "host":
            host = value.strip()  # Keep hostname for further checks

    details_dict = {}
    details_dict['method'] = new_request_method.split(' ', 1)[0].strip()
    details_dict['Host'] = host
    # Not using whatever stored in parsed_request for the reason to keep the request as original as possible
    try:  # try to split the path from request if one is passed.
        proto_ver = new_request_method.split(' ', 2)[2].split('/', 1)
        details_dict['protocol'] = proto_ver[0].strip()
        details_dict['version'] = proto_ver[1].strip()
        details_dict['path'] = new_request_method.split(' ', 2)[1].strip()
    except IndexError:
        details_dict['path'] = ""
        try:
            proto_ver = new_request_method.split(' ', 2)[1].split('/', 1)
        except IndexError:  # Failed to get protocol and version.
            raise ValueError("Request Malformed. Please Enter a Valid HTTP request.")
        details_dict['protocol'] = proto_ver[0].strip()
        details_dict['version'] = proto_ver[1].strip()
    # Parse the GET Path to update it to only contain the relative path and not whole url
    # scheme://netloc/path;parameters?query#fragment
    # Eg: Path=https://google.com/robots.txt to /robots.txt
    scheme, netloc, path, params, query, frag = urlparse(details_dict['path'])
    if params:
        path = path + ";" + params
    if query:
        path = path + "?" + query
    if frag:
        path = path + "#" + frag
    details_dict['path'] = path
    # If scheme is specified in GET Path and Header 'Host' Field doesn't already starts with it
    if scheme and not host.startswith(scheme):
        details_dict['pre_scheme'] = scheme + "://"  # Store the scheme defined in GET path for later checks
    else:
        details_dict['pre_scheme'] = ''
    return header_list, details_dict

def main():
    # TODO: Docstring and comments.
    take_arguments()

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


<commit_before># Local
from .base import *

# Heroku
ALLOWED_HOSTS = [
    'testserver',
]
DATABASES['default']['TEST'] = {
    'NAME': DATABASES['default']['NAME'],
}

# Email
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
<commit_msg>Add DOCRAPTOR<commit_after># Local
from .base import *

# Heroku
ALLOWED_HOSTS = [
    'testserver',
]
DATABASES['default']['TEST'] = {
    'NAME': DATABASES['default']['NAME'],
}

# Email
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'

#  Docraptor
DOCRAPTOR_API_KEY = get_env_variable("DOCRAPTOR_API_KEY")
<|endoftext|>


<commit_before>import csv

class LoadCSV:
    def __init__(self):
        pass

    def load(self, data, outfile):
        self.outfile = outfile
        self.data = data
        key = data[0].keys()
        with open(outfile, 'w') as outfile:
            dict_writer = csv.DictWriter(outfile, key)
            dict_writer.writeheader()
            dict_writer.writerows(data)

<commit_msg>fix loader<commit_after>import csv

class LoadCSV:
    def __init__(self):
        pass

    def load(self, data, outfile):
        self.outfile = outfile
        self.data = data
        key = data[0].keys()
        with open(outfile, 'w') as outfile:
            dict_writer = csv.DictWriter(outfile, key, delimiter=',', lineterminator='\n')
            dict_writer.writeheader()
            dict_writer.writerows(data)

<|endoftext|>


<commit_before>import Image
from project.extensions import celery

@celery.task()
def celery_make_thumbnail(path_to_original, destination, size):
    thumb = Image.open(path_to_original)
    thumb.thumbnail(size, Image.LANCZOS)
    thumb.save(destination)
<commit_msg>fixed import for PIL Image module<commit_after>from PIL import Image
from project.extensions import celery

@celery.task()
def celery_make_thumbnail(path_to_original, destination, size):
    thumb = Image.open(path_to_original)
    thumb.thumbnail(size, Image.LANCZOS)
    thumb.save(destination)
<|endoftext|>


<commit_before># Copyright 2013: Mirantis Inc.
# All Rights Reserved.
#
#    Licensed under the Apache License, Version 2.0 (the "License"); you may
#    not use this file except in compliance with the License. You may obtain
#    a copy of the License at
#
#         http://www.apache.org/licenses/LICENSE-2.0
#
#    Unless required by applicable law or agreed to in writing, software
#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
#    License for the specific language governing permissions and limitations
#    under the License.

import sys

from oslo.config import cfg

from rally.openstack.common.gettextutils import _
from rally.openstack.common import log as logging

LOG = logging.getLogger(__name__)

exc_log_opts = [
    cfg.BoolOpt('fatal_exception_format_errors',
                default=False,
                help='make exception message format errors fatal'),
]

CONF = cfg.CONF
CONF.register_opts(exc_log_opts)

class RallyException(Exception):
    """Base Rally Exception

    To correctly use this class, inherit from it and define
    a 'msg_fmt' property. That msg_fmt will get printf'd
    with the keyword arguments provided to the constructor.

    """
    msg_fmt = _("An unknown exception occurred.")

    def __init__(self, message=None, **kwargs):
        self.kwargs = kwargs

        if 'code' not in self.kwargs:
            try:
                self.kwargs['code'] = self.code
            except AttributeError:
                pass

        if not message:
            try:
                message = self.msg_fmt % kwargs
            except KeyError:
                exc_info = sys.exc_info()
                # kwargs doesn't match a variable in the message
                # log the issue and the kwargs
                msg = "kwargs don't match in string format operation: %s"
                LOG.debug(msg % kwargs, exc_info=exc_info)

                if CONF.fatal_exception_format_errors:
                    raise exc_info[0], exc_info[1], exc_info[2]
                else:
                    # at least get the core message out if something happened
                    message = self.msg_fmt

        super(RallyException, self).__init__(message)

    def format_message(self):
        if self.__class__.__name__.endswith('_Remote'):
            return self.args[0]
        else:
            return unicode(self)

class ImmutableException(RallyException):
    msg_fmt = _("This object is immutable.")

class InvalidArgumentsException(RallyException):
    msg_fmt = _("Invalid arguments: '%(message)s'")

class InvalidConfigException(RallyException):
    msg_fmt = _("This config has invalid schema: `%(message)s`")

class InvalidRunnerResult(RallyException):
    msg_fmt = _("Type of result of `%(name)s` runner should be"
                " `base.ScenarioRunnerResult`. Got: `%(results_type)s`")

class InvalidTaskException(InvalidConfigException):
    msg_fmt = _("This config is invalid: `%(message)s`")

class InvalidTaskConfigException(InvalidTaskException):
    msg_fmt = _("This config has invalid schema: `%(message)s`")

class NotFoundScenarios(InvalidTaskException):
    msg_fmt = _("There are no benchmark scenarios with names: `%(names)s`.")

class InvalidBenchmarkConfig(InvalidTaskException):
    msg_fmt = _("Task config is invalid.\n"
                "\tBenchmark %(name)s has wrong configuration at"
                " position %(pos)s"
                "\n\tReason: %(reason)s"
                "\n\tBenchmark configuration: %(config)s")

class TestException(RallyException):
    msg_fmt = _("Test failed: %(test_message)s")

class NotFoundException(RallyException):
    msg_fmt = _("Not found.")

class NoSuchEngine(NotFoundException):
    msg_fmt = _("There is no engine with name `%(engine_name)s`.")

class NoSuchVMProvider(NotFoundException):
    msg_fmt = _("There is no vm provider with name `%(vm_provider_name)s`.")

class NoSuchScenario(NotFoundException):
    msg_fmt = _("There is no benchmark scenario with name `%(name)s`.")

class NoSuchRunner(NotFoundException):
    msg_fmt = _("There is no benchmark runner with type `%(type)s`.")

class NoSuchContext(NotFoundException):
    msg_fmt = _("There is no benchmark context with name `%(name)s`.")

class NoSuchConfigField(NotFoundException):
    msg_fmt = _("There is no field in the task config with name `%(name)s`.")

class NoSuchRole(NotFoundException):
    msg_fmt = _("There is no role with name `%(role)s`.")

class TaskNotFound(NotFoundException):
    msg_fmt = _("Task with uuid=%(uuid)s not found.")

class DeploymentNotFound(NotFoundException):
    msg_fmt = _("Deployment with uuid=%(uuid)s not found.")

class DeploymentIsBusy(RallyException):
    msg_fmt = _("There are allocated resources for the deployment with "
                "uuid=%(uuid)s.")

class ResourceNotFound(NotFoundException):
    msg_fmt = _("Resource with id=%(id)s not found.")

class TimeoutException(RallyException):
    msg_fmt = _("Timeout exceeded.")

class GetResourceFailure(RallyException):
    msg_fmt = _("Failed to get the resource %(resource)s: %(err)s")

class GetResourceNotFound(GetResourceFailure):
    msg_fmt = _("Resource %(resource)s is not found.")

class GetResourceErrorStatus(GetResourceFailure):
    msg_fmt = _("Resource %(resource)s has %(status)s status: %(fault)s")

class SSHError(RallyException):
    msg_fmt = _("Remote command failed.")

class ScriptError(RallyException):
    msg_fmt = _("Script execution failed.")

class TaskInvalidStatus(RallyException):
    msg_fmt = _("Task `%(uuid)s` in `%(actual)s` status but `%(require)s` is "
                "required.")

class ChecksumMismatch(RallyException):
    msg_fmt = _("Checksum mismatch for image: %(url)s")

class InvalidAdminException(InvalidArgumentsException):
    msg_fmt = _("user %(username)s doesn't have 'admin' role")

class InvalidEndpointsException(InvalidArgumentsException):
    msg_fmt = _("wrong keystone credentials specified in your endpoint"
                " properties. (HTTP 401)")

class HostUnreachableException(InvalidArgumentsException):
    msg_fmt = _("unable to establish connection to the remote host: %(url)s")

class InvalidScenarioArgument(RallyException):
    msg_fmt = _("Invalid scenario argument: '%(message)s'")

class TempestConfigCreationFailure(RallyException):
    msg_fmt = _("Unable create tempest.conf: '%(message)s'")

class TempestSetupFailure(RallyException):
    msg_fmt = _("Unable to setup tempest: '%(message)s'")

class TempestBenchmarkFailure(RallyException):
    msg_fmt = _("Failed tempest test(s): '%(message)s'")

class BenchmarkSetupFailure(RallyException):
    msg_fmt = _("Unable to setup benchmark: '%(message)s'")

class DummyScenarioException(RallyException):
    msg_fmt = _("Dummy scenario expected exception: '%(message)s'")

class ValidationError(RallyException):
    msg_fmt = _("Validation error: %(message)s")

class NoNodesFound(RallyException):
    msg_fmt = _("There is no nodes matching filters: %(filters)r")

class UnknownRelease(RallyException):
    msg_fmt = _("Unknown release '%(release)s'")

class ImageCleanUpException(RallyException):
    msg_fmt = _("Image Deletion Failed")

class IncompatiblePythonVersion(RallyException):
    msg_fmt = _("Incompatible python version found '%(version)s', "
                "required at least python>=2.7.x")

class WorkerNotFound(NotFoundException):
    msg_fmt = _("Worker %(worker)s could not be found")

class WorkerAlreadyRegistered(RallyException):
    msg_fmt = _("Worker %(worker)s already registered")
<commit_msg>Remove two unused exceptions<commit_after># Copyright 2013: Mirantis Inc.
# All Rights Reserved.
#
#    Licensed under the Apache License, Version 2.0 (the "License"); you may
#    not use this file except in compliance with the License. You may obtain
#    a copy of the License at
#
#         http://www.apache.org/licenses/LICENSE-2.0
#
#    Unless required by applicable law or agreed to in writing, software
#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
#    License for the specific language governing permissions and limitations
#    under the License.

import sys

from oslo.config import cfg

from rally.openstack.common.gettextutils import _
from rally.openstack.common import log as logging

LOG = logging.getLogger(__name__)

exc_log_opts = [
    cfg.BoolOpt('fatal_exception_format_errors',
                default=False,
                help='make exception message format errors fatal'),
]

CONF = cfg.CONF
CONF.register_opts(exc_log_opts)

class RallyException(Exception):
    """Base Rally Exception

    To correctly use this class, inherit from it and define
    a 'msg_fmt' property. That msg_fmt will get printf'd
    with the keyword arguments provided to the constructor.

    """
    msg_fmt = _("An unknown exception occurred.")

    def __init__(self, message=None, **kwargs):
        self.kwargs = kwargs

        if 'code' not in self.kwargs:
            try:
                self.kwargs['code'] = self.code
            except AttributeError:
                pass

        if not message:
            try:
                message = self.msg_fmt % kwargs
            except KeyError:
                exc_info = sys.exc_info()
                # kwargs doesn't match a variable in the message
                # log the issue and the kwargs
                msg = "kwargs don't match in string format operation: %s"
                LOG.debug(msg % kwargs, exc_info=exc_info)

                if CONF.fatal_exception_format_errors:
                    raise exc_info[0], exc_info[1], exc_info[2]
                else:
                    # at least get the core message out if something happened
                    message = self.msg_fmt

        super(RallyException, self).__init__(message)

    def format_message(self):
        if self.__class__.__name__.endswith('_Remote'):
            return self.args[0]
        else:
            return unicode(self)

class ImmutableException(RallyException):
    msg_fmt = _("This object is immutable.")

class InvalidArgumentsException(RallyException):
    msg_fmt = _("Invalid arguments: '%(message)s'")

class InvalidConfigException(RallyException):
    msg_fmt = _("This config has invalid schema: `%(message)s`")

class InvalidRunnerResult(RallyException):
    msg_fmt = _("Type of result of `%(name)s` runner should be"
                " `base.ScenarioRunnerResult`. Got: `%(results_type)s`")

class InvalidTaskException(InvalidConfigException):
    msg_fmt = _("This config is invalid: `%(message)s`")

class InvalidTaskConfigException(InvalidTaskException):
    msg_fmt = _("This config has invalid schema: `%(message)s`")

class NotFoundScenarios(InvalidTaskException):
    msg_fmt = _("There are no benchmark scenarios with names: `%(names)s`.")

class InvalidBenchmarkConfig(InvalidTaskException):
    msg_fmt = _("Task config is invalid.\n"
                "\tBenchmark %(name)s has wrong configuration at"
                " position %(pos)s"
                "\n\tReason: %(reason)s"
                "\n\tBenchmark configuration: %(config)s")

class NotFoundException(RallyException):
    msg_fmt = _("Not found.")

class NoSuchEngine(NotFoundException):
    msg_fmt = _("There is no engine with name `%(engine_name)s`.")

class NoSuchVMProvider(NotFoundException):
    msg_fmt = _("There is no vm provider with name `%(vm_provider_name)s`.")

class NoSuchScenario(NotFoundException):
    msg_fmt = _("There is no benchmark scenario with name `%(name)s`.")

class NoSuchRunner(NotFoundException):
    msg_fmt = _("There is no benchmark runner with type `%(type)s`.")

class NoSuchContext(NotFoundException):
    msg_fmt = _("There is no benchmark context with name `%(name)s`.")

class NoSuchConfigField(NotFoundException):
    msg_fmt = _("There is no field in the task config with name `%(name)s`.")

class NoSuchRole(NotFoundException):
    msg_fmt = _("There is no role with name `%(role)s`.")

class TaskNotFound(NotFoundException):
    msg_fmt = _("Task with uuid=%(uuid)s not found.")

class DeploymentNotFound(NotFoundException):
    msg_fmt = _("Deployment with uuid=%(uuid)s not found.")

class DeploymentIsBusy(RallyException):
    msg_fmt = _("There are allocated resources for the deployment with "
                "uuid=%(uuid)s.")

class ResourceNotFound(NotFoundException):
    msg_fmt = _("Resource with id=%(id)s not found.")

class TimeoutException(RallyException):
    msg_fmt = _("Timeout exceeded.")

class GetResourceFailure(RallyException):
    msg_fmt = _("Failed to get the resource %(resource)s: %(err)s")

class GetResourceNotFound(GetResourceFailure):
    msg_fmt = _("Resource %(resource)s is not found.")

class GetResourceErrorStatus(GetResourceFailure):
    msg_fmt = _("Resource %(resource)s has %(status)s status: %(fault)s")

class ScriptError(RallyException):
    msg_fmt = _("Script execution failed.")

class TaskInvalidStatus(RallyException):
    msg_fmt = _("Task `%(uuid)s` in `%(actual)s` status but `%(require)s` is "
                "required.")

class ChecksumMismatch(RallyException):
    msg_fmt = _("Checksum mismatch for image: %(url)s")

class InvalidAdminException(InvalidArgumentsException):
    msg_fmt = _("user %(username)s doesn't have 'admin' role")

class InvalidEndpointsException(InvalidArgumentsException):
    msg_fmt = _("wrong keystone credentials specified in your endpoint"
                " properties. (HTTP 401)")

class HostUnreachableException(InvalidArgumentsException):
    msg_fmt = _("unable to establish connection to the remote host: %(url)s")

class InvalidScenarioArgument(RallyException):
    msg_fmt = _("Invalid scenario argument: '%(message)s'")

class TempestConfigCreationFailure(RallyException):
    msg_fmt = _("Unable create tempest.conf: '%(message)s'")

class TempestSetupFailure(RallyException):
    msg_fmt = _("Unable to setup tempest: '%(message)s'")

class TempestBenchmarkFailure(RallyException):
    msg_fmt = _("Failed tempest test(s): '%(message)s'")

class BenchmarkSetupFailure(RallyException):
    msg_fmt = _("Unable to setup benchmark: '%(message)s'")

class DummyScenarioException(RallyException):
    msg_fmt = _("Dummy scenario expected exception: '%(message)s'")

class ValidationError(RallyException):
    msg_fmt = _("Validation error: %(message)s")

class NoNodesFound(RallyException):
    msg_fmt = _("There is no nodes matching filters: %(filters)r")

class UnknownRelease(RallyException):
    msg_fmt = _("Unknown release '%(release)s'")

class ImageCleanUpException(RallyException):
    msg_fmt = _("Image Deletion Failed")

class IncompatiblePythonVersion(RallyException):
    msg_fmt = _("Incompatible python version found '%(version)s', "
                "required at least python>=2.7.x")

class WorkerNotFound(NotFoundException):
    msg_fmt = _("Worker %(worker)s could not be found")

class WorkerAlreadyRegistered(RallyException):
    msg_fmt = _("Worker %(worker)s already registered")
<|endoftext|>


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

"""
Django settings for {{ project_name }} project.

Generated by 'django-admin startproject' using Django {{ django_version }}.

For more information on this file, see
https://docs.djangoproject.com/en/{{ docs_version }}/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/{{ docs_version }}/ref/settings/
"""

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os

from decouple import config, Csv

BASE_DIR = os.path.dirname(__file__)

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/{{ docs_version }}/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = config('SECRET_KEY')

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = config('DEBUG', default=False, cast=bool)

TEMPLATE_DEBUG = DEBUG

ALLOWED_HOSTS = config('ALLOWED_HOSTS', default='*', cast=Csv())

# Application definition

INSTALLED_APPS = (
    # django
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    # 3rd
    'debug_toolbar',
    'django_extensions',
    # project
    '{{ project_name }}.accounts',
    '{{ project_name }}.core',
)

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

ROOT_URLCONF = '{{ project_name }}.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [
            os.path.join(BASE_DIR, 'templates'),
        ],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = '{{ project_name }}.wsgi.application'

# Database
# https://docs.djangoproject.com/en/{{ docs_version }}/ref/settings/#databases

from dj_database_url import parse as db_url
DATABASES = {'default': config('DATABASE_URL', cast=db_url)}

# Internationalization
# https://docs.djangoproject.com/en/{{ docs_version }}/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/{{ docs_version }}/howto/static-files/

STATIC_URL = '/static/'

MEDIA_URL = '/media/'

STATIC_ROOT = os.path.join(BASE_DIR, '..', 'static-root')

MEDIA_ROOT = os.path.join(BASE_DIR, '..', 'media-root')

STATICFILES_DIRS = (
    os.path.join(BASE_DIR, 'static'),
    os.path.join(BASE_DIR, '..', 'bower_components'),
)

# Auth

AUTH_USER_MODEL = 'accounts.User'

LOGIN_URL = '/auth/login/'

LOGOUT_URL = '/auth/logout/'

LOGIN_REDIRECT_URL = '/'

PASSWORD_HASHERS = (
    'django.contrib.auth.hashers.BCryptSHA256PasswordHasher',
)
<commit_msg>Update settings.py<commit_after># -*- coding: utf-8 -*-

"""
Django settings for {{ project_name }} project.

Generated by 'django-admin startproject' using Django {{ django_version }}.

For more information on this file, see
https://docs.djangoproject.com/en/{{ docs_version }}/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/{{ docs_version }}/ref/settings/
"""

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os

from decouple import config, Csv

BASE_DIR = os.path.dirname(__file__)

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/{{ docs_version }}/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = config('SECRET_KEY')

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = config('DEBUG', default=False, cast=bool)

TEMPLATE_DEBUG = DEBUG

ALLOWED_HOSTS = config('ALLOWED_HOSTS', default='*', cast=Csv())

# Application definition

INSTALLED_APPS = (
    'flat',
    # django
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    # 3rd
    'debug_toolbar',
    'django_extensions',
    # project
    '{{ project_name }}.accounts',
    '{{ project_name }}.core',
)

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

ROOT_URLCONF = '{{ project_name }}.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [
            os.path.join(BASE_DIR, 'templates'),
        ],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = '{{ project_name }}.wsgi.application'

# Database
# https://docs.djangoproject.com/en/{{ docs_version }}/ref/settings/#databases

from dj_database_url import parse as db_url
DATABASES = {'default': config('DATABASE_URL', cast=db_url)}

# Internationalization
# https://docs.djangoproject.com/en/{{ docs_version }}/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/{{ docs_version }}/howto/static-files/

STATIC_URL = '/static/'

MEDIA_URL = '/media/'

STATIC_ROOT = os.path.join(BASE_DIR, '..', 'static-root')

MEDIA_ROOT = os.path.join(BASE_DIR, '..', 'media-root')

STATICFILES_DIRS = (
    os.path.join(BASE_DIR, 'static'),
    os.path.join(BASE_DIR, '..', 'bower_components'),
)

# Auth

AUTH_USER_MODEL = 'accounts.User'

LOGIN_URL = '/auth/login/'

LOGOUT_URL = '/auth/logout/'

LOGIN_REDIRECT_URL = '/'

PASSWORD_HASHERS = (
    'django.contrib.auth.hashers.BCryptSHA256PasswordHasher',
)
<|endoftext|>


<commit_before>"""Leetcode 451. Sort Characters By Frequency
Medium

URL: https://leetcode.com/problems/sort-characters-by-frequency/

Given a string, sort it in decreasing order based on the frequency of characters.

Example 1:
Input:
"tree"
Output:
"eert"
Explanation:
'e' appears twice while 'r' and 't' both appear once.
So 'e' must appear before both 'r' and 't'. Therefore "eetr" is also a valid answer.

Example 2:
Input:
"cccaaa"
Output:
"cccaaa"
Explanation:
Both 'c' and 'a' appear three times, so "aaaccc" is also a valid answer.
Note that "cacaca" is incorrect, as the same characters must be together.

Example 3:
Input:
"Aabb"
Output:
"bbAa"
Explanation:
"bbaA" is also a valid answer, but "Aabb" is incorrect.
Note that 'A' and 'a' are treated as two different characters.
"""

class SolutionCharFreqDict(object):
    def frequencySort(self, s):
        """
        :type s: str
        :rtype: str
        """
        from collections import defaultdict

        if not s:
            return ''

        # Use a dict to collect chars's frequencies.
        char_freqs = defaultdict(int)
        for c in s:
            char_freqs[c] += 1

        # Sort dict by values.
        sorted_char_freqs = sorted(char_freqs.items(),
                                   key=lambda x: x[1], reverse=True)

        # Convert dict to list with duplicated chars based on frequencies.
        sorted_chars = [char * freq for (char, freq) in sorted_char_freqs]
        return ''.join(sorted_chars)

def main():
    # Output: eert
    s = "tree"
    print SolutionCharFreqDict().frequencySort(s)

    # Output: cccaaa
    s = "cccaaa"
    print SolutionCharFreqDict().frequencySort(s)

    # Output: bbAa
    s = "Aabb"
    print SolutionCharFreqDict().frequencySort(s)

if __name__ == '__main__':
    main()
<commit_msg>Add time/space complexity<commit_after>"""Leetcode 451. Sort Characters By Frequency
Medium

URL: https://leetcode.com/problems/sort-characters-by-frequency/

Given a string, sort it in decreasing order based on the frequency of characters.

Example 1:
Input:
"tree"
Output:
"eert"
Explanation:
'e' appears twice while 'r' and 't' both appear once.
So 'e' must appear before both 'r' and 't'. Therefore "eetr" is also a valid answer.

Example 2:
Input:
"cccaaa"
Output:
"cccaaa"
Explanation:
Both 'c' and 'a' appear three times, so "aaaccc" is also a valid answer.
Note that "cacaca" is incorrect, as the same characters must be together.

Example 3:
Input:
"Aabb"
Output:
"bbAa"
Explanation:
"bbaA" is also a valid answer, but "Aabb" is incorrect.
Note that 'A' and 'a' are treated as two different characters.
"""

class SolutionCharFreqDict(object):
    def frequencySort(self, s):
        """
        :type s: str
        :rtype: str

        Time complexity: O(n*logn), where n is the length of s.
        Space complexity: O(n).
        """
        from collections import defaultdict

        if not s:
            return ''

        # Use a dict to collect chars's frequencies.
        char_freqs = defaultdict(int)
        for c in s:
            char_freqs[c] += 1

        # Sort dict by values.
        sorted_char_freqs = sorted(char_freqs.items(),
                                   key=lambda x: x[1], reverse=True)

        # Convert dict to list with duplicated chars based on frequencies.
        sorted_chars = [char * freq for (char, freq) in sorted_char_freqs]
        return ''.join(sorted_chars)

def main():
    # Output: eert
    s = "tree"
    print SolutionCharFreqDict().frequencySort(s)

    # Output: cccaaa
    s = "cccaaa"
    print SolutionCharFreqDict().frequencySort(s)

    # Output: bbAa
    s = "Aabb"
    print SolutionCharFreqDict().frequencySort(s)

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