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

# libavg - Media Playback Engine.
# Copyright (C) 2003-2013 Ulrich von Zadow
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2 of the License, or (at your option) any later version.
#
# This library 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
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#
# Current versions can be found at www.libavg.de
#
# Original author of this file is OXullo Interecans <x at brainrapers dot org>
# Sponsored by Archimedes Exhibitions GmbH ( http://www.archimedes-exhibitions.de )

import os
import io
import math
import time

import libavg
from libavg import avg, Point2D

import settings
from settings import Option
import keyboardmanager
import debugpanel
import flashmessage

class MainDiv(libavg.avg.DivNode):
    '''
    Main construction block for libavg-based applications
    '''
    INIT_FUNC = 'onInit'
    EXTRA_OPTIONS = []

    def __init__(self, **kargs):
        assert not 'parent' in kargs
        super(MainDiv, self).__init__(**kargs)
        self.registerInstance(self, None)

    def onStartup(self):
        '''
        Called before libavg has been setup
        Setup early services or communication channels here
        '''
        pass

    def onInit(self):
        '''
        Called by a libavg timer as soon as the main loop starts
        Build the application node tree here
        '''
        pass

    def onExit(self):
        '''
        Called when the main loop stops
        Release resources and cleanup here
        '''
        pass

    def onFrame(self, delta):
        '''
        Called at every frame
        @param delta: time in seconds since the last onFrame() call
        @type delta: float
        '''
        pass

class App(object):
    '''
    libavg-based application class
    '''

    def __init__(self):
        import libavg.app

        if libavg.app.instance is not None:
            raise RuntimeError('%s has been already instantiated' %
                    self.__class__.__name__)

        libavg.app.instance = self

        self._mainDiv = None
        self._appParent = None
        self._debugPanel = None
        self._overlayPanel = None
        self._resolution = None
        self._windowSize = None

        self.__lastFrameTimestamp = 0

        self._setupSettings()

    def run(self, mainDiv, **kargs):
        '''
        Start the application using the provided L{MainDiv} instance

        @param mainDiv: an instance of L{MainDiv} (or derived class)
        '''
        assert isinstance(mainDiv, MainDiv)
        self._mainDiv = mainDiv

        for option in mainDiv.EXTRA_OPTIONS:
            self.settings.addOption(option)

        self._applySettingsExtenders(kargs)
        self._setupLogging()

        mainDiv.onStartup()

        self._setupResolution()
        self._setupRootNode()
        self._setupMouse()
        self._setupMultitouch()
        pos, size, angle = self._getAppParentGeometry()
        self._setupAppParent(pos, size, angle)
        self._setupMainDiv()
        self._setupTopPanel()

        self._setupDebugPanel()
        self._setupKeyboardManager()
        self._setupDebuggingWidgets()
        self._applyResolution()
        self._setupOnInit()

        self.onBeforeLaunch()

        self.__lastFrameTimestamp = time.time()

        self._runLoop()

        mainDiv.onExit()

        self._teardownKeyboardManager()

        return 0

    def stop(self):
        libavg.player.stop()

    @property
    def mainDiv(self):
        '''
        MainDiv instance passed to method L{run}
        '''
        return self._mainDiv

    @property
    def appParent(self):
        '''
        Base DivNode where the application sets up the control layers
            (L{MainDiv}, debug, messaging)
        '''
        return self._appParent

    @property
    def debugPanel(self):
        '''
        The instance of L{app.debugpanel.DebugPanel} that currently runs in the
            application
        '''
        return self._debugPanel

    @property
    def overlayPanel(self):
        '''
        DivNode that stands on top of the MainDiv
        '''
        return self._overlayPanel

    @property
    def settings(self):
        '''
        The instance of L{app.settings.Settings} associated to the application
        '''
        return self._settings

    @property
    def resolution(self):
        '''
        Current target screen resolution
        '''
        return self._resolution

    @property
    def windowSize(self):
        '''
        Current target window size
        '''
        return self._windowSize

    def onBeforeLaunch(self):
        pass

    def takeScreenshot(self):
        screenBmp = libavg.player.screenshot()

        filenameTemplate = '%s-%03d.png'

        i = 1
        while i < 1000:
            filename = filenameTemplate % (self.__class__.__name__, i)
            if os.path.exists(filename):
                i += 1
            else:
                break

        if i == 1000:
            flashmessage.FlashMessage('Maximum number of screenshots reached',
                    parent=self.appParent, isError=True)
        else:
            screenBmp.save(filename)
            flashmessage.FlashMessage('Screenshot saved as %s' % filename,
                    parent=self.appParent)

    def dumpTextObjectCount(self):
        objects = libavg.player.getTestHelper().getObjectCount()
        savedSeverity = libavg.logger.getCategories()[libavg.logger.Category.APP]
        libavg.logger.configureCategory(libavg.logger.Category.APP,
                libavg.logger.Severity.INFO)
        for key, value in objects.iteritems():
            libavg.logger.info('%-25s: %s' % (key, value))

        libavg.logger.configureCategory(libavg.logger.Category.APP, savedSeverity)

    def _setupSettings(self):
        self._settings = settings.Settings()
        self._settings.addOption(Option('app_resolution', '640x480'))
        self._settings.addOption(Option('app_window_size', ''))
        self._settings.addOption(Option('app_fullscreen', 'false'))
        self._settings.addOption(Option('app_show_cursor', 'true'))
        self._settings.addOption(Option('app_rotation', 'normal'))
        self._settings.addOption(Option('app_panel_fontsize', '10'))
        self._settings.addOption(Option('app_mouse_enabled', 'true'))
        self._settings.addOption(Option('multitouch_enabled', 'false'))
        self._settings.addOption(Option('multitouch_driver', ''))
        self._settings.addOption(Option('multitouch_tuio_port', ''))
        self._settings.addOption(Option('multitouch_mtdev_device', ''))
        self._settings.addOption(Option('log_avg_categories', ''))

    def _applySettingsExtenders(self, kargs):
        self.settings.applyExtender(settings.KargsExtender(kargs))
        self.settings.applyExtender(settings.ArgvExtender())

    def _setupLogging(self):
        catMap = self.settings.get('log_avg_categories').strip()
        if catMap:
            for catPair in catMap.split(' '):
                cat, strLevel = catPair.split(':')
                level = getattr(avg.logger.Severity, strLevel)

                libavg.avg.logger.configureCategory(cat, level)

    def _setupRootNode(self):
        libavg.player.loadString('''<?xml version="1.0"?>
        <!DOCTYPE avg SYSTEM "../../libavg/doc/avg.dtd">
        <avg width="%s" height="%s">
        </avg>''' % tuple(self.resolution))

    def _setupMouse(self):
        libavg.player.enableMouse(self.settings.getboolean('app_mouse_enabled'))

    def _setupMultitouch(self):
        if self.settings.getboolean('multitouch_enabled'):
            driver = self.settings.get('multitouch_driver').upper()
            if driver:
                os.putenv('AVG_MULTITOUCH_DRIVER', driver)

            tuio_port = self.settings.get('multitouch_tuio_port').upper()
            if tuio_port:
                os.putenv('AVG_TUIO_PORT', tuio_port)

            mtdev_device = self.settings.get('multitouch_mtdev_device').upper()
            if mtdev_device:
                os.putenv('AVG_LINUX_MULTITOUCH_DEVICE', mtdev_device)

            libavg.player.enableMultitouch()

    def _getAppParentGeometry(self):
        rotation = self.settings.get('app_rotation').lower()
        size = self.resolution
        pos = (0, 0)
        angle = 0

        if rotation == 'left':
            angle = -math.pi / 2
            size = (self.resolution.y, self.resolution.x)
            pos = ((self.resolution.x - self.resolution.y) / 2,
                    (self.resolution.y - self.resolution.x) / 2)
        elif rotation == 'right':
            angle = math.pi / 2
            size = (self.resolution.y, self.resolution.x)
            pos = ((self.resolution.x - self.resolution.y) / 2,
                    (self.resolution.y - self.resolution.x) / 2)
        elif rotation == 'inverted':
            angle = math.pi
        elif rotation != 'normal':
            raise TypeError('Invalid rotation %s' % rotation)

        return (pos, size, angle)

    def _setupAppParent(self, pos, size, angle):
        self._appParent = libavg.avg.DivNode(parent=libavg.player.getRootNode(),
                pos=pos, size=size, angle=angle)

    def _setupMainDiv(self):
        self.appParent.appendChild(self.mainDiv)
        self.mainDiv.size = self.appParent.size

    def _setupTopPanel(self):
        self._overlayPanel = libavg.avg.DivNode(parent=self.appParent, id='overlayPanel')

    def _setupDebugPanel(self):
        self._debugPanel = debugpanel.DebugPanel(parent=self.appParent,
                    size=self.appParent.size, id='debugPanel',
                    fontsize=self.settings.getfloat('app_panel_fontsize'))

    def _setupDebuggingWidgets(self):
        # self._debugPanel.addWidget(debugpanel.KeyboardManagerBindingsShower)
        pass

    def _setupResolution(self):
        rotation = self.settings.get('app_rotation').lower()
        resolution = self.settings.getpoint2d('app_resolution')
        windowSizeStr = self.settings.get('app_window_size')
        if windowSizeStr != '':
            windowSize = self.settings.getpoint2d('app_window_size')
        else:
            windowSize = resolution

        if rotation in ('left', 'right'):
            resolution = Point2D(resolution.y, resolution.x)
            windowSize = Point2D(windowSize.y, windowSize.x)

        self._resolution = resolution
        self._windowSize = windowSize

    def _applyResolution(self):
        fullscreen = self.settings.getboolean('app_fullscreen')

        if fullscreen:
            resolution = self.resolution
        else:
            resolution = self.windowSize

        libavg.player.setResolution(
                fullscreen,
                int(resolution.x), int(resolution.y),
                0  # color depth
                )

        libavg.player.showCursor(self.settings.getboolean('app_show_cursor'))

    def _setupKeyboardManager(self):
        keyboardmanager.init()
        keyboardmanager.bindKeyDown(
                keystring='d',
                handler=self._debugPanel.toggleVisibility,
                help='Show/hide the debug panel',
                modifiers=libavg.avg.KEYMOD_CTRL)

        keyboardmanager.bindKeyDown(
                keystring='m',
                handler=lambda: libavg.player.showCursor(
                        not libavg.player.isCursorShown()),
                help='Show/hide cursor',
                modifiers=libavg.avg.KEYMOD_CTRL)

        keyboardmanager.bindKeyDown(
                keystring='p',
                handler=self.takeScreenshot,
                help='Take screenshot',
                modifiers=libavg.avg.KEYMOD_CTRL)

        keyboardmanager.bindKeyDown(
                keystring='o',
                handler=self.dumpTextObjectCount,
                help='Dump objects count to the console',
                modifiers=libavg.avg.KEYMOD_CTRL)

    def _teardownKeyboardManager(self):
        keyboardmanager.unbindAll()

    def _setupOnInit(self):
        libavg.player.setTimeout(0, self._onInitInternal)

    def _runLoop(self):
        libavg.player.play()

    def _onInitInternal(self):
        initFunc = getattr(self.mainDiv, self.mainDiv.INIT_FUNC)
        initFunc()
        libavg.player.subscribe(libavg.player.ON_FRAME, self._onFrameInternal)

    def _onFrameInternal(self):
        now = time.time()
        self.mainDiv.onFrame(now - self.__lastFrameTimestamp)
        self.__lastFrameTimestamp = now

