コード例 #1
0
 def import_block(self, path_to_file, path_tia):
     print(path_tia)
     if os.path.exists(path_to_file):
         if path_tia:
             path_list = list(filter(None, path_tia.split('/')))
             block_group = self.get_block_group(
                 self.software_container.Software.BlockGroup.Groups,
                 path_list)
             return block_group.Blocks.Import(FileInfo(path_to_file),
                                              tia.ImportOptions.Override)
         else:
             return self.software_container.Software.BlockGroup.Blocks.Import(
                 FileInfo(path_to_file), tia.ImportOptions.Override)
     else:
         return 'path to imported file does not exist'
コード例 #2
0
    def __init__(self, mode):
        f = FileStream(Path.Combine(SCRIPTDIRECTORY, "DuplicateForm.xaml"),
                       FileMode.Open)
        self.win = XamlReader.Load(XmlReader.Create(f))
        f.Close()

        self._action = None

        self.RenameText = "The file you are moving will be renamed: "

        #Load the images and icon
        path = FileInfo(__file__).DirectoryName
        arrow = BitmapImage()
        arrow.BeginInit()

        arrow.UriSource = Uri(Path.Combine(SCRIPTDIRECTORY, "arrow.png"),
                              UriKind.Absolute)
        arrow.EndInit()
        self.win.FindName("Arrow1").Source = arrow
        self.win.FindName("Arrow2").Source = arrow
        self.win.FindName("Arrow3").Source = arrow

        icon = BitmapImage()
        icon.BeginInit()
        icon.UriSource = Uri(ICON, UriKind.Absolute)
        icon.EndInit()

        self.win.Icon = icon

        self.win.FindName("CancelButton").Click += self.CancelClick
        self.win.FindName("Cancel").Click += self.CancelClick
        self.win.FindName("ReplaceButton").Click += self.ReplaceClick
        self.win.FindName("RenameButton").Click += self.RenameClick

        self.win.Closing += self.FormClosing

        #The the correct text based on what mode we are in
        #Mode is set by default so only change if in Copy or Simulation mode
        if mode == Mode.Copy:
            self.win.FindName("MoveHeader").Content = "Copy and Replace"
            self.win.FindName(
                "MoveText"
            ).Content = "Replace the file in the destination folder with the file you are copying:"

            self.win.FindName("DontMoveHeader").Content = "Don't Copy"

            self.win.FindName(
                "RenameHeader").Content = "Copy, but keep both files"
            self.RenameText = "The file you are copying will be renamed: "
            self.win.FindName(
                "RenameText"
            ).Text = "The file you are copying will be renamed: "

        if mode == Mode.Simulate:
            self.win.FindName(
                "Subtitle"
            ).Content = "Click the file you want to keep (simulated, no files will be deleted or moved)"
コード例 #3
0
 def export_block(self, name):
     block_group = self.software_container.Software.BlockGroup
     block = self.get_block_by_name(block_group, name)
     if block:
         self.logger.info('Block ' + name + ' was exported')
         block.Export(
             FileInfo('Z:\\Projects\\Siemens\\BlockGenerator\\export\\' +
                      name + '.xml'), tia.ExportOptions.WithDefaults)
     else:
         self.logger.error('Block ' + name + ' was not found')
def SaveCoverAsImage(books):
	for book in books:
		bookFileInfo = FileInfo(book.FilePath)
		bookNameWithoutExt = Path.GetFileNameWithoutExtension(book.FilePath);
		dirName = bookFileInfo.DirectoryName
		
		destinationFilePath = dirName + "\\" + bookNameWithoutExt + '.jpg'
		
		pageImage = ComicRack.App.GetComicPage(book, book.FrontCoverPageIndex)
		pageImage.Save(destinationFilePath, ImageFormat.Jpeg)
コード例 #5
0
ファイル: exportIFC.py プロジェクト: karthi1015/bim
def checkInput(filePath):
    err = 0
    if not ModelPathUtils.IsValidUserVisibleFullServerPath(filePath):
        err = 1
    if err:
        err = 0
        fi = FileInfo(filePath)
        if not fi.Exists or fi.Name.Split('.')[1].ToLower() != "rvt":
            err = 2
    return (err)
コード例 #6
0
    def setUp(self):
        temp_dir = DirectoryInfo(Environment.GetEnvironmentVariable("TEMP"))
        #       myDocuments = DirectoryInfo(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments))
        self.temp_dir = temp_dir.CreateSubdirectory('tempDir')
        self.temp_dir_path = self.temp_dir.ToString()

        self.file1 = FileInfo(self.temp_dir_path + '\\file1.txt')
        self.file2 = FileInfo(self.temp_dir_path + '\\file2.txt')
        self.file3 = FileInfo(self.temp_dir_path + '\\file3.txt')

        sw = self.file1.CreateText()
        sw.WriteLine("Hello1")
        sw.Close()

        sw = self.file2.CreateText()
        sw.WriteLine("Hello2")
        sw.Close()

        sw = self.file3.CreateText()
        sw.WriteLine("Hello3")
        sw.Close()

        today = DateTime.Now
        one_day_old = today.AddDays(-1).ToString("yyyy.MM.dd")
        two_days_old = today.AddDays(-2).ToString("yyyy.MM.dd")
        self.file1.CreationTime = DateTime.Parse(today.ToString("yyyy.MM.dd"))
        self.file2.CreationTime = DateTime.Parse(one_day_old)
        self.file3.CreationTime = DateTime.Parse(two_days_old)

        print "\r myDocuments temp path = [%s]" % self.temp_dir_path
        print "CreationTime file1 = [%s]" % self.file1.CreationTime
        print "CreationTime file2 = [%s]" % self.file2.CreationTime
        print "CreationTime file3 = [%s]" % self.file3.CreationTime
