Example #1
0
def RebuildLoadMenu():
	import nt
	import strop

	# load both directorys, where we can find Missions here.
	list = nt.listdir('scripts\Custom\QuickBattleGame') + nt.listdir('scripts\Custom\QuickBattleGame\Missions')
	files = []

	for file in list:
		s = strop.split(file, '.')
		if (len(s)>1) and ((s[-1] == 'pyc') or (s[-1] == 'py')):
			filename = s[0]
			try:
			        pModule = __import__('Custom.QuickBattleGame.Missions.'+filename)
			except:
			        pModule = __import__('Custom.QuickBattleGame.'+filename)
			
			if (hasattr(pModule, 'gVersion')):
				if (files.count(filename)==0):
					files.append(filename)
	
	pSet =  App.g_kSetManager.GetSet('bridge')
	pSaffi = App.CharacterClass_GetObject(pSet, 'XO')

	g_pLoadMenu.KillChildren()
	for file in files:
		button = CreateBridgeMenuButton(App.TGString(file), Lib.Ambiguity.getEvent("ET_SELECT_FILE"), file, pSaffi)
		button.SetUseUIHeight(0)
		g_pLoadMenu.AddChild(button)

	g_pLoadMenu.ResizeToContents()
	g_pLoadWindow.Layout()
Example #2
0
def main():
    fileList = [x for x in listdir(r'.') if (x.lower().endswith(".csv") and not(x.lower().endswith(".log.csv")))]
    missingBoxfileList = [x for x in listdir(r'.') if x.lower().endswith(".txt")]
    m = len(fileList)
    n = len(missingBoxfileList)

    missingBoxNums = []

    for i in range(n):
        boxNums=[line.strip() for line in open(missingBoxfileList[i],'rU').readlines()]
        missingBoxNums.extend(boxNums)
    missingBoxNums=set(missingBoxNums)


    with open(LogFile, 'wb') as f:
        writer = csv.writer(f)
        writer.writerow(('box number','old file name','new file name'))

        for i in range(m):
            boxNums=[line.strip().split(';')[11] for line in open(fileList[i],'rU').readlines()]
            boxNums = set(boxNums)
            outputMissingBox = list(missingBoxNums & boxNums)
            
            if len(outputMissingBox)>0:
                mkdir()
                print 'Missing:',fileList[i]
                newFile = getFileName()
                shutil.copyfile(fileList[i], "./"+FolderName+"/"+newFile)

                for item in outputMissingBox:
                    writer.writerow((item,fileList[i],newFile))
            else:
                print 'No Missing:',fileList[i]
Example #3
0
def handwriteingClassTest():
    hwLabels = []
    trainingFileList = listdir('trainingDigits')
    m = len(trainingFileList)
    trainingMat = zeros((m,1024))
    
    for i in range(m):
        fileNameStr = trainingFileList[i]
        fileStr = fileNameStr.split('.')[0]
        classNumStr = int(fileStr.split('_')[0])
        hwLabels.append(classNumStr)
        trainingMat[i,:] = img2vector('trainingDigits/%s' % fileNameStr)
    testFileList = listdir('testDigits')
    errorCount = 0.0
    mTest = len(testFileList)
    for i in range(mTest):
        fileNameStr = testFileList[i]
        fileStr = fileNameStr.split('.')[0]
        classNumStr = int(fileStr.split('_')[0])
        vectorUnderTest = img2vector('testDigits/%s' % fileNameStr)
        classifierResult = classify(vectorUnderTest,trainingMat,hwLabels,3)
        
        print("the classifier came back with: %d, the real answer is : %d" % (classifierResult,classNumStr))
        if classifierResult != classNumStr:
            errorCount += 1.0
    
    print("The total number of errors is: %d." % errorCount)
    print("The total error rate is: %f." % (errorCount/float(mTest)))
Example #4
0
def handwritingClassTest():
    hwLabels = []
    trainingFileList = listdir(r'F:\PY\data\trainingDigits')
    m = len(trainingFileList)
    trainingMat = zeros((m,1024))

    for i in range(m):
        fileNameStr = trainingFileList[i]
        fileStr = fileNameStr.split('.')[0]
        classNumStr = int(fileStr.split('_')[0])
        hwLabels.append(classNumStr)
        trainingMat[i,:] = img2Vector(r'F:\PY\data\trainingDigits\%s' % fileNameStr)

    testFileList = listdir(r'F:\PY\data\testDigits')
    errorCount=0.0
    mTest = len(testFileList)
    for i in range(mTest):
        fileNameStr = testFileList[i]
        fileStr = fileNameStr.split('.')[0]
        classNumStr = int(fileStr.split('_')[0])
        vectorUnderTest = img2Vector(r'F:\PY\data\testDigits\%s' % fileNameStr)
        classifierResult = classify0(vectorUnderTest,trainingMat,hwLabels,3)
        print "the classifier came back with: %d, the real number is: %d" % (classifierResult,classNumStr)
        if(classNumStr!=classifierResult): errorCount +=1.0

    print '\nthe total number of error is: %d' % errorCount
    print '\nthe total error rate is: %f' % (errorCount/float(mTest))
Example #5
0
def run_test_pkg(pkg_name):
    log_info("--%s package----------------------------------------" % pkg_name)
    
    #Determine where the test package is and ensure it exists
    log_debug("The current working directory is " + __CWD)
    pkg_dir_name = __CWD + "\\" + pkg_name.replace(".", "\\")
    log_debug("The test package location is " + pkg_dir_name)
    if not file_exists(pkg_dir_name + r"\__init__.py"):
        err_msg = "No such test package: %s" % pkg_dir_name
        log_error(err_msg)
        raise Exception(err_msg)
    
    #Build up a list of all subpackages/modules contained in test package
    subpkg_list = [x for x in nt.listdir(pkg_dir_name) if not x.endswith(".py") and file_exists(pkg_dir_name + "\\" + x + "\\__init__.py")]
    log_debug("Subpackages found: %s" % (str(subpkg_list)))
    module_list = [x for x in nt.listdir(pkg_dir_name) if x.endswith(".py") and x!="__init__.py"]
    log_debug("Modules found: %s" % (str(module_list)))
    if len(module_list)==0:
        log_warn("No test modules found in the %s test package!" % pkg_name)
        print ""
    
    #Import all tests
    for test_module in module_list:
        test_module = pkg_name + "." + test_module.split(".py", 1)[0]
        log_info("--Testing %s..." % test_module)
        try:
            __import__(test_module)
        except SystemExit, e:
            if e.code!=0: 
                raise Exception("Importing '%s' caused an unexpected exit code: %s" % (test_module, str(e.code)))
        print ""
