示例#1
1
def sort_choose():
    '''allows user to choose folder to sort
    '''
    msg = "Please select the folder to sort: "
    title = "Folder to sort..."
    download_dir = easygui.diropenbox(msg, title, 'C:\\')
    return download_dir
def main():
	# Check to see if we have all the information we need
	try:
		#directory = unicode(sys.argv[1])
		directory = sys.argv[1]
		template = sys.argv[2]
	except IndexError:
		try:
			import easygui
			
			# get directory from user
			directory = None
			while not directory:
				directory = easygui.diropenbox('Where are the files?')
			
			# get template from user
			template = None
			while not template:
				template = easygui.choicebox('What template do you want?', choices=os.listdir(absolute_path('templates')))
		except ImportError:
			sys.stderr.write("Usage: " + sys.argv[0] + " <directory> <template>\n")
			exit()
	
	root = Folder(directory)
	root.scan()
	
	env = Environment(loader=PackageLoader('bxt_description_generator', 'templates'))
	env.filters['cleanify'] = cleanify
	template = env.get_template(template)
	output = template.render(root=root).encode("utf-8")
	
	try:
		easygui.codebox(text=output)
	except NameError:
		print output
示例#3
0
文件: __init__.py 项目: Uberi/autom
def dialog_folder_select(title = "Choose a folder", initial_shown_glob = None):
    """
    Show a folder selection dialog with title `title`, initially showing files matching the glob `initial_shown_glob`.
    
    Returns the selected path.
    """
    return easygui.diropenbox(None, str(title), str(initial_shown_glob))
 def _check_target_dir(self):
     """
     GUI: show GUI for selecting the target folder when there is no given "--dest-dir" argument.
     """
     if not self.dest_dir:
         title = 'Select Target Folder'
         self.dest_dir = easygui.diropenbox(title=title, default=os.getcwd())
示例#5
0
    def dir_open(self):
        directorio = eg.diropenbox(msg="Abrir directorio:",
                                   title="Control: diropenbox",
                                   default='/home/antonio')

        eg.msgbox(directorio, "diropenbox", ok_button="Continuar")
        return directorio
示例#6
0
def dlTutAll():
  msg = 'This will download all available tutorials as separate files.\nDo you wish to continue?'
  title = 'Download All?'

  if eg.ccbox(msg, title, image=imgTC):
    msg = 'Choose where you want the downloads to be kept:'
    path = eg.diropenbox(msg, default=os.getcwd() + os.sep + os.pardir)

    maker.makePDFfromList(tutList, path)
示例#7
0
def get_update_list(base_path=''):
    if base_path == '':
        base_path = eg.diropenbox(msg='Select directory to crawl',default ='/Volumes/Data/Work/Research/BodenheimerCode/Code_for_Kozai/outputs/2013/')         
        #    result = []
    for (path,dirs,files) in os.walk(base_path):
        if 'full_run_output.txt' in files:
            update_index_main(path)
            #      result.append(path)    
    return 0
def find_lst_files():
    src_dir = easygui.diropenbox(default=r"C:\Users\lws\Desktop\pcgen installers\pcgen\data")
    lst_files = []
    for root, dirs, files in os.walk(src_dir):
        for f in files:
            fn, ext = os.path.splitext(f)
            if ext == ".lst":
                full_name = os.path.join(root, f)
                lst_files.append(full_name)
    return lst_files
示例#9
0
def main():							# TODO allow local picture file input
    url = easygui.enterbox(msg='Image URL: ', title='Input URL', default='', strip=True)
    path = easygui.diropenbox(msg='Image Save Path : ', title="Save Path", default='')
    if not valid_url(url):
        print "Error: Not valid URL"
    start = time.time()
    links = image_lookup(url)   # search for similar
    image_scrape(links, path)         # save results
    end = time.time()   # Debug runtime
    print "Search Time: " + str(end - start) + ' seconds'
	def uifindinfile(self):
		import os;
		initpath=os.path.abspath(os.path.curdir);
		dir2search=easygui.diropenbox("Choose the directory","Finding string in files",initpath);
		if dir2search is not None:
			str2find=easygui.enterbox("string 2 find?","Finding string in files","print");
			if str2find is not None:
				found=findindir(dir2search,str2find);
				for record in found:
					self.print_(record);
示例#11
0
def renamer(dirPath=None,trans=dict(ft=[0,90],bk=[1,-90],rt=[2,0],lf=[3,180],up=[4,0],dn=[5,180])):
    if dirPath is None:
        dirPath=easygui.diropenbox()
        
    fileList=glob.glob(dirPath+'/*.tga')
    for fn in fileList:
        ori=fn.split('/')[-1].split('.tga')[0].split('_')[-1]
        fn.split('.tga')
        PIL.Image.open(fn).rotate(trans[ori][1]).save(fn.split('.tga')[0][:-2]+str(trans[ori][0])+'.tga')

    return fn.split('.tga')[0][:-2]++'#.tga'
示例#12
0
文件: gui1.py 项目: rockman507/tfi_py
def get_directory():
    path = diropenbox("Pick directory to process", default=r"c:\phase")
    # Avoids a crash if the directory window is closed without choosing a directory
    try:
        # Unwrap call is a CMD.exe call so spaces in path name will crash the call
        # GetShortPathName returns 8.3 compatable file name
        path = win32api.GetShortPathName(path)
        # path = path_convert(path)
        path_entry.set(path)
    except:
        pass
示例#13
0
def get_dir():
    dir_path = None
    while(dir_path == None):
        dir_path = easygui.diropenbox(msg="Choose directory",title="Choose directory",default=DEFAULT_DIRECTORY)
        if dir_path == None:
            if easygui.ccbox("Are you sure that you want to stop the scrip's execution?", "Please confirm"):
                sys.exit(0)
            else:
                continue
    print("Chosen directory: %s" % dir_path)
    return dir_path
示例#14
0
def searchExt(download_dir):
    ext_counts = fileCheck(download_dir)
    ext_dests = {}
    for k, v in ext_counts.items():
        while True:
            msg = 'Choose the destination for the {1} files ending in {0}: '.format(k, v)
            title = 'File Sorter v1.0'
            dest_path = easygui.diropenbox(msg, title, 'C:\\')
            ext_dests[k] = dest_path
            break

    return ext_dests
示例#15
0
def userOutdir():
    '''
    Asks the user to point to a directory indicating where the output file should
    be created. Returns a string path to the directory if given. If the user
    chooses to cancel, the program closes. The output is not checked for any
    form of vallidty, as it only becomes a default in a later window that the
    user can overwrite: the error checking is performed then.
    '''
    dirbox = eg.diropenbox(title="Select output directory for map")
    if dirbox is None:
        cancel()
    return dirbox
def findExecutable(execname,msg=''):
    '''
    @return full path to a command using the shell's which function
    '''
    execpath=subprocess.Popen(["which", execname], stdout=subprocess.PIPE).communicate()[0].rstrip()
    if execpath == '' :
        if msg == '' :
            msg="Locate the directory containing program "+execname
        execdir = easygui.diropenbox(msg=msg)
        execpath = os.path.join(execdir,execname)
        if os.path.exists(execpath) :
            return execpath
        else :
            sys.exit('Unable to locate '+execname+' in directory '+execdir)
    else : return execpath
示例#17
0
    def __init__(self,*args):

        if not args:
            # popup a windows and ask for it!
            path_to_watch=easygui.diropenbox()
            file_regex=easygui.textbox(msg='Enter Regular Expression', title = 'regex')
            file_regex=file_regex[:-1]
        else:
            path_to_watch=args[0]
            file_regex=args[1]
            
        # store it in the instance..
        self.file_regex = file_regex
        self.path_to_watch = path_to_watch
        self.before = dict ([(f, None) for f in os.listdir (self.path_to_watch)])
