Exemplo n.º 1
0
    def InitializePath(self):
        searchPath = []
        currentDir = Directory.GetCurrentDirectory()
        searchPath.append(currentDir)
        filePathDir = Path.GetDirectoryName(Path.Combine(currentDir, self.fileName))
        searchPath.append(filePathDir)
        entryDir = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location)
        searchPath.append(entryDir)
        siteDir = Path.Combine(entryDir, "Lib")
        searchPath.append(siteDir)
        dllsDir = Path.Combine(entryDir, "DLLs")
        if Directory.Exists(dllsDir):
            searchPath.append(dllsDir)

        self.engine.SetSearchPaths(Array[str](searchPath))
Exemplo n.º 2
0
def _check_magic_file(path_s):
   ''' ComicVine implementation of the identically named method in the db.py '''
   series_ref = None
   file_s = None
   try:
      # 1. get the directory to search for a cvinfo file in, or None
      dir_s = path_s if path_s and Directory.Exists(path_s) else \
         Path.GetDirectoryName(path_s) if path_s else None
      dir_s = dir_s if dir_s and Directory.Exists(dir_s) else None
      
      if dir_s:
         # 2. search in that directory for a properly named cvinfo file
         #    note that Windows filenames are not case sensitive.
         for f in [dir_s + "\\" + x for x in ["cvinfo.txt", "cvinfo"]]:
            if File.Exists(f):
               file_s = f 
            
         # 3. if we found a file, read it's contents in, and parse the 
         #    comicvine series id out of it, if possible.
         if file_s:
            with StreamReader(file_s, Encoding.UTF8, False) as sr:
               line = sr.ReadToEnd()
               line = line.strip() if line else line
               series_ref = __url_to_seriesref(line)
   except:
      log.debug_exc("bad cvinfo file: " + sstr(file_s))
      
   if file_s and not series_ref:
      log.debug("ignoring bad cvinfo file: ", sstr(file_s))

   return series_ref # may be None!
def SetTrafficLightsFromMatrix(selectrow, selectcolumn, green_limit, 
                               yellow_limit, Table = None, Matrix = None, 
                               image_list = None):
    """Adding Backwards compatibility support for v4.2 script.
    
    This script will update all shapes within the last column of the table, 
    rather than one at a time.
    
    """
    
    if Matrix is None:
        from globals import Matrix
    if Table is None:
        from globals import Table
    if image_list is None:
        from System.IO import Path
        _my_dir = Path.GetDirectoryName(__file__) #relative to the module file
        _image_path = _my_dir + "\\transformations\\utils\\images\\"
        image_list = list()
        image_list.append(_image_path+"\\images\\greenarrow.png")
        image_list.append(_image_path+"\\images\\greyarrow.png")
        image_list.append(_image_path+"\\images\\redarrow.png")
        
    from texts import set_image_in_table_column_based_on_limit
    set_image_in_table_column_based_on_limit(Table, Matrix, image_list, green_limit, yellow_limit) 
Exemplo n.º 4
0
def SetTrafficLightsFromMatrix(selectrow,
                               selectcolumn,
                               greenLimit,
                               yellowLimit,
                               Table=None):
    import backgrounds
    from globals import *
    from System.IO import Path
    myDir = Path.GetDirectoryName(__file__)
    greenImage = ""
    yellowImage = ""
    redImage = ""
    greenImage = myDir + "\\images\\greenarrow.png"
    yellowImage = myDir + "\\images\\greyarrow.png"
    redImage = myDir + "\\images\\redarrow.png"

    x = selectrow - 1
    y = selectcolumn - 1
    value = Matrix[x][y][0].GetNumericValue()

    imageToUse = redImage
    if (value >= greenLimit):
        imageToUse = greenImage
    elif (value >= yellowLimit):
        imageToUse = yellowImage
    try:
        backgrounds.SetBgImageAndSize(imageToUse)
    except:
        from v4_2_support import SetBgImageAndSize
        SetBgImageAndSize(imageToUse,
                          Table.Cell(selectrow + 1, selectcolumn + 1).Shape)