Example #6
0
def run_test_pkg(pkg_name, do_not_run=[]):
    log_info("--%s package----------------------------------------" % pkg_name)

    #Determine where the test package is and ensure it exists
    log_debug("The current working directory is " + __CWD)
    pkg_dir_name = __CWD + "\\" + pkg_name.replace(".", "\\")
    log_debug("The test package location is " + pkg_dir_name)
    if not file_exists(pkg_dir_name + r"\__init__.py"):
        err_msg = "No such test package: %s" % pkg_dir_name
        log_error(err_msg)
        raise Exception(err_msg)

    #Build up a list of all subpackages/modules contained in test package
    subpkg_list = [
        x for x in nt.listdir(pkg_dir_name)
        if not x.endswith(".py") and file_exists(pkg_dir_name + "\\" + x +
                                                 "\\__init__.py")
    ]
    log_debug("Subpackages found: %s" % (str(subpkg_list)))
    module_list = [
        x for x in nt.listdir(pkg_dir_name)
        if x.endswith(".py") and x != "__init__.py"
    ]
    log_debug("Modules found: %s" % (str(module_list)))
    if len(module_list) == 0:
        log_warn("No test modules found in the %s test package!" % pkg_name)
        print("")

    if options.GEN_TEST_PLAN:
        l.info("Generating test documentation for '%s' package..." % pkg_name)
        pydoc.writedoc(pkg_name)

    #Import all tests
    for test_module in module_list:
        test_module = pkg_name + "." + test_module.split(".py", 1)[0]

        if options.RUN_TESTS:
            if test_module in do_not_run:
                log_info("--Testing of %s has been disabled!" % test_module)
                continue
            log_info("--Testing %s..." % test_module)
            try:
                __import__(test_module)
            except SystemExit as e:
                if e.code != 0:
                    raise Exception(
                        "Importing '%s' caused an unexpected exit code: %s" %
                        (test_module, str(e.code)))
            print("")

        if options.GEN_TEST_PLAN:
            l.info("Generating test documentation for '%s' module..." %
                   test_module)
            pydoc.writedoc(test_module)

    #Recursively import subpackages
    for subpkg in subpkg_list:
        run_test_pkg(pkg_name + "." + subpkg)
Example #7
0
    def test_getcwdb(self):
        self.assertEqual(nt.getcwdb(),nt.getcwd().encode())

        nt.mkdir('dir_create_test')
        if is_cli:
            self.assertEqual(nt.listdir(nt.getcwdb()).count('dir_create_test'), 1)
        else:
            self.assertEqual(nt.listdir(nt.getcwdb()).count(b'dir_create_test'), 1)
        nt.rmdir('dir_create_test')
Example #8
0
def main(cpy_dir):
    global CPY_DIR
    global CPY_LIB_DIR

    CPY_DIR = cpy_dir
    CPY_LIB_DIR = cpy_dir + "\\Lib"  #E.g., C:\Python25\Lib

    path.append(CPY_LIB_DIR)
    path.insert(0, ".")

    print(
        "------------------------------------------------------------------------"
    )
    print("--PACKAGES")
    cwd = nt.getcwd()
    nt.chdir(CPY_LIB_DIR)

    for pack_name in nt.listdir(CPY_LIB_DIR):
        if not is_package(pack_name):
            continue
        elif pack_name in BLACKLIST:
            continue

        check_package(pack_name)
    print()

    nt.chdir(cwd)

    print(
        "------------------------------------------------------------------------"
    )
    print("--MODULES")

    for x in nt.listdir(CPY_LIB_DIR):
        if x.endswith(".py"):
            mod_name = x.split(".py", 1)[0]
        else:
            continue

        try:
            import_helper(mod_name)
            log_ok(mod_name)

        except Exception as e:
            log_broken(mod_name, e)

    #Cleanup
    for f in FILE_LIST:
        f.close()

    return BROKEN_LIST
Example #9
0
def run_test_pkg(pkg_name, do_not_run=[]):
    log_info("--%s package----------------------------------------" % pkg_name)
    
    #Determine where the test package is and ensure it exists
    log_debug("The current working directory is " + __CWD)
    pkg_dir_name = __CWD + "\\" + pkg_name.replace(".", "\\")
    log_debug("The test package location is " + pkg_dir_name)
    if not file_exists(pkg_dir_name + r"\__init__.py"):
        err_msg = "No such test package: %s" % pkg_dir_name
        log_error(err_msg)
        raise Exception(err_msg)
    
    #Build up a list of all subpackages/modules contained in test package
    subpkg_list = [x for x in nt.listdir(pkg_dir_name) if not x.endswith(".py") and file_exists(pkg_dir_name + "\\" + x + "\\__init__.py")]
    log_debug("Subpackages found: %s" % (str(subpkg_list)))
    module_list = [x for x in nt.listdir(pkg_dir_name) if x.endswith(".py") and x!="__init__.py"]
    log_debug("Modules found: %s" % (str(module_list)))
    if len(module_list)==0:
        log_warn("No test modules found in the %s test package!" % pkg_name)
        print("")
    
    if options.GEN_TEST_PLAN:
        l.info("Generating test documentation for '%s' package..." % pkg_name)
        pydoc.writedoc(pkg_name)
    
    #Import all tests
    for test_module in module_list:
        test_module = pkg_name + "." + test_module.split(".py", 1)[0]
        
        if options.RUN_TESTS:
            if test_module in do_not_run:
                log_info("--Testing of %s has been disabled!" % test_module)
                continue
            log_info("--Testing %s..." % test_module)
            try:
                __import__(test_module)
            except SystemExit as e:
                if e.code!=0: 
                    raise Exception("Importing '%s' caused an unexpected exit code: %s" % (test_module, str(e.code)))
            print("")
        
        if options.GEN_TEST_PLAN:
            l.info("Generating test documentation for '%s' module..." % test_module)
            pydoc.writedoc(test_module)

    
    #Recursively import subpackages
    for subpkg in subpkg_list:
        run_test_pkg(pkg_name + "." + subpkg)
        
Example #10
0
def test_cp20174():
    cp20174_path = testpath.public_testdir + r"\cp20174"
    
    try:
        nt.mkdir(cp20174_path)
        
        cp20174_init = cp20174_path + r"\__init__.py"
        write_to_file(cp20174_init, "import a")
        
        cp20174_a = cp20174_path + r"\a.py"
        write_to_file(cp20174_a, """
from property import x
class C:
    def _get_x(self): return x
    x = property(_get_x)
""")
        
        cp20174_property = cp20174_path + r"\property.py"
        write_to_file(cp20174_property, "x=1")
        
        import cp20174
        AreEqual(cp20174.property.x, 1)
        
    finally:
        for x in nt.listdir(cp20174_path):
            nt.unlink(cp20174_path + "\\" + x)
        nt.rmdir(cp20174_path)
def CreatePluginBase():	
	PluginList = nt.listdir('scripts/Custom/GravityFX/Plugins')
	PluginList.remove('__init__.py')
	MainDict = {'Ships': {}, 'Torpedoes': {}}
	for sFile in PluginList:
		sFileStrings = string.split(sFile, '.')
		sPlugin = sFileStrings[0]
		sExt = sFileStrings[-1]
		if sExt == "py":
			pModule = __import__("Custom.GravityFX.Plugins." + sPlugin)
			InfoDict = {}
			if sPlugin == "NotToBeAffectedShips":
				for sShipScriptName in pModule.lShips:
					MainDict['Ships'][sShipScriptName] = {'Type': "NotToBeAffected"}
			else:
				sPluginType = pModule.PluginType
				InfoDict['Type'] = sPluginType
				if sPluginType == "GravTorpedo" or sPluginType == "AntiGravTorpedo":
					InfoDict['Lifetime'] = pModule.Lifetime
					InfoDict['Mass'] = pModule.Mass
					InfoDict['SoundDelay'] = pModule.SoundDelay
					InfoDict['ColorRed'] = pModule.ColorRed
					InfoDict['ColorGreen'] = pModule.ColorGreen
					InfoDict['ColorBlue'] = pModule.ColorBlue
					InfoDict['ColorAlpha'] = pModule.ColorAlpha
					MainDict['Torpedoes'][sPlugin] = InfoDict
				elif sPluginType == "NotToBeAffected":
					MainDict['Ships'][sPlugin] = InfoDict
	return MainDict