コード例 #7
0
def __PrintFileInformation(fullpath):
    "Displays a file's information."
    fi = FileInfo(fullpath)
    info = "Full Path:  " + fullpath + "\n"
    info += "File Name:  " + Path.GetFileName(fullpath) + "\n"
    info += "File Attributes:  " + __FileAttributes(fullpath) + "\n"
    info += "Date Created:  " + File.GetCreationTime(
        fullpath).ToString() + "\n"
    info += "Last Date Accessed:  " + File.GetLastAccessTime(
        fullpath).ToString() + "\n"
    info += "Last Date Modified:  " + File.GetLastWriteTime(
        fullpath).ToString() + "\n"
    info += "File Size (Bytes):  " + fi.Length.ToString() + "\n"
    rs.MessageBox(info, 0, "Current Model Information")
コード例 #8
0
    def CheckPathLength(self, sender, e):

        try:

            f = FileInfo(self._Path.Text)

        except PathTooLongException, ex:

            self._errorProvider.SetError(
                self._Path,
                "The entire path has to be less then 260 characters. Current path size is: "
                + str(self._Path.Text.Length))
            self._ErrorLabel.Text = "The entire path has to be less then 260 characters. Current path size is: " + str(
                self._Path.Text.Length)
            self.DialogResult = DialogResult.None
            return
コード例 #9
0
 def dosave():
    dialog = SaveFileDialog()
    dialog.FileName="cvs-debug-log-" + \
       DateTime.Today.ToString("yyyy-MM-dd") + ".txt"
    dialog.Title = i18n.get("LogSaveTitle")
    dialog.Filter = i18n.get("LogSaveFilter")+'|*.*'
 
    try:
       if dialog.ShowDialog(__app_window) == DialogResult.OK:
          if dialog.FileName != None:
             debug("wrote debug logfile: ", FileInfo(dialog.FileName).Name)
             __logger.save(dialog.FileName)
             if show_error_message:
                MessageBox.Show(__app_window, i18n.get("LogSavedText"),
                   i18n.get("LogSavedTitle"), MessageBoxButtons.OK, 
                   MessageBoxIcon.Information )
    except:
       debug_exc()
       MessageBox.Show( __app_window, i18n.get("LogSaveFailedText") )
コード例 #10
0
def getFilesYoungerThan(dir, younger_than=0):
    if exists(dir):
        files = Directory.GetFiles(dir)
        date_to_check = DateTime.Parse(
            DateTime.Now.AddDays(-younger_than).ToString("yyyy.MM.dd"))
        files_of_age = []
        for file in files:
            file = FileInfo(file)
            print file
            result = DateTime.Compare(file.CreationTime, date_to_check)

            if result < 0:
                relationship = "is earlier than %s" % date_to_check
            elif result == 0:
                relationship = "is the same time as %s" % date_to_check
                files_of_age.append(file)
            else:
                relationship = "is later than %s" % date_to_check
                files_of_age.append(file)
            print relationship
        return files_of_age
コード例 #11
0
ファイル: env_indigo.py プロジェクト: uleming/Indigo
def file_exists(path):
    if sys.platform == 'cli':
        return FileInfo(path).Exists
    else:
        return os.path.exists(path)
コード例 #12
0
ファイル: _ipysupport.py プロジェクト: MiniJavaInScala/jFirm
 def getmtime(self, filename):
     info = FileInfo(filename)
     return int((info.LastAccessTimeUtc - epoch).TotalSeconds)
コード例 #13
0
ファイル: Create_Z_stack.py プロジェクト: yoser-alrawi/OAD
if (Directory.Exists(newstrFolder)== False):
    strMessage = 'Path: ' + newstrFolder + ' does not exist!\nRestart macro and select an existing path!'
    sys.exit(strMessage)

imgSeries = ZenImage()

t = 0
c = 0
z = 0

files = Directory.GetFiles(strFolder, "*czi")

for z in range(0, files.Length):
    #--- Get the next image file ---
    file = files[z]
    fileInfo = FileInfo(file)
    strFilenameFullPath = strFolder + "\\" + fileInfo.Name
    img = Zen.Application.LoadImage(strFilenameFullPath, False)
    # separate channels
    for c in range(0, img.Bounds.SizeC):
        channelImage = img.CreateSubImage('C(' + str(c+1) + ')')
        #--- Add image to series ---
        imgSeries.AddSubImage(channelImage, t, c, z)
    #--- Clean up ---
    img.Close()