Exemplo n.º 5
0
    def InitializePath(self):
        searchPath = []
        currentDir = Directory.GetCurrentDirectory()
        searchPath.append(currentDir)
        filePathDir = Path.GetDirectoryName(Path.Combine(currentDir, self.fileName))
        searchPath.append(filePathDir)
        entryDir = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location)
        searchPath.append(entryDir)
        siteDir = Path.Combine(entryDir, "Lib")
        searchPath.append(siteDir)
        devStdLibDir = Path.Combine(entryDir, '../../External.LCA_RESTRICTED/Languages/IronPython/27/Lib')
        searchPath.append(devStdLibDir)
        dllsDir = Path.Combine(entryDir, "DLLs")
        if Directory.Exists(dllsDir):
            searchPath.append(dllsDir)

        self.engine.SetSearchPaths(Array[str](searchPath))
    def test_GetCsvVal(self):

        from System.IO import Path

        my_dir = Path.GetDirectoryName(__file__)  # relative to the module file
        file = my_dir + "\\transformations\\utils\\file_name.txt"
        x = v4_2_support.GetCsvVal(file, "myRow 1")
        self.assertEqual(x, ['Strongly Agree'])
        print "test_GetCSVVal = ", x
Exemplo n.º 7
0
    def run(self, Mml2vgmInfo, index):

        #設定値の読み込み
        Mml2vgmInfo.loadSetting()

        #初回のみ(設定値が無いときのみ)git.exeの場所をユーザーに問い合わせ、設定値として保存する
        gt = Mml2vgmInfo.getSettingValue("soxpath")
        if gt is None:
            gt = Mml2vgmInfo.fileSelect(
                "sox.exeを選択してください(この選択内容は設定値として保存され次回からの問い合わせはありません)")
            if not Mml2vgmInfo.confirm("sox.exeの場所は以下でよろしいですか\r\n" + gt):
                return None
            Mml2vgmInfo.setSettingValue("soxpath", gt)
            Mml2vgmInfo.saveSetting()

        #念のため
        if gt is None or gt == "":
            Mml2vgmInfo.msg("sox.exeを指定してください")
            return None

        #ファイル情報の整理
        for fnf in Mml2vgmInfo.fileNamesFull:
            ext = Path.GetExtension(fnf)
            bas = Path.GetFileNameWithoutExtension(fnf)
            wp = Path.GetDirectoryName(fnf)
            Directory.SetCurrentDirectory(wp)

            si = ScriptInfo()

            # 引数を組み立てる
            if index == 0:
                args = "--i \"" + bas + ext + "\""
            elif index == 1:
                # -b       8bit
                # -c 1     mono
                # -r 14k   rate 14KHz
                args = bas + ext + " -b 8 -r 8k -c 1 " + bas + "_8k" + ext
            elif index == 2:
                args = bas + ext + " -r 14k -e signed-integer -c 1 " + bas + "_14k" + ext
            elif index == 3:
                args = bas + ext + " -r 16k -e signed-integer -c 1 " + bas + "_16k" + ext
            elif index == 4:
                args = bas + ext + " -r 18500 -e signed-integer -c 1 " + bas + "_18500" + ext

            ret = Mml2vgmInfo.runCommand(gt, args, True)

            if ret != "":
                Mml2vgmInfo.msg(ret)
            else:
                if index != 0:
                    Mml2vgmInfo.msg("success")

        Mml2vgmInfo.refreshFolderTreeView()

        return si
Exemplo n.º 8
0
    def run(self, Mml2vgmInfo, index):

        #設定値の読み込み
        Mml2vgmInfo.loadSetting()

        #初回のみ(設定値が無いときのみ)mucom88.exeの場所をユーザーに問い合わせ、設定値として保存する
        mc = Mml2vgmInfo.getSettingValue("mucom88path")
        if mc is None:
            mc = Mml2vgmInfo.fileSelect(
                "mucom88.exeを選択してください(この選択内容は設定値として保存され次回からの問い合わせはありません)")
            if not Mml2vgmInfo.confirm("mucom88.exeの場所は以下でよろしいですか\r\n" + mc):
                return None
            Mml2vgmInfo.setSettingValue("mucom88path", mc)
            Mml2vgmInfo.saveSetting()

        #念のため
        if mc is None or mc == "":
            Mml2vgmInfo.msg("mucom88.exeを指定してください")
            return None

        #ファイル選択
        muc = Mml2vgmInfo.fileSelect("mucファイルの選択")
        if muc is None:
            return None

        #ファイル情報の整理
        #Mml2vgmInfo.msgLogWindow(muc)
        wp = Path.GetDirectoryName(muc)
        #Mml2vgmInfo.msgLogWindow(wp)
        Directory.SetCurrentDirectory(wp)

        #mucom88.exeでコンパイルを行いmubファイルを生成する
        args = "-c " + muc
        Mml2vgmInfo.runCommand(mc, args, True)

        #mubファイルが出来たかチェック(mucom88.exeはコンパイルが成功するとmucom88.mubというファイルができる)
        mm = Path.Combine(wp, "mucom88.mub")
        #Mml2vgmInfo.msgLogWindow(mm)
        if not File.Exists(mm):
            return None

        #mucom88.mubを本来のファイル名にリネーム
        mub = Path.Combine(wp, Path.GetFileNameWithoutExtension(muc) + ".mub")
        #Mml2vgmInfo.msgLogWindow(mub)
        File.Delete(mub)
        File.Move(mm, mub)

        #mucom88.exeで演奏を開始
        Mml2vgmInfo.runCommand(mc, mub, False)

        #戻り値を生成(何もしないけど念のため)
        si = ScriptInfo()
        si.responseMessage = ""

        return si