Example #12
0
def LoadExtraPlugins(dir = 'scripts\\Custom\\Autoload', dExcludePlugins = {}):
	import nt
	import string

	list = nt.listdir(dir)
	list.sort()

	dotPrefix = string.join(string.split(dir, '\\')[1:], '.') + '.'

	for plugin in list:
		s = string.split(plugin, '.')
		if len(s) <= 1:
			continue
		# Indexing by -1 lets us be sure we're grabbing the extension. -Dasher42
		extension = s[-1]
		fileName = string.join(s[:-1], '.')

		# We don't want to accidentally load the wrong ship.
		if (extension == 'pyc' or extension == 'py') and not dExcludePlugins.has_key(fileName):
			if bTesting:
				pModule = __import__(dotPrefix + fileName)
			else:
				try:
					pModule = __import__(dotPrefix + fileName)
				except:
					pass
Example #13
0
def LoadPlugins(dir, type):
    debug(__name__ + ", LoadPlugins")
    import nt
    import string
    list = nt.listdir(dir)
    list.sort()

    dotPrefix = string.join(string.split(dir, '\\')[1:], '.') + '.'

    global dMenus
    dMenus[type] = []

    lLoaded = ["__init__"]

    for plugin in list:
        s = string.split(plugin, '.')
        if len(s) <= 1:
            continue
        # Indexing by -1 lets us be sure we're grabbing the extension. -Dasher42
        extension = s[-1]
        fileName = string.join(s[:-1], '.')

        if (extension == 'pyc' or extension == 'py') and not fileName in lLoaded:
            lLoaded.append(fileName)
            pModule = __import__(dotPrefix + fileName)
            dMenus[type].append([dotPrefix + fileName, fileName])
Example #14
0
def test_cp20174():
    cp20174_path = testpath.public_testdir + r"\cp20174"

    try:
        nt.mkdir(cp20174_path)

        cp20174_init = cp20174_path + r"\__init__.py"
        write_to_file(cp20174_init, "import a")

        cp20174_a = cp20174_path + r"\a.py"
        write_to_file(
            cp20174_a, """
from property import x
class C:
    def _get_x(self): return x
    x = property(_get_x)
""")

        cp20174_property = cp20174_path + r"\property.py"
        write_to_file(cp20174_property, "x=1")

        import cp20174
        AreEqual(cp20174.property.x, 1)

    finally:
        for x in nt.listdir(cp20174_path):
            nt.unlink(cp20174_path + "\\" + x)
        nt.rmdir(cp20174_path)
Example #15
0
def test_ipy_dash_m_pkgs():
    # Python packages work
    import nt
    Assert("testpkg1" in [x.lower() for x in nt.listdir(nt.getcwd())],
           nt.getcwd())

    old_ipy_path = get_environ_variable("IRONPYTHONPATH")
    try:
        nt.environ["IRONPYTHONPATH"] = nt.getcwd()
        ipi = IronPythonInstance(executable, exec_prefix,
                                 extraArgs + " -m testpkg1")
        res, output, err, exit = ipi.StartAndRunToCompletion()
        AreEqual(res, True)  # run should have worked
        AreEqual(exit, 0)  # should have returned 0
        AreEqual(output, "")

        # Bad module names should not work
        ipi = IronPythonInstance(executable, exec_prefix,
                                 extraArgs + " -m libxyz")
        res, output, err, exit = ipi.StartAndRunToCompletion()
        AreEqual(res, True)  # run should have worked
        AreEqual(exit, 1)  # should have returned 0
        Assert("ImportError: No module named libxyz" in err,
               "stderr is:" + str(err))
    finally:
        nt.environ["IRONPYTHONPATH"] = old_ipy_path
def LoadExtraPlugins(dir = 'scripts\\Custom\\Carriers\\'):
    debug(__name__ + ", LoadExtraPlugins")
    import nt
    import string

    list = nt.listdir(dir)
    list.sort()

    dotPrefix = string.join(string.split(dir, '\\')[1:], '.')

    for plugin in list:
        s = string.split(plugin, '.')
        pluginFile = ''
        # We don't want to accidentally load the wrong ship.
        # Indexing by -1 lets us be sure we're grabbing the extension. -Dasher42
        if len(s) > 1 and \
           ( s[-1] == 'pyc' or s[-1] == 'py'):
            pluginFile = s[0]
        else:
            continue

        try:
            pModule = __import__(dotPrefix + pluginFile)
        except ImportError:
            print "Error Loading", dotPrefix + pluginFile
Example #17
0
def LoadExtraShips(dir = 'scripts\\Custom\\Ships', hpdir = 'scripts\\Custom\\Ships\\Hardpoints', dReservedShips = reservedShips):
	import nt
	import string

	list = nt.listdir(dir)
	list.sort()

	shipDotPrefix = string.join(string.split(dir, '\\')[1:], '.') + '.'
	hpDotPrefix = string.join(string.split(hpdir, '\\')[1:], '.') + '.'

	for ship in list:
		s = string.split(ship, '.')
		if len(s) <= 1:
			continue
		# Indexing by -1 lets us be sure we're grabbing the extension. -Dasher42
		extension = s[-1]
		shipFile = string.join(s[:-1], '.')

		# We don't want to accidentally load the wrong ship.
		if (extension == 'pyc' or extension == 'py') and not dReservedShips.has_key(string.lower(shipFile)):
			if bTesting:
				pModule = __import__(shipDotPrefix + shipFile)
				if hasattr(pModule, 'GetShipStats'):
					stats = pModule.GetShipStats()
					LoadToOther(shipFile, stats['Name'], stats['Species'], shipDotPrefix)
			else:
				try:
					pModule = __import__(shipDotPrefix + shipFile)
					if hasattr(pModule, 'GetShipStats'):
						stats = pModule.GetShipStats()
						LoadToOther(shipFile, stats['Name'], stats['Species'], shipDotPrefix)
				except:
					continue