#--- Show and save the resulting series image ---
Zen.Application.Documents.Add(imgSeries)
imgSeriesNameWE = fileInfo.Name.Substring(0,fileInfo.Name.Length-6)
newimgSeriesName = imgSeriesNameWE + '_ZStack.czi'
imgSeriefullName = Path.Combine(newstrFolder, newimgSeriesName) 
コード例 #14
0
ファイル: Analyze.py プロジェクト: maelstrompli/inVtero.net
def ScanDump(MemoryDump, copts):
    MemoryDumpSize = FileInfo(MemoryDump).Length
    copts.FileName = MemoryDump
    # Check StopWatch
    runTime = Stopwatch.StartNew()
    # since we are not ignoring SaveData, this just get's our state from
    # the underlying protobuf, pretty fast
    vtero = Scan.Scanit(copts)
    proc_arr = vtero.Processes.ToArray()
    low_proc = proc_arr[0]
    for proc in proc_arr:
        if proc.CR3Value < low_proc.CR3Value:
            low_proc = proc
    proc = low_proc
    print "Assumed Kernel Proc: " + proc.ToString()
    vtero.KernelProc = proc
    #vtero.CheckpointSaveState()
    proc.MemAccess = Mem(vtero.MemAccess)
    #swModScan = Stopwatch.StartNew()
    # by default this will scan for kernel symbols
    if vtero.KVS is None:
        kvs = proc.ScanAndLoadModules()
        vtero.KVS = kvs
        vtero.CheckpointSaveState()
    else:
        proc.LoadSymbols()
    #apply some setup
    kMinorVer = proc.GetSymValueLong("NtBuildNumber") & 0xffff
    Console.ForegroundColor = ConsoleColor.Cyan
    print "kernel build: " + kMinorVer.ToString()
    # Use dynamic typing to walk EPROCES
    logicalList = vtero.WalkProcList(proc)
    print "Physical Proc Count: " + proc_arr.Count.ToString()
    #for pproc in proc_arr:
    #    print pproc
    if logicalList is not None:
        print "Logical Proc Count: " + logicalList.Count.ToString()
        for proc in logicalList:
            # This is due to a structure member name change pre win 8
            if proc.Dictionary.ContainsKey("VadRoot.BalancedRoot.RightChild"):
                proc.VadRoot = proc.Dictionary[
                    "VadRoot.BalancedRoot.RightChild"]
            print proc.ImagePath + " : " + proc.Dictionary[
                "Pcb.DirectoryTableBase"].ToString(
                    "X") + " : " + proc.VadRoot.ToString(
                        "X") + " : " + proc.UniqueProcessId.ToString("X")
        Console.ForegroundColor = ConsoleColor.Green
        print "checking that all logical processes exist in the physical list."
        # Miss list mostly bad for yellow printing
        for proc in logicalList:
            found = False
            for hwproc in proc_arr:
                if proc.Dictionary[
                        "Pcb.DirectoryTableBase"] == hwproc.CR3Value:
                    found = True
                    #print "Found logical proc[" + hwproc.CR3Value.ToString("X") + "] in physical array"
            if found == False:
                Console.ForegroundColor = ConsoleColor.Yellow
                if proc.VadRoot == 0:
                    Console.ForegroundColor = ConsoleColor.Green
                    print "An expected, ",
                print "Logical miss for " + proc.ImagePath + " : " + proc.Dictionary[
                    "Pcb.DirectoryTableBase"].ToString(
                        "X") + " : " + proc.VadRoot.ToString(
                            "X") + " : " + proc.UniqueProcessId.ToString("X")
        print "Checking that all physical processes exist in the logical list"
        for hwproc in proc_arr:
            found = False
            for proc in logicalList:
                if proc.Dictionary[
                        "Pcb.DirectoryTableBase"] == hwproc.CR3Value:
                    found = True
                    #print "Found physical proc[" + proc.Dictionary["Pcb.DirectoryTableBase"].ToString("X") + "] in logical array"
            if found == False:
                Console.ForegroundColor = ConsoleColor.Yellow
                hwmiss.append(hwproc)
                print "physical miss for " + hwproc.ToString()
    Console.ForegroundColor = ConsoleColor.White
    print "PART RUNTIME: " + runTime.Elapsed.ToString(
    ) + " (seconds), INPUT DUMP SIZE: " + MemoryDumpSize.ToString(
        "N") + " bytes."
    print "SPEED: " + ((MemoryDumpSize / 1024) /
                       ((runTime.ElapsedMilliseconds / 1000) + 1)).ToString(
                           "N0") + " KB / second  (all phases aggregate time)"
    return vtero
コード例 #15
0
# some variables for global use
import clr
import System
from System.IO import Path, FileInfo
import iniReadWrite
from System import Array
from System import StringSplitOptions
from iniReadWrite import *
from System.Collections.Generic import Dictionary
#clr.AddReference("ComicRack.Engine")
from cYo.Projects.ComicRack.Engine import MangaYesNo, YesNo

############Set Paths##############
FOLDER = FileInfo(
    __file__).DirectoryName + Path.DirectorySeparatorChar.ToString()
IMGFOLDER = FOLDER + 'images' + Path.DirectorySeparatorChar.ToString()
DATFILE = Path.Combine(
    FOLDER,
    'dataMan.dat')  #can load 1.24 text files or 2.3.1 xml files saves as xml
SAMPLEFILE = Path.Combine(FOLDER, 'dataManSample.dat')
INIFILE = Path.Combine(FOLDER, 'dataMan.ini')
USERINI = Path.Combine(FOLDER, 'user.ini')
BAKFILE = Path.Combine(FOLDER, 'dataMan.bak')
ERRFILE = Path.Combine(FOLDER, 'dataMan.err')
TMPFILE = Path.Combine(FOLDER, 'dataMan.tmp')
LOGFILE = Path.Combine(FOLDER, 'dataMan.log')
CHKFILE = Path.Combine(
    FOLDER, 'dataMan.chk')  # will be created once the configuration is saved
GUIEXE = Path.Combine(FOLDER, 'crdmgui.exe')

##############End Set Paths##############
コード例 #16
0
ファイル: site.py プロジェクト: swdipper/SidEDMSuite
#####################################################################################
#
#  Copyright (c) Microsoft Corporation. All rights reserved.
#
#  This source code is subject to terms and conditions of the Shared Source License
#  for IronPython. A copy of the license can be found in the License.html file
#  at the root of this distribution. If you can not locate the Shared Source License
#  for IronPython, please send an email to [email protected].
#  By using this source code in any fashion, you are agreeing to be bound by
#  the terms of the Shared Source License for IronPython.
#
#  You must not remove this notice, or any other, from this software.
#
######################################################################################

import sys
import clr
from System.IO import Path, Directory, FileInfo

dir = Path.Combine(sys.prefix, 'DLLs')
if Directory.Exists(dir):
    sys.path.append(dir)
    files = Directory.GetFiles(dir)
    for file in files:
        if file.lower().endswith('.dll'):
            try:
                clr.AddReference(FileInfo(file).Name)
            except:
                pass
コード例 #17
0
MemoryDump = "d:\\temp\\2012R2.debug.MEMORY.DMP"
#MemoryDump = "d:\\temp\\server2016.xendump"
import clr, sys

clr.AddReferenceToFileAndPath("inVtero.net.dll")
clr.AddReferenceToFileAndPath("inVtero.net.ConsoleUtils.dll")

from inVtero.net import *
from inVtero.net.ConsoleUtils import *
from ConsoleUtils import *
from System.IO import Directory, File, FileInfo, Path
from System import Environment, String, Console, ConsoleColor
from System import Text
from System.Diagnostics import Stopwatch

MemoryDumpSize = FileInfo(MemoryDump).Length

# This code fragment can be removed but it's a reminder you need symbols working
sympath = Environment.GetEnvironmentVariable("_NT_SYMBOL_PATH")
if String.IsNullOrWhiteSpace(sympath):
    sympath = "SRV*http://msdl.microsoft.com/download/symbols"