Exemplo n.º 9
0
def GetProjectFolderNameFromRevitProjectFilePath(revitProjectFilePath):
  projectFolderName = None
  # NOTE: called Path.GetDirectoryName() before expanding the path (rather than after) in
  # order to reduce the risk of hitting .NET path length limit (260 characters?)
  folderPath = ExpandedFullNetworkPath(Path.GetDirectoryName(revitProjectFilePath))
  parts = GetDirectoryParts(folderPath)
  numberOfParts = len(parts)
  if numberOfParts > (2):
    if IsProjectYearFolderName(parts[1]):
      projectFolderName = parts[2]
  return projectFolderName
Exemplo n.º 10
0
    def run(self, Mml2vgmInfo, index):

        #設定値の読み込み
        Mml2vgmInfo.loadSetting()

        #初回のみ(設定値が無いときのみ)sox.exeの場所をユーザーに問い合わせ、設定値として保存する
        gt = Mml2vgmInfo.getSettingValue("soxpath")
        if gt is None:
            gt = Mml2vgmInfo.fileSelect(
                "sox.exeを選択してください(この選択内容は設定値として保存され次回からの問い合わせはありません)")
            if not Mml2vgmInfo.confirm("sox.exeの場所は以下でよろしいですか\r\n" + gt):
                return None
            Mml2vgmInfo.setSettingValue("soxpath", gt)
            Mml2vgmInfo.saveSetting()

        #念のため
        if gt is None or gt == "":
            Mml2vgmInfo.msg("sox.exeを指定してください")
            return None

        #ファイル情報の整理
        for fnf in Mml2vgmInfo.fileNamesFull:
            ext = Path.GetExtension(fnf)
            bas = Path.GetFileNameWithoutExtension(fnf)
            wp = Path.GetDirectoryName(fnf)
            Directory.SetCurrentDirectory(wp)

            si = ScriptInfo()

            argList = [
                "--i \"{0}{1}\"",
                "\"{0}{1}\" -r 8000  -b 8 -c 1 \"{0}_8k{1}\"",
                "\"{0}{1}\" -r 14000 -b 8 -c 1 \"{0}_14k{1}\"",
                "\"{0}{1}\" -r 16000 -b 8 -c 1 \"{0}_16k{1}\"",
                "\"{0}{1}\" -r 18500 -b 8 -c 1 \"{0}_18500{1}\"",
                "\"{0}{1}\" -b 16 -r 14000 -e signed-integer -c 1 \"{0}_16b_14k{1}\"",
                "\"{0}{1}\" -b 16 -r 16000 -e signed-integer -c 1 \"{0}_16b_16k{1}\"",
                "\"{0}{1}\" -b 16 -r 18500 -e signed-integer -c 1 \"{0}_16b_18500{1}\"",
                "\"{0}{1}\" -n trim 0 1.5 noiseprof \"{0}.noise-profile\"",
                "\"{0}{1}\" \"{0}_cleaned{1}\" noisered \"{0}.noise-profile\" 0.2 "
            ]
            args = argList[index].format(bas, ext)

            ret = Mml2vgmInfo.runCommand(gt, args, True)
            if ret != "":
                Mml2vgmInfo.msg(ret)
            else:
                if index != 0:
                    Mml2vgmInfo.msg("success")

        Mml2vgmInfo.refreshFolderTreeView()

        return si
