Beispiel #1
0
    def _copyWalker(self, walkData):
        staticFolder = False
        for folder in self._staticPaths:
            path = FileUtils.cleanupPath(walkData.folder, isDir=True)
            folder = FileUtils.cleanupPath(folder, isDir=True)
            if path == folder or FileUtils.isInFolder(path, folder):
                staticFolder = True
                break

        copiedNames = []
        for item in walkData.names:
            if not staticFolder and not StringUtils.ends(item, self._FILE_COPY_TYPES):
                continue

            sourcePath = FileUtils.createPath(walkData.folder, item)
            if os.path.isdir(sourcePath):
                continue

            destPath = FileUtils.changePathRoot(
                sourcePath, self.sourceWebRootPath, self.targetWebRootPath)

            try:
                FileUtils.getDirectoryOf(destPath, createIfMissing=True)
                shutil.copy(sourcePath, destPath)

                lastModified = FileUtils.getUTCModifiedDatetime(sourcePath)
                SiteProcessUtils.createHeaderFile(destPath, lastModified)
                SiteProcessUtils.copyToCdnFolder(destPath, self, lastModified)
                copiedNames.append(item)
            except Exception, err:
                self.writeLogError(u'Unable to copy file', error=err, extras={
                    'SOURCE':sourcePath,
                    'TARGET':destPath })
                return
Beispiel #2
0
    def initializeFromInternalPath(cls, referencePath, force =False):
        """ Used to explicitly initialiize the pyglass environment when running inside the source
            code respository with a standard structure where the repository root has a src and
            a resources folder. """

        if cls.isInitialized and not force:
            return True

        path = FileUtils.cleanupPath(referencePath, noTail=True)
        if os.path.isfile(path):
            path = FileUtils.getDirectoryOf(referencePath, noTail=True)

        rootPath = None
        while path:
            srcPath = FileUtils.makeFolderPath(path, 'src', isDir=True)
            resPath = FileUtils.makeFolderPath(path, 'resources', isDir=True)
            if os.path.exists(srcPath) and os.path.exists(resPath):
                rootPath = path
                break
            path = FileUtils.getDirectoryOf(path, noTail=True)

        if not rootPath:
            return False

        cls._rootResourcePath       = FileUtils.makeFolderPath(rootPath, 'resources')
        cls._rootLocalResourcePath  = FileUtils.makeFolderPath(rootPath, 'resources', 'local')
        return True
Beispiel #3
0
    def __init__(self):
        """Creates a new instance of PyGlassApplication."""
        QtCore.QObject.__init__(self)
        self._qApplication = None
        self._window       = None
        self._splashScreen = None

        # Sets a temporary standard out and error for deployed applications in a write allowed
        # location to prevent failed write results.
        if PyGlassEnvironment.isDeployed:
            if appdirs:
                userDir = appdirs.user_data_dir(self.appID, self.appGroupID)
            else:
                userDir = FileUtils.createPath(
                    os.path.expanduser('~'), '.pyglass', self.appGroupID, self.appID, isDir=True)

            path = FileUtils.createPath(
                userDir,
                self.appID + '_out.log', isFile=True)
            folder = FileUtils.getDirectoryOf(path, createIfMissing=True)
            sys.stdout = open(path, 'w+')

            FileUtils.createPath(
                appdirs.user_data_dir(self.appID, self.appGroupID),
                self.appID + '_error.log',
                isFile=True)
            folder = FileUtils.getDirectoryOf(path, createIfMissing=True)
            sys.stderr = open(path, 'w+')

        PyGlassEnvironment.initializeAppSettings(self)
Beispiel #4
0
    def save(self, toPDF=True):
        """ Writes the current _drawing in SVG format to the file specified at initialization. If
            one wishes to have create a PDF file (same file name as used for the .SVG, but with
            suffix .PDF), then call with toPDF True). """

        if not self.siteMapReady:
            return

        # Make sure the directory where the file will be saved exists before saving
        FileUtils.getDirectoryOf(self._drawing.filename, createIfMissing=True)

        self._drawing.save()

        #  we're done if no PDF version is also required
        if not toPDF:
            return

        # strip any extension off of the file name
        basicName = self.fileName.split(".")[0]

        # load up the command
        cmd = ["/Applications/Inkscape.app/Contents/Resources/bin/inkscape", "-f", None, "-A", None]
        cmd[2] = basicName + ".svg"
        cmd[4] = basicName + ".pdf"

        # and execute it
        response = SystemUtils.executeCommand(cmd)
        if response["error"]:
            print("response[error]=%s" % response["error"])
