Example #1
0
def read_img(filename):
    # filename = easygui.fileopenbox()
    # print(filename)
    # cmd = r"C:\Users\James\PycharmProjects\test_alpr\openalpr\alpr.exe -n 1 -j C:\Users\James\PycharmProjects\test_alpr\LicPlateImages\2.png"

    cmd = r"C:\Users\James\PycharmProjects\test_alpr\openalpr\alpr.exe -n 1 -j " + filename
    output = qx(cmd)
    #output level
    print('Producing output now')

    out_str = output.decode("utf-8")
    plate_txt = out_str.find("plate")

    if plate_txt != -1:
        print(out_str)
        plate_txt = plate_txt + 8
        plate_txt_end = out_str.find('","', plate_txt)

        print(
            "============================================\n           Printing plate #\n"
        )
        x = plate_txt
        plate_num = ""
        while x < plate_txt_end:
            plate_num = plate_num + out_str[x]
            x = x + 1

        print(plate_num)
        print('This is plate number', plate_num)
        return plate_num
def get_line_1():
	status = qx(["mpc"])
	status = status.split('\n')
	if len(status) >= 1:
		return status[0]
	else:
		return ""
Example #3
0
def indexpdb(pdbpath):
    output = qx([args.srcTool, pdbpath, "-r"])
    outputFiles = output.split("\r\n")

    pdbStreamFile = open("pdbstream.txt", "w")
    print >> pdbStreamFile, "SRCSRV: ini ------------------------------------------------"
    print >> pdbStreamFile, "VERSION=1"
    print >> pdbStreamFile, "INDEXVERSION=2"
    print >> pdbStreamFile, "VERCTRL=GitHub"
    print >> pdbStreamFile, "DATETIME=Sun May 24 22:51:33 2015"
    print >> pdbStreamFile, "SRCSRV: variables ------------------------------------------"
    print >> pdbStreamFile, "GIT_REVNO=" + revno
    print >> pdbStreamFile, "GIT_WEB_ADDRESS=" + args.webAddr
    print >> pdbStreamFile, "GIT_URL=%git_web_address%/%git_revno%/%var2%"
    print >> pdbStreamFile, "GIT_EXTRACT_TARGET=%targ%\%fnfile%(%var1%)"
    print >> pdbStreamFile, 'GIT_EXTRACT_CMD=cmd /c curl.exe "%git_url%" > "%git_extract_target%"'
    print >> pdbStreamFile, "SRCSRVTRG=%git_extract_target%"
    print >> pdbStreamFile, "SRCSRVCMD=%git_extract_cmd%"

    print >> pdbStreamFile, "SRCSRV: source files ---------------------------------------"
    for f in outputFiles:
        if os.path.commonprefix([args.repo, f.lower()]) == args.repo:
            relPath = os.path.relpath(f, args.repo)
            relPath = correctPath(args.repo, relPath)
            if f:
                print >> pdbStreamFile, f + "*" + relPath.replace("\\", "/")
    print >> pdbStreamFile, "SRCSRV: end ------------------------------------------------"
    pdbStreamFile.close()

    subprocess.call([args.pdbStr, "-w", "-p:" + pdbpath, "-s:srcsrv", "-i:pdbstream.txt"])
def get_line_3():
	status = qx(["mpc"])
	status = status.split('\n')
	if len(status) >= 3:
		return status[2]
	else:
		return ""
def get_line_2():
	status = qx(["mpc"])
	status = status.split('\n')
	if len(status) >= 2:
		return status[1]
	else:
		return ""