# Basic option handling
# This script can be pretty chatty to stdout
#
copts = ConfigOptions()
copts.IgnoreSaveData = False
copts.FileName = MemoryDump
copts.VersionsToEnable = PTType.GENERIC
# To get some additional output
copts.VerboseOutput = True
コード例 #18
0
# some variables for global use

import System
from System.IO import Path, FileInfo

FOLDER = FileInfo(__file__).DirectoryName + "\\"
DATFILE = Path.Combine(FOLDER, 'dataMan.dat')
SAMPLEFILE = Path.Combine(FOLDER, 'dataManSample.dat')
INIFILE = Path.Combine(FOLDER, 'dataMan.ini')
USERINI = Path.Combine(FOLDER, 'user.ini')
BAKFILE = Path.Combine(FOLDER, 'dataMan.bak')
ERRFILE = Path.Combine(FOLDER, 'dataMan.err')
TMPFILE = Path.Combine(FOLDER, 'dataMan.tmp')
LOGFILE = Path.Combine(FOLDER, 'dataMan.log')
CHKFILE = Path.Combine(
    FOLDER, 'dataMan.chk')  # will be created once the configuration is saved
GUIEXE = Path.Combine(FOLDER, 'crdmcgui.exe')

ICON_SMALL = Path.Combine(FOLDER, 'dataMan16.ico')
ICON = Path.Combine(FOLDER, 'dataMan.ico')
IMAGE = Path.Combine(FOLDER, 'dataMan.png')
IMAGESEARCH = Path.Combine(FOLDER, 'search.png')
IMAGEADD = Path.Combine(FOLDER, 'yes.png')
IMAGEAPPLY = Path.Combine(FOLDER, 'Apply.png')
IMAGETRASH = Path.Combine(FOLDER, 'Trash.png')
IMAGEDELETE_SMALL = Path.Combine(FOLDER, 'erase.png')
IMAGEDOWN = Path.Combine(FOLDER, 'down.png')
IMAGELIGHTNING = Path.Combine(FOLDER, 'lightning.png')
IMAGETEXT = Path.Combine(FOLDER, 'text.png')
DONATE = 'https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=UQ7JZY366R85S'
WIKI = 'http://code.google.com/p/cr-data-manager/'
コード例 #19
0
"""

import clr

import System

clr.AddReference("System.Xml")
clr.AddReference("System.Windows.Forms")

from System.Xml import XmlWriter, XmlWriterSettings

from System.Windows.Forms import MessageBox, MessageBoxButtons, MessageBoxIcon

from System.IO import FileInfo, Path

SCIRPT_DIRECTORY = FileInfo(__file__).DirectoryName

REGEX_FILE = Path.Combine(SCIRPT_DIRECTORY, "regex.dat")

ICON = Path.Combine(SCIRPT_DIRECTORY, "webcomichelper.ico")

HEADER_IMAGE = Path.Combine(SCIRPT_DIRECTORY, "Webcomic Helper.png")


class WebComicHelperResult(object):
    def __init__(self, result, imageregex=None, linkregex=None):

        self._result = result
        self._image_regex = imageregex
        self._link_regex = linkregex
コード例 #20
0
ファイル: env_indigo.py プロジェクト: uleming/Indigo
def file_size(path):
    if sys.platform == 'cli':
        return FileInfo(path).Length
    else:
        return os.path.getsize(path)
コード例 #21
0
"""

import clr
import System
import datetime
clr.AddReference('System.Windows.Forms')
clr.AddReference('System.Drawing')

from System.IO import FileInfo, Path

from System.ComponentModel import BackgroundWorker
from System.Windows.Forms import *

from System.Drawing import *
import re
ICON = Path.Combine(FileInfo(__file__).DirectoryName, "Copy move.ico")
SETTINGS_FILE = Path.Combine(FileInfo(__file__).DirectoryName, "settings.dat")


#@Name Copy/Move Field
#@Hook Books
#@Image Copy move.png
def CopyMoveField(books):

    if books:
        settings = load_settings()
        f = CopyMoveFieldForm(books, settings)
        r = f.ShowDialog()

        settings["source_field"] = f._source.SelectedItem
        settings["destination_field"] = f._destination.SelectedItem