Beispiel #5
0
    def __init__(self, parent, test =True, install =True, check =False, verbose =True, **kwargs):
        """Creates a new instance of MayaIniRemoteThread."""
        super(MayaIniRemoteThread, self).__init__(parent, **kwargs)
        self._test      = test
        self._verbose   = verbose
        self._install   = install
        self._check     = check
        self._output    = {}

        self._cadenceEntry = MayaEnvEntry.fromRootPath(FileUtils.createPath(
            FileUtils.getDirectoryOf(cadence.__file__), noTail=True))

        self._elixirEntry = MayaEnvEntry.fromRootPath(FileUtils.createPath(
            FileUtils.getDirectoryOf(elixir.__file__), noTail=True))
    def _handleImportSitemaps(self):

        self.mainWindow.showLoading(
            self,
            u'Browsing for Sitemap File',
            u'Choose the Sitemap CSV file to import into the database')

        path = PyGlassBasicDialogManager.browseForFileOpen(
            parent=self,
            caption=u'Select CSV File to Import',
            defaultPath=self.mainWindow.appConfig.get(UserConfigEnum.LAST_BROWSE_PATH) )

        self.mainWindow.hideLoading(self)

        if not path or not StringUtils.isStringType(path):
            self.mainWindow.toggleInteractivity(True)
            return

        # Store directory location as the last active directory
        self.mainWindow.appConfig.set(
            UserConfigEnum.LAST_BROWSE_PATH, FileUtils.getDirectoryOf(path) )

        self.mainWindow.showStatus(
            self,
            u'Importing Sitemaps',
            u'Reading sitemap information into database')

        SitemapImporterRemoteThread(
            parent=self,
            path=path
        ).execute(
            callback=self._sitemapImportComplete,
            logCallback=self._handleImportStatusUpdate)
Beispiel #7
0
    def rootPath(self):
        if self._rootPath:
            return self._rootPath

        if self._appFilePath:
            return FileUtils.getDirectoryOf(self._appFilePath)

        return FileUtils.createPath(os.path.expanduser('~'), self.appName, isDir=True)
Beispiel #8
0
def initialize(my_path):
    if os.path.isfile(my_path):
        my_path = FileUtils.getDirectoryOf(my_path)

    path = FileUtils.makeFolderPath(my_path, 'data')
    SystemUtils.remove(path)
    os.makedirs(path)

    return path
Beispiel #9
0
    def redirectLogOutputs(self, prefix =None, logFolderPath =None):
        """ Sets a temporary standard out and error for deployed applications in a write allowed
            location to prevent failed write results. """

        if not PyGlassEnvironment.isDeployed:
            return

        if not prefix:
            prefix = self.appID

        if not prefix.endswith('_'):
            prefix += '_'

        if logFolderPath:
            logPath = logFolderPath
        elif PyGlassEnvironment.isInitialized:
            logPath = PyGlassEnvironment.getRootLocalResourcePath('logs', isDir=True)
        else:
            prefix += 'init_'
            if appdirs:
                logPath = appdirs.user_data_dir(self.appID, self.appGroupID)
            else:
                logPath = FileUtils.createPath(
                    os.path.expanduser('~'), '.pyglass', self.appGroupID, self.appID, isDir=True)

        FileUtils.getDirectoryOf(logPath, createIfMissing=True)
        try:
            sys.stdout.flush()
            sys.stdout.close()
        except Exception as err:
            pass
        sys.stdout = open(FileUtils.makeFilePath(logPath, prefix + 'out.log'), 'w+')

        try:
            sys.stderr.flush()
            sys.stderr.close()
        except Exception as err:
            pass
        sys.stderr = open(FileUtils.makeFilePath(logPath, prefix + 'error.log'), 'w+')

        return True