Exemplo n.º 11
0
def DumpPlainTextLogFile():
    plainTextLogFilePath = None
    logFilePath = GetLogFilePath()
    if not str.IsNullOrWhiteSpace(logFilePath):
        plainTextLogFilePath = Path.Combine(
            Path.GetDirectoryName(logFilePath),
            Path.GetFileNameWithoutExtension(logFilePath) + ".txt")
        try:
            File.WriteAllLines(plainTextLogFilePath,
                               LogFile.ReadLinesAsPlainText(logFilePath))
        except Exception, e:
            plainTextLogFilePath = None
Exemplo n.º 12
0
def GetSnapshotData(sessionId, revitFilePath, snapshotStartTime,
                    snapshotEndTime, snapshotFolderPath, revitJournalFilePath,
                    snapshotError):
    projectFolderName = path_util.GetProjectFolderNameFromRevitProjectFilePath(
        revitFilePath)
    projectModelFolderPath = Path.GetDirectoryName(revitFilePath)
    modelName = snapshot_data_util.GetRevitModelName(revitFilePath)
    modelFileLastModified = path_util.GetLastWriteTimeUtc(revitFilePath)
    modelFileSize = path_util.GetFileSize(revitFilePath)
    modelRevitVersion = revit_file_util.GetRevitFileVersion(revitFilePath)
    modelRevitVersionDetails = snapshot_data_util.GetRevitFileVersionDetails(
        revitFilePath)

    snapshotData = {
        "projectFolderName":
        projectFolderName,
        "modelFolder":
        path_util.ExpandedFullNetworkPath(projectModelFolderPath),
        "modelName":
        modelName,
        "modelFileLastModified":
        (time_util.GetTimestampObject(modelFileLastModified)
         if modelFileLastModified is not None else None),
        "modelFileSize":
        modelFileSize,
        "modelRevitVersion":
        modelRevitVersion,
        "modelRevitVersionDetails":
        modelRevitVersionDetails,
        "snapshotStartTime": (time_util.GetTimestampObject(snapshotStartTime)
                              if snapshotStartTime is not None else None),
        "snapshotEndTime": (time_util.GetTimestampObject(snapshotEndTime)
                            if snapshotEndTime is not None else None),
        "sessionId":
        sessionId,
        "snapshotFolder":
        path_util.ExpandedFullNetworkPath(snapshotFolderPath),
        "snapshotError":
        snapshotError,
        "username":
        environment.GetUserName(),
        "machineName":
        environment.GetMachineName(),
        "gatewayAddresses":
        network_util.GetGatewayAddresses(),
        "ipAddresses":
        network_util.GetIPAddresses(),
        snapshot_data_util.SNAPSHOT_DATA__REVIT_JOURNAL_FILE:
        revitJournalFilePath
    }

    return snapshotData
Exemplo n.º 13
0
def compilePackage(packageName, codeDict):
    packagePath = path_combine(testpath.temporary_dir, packageName)
    ensure_directory_present(packagePath)
    fileList = []
    for fileName, code in codeDict.iteritems():
        filePath = path_combine(packagePath, fileName)
        ensure_directory_present(Path.GetDirectoryName(filePath))
        write_to_file(filePath, code)
        fileList.append(filePath)
    dllFile = path_combine(testpath.temporary_dir, packageName + ".dll")
    clr.CompileModules(dllFile, mainModule=fileList[0], *fileList)
    delete_files(*fileList)
    clr.AddReferenceToFileAndPath(dllFile)
Exemplo n.º 14
0
    def recalculate(self, Constants=Constants, Formatting=Formatting):
        self.__reset()
        workbook = self

        # Worksheet creation
        workbook.AddWorksheet("Colored Range")
        workbook["Colored Range"].Bounds = (3, 5, 8, 15)
        workbook["Colored Range"].ShowGrid = False

        workbook.AddWorksheet("Silly Colors - No Grid")
        workbook["Silly Colors - No Grid"].ShowGrid = False

        workbook.AddWorksheet("The Silly Colors")

        # Pre-constants user code
        from System.Drawing import Image
        from System.IO import Path
        directory = Path.GetDirectoryName(__file__)
        imagePath = Path.Combine(directory, '3d-space.jpg')
        image = Image.FromFile(imagePath)
        workbook.AddImageWorksheet("Gnuplot Image", image)

        workbook.Populate(Constants, Formatting)

        # Pre-formulae user code

        # Formula code

        # Post-formulae user code
        from random import random

        def RandomColor():
            return Color.FromArgb(random() * 256,
                                  random() * 256,
                                  random() * 256)

        def FillWithSillyColors(sheet):
            for x in range(1, 10):
                for y in range(1, 6):
                    cellLoc = (x, y)
                    cell = sheet.Cells[cellLoc]
                    cell.BackColor = RandomColor()
                    cell.Value = cellLoc
                    cell.Bold = True
                    print cellLoc,
            print

        sheet1 = workbook['The Silly Colors']
        sheet2 = workbook['Silly Colors - No Grid']
        FillWithSillyColors(sheet1)
        FillWithSillyColors(sheet2)