Example #6
0
 def unlockDrive(self):
     try:
         from subprocess import check_output as qx
         out = qx("/bin/dmesg | grep sg | grep \"type 13\" | awk \'{print $8}\'",shell=True)
         #check if there is only one unique sg device otherwise stop
         try:
             cmp = out.split( )[0]
         except IndexError:
             self.textEdit.append("Couldn't find WD Drive in dmesg, pls unplug and replug the drive again!")
             return
         multipleDevices = False;
         for word in out.split( ):
             if not cmp==word:
                multipleDevices = True
                break
         if not multipleDevices:
             #finally lets send the SCSI command to encrypt
             self.textEdit.append("Secure Harddrive identified at /dev/"+cmp)
             try:
                 subprocess.check_call("gksudo whoami", shell=True)
                 subprocess.check_call("sudo sg_raw -s 40 -i "+fpathp+" /dev/"+cmp+" c1 e1 00 00 00 00 00 00 28 00", shell=True)
                 self.textEdit.append("Drive is now unlogged and can be mounted!")
                 self.mountBtn.setEnabled(True)
             except subprocess.CalledProcessError:
                 self.textEdit.append("Failure while sending SCSI encrypt command -> Check if harddrive is connected properly! (Maybe /dev/"+cmp+" does not exist)")
                 return
         else:
             self.textEdit.append("Failure multiple SCSI type 13 devices recognized pls unplug everything except the WD drive and wait a bit before you retry.")
             return
     except subprocess.CalledProcessError:
         self.textEdit.append("Failure couldn't find sg type within dmesg!")
         return
Example #7
0
def indexpdb(pdbpath):
    output = qx([args.srcTool, pdbpath, '-r'])
    outputFiles = output.split('\r\n')

    pdbStreamFile = open('pdbstream.txt', 'w')
    print >> pdbStreamFile, 'SRCSRV: ini ------------------------------------------------'
    print >> pdbStreamFile, 'VERSION=1'
    print >> pdbStreamFile, 'INDEXVERSION=2'
    print >> pdbStreamFile, 'VERCTRL=GitHub'
    print >> pdbStreamFile, 'DATETIME=Sun May 24 22:51:33 2015'
    print >> pdbStreamFile, 'SRCSRV: variables ------------------------------------------'
    print >> pdbStreamFile, 'GIT_REVNO=' + revno
    print >> pdbStreamFile, 'GIT_WEB_ADDRESS=' + args.webAddr
    print >> pdbStreamFile, 'GIT_URL=%git_web_address%/%git_revno%/%var2%'
    print >> pdbStreamFile, 'GIT_EXTRACT_TARGET=%targ%\%fnfile%(%var1%)'
    print >> pdbStreamFile, 'GIT_EXTRACT_CMD=cmd /c curl.exe "%git_url%" > "%git_extract_target%"'
    print >> pdbStreamFile, 'SRCSRVTRG=%git_extract_target%'
    print >> pdbStreamFile, 'SRCSRVCMD=%git_extract_cmd%'

    print >> pdbStreamFile, 'SRCSRV: source files ---------------------------------------'
    for f in outputFiles:
        if os.path.commonprefix([args.repo, f.lower()]) == args.repo:
            relPath = os.path.relpath(f, args.repo)
            relPath = correctPath(args.repo, relPath)
            if f:
                print >> pdbStreamFile, f + '*' + relPath.replace('\\', '/')
    print >> pdbStreamFile, 'SRCSRV: end ------------------------------------------------'
    pdbStreamFile.close()

    subprocess.call(
        [args.pdbStr, '-w', '-p:' + pdbpath, '-s:srcsrv', '-i:pdbstream.txt'])
Example #8
0
def execute_on_hosts(Cmd, Hosts):
    # loop through all server and collect the output
    Result = []
    for UserHost in Hosts:
        Host   = UserHost.split("@")[1]
        Output = qx(["ssh", UserHost, Cmd])
        try:
            Json = json.loads(Output)
            Json['host'] = Host
            Result.append(Json)
        except:
            UserMsg = "Internal error, please contact the administrator"
            LogMsg  = "no json result: %s"%Output
            Result.append({'result':'error', 'host':Host, 'user_msg': UserMsg, 'log_msg':LogMsg})

    AllGood = True
    for Entry in Result:
        if not 'result' in Entry:
            AllGood = False
        elif Entry['result'] != 'ok':
            AllGood = False

    # f = open('ResultFileGridMap.txt', 'w')
    # f.write(str(Result))
    # f.close()

    return AllGood