<commit_msg>libavg_app: resolution parameter can be now empty, which defaults to screen resolution<commit_after>#!/usr/bin/env python
# -*- coding: utf-8 -*-

# libavg - Media Playback Engine.
# Copyright (C) 2003-2013 Ulrich von Zadow
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2 of the License, or (at your option) any later version.
#
# This library 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
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#
# Current versions can be found at www.libavg.de
#
# Original author of this file is OXullo Interecans <x at brainrapers dot org>
# Sponsored by Archimedes Exhibitions GmbH ( http://www.archimedes-exhibitions.de )

import os
import io
import math
import time

import libavg
from libavg import avg, Point2D

import settings
from settings import Option
import keyboardmanager
import debugpanel
import flashmessage

class MainDiv(libavg.avg.DivNode):
    '''
    Main construction block for libavg-based applications
    '''
    INIT_FUNC = 'onInit'
    EXTRA_OPTIONS = []

    def __init__(self, **kargs):
        assert not 'parent' in kargs
        super(MainDiv, self).__init__(**kargs)
        self.registerInstance(self, None)

    def onStartup(self):
        '''
        Called before libavg has been setup
        Setup early services or communication channels here
        '''
        pass

    def onInit(self):
        '''
        Called by a libavg timer as soon as the main loop starts
        Build the application node tree here
        '''
        pass

    def onExit(self):
        '''
        Called when the main loop stops
        Release resources and cleanup here
        '''
        pass

    def onFrame(self, delta):
        '''
        Called at every frame
        @param delta: time in seconds since the last onFrame() call
        @type delta: float
        '''
        pass