Exemplo n.º 15
0
def get_code(path, page, index):
    directory = Path.GetDirectoryName(path)
    code_directory = Path.Combine(directory, 'code%s' % page)
    code_file = Path.Combine(code_directory, 'example%s.txt' % index)
    if code_file in _code_cache:
        return _code_cache[code_file]

    handle = open(code_file)
    code = handle.read().decode('utf-8')
    code = code.replace('\r\n', '\n').replace('\r', '\n')
    code_lines = code.splitlines()
    handle.close()
    _code_cache[code_file] = code_lines
    return code_lines
Exemplo n.º 16
0
def ExecuteDynamoScript(uiapp, dynamoScriptFilePath, showUI=False):
    externalCommandResult = None
    # NOTE: The temporary copy of the Dynamo script file is created in same folder as the original so
    # that any relative paths in the script won't break.
    tempDynamoScriptFilePath = Path.Combine(
        Path.GetDirectoryName(dynamoScriptFilePath), Path.GetRandomFileName())
    File.Copy(dynamoScriptFilePath, tempDynamoScriptFilePath)
    try:
        SetDynamoScriptRunType(tempDynamoScriptFilePath,
                               DYNAMO_RUNTYPE_AUTOMATIC)
        externalCommandResult = ExecuteDynamoScriptInternal(
            uiapp, tempDynamoScriptFilePath, showUI)
    finally:
        File.Delete(tempDynamoScriptFilePath)
    return externalCommandResult
Exemplo n.º 17
0
 def __init__(self):
     self.executablePath = __file__
     if self.executablePath is None:
         self.executablePath = Application.ExecutablePath
     self.executableDirectory = Path.GetDirectoryName(self.executablePath)
     self.InitializeComponent()
     self.controller = SimpleICMController(self)
     self.go_button.Click += self.controller.handle_go
     for stack in self.stacks:
         stack.GotFocus += self.controller.cache_value
         stack.LostFocus += self.controller.validate_number
     for payout in self.payouts:
         payout.GotFocus += self.controller.cache_value
         payout.LostFocus += self.controller.validate_number
     self._WebBrowser1.Navigating += self.controller.handle_navigate
Exemplo n.º 18
0
    def run(self, Mml2vgmInfo, index):

        #設定値の読み込み
        Mml2vgmInfo.loadSetting()

        #初回のみ(設定値が無いときのみ)git.exeの場所をユーザーに問い合わせ、設定値として保存する
        gt = Mml2vgmInfo.getSettingValue("gitpath")
        if gt is None:
            gt = Mml2vgmInfo.fileSelect(
                "git.exeを選択してください(この選択内容は設定値として保存され次回からの問い合わせはありません)")
            if not Mml2vgmInfo.confirm("git.exeの場所は以下でよろしいですか\r\n" + gt):
                return None
            Mml2vgmInfo.setSettingValue("gitpath", gt)
            Mml2vgmInfo.saveSetting()

        #念のため
        if gt is None or gt == "":
            Mml2vgmInfo.msg("git.exeを指定してください")
            return None

        si = ScriptInfo()

        commitMsg = ""
        if index == 1:
            #git コミット
            commitMsg = Mml2vgmInfo.inputBox("コミット時のコメントを入力してください")
            if commitMsg == "":
                return si

        #ファイル情報の整理
        for fnf in Mml2vgmInfo.fileNamesFull:
            wp = Path.GetDirectoryName(fnf)
            Directory.SetCurrentDirectory(wp)

            if index == 0:
                #git ステージング
                args = "add " + fnf
                ret = Mml2vgmInfo.runCommand(gt, args, True)
                if ret != "":
                    Mml2vgmInfo.msg(ret)
            else:
                #git コミット
                args = "commit -m\"" + commitMsg + "\""
                ret = Mml2vgmInfo.runCommand(gt, args, True)
                if ret != "":
                    Mml2vgmInfo.msg(ret)

        return si