Example #9
0
def airsage_default(start_date, end_date, t_zone, fp):
    days = list()
    fp.write('[hwmrun]\n')
    fp.write('\tcounty=-f %d  %d -m county\n' %
             (int(start_date), int(end_date)))
    fp.write('\tzone=-f %d  %d -m zone\n' % (int(start_date), int(end_date)))
    fp.write('\n[tlmrun]\n')

    days_matrix = [
        'airsageWDDP', 'airsageWEDP', 'airsageDP9class', 'airsageWDH',
        'airsageWEH'
    ]
    for index, each_matrix in enumerate(days_matrix):
        #airsageWEDP=subprocess.Popen(["python","testing_date_modified.py",start_date,end_date,'airsageWE'], stdout=PIPE)
        #days_list=subprocess.Popen(["python","testing_date_modified.py",start_date,end_date,each_matrix], stdout=PIPE)
        if index == 3:
            fp.write('\n[admrun]\n')

        days_list = ""
        days_list = qx([
            "python", "testing_date_modified.py", start_date, end_date,
            each_matrix
        ])
        #for line in iter(days_list.stdout.readline,''):
        #	a=line # putting into a string format
        a = days_list
        str_len = len(a)
        r = a[2:str_len - 2]  # trivial process, dont know how to make it nice
        for i in r.split(','):
            val = i.replace("'", '')
            days.append(val)
        #fp.write('--tlmrun\n')
        if each_matrix in ('airsageWDH', 'airsageWEH'):
            fp.write('\t%s=' % each_matrix + 'America/%s' % t_zone)
        else:
            fp.write('\t%s=' % each_matrix + 'America/%s' % t_zone)
        if each_matrix in ('airsageWDDP', 'airsageWDH', 'airsageDP9class'):
            fp.write(' -g Tue Wed Thu -f ')
        else:
            fp.write(' -g Sat Sun -f ')
        fp.write(' '.join(str(v) for v in days))
        del days[:]  # delete the list
        if 'DP' in each_matrix:  # that is dap part exist
            fp.write(
                ' -t 0000-0600-H00:H06 0600-1000-H06:H10  1000-1500-H10:H15 1500-1900-H15:H19 1900-2400-H19:H24'
            )
        else:
            fp.write(' -t H')
        if each_matrix in ('airsageDP9class'):
            fp.write(' -p 9-class --subscriber2class\n')
        else:
            fp.write(' --subscriber2class -p 3-class\n')
Example #10
0
def execute_on_hosts(Parameter, Hosts):
    # loop through all server and collect the output
    Cmd = "sudo /home/watts/.config/watts/ssh_vm.py %s" % Parameter
    Result = []
    for UserHost in Hosts:
        Host = UserHost.split("@")[1]
        Output = qx(["ssh", UserHost, Cmd])
        try:
            Json = json.loads(Output)
            Json['host'] = Host
            Result.append(Json)
        except:
            UserMsg = "Internal error, please contact the administrator"
            LogMsg = "no json result: %s"%Output
            Result.append({'result':'error', 'host':Host, 'user_msg': UserMsg, 'log_msg':LogMsg})

    return Result
	def updateStatusLED(self):
		status = qx(["mpc"])
		now = datetime.datetime.now()
		delta = now - self.lastStatusUpdate
		if delta.total_seconds() > 0.5:
			self.lastStatusUpdate = now
			#print status
			if "[playing]" in status:
				GPIO.output(10,1)
				GPIO.output(16,1)
				GPIO.output(22,1)


			else:
				GPIO.output(10,0)
				GPIO.output(16,0)
				GPIO.output(22,0)