class App(object):
    '''
    libavg-based application class
    '''

    def __init__(self):
        import libavg.app

        if libavg.app.instance is not None:
            raise RuntimeError('%s has been already instantiated' %
                    self.__class__.__name__)

        libavg.app.instance = self

        self._mainDiv = None
        self._appParent = None
        self._debugPanel = None
        self._overlayPanel = None
        self._resolution = None
        self._windowSize = None

        self.__lastFrameTimestamp = 0

        self._setupSettings()

    def run(self, mainDiv, **kargs):
        '''
        Start the application using the provided L{MainDiv} instance

        @param mainDiv: an instance of L{MainDiv} (or derived class)
        '''
        assert isinstance(mainDiv, MainDiv)
        self._mainDiv = mainDiv

        for option in mainDiv.EXTRA_OPTIONS:
            self.settings.addOption(option)

        self._applySettingsExtenders(kargs)
        self._setupLogging()

        mainDiv.onStartup()

        self._setupResolution()
        self._setupRootNode()
        self._setupMouse()
        self._setupMultitouch()
        pos, size, angle = self._getAppParentGeometry()
        self._setupAppParent(pos, size, angle)
        self._setupMainDiv()
        self._setupTopPanel()

        self._setupDebugPanel()
        self._setupKeyboardManager()
        self._setupDebuggingWidgets()
        self._applyResolution()
        self._setupOnInit()

        self.onBeforeLaunch()

        self.__lastFrameTimestamp = time.time()

        self._runLoop()

        mainDiv.onExit()

        self._teardownKeyboardManager()

        return 0

    def stop(self):
        libavg.player.stop()

    @property
    def mainDiv(self):
        '''
        MainDiv instance passed to method L{run}
        '''
        return self._mainDiv

    @property
    def appParent(self):
        '''
        Base DivNode where the application sets up the control layers
            (L{MainDiv}, debug, messaging)
        '''
        return self._appParent

    @property
    def debugPanel(self):
        '''
        The instance of L{app.debugpanel.DebugPanel} that currently runs in the
            application
        '''
        return self._debugPanel

    @property
    def overlayPanel(self):
        '''
        DivNode that stands on top of the MainDiv
        '''
        return self._overlayPanel

    @property
    def settings(self):
        '''
        The instance of L{app.settings.Settings} associated to the application
        '''
        return self._settings

    @property
    def resolution(self):
        '''
        Current target screen resolution
        '''
        return self._resolution

    @property
    def windowSize(self):
        '''
        Current target window size
        '''
        return self._windowSize

    def onBeforeLaunch(self):
        pass

    def takeScreenshot(self):
        screenBmp = libavg.player.screenshot()

        filenameTemplate = '%s-%03d.png'

        i = 1
        while i < 1000:
            filename = filenameTemplate % (self.__class__.__name__, i)
            if os.path.exists(filename):
                i += 1
            else:
                break

        if i == 1000:
            flashmessage.FlashMessage('Maximum number of screenshots reached',
                    parent=self.appParent, isError=True)
        else:
            screenBmp.save(filename)
            flashmessage.FlashMessage('Screenshot saved as %s' % filename,
                    parent=self.appParent)

    def dumpTextObjectCount(self):
        objects = libavg.player.getTestHelper().getObjectCount()
        savedSeverity = libavg.logger.getCategories()[libavg.logger.Category.APP]
        libavg.logger.configureCategory(libavg.logger.Category.APP,
                libavg.logger.Severity.INFO)
        for key, value in objects.iteritems():
            libavg.logger.info('%-25s: %s' % (key, value))

        libavg.logger.configureCategory(libavg.logger.Category.APP, savedSeverity)

    def _setupSettings(self):
        self._settings = settings.Settings()
        self._settings.addOption(Option('app_resolution', '640x480'))
        self._settings.addOption(Option('app_window_size', ''))
        self._settings.addOption(Option('app_fullscreen', 'false'))
        self._settings.addOption(Option('app_show_cursor', 'true'))
        self._settings.addOption(Option('app_rotation', 'normal'))
        self._settings.addOption(Option('app_panel_fontsize', '10'))
        self._settings.addOption(Option('app_mouse_enabled', 'true'))
        self._settings.addOption(Option('multitouch_enabled', 'false'))
        self._settings.addOption(Option('multitouch_driver', ''))
        self._settings.addOption(Option('multitouch_tuio_port', ''))
        self._settings.addOption(Option('multitouch_mtdev_device', ''))
        self._settings.addOption(Option('log_avg_categories', ''))

    def _applySettingsExtenders(self, kargs):
        self.settings.applyExtender(settings.KargsExtender(kargs))
        self.settings.applyExtender(settings.ArgvExtender())

    def _setupLogging(self):
        catMap = self.settings.get('log_avg_categories').strip()
        if catMap:
            for catPair in catMap.split(' '):
                cat, strLevel = catPair.split(':')
                level = getattr(avg.logger.Severity, strLevel)

                libavg.avg.logger.configureCategory(cat, level)

    def _setupRootNode(self):
        libavg.player.loadString('''<?xml version="1.0"?>
        <!DOCTYPE avg SYSTEM "../../libavg/doc/avg.dtd">
        <avg width="%s" height="%s">
        </avg>''' % tuple(self.resolution))

    def _setupMouse(self):
        libavg.player.enableMouse(self.settings.getboolean('app_mouse_enabled'))

    def _setupMultitouch(self):
        if self.settings.getboolean('multitouch_enabled'):
            driver = self.settings.get('multitouch_driver').upper()
            if driver:
                os.putenv('AVG_MULTITOUCH_DRIVER', driver)

            tuio_port = self.settings.get('multitouch_tuio_port').upper()
            if tuio_port:
                os.putenv('AVG_TUIO_PORT', tuio_port)

            mtdev_device = self.settings.get('multitouch_mtdev_device').upper()
            if mtdev_device:
                os.putenv('AVG_LINUX_MULTITOUCH_DEVICE', mtdev_device)

            libavg.player.enableMultitouch()

    def _getAppParentGeometry(self):
        rotation = self.settings.get('app_rotation').lower()
        size = self.resolution
        pos = (0, 0)
        angle = 0

        if rotation == 'left':
            angle = -math.pi / 2
            size = (self.resolution.y, self.resolution.x)
            pos = ((self.resolution.x - self.resolution.y) / 2,
                    (self.resolution.y - self.resolution.x) / 2)
        elif rotation == 'right':
            angle = math.pi / 2
            size = (self.resolution.y, self.resolution.x)
            pos = ((self.resolution.x - self.resolution.y) / 2,
                    (self.resolution.y - self.resolution.x) / 2)
        elif rotation == 'inverted':
            angle = math.pi
        elif rotation != 'normal':
            raise TypeError('Invalid rotation %s' % rotation)

        return (pos, size, angle)

    def _setupAppParent(self, pos, size, angle):
        self._appParent = libavg.avg.DivNode(parent=libavg.player.getRootNode(),
                pos=pos, size=size, angle=angle)

    def _setupMainDiv(self):
        self.appParent.appendChild(self.mainDiv)
        self.mainDiv.size = self.appParent.size

    def _setupTopPanel(self):
        self._overlayPanel = libavg.avg.DivNode(parent=self.appParent, id='overlayPanel')

    def _setupDebugPanel(self):
        self._debugPanel = debugpanel.DebugPanel(parent=self.appParent,
                    size=self.appParent.size, id='debugPanel',
                    fontsize=self.settings.getfloat('app_panel_fontsize'))

    def _setupDebuggingWidgets(self):
        # self._debugPanel.addWidget(debugpanel.KeyboardManagerBindingsShower)
        pass

    def _setupResolution(self):
        rotation = self.settings.get('app_rotation').lower()
        resolutionStr = self.settings.get('app_resolution').lower()
        if resolutionStr != '':
            resolution = self.settings.getpoint2d('app_resolution')
        else:
            resolution = libavg.player.getScreenResolution()

        windowSizeStr = self.settings.get('app_window_size')
        if windowSizeStr != '':
            windowSize = self.settings.getpoint2d('app_window_size')
        else:
            windowSize = resolution

        if rotation in ('left', 'right'):
            resolution = Point2D(resolution.y, resolution.x)
            windowSize = Point2D(windowSize.y, windowSize.x)

        self._resolution = resolution
        self._windowSize = windowSize

    def _applyResolution(self):
        fullscreen = self.settings.getboolean('app_fullscreen')

        if fullscreen:
            resolution = self.resolution
        else:
            resolution = self.windowSize

        libavg.player.setResolution(
                fullscreen,
                int(resolution.x), int(resolution.y),
                0  # color depth
                )

        libavg.player.showCursor(self.settings.getboolean('app_show_cursor'))

    def _setupKeyboardManager(self):
        keyboardmanager.init()
        keyboardmanager.bindKeyDown(
                keystring='d',
                handler=self._debugPanel.toggleVisibility,
                help='Show/hide the debug panel',
                modifiers=libavg.avg.KEYMOD_CTRL)

        keyboardmanager.bindKeyDown(
                keystring='m',
                handler=lambda: libavg.player.showCursor(
                        not libavg.player.isCursorShown()),
                help='Show/hide cursor',
                modifiers=libavg.avg.KEYMOD_CTRL)

        keyboardmanager.bindKeyDown(
                keystring='p',
                handler=self.takeScreenshot,
                help='Take screenshot',
                modifiers=libavg.avg.KEYMOD_CTRL)

        keyboardmanager.bindKeyDown(
                keystring='o',
                handler=self.dumpTextObjectCount,
                help='Dump objects count to the console',
                modifiers=libavg.avg.KEYMOD_CTRL)

    def _teardownKeyboardManager(self):
        keyboardmanager.unbindAll()

    def _setupOnInit(self):
        libavg.player.setTimeout(0, self._onInitInternal)

    def _runLoop(self):
        libavg.player.play()

    def _onInitInternal(self):
        initFunc = getattr(self.mainDiv, self.mainDiv.INIT_FUNC)
        initFunc()
        libavg.player.subscribe(libavg.player.ON_FRAME, self._onFrameInternal)

    def _onFrameInternal(self):
        now = time.time()
        self.mainDiv.onFrame(now - self.__lastFrameTimestamp)
        self.__lastFrameTimestamp = now

<|endoftext|>


<commit_before>'''
Created on Feb 15, 2011

@author: eplaster
'''
import suds

serviceTypes = {
    'alarmManager'              : 'AlarmManager',
    'authorizationManager'      : 'AuthorizationManager',
    'clusterProfileManager'     : 'ClusterProfileManager',
    'complianceManager'         : 'ProfileComplianceManager',
    'customFieldsManager'       : 'CustomFieldsManager',
    'customizationSpecManager'  : 'CustomizationSpecManager',
    'diagnosticManager'         : 'DiagnosticManager',
    'dvSwitchManager'           : 'DistributedVirtualSwitchManager',
    'eventManager'              : 'EventManager',
    'extensionManager'          : 'ExtensionManager',
    'fileManager'               : 'FileManager',
    'hostProfileManager'        : 'HostProfileManager',
    'ipPoolManager'             : 'IpPoolManager',
    'licenseManager'            : 'LicenseManager',
    'localizationManager'       : 'LocalizationManager',
    'ovfManager'                : 'OvfManager',
    'perfManager'               : 'PerformanceManager',
    'propertyCollector'         : 'PropertyCollector',
    'rootFolder'                : 'Folder',
    'scheduledTaskManager'      : 'ScheduledTaskManager',
    'searchIndex'               : 'SearchIndex',
    'sessionManager'            : 'SessionManager',
    'setting'                   : 'OptionManager',
    'snmpSystem'                : 'HostSnmpSystem',
    'storageResourceManager'    : 'StorageResourceManager',
    'taskManager'               : 'TaskManager',
    'userDirectory'             : 'UserDirectory',
    'viewManager'               : 'ViewManager',
    'virtualDiskManager'        : 'VirtualDiskManager',
    'vmCompatibilityChecker'    : 'VirtualMachineCompatibilityChecker',
    'vmProvisioningChecker'     : 'VirtualMachineProvisioningChecker',
}

# managed entities
ManagedEntity = "ManagedEntity"
ComputeResource = "ComputeResource"
ClusterComputeResource = "ClusterComputeResource"
Datacenter = "Datacenter"
Folder = "Folder"
HostSystem = "HostSystem"
ResourcePool = "ResourcePool"
VirtualMachine = "VirtualMachine"
VirtualMachineSnapshot = "VirtualMachineSnapshot"

# compute resources
ComputeResource = "ComputeResource"
ClusterComputeResource = "ClusterComputeResource"

# Collectors
HistoryCollector = "HistoryCollector",
EventHistoryCollector = "EventHistoryCollector",
TaskHistoryCollector = "TaskHistoryCollector"

class ManagedObjectRef(suds.sudsobject.Property):
    """Custom class to replace the suds generated class, which lacks _type."""
    def __init__(self, _type, value):
        suds.sudsobject.Property.__init__(self, value)
        self._type = _type

<commit_msg>Added back TaskInfoState<commit_after>'''
Created on Feb 15, 2011

@author: eplaster
'''
import suds