示例#18
0
def main(inputFile=None):
    if(inputFile is not None):
        myarq = inputFile
    else:
        myarq = eg.fileopenbox(msg="Enter the latex file to be converted",
               title="Open tex file", default='*', filetypes=["*.tex"])

    msg = """
The file:
         %s
will be used to generate the .doc,.html and .pdf files.
Do you want to continue ?""" % myarq

    if eg.ccbox(msg, 'Start Process'):
        pass
    else:
        sys.exit(0)

    msg = '''If you have some figures in pdf it will be necessary convert these
    images in png files? Have you somo pdf images
'''
    if eg.ccbox(msg, title='Convert pdf figures to png',
                choices=('Yes', 'No')):
        figuresDir = eg.diropenbox(msg='Open the Figure Directory',
                                     title='Figure Directory')
    else:
        pass

    changeDir(myarq)

    depurarFicheiro(myarq)

    cleantemp1()

    bibAndHtml()

    grafiAjust()

    docGen()

    cleantemp2()

    changeFinalName(myarq)

    loc = '/'.join(myarq.split('/')[:-1])

    eg.msgbox("The .doc,.html and .pdf are in the folder:\n %s/ " % loc)
示例#19
0
文件: gui.py 项目: Aki92/mp3fm
    def folder_choice(self):
        msg = "\t     Welcome to MP3fm!\n\n Select the Songs \
Folder containing Bulk of Songs"
        eg.msgbox(msg, 'MP3fm')
        """ Opens folder choice box and confirm it using index box"""
        fname = eg.diropenbox('Songs Folder', 'Choose', os.getcwd())
        if fname is None:
            exit(0)
        fn = fname[fname.rfind('/')+1:]
        msg = 'Choosen Songs folder:: \t%s' % fn
        options = ('Continue', 'Choose Again', 'Quit')
        ch = eg.indexbox(msg, 'MP3fm', options)
        if ch == 0:
            self.folder = fname
            self.user_choice()
        elif ch == 1:
            self.folder_choice()
        else:
            exit(0)
        return (self.folder, self.choice, self.tag)
示例#20
0
def promptExtAndDest():
    '''Prompt for a destination to put each file by extension
    '''

    ext_dests = {}
    while True:
        msg = 'Input file extension (format- .ext) (or type \'done\'): '
        title = 'File Sorter v1.0'
        ext = easygui.enterbox(msg, title)
        if ext == 'done': break
        if ext == '': break
        if ext[0] != '.': ext = '.' + ext

        while True:
            msg = 'Where do you want to put {} files: '.format(ext)
            title = 'File Sorter v1.0'
            dest_path = easygui.diropenbox(msg, title, 'C:\\')
            ext_dests[ext] = dest_path
            break

    return ext_dests
示例#21
0
def main():
	dir_name = str(easygui.diropenbox(title="please choose contacts folder"))
	dict = {
			"01([2|7|8]{1})([0-9]{7})(\r|\n)$": r"012\1\2\3",
			"01([0|9|6]{1})([0-9]{7})(\r|\n)$": r"010\1\2\3",
			"01([1|4]{1})([0-9]{7})(\r|\n)$": r"011\1\2\3",
			"0150([0-9]{7})(\r|\n)$": r"0120\1\2",
			"0151([0-9]{7})(\r|\n)$": r"0101\1\2",
			"0152([0-9]{7})(\r|\n)$": r"0112\1\2"
			}
	if dir_name != 'None' :
		msg = "Are you sure you wanna update cellphone numbers in " + dir_name
		title = "Please Confirm"
		if easygui.ccbox(msg, title):
			for key in dict:
				replace_vcf(key, dict[key], dir_name)
			easygui.msgbox("Contacts have been updated successfully :) ")
		else:
			sys.exit(0)
	else:
		sys.exit(0)
示例#22
0
    def enter_settings(self):
        s1 = "What is your local time zone? (i.e. Australia/Perth.) Used to determine the UTC/GMT time for file naming purposes."
        self.timezone_name = easygui.choicebox(s1,
                                               "Choose local time zone",
                                               pytz.common_timezones)

        s2 = "Enable debug mode? (Displays very detailed program execution information on screen.)"
        a = easygui.buttonbox(s2,"Debug mode?",("Normal mode (recommended)","Debug mode (experts only)"))
        self.debug_mode = True if a.lower().startswith("debug") else False

        s3 = "Save emails older than X days: (default 60 days; 0 for all emails regardless of age.)"
        self.days_old = easygui.integerbox(s3,"Email age?",default=60,
                                           lowerbound=0, upperbound=99999999)

        self.dest_dir = easygui.diropenbox("Pick a folder to save the email .msg files to.",
                                           "Choose backup destination",
                                           "%HOMEPATH%")

        b = easygui.ynbox("Apply 'Saved as MSG' tag to emails that are saved?",
                          title="Mark emails as saved?",
                          choices=("Yes (recommended)","No (experts only)"))
        self.mark_as_saved = bool(b)
    def newDownload(self):
        msg         = "Enter the download information"
        title       = self.title
        fieldNames  = ["SoundCloud Profile URL"]
        fieldValues = ['http://www.soundcloud.com/']  # we start with blanks for the values
        fieldValues = eg.multenterbox(msg,title, fieldNames, values=fieldValues)
        
        
        # make sure that none of the fields was left blank
        while 1:  # do forever, until we find acceptable values and break out
            if fieldValues == None: 
                break
            errmsg = ""
            
            # look for errors in the returned values
            for i in range(len(fieldNames)):
                if fieldValues[i].strip() == "" :
                    errmsg = errmsg + ('"%s" is a required field.\n\n' % fieldNames[i])
                if i == 0:
                    self.url = fieldValues[0]
                   
            # Designate save folder as PATH
            path = eg.diropenbox(msg="Select a folder to save the mp3 files to", title=self.title)
            self.downloader = scLikesDownloader.downloader(fieldValues[0], path)

            if not self.downloader:
                errmsg = "Invalid Path or SoundCloud Profile URL.  Please try again."
            elif True:
                eg.msgbox(msg='Press start to begin retrieving this user\'s likes (This may take a while)', title=self.title, ok_button='Start Retrieval')
                favorites = self.downloader.trackList()
                eg.msgbox(msg='We have all their favorites.  There are ' + str(len(favorites)) + ' to download.  Press start to begin download', title=self.title, ok_button='Start Download')
                reply = self.downloadFavs(favorites)
                eg.msgbox(msg='Completed!  Downloaded ' + str(reply['numFiles']) + ' in ' + str(reply['delta']) + ' seconds', title=self.title, ok_button='Main menu')
                break
            else:
                # show the box again, with the errmsg as the message    
                fieldValues = eg.multenterbox(errmsg, title, fieldNames, fieldValues)
        self.mainMenu()
示例#24
0
def setUnlabeledFolder():
	global unlabeled_folder
	unlabeled_folder = os.path.abspath(easygui.diropenbox())
	labelUnlabeledText.set(unlabeled_folder)
示例#25
0
    ans = raw_input("Y/N ?")
    if ans == "Y":
        print "training svm "
        svm_trainer(data, labels)
        print "svm training completed"
        print "training Decision Tree"
        DecisionTreeTrainer(data, labels)
        print "decision tree training completed"
        print "trainig random forest"
        RandomForestTrainer(data, labels)
        print "Random Forest Training completed"
        exit()
except Exception as E:
    print E
    print "need to read files"
path = easygui.diropenbox("select the root of database")
naming = []
labels = []
locations = []
data = []
k = 0
persons = os.listdir(path)
try:
    persons = map(int, persons)
except Exception as E:
    print E
persons = sorted(persons)
persons = map(str, persons)
for folders in persons:  #loop over all the persons
    folder = path + '/' + folders
    naming.append(folders)
##Created January 2019
##Author: Clara Bird ([email protected]), Duke MarineUAS
##---------------------------------------

import pandas as pd
import numpy as np
import os, sys
import PIL.Image
from datetime import datetime
from datetime import timedelta
import easygui

print(sys.version)
print(sys.path)
#import .csv with IMG and GPStime
scriptWS = easygui.diropenbox(msg="select Time Corrections folder")
imageFold = os.path.join(scriptWS, "images")

csv = os.path.join(scriptWS, "GPStime_images.csv")
df1 = pd.read_csv(csv, sep=',')

imgnames = []
imgtimes = []
addsub = []
img_files = os.listdir(imageFold)
for img in img_files:
    #print(img)
    if img.endswith('.JPG'):
        imgnames += [img]
        imgF = os.path.join(imageFold, img)
        image = PIL.Image.open(imgF)