Example #18
0
def DoMvamMenus(pMenu, tuple, num, pDatabase, pButton, pMissionPane):
    try:
        import Custom.Autoload.Mvam
    except:
        return 0

    if len(tuple) >= 7 and tuple[7] != None:

        List = nt.listdir("scripts\\Custom\\Autoload\\Mvam\\")

        Mod = None
        for i in range(len(List)):
            PosModName = string.split(List[i], ".")
            if len(PosModName) > 1 and PosModName[0] != "__init__":
                try:
                    PosMod = __import__("Custom.Autoload.Mvam." + PosModName[0])
                    if PosMod and hasattr(PosMod, "MvamShips"):
                        if IsInList(tuple[0], PosMod.MvamShips):
                            Mod = PosMod
                            break
                except:
                    continue

        if not Mod:
            return 0
        if Mod.MvamShips[0] == tuple[0]:
            # Full Ship
            TGName = Multiplayer.MissionShared.g_pShipDatabase.GetString(
                Multiplayer.SpeciesToShip.GetScriptFromSpecies(iIndex)
            )
            pParentShipMenu = pMenu.GetSubmenuW(TGName)
            if not pParentShipMenu:
                pParentShipMenu = App.STCharacterMenu_CreateW(TGName)
                pEvent = App.TGIntEvent_Create()
                pEvent.SetEventType(Multiplayer.MissionMenusShared.ET_SELECT_SHIP_SPECIES)
                pEvent.SetDestination(pMissionPane)
                pEvent.SetSource(pParentShipMenu)
                pEvent.SetInt(num)
                pParentShipMenu.SetActivationEvent(pEvent)
                pParentShipMenu.SetTwoClicks()
                pMenu.AddChild(pParentShipMenu, 0, 0, 0)
                pMenu.ForceUpdate(0)
        else:
            # Sep Ship
            TGName = Multiplayer.MissionShared.g_pShipDatabase.GetString(Mod.MvamShips[0])
            pParentShipMenu = pMenu.GetSubmenuW(TGName)
            if not pParentShipMenu:
                pParentShipMenu = App.STCharacterMenu_CreateW(TGName)
                pEvent = App.TGIntEvent_Create()
                pEvent.SetEventType(Multiplayer.MissionMenusShared.ET_SELECT_SHIP_SPECIES)
                pEvent.SetDestination(pMissionPane)
                pEvent.SetSource(pParentShipMenu)
                pEvent.SetInt(num)
                pParentShipMenu.SetActivationEvent(pEvent)
                pParentShipMenu.SetTwoClicks()
                pMenu.AddChild(pParentShipMenu, 0, 0, 0)
                pMenu.ForceUpdate(0)
            pParentShipMenu.AddChild(pButton, 0, 0, 0)
            pMenu.ForceUpdate(0)
    return 0
Example #19
0
def classifyImg():
    fileList = [
        x for x in listdir(r'F:\PY\data\Img') if x.lower().endswith(".jpg")
    ]
    m = len(fileList)

    for fn in range(m):
        img = Image.open(r'F:\PY\data\Img\{0}'.format(fileList[fn]))
        arr = array(img)
        list = []
        if arr.ndim == 2:
            print fileList[fn]
            continue
        for n in arr:
            list.append(n[0][0])
        for n in arr:
            list.append(n[0][1])
        for n in arr:
            list.append(n[0][2])

        data[fileList[fn]] = list
    reference = data['007_0025.jpg']
    result = {}

    for x, y in data.items():
        dist = mlpy.dtw_std(reference, y, dist_only=True)
        result[x] = dist

    sortedRes = OrderedDict(sorted(result.items(), key=lambda x: x[1]))

    for a, b in sortedRes.items():
        print("{0} - {1}".format(a, b))
        i = i + 1
        if i == 10:
            break
Example #20
0
def classifyImg():
    fileList = [x for x in listdir(r'F:\PY\data\Img') if x.lower().endswith(".jpg")]
    m = len(fileList)
    
    for fn in range(m):
        img = Image.open(r'F:\PY\data\Img\{0}'.format(fileList[fn]))
        arr = array(img)
        list = []
        if arr.ndim==2:
            print fileList[fn]
            continue;
        for n in arr: list.append(n[0][0])
        for n in arr: list.append(n[0][1])
        for n in arr: list.append(n[0][2])
        
        data[fileList[fn]] = list
    reference = data['007_0025.jpg']
    result = {}

    for x,y in data.items():
        dist = mlpy.dtw_std(reference,y,dist_only=True)
        result[x]=dist

    sortedRes = OrderedDict(sorted(result.items(),key=lambda x:x[1]))


    for a,b in sortedRes.items():
        print("{0} - {1}".format(a,b))
        i=i+1
        if i==10:
            break
def listfiles(path):
    """ Returns list of files of a given directory """
    filelist = []
    try:
        filelist = [f for f in nt.listdir(path) if isFile(path + "\\" + f)]
    except:
        pass
    return filelist
Example #22
0
def listFile(dir):
    filelist = listdir(dir)
    for file in filelist:
        relativePath = dir+file
        if (path.isfile(relativePath)):
            print("File: "+relativePath)
        if (path.isdir(relativePath)):
            print("Directory: "+relativePath)
def list(path):
    """ Returns list of all items within directory """
    alllist = []
    try:
        alllist = nt.listdir(path)
    except:
        pass
    return alllist
Example #24
0
def main():
    fileList = [
        x for x in listdir(r'.')
        if (x.lower().endswith(".csv") and not (x.lower().endswith(".log.csv"))
            )
    ]
    missingBoxfileList = [
        x for x in listdir(r'.') if x.lower().endswith(".txt")
    ]
    m = len(fileList)
    n = len(missingBoxfileList)

    missingBoxNums = []

    for i in range(n):
        boxNums = [
            line.strip()
            for line in open(missingBoxfileList[i], 'rU').readlines()
        ]
        missingBoxNums.extend(boxNums)
    missingBoxNums = set(missingBoxNums)

    with open(LogFile, 'wb') as f:
        writer = csv.writer(f)
        writer.writerow(('box number', 'old file name', 'new file name'))

        for i in range(m):
            boxNums = [
                line.strip().split(';')[11]
                for line in open(fileList[i], 'rU').readlines()
            ]
            boxNums = set(boxNums)
            outputMissingBox = list(missingBoxNums & boxNums)

            if len(outputMissingBox) > 0:
                mkdir()
                print 'Missing:', fileList[i]
                newFile = getFileName()
                shutil.copyfile(fileList[i], "./" + FolderName + "/" + newFile)

                for item in outputMissingBox:
                    writer.writerow((item, fileList[i], newFile))
            else:
                print 'No Missing:', fileList[i]
Example #25
0
def get_sbs_tests():
    not_run_tests = [ ]
    if sys.platform == "cli":
        import System
        if System.IntPtr.Size == 8:
            not_run_tests = ["sbs_exceptions.py"]	

    import nt
    return [x[:-3] for x in nt.listdir(compat_test_path) 
                   if x.startswith("sbs_") and x.endswith(".py") and (x.lower() not in not_run_tests)]
Example #26
0
def LoadCache():
    try:
        files = nt.listdir(nt.getcwd() + "\\cache")
    except:
        print "Error reading cache folder"
        return

    for f in files:
        if f.endswith(".jpeg"):
            cache[f[:-5]] = True
Example #27
0
def LoadCache():
    try:
        files = nt.listdir(nt.getcwd() + "\\cache")
    except:
        print "Error reading cache folder"
        return

    for f in files:
        if f.endswith(".jpeg"):
            cache[f[:-5]] = True
