<commit_before>import random

import cv2
import numpy as np
from os.path import basename
from zimpy.camera_preprocessor import preprocess_image

def load_image(imagepath):
    imagepath = 'IMG/'+basename(imagepath)
    image_array = cv2.imread(imagepath, 1)
    if image_array is None:
        print('File Not Found: {}'.format(imagepath))
    return image_array

def augment_brightness_camera_images(image):
    image1 = cv2.cvtColor(image, cv2.COLOR_RGB2HSV)
    random_bright = .25 + np.random.uniform()
    # print(random_bright)
    image1[:, :, 2] = image1[:, :, 2] * random_bright
    image1 = cv2.cvtColor(image1, cv2.COLOR_HSV2RGB)
    return image1

def batch_generator(X, Y, label, num_epochs, batch_size=32, output_shape=None, flip_images=True):
    population = len(X)
    counter = 0
    _index_in_epoch = 0
    start_i = 0
    _tot_epochs = 0
    batch_size = min(batch_size, population)

    print('Batch generating against the {} dataset with population {} and shape {}'.format(label, population, X.shape))
    while True:
        counter += 1
        print('batch gen iter {}'.format(counter))
        for i in range(batch_size):
            start_i = _index_in_epoch
            _index_in_epoch += batch_size
            if _index_in_epoch >= population:
                print('  sampled entire population. reshuffling deck and resetting all counters.')
                perm = np.arange(population)
                np.random.shuffle(perm)
                X = X[perm]
                Y = Y[perm]
                start_i = 0
                _index_in_epoch = batch_size
                _tot_epochs += 1
            end_i = _index_in_epoch

            X_batch = []
            y_batch = []
            # print('  yielding train items in range {}'.format(range(start_i, end_i)))
            for j in range(start_i, end_i):
                steering_angle = Y[j]
                image_path = None

                mode = 2
                if mode == 1:
                    if steering_angle < -0.01:
                        chance = random.random()
                        if chance > 0.75:
                            image_path = X[j].split(':')[0]
                            steering_angle *= 3.0
                        else:
                            if chance > 0.5:
                                image_path = X[j].split(':')[0]
                                steering_angle *= 2.0
                            else:
                                if chance > 0.25:
                                    image_path = X[j].split(':')[1]
                                    steering_angle *= 1.5
                                else:
                                    if True or random.random() > (1. - _tot_epochs / num_epochs):
                                        image_path = X[j].split(':')[1]
                                        # steering_angle += 0.05
                    else:
                        if steering_angle > 0.01:
                            chance = random.random()
                            if chance > 0.75:
                                image_path = X[j].split(':')[2]
                                steering_angle *= 3.0
                            else:
                                if chance > 0.5:
                                    image_path = X[j].split(':')[2]
                                    steering_angle *= 2.0
                                else:
                                    if chance > 0.25:
                                        image_path = X[j].split(':')[1]
                                        steering_angle *= 1.5
                                    else:
                                        if True or random.random() > (1. - _tot_epochs / num_epochs):
                                            image_path = X[j].split(':')[1]
                                            # steering_angle += 0.05
                        else:
                            # gradually increase our chances of intoducing
                            if True or random.random() > (1. - _tot_epochs / num_epochs):
                                image_path = X[j].split(':')[1]
                                # steering_angle += 0.05
                else:
                    image_path = X[j].split(':')[1]

                if image_path is not None:
                    # print(image_path)
                    image = load_image(image_path)
                    image = preprocess_image(image, output_shape=output_shape)

                    # steering_angle = np.array([[steering_angle]])
                    # steering_angle = np.array([steering_angle])
                    # image = image.reshape(1, output_shape[0], output_shape[1], output_shape[2])
                    # image = image.reshape(1, image.shape[0], image.shape[1], image.shape[2])
                    if image is not None:
                        if random.random() > 0.5:
                            X_batch.append(image)
                            y_batch.append(steering_angle)
                        else:
                            print('     # flipping image and steering')
                            X_batch.append(np.fliplr(image))
                            y_batch.append(-steering_angle)

            yield np.array(X_batch), np.array(y_batch)
<commit_msg>no print<commit_after>import random

import cv2
import numpy as np
from os.path import basename
from zimpy.camera_preprocessor import preprocess_image

def load_image(imagepath):
    imagepath = 'IMG/'+basename(imagepath)
    image_array = cv2.imread(imagepath, 1)
    if image_array is None:
        print('File Not Found: {}'.format(imagepath))
    return image_array

def augment_brightness_camera_images(image):
    image1 = cv2.cvtColor(image, cv2.COLOR_RGB2HSV)
    random_bright = .25 + np.random.uniform()
    # print(random_bright)
    image1[:, :, 2] = image1[:, :, 2] * random_bright
    image1 = cv2.cvtColor(image1, cv2.COLOR_HSV2RGB)
    return image1

def batch_generator(X, Y, label, num_epochs, batch_size=32, output_shape=None, flip_images=True):
    population = len(X)
    counter = 0
    _index_in_epoch = 0
    start_i = 0
    _tot_epochs = 0
    batch_size = min(batch_size, population)

    print('Batch generating against the {} dataset with population {} and shape {}'.format(label, population, X.shape))
    while True:
        counter += 1
        print('batch gen iter {}'.format(counter))
        for i in range(batch_size):
            start_i = _index_in_epoch
            _index_in_epoch += batch_size
            if _index_in_epoch >= population:
                print('  sampled entire population. reshuffling deck and resetting all counters.')
                perm = np.arange(population)
                np.random.shuffle(perm)
                X = X[perm]
                Y = Y[perm]
                start_i = 0
                _index_in_epoch = batch_size
                _tot_epochs += 1
            end_i = _index_in_epoch

            X_batch = []
            y_batch = []
            # print('  yielding train items in range {}'.format(range(start_i, end_i)))
            for j in range(start_i, end_i):
                steering_angle = Y[j]
                image_path = None

                mode = 2
                if mode == 1:
                    if steering_angle < -0.01:
                        chance = random.random()
                        if chance > 0.75:
                            image_path = X[j].split(':')[0]
                            steering_angle *= 3.0
                        else:
                            if chance > 0.5:
                                image_path = X[j].split(':')[0]
                                steering_angle *= 2.0
                            else:
                                if chance > 0.25:
                                    image_path = X[j].split(':')[1]
                                    steering_angle *= 1.5
                                else:
                                    if True or random.random() > (1. - _tot_epochs / num_epochs):
                                        image_path = X[j].split(':')[1]
                                        # steering_angle += 0.05
                    else:
                        if steering_angle > 0.01:
                            chance = random.random()
                            if chance > 0.75:
                                image_path = X[j].split(':')[2]
                                steering_angle *= 3.0
                            else:
                                if chance > 0.5:
                                    image_path = X[j].split(':')[2]
                                    steering_angle *= 2.0
                                else:
                                    if chance > 0.25:
                                        image_path = X[j].split(':')[1]
                                        steering_angle *= 1.5
                                    else:
                                        if True or random.random() > (1. - _tot_epochs / num_epochs):
                                            image_path = X[j].split(':')[1]
                                            # steering_angle += 0.05
                        else:
                            # gradually increase our chances of intoducing
                            if True or random.random() > (1. - _tot_epochs / num_epochs):
                                image_path = X[j].split(':')[1]
                                # steering_angle += 0.05
                else:
                    image_path = X[j].split(':')[1]

                if image_path is not None:
                    # print(image_path)
                    image = load_image(image_path)
                    image = preprocess_image(image, output_shape=output_shape)

                    # steering_angle = np.array([[steering_angle]])
                    # steering_angle = np.array([steering_angle])
                    # image = image.reshape(1, output_shape[0], output_shape[1], output_shape[2])
                    # image = image.reshape(1, image.shape[0], image.shape[1], image.shape[2])
                    if image is not None:
                        if random.random() > 0.5:
                            X_batch.append(image)
                            y_batch.append(steering_angle)
                        else:
                            # print('     # flipping image and steering')
                            X_batch.append(np.fliplr(image))
                            y_batch.append(-steering_angle)

            yield np.array(X_batch), np.array(y_batch)
<|endoftext|>


<commit_before>"""

##BOILERPLATE_COPYRIGHT
##BOILERPLATE_COPYRIGHT_END

"""

from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.bcrypt import Bcrypt
from flask.ext.login import LoginManager

import os

__version__ = "2.9.0"

try:
    __setup
except:
    __setup = False

def _parseConfig():
    '''
    '''
    try:
        mainApp.config.from_envvar('NOINK_CONFIGURATION')
    except:
        mainApp.config.from_object('noink.defaultConfig')

    mainApp.secret_key = mainApp.config['SECRET_KEY']

    # Setup our template pathing
    if mainApp.config['HTML_TEMPLATES']:
        __newTemplatePath = []
        from os.path import abspath
        for element in mainApp.config['HTML_TEMPLATES']:
            __newTemplatePath.append(abspath(element))
        mainApp.jinja_loader.searchpath = __newTemplatePath

def reInit():
    '''
    Call this method when you want to re-initialize as much as possible.
    '''
    _parseConfig()

if not __setup:
    mainApp = Flask("noink")
    mainApp.noinkVersion = __version__
    _parseConfig()
    mainDB = SQLAlchemy(mainApp)
    mainCrypt = Bcrypt(mainApp)
    loginManager = LoginManager()

    # filters
    from noink.filters import nofilter_breakSplit, nofilter_breakClean, \
            nofilter_newLines

    # blueprints
    from noink.blueprints.listEntries import listEntries
    from noink.blueprints.node import node
    from noink.blueprints.static import staticPage
    mainApp.register_blueprint(listEntries)
    mainApp.register_blueprint(node)
    mainApp.register_blueprint(staticPage)

    loginManager.init_app(mainApp)

    __setup = True