コード例 #22
0
def non_steam_shortcuts(menu_args):
    games_updated = 0
    games_new = 0
    games_skipped_no_action = []
    games_skipped_steam_native = []
    games_skipped_bad_emulator = []
    games_url = []

    steam_userdata = get_steam_userdata_dir()
    if not steam_userdata:
        return

    shortcuts_vdf = join(steam_userdata, "config", "shortcuts.vdf")

    if isfile(shortcuts_vdf):
        try:
            shutil.copyfile(shortcuts_vdf, shortcuts_vdf + ".bak")
        except Exception as e:
            PlayniteApi.Dialogs.ShowErrorMessage(
                traceback.format_exc(), "Error backing up shortcuts.vdf")
            return

        try:
            with open(shortcuts_vdf, "rb") as f:
                steam_shortcuts = parse_shortcuts(f)
        except Exception as e:
            PlayniteApi.Dialogs.ShowErrorMessage(
                traceback.format_exc(), "Error loading shortcuts.vdf")
            return
    else:
        steam_shortcuts = {}

    for game in menu_args.Games:
        play_action = find_play_action(game)

        # If a game somehow has no PlayAction, skip it
        if not play_action:
            games_skipped_no_action.append(game.Name)
            __logger.Error("Non-Steam: Game has no PlayAction: {}".format(
                game.Name))
            continue

        # Skip the game if it is handled by the Steam plugin
        if game.PluginId == STEAM_PLUGIN_GUID:
            __logger.Warn("Non-Steam: Game is already a Steam game: {}".format(
                game.Name))
            games_skipped_steam_native.append(game.Name)
            continue

        # If a game has a URL PlayAction, use it anyway but log it
        if play_action.Type == GameActionType.URL:
            __logger.Warn("Non-Steam: Game has a URL as PlayAction: {}".format(
                game.Name))
            games_url.append(game.Name)

        # Create/Update Non-Steam shortcut
        play_action_expanded = PlayniteApi.ExpandGameVariables(
            game, play_action)
        if play_action_expanded.Type == GameActionType.Emulator:
            emulator = PlayniteApi.Database.Emulators.Get(
                play_action.EmulatorId)
            if emulator.Profiles:
                profile = emulator.Profiles.FirstOrDefault(
                    lambda a: a.Id == play_action.EmulatorProfileId)
            else:
                profile = None
            if not profile:
                games_skipped_bad_emulator.append(game.Name)
                continue
            profile_expanded = emulator_expand_variables(profile, game)
            start_dir = profile_expanded.WorkingDirectory
            exe = profile_expanded.Executable
            arguments = profile_expanded.Arguments or ""
            if play_action_expanded.AdditionalArguments:
                arguments += " " + play_action_expanded.AdditionalArguments
            if play_action_expanded.OverrideDefaultArgs:
                arguments = play_action_expanded.Arguments or ""
        elif play_action_expanded.Type == GameActionType.File:
            start_dir = play_action_expanded.WorkingDir
            exe = play_action_expanded.Path
            arguments = play_action_expanded.Arguments or ""
        elif play_action_expanded.Type == GameActionType.URL:
            exe = play_action_expanded.Path
            start_dir = ""
            arguments = ""
        if not play_action_expanded.Type == GameActionType.URL:
            if not start_dir:
                start_dir = FileInfo(exe).Directory.FullName
            exe = Path.Combine(start_dir, exe)
        if game.Icon:
            icon = PlayniteApi.Database.GetFullFilePath(game.Icon)
        else:
            icon = ""
        shortcut = {
            "icon": icon,
            "exe": '"{}"'.format(exe),
            "startdir": '"{}"'.format(start_dir),
            "appname": game.Name,
            "launchoptions": arguments,
        }
        if game.Name in steam_shortcuts:
            games_updated += 1
            steam_shortcuts[game.Name].update(shortcut)
            shortcut = steam_shortcuts[game.Name]
        else:
            games_new += 1
            shortcut.update(SHORTCUT_DEFAULTS)
            steam_shortcuts[game.Name] = shortcut

        # Update Playnite actions
        # Only run once, don't create duplicate OtherActions
        if play_action == game.PlayAction:
            old_action = game.PlayAction
            steam_action = GameAction(
                Name="Non-Steam Steam Shortcut",
                Type=GameActionType.URL,
                Path=steam_URL(shortcut),
                IsHandledByPlugin=False,
            )
            game.PlayAction = steam_action
            if not game.OtherActions:
                game.OtherActions = ObservableCollection[GameAction]()
            old_action.Name = "Launch without Steam"
            game.OtherActions.Insert(0, old_action)
        else:
            # play_action is already an OtherAction
            # Just make sure the URL is up to date on the main PlayAction
            game.PlayAction.Path = steam_URL(shortcut)

    # Save updated shortcuts.vdf
    try:
        with open(shortcuts_vdf, "wb") as f:
            dump_shortcuts(f, steam_shortcuts)
    except Exception as e:
        PlayniteApi.Dialogs.ShowErrorMessage(traceback.format_exc(),
                                             "Error saving shortcuts.vdf")
        if isfile(shortcuts_vdf + ".bak"):
            try:
                shutil.copyfile(shortcuts_vdf + ".bak", shortcuts_vdf)
                PlayniteApi.Dialogs.ShowMessage(
                    "Successfully restored shortcuts.vdf backup")
            except Exception as e:
                PlayniteApi.Dialogs.ShowErrorMessage(
                    traceback.format_exc(),
                    "Error restoring shortcuts.vdf backup")
        else:
            os.remove(shortcuts_vdf)
        return

    # Truncate long lists of games
    if len(games_skipped_steam_native) > 10:
        games_skipped_steam_native = games_skipped_steam_native[:10] + [
            "[...]"
        ]
    if len(games_skipped_no_action) > 10:
        games_skipped_no_action = games_skipped_no_action[:10] + ["[...]"]
    if len(games_skipped_bad_emulator) > 10:
        games_skipped_bad_emulator = games_skipped_bad_emulator[:10] + [
            "[...]"
        ]
    if len(games_url) > 10:
        games_url = games_url[:10] + ["[...]"]

    errors = False
    message = "Please relaunch Steam to update non-Steam shortcuts!\n\n"
    message += "Updated {} existing non-Steam shortcuts\n".format(
        games_updated)
    message += "Created {} new non-Steam shortcuts".format(games_new)
    if games_skipped_steam_native:
        message += "\n\nSkipped {} native Steam game(s):\n".format(
            len(games_skipped_steam_native))
        message += "\n".join(games_skipped_steam_native)
        errors = True
    if games_skipped_no_action:
        message += "\n\nSkipped {} game(s) without any PlayAction set (not installed?):\n".format(
            len(games_skipped_no_action))
        message += "\n".join(games_skipped_no_action)
        errors = True
    if games_skipped_bad_emulator:
        message += "\n\nSkipped {} emulated game(s) with bad emulator profiles:\n".format(
            len(games_skipped_bad_emulator))
        message += "\n".join(games_skipped_bad_emulator)
        errors = True
    if games_url:
        message += "\n\nWarning: Some games had URL launch actions. (Typically managed by a library plugin.) "
        message += (
            "You may wish to update their actions and recreate non-Steam shortcuts. "
        )
        message += "Steam will still launch these games, but the Steam overlay will not function."
        message += "\n\nThe following {} game(s) had URL launch actions:\n".format(
            len(games_url))
        message += "\n".join(games_url)
        errors = True
    if errors:
        message += "\n\nOpen playnite.log for full list of errors?"
        show_log = PlayniteApi.Dialogs.ShowMessage(
            message,
            "Updated Non-Steam Shortcuts",
            MessageBoxButton.YesNo,
            MessageBoxImage.Error,
        )
        if show_log == MessageBoxResult.Yes:
            open_playnite_log()
    else:
        PlayniteApi.Dialogs.ShowMessage(message, "Updated Non-Steam Shortcuts")