Beispiel #10
0
    def _getSourcePaths(cls, otherPaths =None):
        nimbleEntry = MayaEnvEntry.fromRootPath(FileUtils.createPath(
            FileUtils.getDirectoryOf(nimble.__file__), noTail=True) )

        pyaidEntry = MayaEnvEntry.fromRootPath(FileUtils.createPath(
            FileUtils.getDirectoryOf(pyaid.__file__), noTail=True) )

        pyglassEntry = MayaEnvEntry.fromRootPath(FileUtils.createPath(
            FileUtils.getDirectoryOf(pyglass.__file__), noTail=True) )

        additions = [nimbleEntry, pyaidEntry, pyglassEntry]

        if not otherPaths:
            return additions

        for p in otherPaths:
            additions.append(
                p if isinstance(p, MayaEnvEntry) else
                MayaEnvEntry.fromRootPath(p) )

        return additions
Beispiel #11
0
    def compileCss(cls, site, path):
        outPath = FileUtils.changePathRoot(
            path, site.sourceWebRootPath, site.targetWebRootPath)
        FileUtils.getDirectoryOf(outPath, createIfMissing=True)

        if site.isLocal:
            shutil.copy(path, outPath)
            site.writeLogSuccess(u'COPIED', unicode(path))
        else:
            cmd = cls.modifyNodeCommand([
                FileUtils.createPath(
                    StaticFlowEnvironment.nodePackageManagerPath, 'minify', isFile=True),
                '"%s"' % path,
                '"%s"' % outPath])

            iniDirectory = os.curdir
            os.chdir(os.path.dirname(path))
            result = SystemUtils.executeCommand(cmd)
            if result['code']:
                site.logger.write(unicode(result['error']))
                site.writeLogError(u'CSS compilation failure:', extras={
                    'PATH':path,
                    'ERROR':result['error']})
                os.chdir(iniDirectory)
                return False

            site.writeLogSuccess(u'COMPRESSED', unicode(path))
            os.chdir(iniDirectory)

        source = FileUtils.getContents(outPath)
        if not source:
            return False
        FileUtils.putContents(
            cls._CSS_CDN_IMAGE_RE.sub('url(\g<quote>' + site.cdnRootUrl + '/', source),
            outPath)

        lastModified = FileUtils.getUTCModifiedDatetime(path)
        SiteProcessUtils.createHeaderFile(outPath, lastModified)
        cls.copyToCdnFolder(outPath, site, lastModified)
        return True
Beispiel #12
0
    def _getSourcePaths(cls, otherPaths=None):
        nimbleEntry = MayaEnvEntry.fromRootPath(
            FileUtils.createPath(FileUtils.getDirectoryOf(nimble.__file__),
                                 noTail=True))

        pyaidEntry = MayaEnvEntry.fromRootPath(
            FileUtils.createPath(FileUtils.getDirectoryOf(pyaid.__file__),
                                 noTail=True))

        pyglassEntry = MayaEnvEntry.fromRootPath(
            FileUtils.createPath(FileUtils.getDirectoryOf(pyglass.__file__),
                                 noTail=True))

        additions = [nimbleEntry, pyaidEntry, pyglassEntry]

        if not otherPaths:
            return additions

        for p in otherPaths:
            additions.append(p if isinstance(p, MayaEnvEntry) else MayaEnvEntry
                             .fromRootPath(p))

        return additions
Beispiel #13
0
    def compileCoffeescript(cls, site, path):
        csPath  = FileUtils.cleanupPath(path, isFile=True)
        outPath = FileUtils.changePathRoot(
            csPath[:-6] + 'js', site.sourceWebRootPath, site.targetWebRootPath)
        FileUtils.getDirectoryOf(outPath, createIfMissing=True)

        outDir = os.path.dirname(outPath)
        result = cls.compileCoffeescriptFile(csPath, outDir, minify=not site.isLocal)
        if result['code']:
            site.writeLogError(u'Failed to compile: "%s"' % unicode(path))
            print result
            return False
        else:
            site.writeLogSuccess(u'COMPILED', unicode(path))

        lastModified = FileUtils.getUTCModifiedDatetime(csPath)
        SiteProcessUtils.createHeaderFile(outPath, lastModified)
        if site.isLocal:
            return True

        cls.copyToCdnFolder(outPath, site, lastModified)
        site.writeLogSuccess(u'COMPRESSED', unicode(outPath))

        return True