<commit_msg>babel<commit_after>"""

##BOILERPLATE_COPYRIGHT
##BOILERPLATE_COPYRIGHT_END

"""

from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.bcrypt import Bcrypt
from flask.ext.login import LoginManager
from flask.ext.babel import Babel

import os

__version__ = "2.9.0"

try:
    __setup
except:
    __setup = False

def _parseConfig():
    '''
    '''
    try:
        mainApp.config.from_envvar('NOINK_CONFIGURATION')
    except:
        mainApp.config.from_object('noink.defaultConfig')

    mainApp.secret_key = mainApp.config['SECRET_KEY']

    # Setup our template pathing
    if mainApp.config['HTML_TEMPLATES']:
        __newTemplatePath = []
        from os.path import abspath
        for element in mainApp.config['HTML_TEMPLATES']:
            __newTemplatePath.append(abspath(element))
        mainApp.jinja_loader.searchpath = __newTemplatePath

def reInit():
    '''
    Call this method when you want to re-initialize as much as possible.
    '''
    _parseConfig()

if not __setup:
    mainApp = Flask("noink")
    mainApp.noinkVersion = __version__
    _parseConfig()
    mainDB = SQLAlchemy(mainApp)
    mainCrypt = Bcrypt(mainApp)
    loginManager = LoginManager()
    babel = Babel(mainApp)

    # filters
    from noink.filters import nofilter_breakSplit, nofilter_breakClean, \
            nofilter_newLines

    # blueprints
    from noink.blueprints.listEntries import listEntries
    from noink.blueprints.node import node
    from noink.blueprints.static import staticPage
    mainApp.register_blueprint(listEntries)
    mainApp.register_blueprint(node)
    mainApp.register_blueprint(staticPage)

    loginManager.init_app(mainApp)

    __setup = True

<|endoftext|>


<commit_before>#############################################################################
##
## Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
## Contact: http://www.qt-project.org/legal
##
## This file is part of Qt Creator.
##
## Commercial License Usage
## Licensees holding valid commercial Qt licenses may use this file in
## accordance with the commercial license agreement provided with the
## Software or, alternatively, in accordance with the terms contained in
## a written agreement between you and Digia.  For licensing terms and
## conditions see http://qt.digia.com/licensing.  For further information
## use the contact form at http://qt.digia.com/contact-us.
##
## GNU Lesser General Public License Usage
## Alternatively, this file may be used under the terms of the GNU Lesser
## General Public License version 2.1 as published by the Free Software
## Foundation and appearing in the file LICENSE.LGPL included in the
## packaging of this file.  Please review the following information to
## ensure the GNU Lesser General Public License version 2.1 requirements
## will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
##
## In addition, as a special exception, Digia gives you certain additional
## rights.  These rights are described in the Digia Qt LGPL Exception
## version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
##
#############################################################################

source("../../shared/qtcreator.py")

import re
import tempfile
import __builtin__