serviceTypes = {
    'alarmManager'              : 'AlarmManager',
    'authorizationManager'      : 'AuthorizationManager',
    'clusterProfileManager'     : 'ClusterProfileManager',
    'complianceManager'         : 'ProfileComplianceManager',
    'customFieldsManager'       : 'CustomFieldsManager',
    'customizationSpecManager'  : 'CustomizationSpecManager',
    'diagnosticManager'         : 'DiagnosticManager',
    'dvSwitchManager'           : 'DistributedVirtualSwitchManager',
    'eventManager'              : 'EventManager',
    'extensionManager'          : 'ExtensionManager',
    'fileManager'               : 'FileManager',
    'hostProfileManager'        : 'HostProfileManager',
    'ipPoolManager'             : 'IpPoolManager',
    'licenseManager'            : 'LicenseManager',
    'localizationManager'       : 'LocalizationManager',
    'ovfManager'                : 'OvfManager',
    'perfManager'               : 'PerformanceManager',
    'propertyCollector'         : 'PropertyCollector',
    'rootFolder'                : 'Folder',
    'scheduledTaskManager'      : 'ScheduledTaskManager',
    'searchIndex'               : 'SearchIndex',
    'sessionManager'            : 'SessionManager',
    'setting'                   : 'OptionManager',
    'snmpSystem'                : 'HostSnmpSystem',
    'storageResourceManager'    : 'StorageResourceManager',
    'taskManager'               : 'TaskManager',
    'userDirectory'             : 'UserDirectory',
    'viewManager'               : 'ViewManager',
    'virtualDiskManager'        : 'VirtualDiskManager',
    'vmCompatibilityChecker'    : 'VirtualMachineCompatibilityChecker',
    'vmProvisioningChecker'     : 'VirtualMachineProvisioningChecker',
}

class TaskInfoState(object):
    success = "success"
    running = "running"
    error = "error"
    queued = "queued"

# managed entities
ManagedEntity = "ManagedEntity"
ComputeResource = "ComputeResource"
ClusterComputeResource = "ClusterComputeResource"
Datacenter = "Datacenter"
Folder = "Folder"
HostSystem = "HostSystem"
ResourcePool = "ResourcePool"
VirtualMachine = "VirtualMachine"
VirtualMachineSnapshot = "VirtualMachineSnapshot"

# compute resources
ComputeResource = "ComputeResource"
ClusterComputeResource = "ClusterComputeResource"

# Collectors
HistoryCollector = "HistoryCollector",
EventHistoryCollector = "EventHistoryCollector",
TaskHistoryCollector = "TaskHistoryCollector"

class ManagedObjectRef(suds.sudsobject.Property):
    """Custom class to replace the suds generated class, which lacks _type."""
    def __init__(self, _type, value):
        suds.sudsobject.Property.__init__(self, value)
        self._type = _type

<|endoftext|>


<commit_before>#
# This sets up how models are displayed
# in the web admin interface.
#

from django import forms
from django.db import models
from django.conf import settings
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from django.contrib.admin import widgets
from django.contrib.auth.forms import UserChangeForm, UserCreationForm
from django.contrib.auth.models import User
from src.players.models import PlayerDB, PlayerAttribute
from src.utils import logger, create

# remove User itself from admin site
admin.site.unregister(User)

# handle the custom User editor
class CustomUserChangeForm(UserChangeForm):
    username = forms.RegexField(label="Username",
                                max_length=30,
                                regex=r'^[\w. @+-]+$',
                                widget=forms.TextInput(attrs={'size':'30'}),
                                error_messages = {'invalid': "This value may contain only letters, spaces, numbers and @/./+/-/_ characters."},
                                help_text = "30 characters or fewer. Letters, spaces, digits and @/./+/-/_ only.")
    def clean_username(self):
        username = self.cleaned_data['username']
        if username.upper() == self.instance.username.upper():
            return username
        elif User.objects.filter(username__iexact=username):
            raise forms.ValidationError('A player with that name already exists.')
        return self.cleaned_data['username']

class CustomUserCreationForm(UserCreationForm):
    username = forms.RegexField(label="Username",
                                max_length=30,
                                regex=r'^[\w. @+-]+$',
                                widget=forms.TextInput(attrs={'size':'30'}),
                                error_messages = {'invalid': "This value may contain only letters, spaces, numbers and @/./+/-/_ characters."},
                                help_text = "30 characters or fewer. Letters, spaces, digits and @/./+/-/_ only.")

    def clean_username(self):
        username = self.cleaned_data['username']
        if User.objects.filter(username__iexact=username):
            raise forms.ValidationError('A player with that name already exists.')
        return username

# # The Player editor
# class PlayerAttributeForm(forms.ModelForm):
#     "Defines how to display the atttributes"
#     class Meta:
#         model = PlayerAttribute
#     db_key = forms.CharField(label="Key",
#                              widget=forms.TextInput(attrs={'size':'15'}))
#     db_value = forms.CharField(label="Value",
#                                widget=forms.Textarea(attrs={'rows':'2'}))

# class PlayerAttributeInline(admin.TabularInline):
#     "Inline creation of player attributes"
#     model = PlayerAttribute
#     extra = 0
#     form = PlayerAttributeForm
#     fieldsets = (
#         (None, {'fields'  : (('db_key', 'db_value'))}),)

class PlayerForm(forms.ModelForm):
    "Defines how to display Players"

    class Meta:
        model = PlayerDB
    db_key = forms.RegexField(label="Username",
                              initial="PlayerDummy",
                              max_length=30,
                              regex=r'^[\w. @+-]+$',
                              required=False,
                              widget=forms.TextInput(attrs={'size':'30'}),
                              error_messages = {'invalid': "This value may contain only letters, spaces, numbers and @/./+/-/_ characters."},
                              help_text = "This should be the same as the connected Player's key name. 30 characters or fewer. Letters, spaces, digits and @/./+/-/_ only.")

    db_typeclass_path = forms.CharField(label="Typeclass",
                                        initial=settings.BASE_PLAYER_TYPECLASS,
                                        widget=forms.TextInput(attrs={'size':'78'}),
                                        help_text="Required. Defines what 'type' of entity this is. This variable holds a Python path to a module with a valid Evennia Typeclass. Defaults to settings.BASE_PLAYER_TYPECLASS.")
    db_permissions = forms.CharField(label="Permissions",
                                     initial=settings.PERMISSION_PLAYER_DEFAULT,
                                     required=False,
                                     widget=forms.TextInput(attrs={'size':'78'}),
                                     help_text="In-game permissions. A comma-separated list of text strings checked by certain locks. They are often used for hierarchies, such as letting a Player have permission 'Wizards', 'Builders' etc. A Player permission can be overloaded by the permissions of a controlled Character. Normal players use 'Players' by default.")
    db_lock_storage = forms.CharField(label="Locks",
                                      widget=forms.Textarea(attrs={'cols':'100', 'rows':'2'}),
                                      required=False,
                                      help_text="In-game lock definition string. If not given, defaults will be used. This string should be on the form type:lockfunction(args);type2:lockfunction2(args);...")
    db_cmdset_storage = forms.CharField(label="cmdset",
                                        initial=settings.CMDSET_PLAYER,
                                        widget=forms.TextInput(attrs={'size':'78'}),
                                        required=False,
                                        help_text="python path to player cmdset class (set in settings.CMDSET_PLAYER by default)")

class PlayerInline(admin.StackedInline):
    "Inline creation of Player"
    model = PlayerDB
    template = "admin/players/stacked.html"
    form = PlayerForm
    fieldsets = (
        ("In-game Permissions and Locks",
         {'fields': ('db_permissions', 'db_lock_storage'),
          'description':"These are permissions/locks for in-game use. They are unrelated to website access rights."}),
        ("In-game Player data",
         {'fields':('db_typeclass_path', 'db_cmdset_storage'),
          'description':"These fields define in-game-specific properties for the Player object in-game."}),
        )

    extra = 1
    max_num = 1

class UserAdmin(BaseUserAdmin):
    "This is the main creation screen for Users/players"

    list_display = ('username','email', 'is_staff', 'is_superuser')
    form = CustomUserChangeForm
    add_form = CustomUserCreationForm
    inlines = [PlayerInline]
    add_form_template = "admin/players/add_form.html"
    change_form_template = "admin/players/change_form.html"
    change_list_template = "admin/players/change_list.html"
    fieldsets = (
        (None, {'fields': ('username', 'password', 'email')}),
        ('Website profile', {'fields': ('first_name', 'last_name'),
                           'description':"These are not used in the default system."}),
        ('Website dates', {'fields': ('last_login', 'date_joined'),
                             'description':'Relevant only to the website.'}),
        ('Website Permissions', {'fields': ('is_active', 'is_staff', 'is_superuser', 'user_permissions','groups'),
                                 'description': "These are permissions/permission groups for accessing the admin site. They are unrelated to in-game access rights."}),)

    add_fieldsets = (
        (None,
         {'fields': ('username', 'password1', 'password2', 'email'),
          'description':"These account details are shared by the admin system and the game."},),)

    def is_valid(self):
        raise Exception
        if not super(UserAdmin, self).is_valid():
            return False
        username = self.cleaned_data['username']
        if self.instance and self.instance.username.upper() == username.upper():
            return True
        elif User.objects.filter(username__iexact=username):
            raise ValidationError({'username' : 'A player with that name already exists.'})
        return True

    def save_formset(self, request, form, formset, change):
        "Run all hooks on the player object"
        super(UserAdmin, self).save_formset(request, form, formset, change)
        userobj = form.instance
        playerobj = userobj.get_profile()
        playerobj.name = userobj.username
        if not change:
            #uname, passwd, email = str(request.POST.get(u"username")), \
            #        str(request.POST.get(u"password1")), str(request.POST.get(u"email"))
            typeclass = str(request.POST.get(u"playerdb_set-0-db_typeclass_path"))
            create.create_player("","","",
                                 user=userobj,
                                 typeclass=typeclass,
                                 player_dbobj=playerobj)