コード例 #23
0
def build_documentation(dll_path, hierarchy):
    log.info("Building documentation")
    dll_file = FileInfo(dll_path)
    assembly = Assembly.LoadFile(dll_file.FullName)
    # Iterate through all namespaces
    # Each namespace is a folder, each class is a file
    # Also builds a YAML index
    index = []
    for namespace, members in hierarchy.items():
        index_files = []
        for member, content in members.items():
            filename = "{}.md".format(
                (namespace + '/' + member).replace('.', '/'))
            file_path = os.path.join(output_dir, filename)
            # Ensure intermediary directories exist
            os.makedirs(os.path.dirname(file_path), exist_ok=True)
            with open(file_path, "w") as file:
                log.debug("Building %s", file.name)
                index_files.append({member: filename})
                member_type = assembly.GetType("{}.{}".format(
                    namespace, member))
                object_type = "Class"
                if member_type is None:
                    member_type = assembly.GetType("{}+{}".format(
                        namespace, member))
                    object_type = "Delegate"
                if member_type.IsEnum:
                    object_type = "Enum"
                # Check if member inherits other members:
                base_type = member_type.BaseType
                if base_type is not None:
                    file.write("**Inherits**  \n{}\n".format(
                        get_link(assembly,
                                 cs_type=base_type,
                                 current_file=file_path)))
                file.write("# {} {}\n".format(object_type, member))
                file.write("{}\n".format(
                    parse_content(
                        assembly,
                        content.get('documentation',
                                    collections.OrderedDict()).get('summary'),
                        current_file=file_path)))
                _temp = collections.OrderedDict()
                # Enums are represented differently
                if object_type == "Enum":
                    rows = []
                    for field, subcontent in content["children"].items():
                        documentation = subcontent["documentation"]
                        rows.append([field, documentation.get("summary", "")])
                    enum_table = build_table(["Field", "Description"], rows)
                    file.write(enum_table)
                    continue
                if object_type == "Delegate":
                    file.write(
                        parse_delegate(
                            member_type,
                            content.get('documentation',
                                        collections.OrderedDict()), file_path))
                    continue
                for name, subcontent in content['children'].items():
                    if "documentation" not in subcontent:
                        continue
                    documentation = subcontent["documentation"]
                    if subcontent["type"] == "C":
                        if "constructors" not in _temp:
                            _temp['constructors'] = []
                        _temp["constructors"].append(
                            parse_constructor(member_type, name, documentation,
                                              file_path))

                    if subcontent["type"] == "F":
                        if "fields" not in _temp:
                            _temp["fields"] = []
                        _temp["fields"].append(
                            parse_field(member_type, name, documentation,
                                        file_path))

                    if subcontent["type"] == "P":
                        if "properties" not in _temp:
                            _temp["properties"] = []
                        _temp["properties"].append(
                            parse_property(member_type, name, documentation,
                                           file_path))

                    if subcontent["type"] == "M":
                        if "methods" not in _temp:
                            _temp["methods"] = []
                        _temp["methods"].append(
                            parse_method(member_type, name, documentation,
                                         file_path))

                    if subcontent["type"] == "E":
                        if "events" not in _temp:
                            _temp["events"] = []
                        _temp["events"].append(
                            parse_event(member_type, name, documentation,
                                        file_path))

                if "constructors" in _temp:
                    file.write("## Constructors\n----\n")
                    file.write("\n".join(_temp["constructors"]))

                if "fields" in _temp:
                    file.write("## Fields\n----\n")
                    file.write("\n".join(_temp["fields"]))

                if "properties" in _temp:
                    file.write("## Properties\n----\n")
                    file.write("\n".join(_temp["properties"]))

                if "methods" in _temp:
                    file.write("## Methods\n----\n")
                    file.write("\n".join(_temp["methods"]))

                if "events" in _temp:
                    file.write("## Events\n----\n")
                    file.write("\n".join(_temp["events"]))
        index.append({namespace: index_files})

    with open(os.path.join(output_dir, "index.yml"), 'w') as yamlfile:
        yaml.dump(index, yamlfile, default_flow_style=False)
        log.info("Generated index file: %s", yamlfile.name)
コード例 #24
0

import clr

import System

clr.AddReference("System.Drawing")
from System.Drawing import Size, Point

clr.AddReference("System.Windows.Forms")
from System.Windows.Forms import TextBox, Button, ComboBox, FlowLayoutPanel, Panel, Label, ComboBoxStyle


from System.IO import Path, FileInfo

SCRIPTDIRECTORY = FileInfo(__file__).DirectoryName

PROFILEFILE = Path.Combine(SCRIPTDIRECTORY, "losettingsx.dat")

ICON = Path.Combine(SCRIPTDIRECTORY, "libraryorganizer.ico")

UNDOFILE = Path.Combine(SCRIPTDIRECTORY, "undo.dat")

VERSION = 2.1

clr.AddReferenceByPartialName('ComicRack.Engine')
from cYo.Projects.ComicRack.Engine import MangaYesNo, YesNo