Exemplo n.º 19
0
def _check_magic_file(path_s):
    ''' ComicVine implementation of the identically named method in the db.py '''
    series_key_s = None
    file_s = None
    try:
        # 1. get the directory to search for a cvinfo file in, or None
        dir_s = path_s if path_s and Directory.Exists(path_s) else \
           Path.GetDirectoryName(path_s) if path_s else None
        dir_s = dir_s if dir_s and Directory.Exists(dir_s) else None

        if dir_s:
            # 2. search in that directory for a properly named cvinfo file
            #    note that Windows filenames are not case sensitive.
            for f in [dir_s + "\\" + x for x in ["cvinfo.txt", "cvinfo"]]:
                if File.Exists(f):
                    file_s = f

            # 3. if we found a file, read it's contents in, and parse the
            #    comicvine series id out of it, if possible.
            if file_s:
                with StreamReader(file_s, Encoding.UTF8, False) as sr:
                    line = sr.ReadToEnd()
                    line = line.strip() if line else line
                    match = re.match(r"^.*?\b(49|4050)-(\d{2,})\b.*$", line)
                    line = match.group(2) if match else line
                    if utils.is_number(line):
                        series_key_s = utils.sstr(int(line))
    except:
        log.debug_exc("bad cvinfo file: " + sstr(file_s))

    # 4. did we find a series key?  if so, query comicvine to build a proper
    #    SeriesRef object for that series key.
    series_ref = None
    if series_key_s:
        try:
            dom = cvconnection._query_series_details_dom(
                __api_key, utils.sstr(series_key_s))
            num_results_n = int(dom.number_of_total_results)
            series_ref =\
               __volume_to_seriesref(dom.results) if num_results_n==1 else None
        except:
            log.debug_exc("error getting SeriesRef for: " + sstr(series_key_s))

    if file_s and not series_ref:
        log.debug("ignoring bad cvinfo file: ", sstr(file_s))
    return series_ref  # may be None!
Exemplo n.º 20
0
def set_image_based_on_limit(green_limit,
                             yellow_limit,
                             file_name_list,
                             Matrix=None):
    r"""Select which image to display based upon limits, for example a traffic 
    light system or up and down arrows.
    
    This should be run per text shape to set the background image and size 
    based on the image selected. 
    
    Example:
    
    | file_name_list = list()
    | file_name_list.append("traffic-light-green.jpg")
    | file_name_list.append("traffic-light-yellow.jpg")
    | file_name_list.append("traffic-light-red.jpg")
    | 
    | texts.set_image_based_on_limit(0.3, 0.2, file_name_list, Matrix)
    
    """

    if Matrix is None:
        from globals import Matrix

    _green_image = file_name_list[0]
    _yellow_image = file_name_list[1]
    _red_image = file_name_list[2]

    _value = Matrix[0][0][0].GetNumericValue()
    _image_to_use = _red_image
    if (_value >= green_limit):
        _image_to_use = _green_image
    elif (_value >= yellow_limit):
        _image_to_use = _yellow_image
    try:
        set_bg_image_and_size(_image_to_use)
    except:
        # cannot find image, try standard utils\images location
        try:
            from System.IO import Path
            _my_dir = Path.GetDirectoryName(
                __file__)  #relative to the module file
            _image_path = _my_dir + "\\transformations\\utils\\images\\"
            set_bg_image_and_size(_image_path + _image_to_use)
        except:
            raise
Exemplo n.º 21
0
        def onValidate():
            fs = None

            try:
                fs = FileStream(fileName, FileMode.Open, FileAccess.Read,
                                FileShare.Read)

                doc = XmlDocument()
                doc.Load(fs)

                if doc.DocumentElement.Name.Equals("script"):
                    for childNode1 in doc.DocumentElement.ChildNodes:
                        if childNode1.Name.Equals("character"):
                            hasName = False

                            for xmlAttribute in childNode1.Attributes:
                                if xmlAttribute.Name.Equals("name"):
                                    hasName = True

                            if not hasName:
                                if CultureInfo.CurrentCulture.Equals(
                                        CultureInfo.GetCultureInfo("ja-JP")):
                                    errorList.Add("characterタグにname属性がありません。")
                                else:
                                    errorList.Add(
                                        "Could not find name attribute in character tag."
                                    )

                            for childNode2 in childNode1.ChildNodes:
                                if childNode2.Name.Equals("sequence"):
                                    parseSequence(
                                        childNode2,
                                        Path.GetDirectoryName(fileName),
                                        warningList, errorList)

                else:
                    if CultureInfo.CurrentCulture.Equals(
                            CultureInfo.GetCultureInfo("ja-JP")):
                        errorList.Add("scriptタグがありません。")
                    else:
                        errorList.Add("Could not find script tag.")

            except Exception, e:
                errorList.Add(e.clsException.Message)