admin.site.register(User, UserAdmin)
<commit_msg>Removed uneccessary test function.<commit_after>#
# This sets up how models are displayed
# in the web admin interface.
#

from django import forms
from django.db import models
from django.conf import settings
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from django.contrib.admin import widgets
from django.contrib.auth.forms import UserChangeForm, UserCreationForm
from django.contrib.auth.models import User
from src.players.models import PlayerDB, PlayerAttribute
from src.utils import logger, create

# remove User itself from admin site
admin.site.unregister(User)

# handle the custom User editor
class CustomUserChangeForm(UserChangeForm):
    username = forms.RegexField(label="Username",
                                max_length=30,
                                regex=r'^[\w. @+-]+$',
                                widget=forms.TextInput(attrs={'size':'30'}),
                                error_messages = {'invalid': "This value may contain only letters, spaces, numbers and @/./+/-/_ characters."},
                                help_text = "30 characters or fewer. Letters, spaces, digits and @/./+/-/_ only.")
    def clean_username(self):
        username = self.cleaned_data['username']
        if username.upper() == self.instance.username.upper():
            return username
        elif User.objects.filter(username__iexact=username):
            raise forms.ValidationError('A player with that name already exists.')
        return self.cleaned_data['username']

class CustomUserCreationForm(UserCreationForm):
    username = forms.RegexField(label="Username",
                                max_length=30,
                                regex=r'^[\w. @+-]+$',
                                widget=forms.TextInput(attrs={'size':'30'}),
                                error_messages = {'invalid': "This value may contain only letters, spaces, numbers and @/./+/-/_ characters."},
                                help_text = "30 characters or fewer. Letters, spaces, digits and @/./+/-/_ only.")

    def clean_username(self):
        username = self.cleaned_data['username']
        if User.objects.filter(username__iexact=username):
            raise forms.ValidationError('A player with that name already exists.')
        return username

# # The Player editor
# class PlayerAttributeForm(forms.ModelForm):
#     "Defines how to display the atttributes"
#     class Meta:
#         model = PlayerAttribute
#     db_key = forms.CharField(label="Key",
#                              widget=forms.TextInput(attrs={'size':'15'}))
#     db_value = forms.CharField(label="Value",
#                                widget=forms.Textarea(attrs={'rows':'2'}))

# class PlayerAttributeInline(admin.TabularInline):
#     "Inline creation of player attributes"
#     model = PlayerAttribute
#     extra = 0
#     form = PlayerAttributeForm
#     fieldsets = (
#         (None, {'fields'  : (('db_key', 'db_value'))}),)

class PlayerForm(forms.ModelForm):
    "Defines how to display Players"

    class Meta:
        model = PlayerDB
    db_key = forms.RegexField(label="Username",
                              initial="PlayerDummy",
                              max_length=30,
                              regex=r'^[\w. @+-]+$',
                              required=False,
                              widget=forms.TextInput(attrs={'size':'30'}),
                              error_messages = {'invalid': "This value may contain only letters, spaces, numbers and @/./+/-/_ characters."},
                              help_text = "This should be the same as the connected Player's key name. 30 characters or fewer. Letters, spaces, digits and @/./+/-/_ only.")

    db_typeclass_path = forms.CharField(label="Typeclass",
                                        initial=settings.BASE_PLAYER_TYPECLASS,
                                        widget=forms.TextInput(attrs={'size':'78'}),
                                        help_text="Required. Defines what 'type' of entity this is. This variable holds a Python path to a module with a valid Evennia Typeclass. Defaults to settings.BASE_PLAYER_TYPECLASS.")
    db_permissions = forms.CharField(label="Permissions",
                                     initial=settings.PERMISSION_PLAYER_DEFAULT,
                                     required=False,
                                     widget=forms.TextInput(attrs={'size':'78'}),
                                     help_text="In-game permissions. A comma-separated list of text strings checked by certain locks. They are often used for hierarchies, such as letting a Player have permission 'Wizards', 'Builders' etc. A Player permission can be overloaded by the permissions of a controlled Character. Normal players use 'Players' by default.")
    db_lock_storage = forms.CharField(label="Locks",
                                      widget=forms.Textarea(attrs={'cols':'100', 'rows':'2'}),
                                      required=False,
                                      help_text="In-game lock definition string. If not given, defaults will be used. This string should be on the form type:lockfunction(args);type2:lockfunction2(args);...")
    db_cmdset_storage = forms.CharField(label="cmdset",
                                        initial=settings.CMDSET_PLAYER,
                                        widget=forms.TextInput(attrs={'size':'78'}),
                                        required=False,
                                        help_text="python path to player cmdset class (set in settings.CMDSET_PLAYER by default)")

class PlayerInline(admin.StackedInline):
    "Inline creation of Player"
    model = PlayerDB
    template = "admin/players/stacked.html"
    form = PlayerForm
    fieldsets = (
        ("In-game Permissions and Locks",
         {'fields': ('db_permissions', 'db_lock_storage'),
          'description':"These are permissions/locks for in-game use. They are unrelated to website access rights."}),
        ("In-game Player data",
         {'fields':('db_typeclass_path', 'db_cmdset_storage'),
          'description':"These fields define in-game-specific properties for the Player object in-game."}),
        )

    extra = 1
    max_num = 1

class UserAdmin(BaseUserAdmin):
    "This is the main creation screen for Users/players"

    list_display = ('username','email', 'is_staff', 'is_superuser')
    form = CustomUserChangeForm
    add_form = CustomUserCreationForm
    inlines = [PlayerInline]
    add_form_template = "admin/players/add_form.html"
    change_form_template = "admin/players/change_form.html"
    change_list_template = "admin/players/change_list.html"
    fieldsets = (
        (None, {'fields': ('username', 'password', 'email')}),
        ('Website profile', {'fields': ('first_name', 'last_name'),
                           'description':"These are not used in the default system."}),
        ('Website dates', {'fields': ('last_login', 'date_joined'),
                             'description':'Relevant only to the website.'}),
        ('Website Permissions', {'fields': ('is_active', 'is_staff', 'is_superuser', 'user_permissions','groups'),
                                 'description': "These are permissions/permission groups for accessing the admin site. They are unrelated to in-game access rights."}),)

    add_fieldsets = (
        (None,
         {'fields': ('username', 'password1', 'password2', 'email'),
          'description':"These account details are shared by the admin system and the game."},),)

    def save_formset(self, request, form, formset, change):
        "Run all hooks on the player object"
        super(UserAdmin, self).save_formset(request, form, formset, change)
        userobj = form.instance
        playerobj = userobj.get_profile()
        playerobj.name = userobj.username
        if not change:
            #uname, passwd, email = str(request.POST.get(u"username")), \
            #        str(request.POST.get(u"password1")), str(request.POST.get(u"email"))
            typeclass = str(request.POST.get(u"playerdb_set-0-db_typeclass_path"))
            create.create_player("","","",
                                 user=userobj,
                                 typeclass=typeclass,
                                 player_dbobj=playerobj)

admin.site.register(User, UserAdmin)
<|endoftext|>


<commit_before>import sys
import datetime
from pprint import pprint, pformat

from django.core.management.base import BaseCommand, CommandError
from django.db import connection, connections

import base.models
from utils.functions.models import rows_to_dict_list_lower

import lotes.models as models