currentSelectedTreeItem = None
warningOrError = re.compile('
((Error|Warning).*?)
')

def main():
    emptySettings = tempDir()
    __createMinimumIni__(emptySettings)
    SettingsPath = ' -settingspath "%s"' % emptySettings
    startApplication("qtcreator" + SettingsPath)
    if not startedWithoutPluginError():
        return
    invokeMenuItem("Tools", "Options...")
    __checkBuildAndRun__()
    clickButton(waitForObject(":Options.Cancel_QPushButton"))
    invokeMenuItem("File", "Exit")
    __checkCreatedSettings__(emptySettings)

def __createMinimumIni__(emptyParent):
    qtProjDir = os.path.join(emptyParent, "QtProject")
    os.mkdir(qtProjDir)
    iniFile = open(os.path.join(qtProjDir, "QtCreator.ini"), "w")
    iniFile.write("[%General]\n")
    iniFile.write("OverrideLanguage=C\n")
    iniFile.close()

def __checkBuildAndRun__():
    waitForObjectItem(":Options_QListView", "Build & Run")
    clickItem(":Options_QListView", "Build & Run", 14, 15, 0, Qt.LeftButton)
    # check compilers
    expectedCompilers = __getExpectedCompilers__()
    foundCompilers = []
    foundCompilerNames = []
    clickOnTab(":Options.qt_tabwidget_tabbar_QTabBar", "Compilers")
    compilerTV = waitForObject(":BuildAndRun_QTreeView")
    __iterateTree__(compilerTV, __compFunc__, foundCompilers, foundCompilerNames)
    test.verify(__compareCompilers__(foundCompilers, expectedCompilers),
                "Verifying found and expected compilers are equal.")
    # check debugger
    expectedDebuggers = __getExpectedDebuggers__()
    clickOnTab(":Options.qt_tabwidget_tabbar_QTabBar", "Debuggers")
    foundDebugger = []
    debuggerTV = waitForObject(":BuildAndRun_QTreeView")
    __iterateTree__(debuggerTV, __dbgFunc__, foundDebugger)
    test.verify(__compareDebuggers__(foundDebugger, expectedDebuggers),
                "Verifying found and expected debuggers are equal.")
    # check Qt versions
    qmakePath = which("qmake")
    foundQt = []
    clickOnTab(":Options.qt_tabwidget_tabbar_QTabBar", "Qt Versions")
    qtTW = waitForObject(":QtSupport__Internal__QtVersionManager.qtdirList_QTreeWidget")
    __iterateTree__(qtTW, __qtFunc__, foundQt, qmakePath)
    if foundQt:
        foundQt = foundQt[0]
    # check kits
    clickOnTab(":Options.qt_tabwidget_tabbar_QTabBar", "Kits")
    kitsTV = waitForObject(":BuildAndRun_QTreeView")
    __iterateTree__(kitsTV, __kitFunc__, foundQt, foundCompilerNames)

def __iterateTree__(treeObj, additionalFunc, *additionalParameters):
    global currentSelectedTreeItem
    model = treeObj.model()
    # 1st row: Auto-detected, 2nd row: Manual
    for sect in dumpIndices(model):
        sObj = "%s container=%s}" % (objectMap.realName(sect)[:-1], objectMap.realName(treeObj))
        items = dumpIndices(model, sect)
        doneItems = []
        for it in items:
            indexName = str(it.data().toString())
            itObj = "%s container=%s}" % (objectMap.realName(it)[:-1], sObj)
            alreadyDone = doneItems.count(itObj)
            doneItems.append(itObj)
            if alreadyDone:
                itObj = "%s occurrence='%d'}" % (itObj[:-1], alreadyDone + 1)
            currentSelectedTreeItem = waitForObject(itObj, 3000)
            mouseClick(currentSelectedTreeItem, 5, 5, 0, Qt.LeftButton)
            additionalFunc(indexName, *additionalParameters)
            currentSelectedTreeItem = None

def __compFunc__(it, foundComp, foundCompNames):
    try:
        waitFor("object.exists(':Path.Utils_BaseValidatingLineEdit')", 1000)
        pathLineEdit = findObject(":Path.Utils_BaseValidatingLineEdit")
        foundComp.append(str(pathLineEdit.text))
    except:
        label = findObject("{buddy={container=':qt_tabwidget_stackedwidget_QWidget' "
                           "text='Initialization:' type='QLabel' unnamed='1' visible='1'} "
                           "type='QLabel' unnamed='1' visible='1'}")
        foundComp.append({it:str(label.text)})
    foundCompNames.append(it)

def __dbgFunc__(it, foundDbg):
    waitFor("object.exists(':Path.Utils_BaseValidatingLineEdit')", 1000)
    pathLineEdit = findObject(":Path.Utils_BaseValidatingLineEdit")
    foundDbg.append(str(pathLineEdit.text))

def __qtFunc__(it, foundQt, qmakePath):
    foundQt.append(it)
    qtPath = str(waitForObject(":QtSupport__Internal__QtVersionManager.qmake_QLabel").text)
    if platform.system() in ('Microsoft', 'Windows'):
        qtPath = qtPath.lower()
        qmakePath = qmakePath.lower()
    test.compare(qtPath, qmakePath, "Verifying found and expected Qt version are equal.")
    try:
        errorLabel = findObject(":QtSupport__Internal__QtVersionManager.errorLabel.QLabel")
        test.warning("Detected error or warning: '%s'" % errorLabel.text)
    except:
        pass

def __kitFunc__(it, foundQt, foundCompNames):
    global currentSelectedTreeItem, warningOrError
    qtVersionStr = str(waitForObject(":Kits_QtVersion_QComboBox").currentText)
    test.compare(it, "Desktop (default)", "Verifying whether default Desktop kit has been created.")
    if foundQt:
        test.compare(qtVersionStr, foundQt, "Verifying if Qt versions match.")
    compilerCombo = waitForObject(":Compiler:_QComboBox")
    test.verify(str(compilerCombo.currentText) in foundCompNames,
                "Verifying if one of the found compilers had been set.")
    if currentSelectedTreeItem:
        foundWarningOrError = warningOrError.search(str(currentSelectedTreeItem.toolTip))
        if foundWarningOrError:
            details = str(foundWarningOrError.group(1)).replace("
", "\n")
            details = details.replace("", "").replace("", "")
            test.warning("Detected error and/or warning: %s" % details)

def __getExpectedCompilers__():
    expected = []
    if platform.system() in ('Microsoft', 'Windows'):
        expected.extend(__getWinCompilers__())
    compilers = ["g++"]
    if platform.system() in ('Linux', 'Darwin'):
        compilers.extend(["g++-4.0", "g++-4.2", "clang++"])
    for compiler in compilers:
        compilerPath = which(compiler)
        if compilerPath:
            if compiler == 'clang++':
                if subprocess.call(['clang++', '-dumpmachine']) != 0:
                    test.warning("clang found in PATH, but version is not supported.")
                    continue
            expected.append(compilerPath)
    return expected

def __getWinCompilers__():
    result = []
    winEnvVars = __getWinEnvVars__()
    for record in testData.dataset("win_compiler_paths.tsv"):
        envvar = winEnvVars.get(testData.field(record, "envvar"), "")
        compiler = os.path.abspath(os.path.join(envvar, testData.field(record, "path"),
                                                testData.field(record, "file")))
        if os.path.exists(compiler):
            parameters = testData.field(record, "displayedParameters").split(",")
            usedParameters = testData.field(record, "usedParameters").split(",")
            if testData.field(record, "isSDK") == "true":
                for para, used in zip(parameters, usedParameters):
                    result.append(
                                  {"%s \(.*?\) \(%s\)" % (testData.field(record, 'displayName'),
                                                          para)
                                   :"%s %s" % (compiler, used)})
            else:
                for para, used in zip(parameters, usedParameters):
                    result.append({"%s (%s)" % (testData.field(record, 'displayName'), para)
                                   :"%s %s" % (compiler, used)})
    return result

# using os.getenv() or getOutputFromCmdline() do not work - they would return C:\Program Files (x86)
# for %ProgramFiles% as well as for %ProgramFiles(x86)% when using Python 32bit on 64bit machines
def __getWinEnvVars__():
    result = {}
    tmpF, tmpFPath = tempfile.mkstemp()
    envvars = subprocess.call('set', stdout=tmpF, shell=True)
    os.close(tmpF)
    tmpF = open(tmpFPath, "r")
    for line in tmpF:
        tmp = line.split("=")
        result[tmp[0]] = tmp[1]
    tmpF.close()
    os.remove(tmpFPath)
    return result

def __getExpectedDebuggers__():
    result = []
    if platform.system() in ('Microsoft', 'Windows'):
        result.extend(__getCDB__())
    debuggers = ["gdb", "lldb"]
    result.extend(filter(None, map(which, debuggers)))
    if platform.system() == 'Darwin':
        xcodeLLDB = getOutputFromCmdline("xcrun --find lldb").strip("\n")
        if xcodeLLDB and os.path.exists(xcodeLLDB) and xcodeLLDB not in result:
            result.append(xcodeLLDB)
    return result

def __getCDB__():
    result = []
    possibleLocations = ["C:\\Program Files\\Debugging Tools for Windows (x64)",
                         "C:\\Program Files (x86)\\Windows Kits\\8.0\\Debuggers\\x86",
                         "C:\\Program Files\\Windows Kits\\8.0\\Debuggers\\x86",
                         "C:\\Program Files (x86)\\Windows Kits\\8.1\\Debuggers\\x86",
                         "C:\\Program Files\\Windows Kits\\8.1\\Debuggers\\x86"]
    for cdbPath in possibleLocations:
        cdb = os.path.join(cdbPath, "cdb.exe")
        if os.path.exists(cdb):
            result.append(cdb)
    return result

def __compareCompilers__(foundCompilers, expectedCompilers):
    equal = True
    flags = 0
    isWin = platform.system() in ('Microsoft', 'Windows')
    if isWin:
        flags = re.IGNORECASE
    for currentFound in foundCompilers:
        if isinstance(currentFound, dict):
            foundExp = False
            for currentExp in expectedCompilers:
                if isinstance(currentExp, (str, unicode)):
                    continue
                key = currentExp.keys()[0]
                # the regex .*? is used for the different possible version strings of the WinSDK
                # if it's present a regex will be validated otherwise simple string comparison
                if (((".*?" in key and re.match(key, currentFound.keys()[0], flags))
                    or currentFound.keys() == currentExp.keys())):
                    if ((isWin and os.path.abspath(currentFound.values()[0].lower())
                         == os.path.abspath(currentExp.values()[0].lower()))
                        or currentFound.values() == currentExp.values()):
                        foundExp = True
                        break
                equal = foundExp
        else:
            if isWin:
                equal = currentFound.lower() in __lowerStrs__(expectedCompilers)
            else:
                equal = currentFound in expectedCompilers
        if not equal:
            test.fail("Found '%s' but was not expected." % str(currentFound),
                      str(expectedCompilers))
            break
    return equal

def __compareDebuggers__(foundDebuggers, expectedDebuggers):
    if not len(foundDebuggers) == len(expectedDebuggers):
        test.log("Number of found and expected debuggers do not match.",
                 "Found: %s\nExpected: %s" % (str(foundDebuggers), str(expectedDebuggers)))
        return False
    if platform.system() in ('Microsoft', 'Windows'):
        foundSet = set(__lowerStrs__(foundDebuggers))
        expectedSet = set(__lowerStrs__(expectedDebuggers))
    else:
        foundSet = set(foundDebuggers)
        expectedSet = set(expectedDebuggers)
    if not (test.verify(not foundSet.symmetric_difference(expectedSet),
                        "Verifying expected and found debuggers match.")):
        test.log("Found debuggers: %s" % foundDebuggers,
                 "Expected debuggers: %s" % expectedDebuggers)
        return False
    return True

def __lowerStrs__(iterable):
    for it in iterable:
        if isinstance(it, (str, unicode)):
            yield it.lower()
        else:
            yield it

def __checkCreatedSettings__(settingsFolder):
    waitForCleanShutdown()
    qtProj = os.path.join(settingsFolder, "QtProject")
    folders = []
    files = [{os.path.join(qtProj, "QtCreator.db"):0},
             {os.path.join(qtProj, "QtCreator.ini"):30}]
    folders.append(os.path.join(qtProj, "qtcreator"))
    files.extend([{os.path.join(folders[0], "debuggers.xml"):0},
                  {os.path.join(folders[0], "devices.xml"):0},
                  {os.path.join(folders[0], "helpcollection.qhc"):0},
                  {os.path.join(folders[0], "profiles.xml"):0},
                  {os.path.join(folders[0], "qtversion.xml"):0},
                  {os.path.join(folders[0], "toolchains.xml"):0}])
    folders.extend([os.path.join(folders[0], "generic-highlighter"),
                    os.path.join(folders[0], "json"),
                    os.path.join(folders[0], "macros")])
    for f in folders:
        test.verify(os.path.isdir(f),
                    "Verifying whether folder '%s' has been created." % os.path.basename(f))
    for f in files:
        fName = f.keys()[0]
        fMinSize = f.values()[0]
        text = "created non-empty"
        if fMinSize > 0:
            text = "modified"
        test.verify(os.path.isfile(fName) and os.path.getsize(fName) > fMinSize,
                    "Verifying whether file '%s' has been %s." % (os.path.basename(fName), text))
<commit_msg>Squish: Support different lldb versions on Linux<commit_after>#############################################################################
##
## Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
## Contact: http://www.qt-project.org/legal
##
## This file is part of Qt Creator.
##
## Commercial License Usage
## Licensees holding valid commercial Qt licenses may use this file in
## accordance with the commercial license agreement provided with the
## Software or, alternatively, in accordance with the terms contained in
## a written agreement between you and Digia.  For licensing terms and
## conditions see http://qt.digia.com/licensing.  For further information
## use the contact form at http://qt.digia.com/contact-us.
##
## GNU Lesser General Public License Usage
## Alternatively, this file may be used under the terms of the GNU Lesser
## General Public License version 2.1 as published by the Free Software
## Foundation and appearing in the file LICENSE.LGPL included in the
## packaging of this file.  Please review the following information to
## ensure the GNU Lesser General Public License version 2.1 requirements
## will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
##
## In addition, as a special exception, Digia gives you certain additional
## rights.  These rights are described in the Digia Qt LGPL Exception
## version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
##
#############################################################################

source("../../shared/qtcreator.py")

import re
import tempfile
import __builtin__

currentSelectedTreeItem = None
warningOrError = re.compile('
((Error|Warning).*?)
')

def main():
    emptySettings = tempDir()
    __createMinimumIni__(emptySettings)
    SettingsPath = ' -settingspath "%s"' % emptySettings
    startApplication("qtcreator" + SettingsPath)
    if not startedWithoutPluginError():
        return
    invokeMenuItem("Tools", "Options...")
    __checkBuildAndRun__()
    clickButton(waitForObject(":Options.Cancel_QPushButton"))
    invokeMenuItem("File", "Exit")
    __checkCreatedSettings__(emptySettings)

def __createMinimumIni__(emptyParent):
    qtProjDir = os.path.join(emptyParent, "QtProject")
    os.mkdir(qtProjDir)
    iniFile = open(os.path.join(qtProjDir, "QtCreator.ini"), "w")
    iniFile.write("[%General]\n")
    iniFile.write("OverrideLanguage=C\n")
    iniFile.close()

def __checkBuildAndRun__():
    waitForObjectItem(":Options_QListView", "Build & Run")
    clickItem(":Options_QListView", "Build & Run", 14, 15, 0, Qt.LeftButton)
    # check compilers
    expectedCompilers = __getExpectedCompilers__()
    foundCompilers = []
    foundCompilerNames = []
    clickOnTab(":Options.qt_tabwidget_tabbar_QTabBar", "Compilers")
    compilerTV = waitForObject(":BuildAndRun_QTreeView")
    __iterateTree__(compilerTV, __compFunc__, foundCompilers, foundCompilerNames)
    test.verify(__compareCompilers__(foundCompilers, expectedCompilers),
                "Verifying found and expected compilers are equal.")
    # check debugger
    expectedDebuggers = __getExpectedDebuggers__()
    clickOnTab(":Options.qt_tabwidget_tabbar_QTabBar", "Debuggers")
    foundDebugger = []
    debuggerTV = waitForObject(":BuildAndRun_QTreeView")
    __iterateTree__(debuggerTV, __dbgFunc__, foundDebugger)
    test.verify(__compareDebuggers__(foundDebugger, expectedDebuggers),
                "Verifying found and expected debuggers are equal.")
    # check Qt versions
    qmakePath = which("qmake")
    foundQt = []
    clickOnTab(":Options.qt_tabwidget_tabbar_QTabBar", "Qt Versions")
    qtTW = waitForObject(":QtSupport__Internal__QtVersionManager.qtdirList_QTreeWidget")
    __iterateTree__(qtTW, __qtFunc__, foundQt, qmakePath)
    if foundQt:
        foundQt = foundQt[0]
    # check kits
    clickOnTab(":Options.qt_tabwidget_tabbar_QTabBar", "Kits")
    kitsTV = waitForObject(":BuildAndRun_QTreeView")
    __iterateTree__(kitsTV, __kitFunc__, foundQt, foundCompilerNames)

def __iterateTree__(treeObj, additionalFunc, *additionalParameters):
    global currentSelectedTreeItem
    model = treeObj.model()
    # 1st row: Auto-detected, 2nd row: Manual
    for sect in dumpIndices(model):
        sObj = "%s container=%s}" % (objectMap.realName(sect)[:-1], objectMap.realName(treeObj))
        items = dumpIndices(model, sect)
        doneItems = []
        for it in items:
            indexName = str(it.data().toString())
            itObj = "%s container=%s}" % (objectMap.realName(it)[:-1], sObj)
            alreadyDone = doneItems.count(itObj)
            doneItems.append(itObj)
            if alreadyDone:
                itObj = "%s occurrence='%d'}" % (itObj[:-1], alreadyDone + 1)
            currentSelectedTreeItem = waitForObject(itObj, 3000)
            mouseClick(currentSelectedTreeItem, 5, 5, 0, Qt.LeftButton)
            additionalFunc(indexName, *additionalParameters)
            currentSelectedTreeItem = None

def __compFunc__(it, foundComp, foundCompNames):
    try:
        waitFor("object.exists(':Path.Utils_BaseValidatingLineEdit')", 1000)
        pathLineEdit = findObject(":Path.Utils_BaseValidatingLineEdit")
        foundComp.append(str(pathLineEdit.text))
    except:
        label = findObject("{buddy={container=':qt_tabwidget_stackedwidget_QWidget' "
                           "text='Initialization:' type='QLabel' unnamed='1' visible='1'} "
                           "type='QLabel' unnamed='1' visible='1'}")
        foundComp.append({it:str(label.text)})
    foundCompNames.append(it)

def __dbgFunc__(it, foundDbg):
    waitFor("object.exists(':Path.Utils_BaseValidatingLineEdit')", 1000)
    pathLineEdit = findObject(":Path.Utils_BaseValidatingLineEdit")
    foundDbg.append(str(pathLineEdit.text))

def __qtFunc__(it, foundQt, qmakePath):
    foundQt.append(it)
    qtPath = str(waitForObject(":QtSupport__Internal__QtVersionManager.qmake_QLabel").text)
    if platform.system() in ('Microsoft', 'Windows'):
        qtPath = qtPath.lower()
        qmakePath = qmakePath.lower()
    test.compare(qtPath, qmakePath, "Verifying found and expected Qt version are equal.")
    try:
        errorLabel = findObject(":QtSupport__Internal__QtVersionManager.errorLabel.QLabel")
        test.warning("Detected error or warning: '%s'" % errorLabel.text)
    except:
        pass

def __kitFunc__(it, foundQt, foundCompNames):
    global currentSelectedTreeItem, warningOrError
    qtVersionStr = str(waitForObject(":Kits_QtVersion_QComboBox").currentText)
    test.compare(it, "Desktop (default)", "Verifying whether default Desktop kit has been created.")
    if foundQt:
        test.compare(qtVersionStr, foundQt, "Verifying if Qt versions match.")
    compilerCombo = waitForObject(":Compiler:_QComboBox")
    test.verify(str(compilerCombo.currentText) in foundCompNames,
                "Verifying if one of the found compilers had been set.")
    if currentSelectedTreeItem:
        foundWarningOrError = warningOrError.search(str(currentSelectedTreeItem.toolTip))
        if foundWarningOrError:
            details = str(foundWarningOrError.group(1)).replace("
", "\n")
            details = details.replace("", "").replace("", "")
            test.warning("Detected error and/or warning: %s" % details)

def __getExpectedCompilers__():
    expected = []
    if platform.system() in ('Microsoft', 'Windows'):
        expected.extend(__getWinCompilers__())
    compilers = ["g++"]
    if platform.system() in ('Linux', 'Darwin'):
        compilers.extend(["g++-4.0", "g++-4.2", "clang++"])
    for compiler in compilers:
        compilerPath = which(compiler)
        if compilerPath:
            if compiler == 'clang++':
                if subprocess.call(['clang++', '-dumpmachine']) != 0:
                    test.warning("clang found in PATH, but version is not supported.")
                    continue
            expected.append(compilerPath)
    return expected

def __getWinCompilers__():
    result = []
    winEnvVars = __getWinEnvVars__()
    for record in testData.dataset("win_compiler_paths.tsv"):
        envvar = winEnvVars.get(testData.field(record, "envvar"), "")
        compiler = os.path.abspath(os.path.join(envvar, testData.field(record, "path"),
                                                testData.field(record, "file")))
        if os.path.exists(compiler):
            parameters = testData.field(record, "displayedParameters").split(",")
            usedParameters = testData.field(record, "usedParameters").split(",")
            if testData.field(record, "isSDK") == "true":
                for para, used in zip(parameters, usedParameters):
                    result.append(
                                  {"%s \(.*?\) \(%s\)" % (testData.field(record, 'displayName'),
                                                          para)
                                   :"%s %s" % (compiler, used)})
            else:
                for para, used in zip(parameters, usedParameters):
                    result.append({"%s (%s)" % (testData.field(record, 'displayName'), para)
                                   :"%s %s" % (compiler, used)})
    return result

# using os.getenv() or getOutputFromCmdline() do not work - they would return C:\Program Files (x86)
# for %ProgramFiles% as well as for %ProgramFiles(x86)% when using Python 32bit on 64bit machines
def __getWinEnvVars__():
    result = {}
    tmpF, tmpFPath = tempfile.mkstemp()
    envvars = subprocess.call('set', stdout=tmpF, shell=True)
    os.close(tmpF)
    tmpF = open(tmpFPath, "r")
    for line in tmpF:
        tmp = line.split("=")
        result[tmp[0]] = tmp[1]
    tmpF.close()
    os.remove(tmpFPath)
    return result

def __getExpectedDebuggers__():
    result = []
    if platform.system() in ('Microsoft', 'Windows'):
        result.extend(__getCDB__())
    debuggers = ["gdb", "lldb"]
    result.extend(filter(None, map(which, debuggers)))
    if platform.system() == 'Linux':
        result.extend(findAllFilesInPATH("lldb-*"))
    if platform.system() == 'Darwin':
        xcodeLLDB = getOutputFromCmdline("xcrun --find lldb").strip("\n")
        if xcodeLLDB and os.path.exists(xcodeLLDB) and xcodeLLDB not in result:
            result.append(xcodeLLDB)
    return result

def __getCDB__():
    result = []
    possibleLocations = ["C:\\Program Files\\Debugging Tools for Windows (x64)",
                         "C:\\Program Files (x86)\\Windows Kits\\8.0\\Debuggers\\x86",
                         "C:\\Program Files\\Windows Kits\\8.0\\Debuggers\\x86",
                         "C:\\Program Files (x86)\\Windows Kits\\8.1\\Debuggers\\x86",
                         "C:\\Program Files\\Windows Kits\\8.1\\Debuggers\\x86"]
    for cdbPath in possibleLocations:
        cdb = os.path.join(cdbPath, "cdb.exe")
        if os.path.exists(cdb):
            result.append(cdb)
    return result

def __compareCompilers__(foundCompilers, expectedCompilers):
    equal = True
    flags = 0
    isWin = platform.system() in ('Microsoft', 'Windows')
    if isWin:
        flags = re.IGNORECASE
    for currentFound in foundCompilers:
        if isinstance(currentFound, dict):
            foundExp = False
            for currentExp in expectedCompilers:
                if isinstance(currentExp, (str, unicode)):
                    continue
                key = currentExp.keys()[0]
                # the regex .*? is used for the different possible version strings of the WinSDK
                # if it's present a regex will be validated otherwise simple string comparison
                if (((".*?" in key and re.match(key, currentFound.keys()[0], flags))
                    or currentFound.keys() == currentExp.keys())):
                    if ((isWin and os.path.abspath(currentFound.values()[0].lower())
                         == os.path.abspath(currentExp.values()[0].lower()))
                        or currentFound.values() == currentExp.values()):
                        foundExp = True
                        break
                equal = foundExp
        else:
            if isWin:
                equal = currentFound.lower() in __lowerStrs__(expectedCompilers)
            else:
                equal = currentFound in expectedCompilers
        if not equal:
            test.fail("Found '%s' but was not expected." % str(currentFound),
                      str(expectedCompilers))
            break
    return equal

def __compareDebuggers__(foundDebuggers, expectedDebuggers):
    if not len(foundDebuggers) == len(expectedDebuggers):
        test.log("Number of found and expected debuggers do not match.",
                 "Found: %s\nExpected: %s" % (str(foundDebuggers), str(expectedDebuggers)))
        return False
    if platform.system() in ('Microsoft', 'Windows'):
        foundSet = set(__lowerStrs__(foundDebuggers))
        expectedSet = set(__lowerStrs__(expectedDebuggers))
    else:
        foundSet = set(foundDebuggers)
        expectedSet = set(expectedDebuggers)
    if not (test.verify(not foundSet.symmetric_difference(expectedSet),
                        "Verifying expected and found debuggers match.")):
        test.log("Found debuggers: %s" % foundDebuggers,
                 "Expected debuggers: %s" % expectedDebuggers)
        return False
    return True

def __lowerStrs__(iterable):
    for it in iterable:
        if isinstance(it, (str, unicode)):
            yield it.lower()
        else:
            yield it

def __checkCreatedSettings__(settingsFolder):
    waitForCleanShutdown()
    qtProj = os.path.join(settingsFolder, "QtProject")
    folders = []
    files = [{os.path.join(qtProj, "QtCreator.db"):0},
             {os.path.join(qtProj, "QtCreator.ini"):30}]
    folders.append(os.path.join(qtProj, "qtcreator"))
    files.extend([{os.path.join(folders[0], "debuggers.xml"):0},
                  {os.path.join(folders[0], "devices.xml"):0},
                  {os.path.join(folders[0], "helpcollection.qhc"):0},
                  {os.path.join(folders[0], "profiles.xml"):0},
                  {os.path.join(folders[0], "qtversion.xml"):0},
                  {os.path.join(folders[0], "toolchains.xml"):0}])
    folders.extend([os.path.join(folders[0], "generic-highlighter"),
                    os.path.join(folders[0], "json"),
                    os.path.join(folders[0], "macros")])
    for f in folders:
        test.verify(os.path.isdir(f),
                    "Verifying whether folder '%s' has been created." % os.path.basename(f))
    for f in files:
        fName = f.keys()[0]
        fMinSize = f.values()[0]
        text = "created non-empty"
        if fMinSize > 0:
            text = "modified"
        test.verify(os.path.isfile(fName) and os.path.getsize(fName) > fMinSize,
                    "Verifying whether file '%s' has been %s." % (os.path.basename(fName), text))

def findAllFilesInPATH(programGlob):
    result = []
    for path in os.environ["PATH"].split(os.pathsep):
        files = filter(os.path.isfile, glob.glob(os.path.join(path, programGlob)))
        result.extend(files)
    return result
<|endoftext|>


<commit_before>import logging
import openahjo_activity_streams.exceptions as ex
import requests

def scrape_and_push(scrape, convert, push):
    def event():
        try:
            agenda_items = scrape()
            for item in agenda_items:
                activity = convert(item)
                push(activity)
        except (ex.PushFailureException, ex.ConvertFailureException, ex.ScrapeFailureException):
            pass

    return event

def scraper(coracle_endpoint, openahjo_endpoint):
    def scrape():
        coracle_timestamp_response = requests.get(coracle_endpoint)

        if coracle_timestamp_response.status_code != 200:
            raise ex.ScrapeFailureException

        latest_published_time = coracle_timestamp_response.json().get('latest-published-timestamp')
        if latest_published_time is not None:
            logging.info("successful request for latest_published_time " + latest_published_time)
        else:
            logging.info("no latest_published_time is returned")

        agenda_response = requests.get(openahjo_endpoint,
                                       params={'order_by': 'last_modified_time',
                                               'last_modified_time__gte': latest_published_time})

        if agenda_response.status_code != 200:
            raise ex.ScrapeFailureException

        agenda_items = agenda_response.json().get('objects')
        logging.info("scraped " + str(len(agenda_items)) + " items from OpenAhjo")
        return agenda_items

    return scrape

def pusher(coracle_endpoint, bearer_token):
    def push(item):
        response = requests.post(coracle_endpoint,
                                 json=item,
                                 headers={'bearer_token': bearer_token})

        logging.info("pushing to " + coracle_endpoint + " response " + str(response.status_code))
        if response.status_code != 201:
            raise ex.PushFailureException

    return push
<commit_msg>CW + AW | 0 | fix bearer-token header to match update on coracle<commit_after>import logging
import openahjo_activity_streams.exceptions as ex
import requests

def scrape_and_push(scrape, convert, push):
    def event():
        try:
            agenda_items = scrape()
            for item in agenda_items:
                activity = convert(item)
                push(activity)
        except (ex.PushFailureException, ex.ConvertFailureException, ex.ScrapeFailureException):
            pass

    return event

def scraper(coracle_endpoint, openahjo_endpoint):
    def scrape():
        coracle_timestamp_response = requests.get(coracle_endpoint)

        if coracle_timestamp_response.status_code != 200:
            raise ex.ScrapeFailureException

        latest_published_time = coracle_timestamp_response.json().get('latest-published-timestamp')
        if latest_published_time is not None:
            logging.info("successful request for latest_published_time " + latest_published_time)
        else:
            logging.info("no latest_published_time is returned")

        agenda_response = requests.get(openahjo_endpoint,
                                       params={'order_by': 'last_modified_time',
                                               'last_modified_time__gte': latest_published_time})

        if agenda_response.status_code != 200:
            raise ex.ScrapeFailureException

        agenda_items = agenda_response.json().get('objects')
        logging.info("scraped " + str(len(agenda_items)) + " items from OpenAhjo")
        return agenda_items

    return scrape

def pusher(coracle_endpoint, bearer_token):
    def push(item):
        response = requests.post(coracle_endpoint,
                                 json=item,
                                 headers={'bearer-token': bearer_token})

        logging.info("pushing to " + coracle_endpoint + " response " + str(response.status_code))
        if response.status_code != 201:
            raise ex.PushFailureException

    return push
<|endoftext|>


<commit_before>import os

import mock
from django.test import TestCase
from rest_framework import serializers

from kolibri.core.auth.models import Facility
from kolibri.core.auth.models import FacilityUser
from kolibri.core.logger.csv_export import CSV_EXPORT_FILENAMES
from kolibri.core.logger.tasks import ExportLogCSVValidator
from kolibri.utils import conf

@mock.patch.object(os, "mkdir")
class StartExportLogCSVTestCase(TestCase):
    @classmethod
    def setUpTestData(cls):
        cls.facility = Facility.objects.create(name="pytest_facility")
        cls.facility_user = FacilityUser.objects.create(
            username="pytest_user", facility=cls.facility
        )

    def test_validator_raises_validation_error_on_invalid_logtype(self, mock_os_mkdir):
        with self.assertRaises(serializers.ValidationError):
            ExportLogCSVValidator(
                data={
                    "type": "kolibri.core.logger.tasks.exportlogcsv",
                    "log_type": "invalid",
                },
                context={"user": self.facility_user},
            ).is_valid(raise_exception=True)

    def test_validator_sets_right_metadata_summary(self, mock_os_mkdir):
        validator = ExportLogCSVValidator(
            data={
                "type": "kolibri.core.logger.tasks.exportlogcsv",
                "log_type": "summary",
            },
            context={"user": self.facility_user},
        )
        validator.is_valid(raise_exception=True)
        filepath = os.path.join(
            conf.KOLIBRI_HOME,
            "log_export",
            CSV_EXPORT_FILENAMES["summary"].format(
                self.facility.name, self.facility.id[:4]
            ),
        )
        self.assertEqual(
            validator.validated_data,
            {
                "facility_id": self.facility.id,
                "args": ["summary", filepath, self.facility.id],
                "extra_metadata": {
                    "started_by": self.facility_user.id,
                    "started_by_username": self.facility_user.username,
                },
            },
        )

    def test_validator_sets_right_metadata_session(self, mock_os_mkdir):
        validator = ExportLogCSVValidator(
            data={
                "type": "kolibri.core.logger.tasks.exportlogcsv",
                "log_type": "session",
            },
            context={"user": self.facility_user},
        )
        validator.is_valid(raise_exception=True)
        filepath = os.path.join(
            conf.KOLIBRI_HOME,
            "log_export",
            CSV_EXPORT_FILENAMES["session"].format(
                self.facility.name, self.facility.id[:4]
            ),
        )
        self.assertEqual(
            validator.validated_data,
            {
                "facility_id": self.facility.id,
                "args": ["session", filepath, self.facility.id],
                "extra_metadata": {
                    "started_by": self.facility_user.id,
                    "started_by_username": self.facility_user.username,
                },
            },
        )
<commit_msg>Update logger task tests for updated validator.<commit_after>from django.test import TestCase

from kolibri.core.auth.models import Facility
from kolibri.core.auth.models import FacilityUser
from kolibri.core.logger.tasks import ExportLogCSVValidator

class StartExportLogCSVTestCase(TestCase):
    @classmethod
    def setUpTestData(cls):
        cls.facility = Facility.objects.create(name="pytest_facility")
        cls.facility_user = FacilityUser.objects.create(
            username="pytest_user", facility=cls.facility
        )

    def test_validator_sets_right_metadata(self):
        validator = ExportLogCSVValidator(
            data={
                "type": "kolibri.core.logger.tasks.exportsummarylogcsv",
            },
            context={"user": self.facility_user},
        )
        validator.is_valid(raise_exception=True)
        self.assertEqual(
            validator.validated_data,
            {
                "facility_id": self.facility.id,
                "args": [self.facility.id],
                "extra_metadata": {
                    "started_by": self.facility_user.id,
                    "started_by_username": self.facility_user.username,
                },
            },
        )
<|endoftext|>


<commit_before>#
#   Copyright (c) 2015, Scott J Maddox
#
#   This file is part of Open Band Parameters Device Simulator (OBPDS).
#
#   OBPDS is free software: you can redistribute it and/or modify
#   it under the terms of the GNU Affero General Public License as published
#   by the Free Software Foundation, either version 3 of the License, or
#   (at your option) any later version.
#
#   OBPDS is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#   GNU Affero General Public License for more details.
#
#   You should have received a copy of the GNU Affero General Public License
#   along with OBPDS.  If not, see <http://www.gnu.org/licenses/>.
#
#############################################################################

import numpy

__all__ = ['Solution', 'EquilibriumSolution']

class Solution(object):
    pass

class FlatbandSolution(Solution):
    def __init__(self, T, N, x, Ev, Ec_Gamma, Ec_L, Ec_X, Ec, Ei):
        self.T = T
        self.N = N
        self.x = x
        self.Ev = Ev
        self.Ec_Gamma = Ec_Gamma
        self.Ec_L = Ec_L
        self.Ec_X = Ec_X
        self.Ec = Ec
        self.Ei = Ei

class EquilibriumSolution(Solution):
    def __init__(self, T, N, x, Na, Nd,
                 Ev, Ec_Gamma, Ec_L, Ec_X, Ec, Ei,
                 psi, n_Gamma, n_L, n_X, n, p):
        self.T = T
        self.N = N
        self.x = x
        self.Na = Na
        self.Nd = Nd
        self.Ev = Ev
        self.Ec_Gamma = Ec_Gamma
        self.Ec_L = Ec_L
        self.Ec_X = Ec_X
        self.Ec = Ec
        self.Ei = Ei
        self.psi = psi
        self.n_Gamma = n_Gamma
        self.n_L = n_L
        self.n_X = n_X
        self.n = n
        self.p = p
        self.Ef = numpy.zeros(N)<commit_msg>add `ZeroCurrentSolution` to `solution` module<commit_after>#
#   Copyright (c) 2015, Scott J Maddox
#
#   This file is part of Open Band Parameters Device Simulator (OBPDS).
#
#   OBPDS is free software: you can redistribute it and/or modify
#   it under the terms of the GNU Affero General Public License as published
#   by the Free Software Foundation, either version 3 of the License, or
#   (at your option) any later version.
#
#   OBPDS is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#   GNU Affero General Public License for more details.
#
#   You should have received a copy of the GNU Affero General Public License
#   along with OBPDS.  If not, see <http://www.gnu.org/licenses/>.
#
#############################################################################

import numpy

__all__ = ['Solution', 'EquilibriumSolution']

class Solution(object):
    pass

class FlatbandSolution(Solution):
    def __init__(self, T, N, x, Ev, Ec_Gamma, Ec_L, Ec_X, Ec, Ei):
        self.T = T
        self.N = N
        self.x = x
        self.Ev = Ev
        self.Ec_Gamma = Ec_Gamma
        self.Ec_L = Ec_L
        self.Ec_X = Ec_X
        self.Ec = Ec
        self.Ei = Ei

class ZeroCurrentSolution(Solution):
    def __init__(self, T, N, x, Na, Nd,
                 Fp, Fn,
                 Ev, Ec_Gamma, Ec_L, Ec_X, Ec, Ei,
                 psi, n_Gamma, n_L, n_X, n, p):
        self.T = T
        self.N = N
        self.x = x
        self.Na = Na
        self.Nd = Nd
        self.Fp = Fp  # quasi-Fermi energy for holes
        self.Fn = Fn  # quasi-Fermi energy for electrons
        self.Ev = Ev
        self.Ec_Gamma = Ec_Gamma
        self.Ec_L = Ec_L
        self.Ec_X = Ec_X
        self.Ec = Ec
        self.Ei = Ei
        self.psi = psi
        self.n_Gamma = n_Gamma
        self.n_L = n_L
        self.n_X = n_X
        self.n = n
        self.p = p

class EquilibriumSolution(ZeroCurrentSolution):
    def __new__(self, zcs):
        zcs.Ef = numpy.zeros(zcs.N)  # Fermi energy
        return zcs<|endoftext|>


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

""" Module for grid plotting canvas.
"""

import numpy as np
import matplotlib.pyplot as plt

from catplot.canvas import Canvas
from catplot.grid_components.nodes import Node2D
from catplot.grid_components.edges import Edge2D, Arrow2D
from catplot.grid_components.supercell import SuperCell2D

class Grid2DCanvas(Canvas):
    """ Canvas for 2D grid plotting.
    """
    def __init__(self, **kwargs):
        super(Grid2DCanvas, self).__init__(**kwargs)

        # Equalize the scale of x and y axis.
        self.axes.set_aspect("equal")

        # Attributes for 2D grid canvas.
        self.nodes = []
        self.edges = []
        self.arrows = []
        self.supercells = []

    def add_supercell(self, supercell):
        """ Add a supercell to 2D grid canvas.
        """
        if not isinstance(supercell, SuperCell2D):
            raise ValueError("supercell must be a SuperCell2D object")

        self.supercells.append(supercell)
        self.nodes.extend(supercell.nodes)
        self.edges.extend(supercell.edges)

    def add_supercells(self, supercells):
        """ Add multiple supercells to 2D grid canvas.
        """
        for sc in supercells:
            self.add_supercell(sc)

    def add_node(self, node):
        """ Add a node to grid canvas.
        """
        # Check node.
        if not isinstance(node, Node2D):
            raise ValueError("node must be a Node2D object")

        self.nodes.append(node)

    def add_nodes(self, nodes):
        """ Add multiple nodes to canvas.
        """
        for node in nodes:
            self.add_node(node)

    def add_edge(self, edge):
        """ Add a edge to grid canvas.
        """
        if not isinstance(edge, Edge2D):
            raise ValueError("edge must be an Edge2D object")

        if isinstance(edge, Arrow2D):
            self.arrows.append(edge)
        else:
            self.edges.append(edge)

    def add_edges(self, edges):
        """ Add multiple edges to canvas.
        """
        for edge in self.edges:
            self.add_edge(edges)

    @property
    def node_coordinates(self):
        """ Coordinates for all nodes.
        """
        return np.array([node.coordinate.tolist() for node in self.nodes])

    @property
    def node_edgecolors(self):
        """ Color codes for node edges.
        """
        return [node.edgecolor for node in self.nodes]

    @property
    def node_colors(self):
        """ Colors for all nodes.
        """
        return [node.color for node in self.nodes]

    @property
    def edge_coordinates(self):
        """ Coordiantes for all edges.
        """
        if not self.edges:
            return []
        else:
            x = np.concatenate([edge.x for edge in self.edges])
            y = np.concatenate([edge.y for edge in self.edges])
            return np.array(list(zip(x, y)))

    @property
    def arrow_colors(self):
        """ Colors for all arrows.
        """
        return [arrow.color for arrow in self.arrows]

    @property
    def arrow_coordinates(self):
        """ Coordinates for all arrows.
        """
        if not self.arrows:
            return []
        else:
            x = np.concatenate([arrow.x for arrow in self.arrows])
            y = np.concatenate([arrow.y for arrow in self.arrows])
            return np.array(list(zip(x, y)))

    def _get_data_limits(self):
        """ Private helper function to get the limits of data.
        """
        node_x = self.node_coordinates[:, 0] if self.nodes else []
        edge_x = self.edge_coordinates[:, 0] if self.edges else []
        arrow_x = self.arrow_coordinates[:, 0] if self.arrows else []
        x = np.concatenate([node_x, edge_x, arrow_x])
        max_x, min_x = np.max(x), np.min(x)

        node_y = self.node_coordinates[:, 1] if self.nodes else []
        edge_y = self.edge_coordinates[:, 1] if self.edges else []
        arrow_y = self.arrow_coordinates[:, 1] if self.arrows else []
        y = np.concatenate([node_y, edge_y, arrow_y])
        max_y, min_y = np.max(y), np.min(y)

        return self._limits(max_x, min_x, max_y, min_y)

    def draw(self):
        """ Draw all nodes and edges on canvas.
        """
        if not any([self.nodes, self.edges, self.arrows]):
            self._logger.warning("Attempted to draw in an empty canvas")
            return

        # Add edges to canvas.
        for edge in self.edges:
            self.axes.add_line(edge.line2d())

        for arrow in self.arrows:
            self.axes.arrow(*arrow.start, arrow.dx, arrow.dy,
                            length_includes_head=True,
                            head_width=arrow.head_width,
                            head_length=arrow.head_length,
                            shape=arrow.shape,
                            alpha=arrow.alpha,
                            linewidth=arrow.width,
                            color=arrow.color,
                            linestyle=arrow.style,
                            zorder=arrow.zorder)

        # Add nodes to canvas one by one.
        for node in self.nodes:
            self.axes.scatter(*node.coordinate,
                              color=node.color,
                              edgecolors=node.edgecolor,
                              marker=node.style,
                              alpha=node.alpha,
                              s=node.size,
                              linewidth=node.line_width,
                              zorder=99)

        # Set axes limits.
        limits = self._get_data_limits()
        self.axes.set_xlim(limits.min_x, limits.max_x)
        self.axes.set_ylim(limits.min_y, limits.max_y)

    def redraw(self):
        """ Clear the canvas and draw all components again.
        """
        self.clear()
        self.draw()

    def clear(self):
        """ Clear components drawned in canvas.
        """
        self.axes.clear()

    def deep_clear(self):
        """ Clear all components in canvas.
        """
        self.clear()
        self.nodes = []
        self.edges = []
        self.arrows = []
        self.supercells = []

<commit_msg>Add arrows when adding supercell to canvas.<commit_after>#!/usr/bin/env python
# -*- coding: utf-8 -*-

""" Module for grid plotting canvas.
"""

import numpy as np
import matplotlib.pyplot as plt

from catplot.canvas import Canvas
from catplot.grid_components.nodes import Node2D
from catplot.grid_components.edges import Edge2D, Arrow2D
from catplot.grid_components.supercell import SuperCell2D

class Grid2DCanvas(Canvas):
    """ Canvas for 2D grid plotting.
    """
    def __init__(self, **kwargs):
        super(Grid2DCanvas, self).__init__(**kwargs)

        # Equalize the scale of x and y axis.
        self.axes.set_aspect("equal")

        # Attributes for 2D grid canvas.
        self.nodes = []
        self.edges = []
        self.arrows = []
        self.supercells = []

    def add_supercell(self, supercell):
        """ Add a supercell to 2D grid canvas.
        """
        if not isinstance(supercell, SuperCell2D):
            raise ValueError("supercell must be a SuperCell2D object")

        self.supercells.append(supercell)
        self.nodes.extend(supercell.nodes)
        self.edges.extend(supercell.edges)
        self.arrows.extend(supercell.arrows)

    def add_supercells(self, supercells):
        """ Add multiple supercells to 2D grid canvas.
        """
        for sc in supercells:
            self.add_supercell(sc)

    def add_node(self, node):
        """ Add a node to grid canvas.
        """
        # Check node.
        if not isinstance(node, Node2D):
            raise ValueError("node must be a Node2D object")

        self.nodes.append(node)

    def add_nodes(self, nodes):
        """ Add multiple nodes to canvas.
        """
        for node in nodes:
            self.add_node(node)

    def add_edge(self, edge):
        """ Add a edge to grid canvas.
        """
        if not isinstance(edge, Edge2D):
            raise ValueError("edge must be an Edge2D object")

        if isinstance(edge, Arrow2D):
            self.arrows.append(edge)
        else:
            self.edges.append(edge)

    def add_edges(self, edges):
        """ Add multiple edges to canvas.
        """
        for edge in self.edges:
            self.add_edge(edges)

    @property
    def node_coordinates(self):
        """ Coordinates for all nodes.
        """
        return np.array([node.coordinate.tolist() for node in self.nodes])

    @property
    def node_edgecolors(self):
        """ Color codes for node edges.
        """
        return [node.edgecolor for node in self.nodes]

    @property
    def node_colors(self):
        """ Colors for all nodes.
        """
        return [node.color for node in self.nodes]

    @property
    def edge_coordinates(self):
        """ Coordiantes for all edges.
        """
        if not self.edges:
            return []
        else:
            x = np.concatenate([edge.x for edge in self.edges])
            y = np.concatenate([edge.y for edge in self.edges])
            return np.array(list(zip(x, y)))

    @property
    def arrow_colors(self):
        """ Colors for all arrows.
        """
        return [arrow.color for arrow in self.arrows]

    @property
    def arrow_coordinates(self):
        """ Coordinates for all arrows.
        """
        if not self.arrows:
            return []
        else:
            x = np.concatenate([arrow.x for arrow in self.arrows])
            y = np.concatenate([arrow.y for arrow in self.arrows])
            return np.array(list(zip(x, y)))

    def _get_data_limits(self):
        """ Private helper function to get the limits of data.
        """
        node_x = self.node_coordinates[:, 0] if self.nodes else []
        edge_x = self.edge_coordinates[:, 0] if self.edges else []
        arrow_x = self.arrow_coordinates[:, 0] if self.arrows else []
        x = np.concatenate([node_x, edge_x, arrow_x])
        max_x, min_x = np.max(x), np.min(x)

        node_y = self.node_coordinates[:, 1] if self.nodes else []
        edge_y = self.edge_coordinates[:, 1] if self.edges else []
        arrow_y = self.arrow_coordinates[:, 1] if self.arrows else []
        y = np.concatenate([node_y, edge_y, arrow_y])
        max_y, min_y = np.max(y), np.min(y)

        return self._limits(max_x, min_x, max_y, min_y)

    def draw(self):
        """ Draw all nodes and edges on canvas.
        """
        if not any([self.nodes, self.edges, self.arrows]):
            self._logger.warning("Attempted to draw in an empty canvas")
            return

        # Add edges to canvas.
        for edge in self.edges:
            self.axes.add_line(edge.line2d())

        for arrow in self.arrows:
            self.axes.arrow(*arrow.start, arrow.dx, arrow.dy,
                            length_includes_head=True,
                            head_width=arrow.head_width,
                            head_length=arrow.head_length,
                            shape=arrow.shape,
                            alpha=arrow.alpha,
                            linewidth=arrow.width,
                            color=arrow.color,
                            linestyle=arrow.style,
                            zorder=arrow.zorder)

        # Add nodes to canvas one by one.
        for node in self.nodes:
            self.axes.scatter(*node.coordinate,
                              color=node.color,
                              edgecolors=node.edgecolor,
                              marker=node.style,
                              alpha=node.alpha,
                              s=node.size,
                              linewidth=node.line_width,
                              zorder=99)

        # Set axes limits.
        limits = self._get_data_limits()
        self.axes.set_xlim(limits.min_x, limits.max_x)
        self.axes.set_ylim(limits.min_y, limits.max_y)

    def redraw(self):
        """ Clear the canvas and draw all components again.
        """
        self.clear()
        self.draw()

    def clear(self):
        """ Clear components drawned in canvas.
        """
        self.axes.clear()

    def deep_clear(self):
        """ Clear all components in canvas.
        """
        self.clear()
        self.nodes = []
        self.edges = []
        self.arrows = []
        self.supercells = []

<|endoftext|>


<commit_before><commit_msg>minor fix to the grasshopper interface. i hope it still works...<commit_after><|endoftext|>


<commit_before><commit_msg>rename Youtube -> You Tube<commit_after><|endoftext|>


<commit_before><commit_msg>We now re-sort the results in Python if we're running on sqlite (CNY-2186)<commit_after><|endoftext|>


<commit_before>from logging import getLogger

from django.conf import settings
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext as _
from opaque_keys import InvalidKeyError
from opaque_keys.edx.django.models import CourseKey, UsageKey
from rest_framework import serializers
from rest_framework.exceptions import APIException
from submissions.api import SubmissionError

from courseware.models import StudentModule
from lms.djangoapps.instructor import enrollment
from xmodule.modulestore.django import modulestore

from . import constants
from .models import CompetencyAssessmentRecord

log = getLogger(__name__)

def get_nth_chapter_link(course, chapter_index=0):
    course_chapters = modulestore().get_items(
        course.id,
        qualifiers={'category': 'course'}
    )
    if not course_chapters:
        log.info("%s Course dont have any chapters", course.display_name)

    try:
        chapter = course_chapters[0].children[chapter_index]
    except IndexError:
        return ""

    subsection = modulestore().get_item(chapter).children[0]

    course_target = reverse(
        'courseware_section',
        args=[course.id.to_deprecated_string(),
              chapter.block_id,
              subsection.block_id]
    )

    base_url = settings.LMS_ROOT_URL

    return base_url + course_target

def get_competency_assessments_score(user, chapter_id):
    """
    Return competency assessments scores of user in chapter of specified course

    :param user: user
    :param chapter_id: chapter url_name.
    :return: assessments score dictionary
    :raises:
        NotFound: if chapter, pre or post assessment not found
    """

    pre_assessment_attempted = None
    pre_assessment_score = post_assessment_score = 0
    attempted_pre_assessments = attempted_post_assessments = 0

    COMPETENCY_ASSESSMENT_RECORD_QUERY_FORMAT = """
        SELECT
        MAX(id) AS id,
        COUNT(assessment_type) AS assessments_count,
        assessment_type,
        correctness
        FROM philu_courseware_competencyassessmentrecord
        WHERE id IN (
            SELECT
            MAX(id) FROM philu_courseware_competencyassessmentrecord
            WHERE chapter_id = "{chapter_id}" and user_id = {user_id}
            GROUP BY problem_id, question_number
        ) GROUP BY correctness, assessment_type
    """

    assessments_record = CompetencyAssessmentRecord.objects.raw(
        COMPETENCY_ASSESSMENT_RECORD_QUERY_FORMAT.format(chapter_id=chapter_id, user_id=user.id))

    """
        Sample result of upper query. This Query will return results of problems from latest attempt
        for both "Pre" and "Post" assessments. All attempts are saved in our table and we are concerned only with the
        latest one, hence sub query provide us the latest attempt of all problems

        |  id   | assessment_count | assessment_type   |  correctness  |
        +-------+------------------+-------------------+---------------+
        |  231  |         4        |       post        |   correct     |
        |  229  |         4        |       pre         |   correct     |
        |  232  |         1        |       post        |   incorrect   |
        |  233  |         1        |       pre         |   incorrect   |
    """

    for assessment in assessments_record:
        if assessment.assessment_type == constants.PRE_ASSESSMENT_KEY:
            pre_assessment_attempted = True
            if assessment.correctness == constants.CORRECT_ASSESSMENT_KEY:
                pre_assessment_score = assessment.assessments_count
            attempted_pre_assessments += assessment.assessments_count

        else:
            if assessment.correctness == constants.CORRECT_ASSESSMENT_KEY:
                post_assessment_score = assessment.assessments_count
            attempted_post_assessments += assessment.assessments_count

    return {
        'pre_assessment_score': pre_assessment_score,
        'post_assessment_score': post_assessment_score,
        'pre_assessment_attempted': pre_assessment_attempted,
        'all_pre_assessment_attempted': attempted_pre_assessments == constants.COMPETENCY_ASSESSMENT_DEFAULT_PROBLEMS_COUNT,
        'all_post_assessment_attempted': attempted_post_assessments == constants.COMPETENCY_ASSESSMENT_DEFAULT_PROBLEMS_COUNT,
    }

def is_pre_assessment(section):
    return get_section_format(section) == constants.PRE_ASSESSMENT_FORMAT

def is_post_assessment(section):
    return get_section_format(section) == constants.POST_ASSESSMENT_FORMAT

def get_section_format(section):
    return section.format.lower() if section and section.format else ''

def validate_problem_id(problem_id):
    """
    validate if problem_id is valid UsageKeyField or not
    """
    if not problem_id:
        raise serializers.ValidationError(_('Problem id is required'))
    try:
        return UsageKey.from_string(problem_id)
    except InvalidKeyError:
        raise serializers.ValidationError(constants.INVALID_PROBLEM_ID_MSG)

def revert_user_attempts_from_edx(course_id, user, problem_usage_key):
    course_id = CourseKey.from_string(course_id)
    module_state_key = problem_usage_key.map_into_course(course_id)
    try:
        enrollment.reset_student_attempts(
            course_id,
            user,
            module_state_key,
            requesting_user=user,
            delete_module=True
        )
    except StudentModule.DoesNotExist:
        raise serializers.ValidationError(_('Module does not exist.'))
    except SubmissionError:
        # Trust the submissions API to log the error
        raise APIException(_('An error occurred while deleting the score.'))
<commit_msg>LP-2161 Add api view to revert user post assessment attempts<commit_after>from logging import getLogger

from django.conf import settings
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext as _
from opaque_keys import InvalidKeyError
from opaque_keys.edx.django.models import CourseKey, UsageKey
from rest_framework import serializers
from rest_framework.exceptions import APIException
from submissions.api import SubmissionError

from courseware.models import StudentModule
from lms.djangoapps.instructor import enrollment
from xmodule.modulestore.django import modulestore

from . import constants
from .models import CompetencyAssessmentRecord

log = getLogger(__name__)

def get_nth_chapter_link(course, chapter_index=0):
    course_chapters = modulestore().get_items(
        course.id,
        qualifiers={'category': 'course'}
    )
    if not course_chapters:
        log.info("%s Course dont have any chapters", course.display_name)

    try:
        chapter = course_chapters[0].children[chapter_index]
    except IndexError:
        return ""

    subsection = modulestore().get_item(chapter).children[0]

    course_target = reverse(
        'courseware_section',
        args=[course.id.to_deprecated_string(),
              chapter.block_id,
              subsection.block_id]
    )

    base_url = settings.LMS_ROOT_URL

    return base_url + course_target

def get_competency_assessments_score(user, chapter_id):
    """
    Return competency assessments scores of user in chapter of specified course

    :param user: user
    :param chapter_id: chapter url_name.
    :return: assessments score dictionary
    :raises:
        NotFound: if chapter, pre or post assessment not found
    """

    pre_assessment_attempted = None
    pre_assessment_score = post_assessment_score = 0
    attempted_pre_assessments = attempted_post_assessments = 0

    COMPETENCY_ASSESSMENT_RECORD_QUERY_FORMAT = """
        SELECT
        MAX(id) AS id,
        COUNT(assessment_type) AS assessments_count,
        assessment_type,
        correctness
        FROM philu_courseware_competencyassessmentrecord
        WHERE id IN (
            SELECT
            MAX(id) FROM philu_courseware_competencyassessmentrecord
            WHERE chapter_id = "{chapter_id}" and user_id = {user_id}
            GROUP BY problem_id, question_number
        ) GROUP BY correctness, assessment_type
    """

    assessments_record = CompetencyAssessmentRecord.objects.raw(
        COMPETENCY_ASSESSMENT_RECORD_QUERY_FORMAT.format(chapter_id=chapter_id, user_id=user.id))

    """
        Sample result of upper query. This Query will return results of problems from latest attempt
        for both "Pre" and "Post" assessments. All attempts are saved in our table and we are concerned only with the
        latest one, hence sub query provide us the latest attempt of all problems

        |  id   | assessment_count | assessment_type   |  correctness  |
        +-------+------------------+-------------------+---------------+
        |  231  |         4        |       post        |   correct     |
        |  229  |         4        |       pre         |   correct     |
        |  232  |         1        |       post        |   incorrect   |
        |  233  |         1        |       pre         |   incorrect   |
    """

    for assessment in assessments_record:
        if assessment.assessment_type == constants.PRE_ASSESSMENT_KEY:
            pre_assessment_attempted = True
            if assessment.correctness == constants.CORRECT_ASSESSMENT_KEY:
                pre_assessment_score = assessment.assessments_count
            attempted_pre_assessments += assessment.assessments_count

        else:
            if assessment.correctness == constants.CORRECT_ASSESSMENT_KEY:
                post_assessment_score = assessment.assessments_count
            attempted_post_assessments += assessment.assessments_count

    return {
        'pre_assessment_score': pre_assessment_score,
        'post_assessment_score': post_assessment_score,
        'pre_assessment_attempted': pre_assessment_attempted,
        'all_pre_assessment_attempted': attempted_pre_assessments == constants.COMPETENCY_ASSESSMENT_DEFAULT_PROBLEMS_COUNT,
        'all_post_assessment_attempted': attempted_post_assessments == constants.COMPETENCY_ASSESSMENT_DEFAULT_PROBLEMS_COUNT,
    }

def is_pre_assessment(section):
    return get_section_format(section) == constants.PRE_ASSESSMENT_FORMAT

def is_post_assessment(section):
    return get_section_format(section) == constants.POST_ASSESSMENT_FORMAT

def get_section_format(section):
    return section.format.lower() if section and section.format else ''

def validate_problem_id(problem_id):
    """
    validate if problem_id is valid UsageKeyField or not
    """
    if not problem_id:
        raise serializers.ValidationError({'problem_id': _('Problem id is required')})
    try:
        return UsageKey.from_string(problem_id)
    except InvalidKeyError:
        raise serializers.ValidationError({'problem_id': constants.INVALID_PROBLEM_ID_MSG})

def revert_user_attempts_from_edx(course_id, user, problem_usage_key):
    """
    :param course_id: str course id of user
    :param user: Django User
    :param problem_usage_key: UsageKey problem id
    """
    course_id = CourseKey.from_string(course_id)
    module_state_key = problem_usage_key.map_into_course(course_id)
    try:
        enrollment.reset_student_attempts(
            course_id,
            user,
            module_state_key,
            requesting_user=user,
            delete_module=True
        )
    except StudentModule.DoesNotExist:
        raise serializers.ValidationError(_('Module does not exist.'))
    except SubmissionError:
        # Trust the submissions API to log the error
        raise APIException(_('An error occurred while deleting the score.'))
<|endoftext|>


<commit_before>from flask import jsonify

class NotFoundError(Exception):
    pass

class InvalidParameterError(Exception):
    pass

class HttpHandler(object):

    def __init__(self, logger=None, context=dict()):
        """
        :param logger: the mongolog logger to use
        :param context: a dictionary of extra data to log
            as a context for any exceptions that may occur
        """
        self.response = None
        self.logger = logger
        self.context = context

    def __enter__(self):
        """
        Enters the HttpHandler
        This handler will catch exceptions and jsonify them for
        returning to a client.
        Also supports logging via a mongolog logger
        """
        return self

    def __exit__(self, type, value, traceback):
        if (type is not None and self.logger is not None):
            self.logger.log_exception(value, self.context)

        if (type is NotFoundError):
            self.response = jsonify(status='error',
                                    message=str(value))
            self.response.status_code = 404
            return True
        elif (type is InvalidParameterError):
            self.response = jsonify(status='error',
                                    message=str(value))
            self.response.status_code = 400
            return True
        elif (type is not None):
            self.response = jsonify(status='error',
                                    message='Internal Server Error')
            print('Internal server error: {0}'.format(str(value)), flush=True
            self.response.status_code = 500
            return True
        else:
            return
<commit_msg>ugh forgot parentheses<commit_after>from flask import jsonify

class NotFoundError(Exception):
    pass

class InvalidParameterError(Exception):
    pass

class HttpHandler(object):

    def __init__(self, logger=None, context=dict()):
        """
        :param logger: the mongolog logger to use
        :param context: a dictionary of extra data to log
            as a context for any exceptions that may occur
        """
        self.response = None
        self.logger = logger
        self.context = context

    def __enter__(self):
        """
        Enters the HttpHandler
        This handler will catch exceptions and jsonify them for
        returning to a client.
        Also supports logging via a mongolog logger
        """
        return self

    def __exit__(self, type, value, traceback):
        if (type is not None and self.logger is not None):
            self.logger.log_exception(value, self.context)

        if (type is NotFoundError):
            self.response = jsonify(status='error',
                                    message=str(value))
            self.response.status_code = 404
            return True
        elif (type is InvalidParameterError):
            self.response = jsonify(status='error',
                                    message=str(value))
            self.response.status_code = 400
            return True
        elif (type is not None):
            self.response = jsonify(status='error',
                                    message='Internal Server Error')
            print('Internal server error: {0}'.format(str(value)), flush=True)
            self.response.status_code = 500
            return True
        else:
            return
<|endoftext|>