def SetTrafficLights(greenLimit, yellowLimit, file_name_list = None, Matrix = None):
    """Adding Backwards compatibility support for v4.2 script.
    
    NOTE: This script will add the shapes within the chart shape, rather than as
    independent shapes on the slide.
    
    """
    
    from texts import set_image_based_on_limit
    from System.IO import Path
    
    my_dir = Path.GetDirectoryName(__file__) #relative to the module file
    
    image_path = my_dir + "\\transformations\\utils\\images"
    
    if file_name_list is None:
        file_name_list = [image_path + "\\traffic-light-green.jpg", image_path + "\\traffic-light-yellow.jpg", image_path + "\\traffic-light-red.jpg"]
            
    set_image_based_on_limit(greenLimit, yellowLimit, file_name_list)
Exemplo n.º 23
0
def GetFileList():
    dlgFile = OpenFileDialog()
    dlgFile.Title = "Select files to change"
    dlgFile.Filter = "Wave files (*.wav)|*.wav"
    dlgFile.InitialDirectory = Settings.Instance().DataDir
    dlgFile.CheckFileExists = True
    dlgFile.CheckPathExists = True
    dlgFile.AddExtension = True
    dlgFile.AutoUpgradeEnabled = True
    dlgFile.DefaultExt = "wav"
    dlgFile.Multiselect = True
    dlgFile.RestoreDirectory = True
    dlgFile.SupportMultiDottedExtensions = True
    dlgFile.FileName = ""
    result = dlgFile.ShowDialog()
    if (result == DialogResult.OK):
        Settings.Instance().DataDir = Path.GetDirectoryName(dlgFile.FileName)
        return dlgFile.FileNames
    else:
        return
Exemplo n.º 24
0
    def __unique_series_s(self):
        '''
      Gets the unique series name for this ComicBook.   This is a special 
      string that will be identical for (and only for) any comic books that 
      "appear" to be from the same series.
      
      The unique series name is meant to be used internally (i.e. the key for
      a map, or for grouping ComicBooks), not for displaying to users.
      
      This value is NOT the same as the series_s property.
      '''
        bd = self.__bookdata
        sname = '' if not bd.series_s else bd.series_s
        if sname and bd.format_s:
            sname += bd.format_s
        sname = re.sub('\W+', '', sname).lower()

        svolume = ''
        if sname:
            if bd.volume_year_n and bd.volume_year_n > 0:
                svolume = sstr(bd.volume_year_n)
        else:
            # if we can't find a name at all (very weird), fall back to the
            # memory ID, which is be unique and thus ensures that this
            # comic doesn't get lumped in to the same series choice as any
            # other unnamed comics!
            sname = "uniqueid-" + utils.sstr(id(self))

        # generate a hash to add onto the string.  the hash should be identical
        # for all comics that belong to the same series, and different otherwise.
        # not how by default, comics that are in different directories are always
        # considered to belong to different series.
        location = Path.GetDirectoryName(bd.path_s) if bd.path_s else None
        location = location if location else ''
        hash = svolume if self.__scraper.config.ignore_folders_b \
           else location + svolume
        if hash:
            with MD5.Create() as md5:
                bytes = md5.ComputeHash(Encoding.UTF8.GetBytes(hash))
                hash = ''.join(["%02X" % x for x in bytes[:5]]).strip()
        return sname + hash