class Command(BaseCommand):
    help = 'Move HIST_010 do banco do systextil para o banco da intranet'
    __MAX_TASKS = 100000

    def my_println(self, text=''):
        self.my_print(text, ending='\n')

    def my_print(self, text='', ending=''):
        self.stdout.write(text, ending=ending)
        self.stdout.flush()

    def my_pprintln(self, object):
        self.my_pprint(object, ending='\n')

    def my_pprint(self, object, ending=''):
        self.stdout.write(pformat(object), ending=ending)
        self.stdout.flush()

    def iter_cursor(self, cursor):
        columns = [i[0].lower() for i in cursor.description]
        for row in cursor:
            dict_row = dict(zip(columns, row))
            yield dict_row

    def data_cursor(self, iter):
        data = []
        for row in iter:
            data.append(row)
        return data

    def get_last_hist_010_data(self):
        cursor_s = connections['so'].cursor()
        sql = '''
            SELECT
              hhh.*
            FROM
            ( SELECT
                hh.*
              FROM
              ( SELECT DISTINCT
                  h.DATA_OCORR
                FROM HIST_010 h
                ORDER BY
                  h.DATA_OCORR DESC
              ) hh
              WHERE rownum <= 10
              ORDER BY
                hh.DATA_OCORR
            ) hhh
            WHERE rownum = 1
        '''
        data_s = list(cursor_s.execute(sql))
        if len(data_s) == 0:
            return None
        else:
            return data_s[0][0]

    def get_hist_010(self, data):
        cursor_s = connections['so'].cursor()
        sql = '''
            SELECT
              h.*
            FROM HIST_010 h
            WHERE h.DATA_OCORR < %s
            ORDER BY
              h.DATA_OCORR
        '''
        cursor_s.execute(sql, [data])
        return self.iter_cursor(cursor_s)

    def insert_hist_010(self, row):
        cursor_f = connections['default'].cursor()
        sql = f'''
            INSERT INTO systextil_logs.hist_010
            ( area_producao
            , ordem_producao
            , periodo_producao
            , ordem_confeccao
            , tipo_historico
            , descricao_historico
            , tipo_ocorr
            , data_ocorr
            , hora_ocorr
            , usuario_rede
            , maquina_rede
            , aplicacao
            , nome_programa
            , usuario_sistema
            , grupo_maquina
            , tipo_ordem
            , codigo_empresa
            , codigo_estagio
            )
            VALUES
            ( {row["area_producao"]}
            , {row["ordem_producao"]}
            , {row["periodo_producao"]}
            , {row["ordem_confeccao"]}
            , {row["tipo_historico"]}
            , '{row["descricao_historico"]}'
            , '{row["tipo_ocorr"]}'
            , '{row["data_ocorr"]}'
            , '{row["hora_ocorr"]}'
            , '{row["usuario_rede"]}'
            , '{row["maquina_rede"]}'
            , '{row["aplicacao"]}'
            , '{row["nome_programa"]}'
            , '{row["usuario_sistema"]}'
            , '{row["grupo_maquina"]}'
            , {row["tipo_ordem"]}
            , {row["codigo_empresa"]}
            , {row["codigo_estagio"]}
            )
        '''
        cursor_f.execute(sql)

    def none_0(self, valor):
        return 0 if valor is None else valor

    def none_str_empty(self, valor):
        return '' if valor is None else valor

    def n_none_0(self, row, campos):
        for campo in campos:
            row[campo] = self.none_0(row[campo])

    def n_none_str_empty(self, row, campos):
        for campo in campos:
            row[campo] = self.none_str_empty(row[campo])

    def trata_none(self, row):
        self.n_none_0(
            row,
            [
                'area_producao',
                'ordem_producao',
                'periodo_producao',
                'ordem_confeccao',
                'tipo_historico',
                'tipo_ordem',
                'codigo_empresa',
                'codigo_estagio'
            ]
        )
        self.n_none_str_empty(
            row,
            [
                'descricao_historico',
                'tipo_ocorr',
                'data_ocorr',
                'hora_ocorr',
                'usuario_rede',
                'maquina_rede',
                'aplicacao',
                'nome_programa',
                'usuario_sistema',
                'grupo_maquina'
            ]
        )

    def del_hist_010(self, data):
        cursor_s = connections['so'].cursor()
        sql = '''
            DELETE FROM HIST_010 h
            WHERE h.DATA_OCORR <= %s
        '''
        cursor_s.execute(sql, [data])

    def handle(self, *args, **options):
        self.my_println('---')
        self.my_println('{}'.format(datetime.datetime.now()))

        try:
            data = self.get_last_hist_010_data()
            self.my_println(f"data {data}")

            ics = self.get_hist_010(data)

            def generator_list_echo(mylist):
                for i in mylist:
                    yield i
                while True:
                    yield i

            count = 0
            divisores = generator_list_echo([5, 10, 20, 50, 100])
            divisor = next(divisores)
            ult_data_ocorr = None
            can_break = False
            for row in ics:
                count += 1
                if (ult_data_ocorr is None or
                        ult_data_ocorr != row['data_ocorr']):
                    if can_break:
                        break
                    ult_data_ocorr = row['data_ocorr']

                self.trata_none(row)
                self.insert_hist_010(row)

                if (count % divisor) == 0:
                    divisor = next(divisores)
                    self.my_print(str(count))
                    self.my_print(' ')
                if count >= self.__MAX_TASKS:
                    can_break = True

            self.my_println(f"{count} registros copiados")

            if ult_data_ocorr is not None:
                self.del_hist_010(ult_data_ocorr)

        except Exception as e:
            raise CommandError('Erro movendo HIST_010 "{}"'.format(e))

        self.my_println(format(datetime.datetime.now(), '%H:%M:%S.%f'))
<commit_msg>mostra ult_data<commit_after>import sys
import datetime
from pprint import pprint, pformat

from django.core.management.base import BaseCommand, CommandError
from django.db import connection, connections

import base.models
from utils.functions.models import rows_to_dict_list_lower

import lotes.models as models

class Command(BaseCommand):
    help = 'Move HIST_010 do banco do systextil para o banco da intranet'
    __MAX_TASKS = 100000

    def my_println(self, text=''):
        self.my_print(text, ending='\n')

    def my_print(self, text='', ending=''):
        self.stdout.write(text, ending=ending)
        self.stdout.flush()

    def my_pprintln(self, object):
        self.my_pprint(object, ending='\n')

    def my_pprint(self, object, ending=''):
        self.stdout.write(pformat(object), ending=ending)
        self.stdout.flush()

    def iter_cursor(self, cursor):
        columns = [i[0].lower() for i in cursor.description]
        for row in cursor:
            dict_row = dict(zip(columns, row))
            yield dict_row

    def data_cursor(self, iter):
        data = []
        for row in iter:
            data.append(row)
        return data

    def get_last_hist_010_data(self):
        cursor_s = connections['so'].cursor()
        sql = '''
            SELECT
              hhh.*
            FROM
            ( SELECT
                hh.*
              FROM
              ( SELECT DISTINCT
                  h.DATA_OCORR
                FROM HIST_010 h
                ORDER BY
                  h.DATA_OCORR DESC
              ) hh
              WHERE rownum <= 10
              ORDER BY
                hh.DATA_OCORR
            ) hhh
            WHERE rownum = 1
        '''
        data_s = list(cursor_s.execute(sql))
        if len(data_s) == 0:
            return None
        else:
            return data_s[0][0]

    def get_hist_010(self, data):
        cursor_s = connections['so'].cursor()
        sql = '''
            SELECT
              h.*
            FROM HIST_010 h
            WHERE h.DATA_OCORR < %s
            ORDER BY
              h.DATA_OCORR
        '''
        cursor_s.execute(sql, [data])
        return self.iter_cursor(cursor_s)

    def insert_hist_010(self, row):
        cursor_f = connections['default'].cursor()
        sql = f'''
            INSERT INTO systextil_logs.hist_010
            ( area_producao
            , ordem_producao
            , periodo_producao
            , ordem_confeccao
            , tipo_historico
            , descricao_historico
            , tipo_ocorr
            , data_ocorr
            , hora_ocorr
            , usuario_rede
            , maquina_rede
            , aplicacao
            , nome_programa
            , usuario_sistema
            , grupo_maquina
            , tipo_ordem
            , codigo_empresa
            , codigo_estagio
            )
            VALUES
            ( {row["area_producao"]}
            , {row["ordem_producao"]}
            , {row["periodo_producao"]}
            , {row["ordem_confeccao"]}
            , {row["tipo_historico"]}
            , '{row["descricao_historico"]}'
            , '{row["tipo_ocorr"]}'
            , '{row["data_ocorr"]}'
            , '{row["hora_ocorr"]}'
            , '{row["usuario_rede"]}'
            , '{row["maquina_rede"]}'
            , '{row["aplicacao"]}'
            , '{row["nome_programa"]}'
            , '{row["usuario_sistema"]}'
            , '{row["grupo_maquina"]}'
            , {row["tipo_ordem"]}
            , {row["codigo_empresa"]}
            , {row["codigo_estagio"]}
            )
        '''
        cursor_f.execute(sql)

    def none_0(self, valor):
        return 0 if valor is None else valor

    def none_str_empty(self, valor):
        return '' if valor is None else valor

    def n_none_0(self, row, campos):
        for campo in campos:
            row[campo] = self.none_0(row[campo])

    def n_none_str_empty(self, row, campos):
        for campo in campos:
            row[campo] = self.none_str_empty(row[campo])

    def trata_none(self, row):
        self.n_none_0(
            row,
            [
                'area_producao',
                'ordem_producao',
                'periodo_producao',
                'ordem_confeccao',
                'tipo_historico',
                'tipo_ordem',
                'codigo_empresa',
                'codigo_estagio'
            ]
        )
        self.n_none_str_empty(
            row,
            [
                'descricao_historico',
                'tipo_ocorr',
                'data_ocorr',
                'hora_ocorr',
                'usuario_rede',
                'maquina_rede',
                'aplicacao',
                'nome_programa',
                'usuario_sistema',
                'grupo_maquina'
            ]
        )

    def del_hist_010(self, data):
        cursor_s = connections['so'].cursor()
        sql = '''
            DELETE FROM HIST_010 h
            WHERE h.DATA_OCORR <= %s
        '''
        cursor_s.execute(sql, [data])

    def handle(self, *args, **options):
        self.my_println('---')
        self.my_println('{}'.format(datetime.datetime.now()))

        try:
            data = self.get_last_hist_010_data()
            self.my_println(f"data {data}")

            ics = self.get_hist_010(data)

            def generator_list_echo(mylist):
                for i in mylist:
                    yield i
                while True:
                    yield i

            count = 0
            divisores = generator_list_echo([5, 10, 20, 50, 100])
            divisor = next(divisores)
            ult_data_ocorr = None
            can_break = False
            for row in ics:
                count += 1
                if (ult_data_ocorr is None or
                        ult_data_ocorr != row['data_ocorr']):
                    if can_break:
                        break
                    ult_data_ocorr = row['data_ocorr']

                self.trata_none(row)
                self.insert_hist_010(row)

                if (count % divisor) == 0:
                    divisor = next(divisores)
                    self.my_print(str(count))
                    self.my_print(' ')
                if count >= self.__MAX_TASKS:
                    can_break = True

            self.my_println(f"{count} registros copiados")

            if ult_data_ocorr is not None:
                self.my_println(f"ult_data_ocorr {ult_data_ocorr}")
                self.del_hist_010(ult_data_ocorr)

        except Exception as e:
            raise CommandError('Erro movendo HIST_010 "{}"'.format(e))

        self.my_println(format(datetime.datetime.now(), '%H:%M:%S.%f'))