Example #12
0
 def unlockDrive(self):
     try:
         from subprocess import check_output as qx
         out = qx(
             "/bin/dmesg | grep sg | grep \"type 13\" | awk \'{print $8}\'",
             shell=True)
         #check if there is only one unique sg device otherwise stop
         try:
             cmp = out.split()[0]
         except IndexError:
             self.textEdit.append(
                 "Couldn't find WD Drive in dmesg, pls unplug and replug the drive again!"
             )
             return
         multipleDevices = False
         for word in out.split():
             if not cmp == word:
                 multipleDevices = True
                 break
         if not multipleDevices:
             #finally lets send the SCSI command to encrypt
             self.textEdit.append("Secure Harddrive identified at /dev/" +
                                  cmp)
             try:
                 subprocess.check_call("gksudo whoami", shell=True)
                 subprocess.check_call("sudo sg_raw -s 40 -i " + fpathp +
                                       " /dev/" + cmp +
                                       " c1 e1 00 00 00 00 00 00 28 00",
                                       shell=True)
                 self.textEdit.append(
                     "Drive is now unlogged and can be mounted!")
                 self.mountBtn.setEnabled(True)
             except subprocess.CalledProcessError:
                 self.textEdit.append(
                     "Failure while sending SCSI encrypt command -> Check if harddrive is connected properly! (Maybe /dev/"
                     + cmp + " does not exist)")
                 return
         else:
             self.textEdit.append(
                 "Failure multiple SCSI type 13 devices recognized pls unplug everything except the WD drive and wait a bit before you retry."
             )
             return
     except subprocess.CalledProcessError:
         self.textEdit.append("Failure couldn't find sg type within dmesg!")
         return
Example #13
0
def airsage_default(start_date,end_date,t_zone,fp):
		days=list()
		fp.write('[hwmrun]\n')
		fp.write('\tcounty=-f %d  %d -m county\n' % (int(start_date),int(end_date)))
		fp.write('\tzone=-f %d  %d -m zone\n'  % (int(start_date),int(end_date)))
		fp.write('\n[tlmrun]\n')

		days_matrix=['airsageWDDP','airsageWEDP','airsageDP9class','airsageWDH','airsageWEH']
		for index,each_matrix in enumerate(days_matrix):
			#airsageWEDP=subprocess.Popen(["python","testing_date_modified.py",start_date,end_date,'airsageWE'], stdout=PIPE)
			#days_list=subprocess.Popen(["python","testing_date_modified.py",start_date,end_date,each_matrix], stdout=PIPE)
			if index == 3:
				fp.write('\n[admrun]\n')
		
			days_list=""
			days_list=qx(["python","testing_date_modified.py",start_date,end_date,each_matrix])
			#for line in iter(days_list.stdout.readline,''):
			#	a=line # putting into a string format 
			a=days_list
			str_len=len(a)
			r=a[2:str_len-2] # trivial process, dont know how to make it nice
			for i in r.split(','):
				val=i.replace("'",'')
				days.append(val)
			#fp.write('--tlmrun\n')
			if each_matrix in ('airsageWDH','airsageWEH'):
                                fp.write('\t%s=' % each_matrix +'America/%s' % t_zone)
                        else:
				fp.write('\t%s=' % each_matrix +'America/%s' % t_zone)
			if each_matrix  in ('airsageWDDP', 'airsageWDH','airsageDP9class'):
				fp.write(' -g Tue Wed Thu -f ')
			else:
				fp.write(' -g Sat Sun -f ')
			fp.write(' '.join(str(v) for v in days))
			del days[:] # delete the list 
			if 'DP' in each_matrix: # that is dap part exist 
				fp.write(' -t 0000-0600-H00:H06 0600-1000-H06:H10  1000-1500-H10:H15 1500-1900-H15:H19 1900-2400-H19:H24')
			else:
				fp.write(' -t H')
			if each_matrix  in ('airsageDP9class'):
				fp.write(' -p 9-class --subscriber2class\n')
			else:
				fp.write(' --subscriber2class -p 3-class\n')