Exemplo n.º 25
0
def set_image_in_table_column_based_on_limit(Table, Matrix, image_list,
                                             green_limit, yellow_limit):
    r"""Within a Table, select which image to display in the last column, based 
    upon limits, for example a traffic light system or up and down arrows.
    
    This should be run per Table, and the background of each cell in the last
    column will be updated to set the background image and size  based on the
    image selected.
    
    Example:
    
    | image_list= ["greenarrow.jpg","greyarrow.jpg","redarrow.jpg"]
    | texts.set_image_in_table_column_based_on_limit(Table, Matrix, image_list, 0.2, 0.1)
    
    """

    _green_image = image_list[0]  # "\\greenarrow.png"
    _yellow_image = image_list[1]  # "\\greyarrow.png"
    _red_image = image_list[2]  # "\\redarrow.png"

    for row in Matrix:
        col = Matrix.TopAxis.DataMembers.Count
        shape = Table.Cell(row.Member.DataIndex + 2, col + 1).Shape
        _value = row[col - 1][0].GetNumericValue()

        _image_to_use = _red_image
        if (_value >= green_limit):
            _image_to_use = _green_image
        elif (_value >= yellow_limit):
            _image_to_use = _yellow_image
        try:
            set_bg_image_and_size(_image_to_use, Shape)
        except:
            try:
                from System.IO import Path
                _my_dir = Path.GetDirectoryName(
                    __file__)  #relative to the module file
                _image_path = _my_dir + "\\transformations\\utils\\images\\"
                set_bg_image_and_size(_image_path + _image_to_use, shape)
            except:
                raise
Exemplo n.º 26
0
def SetTrafficLights(greenLimit, yellowLimit, Shape=None):
    import backgrounds
    reload(backgrounds)

    from globals import *
    from System.IO import Path
    myDir = Path.GetDirectoryName(__file__)
    greenImage = ""
    yellowImage = ""
    redImage = ""
    greenImage = myDir + "\\images\\traffic-light-green.jpg"
    yellowImage = myDir + "\\images\\traffic-light-yellow.jpg"
    redImage = myDir + "\\images\\traffic-light-red.jpg"

    value = Matrix[0][0][0].GetNumericValue()
    imageToUse = redImage
    if (value >= greenLimit):
        imageToUse = greenImage
    elif (value >= yellowLimit):
        imageToUse = yellowImage
    backgrounds.SetBgImageAndSize(imageToUse, Shape)
Exemplo n.º 27
0
 def __init__(self, fileName):
     scriptEnv = Python.CreateRuntime()
     self.fileName = fileName
     self.engine = scriptEnv.GetEngine("python")        
     self.context = HostingHelpers.GetLanguageContext(self.engine) 
     scriptEnv.LoadAssembly(Type.GetType("System.String").Assembly) #mscorlib.dll
     scriptEnv.LoadAssembly(UriBuilder().GetType().Assembly)  #System.dll
             
     self.InitializePath()
     
     executable = Assembly.GetEntryAssembly().Location
     prefix = Path.GetDirectoryName(executable)
     
     self.context.SystemState.executable = executable
     self.context.SystemState.exec_prefix = self.context.SystemState.prefix = prefix
     
     import imp
     mod = imp.new_module('__main__')
     mod.__file__ = fileName
     mod.__builtins__ = sys.modules['__builtin__']
     self.context.SystemState.modules['__main__'] = mod
     self.mainScope = scriptEnv.CreateScope(mod.__dict__)
Exemplo n.º 28
0
def LoadSpreadsheet(path):
    """
    Load and execute a spreadsheet exported as Python.
     
    This function takes a path to the Python file and
    returns a workbook instance.
    """
    import sys
    spreadsheetDirectory = Path.GetDirectoryName(path)
    sys.path.append(spreadsheetDirectory)

    try:
        context = {
            '__name__': '__main__',
            '__file__': path,
            '__builtins__': __builtins__
        }
        h = open(path)
        code = h.read() + '\n'
        h.close()
        exec code in context
        Spreadsheet = context.get('Spreadsheet')
        if Spreadsheet is not None:
            # Spreadsheet was exported as a class
            workbook = Spreadsheet()
            workbook.recalculate()
        else:
            # Spreadsheet exported as non-class
            workbook = context.get('workbook')
            if workbook is None:
                # Not a spreadsheet at all
                raise NoWorkbook(
                    "No workbook defined in this code. Are you sure it is a Resolver spreadsheet?"
                )

        return workbook
    finally:
        sys.path.remove(spreadsheetDirectory)
Exemplo n.º 29
0
def CreateDirectoryForFilePath(filePath):
    directoryInfo = CreateDirectory(Path.GetDirectoryName(filePath))
    return directoryInfo
Exemplo n.º 30
0
def getDirectory(p):
	if File.Exists(p):
		return Path.GetDirectoryName(p)
	if Directory.Exists:
		return p
	return