startbooks = {}
endbooks = {}
コード例 #25
0
class TestDirectoryListing(unittest.TestCase):
    def setUp(self):
        temp_dir = DirectoryInfo(Environment.GetEnvironmentVariable("TEMP"))
        #       myDocuments = DirectoryInfo(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments))
        self.temp_dir = temp_dir.CreateSubdirectory('tempDir')
        self.temp_dir_path = self.temp_dir.ToString()

        self.file1 = FileInfo(self.temp_dir_path + '\\file1.txt')
        self.file2 = FileInfo(self.temp_dir_path + '\\file2.txt')
        self.file3 = FileInfo(self.temp_dir_path + '\\file3.txt')

        sw = self.file1.CreateText()
        sw.WriteLine("Hello1")
        sw.Close()

        sw = self.file2.CreateText()
        sw.WriteLine("Hello2")
        sw.Close()

        sw = self.file3.CreateText()
        sw.WriteLine("Hello3")
        sw.Close()

        today = DateTime.Now
        one_day_old = today.AddDays(-1).ToString("yyyy.MM.dd")
        two_days_old = today.AddDays(-2).ToString("yyyy.MM.dd")
        self.file1.CreationTime = DateTime.Parse(today.ToString("yyyy.MM.dd"))
        self.file2.CreationTime = DateTime.Parse(one_day_old)
        self.file3.CreationTime = DateTime.Parse(two_days_old)

        print "\r myDocuments temp path = [%s]" % self.temp_dir_path
        print "CreationTime file1 = [%s]" % self.file1.CreationTime
        print "CreationTime file2 = [%s]" % self.file2.CreationTime
        print "CreationTime file3 = [%s]" % self.file3.CreationTime

    def testFindThreeFilesInDirectory(self):
        files = directoryListing.getFilesOlderThan(self.temp_dir_path)
        self.assertEqual("file1.txt", files[0].Name)
        self.assertEqual("file2.txt", files[1].Name)
        self.assertEqual("file3.txt", files[2].Name)

    def testFindFilesInDirectoryADayOrOlderFromNow(self):
        files = directoryListing.getFilesOlderThan(self.temp_dir_path, 1)
        self.assertEqual("file2.txt", files[0].Name)
        self.assertEqual("file3.txt", files[1].Name)

    def testFindFilesInDirectoryTwoDaysOrOlderFromNow(self):
        files = directoryListing.getFilesOlderThan(self.temp_dir_path, 2)
        self.assertEqual("file3.txt", files[0].Name)

    def testDeleteAllFilesInDirectory(self):
        files = directoryListing.getFilesOlderThan(self.temp_dir_path)
        deleteFiles.deleteFiles(files)
        self.assertEqual(
            0, len(Directory.GetFileSystemEntries(self.temp_dir_path)))

    def testDeleteFilesInDirectoryOneDayAndOlder(self):
        all_files = directoryListing.getFilesYoungerThan(self.temp_dir_path)
        files = directoryListing.getFilesYoungerThan(self.temp_dir_path, 1)
        deleteFiles.deleteFiles(files)
        self.assertEqual(
            1, len(Directory.GetFileSystemEntries(self.temp_dir_path)))

    def testDeleteFilesInDirectoryTwoDaysAndYounger(self):
        all_files = directoryListing.getFilesYoungerThan(self.temp_dir_path)
        files = directoryListing.getFilesYoungerThan(self.temp_dir_path, 2)
        deleteFiles.deleteFiles(files)
        self.assertEqual(
            0, len(Directory.GetFileSystemEntries(self.temp_dir_path)))

    def tearDown(self):
        self.temp_dir.Delete(True)
from System.IO import File, Directory, FileInfo, Path

## Remove all open images
Zen.Application.Documents.RemoveAll()
##
## Define experiment
exp = ZenExperiment()

## Load experiment
exp.Load("OAD_Training_Exp", ZenSettingDirectory.User)
## Execute experiment, display acquired image
## Image is saved automatically in temp folder of AutoSavePath of Saving tab of Tools/Options menu
image = Zen.Acquisition.Execute(exp)

#get image name
img_filename = image.FileName
finfo = FileInfo(img_filename)
img_name = finfo.Name

## save image
path = Zen.Application.Environment.GetFolderPath(
    ZenSpecialFolder.ImageAutoSave)
fullPath = path + '\\' + img_name
image.Save(fullPath)

## Close image
image.Close()
##
#######################################################
コード例 #27
0
ファイル: dynamo.py プロジェクト: Ianhuuuuang/Code_for_bridge
import Revit
# 导入几何体转换方法(将dynamo中输出的几何体转为revit中的几何体)
clr.ImportExtensions(Revit.GeometryConversion)
# 导入元素转换(revit转dynamo)
clr.ImportExtensions(Revit.Elements) 
#导入系统文件操作,这样才能顺利将EXCEL读取节点进行装换
import System
from System.IO import FileInfo
#导入dynamoEXCEL读取功能
clr.AddReference("DSOffice")
from DSOffice import Data
#导入列表功能节点
clr.AddReference("DSCoreNodes")
import DSCore
from DSCore import *

#这里采用圆心与半径的方法创建圆
#将EXCEL读取节点进行转换
circleExcel=FileInfo(IN[0])
circleInformation=Data.ImportExcel(circleExcel,"Sheet1",False,True)
circleList=[]
for i in range(1,10):
	x=circleInformation[i][1]
	y=circleInformation[i][2]
	z=circleInformation[i][3]
	r=circleInformation[i][4]
	center =Point.ByCoordinates(x,y,z)
	circle =Circle.ByCenterPointRadius(center,r)
	circleList.Add(circle)
OUT=circleList
コード例 #28
0
def getSize(p, mb=mb, kb=kb, kbOnly=IN[1]):
    sb = FileInfo(p).Length
    if sb < mb or kbOnly:
        return '%.3f KB' % (sb / kb)
    else:
        return '%.3f MB' % (sb / mb)
コード例 #29
0
def GetFileSize(filePath):
    fileSize = None
    try:
        fileSize = FileInfo(filePath).Length
    except Exception, e:
        pass