Example #14
0
def solverAttempt (nodeCount, edges):
    #Create solver model file
    upperBound=getUpperBound(nodeCount,edges)
    path='C:\\Solver\\bin\\'
    filename='test_'+str(nodeCount)+'_'+str(datetime.datetime.now().date())+'_'+ str(datetime.datetime.now().hour)+'_'+str(datetime.datetime.now().minute)+'_'+str(datetime.datetime.now().second)+'.mzn'
    solverFile = open(path+filename,'w')
    solverFile.write('%G12 Solver File for '+str(nodeCount)+' nodes run at '+ str(datetime.datetime.now())+'\n')
    solverFile.write('int: nc='+str(nodeCount)+'; \n')
    solverFile.write('\n')
    solverFile.write('array[0..nc] of var 0..'+str(upperBound)+': color; \n')
    solverFile.write('\n')

    solverFile.write('constraint color[0]=0;')

    solverFile.write('\n')

    for edge in edges:
        solverFile.write('constraint color['+str(edge[0])+']!=color['+str(edge[1])+']; \n')

    solverFile.write('\n')
    solverFile.write('solve minimize max(color); \n')
    solverFile.write('')
    solverFile.write('output [ show(color[i]) ++"\\n" | i in 0..nc]; \n')
    solverFile.close()

    #run solver and get solution
    import os
    from subprocess import check_output as qx

    os.chdir('c:\\Solver\\bin')
    cmd = r'mzn-g12fd.bat '+filename
    output = qx(cmd)
    os.chdir('C:\\Users\\keseaman\\Dropbox\\Coursera\\Discrete Optimization\\coloring')
    lines=output.splitlines();

    #format output and return
    numColors = int(max(lines [:nodeCount]))+1
    opt = 0
    if lines [-1]=='==========': opt = 1

    outputData = str(numColors) + ' ' + str(opt) + '\n'
    outputData += ' '.join(map(str, lines[:nodeCount]))
    return outputData;
def run_game(game_number, seed, map_size, bot1, bot2):
    map_param = '-d "' + str(map_size) + " " + str(map_size) + '"'

    cmd = HALITE_RUNNER + " -s " + str(
        seed) + " " + map_param + " " + bot1 + " " + bot2

    print(" Game " + str(game_number) + "/" + str(GAMES_TO_PLAY) + ": " + cmd)
    log_file.write(cmd + '\n')

    output = qx(cmd)

    winner = ""
    for line in output.splitlines():
        line_string = line.decode()
        log_file.write(line_string + '\n')
        if line_string == "1 1":
            winner = bot1
        if line_string == "2 1":
            winner = bot2

    return winner
Example #16
0
 def letters_in_word(self, letter_word, words, distance=10):
     l = " ".join(c for c in letter_word)
     cmd = [fbin, "-d", fdict, "-m", "l2w", "-l", str(distance), "-w", l]
     output = qx(cmd)
     o = output.strip().split("\n")
     self.assertEqual(o, words)
Example #17
0
                * Product REV: EMT01B6Q
                * Serial number: S21HNSAG300129N
                * Capacity: 500107862016 bytes

[+] Read 3538 bytes of SMBIOS data.
###################end of standard output ##################################