<|endoftext|>


<commit_before>import os
import mimetypes
from datetime import timedelta
from functools import reduce

from django import forms
from django.db import IntegrityError
from django.core.exceptions import ObjectDoesNotExist
from django.http import Http404, HttpResponseBadRequest, HttpResponseServerError, FileResponse, JsonResponse
from django.shortcuts import render
from django.utils.http import urlquote
from django.views import View
from django.contrib.auth import get_user_model

from website.views import PlusMemberCheck
from website.models import Session, Category
from .models import ProblemList, ProblemInstance, ProblemAttachment, ProblemAuthLog, ProblemQuestion
from .helpers.score import AuthReplay
from .helpers.problem_info import get_problem_list_user_info, get_user_problem_info, get_problem_list_total_score, get_problem_list_user_score

User = get_user_model()

class ProblemListForm(forms.Form):
    q = forms.CharField(required=False)
    search_by = forms.ChoiceField(required=False, choices=[
        ('list_title', 'list title'),
        ('session', 'session')
    ])

class ProblemListView(PlusMemberCheck, View):
    def get(self, request):
        form = ProblemListForm(request.GET)
        if not form.is_valid():
            return HttpResponseBadRequest()

        all_sessions = Session.objects.order_by('title')
        all_problem_lists = ProblemList.objects.order_by('title')
        sessions = all_sessions.filter(isActive=True)
        categories = Category.objects.order_by('title')
        problem_lists = all_problem_lists
        q = ''
        search_by = 'list_title'
        if form.cleaned_data['q']:
            if form.cleaned_data['search_by']:
                search_by = form.cleaned_data['search_by']
            q = form.cleaned_data['q']

            if search_by == "list_title":
                problem_lists = problem_lists.filter(title__search=q)
            elif search_by == "session":
                sessions = sessions.filter(title__search=q)
                problem_lists = problem_lists.filter(session__in=sessions)
        else:
            problem_lists = problem_lists.filter(session__in=sessions)

        def construct_response():
            for problem_list in problem_lists:
                problem_info, user_score = get_problem_list_user_info(problem_list, request.user)
                announcement_message = problem_list.announcement
                yield problem_list, problem_info, announcement_message, user_score

        queried_problem_lists = list(construct_response())

        return render(request, 'problem/list.html', {
            'sessions': all_sessions,
            'categories': categories,
            'problem_lists': all_problem_lists,
            'queried_problem_lists': queried_problem_lists,
            'search_by': search_by,
            'q': q
        })

class ProblemGetView(PlusMemberCheck, View):
    def get(self, request, pk):
        try:
            problem_instance = ProblemInstance.objects.get(pk=int(pk))
        except ObjectDoesNotExist:
            raise Http404

        return render(request, 'problem/get.html', {
            'info': get_user_problem_info(request.user, problem_instance)
        })

class ProblemAuthForm(forms.Form):
    auth_key = forms.CharField(required=False)

class ProblemAuthView(PlusMemberCheck, View):
    def post(self, request, pk):
        form = ProblemAuthForm(request.POST)
        if not form.is_valid():
            return HttpResponseBadRequest()

        return_obj = {}
        prob_id = int(pk)
        auth_key = form.cleaned_data['auth_key']
        try:
            problem_instance = ProblemInstance.objects.get(pk=prob_id)
        except ObjectDoesNotExist:
            raise Http404

        try:
            ProblemAuthLog.objects.create(
                user=request.user, problem_instance=problem_instance, auth_key=auth_key)
            is_correct = problem_instance.problem.auth_key == auth_key
            return_obj['result'] = is_correct

        except IntegrityError:
            return_obj['result'] = False

        return JsonResponse(return_obj)

class ProblemDownloadView(PlusMemberCheck, View):
    def get(self, request, pk):
        try:
            file_obj = ProblemAttachment.objects.get(pk=int(pk)).file
        except ObjectDoesNotExist:
            raise Http404

        file_name = os.path.basename(file_obj.path)
        file_size = file_obj.size

        response = FileResponse(file_obj)
        content_type, encoding = mimetypes.guess_type(file_name)
        if content_type is None:
            content_type = 'application/octet-stream'
        if encoding is not None:
            response['Content-Encoding'] = encoding
        response['Content-Type'] = content_type
        response['Content-Disposition'] = 'attachment; filename*=UTF-8\'\'%s' % urlquote(file_name)
        response['Content-Length'] = str(file_size)
        return response

class ProblemRankView(PlusMemberCheck, View):
    def get(self, request, pk=None):
        problem_lists = ProblemList.objects
        if pk is None:
            sessions = Session.objects.filter(isActive=True).order_by('title')
            problem_lists = problem_lists.filter(session__in=sessions)
        else:
            problem_list_pk = int(pk)
            problem_lists = problem_lists.filter(pk=problem_list_pk)
            if not problem_lists.exists():
                raise Http404

        rank_info = []
        chart_info = []
        for problem_list in problem_lists:
            replay = AuthReplay(problem_list, timedelta(days=7))
            replay.prepare()
            top10_chart_data, top10_rank = replay.get_statistic_data()
            rank_info.append((problem_list, top10_rank))
            chart_info.append((problem_list, top10_chart_data))

        return render(request, 'problem/rank.html', {
            'rank_info': rank_info,
            'chart_info': chart_info
        })

class ProblemQuestionView(PlusMemberCheck, View):
    def get(self, request):
        questions = request.user.problemquestion_set.order_by('-datetime')
        if self.request.user.is_staff:
            answers = ProblemQuestion.objects.all().order_by('-datetime')
        else:
            answers = {}

        return render(request, 'problem/question.html', {
            'queried_questions': questions,
            'queried_answers': answers
        })

class ProblemQuestionAskForm(forms.Form):
    question = forms.CharField(required=False)

class ProblemQuestionAskView(PlusMemberCheck, View):
    def post(self, request, pk):
        form = ProblemQuestionAskForm(request.POST)
        if not form.is_valid():
            return HttpResponseBadRequest()

        question_text = form.cleaned_data['question']

        try:
            problem_instance = ProblemInstance.objects.get(pk=int(pk))
        except ObjectDoesNotExist:
            raise Http404

        if not problem_instance.problem_list.allow_question:
            return HttpResponseBadRequest()

        question_response = {
            "name": problem_instance.problem.title,
            "list": problem_instance.problem_list.title,
            "question": question_text
        }

        if not question_text:
            question_response['ok'] = False
            return JsonResponse(question_response)

        else:
            question_response['ok'] = True

            try:
                ProblemQuestion.objects.create(
                    user=request.user, problem_instance=problem_instance, question=question_text)

            except BaseException:
                return HttpResponseServerError()

        return JsonResponse(question_response)

class ProblemUserView(PlusMemberCheck, View):
    def get(self, request):
        problem_lists = ProblemList.objects.filter(session__isActive=True)
        problem_lists_with_total = []
        for problem_list in problem_lists:
            total = get_problem_list_total_score(problem_list, fixed=True)
            problem_lists_with_total.append({"problem_list": problem_list, "total": total})

        solved_log_queries = []
        for problem_instance in ProblemInstance.objects.all():
            correct_auth_key = problem_instance.problem.auth_key
            solve_logs = ProblemAuthLog.objects.filter(problem_instance=problem_instance, auth_key=correct_auth_key)
            solved_log_queries.append(solve_logs)

        solve_logs = \
            reduce(lambda x, y: x | y, solved_log_queries, ProblemAuthLog.objects.none()) \
            .order_by('datetime')
        user_pks_with_logs = solve_logs.values_list('user', flat=True)
        users_with_logs = User.objects.filter(pk__in=user_pks_with_logs)

        user_data = []
        for user in users_with_logs:
            scores = []
            for problem_list_with_total in problem_lists_with_total:
                problem_list = problem_list_with_total["problem_list"]
                score = get_problem_list_user_score(problem_list, user, fixed=True)
                scores.append({"score": score, "total": problem_list_with_total["total"]})

            user_data.append({"user": user, "scores": scores})

        return render(request, 'problem/user.html', {
            "user_data": user_data,
            "problem_lists": problem_lists
        })