コード例 #30
0
def non_steam_shortcuts():
    games_updated = 0
    games_new = 0
    games_skipped_no_action = []
    games_skipped_steam_native = []
    games_skipped_bad_emulator = []
    games_url = []

    if not isdir(join(STEAM_USERDATA, "config")):
        PlayniteApi.Dialogs.ShowErrorMessage(
            "Please configure this extension by setting the path to your Steam profile's userdata folder. "
            "Edit the nonsteam.py file of this extension and update STEAM_USERDATA.",
            "Error: Extension not configured")
        return

    if isfile(SHORTCUTS_VDF):
        try:
            shutil.copyfile(SHORTCUTS_VDF, SHORTCUTS_VDF+".bak")
        except Exception as e:
            PlayniteApi.Dialogs.ShowErrorMessage(
                traceback.format_exc(),
                "Error backing up shortcuts.vdf")
            return

        try:
            with open(SHORTCUTS_VDF, "rb") as f:
                steam_shortcuts = parse_shortcuts(f)
        except Exception as e:
            PlayniteApi.Dialogs.ShowErrorMessage(
                traceback.format_exc(),
                "Error loading shortcuts.vdf")
            return
    else:
        steam_shortcuts = {}

    for game in PlayniteApi.MainView.SelectedGames:
        play_action = find_play_action(game)

        # If a game somehow has no PlayAction, skip it
        if not play_action:
            games_skipped_no_action.append(game.Name)
            continue

        # Skip the game if it is handled by the Steam plugin
        if game.PluginId == STEAM_PLUGIN_GUID:
            games_skipped_steam_native.append(game.Name)
            continue

        # If a game has a URL PlayAction, use it anyway but log it
        if play_action.Type == GameActionType.URL:
            games_url.append(game.Name)

        # Create/Update Non-Steam shortcut
        play_action_expanded = PlayniteApi.ExpandGameVariables(game, play_action)
        if play_action_expanded.Type == GameActionType.Emulator:
            emulator = PlayniteApi.Database.Emulators.Get(play_action.EmulatorId)
            if emulator.Profiles:
                profile = emulator.Profiles.FirstOrDefault(lambda a: a.Id == play_action.EmulatorProfileId)
            else:
                profile = None
            if not profile:
                games_skipped_bad_emulator.append(game.Name)
                continue
            profile_expanded = emulator_expand_variables(profile, game)
            start_dir = profile_expanded.WorkingDirectory
            exe = profile_expanded.Executable
            arguments = profile_expanded.Arguments or ""
            if play_action_expanded.AdditionalArguments:
                arguments += " " + play_action_expanded.AdditionalArguments
            if play_action_expanded.OverrideDefaultArgs:
                arguments = play_action_expanded.Arguments or ""
        elif play_action_expanded.Type == GameActionType.File:
            start_dir = play_action_expanded.WorkingDir
            exe = play_action_expanded.Path
            arguments = play_action_expanded.Arguments or ""
        elif play_action_expanded.Type == GameActionType.URL:
            exe = play_action_expanded.Path
            start_dir = ""
            arguments = ""
        if not play_action_expanded.Type == GameActionType.URL:
            if not start_dir:
                start_dir = FileInfo(exe).Directory.FullName
            exe = Path.Combine(start_dir, exe)
        if game.Icon:
            icon = PlayniteApi.Database.GetFullFilePath(game.Icon)
        else:
            icon = ""
        shortcut = {
            "icon": icon,
            "exe": '"{}"'.format(exe),
            "startdir": '"{}"'.format(start_dir),
            "appname": game.Name,
            "launchoptions": arguments,
        }
        if game.Name in steam_shortcuts:
            games_updated += 1
            steam_shortcuts[game.Name].update(shortcut)
            shortcut = steam_shortcuts[game.Name]
        else:
            games_new += 1
            shortcut.update(SHORTCUT_DEFAULTS)
            steam_shortcuts[game.Name] = shortcut

        # Update Playnite actions
        # Only run once, don't create duplicate OtherActions
        if play_action == game.PlayAction:
            old_action = game.PlayAction
            steam_action = GameAction(
                Name="Non-Steam Steam Shortcut",
                Type=GameActionType.URL,
                Path=steam_URL(shortcut),
                IsHandledByPlugin=False,
            )
            game.PlayAction = steam_action
            if not game.OtherActions:
                game.OtherActions = ObservableCollection[GameAction]()
            old_action.Name = "Launch without Steam"
            game.OtherActions.Insert(0, old_action)
        else:
            # play_action is already an OtherAction
            # Just make sure the URL is up to date on the main PlayAction
            game.PlayAction.Path = steam_URL(shortcut)

    # Save updated shortcuts.vdf
    try:
        with open(SHORTCUTS_VDF, "wb") as f:
            dump_shortcuts(f, steam_shortcuts)
    except Exception as e:
        PlayniteApi.Dialogs.ShowErrorMessage(
            traceback.format_exc(),
            "Error saving shortcuts.vdf")
        if isfile(SHORTCUTS_VDF+".bak"):
            try:
                shutil.copyfile(SHORTCUTS_VDF+".bak", SHORTCUTS_VDF)
                PlayniteApi.Dialogs.ShowMessage(
                    "Successfully restored shortcuts.vdf backup")
            except Exception as e:
                PlayniteApi.Dialogs.ShowErrorMessage(
                    traceback.format_exc(),
                    "Error restoring shortcuts.vdf backup")
        else:
            os.remove(SHORTCUTS_VDF)
        return

    message = "Please relaunch Steam to update non-Steam shortcuts!\n\n"
    message += "Updated {} existing non-Steam shortcuts\n".format(games_updated)
    message += "Created {} new non-Steam shortcuts".format(games_new)
    if games_skipped_steam_native:
        message += "\n\nSkipped {} native Steam game(s):\n".format(len(games_skipped_steam_native))
        message += "\n".join(games_skipped_steam_native)
    if games_skipped_no_action:
        message += "\n\nSkipped {} game(s) without any PlayAction set (not installed?):\n".format(len(games_skipped_no_action))
        message += "\n".join(games_skipped_no_action)
    if games_skipped_bad_emulator:
        message += "\n\nSkipped {} emulated game(s) with bad emulator profiles:\n".format(len(games_skipped_bad_emulator))
        message += "\n".join(games_skipped_bad_emulator)
    if games_url:
        message += "\n\nWarning: Some games had URL launch actions. (Typically managed by a library plugin.) "
        message += "You may wish to update their actions and recreate non-Steam shortcuts. "
        message += "Steam will still launch these games, but the Steam overlay will not function."
        message += "\n\nThe following {} game(s) had URL launch actions:\n".format(len(games_url))
        message += "\n".join(games_url)
    PlayniteApi.Dialogs.ShowMessage(
        message,
        "Updated Non-Steam Shortcuts"
    )