"""

from subprocess import check_output as qx
import json
import requests

cmd = r'genid.x86.exe'
output = qx(cmd)

output = str(output).replace('\\r', '').replace('\\n', '').replace('\\t',
                                                                   '').strip()
'''
level1: [+]
level2: -
level3: *
'''

#process the 1st layer ,which is just '[+]'
layer1 = output.split('[+]')[2:]
#layer1[0] is the
'''
[
 ' CPU:- Vendor: GenuineIntel- Brand: Intel(R) Core(TM) i5-4590 CPU @ 3.30GHz- Version information: 0x306C3- Feature bits:* 0x100800* 0x7FFAFBFF* 0xBFEBFBFF- Processors: 4',
				buttonLastPress = now
				print "Play/Pause button pressed"
				toogleRadio()
		if not GPIO.input(12):
			now = datetime.datetime.now()
			delta = now - buttonLastPress
			if delta.total_seconds() > 0.4:
				buttonLastPress = now
				print "Previous button pressed"
				prevRadio()
		if not GPIO.input(18):
			now = datetime.datetime.now()
			delta = now - buttonLastPress
			if delta.total_seconds() > 0.4:
				buttonLastPress = now
				print "Next button pressed"	
				nextRadio()	
	phy.cleanGPIO();
	qx(["mpc", "stop"])
except Exception, e:
	GPIO.cleanup()
	qx(["mpc", "stop"])
	print "Error",e
	print "\nSooo error. No playback. Channels. Much Clean. Very Terminating. WOW."
except:
	GPIO.cleanup()
	qx(["mpc", "stop"])
	print "\nSooo unexpected. Without much error. No playback. Channels. Much Clean. Very Terminating. WOW."


def toogleRadio():
	print qx(["mpc", "toggle"])
Example #20
0
 def word_notin_letters(self, letter_word, distance=10):
     l = " ".join(c for c in letter_word)
     cmd = [fbin, "-d", fdict, "-m", "w2l", "-l", str(distance), "-w", l]
     output = qx(cmd)
     o = output.strip().split("\n")
     self.assertEqual(o, [""])
def stopRadio():
	qx(["mpc", "stop"])
    shutil.copy('SRWLIB_ExampleViewDataFile.bat', data_dir)
    shutil.copy('SRWLIB_ExampleViewDataFile.sh', data_dir)

    start_time = time.time()

    python_command = 'python SRWLIB_Example10.py'
    if i == 0:
        command = python_command
    else:
        command = 'mpiexec -n %i %s' % (i, python_command)

    print(command)

    try:
        # From here: http://stackoverflow.com/questions/1191374/using-module-subprocess-with-timeout
        output = qx(command, stderr=STDOUT, timeout=timeout)
    except TypeError:
        # http://stackoverflow.com/questions/23287689/how-to-make-a-subprocess-call-timeout-using-python-2-7-6
        # http://easyprocess.readthedocs.org/en/latest/
        from easyprocess import EasyProcess

        output = EasyProcess(command).call(timeout=timeout).stdout
    except:
        pass

    print('Command <%s> timed out after %i seconds' % (command, timeout))

    end_time = time.time()

    duration = end_time - start_time
Example #23
0
 start = time.time()
 for fileIndex, fileName in enumerate(files_list):
     t0 = time.time()
     print('Begin {}/{}: {}'.format(fileIndex+1, len(files_list), fileName))
     saveDir = os.path.join(root_path, fileName)
     if not os.path.exists(saveDir):
         os.makedirs(saveDir)
     # savePath is the .mha file store location
     savePath = os.path.join(saveDir, '{}.mha'.format(fileName))
     ct_itk, ct_scan, ori_origin, ori_size, ori_spacing = load_scan_mhda(savePath)
     # compute isocenter
     center = get_center(ori_origin, ori_size, ori_spacing)
     # map the .mha file value to (-1000, 1000)
     cmd_str = plasti_path + '/plastimatch adjust --input {} --output {}\
             --pw-linear "0, -1000"'.format(savePath, saveDir+'/out.mha')  
     output = qx(cmd_str)
     # get virtual xray file
     directions = [1, 2]
     for i in directions:
         if i == 1:
             nrm = "0 1 0"
         else:
             nrm = "1 0 0"    
         '''
         plastimatch usage
         -t : save format
         -g : sid sad [DistanceSourceToPatient]:541 
                      [DistanceSourceToDetector]:949.075012
         -r : output image resolution
         -o : isocenter position
         -z : physical size of imager
def nextRadio():
	print qx(["mpc", "next"])	
def prevRadio():
	print qx(["mpc", "prev"])	
Example #26
0
def solverAttempt (capacity, items, taken, value, values, weight, weights):
    #Create solver model file
    path='C:\\Solver\\bin\\'
    filename='test_'+str(items)+'_'+str(capacity)+'_'+str(datetime.datetime.now().date())+'_'+ str(datetime.datetime.now().hour)+'_'+str(datetime.datetime.now().minute)+'_'+str(datetime.datetime.now().second)+'.mzn'
    solverFile = open(path+filename,'w')
    solverFile.write('%G12 Solver File for '+str(items)+' items and '+str(capacity)+' Capacity run at '+ str(datetime.datetime.now())+'\n')
    solverFile.write('\n%Parameters\n')
    solverFile.write('int: n='+str(items)+'; \n')
    solverFile.write('int: k='+str(capacity)+'; \n')
    solverFile.write('int: maxValue='+str(sum(values))+'; \n')
    sizeString = 'array[1..n] of int: size = ['
    for i in range(0,items):
        sizeString += str(weights[i])
        if i!=items-1:sizeString+=','
    sizeString +="]; \n"
    solverFile.write(sizeString);

    valueString = 'array[1..n] of int: value = ['
    for i in range(0,items):
        valueString += str(values[i])
        if i!=items-1:valueString+=','
    valueString +="]; \n"
    solverFile.write(valueString);

    solverFile.write('\n%Decision Variables\n')

    solverFile.write('array [1..n] of var 0..1: x;\n')
    solverFile.write('var 0..maxValue: v;\n')

    solverFile.write('\n%Constraints\n')
    solverFile.write('constraint sum (i in 1..n) (value[i] * x[i]) >= v; \n')
    solverFile.write('constraint sum (i in 1..n) (size[i] * x[i]) <= k; \n')

    solverFile.write('\n%Solve - Greedy Naive Solver\n')
    solverFile.write('solve maximize v; \n')
    #:: int_search(x, input_order, indomain_max, complete)
    solverFile.write('')

    solverFile.write(r'output [show(v) , "\n"] ++ [show(x[i]) ++"\n" | i in 1..n];')
    solverFile.close()

    #run solver and get solution
    import os
    from subprocess import check_output as qx

    os.chdir('c:\\Solver\\bin')
    cmd = r'mzn-g12fd.bat '+filename
    output = qx(cmd)
    os.chdir('C:\\Users\\keseaman\\Dropbox\\Coursera\\Discrete Optimization\\knapsack')
    lines=output.splitlines();

    #format output and return
    value = int(lines[0])
    #numColors = int(max(lines [:nodeCount]))+1
    opt = 0
    if lines [-1]=='==========': opt = 1

    #outputData = str(numColors) + ' ' + str(opt) + '\n'
    #outputData += ' '.join(map(str, lines[:nodeCount]))
    for line in lines[1:items+1]:
        taken.append(line)
    return [value, opt];
Example #27
0
def get_line(filename, address):
  return qx(['addr2line', '-e', filename, address])
    def unlockDrive(self):
        try:
            # to-do: make this check a separate subroutine
            # multiple drives could be supported by showing a list of 'sg<nn>' ids
            # and selecting the required one
            # also, I think this check is erroneous. the multiple sg<nn> entries are still reported
            # by dmesg, even after the other drives are removed
            from subprocess import check_output as qx
            out = qx(
                "/bin/dmesg | grep sg | grep \"type 13\" | awk \'{print $8}\'",
                shell=True)
            # check # drives attached
            # each drive gets a dmesg id of the form 'sg<nn>'
            cmp = out.split()[0]

            # sometimes, the type(sgXX) is in the 7th column and not 8th
            if cmp == 'type':
                out = qx(
                    "/bin/dmesg | grep sg | grep \"type 13\" | awk \'{print $7}\'",
                    shell=True)
                cmp = out.split()[0]

            multipleDevices = False
            for word in out.split():
                if not cmp == word:
                    #multipleDevices = True
                    break
            if not multipleDevices:
                #finally lets send the SCSI command to encrypt
                self.messageBox.append("Secure Harddrive identified at /dev/" +
                                       cmp)
                try:
                    subprocess.check_call("sudo sg_raw -s 40 -i " + fpathp +
                                          " /dev/" + cmp +
                                          " c1 e1 00 00 00 00 00 00 28 00",
                                          shell=True)
                    self.messageBox.append(
                        "The WD Drive is now unlocked and can be mounted!")

                except subprocess.CalledProcessError:
                    self.messageBox.append(
                        "Failure while sending SCSI decrypt command. Check password and connections."
                    )
                    return

            else:
                self.messageBox.append(
                    "Multiple SCSI 'type 13' devices recognized.")
                self.messageBox.append(
                    "Please unplug everything except the desired drive and retry."
                )
                return

        except subprocess.CalledProcessError:
            self.messageBox.append(
                "Failure couldn't find 'sg' type within dmesg!")
            return

# Drive Unlock successful. So try and automount partitions
        self.pwBox.setEnabled(False)
        self.decryptBtn.setEnabled(False)
        self.mountWD()
Example #29
0
def get_line(filename, address):
    return qx(['addr2line', '-e', filename, address])