Example #28
0
def main(cpy_dir):
    global CPY_DIR
    global CPY_LIB_DIR
    
    CPY_DIR = cpy_dir
    CPY_LIB_DIR = cpy_dir + "\\Lib"  #E.g., C:\Python25\Lib
    
    path.append(CPY_LIB_DIR)
    path.insert(0, ".")


    print "------------------------------------------------------------------------"
    print "--PACKAGES"
    cwd = nt.getcwd()
    nt.chdir(CPY_LIB_DIR)

    for pack_name in nt.listdir(CPY_LIB_DIR):
        if not is_package(pack_name):
            continue
        #Importing all tests takes too long
        elif pack_name in ["test"]:
            continue
        
        check_package(pack_name)
    print

    nt.chdir(cwd)
    
    print "------------------------------------------------------------------------"
    print "--MODULES"
    
    for x in nt.listdir(CPY_LIB_DIR):
        if x.endswith(".py"):
            mod_name = x.split(".py", 1)[0]
        else:
            continue
            
        try:
            import_helper(mod_name)   
            log_ok(mod_name) 
            
        except Exception, e:
            log_broken(mod_name, e)
def listdir(path):
    """ Returns list of subdirectories of a given directory """
    dirlist = []
    try:
        dirlist = [
            f for f in nt.listdir(path)
            if not f.startswith(".") and isDir(path + "\\" + f)
        ]
    except:
        pass
    return dirlist
def PlayRandomCrushSound():
	SoundNamesDict = {'sfx\Explosions': ['collision1.wav', 'collision2.wav', 'collision3.wav', 'collision4.wav', 'collision5.wav', 'collision6.wav', 'collision7.wav', 'collision8.wav', 'explo1.wav', 'explo10.wav', 'explo11.wav', 'explo12.wav', 'explo13.wav', 'explo14.wav', 'explo15.wav', 'explo16.wav', 'explo17.wav', 'explo18.wav', 'explo19.wav', 'explo2.wav', 'explo3.wav', 'explo4.wav', 'explo5.wav', 'explo6.wav', 'explo7.wav', 'explo8.wav', 'explo9.wav', 'explo_flame_01.wav', 'explo_flame_02.wav', 'explo_flame_03.wav', 'explo_flame_04.wav', 'explo_flame_05.wav', 'explo_flame_06.wav', 'explo_flame_07.wav', 'explo_flame_08.wav', 'explo_flame_09.wav', 'explo_flame_10.wav', 'explo_large_01.wav', 'explo_large_02.wav', 'explo_large_03.wav', 'explo_large_04.wav', 'explo_large_05.wav', 'explo_large_06.wav', 'explo_large_07.wav', 'explo_large_08.wav'],
	 'scripts\Custom\NanoFXv2\ExplosionFX\Sfx\ExpCollision': ['Collision_Nano1.wav', 'Collision_Nano2.wav', 'Collision_Nano3.wav', 'Collision_Nano4.wav', 'Collision_Nano5.wav', 'Collision_Nano6.wav', 'Collision_Nano7.wav', 'Collision_Nano8.wav'],
	 'scripts\Custom\NanoFXv2\ExplosionFX\Sfx\ExpSmall': ['small 10.wav', 'small 11.wav', 'small 12.wav', 'small 13.wav', 'small 14.wav', 'small 15.wav', 'small 16.wav', 'small 17.wav', 'small 27.wav', 'small 28.wav', 'small 29.wav', 'small 30.wav', 'small 31.wav', 'small 33.wav', 'small 34.wav', 'small 35.wav', 'small 37.wav', 'small 38.wav', 'small 39.wav', 'small 40.wav', 'small 41.wav', 'small 47.wav', 'small 48.wav', 'small 49.wav'],
###	 'scripts\Custom\NanoFXv2\ExplosionFX\Sfx\ExpMed': ['med 01.wav', 'med 04.wav', 'med 05.wav', 'med 06.wav', 'med 07.wav', 'med 08.wav', 'med 11.wav', 'med 12.wav', 'med 13.wav', 'med 14.wav', 'med 16.wav', 'med 17.wav', 'med 18.wav', 'med 19.wav', 'med 26.wav', 'med 29.wav', 'med 30.wav', 'med 31.wav', 'med 32.wav', 'med 37.wav'],
	 'scripts\Custom\GravityFX\Sounds\Crush': ['ship_creak_low1.wav', 'ship_creak_low2.wav', 'ship_creak_low3.wav', 'ship_creak_low5.wav','ship_creak_medium1.wav', 'ship_creak_medium2.wav', 'ship_creak_medium3.wav', 'ship_creak_rattle1.wav']
}
	NCSpath = 'scripts\Custom\NanoFXv2\ExplosionFX\Sfx\ExpCollision'
	try:
		NanoCollisionsSounds = nt.listdir(NCSpath)
		for s in SoundNamesDict[NCSpath]:
			if s not in NanoCollisionsSounds:
				SoundNamesDict[NCSpath].remove(s)
	except:
		del SoundNamesDict[NCSpath]
	#########
	NESSpath = 'scripts\Custom\NanoFXv2\ExplosionFX\Sfx\ExpSmall'
	try:
		NanoExpSmallSounds = nt.listdir(NESSpath)
		for s in SoundNamesDict[NESSpath]:
			if s not in NanoExpSmallSounds:
				SoundNamesDict[NESSpath].remove(s)
	except:
		del SoundNamesDict[NESSpath]
	#########
	#NEMSpath = 'scripts\Custom\NanoFXv2\ExplosionFX\Sfx\ExpMed'
	#try:
	#	NanoExpMedSounds = nt.listdir(NEMSpath)
	#	for s in SoundNamesDict[NEMSpath]:
	#		if s not in NanoExpMedSounds:
	#			SoundNamesDict[NEMSpath].remove(s)
	#except:
	#	del SoundNamesDict[NEMSpath]
	#######################################################################
	dictindex = App.g_kSystemWrapper.GetRandomNumber(len(SoundNamesDict.keys()))
	soundpath = SoundNamesDict.keys()[dictindex]
	listindex = App.g_kSystemWrapper.GetRandomNumber(len(SoundNamesDict[soundpath]))
	soundName = SoundNamesDict[soundpath][listindex]
	pSound = PlaySound(soundpath+"\\"+soundName, "GravityFX-CrushSound-"+soundName)
	return pSound