Beispiel #14
0
    def copyToCdnFolder(cls, targetPath, processor, lastModified =None, headers =None):
        if processor.isLocal:
            return False

        folder = targetPath[len(processor.targetWebRootPath):].replace('\\', '/').strip('/').split('/')
        destPath = FileUtils.createPath(
            processor.targetWebRootPath, processor.cdnRootFolder, folder, isFile=True)
        destFolder = FileUtils.getDirectoryOf(destPath)
        if not os.path.exists(destFolder):
            os.makedirs(destFolder)
        shutil.copy(targetPath, destPath)

        if not headers:
            headers = dict()

        if 'Expires' not in headers:
            headers['Expires'] = TimeUtils.dateTimeToWebTimestamp(
                datetime.datetime.utcnow() + datetime.timedelta(days=360))
        cls.createHeaderFile(destPath, lastModified=lastModified, headers=headers)
        return True
Beispiel #15
0
    def _handleExport(self):

        self.mainWindow.showLoading(
            self,
            u'Browsing for Exporting File',
            u'Choose the file location to save the export')

        defaultPath = self.mainWindow.appConfig.get(UserConfigEnum.LAST_SAVE_PATH)
        if not defaultPath:
            defaultPath = self.mainWindow.appConfig.get(UserConfigEnum.LAST_BROWSE_PATH)

        path = PyGlassBasicDialogManager.browseForFileSave(
            parent=self, caption=u'Specify Export File', defaultPath=defaultPath)
        self.mainWindow.hideLoading(self)

        if not path:
            self.mainWindow.toggleInteractivity(True)
            return

        # Store directory location as the last save directory
        self.mainWindow.appConfig.set(
            UserConfigEnum.LAST_SAVE_PATH,
            FileUtils.getDirectoryOf(path) )

        if not path.endswith('.json'):
            path += '.json'

        self.mainWindow.showStatus(
            self,
            u'Exporting Tracks',
            u'Writing track information from database')

        self._thread = TrackExporterRemoteThread(
            self, path=path,
            pretty=self.exportPrettyCheck.isChecked(),
            compressed=self.exportCompressCheck.isChecked(),
            difference=self.exportDiffCheck.isChecked())

        self._thread.execute(
            callback=self._handleImportComplete,
            logCallback=self._handleImportStatusUpdate)
Beispiel #16
0
    def _handleImport(self):
        label = u'CSV'
        importType = TrackImporterRemoteThread.CSV

        self.mainWindow.showLoading(
            self,
            u'Browsing for Track File',
            u'Choose the %s file to import into the database' % label)

        path = PyGlassBasicDialogManager.browseForFileOpen(
            parent=self,
            caption=u'Select %s File to Import' % label,
            defaultPath=self.mainWindow.appConfig.get(UserConfigEnum.LAST_BROWSE_PATH) )

        self.mainWindow.hideLoading(self)
        if not path or not StringUtils.isStringType(path):
            self.mainWindow.toggleInteractivity(True)
            return

        # Store directory location as the last active directory
        self.mainWindow.appConfig.set(
            UserConfigEnum.LAST_BROWSE_PATH, FileUtils.getDirectoryOf(path) )

        self.mainWindow.showStatus(
            self,
            u'Importing Tracks',
            u'Reading track information into database')

        TrackImporterRemoteThread(
            parent=self,
            path=path,
            verbose=self.verboseDisplayCheck.isChecked(),
            importType=importType,
            compressed=False
        ).execute(
            callback=self._handleImportComplete,
            logCallback=self._handleImportStatusUpdate )
Beispiel #17
0
    def _processFolderDefinitions(self, path):
        cd        = ConfigsDict(JSON.fromFile(path))
        directory = FileUtils.getDirectoryOf(path)

        for item in os.listdir(directory):
            # Only find content source file types
            if not StringUtils.ends(item, ('.sfml', '.html')):
                continue

            # Skip files that already have a definitions file
            itemPath     = FileUtils.createPath(directory, item, isFile=True)
            itemDefsPath = itemPath.rsplit('.', 1)[0] + '.def'
            if os.path.exists(itemDefsPath):
                continue

            test = SiteProcessUtils.testFileFilter(
                itemPath,
                cd.get(('FOLDER', 'EXTENSION_FILTER')),
                cd.get(('FOLDER', 'NAME_FILTER')))
            if not test:
                continue

            JSON.toFile(itemDefsPath, dict(), pretty=True)
        return True