示例#27
0
文件: Lab04.py 项目: Jaren831/usafa
                }}
                google.maps.event.addDomListener(window, 'load', show_map);
            </script>
        """.format(centerLat=centerLat, centerLon=centerLon,
                   markersCode=markersCode)


# if __name__ == "__main__":
#     main()

if __name__ == "__main__":
    map = Map()
    start = easygui.buttonbox(msg="Picture or Folder?", title="Welcome to Where's My Ex! No you don't have a problem.!",
                              choices=["Upload Directory", "Upload Picture", "Cancel"])
    if start == "Upload Directory":
        file_search = easygui.diropenbox()
        directory_list = os.listdir(file_search)
        for file in directory_list:
            if imghdr.what(file) == "gif" or "jpeg":
                map.add_point(str(get_exif(file)))
            else:
                print("No image detected")
                sys.exit()
    elif start == "Upload Picture":
        file = easygui.fileopenbox(default="./data/")
        if imghdr.what(file) == 'gif' or 'jpeg':
            map.add_point(get_exif(str(file)))

        else:
            print("No image detected")
            sys.exit()
def main():
    x = 15  #Number of seconds for the wait timers
    #url for the election results
    url = "https://results.enr.clarityelections.com/GA/91639/Web02-state.221451/#/access-to-races"

    #Directory for to download the data
    home_dir = eg.diropenbox('', 'Choose download destination directory')

    #List of all the counties in the state
    all_counties = [
        'Appling', 'Atkinson', 'Bacon', 'Baker', 'Baldwin', 'Banks', 'Barrow',
        'Bartow', 'Ben_Hill', 'Berrien', 'Bibb', 'Bleckley', 'Brantley',
        'Brooks', 'Bryan', 'Bulloch', 'Burke', 'Butts', 'Calhoun', 'Camden',
        'Candler', 'Carroll', 'Catoosa', 'Charlton', 'Chatham',
        'Chattahoochee', 'Chattooga', 'Cherokee', 'Clarke', 'Clay', 'Clayton',
        'Clinch', 'Cobb', 'Coffee', 'Colquitt', 'Columbia', 'Cook', 'Coweta',
        'Crawford', 'Crisp', 'Dade', 'Dawson', 'Decatur', 'DeKalb', 'Dodge',
        'Dooly', 'Dougherty', 'Douglas', 'Early', 'Echols', 'Effingham',
        'Elbert', 'Emanuel', 'Evans', 'Fannin', 'Fayette', 'Floyd', 'Forsyth',
        'Franklin', 'Fulton', 'Gilmer', 'Glascock', 'Glynn', 'Gordon', 'Grady',
        'Greene', 'Gwinnett', 'Habersham', 'Hall', 'Hancock', 'Haralson',
        'Harris', 'Hart', 'Heard', 'Henry', 'Houston', 'Irwin', 'Jackson',
        'Jasper', 'Jeff_Davis', 'Jefferson', 'Jenkins', 'Johnson', 'Jones',
        'Lamar', 'Lanier', 'Laurens', 'Lee', 'Liberty', 'Lincoln', 'Long',
        'Lowndes', 'Lumpkin', 'Macon', 'Madison', 'Marion', 'McDuffie',
        'McIntosh', 'Meriwether', 'Miller', 'Mitchell', 'Monroe', 'Montgomery',
        'Morgan', 'Murray', 'Muscogee', 'Newton', 'Oconee', 'Oglethorpe',
        'Paulding', 'Peach', 'Pickens', 'Pierce', 'Pike', 'Polk', 'Pulaski',
        'Putnam', 'Quitman', 'Rabun', 'Randolph', 'Richmond', 'Rockdale',
        'Schley', 'Screven', 'Seminole', 'Spalding', 'Stephens', 'Stewart',
        'Sumter', 'Talbot', 'Taliaferro', 'Tattnall', 'Taylor', 'Telfair',
        'Terrell', 'Thomas', 'Tift', 'Toombs', 'Towns', 'Treutlen', 'Troup',
        'Turner', 'Twiggs', 'Union', 'Upson', 'Walker', 'Walton', 'Ware',
        'Warren', 'Washington', 'Wayne', 'Webster', 'Wheeler', 'White',
        'Whitfield', 'Wilcox', 'Wilkes', 'Wilkinson', 'Worth'
    ]

    #Make sure each county has its own directory
    check_directories(all_counties, home_dir)
    #See if any of the data have already been downloaded
    #(useful if some counties fail and you want to retry later)
    counties = check_for_downloads(all_counties, home_dir)
    if counties == all_counties:  #No data has been scraped already
        print('Scraping data for all counties')
    elif len(counties) != 0:  #Some counties have been done, but not all
        print('Scraping data for the following counties: ')
        print(counties)
    else:  #All data have already been downloaded
        print('The data for all counties have already been scraped')

    while len(counties) > 0:
        driver = webdriver.Firefox()  #We're using firefox as our browser
        driver.implicitly_wait(
            x)  #This should let the page load before doing anything
        driver.get(url)  #Open the page with the results

        wait(
            x
        )  #The implicit wait isn't enough. This makes sure the page loads before we do anything

        for county in counties:
            scrape_county(driver, county, x,
                          home_dir)  #Download data for each county
        handles = driver.window_handles  #What tabs are open?
        driver.switch_to.window(
            handles[0])  #Switch to what should be the only tab left
        driver.close()  #Close the window because (hopefully) we're done

        counties = check_for_downloads(
            all_counties, home_dir)  #Let's see if we're done or not
        done = False
        #If none or only some of the data were downloaded, the user is prompted to try what wasn't done
        #If all of the data were downloaded, we're done!
        if counties == all_counties:
            done_check = input(
                'Something went wrong. Would you like to try again? (Y/N)')
            if done_check == 'n' or done_check == 'N':
                done = True
        elif len(counties) != 0:
            done_check = input(
                "We didn't get it all the first time. Would you like to try again for the following counties? (Y/N) \n{}"
                .format(counties))
            if done_check == 'n' or done_check == 'N':
                done = True
        else:
            print('The data for all counties are all scraped!')
            done = True

        if done:
            break
import numpy as np
import tables
import easygui
import sys
import os
#import matplotlib
#matplotlib.use('Agg')
import matplotlib.pyplot as plt
#import seaborn as sns
#sns.set(style="white", context="talk", font_scale=1.8)
#sns.set_color_codes(palette = 'colorblind')

# Ask the user for the hdf5 files that need to be plotted together
dirs = []
while True:
	dir_name = easygui.diropenbox(msg = 'Choose a directory with a hdf5 file, hit cancel to stop choosing')
	try:
		if len(dir_name) > 0:	
			dirs.append(dir_name)
	except:
		break

# Now run through the directories, and pull out the data
unique_lasers = []
gapes = []
ltps = []
sig_trials = []
pre_stim = []
gapes_Li = []
gape_trials_Li = []
first_gape_Li = []
示例#30
0
#Modules
import easygui, os, configparser, getpass, PyInstaller.__main__

#Init
if not os.path.exists('DUFSplus'):
    os.makedirs('DUFSplus')

config = configparser.ConfigParser()
log = open('DUFSplus/Log.txt', 'w')

#Gather information for config file
gameID = None
pathSteam = easygui.fileopenbox("Select 'steam.exe'", "Point DUFS to Steam Client", "C:/Program Files (x86)/Steam/*.exe")
installLocation = easygui.diropenbox('Select game install directory', 'Point DUFS to game install folder', 'C:/Program Files (x86)/Steam/steamapps/common')
steamOrPath = easygui.ynbox('Tell DUFS to launch the game using it\'s steam game ID?', 'Use GameID')
if steamOrPath:
    gameID = easygui.enterbox('Enter the steam game ID: (use steamdb.info to find this if you do not know it already)', "Enter Steam Game ID")
pathGame = easygui.fileopenbox("Select Game exe", "Point DUFS to Game Executable", installLocation)
monitor = easygui.fileopenbox("Select executable to monitor", "Point DUFS towards the executable DUFS will continually check is running", installLocation)
usr = easygui.enterbox('Enter new user game will launch as. Needs to be in the pattern DOMAIN\\USER', "Enter new User details")
bpm = easygui.ynbox('Use Steam Big Picture Mode?', "Use BPM?")

#Write information to config file
config['PATHS'] = { 'SteamPath': pathSteam,
                    'InstallLocation': installLocation,
                    'UseGameID': steamOrPath,
                    'GameID': gameID,
                    'GamePath': pathGame,
                    'MonitorEXE': monitor
}
config['SETTINGS'] = { 'NewUser': usr,
示例#31
0
    def run(self, use_updated=False):
        try:
            usr_choice = easygui.ynbox("是否执行v2ray云彩姬一键安装脚本?", install_title)
            if usr_choice:
                # 首次安装
                if use_updated is False:
                    PrepareEnv()
                    for x in range(3):
                        self.open_dir = easygui.diropenbox(
                            "请选择安装路径",
                            install_title,
                            default=LOCAL_DIR_DATABASE)
                        # 退出-放弃更新
                        if self.open_dir is None:
                            return False
                        # 选择限制
                        if os.listdir(self.open_dir):
                            easygui.msgbox("当前目录下存在其他文件,请选择独立的文件夹!", TITLE)
                        else:
                            # 记录用户选择的下载目录,便于软件更新时的项目文件拉取
                            with open(LOCAL_PATH_DATABASE_YAML,
                                      "w",
                                      encoding="utf-8") as f:
                                proj = USER_YAML
                                proj["path"] = self.open_dir
                                yaml.dump(proj, f)
                            break
                    # 给头铁的孩子一点教育
                    else:
                        easygui.msgbox("操作有误,请重试!", TITLE)
                        return False
                # 软件更新
                else:
                    try:
                        self.kill_main()

                        # fixme:将updated模块移植到系统路径,通过外部操作控制软件更新;
                        # TODO: 将self.open_dir赋值为软件所在路径
                        with open(LOCAL_PATH_DATABASE_YAML,
                                  "r",
                                  encoding="utf-8") as f:
                            data = yaml.load(f, Loader=yaml.FullLoader)
                            print(data["path"])
                        # self.open_dir = easygui.diropenbox()
                        self.open_dir = data["path"]

                    except Exception as e:
                        print(e)

                # 下载线程
                os.startfile(self.open_dir)
                print(f"install path >> {self.open_dir}")
                with ThreadPoolExecutor(max_workers=1) as t:
                    t.submit(self.download)
                    # t.submit(easygui.msgbox, '正在拉取项目文件,请等待下载', install_title)
                easygui.msgbox("下载完成", install_title)

                # 解压线程
                with ThreadPoolExecutor(max_workers=2) as t:
                    t.submit(UnZipManager, self.open_fp)
                    t.submit(easygui.msgbox,
                             "正在解压核心组件,请等待解压",
                             title=install_title)
                easygui.msgbox("解压完成", install_title)

                # 自启动
                target_file = (self.open_fp.replace(".zip", "") +
                               f"_v{get_server_version()[0]}")
                try:
                    os.startfile(os.path.join(target_file, v2raycs_name))
                except OSError:
                    pass
                finally:
                    for filename in os.listdir(self.open_dir):
                        if ".zip" in filename:
                            try:
                                os.remove(os.path.join(self.open_dir,
                                                       filename))
                            except OSError:
                                pass
                        elif (os.path.basename(target_file).split("_")[-1] !=
                              filename.split("_")[-1]):
                            if os.path.basename(target_file).split(
                                    "_")[0] in filename:
                                try:
                                    shutil.rmtree(
                                        os.path.join(self.open_dir, filename))
                                    os.rmdir(
                                        os.path.join(self.open_dir, filename))
                                except OSError:
                                    pass

        except Exception as e:
            easygui.exceptionbox(f"{e}")
        # over
        finally:
            easygui.msgbox("感谢使用", install_title)
示例#32
0
# Import stuff!
import easygui
import sys
import os

# Ask for the directory where the first dataset sits
dir_name1 = easygui.diropenbox(msg='Where is the data from the first session?',
                               title='First session of data')
# Change to that directory
os.chdir(dir_name1)
# Get the list of filenames (only the Intan .dat files)
files1 = [
    filename for filename in os.listdir(dir_name1) if filename[-4:] == ".dat"
]

# Now do the same for the second session of data
dir_name2 = easygui.diropenbox(
    msg='Where is the data from the second session?',
    title='Second session of data')

# Get the output directory for the joined files
dir_output = easygui.diropenbox(
    msg='Where do you want to save the joined files?',
    title='Output directory')

# Read through the first set of files, append the second set and save to the output directory
for file1 in files1:
    try:
        os.system("cat " + dir_name1 + "/" + file1 + " " + dir_name2 + "/" +
                  file1 + " > " + dir_output + "/" + file1)
    except Exception:
示例#33
0
# coding:utf-8

#    __author__ = 'Mark sinoberg'
#    __date__ = '2016/5/25'
#    __Desc__ = 该函数用于提供一个对话框,返回用户选择的目录名,该目录名是带有完整的路径的
# 选择Cancel的话返回值默认为None

import easygui

msg = '选择一个文件,将会返回该文件的完整的目录哦'
title = ' 文件选择对话框'
default = r'F:\flappy-bird'
full_file_path = easygui.diropenbox(msg, title, default)
print '选择的文件的完整的路径为:' + str(full_file_path)


# D:\Software\Python2\python.exe E:/Code/Python/MyTestSet/easygui_/diropenbox.py
# 选择的文件的完整的路径为:F:\flappy-bird
#
# Process finished with exit code 0
示例#34
0
from os.path import join

import xlrd
import datetime
import pandas as pd
from easygui import fileopenbox, diropenbox

#  input spreadsheet with all the IDD data
file = fileopenbox(title='select pdd commissioning spreadsheet',
                   msg=None,
                   default='*',
                   filetypes='*.xlsx')

#  directory to save the output .w2cad files
oDir = diropenbox(title='Select where to save the .w2cad file', \
                  msg=None, default='*')

if not file:
    print('\nNo input file provided')
    raise SystemExit()

xls = pd.ExcelFile(file)


###  copied from pbtMod/w2cadFiles on 2020-11-24
class W2CADdata:
    def __init__(self):
        self.type = ''
        self.head = []
        self.params = []
        self.x = []
示例#35
0
# python gen_tfw.py <path_to_tiff_directory> [prj]

import osgeo.gdal as gdal
import osgeo.osr as osr
import os
import glob
import sys
import easygui
import fnmatch

dirphoto = easygui.diropenbox(msg=None, title="Selectionez le dossier des GTIFF ou ecrire les TFW", default=None )
list = fnmatch.filter(os.listdir(dirphoto), '*.tif')
total_con=len(list)
D1 = str(total_con)
msg = str(total_con) +" orthos voulez-vous continuer?"
title = "Merci de confirmer"
if easygui.ynbox(msg, title, ('Yes', 'No')): # show a Continue/Cancel dialog
    pass # user chose Continue else: # user chose Cancel
else:
    exit(0)

def update_progress(progress):
    barLength = 30 # Modify this to change the length of the progress bar
    
    block = int(round(barLength*progress))
    text = "\rPercent: [{0}] {1}% ".format( "#"*block + "-"*(barLength-block), int(progress*100))
    sys.stdout.write(text)
    sys.stdout.flush()

def cls():
    os.system('cls' if os.name=='nt' else 'clear')
示例#36
0
file = easygui.fileopenbox(title="mP3 slicer")
filename = file.split('.')[0].split('\\')[-1]

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

# Input Duration of Slice in Seconds
N = easygui.integerbox(msg="Enter the duration of each slice (in Seconds): ",
                       title="mP3 slicer") * 1000

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

# Input Destination folder of the output slices
easygui.msgbox("Choose the destination folder ...",
               ok_button="Choose Folder!",
               title="mP3 slicer")
dest = easygui.diropenbox(title="mP3 slicer")

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

## Reading Sound
sound = AudioSegment.from_file(file, format='mp3')

R = len(sound) // N  # Number of Slices output

########################
## Start window
easygui.msgbox(
    f"it will slice the file: {filename}.mp3 \n \ninto {R+1} files of ({N/1000} Seconds) duration \n\nin the directory: {dest} ",
    ok_button="Start",
    title="mP3 slicer")
示例#37
0
# Create argument parser
parser = argparse.ArgumentParser(
    description='Creates files with experiment info')
parser.add_argument('dir_name', help='Directory containing data files')
parser.add_argument(
    '--template',
    '-t',
    help='Template (.info) file to copy experimental details from')
args = parser.parse_args()

if args.dir_name:
    dir_path = args.dir_name
    if dir_path[-1] != '/':
        dir_path += '/'
else:
    dir_path = easygui.diropenbox(msg='Please select data directory')

dir_name = os.path.basename(dir_path[:-1])

# Extract details from name of folder
splits = dir_name.split("_")
this_dict = {
    "name": splits[0],
    "exp_type": splits[1],
    "date": splits[2],
    "timestamp": splits[3]
}

##################################################
## Brain Regions and Electrode Layout
##################################################
'''Data Converter for AIBT'''
'''1. Search logs in folder.'''
'''2. Testlog Data Crawler.'''
'''3. .csv transfer to .xlsx & sheetnames'''

import os  # 模組 - 負責讀取資料夾跟檔案
import csv  # 模組 - 處理 CSV

from easygui import diropenbox  # 模組 - 直接導入選擇資料夾的UI畫面
from openpyxl import load_workbook  # 模組 - 處理 Excel

Question = input('是否執行轉檔程式? (Y/N) ')

if Question == 'Y':  # 繼續執行
    path = diropenbox()  # 跳出對話窗 選擇 資料夾路徑

    #=================================================================================================
    #=================================== SerialNumber_Data Crawler ===================================
    #=================================================================================================
    def SNDataCrawler():
        files = os.listdir(path)  # 得到資料夾下的所有檔名稱
        for file in files:
            SerialNumber = file.split('.')
            #print(SerialNumber[0])  # 序號 -> 新增至sheetname

            # =================================================================================================
            # =================================== Open CSV to recode data ====================================
            # =================================================================================================
            with open(r'%s\%s' % (path, file), encoding='utf-8',
                      newline='') as csvfile:
                Text = csv.reader(csvfile, delimiter=',', quotechar='|')
示例#39
0
import tensorflow as tf
import os
import easygui


def _bytes_feature(value):
    return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))


def _int64_feature(value):
    return tf.train.Feature(int64_list=tf.train.Int64List(value=[value]))


tfrecords_filename = input('Please input requested filename: ') + '.tfrecords'
writer = tf.python_io.TFRecordWriter(tfrecords_filename)

path_to_images = easygui.diropenbox(msg='Please select image directory',
                                    title=None,
                                    default=None)

for f in os.listdir(path_to_images):
    img = np.array(Image.open(os.path.join(path_to_images, f)))

    img_raw = img.tostring()

    example = tf.train.Example(features=tf.train.Features(
        feature={'image_raw': _bytes_feature(img_raw)}))

    writer.write(example.SerializeToString())

writer.close()
示例#40
0
        "WGS84")  # Set geographic coordinate system to handle lat/lon
    utm_coordinate_system.SetUTM(get_utm_zone(lon), is_northern(lat))

    wgs84_coordinate_system = utm_coordinate_system.CloneGeogCS(
    )  # Clone ONLY the geographic coordinate system

    # create transform component
    wgs84_to_utm_transform = osr.CoordinateTransformation(
        wgs84_coordinate_system, utm_coordinate_system)  # (<from>, <to>)

    return wgs84_to_utm_transform.TransformPoint(
        lon, lat, alt)  # returns easting, northing, altitude


dirname = easygui.diropenbox(msg=None,
                             title="Please select a directory",
                             default=None)
total_con = len(fnmatch.filter(os.listdir(dirname), '*.jpg'))
msg = str(total_con) + " files do you want to continue?"
title = "Please Confirm"
if easygui.ynbox(msg, title, ('Yes', 'No')):  # show a Continue/Cancel dialog
    pass  # user chose Continue else: # user chose Cancel
else:
    exit(0)

file_Dir = os.path.basename(dirname)

ci = 0
cls()

# Attention en dur DJI 20MP 1” CMOS Sensor
示例#41
0
        # Make dcm for gamnma image for visualizaiton
        print("  Converting gamma image to dicom")
        gamma_dcm = join(outputdir, "_Gamma.dcm")
        mhdtodicom.mhd2dcm(gamma_img, dcmdose, gamma_dcm)


if __name__ == "__main__":

    # Select directory containing Gate output
    msg = "Select directory containing Gate output files"
    title = "SELECT DIRECTORY"
    if easygui.ccbox(msg, title):
        pass
    else:
        sys.exit(0)
    outputdir = easygui.diropenbox()

    msg = "Select Eclipse dicom file"
    title = "SELECT FILE"
    dcmdose = easygui.fileopenbox(msg, title)

    #required_prims = 206583036427  ## NPL10 208791165462 (beam v1);  ## v2 nmu: 206583036427
    required_prims = 221090286688  ## NPL 15 (V2 NMU)
    #required_prims = 259240843968   ## NPL25: 261854664857 (beam v1) 259240843968 for IDD normalized by area!
    #required_prims = 19116584729   ## DDNCF 10x02_layer1
    #required_prims = 23664065433   ## DDCNF 20x02_layer1
    #required_prims = 1978059663    ## Single spot 174.857

    # 5x5x5 boxes
    #required_prims = 75885464957  ## RS0
    #required_prims = 94286383964## RS2
示例#42
0
def on_press(key):
    global brightness, contrast, EV, saturation, zoom
    global speed, LEDintensity
    global arrowkey_mode, path, filename, recording_mode

    ### F1: keyboard shortcuts

    if key == Key.f1:
        shortcuts()

######## CAMERA

### Camera preview modes, video or photo

    if key == Key.tab:
        if recording_mode == False:
            camera.resolution = (1920, 1080)
            camera.annotate_text = "Video mode"
            recording_mode = True
        elif recording_mode == True:
            if HighResolution == True:
                camera.resolution = (4056, 3040
                                     )  # Pi camera v2 max resolution, 8MP
            else:
                camera.resolution = (1920, 1080)  # reduced resolution, Full HD
            camera.annotate_text = "Photo mode"
            recording_mode = False

### Reset camera settings
    if key == KeyCode(char='0'):
        camera_reset()

### digital zoom

    if key == KeyCode(char='+'):
        if zoom > 0.2:
            zoom = zoom - 0.1
            camera.zoom = (0, 0, zoom, zoom)
            annotate_text = "Digital zoom:" + str(round(1 / zoom, 2)) + "X"
            camera.annotate_text = annotate_text

    if key == KeyCode(char='-'):
        if zoom < 1.0:
            zoom = zoom + 0.1
            camera.zoom = (0, 0, zoom, zoom)
            annotate_text = "Digital zoom:" + str(round(1 / zoom, 2)) + "X"
            camera.annotate_text = annotate_text

### start and stop camera preview

    if key == KeyCode(char='P'):
        camera.start_preview()

    if key == KeyCode(char='p'):
        camera.stop_preview()

### brightness

    if key == KeyCode(char='B'):
        if brightness != 100:
            brightness += 5
            camera.brightness = brightness
            annotate_text = "Brightness:" + str(brightness) + "%"
            camera.annotate_text = annotate_text

    if key == KeyCode(char='b'):
        if brightness != 0:
            brightness -= 5
            camera.brightness = brightness
            annotate_text = "Brightness:" + str(brightness) + "%"
            camera.annotate_text = annotate_text

### contrast

    if key == KeyCode(char='C'):
        if contrast != 100:
            contrast += 5
            camera.contrast = contrast
            annotate_text = "Contrast:" + str(contrast) + "%"
            camera.annotate_text = annotate_text
    if key == KeyCode(char='c'):
        if contrast != -100:
            contrast -= 5
            camera.contrast = contrast
            annotate_text = "Contrast:" + str(contrast) + "%"
            camera.annotate_text = annotate_text

### EV compensation

    if key == KeyCode(char='V'):
        if EV != 25:
            EV += 1
            camera.exposure_compensation = EV
            annotate_text = "EV:" + str(EV)
            camera.annotate_text = annotate_text
    if key == KeyCode(char='v'):
        if EV != -25:
            EV -= 1
            camera.exposure_compensation = EV
            annotate_text = "EV:" + str(EV)
            camera.annotate_text = annotate_text

### saturation

    if key == KeyCode(char='S'):
        if saturation != 100:
            saturation += 5
            camera.saturation = saturation
            annotate_text = "Saturation:" + str(saturation) + "%"
            camera.annotate_text = annotate_text
    if key == KeyCode(char='s'):
        if saturation != -100:
            saturation -= 5
            camera.saturation = saturation
            annotate_text = "Saturation:" + str(saturation) + "%"
            camera.annotate_text = annotate_text

### ISO

    if key == KeyCode(char='i'):
        camera.preview_alpha = 0
        ISO_choices = ["0", "100", "200", "320", "400", "500", "640", "800"]
        ISO_selected = easygui.choicebox("Select ISO (default: 0 for auto)",
                                         "ISO", ISO_choices)
        if ISO_selected is not None:
            camera.iso = int(ISO_selected)
        camera.preview_alpha = 255

### white balance

    if key == KeyCode(char='W'):
        camera.preview_alpha = 0
        WB_choices = [
            "off", "auto", "sunlight", "cloudy", "shade", "tungsten",
            "fluorescent", "flash", "horizon"
        ]
        WB_selected = easygui.choicebox(
            "Select white balance mode (default: auto)", "White Balance",
            WB_choices)
        if WB_selected is not None:
            camera.awb_mode = WB_selected
        if WB_selected == "off":
            WB_gain = easygui.enterbox(
                "White balance gain - typical values between 0.9 and 1.9",
                "White balance gain", "1.0")
            if WB_gain is not None:
                camera.awb_gains = float(WB_gain)
        camera.preview_alpha = 255

### frame rate

    if key == KeyCode(char='r'):
        camera.preview_alpha = 0
        Framerate_choices = [
            "30", "20", "15", "10", "5", "2", "1", "0.5", "0.1", "manual"
        ]
        Framerate_selected = easygui.choicebox("Select framerate", "Framerate",
                                               Framerate_choices)
        if Framerate_selected == "manual":
            Framerate_selected = easygui.enterbox("Framerate", "Input", "")
        if Framerate_selected is not None:
            camera.framerate = float(Framerate_selected)
        camera.preview_alpha = 255

### exposure time (shutter speed)

    if key == KeyCode(char='e'):
        camera.preview_alpha = 0
        Exposure_choices = [
            "0", "10", "20", "50", "100", "200", "500", "1000", "manual"
        ]
        Exposure_selected = easygui.choicebox(
            "Select exposure time in ms (default: 0, auto)\n\
Maximum exposure time is determined by the framerate",
            "Exposure time (shutter speed)", Exposure_choices)
        if Exposure_selected == "manual":
            Exposure_selected = easygui.enterbox("Exposure time (ms)", "Input",
                                                 "")
        if Exposure_selected is not None:
            camera.shutter_speed = int(Exposure_selected) * 1000
        camera.preview_alpha = 255

### exposure modes

    if key == KeyCode(char='E'):
        camera.preview_alpha = 0
        ExposureMode_choices = [
            "off", "auto", "night", "nightpreview", "backlight", "spotlight"
        ]
        ExposureMode_selected = easygui.choicebox("Exposure mode",
                                                  "Exposure mode",
                                                  ExposureMode_choices)
        if ExposureMode_selected is not None:
            camera.exposure_mode = ExposureMode_selected
        camera.preview_alpha = 255

### select folder and set filename prefix

    if key == KeyCode(char='F'):
        camera.preview_alpha = 0
        path = easygui.diropenbox()
        camera.preview_alpha = 255
    if key == KeyCode(char='f'):
        camera.preview_alpha = 0
        filename = easygui.enterbox("Filename prefix", "Input", "")
        camera.preview_alpha = 255

######## MOTORIZED STAGE

### Ctrl: change motor speed

    if key == Key.ctrl_l or key == Key.ctrl_r:
        if speed == slow:
            speed = medium
            camera.annotate_text = "Motor speed = medium"
        elif speed == medium:
            speed = fast
            camera.annotate_text = "Motor speed = fast"
        elif speed == fast:
            speed = slow
            camera.annotate_text = "Motor speed = slow"

### keyboard arrow keys, Alt key toggles between X-Y and Rotate-Tilt
### send Arduino a string to control the motors, e.g. "-100X," or "500Y,"
### the integer defines the direction and the speed of the motor, the letter selects the motor

    if key == Key.alt_l or key == Key.alt_r:
        if arrowkey_mode == True:
            arrowkey_mode = False
            camera.annotate_text = "X-Y"
        elif arrowkey_mode == False:
            arrowkey_mode = True
            camera.annotate_text = "Rotate-Tilt"

    if key == Key.left:
        if arrowkey_mode == False:
            data = str(speed * -1) + "X,"
        else:
            data = str(speed * -1) + "R,"
        ser.write(data.encode())

    if key == Key.right:
        if arrowkey_mode == False:
            data = str(speed) + "X,"
        else:
            data = str(speed) + "R,"
        ser.write(data.encode())

    if key == Key.down:
        if arrowkey_mode == False:
            data = str(speed * -1) + "Y,"
        else:
            data = str(speed * -1) + "T,"
        ser.write(data.encode())

    if key == Key.up:
        if arrowkey_mode == False:
            data = str(speed) + "Y,"
        else:
            data = str(speed) + "T,"
        ser.write(data.encode())

### Z up and down, Page up and Page down

    if key == Key.page_up:
        data = str(speed) + "Z,"
        ser.write(data.encode())

    if key == Key.page_down:
        data = str(speed * -1) + "Z,"
        ser.write(data.encode())

### Camera up and down, Home and End

    if key == Key.home:
        data = str(speed) + "C,"
        ser.write(data.encode())

    if key == Key.end:
        data = str(speed * -1) + "C,"
        ser.write(data.encode())


######## LED

### LED intensity, max. value in the data is set to 20 to make it compatible with the joystick
### PWM of the LED driver works in the opposite direction
### Intensity is controlled in 5% increments

    if key == KeyCode(char='L'):
        if LEDintensity != 20:
            LEDintensity += 1
            data = str(20 - LEDintensity) + "L,"
            ser.write(data.encode())
            annotate_text = "LED intensity:" + str(LEDintensity * 5) + "%"
            camera.annotate_text = annotate_text
    if key == KeyCode(char='l'):
        if LEDintensity != 0:
            LEDintensity -= 1
            data = str(20 - LEDintensity) + "L,"
            ser.write(data.encode())
            annotate_text = "LED intensity:" + str(LEDintensity * 5) + "%"
            camera.annotate_text = annotate_text
示例#43
0
'''----------------------------------------------------------------------------------------------'''

##Decision tree

title = 'Checkpoint 1'
msg = 'Scanning: Locate PDMS | Importing: Import existing scan results'
choices = ['Scanning','Importing']
reply = g.buttonbox(msg,title,choices=choices)


if reply =='Importing':
	title = 'Checkpoint 2'
	msg = 'Specify the directory of the scan-result:'
        default = '/home/user/Desktop/Data'
        path = g.diropenbox(msg,title,default)
        vm = voltage_map(path)

else:
	title = 'Checkpoint 1.1'
	msg = 'Enter the MEA-ID and mount the MEA on the recording unit:'
	MEA_ID = g.enterbox(msg,title)
	today=datetime.datetime.now().year,datetime.datetime.now().month,datetime.datetime.now().day
	date='-'.join(map(str,today))
	outputDir= '/home/user/Desktop/Data/'+str(date)+'/'+str(MEA_ID)+'/voltage_map'
	msg='The result of the scan is saved in the folder '+ outputDir
	g.msgbox(msg)

        vm = voltage_map(outputDir)
        vm.testElectrodes()
示例#44
0
def setLabeledFolder():
	global labeled_folder
	labeled_folder = os.path.abspath(easygui.diropenbox())
	labelLabeledText.set(labeled_folder)
示例#45
0
def get_dicom_path():
        path = gui.diropenbox()
        return path
示例#46
0
def findexcel(path1):
    Allfiles = []  # 创建队列
    Allfiles.append(path1)
    result = []

    while len(Allfiles) != 0:  # 当队列中为空的时候跳出循环
        path = Allfiles.pop(0)  # 从队列中弹出首个路径
        if os.path.isdir(path):  # 判断路径是否为目录
            print(path)
            ALLFilePath = os.listdir(path)  # 若是目录,遍历将里面所有文件入队
            for line in ALLFilePath:
                newPath = path + "\\" + line  # 形成绝对路径
                Allfiles.append(newPath)
        else:  # 如果是一个文件,判断是否为目标文件
            target = os.path.basename(path)
            if target.endswith('xlsx'):
                result.append(path1 + "\\" + target)
    return result


path = g.diropenbox("open path", ' open path',
                    'C:\\Users\\user\\Desktop\\汕头整机\\汕头存档\\20181214\\')
# name = g.enterbox(msg='请输入您要查找的文件名:',default='processed_ecg.xlsx')
# answer = search(path, name)
answer = findexcel(path)
if answer == -1:
    print('no result')
else:
    for path in answer:
        all_in_one.genPdf(path)
示例#47
0
import cv2
import os
import easygui as esg
import math

frameFrequency = 10     # 每隔多少帧读取一次图片
path_1 = esg.fileopenbox(msg='视频', title='视频路径选择', default='*', filetypes='.avi', multiple=False)
path_2 = esg.diropenbox(msg='图片', title='图片保存路径选择', default='*')
cap = cv2.VideoCapture(path_1)   # 读入视频文件

frame_num = cap.get(7)
fill_num = int(math.log10(frame_num))+1     # 读取视频总帧数
count = 0   # 总帧数计数
output_count = 0    # 输出帧数计数
rval = cap.isOpened()
#  timeF = 1  #视频帧计数间隔频率

while rval:   # 循环读取视频帧
    count = count + 1
    print("picture:"+str(count).zfill(fill_num)+"total:" + int(frame_num))
    rval, frame = cap.read()
    if rval:
        if (count%frameFrequency) ==0:
            output_count = output_count +1
           # cv2.imwrite(path_2+'/'+path_1[-42:-4]+'_'+str(output_count).zfill(fill_num) + '.jpg', frame)
            cv2.imwrite(path_2 + '/' + str(output_count).zfill(fill_num) + '.jpg', frame)
            cv2.waitKey(1)
        # img为当前目录下新建的文件夹
        # cv2.imwrite('E:/Recorder_2019-04-08_17-32-42/image/'+
        # 'ME630_408_Recorder_2019-04-08_17-32-42_'+str(c) + '.jpg', frame) #存储为图像
    else:
#!/usr/bin/env python
import os
import csv
import easygui

directory = easygui.diropenbox()
write = csv.writer(open("directory.csv","wb"))
itemslist = os.listdir(directory)
for items in itemslist:
	write.writerow([items])
示例#49
0
def show_files():
    try:
        file_holder = np.load('selected_images.npy', allow_pickle=True)
        np.save('selected_images_bak.npy', file_holder)

        file_holder = file_holder.tolist()

    except:
        file_holder = []
        print('Opening new file for selection')

    # Open jpg folder
    folder = easygui.diropenbox()
    try:
        jpg_files = glob.glob(folder + '\\*.jpg')
        data_size = len(jpg_files)
        print('-->> already {} images selected out of {} ({}%)<<--\n'.format(
            len(file_holder), data_size,
            round(len(file_holder) / data_size * 100, 3)))

    except:
        print('No directory chosen, quitting.')
        quit()

    cv2.namedWindow('ImageStack')
    cv2.namedWindow('ImageStack', cv2.WINDOW_NORMAL)

    # starting slice
    slice = 0

    while (1):
        num = len(file_holder)

        # slice = cv2.getTrackbarPos('Particle', 'ImageStack')

        img = cv2.imread(jpg_files[slice])

        font = cv2.FONT_HERSHEY_SIMPLEX
        bottomLeftCornerOfText = (10, 10)
        fontScale = 0.5
        lineType = 2

        filename = os.path.basename(jpg_files[slice])

        # change the label color
        if filename not in file_holder:
            fontColor = (0, 0, 0)

        else:
            fontColor = (255, 255, 255)

        text_to_show = 'Image {}, {}'.format(slice, filename)
        img = cv2.resize(img, (800, 600))

        cv2.putText(img, text_to_show, bottomLeftCornerOfText, font, fontScale,
                    fontColor, lineType)

        cv2.imshow('ImageStack', img)
        cv2.namedWindow('ImageStack', cv2.WINDOW_NORMAL)

        k = cv2.waitKey(-1) & 0xFF

        # ESC
        if k == 27:
            cv2.destroyAllWindows()
            quit(1)

        # Space
        elif k == 32:
            if filename not in file_holder:

                # print(filename, file=fh)
                print('Selected {}, total files: {}'.format(filename, num))
                file_holder.append(filename)
                save_selected(file_holder)

            else:
                print('File already chosen!')

        # n
        elif k == 110:
            if slice < data_size - 1:
                slice += 1

        # jump by 100
        elif k == ord('i'):
            if slice < data_size - 1 - 100:
                slice += 100

        # jump by -100
        elif k == ord('u'):
            if slice >= 100:
                slice -= 100

        # b, jump by 1
        elif k == 98:
            if slice > 0:
                slice -= 1

        # x
        elif k == ord('x'):
            if filename in file_holder:
                file_holder.remove(filename)
                print('{} removed!'.format(filename))
                save_selected(file_holder)

            else:
                print('{} File not selected yet'.format(filename))

        # Export data to txt
        elif k == ord('e'):
            with open('selected_images.txt', 'w') as f:
                for item in file_holder:
                    # change the final MRC file output so it maches later
                    f.write("%s\n" % item.replace('.jpg', '_fractions.mrc'))
            print('Exported txt file')
示例#50
0
    return hash.hexdigest()

# Welcome Screen
easygui.msgbox(msg="Welcome to CyRep0! \nCyRep0 is a free OpenSource Cydia Repo Manager made By @J0113 in Python.", title="Welcome to CyRep0!", ok_button="START!")

# Main Menu
menu = easygui.indexbox(msg="What do you want to do?", title="CyRep0",choices=["New Repo","Repo Manager","Info","Exit"])

# Creating a new Repo
if menu == 0:
	
	# Save Location
	easygui.msgbox(msg="Creating a new Repo!\nPlease create or select a folder.\nIn this folder all the repo file are going to be saved.", title="CyRep0", ok_button="Ok")
	while True:
		try:
			newrepolocation = easygui.diropenbox()
		except ValueError:
			continue
		if newrepolocation is None:
			continue
		else:
			break
	
	# Creating the Release file
	while True:
		try:
			newreponame = easygui.enterbox(msg="How should we call your Repo?", title="CyRep0")
		except ValueError:
			continue
		if newreponame is None:
			continue
if "(" and "(" in tvd_template_path:
  tvd_template_path = tvd_template_path.replace("(", "{(}")
  tvd_template_path = tvd_template_path.replace(")", "{)}")

# Username bracket fix
if "(" and ")" in username:
  username_striplog = username
  username_striplog = username_striplog.replace("(", "{(}")
  username_striplog = username_striplog.replace(")", "{)}")
if "(" and ")" in geo2name:
  geo2_striplog = geo2name
  geo2_striplog = geo2_striplog.replace("(", "{(}")
  geo2_striplog = geo2_striplog.replace(")", "{)}")
  
# User prompt for the save location for the well files
save_dir = easygui.diropenbox(title = "Select the location to save your well files") + '\\'

# User prompt for the well information. Input goes into string list that can be accessed to populate well files
fieldNames = ['Well Name:', 'License:', 'U.W.I.:', 'AFE:', 'Surface Location:', 'Ground Elevation:', 'Kelly Bushing:', 
'Primary Target:', 'Region:'] # Define fieldNames, text that sits beside each user box
wellInfo = [] # List which holds the user-inputed data
wellInfo = easygui.multenterbox("Fill in Well Information Below", "Well Info", fieldNames)

# Used to break up the well name at the first digit. Puts into separate strings so it can 
# populate the isopach spreadsheet
wellname_first = wellInfo[0]
wellname_end = ""
if wellInfo[0] is not "":
  wellname_break_search = re.search("\d", wellInfo[0])
  if wellname_break_search:
    wellname_break = wellname_break_search.start()
示例#52
0
            #if file_name == 'setup.py':

            file_type = os.path.splitext(file_name)[1]
            if file_type in code_type:

                count = codecalc(file_name)
                source_dict.setdefault(file_type, 0)
                source_dict[file_type] += count

                #full_file_name = os.getcwd()+ os.sep+ file_name
                #countlist.append(full_file_name)

                filetype_dict.setdefault(file_type, 0)
                filetype_dict[file_type] += 1


source_dict = {}
filetype_dict = {}
code_type = ['.py', '.java']
#dir_path = '/Users/apple'
#dir_path='/Users/apple/Documents/workspace'
g.msgbox(msg='请打开所有存放代码的文件夹', title='代码统计')
dir_path = g.diropenbox('请选择代码库')
#dir_path = 'D:\\je_workspace'
searchfile(dir_path)
print 'source_dict', source_dict
print 'filetype_dict', filetype_dict
show_result()
#file_name = 'ex_path.py'
import os
import tables
import numpy as np
import easygui
import ast
import pylab as plt
from sklearn.mixture import GaussianMixture
import blech_waveforms_datashader

# Get directory where the hdf5 file sits, and change to that directory
dir_name = easygui.diropenbox()
os.chdir(dir_name)

# Clean up the memory monitor files, pass if clean up has been done already
if not os.path.exists('./memory_monitor_clustering/memory_usage.txt'):
	file_list = os.listdir('./memory_monitor_clustering')
	f = open('./memory_monitor_clustering/memory_usage.txt', 'w')
	for files in file_list:
		try:
			mem_usage = np.loadtxt('./memory_monitor_clustering/' + files)
			print('electrode'+files[:-4], '\t', str(mem_usage)+'MB', file=f)
			os.system('rm ' + './memory_monitor_clustering/' + files)
		except:
			pass	
	f.close()

# Look for the hdf5 file in the directory
file_list = os.listdir('./')
hdf5_name = ''
for files in file_list:
	if files[-2:] == 'h5':
示例#54
0
from lib.msplot import *
import easygui

if __name__ == '__main__':
    path = easygui.diropenbox()

    s = Spectrum()

    s.load(path)
    #s.load("C:\\Users\\ishma\\Dropbox (SteinLab)\\spectra\\(ID     186nm) 2016-07-26-tip15")
    #s.load("../(ID     186nm) 2016-07-26-tip15/")

    s.makeAnimation(
        window=1000,
        step=1000,
        scan_range=(None, None),
        mass_range=(None, None),
        out_name="test2.mp4",
        normalization=SpecNorm.SCAN,
        label_peaks=True,
        aux_plot_type=AuxPlots.EFFICIENCY,
        #aux_plot_type_2=AuxPlots.DETECTOR_SOURCE_RATIO,
        aux_smoothing=100,
        font_size=14)
示例#55
0
colors = plt.get_cmap('winter_r')(np.linspace(0, 1, len(iter_freqs)))

# =============================================================================
# Identity set-up
# =============================================================================

msg = "Is this a passive or taste session (ie. do you have more than one trial)?"
session_type = easygui.buttonbox(msg, choices=["Passive", "Tastes"])

# =============================================================================
# Create/Import directories
# =============================================================================

#Get name of directory where you want to save output files to
save_name = easygui.diropenbox(
    msg=
    'Choose directory you want output files sent to (and/or where ".dir" files are)',
    default='/home/bradly/drive2/spike_locking')

#Ask user if they have ran set-up before
msg = "Have you performed directory set-up before (ie. do you have '.dir' files in output folder) ?"
dir_check = easygui.buttonbox(msg, choices=["Yes", "No"])

if dir_check == "No":
    #Get data_saving name
    msg = "What condition are you analyzing first?"
    subplot_check1 = easygui.buttonbox(msg,
                                       choices=["Saline", "LiCl", "Other"])

    # Ask the user for the hdf5 files that need to be plotted together (fist condition)
    dirs_1 = []
    while True:
示例#56
0
import os
import easygui


def file_name(file_dir):
    L = []
    K = []
    for root, dirs, files in os.walk(file_dir):
        for file in files:
            if os.path.splitext(file)[1] == '.xlsx':
                L.append(os.path.join(root, file))
                K.append(os.path.splitext(file)[0])
    return L, K


filepath = easygui.diropenbox(title='选择需要合并的excel文件')
#filepath='C:\\Users\\xr chen\\Desktop\\test\\'

if __name__ == '__main__':
    [allxls, allname] = file_name(filepath)
    wb1 = xlwt.Workbook()
    for i in range(len(allxls)):
        df1 = xlrd.open_workbook(allxls[i])
        sheet1 = df1.sheet_by_index(0)
        sheet = wb1.add_sheet(allname[i])
        for i in range(sheet1.nrows):
            for j in range(sheet1.ncols):
                sheet.write(i, j, sheet1.cell_value(i, j))
    outputpath = easygui.diropenbox(title='保存到')
    wb1.save(filepath + 'output.xls')
    easygui.msgbox(msg='按完成键结束',
def get_dir(msg=None, title=None, default='*'):
    path = ''
    while path == '':
        path = easygui.diropenbox(msg=msg, title=title, default=default)
    return path
示例#58
0
        dst = cv2.warpAffine(img, M, (cols, rows))
        r1 = np.mean(dst[300:400, :], axis=0)
        r2 = np.mean(dst[900:1000, :], axis=0)
        #cor.append(np.correlate(r1,r2)[0])
        #rm.append(np.var(r1-r2))
        cf.append(np.corrcoef(r1, r2)[0, 1])
    imax = np.argmax(cf)
    rot_angle = angs[imax]
    return rot_angle


### find tilts

data_folder = easygui.diropenbox(
    msg="open Directory",
    title="Open Directory",
    default=
    "/data/phanindra/Abhilash/Lyott filter tests/first stage of Lyott filter")
if data_folder is None:
    exit(0)

rot_ang_file = glob.glob(data_folder + '/rotation_angles.pkl')
img_files = glob.glob(data_folder + '/*.fits')

if rot_ang_file:
    fid_rot = open(rot_ang_file, 'rb')
    rot_angles = pickle.load(fid_rot)
    vlts = []
    mns = {}
    for img_file in img_files:
        hdus = fits.open(img_file)
			pass
	return line
            

def get_filenuber(dirpath):	#计算py文件,并返回py文件的列表
	#i=0
	filelist=[]
	for root,dirs,filenames in os.walk(dirpath):
		for filename in filenames:
				path=os.path.join(root,filename)
				if os.path.splitext(path)[1]=='.py':
					filelist.append(path)
					#get_line(path)    
					#i+=1

	return filelist

dirpath=g.diropenbox(msg='打开需要统计的文件夹',title='统计.py文件')	#打开文件夹路径
#print(dirpath)
filelist=get_filenuber(dirpath)
#统计各个文件中的代码行数综合
n=0							
for i in filelist:
	n+=get_line(i)			
#print(filelist)
#print(n)
g.msgbox('包含%s个文件,%s行代码'%(len(filelist),n),'统计结果')
                
                
                
# Post processing cleanup of the mess of files created by emg_local_BSA_execute.py. All the output files will be saved to p (named by tastes) and omega in the hdf5 file under the node emg_BSA_results

# Import stuff
import numpy as np
import easygui
import os
import tables

# Ask the user to navigate to the directory that hosts the emg_data, and change to it
dir_name = easygui.diropenbox()
os.chdir(dir_name)

# Look for the hdf5 file in the directory
file_list = os.listdir('./')
hdf5_name = ''
for files in file_list:
	if files[-2:] == 'h5':
		hdf5_name = files

# Open the hdf5 file
hf5 = tables.open_file(hdf5_name, 'r+')

# Delete the raw_emg node, if it exists in the hdf5 file, to cut down on file size
try:
	hf5.remove_node('/raw_emg', recursive = 1)
except:
	print("Raw EMG recordings have already been removed, so moving on ..")


# Load sig_trials.npy to get number of tastes
sig_trials = np.load('sig_trials.npy')