Example #31
0
def DetermineMvamAi(pShip):
	#go through every new Mvam item in the Custom/Autoload/Mvam folder. Create new icons in the mvam menu
	debug(__name__ + ", DetermineMvamAi")
	straMvamList = nt.listdir("scripts\\Custom\\Autoload\\Mvam\\")

	#okay, we need a mock go through.. just so it'll spawn a pyc
	snkMockModule = []
	for t in range(len(straMvamList)):
		#mock mock mock mock
		straTempName = string.split(straMvamList[t], ".")
		snkMockModule.append(__import__ ("Custom.Autoload.Mvam." + straTempName[0]))

	#save some memory
	del snkMockModule

	#reload the list after the mock. Create new icons in the mvam menu
	straMvamList = nt.listdir("scripts\\Custom\\Autoload\\Mvam\\")

	#time to go through every mvam item. set up an int so i can modify it
	intListNum = len(straMvamList)

	#now that all pyc's are in place, lets do the real deal
	for i in range(intListNum):
		#okayyyy, make sure it's a pyc file, and make sure its not the init
		straTempName = string.split(straMvamList[i], ".")
		if ((straMvamList[i] == "__init__.pyc") or (straTempName[-1] == "py")):
			#bad file alert. redo the for loop and lower the counter
			i = i - 1
			intListNum = intListNum - 1

		# we succeeded! good file, so lets go
		else:
			straTempName = string.split(straMvamList[i], ".pyc")
			snkMvamModule = __import__ ("Custom.Autoload.Mvam." + straTempName[0])
			
			#alright, so determine if we're using the MvamAI or not...
			if (pShip.GetScript() == "ships." + snkMvamModule.ReturnMvamShips()[0]):
				return 1
				
	return 0
Example #32
0
def ClearCache():
    try:
        files = nt.listdir(nt.getcwd() + "\\cache")
    except:
        print "Error reading cache folder"
        return
        
    for i in range(0, len(files)):
        if files[i].find(".jpeg") > -1:
            try:
                nt.remove(nt.getcwd() + "\\cache\\" + files[i])
            except:
                x = None
Example #33
0
def get_sbs_tests():
    not_run_tests = []
    if sys.platform == "cli":
        import System
        if System.IntPtr.Size == 8:
            not_run_tests = ["sbs_exceptions.py"]

    import nt
    return [
        x[:-3] for x in nt.listdir(compat_test_path)
        if x.startswith("sbs_") and x.endswith(".py") and (
            x.lower() not in not_run_tests)
    ]
Example #34
0
def ClearCache():
    try:
        files = nt.listdir(nt.getcwd() + "\\cache")
    except:
        print "Error reading cache folder"
        return

    for i in range(0, len(files)):
        if files[i].find(".jpeg") > -1:
            try:
                nt.remove(nt.getcwd() + "\\cache\\" + files[i])
            except:
                x = None
	def DoMVAMMenus(oWork, ship, buttonType, uiHandler, self, raceShipList, fWidth, fHeight):
		if not ship.__dict__.get("bMvamMenu", 1):
			return oWork, 0

		import nt
		import string

		List = nt.listdir("scripts\\Custom\\Autoload\\Mvam\\")
		Mod = None
		for i in List:
			PosModName = string.split(i, ".")
			if len(PosModName) > 1 and PosModName[0] != "__init__":
				try:
					PosMod = __import__("Custom.Autoload.Mvam." + PosModName[0])
					if PosMod and PosMod.__dict__.has_key("MvamShips"):
						if ship.shipFile in PosMod.MvamShips:
							Mod = PosMod
							break
				except:
					continue

		if not Mod:
			return oWork, 0

		shipB = None
		foundShips = {}
		for race in raceShipList.keys():
			for dummyShip in raceShipList[race][0]:
				foundShips[race] = 1
				break

		raceList = foundShips.keys()
		raceList.sort()

		for race in raceList:
			shipB = findShip(Mod.MvamShips[0], raceShipList[race][1])
			if shipB:
				break
		if not shipB:
			return oWork, 0

		if not shipB.__dict__.get("bMvamMenu", 1):
			return oWork, 0

		oTemp = oWork.children.get(shipB.name, None)
		if not oTemp:
			oTemp = TreeNode(shipB.name, oShip = shipB)
			oTemp.bMVAM = 1
			oWork.children[shipB.name] = oTemp
		oWork = oTemp
		return oWork, ship.shipFile == shipB.shipFile
Example #36
0
def test_file_system_enumerations():
    '''
    http://msdn.microsoft.com/en-us/library/dd997370(VS.100).aspx
    
    Only minimal sanity tests should be needed. We already have 
    "for x in IEnumerable:..."-like tests elsewhere.
    '''
    import nt
    nt_dir   = nt.listdir(".")
    nt_dir.sort()
    
    enum_dir = [x[2:] for x in System.IO.Directory.EnumerateFileSystemEntries(".")]
    enum_dir.sort()
    AreEqual(nt_dir, enum_dir)
Example #37
0
 def initCache(self):
     xsdCache = {}
     for xsdFileName in listdir(Constant.CACHE_FOLDER + "xsd"):
         try:
             xsdFile = getXSDFileFromCache(
                 Constant.CACHE_FOLDER + "xsd//" + xsdFileName, None)
             xsdDict = xmltodict.parse(xsdFile)
             xsdDF = pandas.DataFrame(xsdDict["xs:schema"]["xs:element"])
             xsdDF.set_index("@id", inplace=True)
             xsdDF.head()
             xsdCache[xsdFileName] = xsdDF
             print(xsdFileName)
         except Exception as e:
             self.logger.exception(e)
     AbstractImporter.cacheDict["XSD_CACHE"] = xsdCache
Example #38
0
def test_rename():
    # normal test
    handler = open("oldnamefile.txt", "w")
    handler.close()
    str_old = "oldnamefile.txt"
    dst = "newnamefile.txt"
    nt.rename(str_old, dst)
    AreEqual(nt.listdir(nt.getcwd()).count(dst), 1)
    AreEqual(nt.listdir(nt.getcwd()).count(str_old), 0)
    nt.remove(dst)

    # the destination name is a directory
    handler = open("oldnamefile.txt", "w")
    handler.close()
    str_old = "oldnamefile.txt"
    dst = "newnamefile.txt"
    nt.mkdir(dst)
    AssertError(OSError, nt.rename, str_old, dst)
    nt.rmdir(dst)
    nt.remove(str_old)

    # the dst already exists
    handler1 = open("oldnamefile.txt", "w")
    handler1.close()
    handler2 = open("newnamefile.txt", "w")
    handler2.close()
    str_old = "oldnamefile.txt"
    dst = "newnamefile.txt"
    AssertError(OSError, nt.rename, str_old, dst)
    nt.remove(str_old)
    nt.remove(dst)

    # the source file specified does not exist
    str_old = "oldnamefile.txt"
    dst = "newnamefile.txt"
    AssertError(OSError, nt.rename, str_old, dst)
Example #39
0
def test_rename():
    # normal test
    handler = open("oldnamefile.txt","w")
    handler.close()
    str_old = "oldnamefile.txt"
    dst = "newnamefile.txt"
    nt.rename(str_old,dst)
    AreEqual(nt.listdir(nt.getcwd()).count(dst), 1)
    AreEqual(nt.listdir(nt.getcwd()).count(str_old), 0)
    nt.remove(dst)
    
    # the destination name is a directory
    handler = open("oldnamefile.txt","w")
    handler.close()
    str_old = "oldnamefile.txt"
    dst = "newnamefile.txt"
    nt.mkdir(dst)
    AssertError(OSError, nt.rename,str_old,dst)
    nt.rmdir(dst)
    nt.remove(str_old)
    
    # the dst already exists
    handler1 = open("oldnamefile.txt","w")
    handler1.close()
    handler2 = open("newnamefile.txt","w")
    handler2.close()
    str_old = "oldnamefile.txt"
    dst = "newnamefile.txt"
    AssertError(OSError, nt.rename,str_old,dst)
    nt.remove(str_old)
    nt.remove(dst)
    
    # the source file specified does not exist
    str_old = "oldnamefile.txt"
    dst = "newnamefile.txt"
    AssertError(OSError, nt.rename,str_old,dst)