Beispiel #18
0
    def modifyEnvFile(cls, target, install =True, test =False):
        """Doc..."""
        pathSep = OsUtils.getPerOsValue(u';', u':')

        nimblePath = FileUtils.createPath(
            FileUtils.getDirectoryOf(nimble.__file__),
            '..', isDir=True, noTail=True)

        pyaidPath = FileUtils.createPath(
            FileUtils.getDirectoryOf(pyaid.__file__),
            '..', isDir=True, noTail=True)

        pyglassPath = FileUtils.createPath(
            FileUtils.getDirectoryOf(pyglass.__file__),
            '..', isDir=True, noTail=True)

        removals  = []
        additions = [nimblePath]
        if not StringUtils.matches(pyaidPath, additions):
            additions.append(pyaidPath)

        if not StringUtils.matches(pyglassPath, additions):
            additions.append(pyglassPath)

        with open(target, 'r') as f:
            contents = f.read()

        result = cls._PYTHON_PATH_PATTERN.search(contents)
        if not result:
            if install:
                contents += (u'\n' if contents else u'') + u'PYTHONPATH=' + pathSep.join(additions)
            else:
                return cls.MAYA_ENV_MODIFIED_RESULT_NT([], [])
        else:
            paths = result.groupdict()['paths'].split(pathSep)
            index = 0
            while index < len(paths):
                if not additions:
                    break

                p = paths[index]

                # If path already exists don't add it again
                if p in additions:
                    additions.remove(p)
                    if not install:
                        removals.append(p)
                        paths.remove(p)
                    else:
                        index += 1
                    continue
                elif not install:
                    index += 1
                    continue

                # Remove unrecognized paths that import nimble, pyaid, or pyglass
                testPaths = [
                    FileUtils.createPath(p, u'nimble', isDir=True),
                    FileUtils.createPath(p, u'pyaid', isDir=True),
                    FileUtils.createPath(p, u'pyglass', isDir=True) ]
                for test in testPaths:
                    if os.path.exists(test):
                        paths.remove(p)
                        continue

                index += 1

            paths += additions
            contents = contents[:result.start()] + u'PYTHONPATH=' + pathSep.join(paths) \
                + u'\n' + contents[result.end():]

        result = cls.MAYA_ENV_MODIFIED_RESULT_NT(additions if install else [], removals)
        if test:
            return result

        with open(target, 'w') as f:
            f.write(contents)

        return result
Beispiel #19
0
# helloPythonImport.py
# (C)2014
# Scott Ernst
""" This example shows how to use the advanced import scripting in Nimble. """

from __future__ import print_function, absolute_import, unicode_literals, division

import sys

from pyaid.file.FileUtils import FileUtils

import nimble

# Add the src path for this example to the python system path for access to the scripts
scriptPath = FileUtils.createPath(FileUtils.getDirectoryOf(__file__),
                                  'src',
                                  isDir=True)
sys.path.append(scriptPath)

from helloPythonImportExample.scripts import CreateSpheres

# Create a Nimble connection object. This object will be used to send and receive across the
# nimble communication bridge between this script and the Nimble server running in Maya
conn = nimble.getConnection()