<commit_msg>Add from attribute to Exception<commit_after>import os
import mimetypes
from datetime import timedelta
from functools import reduce

from django import forms
from django.db import IntegrityError
from django.core.exceptions import ObjectDoesNotExist
from django.http import Http404, HttpResponseBadRequest, HttpResponseServerError, FileResponse, JsonResponse
from django.shortcuts import render
from django.utils.http import urlquote
from django.views import View
from django.contrib.auth import get_user_model

from website.views import PlusMemberCheck
from website.models import Session, Category
from .models import ProblemList, ProblemInstance, ProblemAttachment, ProblemAuthLog, ProblemQuestion
from .helpers.score import AuthReplay
from .helpers.problem_info import get_problem_list_user_info, get_user_problem_info, get_problem_list_total_score, get_problem_list_user_score

User = get_user_model()

class ProblemListForm(forms.Form):
    q = forms.CharField(required=False)
    search_by = forms.ChoiceField(required=False, choices=[
        ('list_title', 'list title'),
        ('session', 'session')
    ])

class ProblemListView(PlusMemberCheck, View):
    def get(self, request):
        form = ProblemListForm(request.GET)
        if not form.is_valid():
            return HttpResponseBadRequest()

        all_sessions = Session.objects.order_by('title')
        all_problem_lists = ProblemList.objects.order_by('title')
        sessions = all_sessions.filter(isActive=True)
        categories = Category.objects.order_by('title')
        problem_lists = all_problem_lists
        q = ''
        search_by = 'list_title'
        if form.cleaned_data['q']:
            if form.cleaned_data['search_by']:
                search_by = form.cleaned_data['search_by']
            q = form.cleaned_data['q']

            if search_by == "list_title":
                problem_lists = problem_lists.filter(title__search=q)
            elif search_by == "session":
                sessions = sessions.filter(title__search=q)
                problem_lists = problem_lists.filter(session__in=sessions)
        else:
            problem_lists = problem_lists.filter(session__in=sessions)

        def construct_response():
            for problem_list in problem_lists:
                problem_info, user_score = get_problem_list_user_info(problem_list, request.user)
                announcement_message = problem_list.announcement
                yield problem_list, problem_info, announcement_message, user_score

        queried_problem_lists = list(construct_response())

        return render(request, 'problem/list.html', {
            'sessions': all_sessions,
            'categories': categories,
            'problem_lists': all_problem_lists,
            'queried_problem_lists': queried_problem_lists,
            'search_by': search_by,
            'q': q
        })

class ProblemGetView(PlusMemberCheck, View):
    def get(self, request, pk):
        try:
            problem_instance = ProblemInstance.objects.get(pk=int(pk))
        except ObjectDoesNotExist:
            raise Http404 from ObjectDoesNotExist

        return render(request, 'problem/get.html', {
            'info': get_user_problem_info(request.user, problem_instance)
        })

class ProblemAuthForm(forms.Form):
    auth_key = forms.CharField(required=False)

class ProblemAuthView(PlusMemberCheck, View):
    def post(self, request, pk):
        form = ProblemAuthForm(request.POST)
        if not form.is_valid():
            return HttpResponseBadRequest()

        return_obj = {}
        prob_id = int(pk)
        auth_key = form.cleaned_data['auth_key']
        try:
            problem_instance = ProblemInstance.objects.get(pk=prob_id)
        except ObjectDoesNotExist:
            raise Http404 from ObjectDoesNotExist

        try:
            ProblemAuthLog.objects.create(
                user=request.user, problem_instance=problem_instance, auth_key=auth_key)
            is_correct = problem_instance.problem.auth_key == auth_key
            return_obj['result'] = is_correct

        except IntegrityError:
            return_obj['result'] = False

        return JsonResponse(return_obj)

class ProblemDownloadView(PlusMemberCheck, View):
    def get(self, request, pk):
        try:
            file_obj = ProblemAttachment.objects.get(pk=int(pk)).file
        except ObjectDoesNotExist:
            raise Http404 from ObjectDoesNotExist

        file_name = os.path.basename(file_obj.path)
        file_size = file_obj.size

        response = FileResponse(file_obj)
        content_type, encoding = mimetypes.guess_type(file_name)
        if content_type is None:
            content_type = 'application/octet-stream'
        if encoding is not None:
            response['Content-Encoding'] = encoding
        response['Content-Type'] = content_type
        response['Content-Disposition'] = 'attachment; filename*=UTF-8\'\'%s' % urlquote(file_name)
        response['Content-Length'] = str(file_size)
        return response

class ProblemRankView(PlusMemberCheck, View):
    def get(self, request, pk=None):
        problem_lists = ProblemList.objects
        if pk is None:
            sessions = Session.objects.filter(isActive=True).order_by('title')
            problem_lists = problem_lists.filter(session__in=sessions)
        else:
            problem_list_pk = int(pk)
            problem_lists = problem_lists.filter(pk=problem_list_pk)
            if not problem_lists.exists():
                raise Http404

        rank_info = []
        chart_info = []
        for problem_list in problem_lists:
            replay = AuthReplay(problem_list, timedelta(days=7))
            replay.prepare()
            top10_chart_data, top10_rank = replay.get_statistic_data()
            rank_info.append((problem_list, top10_rank))
            chart_info.append((problem_list, top10_chart_data))

        return render(request, 'problem/rank.html', {
            'rank_info': rank_info,
            'chart_info': chart_info
        })

class ProblemQuestionView(PlusMemberCheck, View):
    def get(self, request):
        questions = request.user.problemquestion_set.order_by('-datetime')
        if self.request.user.is_staff:
            answers = ProblemQuestion.objects.all().order_by('-datetime')
        else:
            answers = {}

        return render(request, 'problem/question.html', {
            'queried_questions': questions,
            'queried_answers': answers
        })

class ProblemQuestionAskForm(forms.Form):
    question = forms.CharField(required=False)

class ProblemQuestionAskView(PlusMemberCheck, View):
    def post(self, request, pk):
        form = ProblemQuestionAskForm(request.POST)
        if not form.is_valid():
            return HttpResponseBadRequest()

        question_text = form.cleaned_data['question']

        try:
            problem_instance = ProblemInstance.objects.get(pk=int(pk))
        except ObjectDoesNotExist:
            raise Http404 from ObjectDoesNotExist

        if not problem_instance.problem_list.allow_question:
            return HttpResponseBadRequest()

        question_response = {
            "name": problem_instance.problem.title,
            "list": problem_instance.problem_list.title,
            "question": question_text
        }

        if not question_text:
            question_response['ok'] = False
            return JsonResponse(question_response)

        else:
            question_response['ok'] = True

            try:
                ProblemQuestion.objects.create(
                    user=request.user, problem_instance=problem_instance, question=question_text)

            except BaseException:
                return HttpResponseServerError()

        return JsonResponse(question_response)

class ProblemUserView(PlusMemberCheck, View):
    def get(self, request):
        problem_lists = ProblemList.objects.filter(session__isActive=True)
        problem_lists_with_total = []
        for problem_list in problem_lists:
            total = get_problem_list_total_score(problem_list, fixed=True)
            problem_lists_with_total.append({"problem_list": problem_list, "total": total})

        solved_log_queries = []
        for problem_instance in ProblemInstance.objects.all():
            correct_auth_key = problem_instance.problem.auth_key
            solve_logs = ProblemAuthLog.objects.filter(problem_instance=problem_instance, auth_key=correct_auth_key)
            solved_log_queries.append(solve_logs)

        solve_logs = \
            reduce(lambda x, y: x | y, solved_log_queries, ProblemAuthLog.objects.none()) \
            .order_by('datetime')
        user_pks_with_logs = solve_logs.values_list('user', flat=True)
        users_with_logs = User.objects.filter(pk__in=user_pks_with_logs)

        user_data = []
        for user in users_with_logs:
            scores = []
            for problem_list_with_total in problem_lists_with_total:
                problem_list = problem_list_with_total["problem_list"]
                score = get_problem_list_user_score(problem_list, user, fixed=True)
                scores.append({"score": score, "total": problem_list_with_total["total"]})

            user_data.append({"user": user, "scores": scores})

        return render(request, 'problem/user.html', {
            "user_data": user_data,
            "problem_lists": problem_lists
        })
<|endoftext|>