def GetFileNames(sFolderPath, extension):
	import string
	sFileList = nt.listdir(sFolderPath)

	retList = []

	for i in sFileList:
		s = string.split(string.lower(i), '.')
		ext = s[-1]

		if extension == ext:
			retList.append(i)

	retList.sort()
	return retList
	def CreateIconGroup(self, name, folder):
		if name in self.IconGroupList:
			raise NameError, "Can't create icon group with name "+name+", there's already an icon group created with this name."
			return
		IconGroup = App.g_kIconManager.CreateIconGroup(name)
		FileList = nt.listdir(folder)
		index = 0
		for File in FileList:
			sExt = string.split(File, ".")[-1]
			if sExt == "tga":
				Texture = IconGroup.LoadIconTexture(folder+"/"+File)
				IconGroup.SetIconLocation(index, Texture, 0, 0, 128, 128)
				index = index+1
		App.g_kIconManager.AddIconGroup(IconGroup)
		App.g_kIconManager.RegisterIconGroup(name, name, name)
		self.IconGroupList.append(name)
	def AddFolder(self, sFolder, sGroup):
		if not self.dStates.has_key(sGroup):
			self.dStates[sGroup] = []
		try:
			lFolder = nt.listdir(sFolder)
			for i in lFolder:
				sName = sFolder + '/' + i

				s = string.split(i, '.')
				name = string.join(s[:-1], '.')
				ext = string.lower(s[-1])
				if ext == 'mp3':
					self.dMain[sName] = name
					self.dStates[sGroup].append(name)
		except:
			pass
def test_file_system_enumerations():
    '''
    http://msdn.microsoft.com/en-us/library/dd997370(VS.100).aspx
    
    Only minimal sanity tests should be needed. We already have 
    "for x in IEnumerable:..."-like tests elsewhere.
    '''
    import nt
    nt_dir = nt.listdir(".")
    nt_dir.sort()

    enum_dir = [
        x[2:] for x in System.IO.Directory.EnumerateFileSystemEntries(".")
    ]
    enum_dir.sort()
    AreEqual(nt_dir, enum_dir)
Example #44
0
def test_remove():
    # remove an existing file
    handler = open("create_test_file.txt","w")
    handler.close()
    path1 = nt.getcwd()
    nt.remove(path1+'\\create_test_file.txt')
    AreEqual(nt.listdir(nt.getcwd()).count('create_test_file.txt'), 0)
    
    AssertErrorWithNumber(OSError, 2, nt.remove, path1+'\\create_test_file2.txt')
    AssertErrorWithNumber(OSError, 2, nt.unlink, path1+'\\create_test_file2.txt')
    AssertErrorWithNumber(OSError, 22, nt.remove, path1+'\\create_test_file?.txt')
    AssertErrorWithNumber(OSError, 22, nt.unlink, path1+'\\create_test_file?.txt')
    
    # the path is a type other than string
    AssertError(TypeError, nt.remove, 1)
    AssertError(TypeError, nt.remove, True)
    AssertError(TypeError, nt.remove, None)
Example #45
0
def test_remove():
    # remove an existing file
    handler = open("create_test_file.txt","w")
    handler.close()
    path1 = nt.getcwd()
    nt.remove(path1+'\\create_test_file.txt')
    AreEqual(nt.listdir(nt.getcwd()).count('create_test_file.txt'), 0)
    
    AssertErrorWithNumber(OSError, 2, nt.remove, path1+'\\create_test_file2.txt')
    AssertErrorWithNumber(OSError, 2, nt.unlink, path1+'\\create_test_file2.txt')
    AssertErrorWithNumber(OSError, 22, nt.remove, path1+'\\create_test_file?.txt')
    AssertErrorWithNumber(OSError, 22, nt.unlink, path1+'\\create_test_file?.txt')
    
    # the path is a type other than string
    AssertError(TypeError, nt.remove, 1)
    AssertError(TypeError, nt.remove, True)
    AssertError(TypeError, nt.remove, None)
Example #46
0
def get_mod_names(filename):
    '''
    Returns a list of all Python modules and subpackages in the same location 
    as filename w/o their ".py" extension.
    '''
    directory = filename
    
    if file_exists(filename):
        directory = get_directory_name(filename)
    else:
        raise Exception("%s does not exist!" % (str(filename)))
    
    #Only look at files with the .py extension and directories.    
    ret_val = [x.rsplit(".py")[0] for x in nt.listdir(directory) if (x.endswith(".py") or "." not in x) \
               and x.lower()!="__init__.py"]
    
    return ret_val
Example #47
0
def get_mod_names(filename):
    '''
    Returns a list of all Python modules and subpackages in the same location 
    as filename w/o their ".py" extension.
    '''
    directory = filename
    
    if file_exists(filename):
        directory = get_directory_name(filename)
    else:
        raise Exception("%s does not exist!" % (str(filename)))
    
    #Only look at files with the .py extension and directories.    
    ret_val = [x.rsplit(".py")[0] for x in nt.listdir(directory) if (x.endswith(".py") or "." not in x) \
               and x.lower()!="__init__.py"]
    
    return ret_val
def test_cp12009():
    import nt
    import shutil

    dir1 = "temp_test_stdmodules_dir"
    dir2 = dir1 + "2"

    nt.mkdir(dir1)
    f = open(dir1 + r"\stuff.txt", "w")
    f.close()

    try:
        shutil.copytree(dir1, dir2)
        Assert("stuff.txt" in nt.listdir(dir2))
    finally:
        for t_dir in [dir1, dir2]:
            nt.unlink(t_dir + r"\stuff.txt")
            nt.rmdir(t_dir)
Example #49
0
def test_cp12009():
    import nt
    import shutil
    
    dir1 = "temp_test_stdmodules_dir"
    dir2 = dir1 + "2"
    
    nt.mkdir(dir1)
    f = open(dir1 + r"\stuff.txt", "w")
    f.close()
    
    try:
        shutil.copytree(dir1, dir2)
        Assert("stuff.txt" in nt.listdir(dir2))
    finally:
        for t_dir in [dir1, dir2]:
            nt.unlink(t_dir + r"\stuff.txt")
            nt.rmdir(t_dir)
Example #50
0
def CreateLoadMenuChilds(pMenu):
        global lMissions
        list = nt.listdir(MISSIONS_SAVE_DIR)
        list.sort()
        i = 0
        
        for plugin in list:
                s = string.split(plugin, '.')
                sExtension = s[-1]
                sSaveName = string.join(s[:-1], '.')

                if sSaveName != "__init__" and sExtension == "py":
                        sSaveModule = "BCROOT." + string.replace(MISSIONS_SAVE_DIR, '/', '.') + sSaveName
                        sSaveModule = string.replace(sSaveModule, "BCROOT.scripts.", "")
                        
                        lMissions.append(sSaveModule)
                        Libs.LibEngineering.CreateMenuButton(sSaveName, "XO", __name__ + ".Load", i, pMenu, "append")
                        i = i + 1