# Add the script src path to the Maya Python environment as well so that it can import and run
# the scripts directly
result = conn.addToMayaPythonPath(scriptPath)
if not result.success:
    print(
        'Unable to modify Maya Python path. Are you sure Maya is running a Nimble server?'
Beispiel #20
0
# helloPythonImport.py
# (C)2014
# Scott Ernst

""" This example shows how to use the advanced import scripting in Nimble. """

from __future__ import print_function, absolute_import, unicode_literals, division

import sys

from pyaid.file.FileUtils import FileUtils

import nimble

# Add the src path for this example to the python system path for access to the scripts
scriptPath = FileUtils.createPath(FileUtils.getDirectoryOf(__file__), 'src', isDir=True)
sys.path.append(scriptPath)

from helloPythonImportExample.scripts import CreateSpheres

# Create a Nimble connection object. This object will be used to send and receive across the
# nimble communication bridge between this script and the Nimble server running in Maya
conn = nimble.getConnection()

# Add the script src path to the Maya Python environment as well so that it can import and run
# the scripts directly
result = conn.addToMayaPythonPath(scriptPath)
if not result.success:
    print('Unable to modify Maya Python path. Are you sure Maya is running a Nimble server?')
    print(result)
    sys.exit(1)
Beispiel #21
0
def getProjectPath(*args, **kwargs):
    return FileUtils.createPath(
        FileUtils.getDirectoryOf(__file__),
        '..', '..', *args, **kwargs)
Beispiel #22
0
#---------------------------------------------------------------------------------------------------
# INITIALIZE PYGLASS ENVIRONMENT
#       When running outside of a PyGlass application, the PyGlass environment must be initialized
#       explicitly, including specifying the relationship between the run script (this file) and
#       the resource directory. This must be done before importing database classes so that the
#       database import correctly locates the database file and initializes the model classes to
#       that file.

from pyaid.system.SystemUtils import SystemUtils

from pyaid.file.FileUtils import FileUtils

from pyglass.app.PyGlassEnvironment import PyGlassEnvironment

location = FileUtils.getDirectoryOf(__file__)

PyGlassEnvironment.initializeExplicitAppSettings(
    FileUtils.createPath(location, '..', 'resources', isDir=True),
    FileUtils.createPath(location, '..', 'resources', 'local', isDir=True) )

#---------------------------------------------------------------------------------------------------
# RUN TEST SCRIPT

from cadence.models.tracks.Tracks_SiteMap import Tracks_SiteMap
from cadence.svg.CadenceDrawing import CadenceDrawing

model   = Tracks_SiteMap.MASTER
session = model.createSession()
siteMap = session.query(model).filter(model.index == 13).first()
fileName = 'test_new.svg'
Beispiel #23
0
# Scott Ernst

from __future__ import \
    print_function, absolute_import, \
    unicode_literals, division

import os
import re

import sqlalchemy as sqla
import pandas as pd

from pyaid.file.FileUtils import FileUtils

ROOT_PROJECT_PATH = FileUtils.makeFolderPath(
    FileUtils.getDirectoryOf(__file__), '..', '..')

_data = None

#_______________________________________________________________________________
def getProjectPath(*args, **kwargs):
    """ Creates an absolute path from the relative path arguments within the
        project folder.
    """
    return FileUtils.createPath(ROOT_PROJECT_PATH, *args, **kwargs)

#_______________________________________________________________________________
def getResourcesPath(*args, **kwargs):
    """ Creates an absolute path from the relative path arguments within the
        project folder.
    """
Beispiel #24
0
# initializeStatsEnv.py
# (C)2015
# Scott Ernst

from __future__ import print_function, absolute_import, unicode_literals, division

import sys
import os

from pyaid.file.FileUtils import FileUtils
from pyaid.string.StringUtils import StringUtils
from pyaid.system.SystemUtils import SystemUtils

rootPath = FileUtils.getDirectoryOf(__file__)

#---------------------------------------------------------------------------------------------------
# INPUTS

inputPath = FileUtils.createPath('input', isDir=True)
if os.path.exists(inputPath):
    SystemUtils.remove(inputPath)
os.makedirs(inputPath)

localDatabasePath = FileUtils.createPath(
    rootPath, '..', 'resources', 'local', 'apps', 'Cadence', 'data', isDir=True)

if not os.path.exists(localDatabasePath):
    print('[ERROR]: No local database resource folder exists')
    sys.exit(1)

for filename in os.listdir(localDatabasePath):
Beispiel #25
0
# Scott Ernst

from __future__ import print_function, absolute_import, unicode_literals, division

import os
import sys

from pyaid.file.FileUtils import FileUtils
from pyaid.json.JSON import JSON
from pyaid.system.SystemUtils import SystemUtils

FOLDER_NAME = 'Statistical-Results'

#---------------------------------------------------------------------------------------------------

rootPath = FileUtils.getDirectoryOf(__file__)
localAnalysisPath = FileUtils.makeFolderPath(rootPath, '..', 'resources', 'local', 'analysis')
analysisConfigPath = FileUtils.makeFilePath(localAnalysisPath, 'analysis.json')

config = JSON.fromFile(analysisConfigPath)

if 'OUTPUT_PATH' not in config:
    rootTargetPath = localAnalysisPath
else:
    rootTargetPath = FileUtils.cleanupPath(config['OUTPUT_PATH'], isDir=True)

targetPath = FileUtils.makeFolderPath(rootTargetPath, FOLDER_NAME)

if os.path.exists(targetPath):
    SystemUtils.remove(targetPath)
Beispiel #26
0
import locale
import numpy as np
import pandas as pd
import plotly.graph_objs as plotlyGraph
from cadence.analysis.shared import DataLoadUtils, PlotConfigs
from cadence.analysis.shared.plotting import PlotlyUtils
from plotly import plotly

################################################################################

locale.setlocale(locale.LC_ALL, ('en_US', 'utf8'))

PLOTLY_FOLDER = 'Comparison'

MY_DIR = FileUtils.getDirectoryOf(__file__)
DATA_DIR = FileUtils.makeFolderPath(MY_DIR, 'data')
OUT_PATH = FileUtils.makeFilePath(DATA_DIR, 'deviation.h5')
METADATA_FILE = FileUtils.makeFilePath(DATA_DIR, 'deviation.metadata.json')

#_______________________________________________________________________________
def _getLayout(
        metadata, title, fixed = False, xAxis =None, yAxis =None, **kwargs
):
    if not xAxis:
        xAxis = {}
    xAxis.setdefault('title', 'Deviation (%)')

    if not yAxis:
        yAxis = {}
    yAxis.setdefault('title', 'Frequency')
Beispiel #27
0
    def _handleReplaceDatabase(self):

        self.mainWindow.showLoading(
            self,
            u'Browsing for Database File',
            u'Choose a valid database (*.vcd) file')

        defaultPath = self.appConfig.get(UserConfigEnum.DATABASE_IMPORT_PATH)
        if not defaultPath:
            defaultPath = self.appConfig.get(UserConfigEnum.LAST_BROWSE_PATH)

        path = PyGlassBasicDialogManager.browseForFileOpen(
            parent=self,
            caption=u'Select Database File',
            defaultPath=defaultPath)
        self.mainWindow.hideLoading(self)

        if not path:
            self.mainWindow.toggleInteractivity(True)
            return

        # Store directory for later use
        self.appConfig.set(
            UserConfigEnum.DATABASE_IMPORT_PATH,
            FileUtils.getDirectoryOf(path) )

        self.mainWindow.showStatus(
            self,
            u'Replacing Database File',
            u'Removing existing database file and replacing it with selection')

        sourcePath = getattr(Tracks_Track, 'URL')[len(u'sqlite:'):].lstrip(u'/')
        if not OsUtils.isWindows():
            sourcePath = u'/' + sourcePath

        savePath = '%s.store' % sourcePath
        try:
            if os.path.exists(savePath):
                SystemUtils.remove(savePath, throwError=True)
        except Exception as err:
            self.mainWindow.appendStatus(
                self, u'<span style="color:#CC3333">ERROR: Unable to access database save location.</span>')
            self.mainWindow.showStatusDone(self)
            return

        try:
            SystemUtils.move(sourcePath, savePath)
        except Exception as err:
            self.mainWindow.appendStatus(
                self, u'<span style="color:#CC3333;">ERROR: Unable to modify existing database file.</span>')
            self.mainWindow.showStatusDone(self)
            return

        try:
            SystemUtils.copy(path, sourcePath)
        except Exception as err:
            SystemUtils.move(savePath, sourcePath)
            self.mainWindow.appendStatus(
                self, u'<span style="color:#CC3333;">ERROR: Unable to copy new database file.</span>')
            self.mainWindow.showStatusDone(self)
            return

        if os.path.exists(savePath):
            SystemUtils.remove(savePath)

        self.mainWindow.appendStatus(self, u'<span style="color:#33CC33;">Database Replaced</span>')
        self.mainWindow.showStatusDone(self)
Beispiel #28
0
 def targetPath(self):
     """ Absolute path to the location where the rss file will be generated. """
     return FileUtils.createPath(
         FileUtils.getDirectoryOf(self.page.targetPath), 'rss.xml', isFile=True)