Example #51
0
def check_package(package_name):
    '''
    Checks all subpackages and modules in the package_name package.
    '''
    cwd = nt.getcwd()

    if cwd == CPY_LIB_DIR:
        root_name = package_name
    else:
        root_name = cwd.split(CPY_DIR + "\\Lib\\")[1].replace(
            "\\", ".") + "." + package_name

    #First check that the root package can be imported
    try:
        import_helper(package_name)
        log_ok(root_name)

    except (Exception, SystemExit) as e:
        log_broken(root_name, e)

        # no sense continuing
        return

    #Next examine subpackages and modules
    nt.chdir(cwd + "\\" + package_name)

    for x in nt.listdir("."):
        if x.endswith(".py") and x not in ("__init__.py", '__main__.py'):
            x = x.split(".py", 1)[0]
            mod_name = nt.getcwd().split(CPY_DIR + "\\Lib\\")[1] + "\\" + x
            mod_name = mod_name.replace("\\", ".")

            try:
                import_helper(mod_name)
                log_ok(mod_name)

            except (Exception, SystemExit) as e:
                log_broken(mod_name, e)

        elif is_package(x) and not x.startswith('test'):
            check_package(x)

    nt.chdir(cwd)
Example #52
0
def ImportTechs(dir="scripts\\Custom\\Tech"):
    import nt
    import string
    global pluginsLoaded

    list = nt.listdir(dir)

    for tech in list:
        s = string.split(tech, ".")

        if len(s) <= 1:
            continue

        extension = s[-1]
        techFile = string.join(s[:-1], ".")

        if ((extension == "pyc" or extension == "py")
                and not pluginsLoaded.has_key(techFile)):
            pluginsLoaded[techFile] = 1  # save, so we don't load twice.
            pModule = __import__("Custom.Tech." + techFile)
            if hasattr(pModule, 'Setup'):
                pModule.Setup()
Example #53
0
def is_package(dir_name):
    '''
    Returns True if dir_name is actually a Python package in the current
    working directory.
    '''
    #*.py, *.pyd, etc
    if "." in dir_name:
        return False        
    
    #Make sure it exists
    try:
        if not nt.stat(dir_name): return False
    except:
        return False
    
    #Make sure it has an __init__.py
    try:
        if "__init__.py" not in nt.listdir(nt.getcwd() + "\\" + dir_name):
            return False
    except:
        return False
        
    return True
def LoadExtraPlugins(dir='scripts\\Custom\\Carriers\\'):
    import nt
    import string

    list = nt.listdir(dir)
    list.sort()

    dotPrefix = string.join(string.split(dir, '\\')[1:], '.')

    for plugin in list:
        s = string.split(plugin, '.')
        pluginFile = ''
        # We don't want to accidentally load the wrong ship.
        # Indexing by -1 lets us be sure we're grabbing the extension. -Dasher42
        if len(s) > 1 and \
           ( s[-1] == 'pyc' or s[-1] == 'py'):
            pluginFile = s[0]
        else:
            continue

        try:
            pModule = __import__(dotPrefix + pluginFile)
        except ImportError:
            pass
Example #55
0
def getDataSet():
    files = (listdir("./data/Cleaned_dataset"))
    for file in files:
        with open("./data/Cleaned_dataset/" + file) as f:
            gameinfo = {}
            game = json.load(f)
            if game['genres'] != [] and (game['id'] is not None or game['id']
                                         != '') and (game['name'] is not None
                                                     or game['name'] != ''):
                if game['description_raw'] is not None:
                    description = game['description_raw']
                elif game['description'] is not None:
                    description = game['description']

                if description != '':
                    gameinfo['id'] = game['id']
                    gameinfo['name'] = cleanName(game['name'])
                    gameinfo['description'] = cleanDescription(description)
                    gameinfo['genres'] = cleanGenres(game['genres'])

                    if gameinfo['name'] != '' and gameinfo[
                            'description'] != '' and gameinfo['genres'] != []:
                        print(gameinfo['id'])
                        cleanCSVrow(gameinfo)
Example #56
0
Cleans a directory full of tests.

USAGE:
    ipy cleantests.py C:\...\IronPython\Tests
'''
from sys import argv
import nt
import re

#--GLOBALS---------------------------------------------------------------------
DEBUG = False

TEST_DIR = argv[1]
THIS_MOD = __file__.rsplit("\\", 1)[1]
TESTS = [
    x for x in nt.listdir(TEST_DIR) if x.endswith(".py") and x != THIS_MOD
]
if DEBUG:
    print "TESTS:", TESTS

TF_DIR = nt.environ["DevEnvDir"] + r"\tf"
TFPT_DIR = nt.environ["DLR_ROOT"] + r"\Util\tfpt\tfpt.exe"


#--FUNCTIONS-------------------------------------------------------------------
def apply_filters(lines):
    for filter in [strip_ws, tabs_are_bad]:
        filter(lines)


def strip_ws(lines):
Example #57
0
The variables sm, and hc are pre-assigned to the ScanMaster,
and EDMHardwareControl Controller objects respectively. You can call any of
these objects methods, for example: sm.AcquireAndWait(5). Look at the c#
code to see which remote methods are available. You can use any Python code
you like to script these calls.

You can run scripts in the ScanMasterScripts directory with the command run(i),
where i is the script's index number (below). For this to work the script
must have a run_script() function defined somewhere. You'd be unwise to
try and run more than one script in a session with this method!

Available scripts:''')

# script shortcuts
import nt
pp = Path.GetFullPath("..\\SMScripts")
files = nt.listdir(pp)
scriptsToLoad = [
    e for e in files
    if e.EndsWith(".py") and e != "sm_init.py" and e != "winforms.py"
]
for i in range(len(scriptsToLoad)):
    print str(i) + ": " + scriptsToLoad[i]
print ""


def run(i):
    global run_script
    execfile(scriptsToLoad[i], globals())
    run_script()
Example #58
0
    "zlib",  #CodePlex 2590
    "_subprocess",
    "msvcrt",
]

#Most of these are standard *.py modules which IronPython overrides for one
#reason or another
OVERRIDDEN_MODULES = [
    "copy_reg",
    "socket",
]

MODULES = BUILTIN_MODULES + OVERRIDDEN_MODULES

#Add any extension modules found in DLLs or Lib
for x in nt.listdir(CPY_DIR + "\\DLLs"):
    if x.endswith(".pyd"):
        MODULES.append(x.split(".pyd", 1)[0])

for x in nt.listdir(CPY_DIR + "\\Lib"):
    if x.endswith(".pyd"):
        MODULES.append(x.split(".pyd", 1)[0])

#Modules we don't implement found in DLLs or Lib and
#the reason why:
# bz2 - TODO?
# pyexpat - CodePlex 20023
# unicodedata - CodePlex 21404
# winsound - CodePlex 21405
# _bsddb - CodePlex 362
# _ctypes - CodePlex 374