Example #1
0
def process_loadedFile(filename):

    loadedfile=loadWeatherIndex(filename)
    
    fengxiangSet=set()
    fengliSet=set()
    for item in loadedfile:  
#        print item[4]
        fengxiang=item[4].split("~")
        for feng in fengxiang:
#            print feng
            fengxiangSet.add(feng)     
        fengli=item[5].split('~')
        for feng in fengli:
            fengliSet.add(feng)
            
    print '----------weather-------------------'    
    print 'fengxiangSet:',len(fengxiangSet)
    for i in fengxiangSet:
        print i
    print 'fengliSet:',len(fengliSet)
    for i in fengliSet:
        print i

    processed_file=[]

    for item in loadedfile: 

        temp=item[0].split('-')
        temp=[string.atoi(i) for i in temp]
        date=datetime.date(*temp)

       
       
        temperature_high=string.atoi(item[1].strip(u'℃'))
       
        temperature_low=string.atoi(item[2].strip(u'℃'))
       
       
        tianqi=[u'晴',u'云',u'阴',u'雨',u'雾',u'霾',u'雪',u'沙',u'雷']
        weather=[1 for i in tianqi]
        for i in range(len(tianqi)):
            if item[3].find(tianqi[i]) == -1:
                weather[i]=0                   
     
    
        fengxiang=[1 for i in fengxiangSet]
        fengxiangSet=list(fengxiangSet)
        for i in range(len(fengxiangSet)):
            if item[4].find(fengxiangSet[i]) == -1:
                fengxiang[i]=0       
        fengli=[1 for i in fengliSet]
        fengliSet=list(fengliSet)
       
        for i in range(len(fengliSet)):
            if item[5].find(fengliSet[i]) == -1:
                fengli[i]=0
                      
        processed_file+=[ [date]+[temperature_high]+[temperature_low]+[weather]+[fengxiang]+[fengli] ]
    return processed_file
def dump_gop_rec(pathF, pathP):
    logF = open(pathF, "r")
    logP = open(pathP, "w")
    iFrame = 0
    pFrame = 0
    gopStarted = 0
    totalFrameNum = 0
    while True:
      aLine = logF.readline()
      if (aLine == ""):
        break
      if ("+" in aLine):
	tokens = re.split(":", aLine)
	if ("1" in tokens[1]):
	    iFrame = string.atoi(string.lstrip(tokens[0], "+"))
	    totalFrameNum = totalFrameNum + 1
	    if (gopStarted == 0):
		logP.write(str(iFrame) + ":")
		gopStarted = 1
	    else:
		logP.write(str(iFrame-1) + ":\n")
		logP.write(str(iFrame) + ":")
        if ("65" in tokens[1]):
            #it's p frame
            pFrame = string.atoi(string.lstrip(tokens[0], "+"))
            totalFrameNum = totalFrameNum + 1
            #print pFrame
    logP.write(str(totalFrameNum) + ":\n")
    logF.close()
    logP.close()
Example #3
0
def rollbackDiagnose(diagnoseId):
    userId=session['userId']
    if userId is None:
        return json.dumps(rs.NO_LOGIN.__dict__,ensure_ascii=False)
    userId=string.atoi(userId)

    status=request.form.get('status')
    comments=request.form.get('comments')
    if status:
        status=string.atoi(status)
    diagnose=Diagnose.getDiagnoseById(diagnoseId)
    if diagnose is None:
        return  json.dumps(rs.NO_DATA.__dict__,ensure_ascii=False)
    if hasattr(diagnose,'adminId') and diagnose.adminId and  diagnose.adminId==userId:
        if status is None:
            status=constant.DiagnoseStatus.Draft
        diagnose.status=status
        Diagnose.save(diagnose)

        diagoseLog=DiagnoseLog(userId,diagnoseId,constant.DiagnoseLogAction.DiagnoseNeedUpateAction)
        diagoseLog.description=comments
        DiagnoseLog.save(db_session,diagoseLog)

        if hasattr(diagnose,'patient') and diagnose.patient.userID:
            content=dataChangeService.getPatienDiagnoseMessageContent(diagnose)

            #诊断通知
            message=Message(constant.DefaultSystemAdminUserId,diagnose.patient.userID,'诊断通知',content,constant.MessageType.Diagnose)
            Message.save(message)

        return  json.dumps(rs.SUCCESS.__dict__,ensure_ascii=False)
    else:
        return  json.dumps(rs.PERMISSION_DENY.__dict__,ensure_ascii=False)
Example #4
0
def varParse(entry):
    id=0
    title='None'
    units='None'
    datatype=slats.LatsFloat
    leveltype=''
    scale_fac=-999
    precision=-999
    comment1=''
    comment2=''
    nentry = len(entry)
    if nentry>1: id = string.atoi(entry[1])
    if nentry>2: title = string.strip(entry[2])
    if nentry>3: units = string.strip(entry[3])
    if nentry>4: 
	if string.lower(string.strip(entry[4]))=='float':
	    datatype = slats.LatsFloat
	else:
	    datatype = slats.LatsInt
    if nentry>5: leveltype = string.strip(entry[5])
    if nentry>6: scale_fac = string.atoi(entry[6])
    if nentry>7: precision = string.atoi(entry[7])
    if nentry>8: comment1 = string.strip(entry[8])
    if nentry>9: comment2 = string.strip(entry[9])
    return [id,title,units,datatype,leveltype,scale_fac,precision,comment1,comment2]
Example #5
0
def evaluateDiagnose(diagnoseId):
    userId=session['uesrId']
    if userId is None:
        return json.dumps(rs.NO_LOGIN.__dict__,ensure_ascii=False)
    userId=string.atoi(userId)

    score=request.args.get('score')
    description=request.args.get('description')
    if score:
        score=string.atoi(score)
    else:
        return  json.dumps(rs.PARAM_ERROR.__dict__,ensure_ascii=False)

    diagnose=Diagnose.getDiagnoseById(diagnoseId)
    if diagnose is None:
        return  json.dumps(rs.NO_DATA.__dict__,ensure_ascii=False)
    if hasattr(diagnose,'patient') and diagnose.patient and diagnose.patient.userID and  diagnose.patient.userID==userId:
        diagnose.status=constant.DiagnoseStatus.Diagnosed
        diagnose.score=score
        Diagnose.save(diagnose)

        diagoseLog=DiagnoseLog(userId,diagnoseId,constant.DiagnoseLogAction.DiagnoseFinished)
        diagoseLog.description=description
        DiagnoseLog.save(db_session,diagoseLog)
        return  json.dumps(rs.SUCCESS.__dict__,ensure_ascii=False)
    else:
        return  json.dumps(rs.PERMISSION_DENY.__dict__,ensure_ascii=False)
Example #6
0
def fn_create_cirela(i_source_fid,i_target_fid,i_type_fid,i_owner,i_family_id,i_change_log,i_endtime=ENDTIME):    
    #Function:create ci_relation
    v_crd = 'PCRD00000001'
    v_frd = 'FCRD00000001'
    ci_id = db.query('select max(id) cad, max(family_id) fad from t_ci_relation ')
    #Although there will be only one record, it also needs to iteratively generate the dict. It will raise an error if directly transforming ci_id[0] to json format
    ci_as_dict = []
    for ci in ci_id:
        ci_as_dict.append(ci)
    
    v_json = json.dumps(ci_as_dict).decode("GB2312")
    v_djson = json.loads(v_json,encoding="gb2312")
    v_num = len(v_djson)
    #Take the default value when inserting the first record
    if v_num <> 0 :
        v_crd = v_djson[0]['CAD']
        v_frd = v_djson[0]['FAD']
        v_crd = 'PCRD' + str(string.atoi(v_crd[4:])+1).rjust(8,'0')
        if i_family_id == None :
            v_frd = 'FCRD' + str(string.atoi(v_frd[4:])+1).rjust(8,'0')
        else:
            v_frd = i_family_id
    v_curtime = time.strftime("%Y%m%d%H%M%S", time.localtime())
    n = db.insert('t_ci_relation',id = v_crd,source_fid = i_source_fid, target_fid = i_target_fid, type_fid = i_type_fid, 
                  owner = i_owner, starttime = v_curtime, endtime = i_endtime, family_id = v_frd, change_log = i_change_log)
    return v_frd
Example #7
0
def get_ms_space(ms_local):    
    try:
        # get disk space
        url = 'http://%s:%d/macross?cmd=querydisk' % (ms_local.controll_ip, ms_local.controll_port)
        print url
        req = urllib2.Request(url)
        response = urllib2.urlopen(req, timeout=10)
        output = response.read()
        print output
        #return=ok
        #result=12|22005|2290
        lines = output.split('\n')
        if(len(lines)>=2):
            line_1 = lines[0].strip()
            line_2 = lines[1].strip()
            if(line_1 == 'return=ok'):
                fields = line_2.split('=')
                field2 = fields[1]
                values = field2.split('|')
                ms_local.total_disk_space = string.atoi(values[1])
                ms_local.free_disk_space = string.atoi(values[2])
                ms_local.save()
                return True
    except:
        print '%s get disk space error' % (ms_local.controll_ip)        
    return False
Example #8
0
 def getLearningParams(self):
     return {
         "pretrain_epochs": string.atoi(self.pretrian_epochs_line_edit.text()),
         "pretrain_lr": 1.0 / pow(10, self.pretrain_lr_slider.value()),
         "finetune_epochs": string.atoi(self.finetune_epochs_line_edit.text()),
         "finetune_lr": 1.0 / pow(10, self.finetune_lr_slider.value()),
     }
Example #9
0
def unescape(input):
    result = input[:]

    aliases = {
        "quot": "\"",
        "amp":  "&",
        "gt":   ">",
        "lt":   "<"
    }

    pattern = r"&((?:#\d+)|(?:(?:\w|\d)+));"
    while True:
        match = re.search(pattern, result)
        if match is None:
            break

        value = match.group(1)
        if aliases.has_key(value):
            result = result[:match.start()] + aliases[value] + result[match.end():]
        elif value[0] == "#":
            if value[1].lower() == "x":
                value = unichr(string.atoi(value[2:], 16))
            else:
                value = unichr(string.atoi(value[1:]))
            result = result[:match.start()] + value + result[match.end():]

    return result
Example #10
0
def parse_address(local_address, str):
    check.check_is_af_inet_address(local_address)  #=@R19
    
    try:
        match = re.match(r"\s*(.+)\s*:\s*([0-9]+)\s*$", str)
        if match:
            ret = (socket.gethostbyname(match.group(1)),
                   string.atoi(match.group(2)))
        else:
            match = re.match(r"\s*([0-9]+)\s*$", str)
            if match:
                ret = (local_address[0],
                       string.atoi(match.group(1)))
            else:
                ret = (socket.gethostbyname(string.strip(str)),
                       settings.default_ports[0])
        
        check.check_is_af_inet_address(ret)  #=@E9
        # Proof: socket.gethostbyname returns a string, atoi returns an int,
        # settings.default_ports is a non-empty list of integers.
        # local_address is itself an af_inet_address (@R19), so its first
        # element is a string suitable for an af_inet_address.  local_address
        # is deeply immutable from @E11.
        return ret

    except:
        raise error.Error(_("Could not find peer.\n"+\
                            "Please give a valid IP address or machine name,\n"+\
                            "optionally followed by a colon and a port number"))
Example #11
0
def CheckFillFile(fillfile):
    myfile=open(fillfile,'r').readlines()
    valid=True
    for r in myfile[1:]:
        temp=string.split(r)
        if len(temp)<3:
            valid=False
            print "Bad line '%s' in fillfile '%s':  not enough arguments"%(r,fillfile)
            return valid
        try:
            fill=string.atoi(temp[0])
        except:
            print "Bad line '%s' in fillfile '%s':  can't read fill # as an integer"%(r,fillfile)
            valid=False
            return valid
        try:
            runs=string.strip(temp[2])
            runs=string.split(runs,",")
            for run in runs:
                try:
                    string.atoi(run)
                except:
                    valid=False
                    print "Bad line '%s' in fillfile '%s':  can't parse runs"%(r,fillfile)
                    return valid
        except:
            print "Bad line '%s' in fillfile '%s':  can't ID runs"%(r,fillfile)
            valid=False
            return valid
    print "<CheckFillFile>  fill file '%s' appears to be formatted correctly!"%fillfile
    return valid
Example #12
0
File: ps9.py Project: Nyna71/Python
def loadSubjects(filename=SHORT_SUBJECT_FILENAME):
    """
    Returns a dictionary mapping subject name to (value, work), where the name
    is a string and the value and work are integers. The subject information is
    read from the file named by the string filename. Each line of the file
    contains a string of the form "name,value,work".

    returns: dictionary mapping subject name to (value, work)
    """

    # The following sample code reads lines from the specified file and prints
    # each one.
    subjects = {}
    
    inputFile = open(filename)
    for line in inputFile:
        if len(line) == 0 or line[0] == '#':
            continue
        dataLine = string.split(line, sep=",")
        courseName = dataLine[0]
        valueworkTuple = (string.atoi(dataLine[1]), string.atoi(dataLine[2]))
        
        subjects[courseName] = valueworkTuple
        #print "Course Name:", courseName, "valueworkTuple:", valueworkTuple
    
    return subjects
Example #13
0
    def ChkCommAddr(self, event):
        sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)        
        EDIdInput = self.EDId.GetValue()
        #EDMacInput = self.EDMac.GetValue()
        EDNetIdInput = self.EDNetId.GetValue()
        
        #EDMacInputList = EDMacInput.split(' ')
        #Mac1 = hex(int(EDMacInputList[0], 16))
        #Mac2 = hex(int(EDMacInputList[1], 16))
        #Mac3 = hex(int(EDMacInputList[2], 16))
        #Mac4 = hex(int(EDMacInputList[3], 16))
        #Mac5 = hex(int(EDMacInputList[4], 16))
        #print Mac1,Mac2,Mac3,Mac4,Mac5

        self.LogInfo.AppendText('校验通讯地址' + "\r\n")
        #self.LogInfo.AppendText('EDMacInput ' + EDMacInput + "\r\n")
        self.LogInfo.AppendText('EDIdInput ' + EDIdInput + "\r\n")
        self.LogInfo.AppendText('EDNetIdInput ' + EDNetIdInput + "\r\n")
        
        ChkAddrMsg = struct.pack('!3l', 1155, string.atoi(EDNetIdInput), string.atoi(EDIdInput))
        #self.LogInfo.AppendText(ChkAddrMsg)
        self.LogInfo.AppendText(repr(ChkAddrMsg) + "\r\n")
        self.LogInfo.AppendText("\r\n")

        #sock.sendto(ChkAddrMsg, ('10.30.141.220', 5555))
        sock.sendto(ChkAddrMsg, ('127.0.0.1', 5555))
        #szBuf = sock.recvfrom(1024)
        #self.LogInfo.AppendText("recv " + szBuf + "\r\n")
        sock.close();
        #self.LogInfo.AppendText("end of connect" + "\r\n")

        self.BtnChkCommAddr.SetLabel("校验通讯地址")
Example #14
0
def pkgcmp(pkg1,pkg2):
    """ Compares two packages, which should have been split via
    pkgsplit(). if the return value val is less than zero, then pkg2 is
    newer than pkg1, zero if equal and positive if older.

    >>> pkgcmp(['glibc', '2.2.5', 'r7'], ['glibc', '2.2.5', 'r7'])
    0
    >>> pkgcmp(['glibc', '2.2.5', 'r4'], ['glibc', '2.2.5', 'r7'])
    -1
    >>> pkgcmp(['glibc', '2.2.5', 'r7'], ['glibc', '2.2.5', 'r2'])
    1
    """

    mycmp = vercmp(pkg1[1],pkg2[1])
    if mycmp > 0:
        return 1
    if mycmp < 0:
        return -1
    r1=string.atoi(pkg1[2][1:])
    r2=string.atoi(pkg2[2][1:])
    if r1 > r2:
        return 1
    if r2 > r1:
        return -1
    return 0
Example #15
0
def decodeDP_POI(C):
        I = -1;
        H = 0;
        B = "";
        J = len(C);
        G = C[J - 1];
        C = C[0: J - 1];
        J -= 1
        for E in range(0, J):
            D = string.atoi(C[E], settings['cha']) - settings['add'];
            if D >= settings['add']:
                D = D - settings['plus']
            B += intToStr (D, settings['cha'])
            if D > H:
                I = E;
                H = D
        A = string.atoi(B[0:I], settings['digi']);
        F = string.atoi(B[I + 1:], settings['digi']);
        L = float(A + F - string.atoi(G, 36)) / 2;
        K = float(F - L) / 100000;
        L = float(L) / 100000;
        return {
            'lat': K,
            'lng': L
        }
Example #16
0
def readportlist(listfile):
	print 'File',listfile,
	try:
		f = open(listfile,'r')
		print 'Read Success',
	except:
		print 'Read Failed'
		return False
	total = 0
	for line in f.readlines():
		if line[-1] == '\n':
			line = line[0:-1]
		port1 = 0
		port2 = 0
		ports_iter = iter(line.split(' '))
		try:
			port1 = ports_iter.next()
			port2 = ports_iter.next()
		except:
			port2 = port1

		if port2:
			total += 1
			port1 = string.atoi(port1)
			port2 = string.atoi(port2)
			addport(port1,port2)
		else:
			break
	print 'Add',total,'port range'
	return total
Example #17
0
def lanceScriptSVDetect():
    #liStrains = ['55-86_1','62-196','62-1041','67-588','CBS2861','CBS4104','CBS4568','CBS5828','CBS6545','CBS6547','CBS6626','CBS10367','CBS10368','dd281a','DBVPG3108','DBVPG4002','68917-2','CBS10369','CBS6546','DBVPG3452','NRBC101999','NRBC10572','NRBC10955','NRBC1811','NRBC1892']
    #liStrains = ['55-86_1','62-196','62-1041','67-588','CBS2861']
    #liStrains = ['CBS4104','CBS4568','CBS5828','CBS6545','CBS6547']
    #liStrains = ['CBS6626','CBS10367','CBS10368','dd281a','DBVPG3108']
    #liStrains = ['DBVPG4002','68917-2','CBS10369','CBS6546','DBVPG3452']
    liStrains = ['NRBC101999', 'NRBC10572', 'NRBC10955', 'NRBC1811', 'NRBC1892']

    workdir = "/Volumes/BioSan/Users/dpflieger/SVDetect"
    #workdir = "/Volumes/BioSan/Users/jhou/Documents/Incompatibility/StructuralVariants/SVDetect"
    mapLen = "/Volumes/BioSan/Users/dpflieger/Data/saklChromMap.len"
    #mapLen = "%s/saceChromMap.len" % workdir
    for strain in liStrains:
        repOut = "%s/%s" % (workdir, strain)
        confFile = "%s/%s.sv.conf" % (repOut, strain)
        #os.system("touch %s" %confFile)
        # au BGI, long de 100
        readLen = 100
        #bamFile = "%s/aln_%s_PE-rel.sorted.ab.bam" % (repOut,strain)
        #bamFile = "/Volumes/BioSan/Users/dpflieger/BWA/%s/alnFin-%sPE-rel.sorted.inRef.ab.bam" % (strain,strain)
        bamFile = "/Volumes/BioSan/Users/dpflieger/SVDetect/%s/alnFin-%sPE-rel.sorted.inRef.ab.bam" % (strain, strain)
        preSVfile = "/Volumes/BioSan/Users/dpflieger/SVDetect/%s/preProcess_%s.log" % (strain, strain)
        lPreProc = getMuSigmaFromSVdetectPreProcess(preSVfile)
        mu = string.atoi(lPreProc[0])
        sigma = string.atoi(lPreProc[1])
        createSVConfFile(confFile, strain, bamFile, readLen, mapLen, mu, sigma)

        cmd = "/Volumes/BioSan/opt/SVDetect_r0.7m/bin/SVDetect linking filtering -conf %s" % (confFile)
        os.system(cmd)
        cmd2 = "/Volumes/BioSan/opt/SVDetect_r0.7m/bin/SVDetect links2SV -conf %s" % (confFile)
        os.system(cmd2)
Example #18
0
def is_valid_msg_type(x):
    """
    @return: True if the name is a syntatically legal message type name
    @rtype: bool
    """
    if not x or len(x) != len(x.strip()):
        return False
    base = base_msg_type(x)
    if not rosidl.names.is_legal_resource_name(base):
        return False
    #parse array indicies
    x = x[len(base):]
    state = 0
    i = 0
    for c in x:
        if state == 0:
            if c != '[':
                return False
            state = 1 #open
        elif state == 1:
            if c == ']':
                state = 0 #closed
            else:
                try:
                    string.atoi(c)
                except:
                    return False
    return state == 0
Example #19
0
def ReadSparseMatrix( filename,
                      separator = "\t",
                      numeric_type = numpy.float,
                      is_symmetric = None):
    """read sparse matrix."""

    lines = map(lambda x: string.split(x[:-1], separator)[:3],
                filter(lambda x: x[0] != "#", open(filename,"r").readlines()))

    data = map(lambda x: (string.atoi(x[0]), string.atoi(x[1]), string.atof(x[2])), lines)

    num_rows = max( map(lambda x: x[0], data))
    num_cols = max( map(lambda x: x[1], data))   

    if (is_symmetric):
        num_rows= max( num_rows, num_cols)
        num_cols= max( num_rows, num_cols)

    matrix = numpy.zeros( (num_rows, num_cols), numeric_type )

    for row, col, weight in data:
        matrix[row-1,col-1] = weight

    if is_symmetric:
        for col, row, weight in data:
            matrix[row-1,col-1] = weight
            
    return matrix
Example #20
0
    def testCapturePictureWithSelfTimer(self):
        """
        Summary:testCapturePictureWithSelfTimerOff: Capture image with Self-timer off
        Steps:  1.Launch HDR capture activity
                2.Set Self-timer
                3.Touch shutter button to capture picture
                4.Exit  activity
        """
        self.expect('1_launch_checkpoint.png', similarity=0.6) 
        #Step 2
	selftimer = random.choice( ['0', '3','5','10'] )
        self._setSelftTimerstatus(selftimer)
        #Step 3
        result = self.adbCmd('ls '+DCIM_PATH)
        if result.find(CAMERA_FOLDER) == -1:
            self.logger.info("no 100ANDRO folder.")
            beforeNo = '0'
        #Get the number of photo in sdcard
        else:
            beforeNo = commands.getoutput('adb shell ls /sdcard/DCIM/* | grep IMG | wc -l')
            self.sleep(3)
        self.touch(Camera,waittime=5)
	time.sleep(12)
        afterNo = commands.getoutput('adb shell ls /sdcard/DCIM/* | grep IMG | wc -l')
        if string.atoi(beforeNo) != string.atoi(afterNo) - 1:
            self.fail('take picture fail!')
        self._setSelftTimerstatus('0')
Example #21
0
    def evt_save_as( self, master=None):
##    def __init__(self, eself, parent, vcs_legacy, type, title, text, entry_str = ''):
##       create_entry_popup(eself, parent, vcs_legacy, 'sa',('Save VCS colormap ( %s ) as:' % vcs_legacy.getcolormapname()),'Enter the new name of the colormap:\n\tFor example:\n\t\tnewcolormapname')
        self.savedialog = Pmw.Dialog( master=master,
            title = 'Save VCS TextObject ( %s ) as:' % self.text.Tt_name,
            buttons = ('OK', 'Dismiss'),
            defaultbutton = 'OK',
            command = self.rename_text )

        lbl=Tkinter.Label(self.savedialog.interior(),
            text = 'Enter the new name of the text object:\n\tFor example:\n\t\tnewname',
            justify = 'left',
            anchor = 'w',
            )
        lbl.pack( expand = 1, fill = 'both', padx=10, pady=5 )

        self.eny3=Pmw.EntryField(self.savedialog.interior(),
            labelpos = 'w',
            entry_background = 'white',
            entry_foreground = 'black',
            value = '',
            entry_width =  50,
            )
        self.eny3.pack( expand = 1, fill = 'both', padx=10, pady=5 )

        # Position dialog popup
        parent_geom = self.dialog.geometry()
        geom = string.split(parent_geom, '+')
        d1 = string.atoi( geom[1] )
        d2 = string.atoi( geom[2] )
        self.savedialog.activate(geometry= "+%d+%d" % (d1, d2) )
Example #22
0
    def getImageData(self):
        "Gets data, height, width - whatever type of image"
        image = self.image
        (width, height) = self.dimensions

        if type(image) == StringType:
            self.filename = image
            if os.path.splitext(image)[1] in ['.jpg', '.JPG', '.jpeg', '.JPEG']:
                (imagedata, imgwidth, imgheight) = self.jpg_imagedata()
            else:
                if not self.imageCaching:
                    imagedata = pdfutils.cacheImageFile(image,returnInMemory=1)
                else:
                    imagedata = self.cache_imagedata()
                #parse line two for width, height
                words = string.split(imagedata[1])
                imgwidth = string.atoi(words[1])
                imgheight = string.atoi(words[3])
        else:
            import sys
            if sys.platform[0:4] == 'java':
                #jython, PIL not available
                (imagedata, imgwidth, imgheight) = self.JAVA_imagedata()
            else:
                (imagedata, imgwidth, imgheight) = self.PIL_imagedata()
        #now build the PDF for the image.
        if not width:
            width = imgwidth
        if not height:
            height = imgheight
        self.width = width
        self.height = height
        self.imageData = imagedata
 def __normalize(self, event=None):
     ew = event.widget
     contents = ew.get()
     icursor = ew.index(INSERT)
     if contents == '':
         contents = '0'
     if contents[0] in 'xX' and self.__hexp.get():
         contents = '0' + contents
     # figure out what the contents value is in the current base
     try:
         if self.__hexp.get():
             v = string.atoi(contents, 16)
         else:
             v = string.atoi(contents)
     except ValueError:
         v = None
     # if value is not legal, delete the last character inserted and ring
     # the bell
     if v is None or v < 0 or v > 255:
         i = ew.index(INSERT)
         if event.char:
             contents = contents[:i-1] + contents[i:]
             icursor = icursor-1
         ew.bell()
     elif self.__hexp.get():
         contents = hex(v)
     else:
         contents = int(v)
     ew.delete(0, END)
     ew.insert(0, contents)
     ew.icursor(icursor)
Example #24
0
def elong_request_parser(content):
    
    result = -1

    try:
        infos = content.split('|')
        flight_info = infos[0].strip()
        time_info = infos[1].strip()
        ticketsource = infos[2].strip()

        flight_no = flight_info.split('-')[0]
        dept_id,dest_id = flight_info.split('-')[1],flight_info.split('-')[2]

        #date:20140510,time:09:10
        dept_day,dept_hour = time_info.split('_')[0],time_info.split('_')[1]

        dept_date = dept_day[0:4] + '-' + dept_day[4:6] + '-' + dept_day[6:]#2014-05-10

        dept_time = dept_date + 'T' + dept_hour + ':00'

        dept_id = cities_dict[dept_id]
        dest_id = cities_dict[dest_id]
        location = dept_id +  '-' + dest_id

        origday = datetime.datetime(string.atoi(dept_date[0:4]),string.atoi(dept_date[5:7]),string.atoi(dept_date[8:]))
        urlday = (origday - datetime.datetime.today()).days
        #dept_date = orig_date
        #logger.info('contents: %s %s %s %s '%(location,flight_no,dept_date,str(urlday)))
    except Exception,e:
        logger.error(str(e))
        logger.error('Content Error: Wrong content format with %s'%content)
        return result
Example #25
0
    def getImageData(self,preserveAspectRatio=False):
        "Gets data, height, width - whatever type of image"
        image = self.image

        if type(image) == StringType:
            self.filename = image
            if os.path.splitext(image)[1] in ['.jpg', '.JPG', '.jpeg', '.JPEG']:
                (imagedata, imgwidth, imgheight) = self.jpg_imagedata()
            else:
                if not self.imageCaching:
                    imagedata = pdfutils.cacheImageFile(image,returnInMemory=1)
                else:
                    imagedata = self.cache_imagedata()
                words = string.split(imagedata[1])
                imgwidth = string.atoi(words[1])
                imgheight = string.atoi(words[3])
        else:
            import sys
            if sys.platform[0:4] == 'java':
                #jython, PIL not available
                (imagedata, imgwidth, imgheight) = self.JAVA_imagedata()
            else:
                (imagedata, imgwidth, imgheight) = self.PIL_imagedata()
        self.imageData = imagedata
        self.imgwidth = imgwidth
        self.imgheight = imgheight
        self.width = self.width or imgwidth
        self.height = self.height or imgheight
def getLOSS(st_ip,ed_ip):
    part1 = "'%(rexmt-data-bytes)d / %(transport-layer-byte)d'"
    part2 = '%s:*-%s:*'%(st_ip,ed_ip)
    part3 = "'"+part2+"'"
    filename = 'loss_'+st_ip+'_'+ed_ip+'.txt'
    cmd = "captcp statistic --format %s --filter %s trace2.txt >./%s"%(part1,part3,filename)
    os.system(cmd)
    floss = open(filename)
    tran = 0.0;
    retran = 0.0;
    try:
        lines = floss.readlines()
        for line in lines:
            mid = line.find('/')
            ed = line.find('\n')
            retran = retran + (float)(string.atoi(line[0:mid-1]))
            tran = tran + (float)(string.atoi(line[mid+2:ed]))
        if(tran == 0.0):
            loss = 0
        else:
            loss = retran / tran
        loss = float('%0.4f'%loss)
        print 'data loss from %s to %s:'%(st_ip,ed_ip),loss
    finally:
        floss.close()
        
    os.system('sudo rm -rf %s'%filename)
    return loss
def extractQueryFromRequest(rec, request):
    post_field = dataplus.dictGetVal(request.REQUEST, 'post_field', '')
    query = models.RecruiterRecentSearchQuery(recruiter=rec.account)
    if post_field != '':
        pickled_query = dataplus.dictGetVal(request.REQUEST,post_field)
        query_dic = cPickle.loads(pickled_query)
        
        if query_dic['industry_category'] != '':
            query.industry_category = models.IndustryCategory.objects.get(name=query_dic['industry_category'])
        query.designation = query_dic['designation']
        query.mandatory_skills = query_dic['mandatory_skills']
        query.desired_skills = query_dic['desired_skills']
        query.location = query_dic['location']
        query.min_exp_years = query_dic['min_exp_years']
        query.max_exp_years = query_dic['max_exp_years']
        query.qualifications = query_dic['educational_qualifications']
    else:
        if dataplus.dictGetVal(request.REQUEST, 'industry_category', '') != '':
            query.industry_category = models.IndustryCategory.objects.get(name=request.REQUEST['industry_category'])
        query.designation = dataplus.dictGetVal(request.REQUEST, 'designation', escapeHtml=True)
        query.mandatory_skills = dataplus.dictGetVal(request.REQUEST, 'mandatory_skills', escapeHtml=True)
        query.desired_skills = dataplus.dictGetVal(request.REQUEST, 'desired_skills', escapeHtml=True)
        query.location = dataplus.dictGetVal(request.REQUEST, 'location', escapeHtml=True)
        exp = string.split(request.REQUEST['experience'],'-')
        query.min_exp_years = string.atoi(exp[0])
        query.max_exp_years = string.atoi(exp[1])
        query.educational_qualifications = dataplus.dictGetVal(request.REQUEST, 'educational_qualifications', escapeHtml=True)
    return query
def readRain(fpath,iskp):
    #iskp  the total line skipped of the file
    # fpath   the full path of the file
    # usage: onedim=readAscii(fpaht,iskp)
    onedim=[]
    ystr=[]
    mstr=[]
    dstr=[]
    linesplit=[]
    datestr=[]
    f=open(fpath)
    ff=f.readlines()[iskp:]  ## first line in obs file is legend 
    for line in ff:
        line=string.lstrip(line)
        linesplit1=line[:-1].split(' ')
        datestr.append(linesplit1[0])
        linesplit.append(linesplit1[1:])
    for lnstrs in linesplit:
        #print lnstrs          
        for strs in lnstrs:
            if strs!='':
                #print strs
                onedim.append(string.atof(strs))
    for lnstrs in datestr:           
        ystr.append(string.atoi(lnstrs[0:4]))
        mstr.append(string.atoi(lnstrs[4:6]))
        dstr.append(string.atoi(lnstrs[6:8]))
    del linesplit1
    f.close()
    return ystr,mstr,dstr,onedim
Example #29
0
def vertDimParse(entry):
    description = 'None'
    units = 'None'
    verticality = slats.SingleLevel
    positive = slats.UpDirection
    grib_id = 0
    grib_p1 = 0
    grib_p2 = 0
    grib_p3 = 0
    nentry = len(entry)
    if nentry>1: description = string.strip(entry[1])
    if nentry>2: units = string.strip(entry[2])
    if nentry>3:
	if string.lower(string.strip(entry[3]))=='single':
	    verticality = slats.SingleLevel
	else:
	    verticality = slats.MultiLevel
    if nentry>4:
	if string.lower(string.strip(entry[4]))=='up':
	    positive = slats.UpDirection
	else:
	    positive = slats.DownDirection
    if nentry>5: grib_id = string.atoi(entry[5])
    if nentry>6: grib_p1 = string.atoi(entry[6])
    if nentry>7: grib_p2 = string.atoi(entry[7])
    if nentry>8: grib_p3 = string.atoi(entry[8])
    return [description, units, verticality, positive, grib_id, grib_p1, grib_p2, grib_p3]
 def _get_from_the_frame(self):
     '''
     从输入获取配置
     :return:
     '''
     IP = self.IpCtrl.GetValue()
     if(IP):
         self.plcConfigDict["PLCAddr"] = IP
     PORT = self.PortCtrl.GetValue()
     if(PORT):
         self.plcConfigDict["PLCPort"] = string.atoi(PORT)
     SLOT = self.SlotCtrl.GetValue()
     if (SLOT):
         self.plcConfigDict["PLCSlot"] = string.atoi(SLOT)
     RACK = self.RackCtrl.GetValue()
     if (RACK):
         self.plcConfigDict["PLCRack"] = string.atoi(RACK)
     STSAP = self.STSAPCtrl.GetValue()
     if (STSAP):
         self.plcConfigDict["PLCLocalTSAP"] = string.atoi(STSAP)
     RTSAP = self.RTSAPCtrl.GetValue()
     if (RTSAP):
         self.plcConfigDict["PLCRemoteTSAP"] = string.atoi(RTSAP)
     CONTYPE = self.ConTypeCtrl.GetValue()
     if (CONTYPE == "PG"):
         self.plcConfigDict["ConnectionType"] = 1
     elif (CONTYPE == "OP"):
         self.plcConfigDict["ConnectionType"] = 2
     elif (CONTYPE == "BASIC"):
         self.plcConfigDict["ConnectionType"] = 3
Example #31
0
def usage():
	print('** usage: filename -l [matrix/vector length] -b [begin] -e [end] -s [step]')

if __name__ == '__main__':

	begin = 0
	end = 0;
	step = 0;
	netlen = 15;
#==========================================================
# parse command line
	for ind in range(1, len(sys.argv)):
		if sys.argv[ind][0] == '-':
			if sys.argv[ind][1] == 'b':
				ind = ind + 1
				begin = string.atoi(sys.argv[ind])
			elif sys.argv[ind][1] == 'e':
				ind = ind + 1
				end = string.atoi(sys.argv[ind])
			elif sys.argv[ind][1] == 's':
				ind = ind + 1
				step = string.atoi(sys.argv[ind])
			elif sys.argv[ind][1] == 'l':
				ind = ind + 1
				netlen = string.atoi(sys.argv[ind])
	if begin == 0 or end == 0 or step == 0:
		usage()
		sys.exit()
#===========================================================
# call executable file to generate .sp file
# call hspice to simulate circuit netlist, and then output .lis files
Example #32
0
    def __call__(self):
        inp     = self.inp
        parents = self.parents
        decays  = self.decays
        
        self.event = [] # cache HepMC event in original format
        
        # find start of event
        
        found = False
        for line in inp:
            self.event.append(line)
            if line[0] != 'E': continue
            found = True
            self.eventsIn += 1
            break
        else:
            return False

        if not found:
            sys.exit("** hepmcfilter: can't find start of event")

        token = split(line)
        self.eventNumber = atoi(token[1])
        self.numberV     = atoi(token[8])  # number of vertices in event

        self.vertex  = {} # cache for event vertices
        self.parent  = {} # cache for final instance of parents in event

        # loop over vertices in event
        for line in inp:
            self.event.append(line)
            if line[0] == 'V':
                
                # found a vertex
                
                token = split(line)
                
                # get vertex barcode
                vbarcode = atoi(token[1]) 
                self.vertex[vbarcode] = None

                # get number of particles out of this vertex
                nout = atoi(token[8])
                if debug > 2:
                    print '\tvertex(barcode): %10d' % vbarcode
                    print '\tvertex(count):   %10d' % nout

                # particles pertaining to this vertex follow immediately
                # after the vertex
                d = [] # cache for PDG id of particles
                # loop over particles pertaining to current vertex
                for ii in xrange(nout):
                    for line in inp:
                        self.event.append(line)
                        if line[0] != 'P':
                            sys.exit("** hepmcfilter: faulty event record\n" + line)

                        token = split(line)
                        pid   = atoi(token[2])
                        d.append(pid)

                        # if this is not one of the desired parents
                        # continue to the next particle by breaking out
                        # of the inner loop
                        if not (pid in parents): break
                        
                        # found parent particle, cache its pid and vertex
                        self.parent[pid] = atoi(token[11])
                        if debug > 1:
                            print '\t\tpid(%d) vertex(%d)' % (pid, self.parent[pid])
                        # break out of inner loop and move to next particle
                        break
                    else:
                        return False # End of File
                    
                # cache PDG ids of daughters associated with current vertex
                self.vertex[vbarcode] = d
                
                if debug > 1:
                    print "%8d\t%s" % (vbarcode, self.vertex[vbarcode])

            # if we have not exhausted the number of vertices for this
            # event, continue to the next vertex
            if len(self.vertex) < self.numberV: continue

            # ----------------------------------------------------------                
            # we've found all vertices for current event
            # ----------------------------------------------------------
            # For each specified parent particle check if it matches a
            # parent ID in self.parent. If there is no match, we skip the
            # event because the desired particle is not present within the
            # event. If there is a match, we check if the decay of the
            # parent particle matches one of its required decays. An event
            # is selected if the decay of each required parent particle
            # matches at least one of its desired decays.

            keepEvent = True 

            # loop over required parents
            for pid in self.parents:

                # if required parent particle not present in the event
                # skip event.
                if not self.parent.has_key(pid):
                    keepEvent = False
                    if debug > 0:
                        print "**  parent with pid %d not present in event **" % pid
                    break

                # required parent is within event, so get "pointer"
                # to the vertex containing its daughters
                v  = self.parent[pid]  # get "pointer" to vertex
                if debug > 1:
                    print '\tPARENT(%d): vertex(%d)' % (pid, v)

                # if this parent has no daughters skip event
                if not self.vertex.has_key(v):
                    keepEvent = False
                    break

                # found vertex for current parent; get daughters
                daughters = set(self.vertex[v])
                if debug > 1:
                    print "\tVERTEX(%d): %s" % (v, daughters)

                # loop over required decays for current parent
                # and check if there is a match with the actual
                # decay.
                keep = False
                for d in decays[pid]:
                    c = 0
                    for p in d:
                        if p in daughters: c += 1
                    keep = keep or (c == len(d))
                    if keep: break

                keepEvent = keepEvent and keep

            if keepEvent:
                self.eventsOut += 1
                if debug > 0:
                    print "\tKEEP EVENT(%d)" % self.eventNumber
                self.out.writelines(self.event)

            # continue to next event
            return True
        else:
            self.out.write('HepMC::IO_GenEvent-END_EVENT_LISTING\n')
            return False # End of File
Example #33
0
    def setup(self, config_file):
        InventoryDatabaseConfig.setup(self, config_file)
        self.rules_matching = []
        if self.dbname == None:
            self.dbname = 'inventory'

        if self.cp.has_option("main",
                              "server"):  # TODO remove in a future version
            logging.getLogger().warning(
                "'server' is obslete, please replace it in your config file by 'host'"
            )
            self.bind = self.cp.get("main", 'server')
        elif self.cp.has_option('main', 'host'):
            self.bind = self.cp.get("main", 'host')
        if self.cp.has_option('main', 'port'):
            self.port = self.cp.get("main", 'port')
        if self.cp.has_option('main', 'ocsmapping'):
            self.ocsmapping = self.cp.get("main", 'ocsmapping')
        if self.cp.has_option('main', 'xmlfixplugindir'):
            self.xmlfixplugindir = self.cp.get("main", 'xmlfixplugindir')
        if self.cp.has_option('main', 'xmldumpdir'):
            self.xmldumpdir = self.cp.get("main", 'xmldumpdir')
        if self.cp.has_option('main', 'xmldumpactive'):
            self.xmldumpactive = self.cp.get("main", 'xmldumpactive')
        if self.cp.has_option('main', 'xmlfixplugindir'):
            self.xmlfixplugindir = self.cp.get("main", 'xmlfixplugindir')
        if self.cp.has_option('main', 'pidfile'):
            self.pidfile = self.cp.get("main", 'pidfile')

        if self.cp.has_option('main', 'enablessl'):
            self.enablessl = self.cp.getboolean('main', 'enablessl')
        if self.cp.has_option('main', 'verifypeer'):
            self.verifypeer = self.cp.getboolean('main', 'verifypeer')
        if self.cp.has_option('main', 'certfile'):
            self.certfile = self.cp.get('main', 'certfile')
        if self.cp.has_option('main', 'cacert'):
            self.cacert = self.cp.get('main', 'cacert')
        if self.cp.has_option('main', 'privkey'):
            self.privkey = self.cp.get('main', 'privkey')
        if self.cp.has_option('main', 'localcert'):
            self.localcert = self.cp.get('main', 'localcert')
        if self.cp.has_option('main', 'enable_forward'):
            self.enable_forward = self.cp.getboolean('main', 'enable_forward')
        if self.cp.has_option('main', 'enable_forward_ocsserver'):
            self.enable_forward_ocsserver = self.cp.getboolean(
                'main', 'enable_forward_ocsserver')
        if self.cp.has_option('main', 'url_to_forward'):
            self.url_to_forward = self.cp.get('main', 'url_to_forward')
        if self.cp.has_option('main', 'inventory_periodicity'):
            self.inventory_periodicity = self.cp.get('main',
                                                     'inventory_periodicity')

        if not os.path.isfile(self.localcert):
            raise Exception('can\'t read SSL key "%s"' % (self.localcert))
            return False
        if not os.path.isfile(self.cacert):
            raise Exception('can\'t read SSL certificate "%s"' % (self.cacert))
            return False
        if self.verifypeer:  # we need twisted.internet.ssl.Certificate to activate certs
            import twisted.internet.ssl
            if not hasattr(twisted.internet.ssl, "Certificate"):
                raise Exception(
                    'I need at least Python Twisted 2.5 to handle peer checking'
                )
                return False

        if self.cp.has_option('main', 'default_entity'):
            self.default_entity = self.cp.get('main', 'default_entity')
        if self.cp.has_option('main', 'entities_rules_file'):
            self.entities_rules_file = self.cp.get('main',
                                                   'entities_rules_file')
        if self.cp.has_section('RulesMatching'):
            self.rules_matching = self.cp.items('RulesMatching')
        if self.cp.has_option('main', 'hostname'):
            path = self.cp.get("main", "hostname").split('|')
            self.hostname = path[0].split('/')
            if len(path) == 2:
                self.hostname.append(path[1].split(':'))

            if len(self.hostname) == 3:
                nom = self.getInventoryNoms()
                if self.hostname[0] in nom:
                    self.hostname[2][0] = (
                        'nom%s%s' % (self.hostname[0], self.hostname[2][0]),
                        self.hostname[2][0])

        if self.cp.has_section("daemon"):
            if self.cp.has_option("daemon", "pid_path"):
                self.pid_path = self.cp.get("daemon", "pid_path")
            if self.cp.has_option("daemon", "user"):
                self.daemon_user = pwd.getpwnam(self.cp.get("daemon",
                                                            "user"))[2]
            if self.cp.has_option("daemon", "group"):
                self.daemon_group = grp.getgrnam(self.cp.get(
                    "daemon", "group"))[2]
            if self.cp.has_option("daemon", "umask"):
                self.umask = string.atoi(self.cp.get("daemon", "umask"), 8)

        if self.cp.has_section("state"):
            if self.cp.has_option("state", "orange"):
                self.orange = self.cp.get("state", "orange")
            if self.cp.has_option("state", "red"):
                self.red = self.cp.get("state", "red")

        for section in self.cp.sections():
            if re.compile('^option_[0-9]+$').match(section):
                params = []
                for param in self.cp.options(section):
                    if re.compile('^param_[0-9]+$').match(param):
                        attrs, value = self.cp.get(section, param).split('##')
                        params.append({
                            'param':
                            map(lambda x: x.split('::'), attrs.split('||')),
                            'value':
                            value
                        })
                self.options[section] = {
                    'name': self.cp.get(section, 'NAME'),
                    'param': params
                }
import string

file_object = open('D:\Data\yoochoose-buys.dat')
file_object_w = open('D:\Data\yoochoose-buys-small.dat', 'w')
n = 100
s = []
for line in file_object:
    index = string.atoi(line.split(",")[0])
    if index <= n:
        s.append(line)
s.sort()
for line in s:
    file_object_w.write(line)
    
file_object_w.close()

Example #35
0
        sys.exit(1)

    elif o == "-c":
        output_format = a

    if o == "-g":
        convert = "L"
    elif o == "-p":
        convert = "P"
    elif o == "-r":
        convert = "RGB"

    elif o == "-o":
        options["optimize"] = 1
    elif o == "-q":
        options["quality"] = string.atoi(a)

if len(argv) != 2:
    usage()

try:
    im = Image.open(argv[0])
    if convert and im.mode != convert:
        im.draft(convert, im.size)
        im = im.convert(convert)
    if output_format:
        im.save(argv[1], output_format, **options)
    else:
        im.save(argv[1], **options)
except:
    print("cannot convert image", end=' ')
Example #36
0
 def hex2str(s):
     s2 = ''
     for i in range(0, len(s), 2):
         s2 = s2 + chr(string.atoi(s[i:i + 2], 16))
     return s2
Example #37
0
                flag = mons_mission(data, con)
            elif (flag == 0):
                print "mons finish the mission!!!"
                flag = 1
                con.close()
                con, addr = a.mons_accept()
            elif (flag == 2):
                print "files cann't be opened in success"
                con.close()
                raise Exception("file op is error")
        except Exception as e:
            print e
            print "all mons must be closed, need to check"
            con.close()
            break


if __name__ == '__main__':
    ip = "127.0.0.1"
    port = 9999
    try:
        opts, args = getopt.getopt(sys.argv[1:], "i:p:", ["ip", "port"])
        for name, value in opts:
            if name in ("-i", "--ip"):
                ip = value
            elif name in ("-p", "--port"):
                port = string.atoi(value)
        schedule_work(ip, port)
    except getopt.GetoptError:
        sys.exit()
Example #38
0
        for a, b in self.bonds:
            a, b = self.atoms[a - 1], self.atoms[b - 1]
            dist = ((a.x - b.x)**2 + (a.y - b.y)**2 + (a.z - b.z)**2)**.5
            if mindist == None or dist < mindist:
                mindist = dist
            if maxdist == None or dist > maxdist:
                maxdist = dist
        return (mindist, maxdist)


if (__name__ == '__main__'):
    if len(sys.argv) < 4:
        sys.stderr.write(__doc__)
        sys.exit(1)

    n = string.atoi(sys.argv[1])
    m = string.atoi(sys.argv[2])
    length = string.atof(sys.argv[3])

    chirality = Chirality(n, m)

    M = Molecule()

    for n in range(chirality.n):
        mmin, mmax = chirality.mlimits(-.5 * length, .5 * length, n)
        for m in range(mmin - 1, mmax + 1):
            x, y, z = chirality.xyz(n, m)
            if -.5 * length <= y <= .5 * length:
                M.add("C", x, y, z)
            x, y, z = chirality.xyz(n + 1. / 3, m + 1. / 3)
            if -.5 * length <= y <= .5 * length:
Example #39
0
        #data = re.sub( r'\:8443', '', self.buffer )
        data = re.sub(r'localhost', self.server.there[0], data)

        self.buffer = self.buffer + data
        self.sender.push(data)

    def found_terminator(self):
        import re
        data = re.sub(r'\:8443', '', self.buffer)
        data = re.sub(r'localhost', self.server.there[0], data)
        self.buffer = ''
        print '<== (%d) %s' % (self.id, repr(data))
        self.sender.push(data + '')

    def handle_close(self):
        print "Closing Connection"
        if len(self.buffer):
            self.found_terminator()

        self.sender.close_when_done()
        self.close()

if __name__ == '__main__':
    import sys
    import string
    if len(sys.argv) < 3:
        print 'Usage: %s <server-host> <server-port>' % sys.argv[0]
    else:
        ps = proxy_server(sys.argv[1], string.atoi(sys.argv[2]),
                          string.atoi(sys.argv[3]))
        asyncore.loop()
Example #40
0
    def test_case_main(self, case_results):
        global case_flag, case_flag_add, case_flag_join, case_flag_groupA, case_flag_groupB
        case_flag = False
        case_flag_add = False
        case_flag_join = False
        case_flag_groupA = False
        case_flag_groupB = False
        global TAG
        TAG = "Dev-ci cases: Contact "
        log_test_framework(TAG, self.name + " -Start")
        """
        cases contnets you need to add
        """

        contact_list = [['contactA', '10086'], ['contactB', '10010']]

        # launch contact
        start_activity("com.android.contacts",
                       "com.android.contacts.activities.PeopleActivity")
        sleep(1)
        contact.go_home()

        # click "All contacts" sheet to lock view
        click_textview_by_text(SC.PRIVATE_CONTACT_CONTACTS_OPTION,
                               isScrollable=0)

        # we need to delete all contact
        contact.contact_to_display()
        local_assert(
            True,
            contact.del_all_contact(SC.PRIVATE_CONTACT_PHONE,
                                    SC.PRIVATE_CONTACT_SIM1,
                                    SC.PRIVATE_CONTACT_SIM2))

        log_test_framework(self.name, "Now add new contactA and B  ")
        for i in range(0, 2):
            scroll_to_top()
            click_imageview_by_desc('add new contact')
            click_textview_by_id('account_type')
            sleep(1)
            click_textview_by_text('PHONE')
            click_textview_by_id('group_list')
            if i == 0:
                click_textview_by_text('Coworkers')
            if i == 1:
                click_textview_by_text('Family')
            goback()
            sleep(3)
            contact.add_contact_into_phone(contact_list[i][0],
                                           contact_list[i][1])

        if search_text(contact_list[0][0]) and search_text(contact_list[1][0]):
            log_test_framework(self.name, "Contact A/B create successfully")
            case_flag_add = True
        else:
            log_test_framework(self.name, "Contact A/B create failed")
            case_flag_add = False
            set_cannot_continue()

        if can_continue():
            click_textview_by_text(contact_list[0][0])
            if is_view_enabled_by_id(VIEW_IMAGE_VIEW,
                                     'menu_edit',
                                     isScrollable=0):
                click_textview_by_id('menu_edit')
                sleep(1)
                #click_imageview_by_desc('More options')
                #click_button_by_index(1)
                send_key(KEY_MENU)
                sleep(1)
                click_textview_by_text('Join')
                click_textview_by_text(contact_list[1][0])
                click_imageview_by_id('save_menu_item')
                scroll_to_bottom()
                if search_text(contact_list[0][0]) and search_text(
                        contact_list[1][1]) and (not search_text(
                            contact_list[1][0])):
                    log_test_framework(
                        self.name, "Contact B have been joined into A editer")
                    case_flag_join = True
                else:
                    log_test_framework(
                        self.name, "Contact B combined with contact A Failed")
                    set_cannot_continue()
        else:
            take_screenshot()

        if can_continue():
            contact.go_home()
            # click "Group" sheet to lock view
            click_textview_by_text('GROUPS', isScrollable=0)
            # index 6 = Coworker
            # index 7 = number of     Coworker
            # index 8 = Family
            # index 9 = number of Family
            # index 10= Friend
            # index 11= number of Friend
            coworker = get_view_text_by_index(VIEW_TEXT_VIEW, 6)
            coworker_counter = get_view_text_by_index(VIEW_TEXT_VIEW, 7)
            family = get_view_text_by_index(VIEW_TEXT_VIEW, 8)
            family_counter = get_view_text_by_index(VIEW_TEXT_VIEW, 9)
            log_test_framework(
                self.name,
                '####Groups detailed info--->####' + coworker + ' : ' +
                coworker_counter + ' ' + family + ' : ' + family_counter)
            local_assert(1, string.atoi(coworker_counter.split(' ')[0]))
            local_assert(1, string.atoi(family_counter.split(' ')[0]))

            click_textview_by_text('Coworkers')
            if search_text(contact_list[0][0]):
                case_flag_groupA = True
            #local_assert(True, search_text(contact_list[0][0]))
            click_imageview_by_desc('Navigate up')
            click_textview_by_text('Family')
            if search_text(contact_list[0][0]):
                case_flag_groupB = True

        contact.go_home()

        case_flag = case_flag_add and case_flag_join and case_flag_groupA and case_flag_groupB

        if case_flag:
            qsst_log_case_status(STATUS_SUCCESS, "", SEVERITY_HIGH)
        else:
            qsst_log_case_status(STATUS_FAILED, "", SEVERITY_HIGH)

        case_results.append(
            (self.case_config_map[fs_wrapper.CASE_NAME_ATTR], case_flag))
Example #41
0
def xres (fini):
  dimstr = file.string_list(fini,"X1-grid")
  dimstr = string.split(dimstr[0])
  return string.atoi(dimstr[3])
    try:
        opts, args = getopt.getopt(sys.argv[1:], \
           'M:h:m:p:r:s:t:w:x:y:')
    except getopt.error, msg:
        sys.stdout = sys.stderr
        print 'Error:', msg, '\n'
        usage()
        sys.exit(2)

    xpf = ypf = None

    # Interpret options
    try:
        for opt, arg in opts:
            if opt == '-M': magnify = atof(arg)
            if opt == '-h': height = string.atoi(arg)
            if opt == '-m': mindelta = string.atoi(arg)
            if opt == '-p': xpf = ypf = string.atoi(arg)
            if opt == '-r': regen = string.atoi(arg)
            if opt == '-s': speed = atof(arg)
            if opt == '-t': newtype = arg
            if opt == '-w': newwidth = string.atoi(arg)
            if opt == '-x': xpf = string.atoi(arg)
            if opt == '-y': ypf = string.atoi(arg)
    except string.atoi_error:
        sys.stdout = sys.stderr
        print 'Option', opt, 'requires integer argument'
        sys.exit(2)
    except atof_error:
        sys.stdout = sys.stderr
        print 'Option', opt, 'requires float argument'
Example #43
0
    def read(self, amt=None):
        if self.fp is None:
            return ''

        if self.chunked:
            chunk_left = self.chunk_left
            value = ''
            while 1:
                if chunk_left is None:
                    line = self.fp.readline()
                    i = string.find(line, ';')
                    if i >= 0:
                        line = line[:i]	# strip chunk-extensions
                    chunk_left = string.atoi(line, 16)
                    if chunk_left == 0:
                        break
                if amt is None:
                    value = value + self._safe_read(chunk_left)
                elif amt < chunk_left:
                    value = value + self._safe_read(amt)
                    self.chunk_left = chunk_left - amt
                    return value
                elif amt == chunk_left:
                    value = value + self._safe_read(amt)
                    self._safe_read(2)	# toss the CRLF at the end of the chunk
                    self.chunk_left = None
                    return value
                else:
                    value = value + self._safe_read(chunk_left)
                    amt = amt - chunk_left

                # we read the whole chunk, get another
                self._safe_read(2)	# toss the CRLF at the end of the chunk
                chunk_left = None

            # read and discard trailer up to the CRLF terminator
            ### note: we shouldn't have any trailers!
            while 1:
                line = self.fp.readline()
                if line == '\r\n':
                    break

            # we read everything; close the "file"
            self.close()

            return value

        elif amt is None:
            # unbounded read
            if self.will_close:
                s = self.fp.read()
            else:
                s = self._safe_read(self.length)
            self.close()	# we read everything
            return s

        if self.length is not None:
            if amt > self.length:
                # clip the read to the "end of response"
                amt = self.length
            self.length = self.length - amt

        # we do not use _safe_read() here because this may be a .will_close
        # connection, and the user is reading more bytes than will be provided
        # (for example, reading in 1k chunks)
        s = self.fp.read(amt)

        return s
Example #44
0
    def do_PUT(self):
        dc = self.IFACE_CLASS
        uri = urlparse.urljoin(self.get_baseuri(dc), self.path)
        uri = urllib.unquote(uri)

        log.debug("do_PUT: uri = %s" % uri)
        log.debug('do_PUT: headers = %s' % self.headers)
        # Handle If-Match
        if 'If-Match' in self.headers:
            log.debug("do_PUT: If-Match %s" % self.headers['If-Match'])
            test = False
            etag = None
            try:
                etag = dc.get_prop(uri, "DAV:", "getetag")
            except:
                pass

            log.debug("do_PUT: etag = %s" % etag)

            for match in self.headers['If-Match'].split(','):
                if match == '*':
                    if dc.exists(uri):
                        test = True
                        break
                else:
                    if match == etag:
                        test = True
                        break
            if not test:
                self.send_status(412)
                self.log_request(412)
                return

        # Handle If-None-Match
        if 'If-None-Match' in self.headers:
            log.debug("do_PUT: If-None-Match %s" %
                      self.headers['If-None-Match'])

            test = True
            etag = None
            try:
                etag = dc.get_prop(uri, "DAV:", "getetag")
            except:
                pass

            log.debug("do_PUT: etag = %s" % etag)

            for match in self.headers['If-None-Match'].split(','):
                if match == '*':
                    if dc.exists(uri):
                        test = False
                        break
                else:
                    if match == etag:
                        test = False
                        break
            if not test:
                self.send_status(412)
                self.log_request(412)
                return

        # locked resources are not allowed to be overwritten
        ifheader = self.headers.get('If')
        if ((self._l_isLocked(uri)) and (not ifheader)):
            return self.send_body(None, 423, 'Locked', 'Locked')

        if ((self._l_isLocked(uri)) and (ifheader)):
            uri_token = self._l_getLockForUri(uri)
            taglist = IfParser(ifheader)
            found = False
            for tag in taglist:
                for listitem in tag.list:
                    token = tokenFinder(listitem)
                    if (token and (self._l_hasLock(token))
                            and (self._l_getLock(token) == uri_token)):
                        found = True
                        break
                if found:
                    break
            if not found:
                res = self.send_body(None, 423, 'Locked', 'Locked')
                self.log_request(423)
                return res

        # Handle expect
        expect = self.headers.get('Expect', '')
        if (expect.lower() == '100-continue'
                and self.protocol_version >= 'HTTP/1.1'
                and self.request_version >= 'HTTP/1.1'):
            self.send_status(100)

        content_type = None
        if 'Content-Type' in self.headers:
            content_type = self.headers['Content-Type']

        headers = {}
        headers['Location'] = uri

        try:
            etag = dc.get_prop(uri, "DAV:", "getetag")
            headers['ETag'] = etag
        except:
            pass

        expect = self.headers.get('transfer-encoding', '')
        if (expect.lower() == 'chunked' and self.protocol_version >= 'HTTP/1.1'
                and self.request_version >= 'HTTP/1.1'):
            self.send_body(None, 201, 'Created', '', headers=headers)

            dc.put(uri, self._readChunkedData(), content_type)
        else:
            # read the body
            body = None
            if 'Content-Length' in self.headers:
                l = self.headers['Content-Length']
                log.debug("do_PUT: Content-Length = %s" % l)
                body = self._readNoChunkedData(atoi(l))
            else:
                log.debug("do_PUT: Content-Length = empty")

            try:
                dc.put(uri, body, content_type)
            except DAV_Error, (ec, dd):
                return self.send_status(ec)

            self.send_body(None, 201, 'Created', '', headers=headers)
            self.log_request(201)
Example #45
0
    rospy.wait_for_service('power_board_control')
    
    try:
        # create a handle to the add_two_ints service
        control = rospy.ServiceProxy('power_board_control', PowerBoardCommand)
        
        print "Requesting %d to %s"%(breaker_number, command)
        
        # simplified style
        resp1 = control(breaker_number, command, 0)
        return resp1.retval
    except rospy.ServiceException, e:
        print "Service call failed: %s"%e

def usage():
    return "%s breaker_number(0 | 1 | 2) command(start | stop | reset | disable | none)"%sys.argv[0]

if __name__ == "__main__":
    
    if len(sys.argv) != 3:
        print usage()
    else:
        try:
            breaker_number = string.atoi(sys.argv[1])
            command = sys.argv[2]
        except:
            print "excepted"
            print usage()
            sys.exit(1)
    print "breaker:%d command:%s = response:%d"%(breaker_number, command, power_board_client(breaker_number, command))
Example #46
0
def DIMENSIONS (fdef):
  dimstr = file.string_list(fdef,"DIMENSIONS")
  dimstr = string.split(dimstr[0])
  return string.atoi(dimstr[2])
Example #47
0
                for x in e[1]:
                    obj = gtk.GtkListItem(make_tv(x.typ, x.name))
                    obj.show()
                    self.lb_rel.append_items([obj])
                return

    def lookup(self, typ, term):  # takes typ for uniformity only, ignores
        if term == '':
            return
        self.textentry.set_text(term)
        self.lb_head.clear_items(0, -1)
        self.lb_rel.clear_items(0, -1)
        self.dat = self.zthes.lookup(term)
        toplist = map(lambda t: t[0], self.dat)
        for e in toplist:
            obj = gtk.GtkListItem(make_tv(e.typ, e.name))
            obj.show()
            self.lb_head.append_items([obj])
        if len(self.dat) > 0:
            self.lb_head.select_item(0)

    def run(self):
        gtk.mainloop()


if __name__ == '__main__':
    if len(sys.argv) < 4:
        App(term='time series').run()
    else:
        App(sys.argv[1], string.atoi(sys.argv[2]), sys.argv[3]).run()
Example #48
0
    self.start=start
    
  def run(self):
    series=self.series
    for i in range(len(self.data)):
      self.data[i]=series.current(toPIL=False).integrate_area(self.coord)
      self.imagenumber[i] = series.number
      if i < len(self.data)-1:
        try:
          series.next()
          #if there's an error opening the file just skip over it
        except (ValueError,IOError) as msg:
          print(msg, '- aborted!')
          break
	
  def getdata(self):
    #return the array containing the rocking curve
    return self.data

if __name__=='__main__':
  import sys,time
  from string import atoi
  b=time.time()
  c=[atoi(sys.argv[4]),atoi(sys.argv[5]),atoi(sys.argv[6]),atoi(sys.argv[7])]
  R=rocker(filename_sample=sys.argv[1],coord=c,startnumber=atoi(sys.argv[2]),endnumber=atoi(sys.argv[3]))
  R.run()
  print(R.getdata())
  e=time.time()
  print((e-b))

Example #49
0
class myRequestHandler(BaseHTTPRequestHandler):
 try:
  def do_GET(self):
    # Always Accept GET
    # Site root: Main Menu
    if self.path == "/":
       self.printCustomHTTPResponse(200)
       load_header(self)
       load_nav(self)
       indexopen=file("bin/web/html/index","r").readlines()
       for line in indexopen:
            self.wfile.write(line)
       load_footer(self)

    # Style.CSS
    if self.path == "/fast_track.css":
       self.send_response(200)
       self.send_header('Content_type', 'text/css')
       self.end_headers()
       cssopen=file("bin/web/html/fast_track.css","r").readlines()
       for line in cssopen:
           self.wfile.write(line)

    # Spacer
    if self.path == "/images/spacer.gif":
       spacer=file("bin/web/html/images/spacer.gif","rb").readlines()
       for line in spacer:
            self.wfile.write(line)

    # Left graphic image for nav
    if self.path == "/images/ft_left_pane_1.jpg":
       spacer=file("bin/web/html/images/ft_left_pane_1.jpg","rb").readlines()
       for line in spacer:
            self.wfile.write(line)

    # Bullet
    if self.path == "/images/bullet.jpg":
       bullet=file("bin/web/html/images/bullet.jpg","rb").readlines()
       for line in bullet:
            self.wfile.write(line)

    # Content
    if self.path == "/images/content.gif":
       content=file("bin/web/html/images/content.gif","rb").readlines()
       for line in content:
            self.wfile.write(line)

    # Fast_Track_01
    if self.path == "/images/fast_track_01.jpg.gif":
       ft1=file("bin/web/html/images/fast_track_01.jpg","rb").readlines()
       for line in ft1:
            self.wfile.write(line)

    # Fast_Track_03
    if self.path == "/images/fast_track_03.jpg":
       ft3=file("bin/web/html/images/fast_track_03.jpg","rb").readlines()
       for line in ft3:
            self.wfile.write(line)

    # Fast_Track_08
    if self.path == "/images/fast_track_08.jpg":
       ft8=file("bin/web/html/images/fast_track_08.jpg","rb").readlines()
       for line in ft8:
            self.wfile.write(line)

    # Fast_Track_09
    if self.path == "/images/fast_track_09.jpg":
       ft9=file("bin/web/html/images/fast_track_09.jpg","rb").readlines()
       for line in ft9:
            self.wfile.write(line)

    # Fast_Track_10
    if self.path == "/images/fast_track_10.jpg":
       ft=file("bin/web/html/images/fast_track_10.jpg","rb").readlines()
       for line in ft:
            self.wfile.write(line)

    # Fast_Track_11
    if self.path == "/images/fast_track_11.jpg":
       ft9=file("bin/web/html/images/fast_track_11.jpg","rb").readlines()
       for line in ft9:
            self.wfile.write(line)

    # Fast_Track_15
    if self.path == "/images/fast_track_15.jpg":
       ft9=file("bin/web/html/images/fast_track_15.jpg","rb").readlines()
       for line in ft9:
            self.wfile.write(line)

    # Fast_Track_16
    if self.path == "/images/fast_track_16.jpg":
       ft9=file("bin/web/html/images/fast_track_16.jpg","rb").readlines()
       for line in ft9:
            self.wfile.write(line)

    # Fast_Track_18
    if self.path == "/images/fast_track_18.jpg":
       ft9=file("bin/web/html/images/fast_track_18.jpg","rb").readlines()
       for line in ft9:
            self.wfile.write(line)

    # Fast_Track_21
    if self.path == "/images/fast_track_21.jpg":
       ft9=file("bin/web/html/images/fast_track_21.jpg","rb").readlines()
       for line in ft9:
            self.wfile.write(line)

    # Fast_Track_25
    if self.path == "/images/fast_track_25.jpg":
       ft9=file("bin/web/html/images/fast_track_25.jpg","rb").readlines()
       for line in ft9:
            self.wfile.write(line)

    # Fast_Track_26
    if self.path == "/images/fast_track_26.jpg":
       ft9=file("bin/web/html/images/fast_track_26.jpg","rb").readlines()
       for line in ft9:
            self.wfile.write(line)

    # FT_header_04
    if self.path == "/images/ft_header_04.jpg":
       ft9=file("bin/web/html/images/ft_header_04.jpg","rb").readlines()
       for line in ft9:
            self.wfile.write(line)

    # ft_header_hover_03
    if self.path == "/images/ft_header_hover_03.jpg":
       ft9=file("bin/web/html/images/ft_header_hover_03.jpg","rb").readlines()
       for line in ft9:
            self.wfile.write(line)

    # ft_header_hover_04
    if self.path == "/images/ft_header_hover_04.jpg":
       ft9=file("bin/web/html/images/ft_header_hover_04.jpg","rb").readlines()
       for line in ft9:
            self.wfile.write(line)

    # ft_header_hover_05
    if self.path == "/images/ft_header_hover_05.jpg":
       ft9=file("bin/web/html/images/ft_header_hover_05.jpg","rb").readlines()
       for line in ft9:
            self.wfile.write(line)

    # ft_header_hover_07
    if self.path == "/images/ft_header_hover_07.jpg":
       ft9=file("bin/web/html/images/ft_header_hover_07.jpg","rb").readlines()
       for line in ft9:
            self.wfile.write(line)

    # page_bg
    if self.path == "/images/page_bg.jpg":
       ft9=file("bin/web/html/images/page_bg.jpg","rb").readlines()
       for line in ft9:
            self.wfile.write(line)

    # btn1
    if self.path == "/images/btn_launch_1.jpg":
       spacer=file("bin/web/html/images/btn_launch_1.jpg","rb").readlines()
       for line in spacer:
            self.wfile.write(line)

    # btn2
    if self.path == "/images/btn_launch_2.jpg":
       spacer=file("bin/web/html/images/btn_launch_2.jpg","rb").readlines()
       for line in spacer:
            self.wfile.write(line)

    # btn3
    if self.path == "/images/btn_launch_3.jpg":
       spacer=file("bin/web/html/images/btn_launch_3.jpg","rb").readlines()
       for line in spacer:
            self.wfile.write(line)

    # msautopwn
    if self.path == "/images/btn_msautopwn.jpg":
       spacer=file("bin/web/html/images/btn_msautopwn.jpg","rb").readlines()
       for line in spacer:
            self.wfile.write(line)

    # btn_reset
    if self.path == "/images/btn_reset.jpg":
       spacer=file("bin/web/html/images/btn_reset.jpg","rb").readlines()
       for line in spacer:
            self.wfile.write(line)

    # btn_browse
    if self.path == "/images/btn_browse.jpg":
       spacer=file("bin/web/html/images/btn_browse.jpg","rb").readlines()
       for line in spacer:
            self.wfile.write(line)

    # btn_updateall
    if self.path == "/images/btn_updateall.jpg":
       spacer=file("bin/web/html/images/btn_updateall.jpg","rb").readlines()
       for line in spacer:
            self.wfile.write(line)

    # updateft
    if self.path == "/images/btn_updateft.jpg":
       spacer=file("bin/web/html/images/btn_updateft.jpg","rb").readlines()
       for line in spacer:
            self.wfile.write(line)

    # meta update
    if self.path == "/images/btn_updatems.jpg":
       spacer=file("bin/web/html/images/btn_updatems.jpg","rb").readlines()
       for line in spacer:
            self.wfile.write(line)

    # Fast_Track_10
    if self.path == "/images/fast_track_10.jpg":
       ft10=file("bin/web/html/images/fast_track_10.jpg","rb").readlines()
       for line in ft10:
            self.wfile.write(line)

    # Update: Update Menu for Fast-Track and various other tools
    if self.path == "/update":
       load_header(self)
       load_nav(self)
       update=file("bin/web/html/updates","r").readlines()
       for line in update:
            self.wfile.write(line)
       load_footer(self)
 
    # Autopwn: Metasploit Autopwn Automated
    if self.path == "/autopwn":
       load_header(self)
       load_nav(self)
       autopwn=file("bin/web/html/autopwn","r").readlines()
       for line in autopwn:
            self.wfile.write(line)
       load_footer(self)

    # SQL Brute Main: Sql brute forcing Main Menu
    if self.path == "/sqlbrute":
       load_header(self)
       load_nav(self)
       sqlbrute=file("bin/web/html/sqlbrutemain","r").readlines()
       for line in sqlbrute:
           self.wfile.write(line)
       load_footer(self)
       # Quick brute option: SQL brute forcing using quick (like 50 passwords)
    if self.path == "/quickbrute":
       load_header(self)
       load_nav(self)
       sqlbrutequick=file("bin/web/html/quickbrute","r").readlines()
       for line in sqlbrutequick:
           self.wfile.write(line)
       load_footer(self)

       # Wordlist brute option wordlist: Import an external wordlist and brute force against one or many hosts
    if self.path == "/wordlistbrute":
       load_header(self)
       load_nav(self)
       wordlistbrute=file("bin/web/html/wordlistbrute","r").readlines()
       for line in wordlistbrute:
           self.wfile.write(line)
       load_footer(self)

       # Binary Convert: Convert binarys to a pasteable format to a windows shell to compile it..used as a PAYLOAD delivery method
    if self.path == "/binaryconvert":
       load_header(self)
       load_nav(self)
       binaryconvert=file("bin/web/html/binaryconvert","r").readlines()
       for line in binaryconvert:
           self.wfile.write(line)
       load_footer(self)

    # Changelog: Fast-Track updates, uses CHANGELOG under readme to generate the info dynamically
    if self.path == "/changelog":
       load_header(self)
       load_nav(self)
       changelog=file("bin/web/html/changelog","r").readlines()
       for line in changelog:
           self.wfile.write(line)
           match2=re.search('<div style="overflow:scroll;', line)
           if match2:
               menuopen=file("readme/CHANGELOG","r").readlines()
               for line in menuopen:
                   self.wfile.write('<p class="box_text">'+line+"</p>")
       load_footer(self)
    # Tutorials for Fast-Track, generate the info dynamically
    if self.path == "/tutorials":
       load_header(self)
       load_nav(self)
       tutorials=file("bin/web/html/tutorials","r").readlines()
       for line in tutorials:
           self.wfile.write(line)
       load_footer(self)
    # Credits for Fast-Track, generate the info dynamically
    if self.path == "/credits":
       load_header(self)
       load_nav(self)
       tutorials=file("bin/web/html/credits","r").readlines()
       for line in tutorials:
           self.wfile.write(line)
       load_footer(self)
    # SQL Injector Main: Find an injectable parameter and this trys to exploit it: Main Menu
    if self.path == "/sqlinjector":
       load_header(self)
       load_nav(self)
       sqlinjectormain=file("bin/web/html/sqlinjector","r").readlines()
       for line in sqlinjectormain:
           self.wfile.write(line)
       load_footer(self)
       # SQL Injector Binary Payload: Use binary to hex conversions to deliver our payload through SQL Injection
    if self.path == "/binarypayload":
       load_header(self)
       load_nav(self)
       binarypayload=file("bin/web/html/binarypayload","r").readlines()
       for line in binarypayload:
           self.wfile.write(line)
       load_footer(self)
       # SQL Injector FTP Payload: Use FTP as a median for transfer, delivers a netcat payload
    if self.path == "/ftppayload":
       load_header(self)
       load_nav(self)
       ftppayload=file("bin/web/html/ftppayload","r").readlines()
       for line in ftppayload:
           self.wfile.write(line)
       load_footer(self)
       # SQL Injector POST Binary Payload:
    if self.path == "/postpayload":
       load_header(self)
       load_nav(self)
       postpayload=file("bin/web/html/postpayload","r").readlines()
       for line in postpayload:
           self.wfile.write(line)
       load_footer(self)
       # SQL Injector Manual Payload: Setup everything manual for you, i.e nc listening on port x and ip of x
    if self.path == "/manualpayload":
       load_header(self)
       load_nav(self)
       manualpayload=file("bin/web/html/manualpayload","r").readlines()
       for line in manualpayload:
           self.wfile.write(line)
       load_footer(self)
    if self.path == "/massclient":
       load_header(self)
       load_nav(self)
       massclient=file("bin/web/html/massclient","r").readlines()
       for line in massclient:
           self.wfile.write(line)
       load_footer(self)
       # Payload Generator
    if self.path == "/payloadgen":
       load_header(self)
       load_nav(self)
       payloadgen=file("bin/web/html/payloadgen","r").readlines()
       for line in payloadgen:
           self.wfile.write(line)
       load_footer(self)
    # Exploits Main
    if self.path == "/exploits":
       load_header(self)
       load_nav(self)
       exploitsmain=file("bin/web/html/exploits","r").readlines()
       for line in exploitsmain:
           self.wfile.write(line)
       load_footer(self)

    # HP OpenView CGI Exploit
    if self.path == "/openviewcgi":
       load_header(self)
       load_nav(self)
       openviewcgi=file("bin/web/html/openviewcgi","r").readlines()
       for line in openviewcgi:
           self.wfile.write(line)
       load_footer(self)

    # IBM Tivoli Exploit
    if self.path == "/ibmtivoli":
       load_header(self)
       load_nav(self)
       ibmtivoli=file("bin/web/html/ibmtivoli","r").readlines()
       for line in ibmtivoli:
           self.wfile.write(line)
       load_footer(self)

    # HP OpenView NNM Exploit
    if self.path == "/openviewnnm":
       load_header(self)
       load_nav(self)
       openviewnnm=file("bin/web/html/openviewnnm","r").readlines()
       for line in openviewnnm:
           self.wfile.write(line)
       load_footer(self)
    # Quicktime RTSP 
    if self.path == "/quicktime":
       load_header(self)
       load_nav(self)
       ibmtivoli=file("bin/web/html/quicktime","r").readlines()
       for line in ibmtivoli:
           self.wfile.write(line)
       load_footer(self)

    # Goodtech
    if self.path == "/goodtech":
       load_header(self)
       load_nav(self)
       goodtech=file("bin/web/html/goodtech","r").readlines()
       for line in goodtech:
           self.wfile.write(line)
       load_footer(self)

    # \MS08-067
    if self.path == "/ms08067":
       load_header(self)
       load_nav(self)
       ms08067=file("bin/web/html/ms08067","r").readlines()
       for line in ms08067:
           self.wfile.write(line)
       load_footer(self)

    # \MS09-002
    if self.path == "/ms09002":
       load_header(self)
       load_nav(self)
       ms09002=file("bin/web/html/ms09002","r").readlines()
       for line in ms09002:
           self.wfile.write(line)
       load_footer(self)


    # MIRC
    if self.path == "/mirc":
       load_header(self)
       load_nav(self)
       mirc=file("bin/web/html/mirc","r").readlines()
       for line in mirc:
           self.wfile.write(line)
       load_footer(self)

    # TFTP
    if self.path == "/tftp":
       load_header(self)
       load_nav(self)
       tftp=file("bin/web/html/tftp","r").readlines()
       for line in tftp:
           self.wfile.write(line)
       load_footer(self)

    # IE XML Corruption
    if self.path == "/xmlcorruptionbo":
       load_header(self)
       load_nav(self)
       xml=file("bin/web/html/xmlcorruptionbo","r").readlines()
       for line in xml:
           self.wfile.write(line)
       load_footer(self)


    # MS Internet Explorer 7 DirectShow (msvidctl.dll) Heap Spray
    if self.path == "/directshowheap":
       load_header(self)
       load_nav(self)
       xml=file("bin/web/html/directshowheap","r").readlines()
       for line in xml:
           self.wfile.write(line)
       load_footer(self)

    # FireFox 3.5 Heap Spray
    if self.path == "/firefox35":
       load_header(self)
       load_nav(self)
       xml=file("bin/web/html/firefox35","r").readlines()
       for line in xml:
           self.wfile.write(line)
       load_footer(self)


    # SQLPwnage Main Menu
    if self.path == "/sqlpwnage":
       load_header(self)
       load_nav(self)
       sqlpwnagemain=file("bin/web/html/sqlpwnage","r").readlines()
       for line in sqlpwnagemain:
           self.wfile.write(line)
       load_footer(self)
    # SQLPwnage Blind Menu
    if self.path == "/sqlpwnageblind":
       load_header(self)
       load_nav(self)
       sqlpwnagemain=file("bin/web/html/sqlpwnageblind","r").readlines()
       for line in sqlpwnagemain:
           self.wfile.write(line)
       load_footer(self)
    # SQLPwnage Blind POST Menu
    #if self.path == "/sqlpwnageblindpost":
    #   sqlpwnagemain=file("bin/web/html/sqlpwnageblindpost.html","r").readlines()
    #   for line in sqlpwnagemain:
    #       self.wfile.write(line)
    #       match=re.search('<ul id="navlist" title="menu">', line)
    #       if match:
    #           menuopen=file("bin/web/html/menu.html","r").readlines()
    #           for line in menuopen:
    #               self.wfile.write(line)
    # SQLPwnage Error Menu
    if self.path == "/sqlpwnageerror":
       load_header(self)
       load_nav(self)
       sqlpwnagemain=file("bin/web/html/sqlpwnageerror","r").readlines()
       for line in sqlpwnagemain:
           self.wfile.write(line)
       load_footer(self)



    # Close any html body tags
    self.wfile.write("</html></body>")

  # Start POST
  def do_POST(self):
   ###################### START UPDATE EVERYTHING SECTION ##############################

   if self.path == "/updatepost":
      load_header(self)
      load_nav(self)
      updatepost=file("bin/web/html/finished","r").readlines()
      for line in updatepost:
          self.wfile.write(line)
      load_footer(self)
      try:
         update=os.popen2("""xterm -geometry 60x20 -bg black -fg green -fn *-fixed-*-*-*-20-* -T "Fast-Track Auto-Update" -e "python %s/fast-track.py -c 1 2" 2> /dev/null""" % (definepath))
      except OSError:
         print "Exiting Fast-Track Web GUI.."
         print "\nType <control>-c again to exit Fast-Track Web Gui.."

    ###################### END UPDATE EVERYTHING SECTION ##############################

   ###################### START UPDATE FT ONLY SECTION ##############################

   if self.path == "/updateftpost":
      load_header(self)
      load_nav(self)
      updatepost=file("bin/web/html/finished","r").readlines()
      for line in updatepost:
          self.wfile.write(line)
      load_footer(self)
      try:
         update=os.popen2("""xterm -geometry 60x20 -bg black -fg green -fn *-fixed-*-*-*-20-* -T "Fast-Track Auto-Update" -e "python %s/fast-track.py -c 1 1" 2> /dev/null""" % (definepath))
      except OSError:
         print "Exiting Fast-Track Web GUI.."
         print "\nType <control>-c again to exit Fast-Track Web Gui.."

    ###################### END UPDATE FT ONLY SECTION ##############################

   ###################### START AUTOPWN SECTION ##############################
   if self.path == "/autopwnpost":
      content_length = string.atoi(self.headers.dict["content-length"])
      raw_post_data = self.rfile.read(content_length)
      raw_post_data=re.split('=|&',raw_post_data)
      self.send_response(200)
      self.end_headers()
      ipaddr=raw_post_data[1].rstrip()
      ipaddr=ipaddr.replace("+"," ")
      ipaddr=ipaddr.replace("%2C",",")
      ipaddr=ipaddr.replace("%2F","/")
      option1=raw_post_data[3].rstrip()
      load_header(self)
      load_nav(self)
      autopwn=file("bin/web/html/finished","r").readlines()    
      for line in autopwn:
          self.wfile.write(line)
      load_footer(self)
      try:
         metapwn=os.popen2("""xterm -geometry 60x20 -bg black -fg green -fn *-fixed-*-*-*-20-* -T "Fast-Track Metasploit Autopwn Automated" -e "python %s/fast-track.py -c 2 \'%s\' %s" 2> /dev/null""" % (definepath,ipaddr,option1))
      except OSError:
         print "Exiting Fast-Track Web GUI.."
         print "\nType <control>-c again to exit Fast-Track Web Gui.."

    ###################### END AUTOPWN SECTION ##############################

   ###################### START METASPLOIT UPDATE SECTION ##############################
   if self.path == "/metaupdatepost":
      self.send_response(200)
      self.end_headers()
      load_header(self)
      load_nav(self)
      metaupdatepost=file("bin/web/html/finished","r").readlines()    
      for line in metaupdatepost:
          self.wfile.write(line) 
      load_footer(self)
      try:
         metaupdate=os.popen2("""xterm -geometry 60x20 -bg black -fg green -fn *-fixed-*-*-*-20-* -T "Fast-Track Metasploit Autopwn Automated" -e "python %s/bin/ftsrc/updatemeta.py" 2> /dev/null""" % (definepath))
      except OSError:
         print "Exiting Fast-Track Web GUI.."
         print "\nType <control>-c again to exit Fast-Track Web Gui.."

    ###################### END METASPLOIT UPDATE SECTION ##############################

   ###################### START SQL QUICK BRUTE ##############################
   if self.path == "/quickbrutepost":
      content_length = string.atoi(self.headers.dict["content-length"])
      raw_post_data = self.rfile.read(content_length)
      raw_post_data=re.split('=|&',raw_post_data)
      self.send_response(200)
      self.end_headers()
      ipaddr=raw_post_data[1].rstrip()
      ipaddr=ipaddr.replace("%2F","/")
      payload=raw_post_data[3].rstrip()
      username=raw_post_data[5].rstrip()
      load_header(self)
      load_nav(self)
      quickbrute=file("bin/web/html/finished","r").readlines()    
      for line in quickbrute:
          self.wfile.write(line)
      load_footer(self)
      try:
         quickbrute=os.popen2(r"""xterm -geometry 80x20 -bg black -fg green -fn *-fixed-*-*-*-20-* -T "Fast-Track SQL Quick Brute" -e "python %s/fast-track.py -c 4 1 %s %s %s" """ % (definepath,ipaddr,username,payload))
      except OSError:
         print "Exiting Fast-Track Web GUI.."
         print "\nType <control>-c again to exit Fast-Track Web Gui.."

    ###################### END SQL QUICK BRUTE ##############################

   ###################### START SQL WORDLIST BRUTE ##############################
   if self.path == "/wordlistbrutepost":
      content_length = string.atoi(self.headers.dict["content-length"])
      raw_post_data = self.rfile.read(content_length)
 #     print raw_post_data
      raw_post_data=re.split('=|&',raw_post_data)
      self.send_response(200)
      self.end_headers()
      ipaddr=raw_post_data[1].rstrip()
      payload=raw_post_data[3].rstrip()
      username=raw_post_data[5].rstrip()
      wordlist=raw_post_data[7].rstrip()
      wordlist=wordlist.replace("%2F","/")
      ipaddr=ipaddr.replace("%2F", "/")
      load_header(self)
      load_nav(self)
      wordlistbrute=file("bin/web/html/finished","r").readlines()
      for line in wordlistbrute:
           self.wfile.write(line)
      load_footer(self)
      try:
         wordlist=os.popen2(r'''xterm -geometry 80x20 -bg black -fg green -fn *-fixed-*-*-*-20-* -T "Fast-Track SQL Wordlist Brute" -e "python %s/fast-track.py -c 4 2 %s %s %s %s"''' % (definepath,ipaddr,username,wordlist,payload))
      except OSError:
         print "Exiting Fast-Track Web GUI.."
         print "\nType <control>-c again to exit Fast-Track Web Gui.."

    ###################### END SQL WORDLIST BRUTE ##############################


   ###################### START BINARYCONVERT ##############################
   if self.path == "/binaryconvertpost":
      content_length = string.atoi(self.headers.dict["content-length"])
      raw_post_data = self.rfile.read(content_length)
      raw_post_data=re.split('=|&',raw_post_data)
      self.send_response(200)
      self.end_headers()
      print raw_post_data
      binpath=raw_post_data[1].rstrip()
      binpath=binpath.replace("%2F","/")
      binaryconvertpost=file("bin/web/html/finished","r").readlines()
      load_header(self)
      load_nav(self)
      for line in binaryconvertpost:
          self.wfile.write(line)
      load_footer(self)
      try:
        binconvert=os.popen2("""python %s/fast-track.py -c 5 %s""" % (definepath,binpath))
      except OSError:
         print "Exiting Fast-Track Web GUI.."
         print "\nType <control>-c again to exit Fast-Track Web Gui.."

    ###################### END BINARYCONVERT ##############################

   ###################### START SQL INJECTOR BINARY PAYLOAD ##############################
   if self.path == "/binarypayloadpost":
      content_length = string.atoi(self.headers.dict["content-length"])
      raw_post_data = self.rfile.read(content_length)
      raw_post_data=re.split('=|&',raw_post_data)
      self.send_response(200)
      self.end_headers()
      url=raw_post_data[1].rstrip()
      url=url.replace("%3A",":")
      url=url.replace("%2F","/")
      url=url.replace("%3F","?")
      url=url.replace("%3D","=")
      url=url.replace("%27","'")
      url=url.replace("%26","&")
      # Used to escape the ' and & in shell
      url=url.replace("'","\\'")
      url=url.replace("&","\\&")
      load_header(self)
      load_nav(self)
      binarypayload=file("bin/web/html/finished","r").readlines()
      for line in binarypayload:
          self.wfile.write(line) 
      load_footer(self) 
      try:
         
         binarypayload=os.popen2('''xterm -geometry 60x20 -bg black -fg green -fn *-fixed-*-*-*-20-* -T "Fast-Track SQL Injector Binary Payload" -e "python %s/fast-track.py -c 3 1 %s" 2> /dev/null''' % (definepath,url))
      except OSError:
         print "Exiting Fast-Track Web GUI.."
         print "\nType <control>-c again to exit Fast-Track Web Gui.."
      except Exception:
         pass

   ###################### END SQL INJECTOR BINARY PAYLOAD ##############################

   ###################### START SQL INJECTOR FTP PAYLOAD ##############################
   if self.path == "/ftppayloadpost":
      content_length = string.atoi(self.headers.dict["content-length"])
      raw_post_data = self.rfile.read(content_length)
      raw_post_data=re.split('=|&',raw_post_data)
      self.send_response(200)
      self.end_headers()
      url=raw_post_data[1].rstrip()
      url=url.replace("%3A",":")
      url=url.replace("%2F","/")
      url=url.replace("%3F","?")
      url=url.replace("%3D","=")
      url=url.replace("%27","'")
      url=url.replace("%26","&")
      # Used to escape the ' and & in shell
      url=url.replace("'","\\'")
      url=url.replace("&","\\&")
      load_header(self)
      load_nav(self)
      ftppayloadpost=file("bin/web/html/finished","r").readlines()
      for line in ftppayloadpost:
           self.wfile.write(line)
      load_footer(self)
      try:
         ftppayload=os.popen2('''xterm -geometry 60x20 -bg black -fg green -fn *-fixed-*-*-*-20-* -T "Fast-Track SQL Injector Binary Payload" -e "python %s/fast-track.py -c 3 2 %s" 2> /dev/null'''% (definepath,url))
      except OSError:
         print "Exiting Fast-Track Web GUI.."
         print "\nType <control>-c again to exit Fast-Track Web Gui.."
      except Exception:
         pass

    ###################### END SQL INJECTOR FTP PAYLOAD ##############################

   ###################### START SQL INJECTOR MANUAL PAYLOAD ##############################
   if self.path == "/manualpayloadpost":
      content_length = string.atoi(self.headers.dict["content-length"])
      raw_post_data = self.rfile.read(content_length)
      raw_post_data=re.split('=|&',raw_post_data)
      self.send_response(200)
      self.end_headers()
      url=raw_post_data[1].rstrip()
      url=url.replace("%3A",":")
      url=url.replace("%2F","/")
      url=url.replace("%3F","?")
      url=url.replace("%3D","=")
      url=url.replace("%27","'")
      url=url.replace("%26","&")
      # Used to escape the ' and & in shell
      url=url.replace("'","\\'")
      url=url.replace("&","\\&")
      ipaddr=raw_post_data[3].rstrip()
      portnum=raw_post_data[5].rstrip()
      load_header(self)
      load_nav(self)
      manualpayloadpost=file("bin/web/html/finished","r").readlines()
      for line in manualpayloadpost:
          self.wfile.write(line)
      load_footer(self)
      try:
         manualpayload=os.popen2('''xterm -geometry 60x20 -bg black -fg green -fn *-fixed-*-*-*-20-* -T "Fast-Track SQL Injector Binary Payload" -e "python %s/fast-track.py -c 3 3 %s %s %s" 2> /dev/null''' % (definepath,url,ipaddr,portnum))
      except OSError:
         print "Exiting Fast-Track Web GUI.."
         print "\nType <control>-c again to exit Fast-Track Web Gui.."
      except Exception:
         pass

    ###################### END SQL INJECTOR MANUAL PAYLOAD ##############################

   ###################### START SQL INJECTOR BINARY PAYLOAD POST ##############################
   if self.path == "/postpayloadpost":
      content_length = string.atoi(self.headers.dict["content-length"])
      raw_post_data = self.rfile.read(content_length)
      raw_post_data=re.split('=|&',raw_post_data)
      self.send_response(200)
      self.end_headers()
      url=raw_post_data[1].rstrip()
      url=url.replace("%3A",":")
      url=url.replace("%2F","/")
      url=url.replace("%3F","?")
      url=url.replace("%3D","=")
      url=url.replace("%27","'")
      url=url.replace("%26","&")
      # Used to escape the ' and & in shell
      url=url.replace("'","\\'")
      url=url.replace("&","\\&")
      load_header(self)
      load_nav(self)
      postpayload=file("bin/web/html/finished","r").readlines()
      for line in postpayload:
          self.wfile.write(line)
      load_footer(self)
      try:
         ftppayload=os.popen2('''xterm -geometry 60x20 -bg black -fg green -fn *-fixed-*-*-*-20-* -T "Fast-Track SQL Injector Binary Payload" -e "python %s/fast-track.py -c 3 4 %s" 2> /dev/null'''% (definepath,url))
      except OSError:
         print "Exiting Fast-Track Web GUI.."
         print "\nType <control>-c again to exit Fast-Track Web Gui.."
      except Exception:
         pass

    ###################### END SQL INJECTOR BINARY PAYLOAD POST ##############################

   ###################### START METASPLOIT CLIENT ATTACK ##############################
   if self.path == "/massclientpost":
      content_length = string.atoi(self.headers.dict["content-length"])
      raw_post_data = self.rfile.read(content_length)
      raw_post_data=re.split('=|&',raw_post_data)
      self.send_response(200)
      self.end_headers()
      ipaddr=raw_post_data[1].rstrip()
      choice=raw_post_data[3].rstrip()
      try:
         etterchoice=raw_post_data[5].rstrip()
      except Exception,e:
          print e 
          etterchoice=0
      try:
         ettercap=raw_post_data[7].rstrip()
      except Exception: ettercap=0
      load_header(self)
      load_nav(self)
      massclientpost=file("bin/web/html/finished","r").readlines()
      for line in massclientpost:
          self.wfile.write(line)     
      load_footer(self)
      print choice
      try:
         massclient=os.popen2("""xterm -geometry 60x20 -bg black -fg green -fn *-fixed-*-*-*-20-* -T "Fast-Track Metasploit Mass Client Attack" -e "python %s/fast-track.py -c 6 %s %s %s %s" 2> /dev/null""" % (definepath,ipaddr,choice,etterchoice,ettercap))
      except OSError:
         print "Exiting Fast-Track Web GUI.."
         print "\nType <control>-c again to exit Fast-Track Web Gui.."

    ###################### END METASPLOIT CLIENT ATTACK ##############################

   ###################### START EXPLOITS OPENVIEWCGI ##############################
   if self.path == "/openviewcgipost":
      content_length = string.atoi(self.headers.dict["content-length"])
      raw_post_data = self.rfile.read(content_length)
      raw_post_data=re.split('=|&',raw_post_data)
      self.send_response(200)
      self.end_headers()
      ipaddr=raw_post_data[1].rstrip()
      ipaddr=ipaddr.replace("+"," ")
      load_header(self)
      load_nav(self)
      openviewcgi=file("bin/web/html/finished","r").readlines()    
      for line in openviewcgi:
          self.wfile.write(line)
      load_footer(self)
      try:
         openviewcgi=os.popen2("""xterm -geometry 60x20 -bg black -fg green -fn *-fixed-*-*-*-20-* -T "Fast-Track HP OpenView CGI Exploit" -e "python %s/fast-track.py -c 7 1 %s" 2> /dev/null""" % (definepath,ipaddr))
      except OSError:
         print "Exiting Fast-Track Web GUI.."
         print "\nType <control>-c again to exit Fast-Track Web Gui.."

    ###################### END EXPLOITS OPENVIEWCGI ##############################

   ###################### START EXPLOITS IBMTIVOLI ##############################
   if self.path == "/ibmtivolipost":
      content_length = string.atoi(self.headers.dict["content-length"])
      raw_post_data = self.rfile.read(content_length)
      raw_post_data=re.split('=|&',raw_post_data)
      self.send_response(200)
      self.end_headers()
      try:
         ipaddr=raw_post_data[1].rstrip()
         ipaddr=ipaddr.replace("+"," ")
      except IndexError: pass
      load_header(self)
      load_nav(self)
      ibmtivoli=file("bin/web/html/finished","r").readlines()    
      for line in ibmtivoli:
          self.wfile.write(line)
      load_footer(self)

      try:
         openviewcgi=os.popen2("""xterm -geometry 60x20 -bg black -fg green -fn *-fixed-*-*-*-20-* -T "Fast-Track IBM Tivoli Exploit" -e "python %s/fast-track.py -c 7 2 %s" 2> /dev/null""" % (definepath,ipaddr))
      except OSError:
         print "Exiting Fast-Track Web GUI.."
         print "\nType <control>-c again to exit Fast-Track Web Gui.."

    ###################### END EXPLOITS IBMTIVOLI ##############################

   ###################### START EXPLOITS OPENVIEWNNM ##############################
   if self.path == "/openviewnnmpost":
      content_length = string.atoi(self.headers.dict["content-length"])
      raw_post_data = self.rfile.read(content_length)
      raw_post_data=re.split('=|&',raw_post_data)
      self.send_response(200)
      self.end_headers()
      ipaddr=raw_post_data[1].rstrip()
      ipaddr=ipaddr.replace("+"," ")
      load_header(self)
      load_nav(self)
      openviewnnm=file("bin/web/html/finished","r").readlines()    
      for line in openviewnnm:
          self.wfile.write(line)
      load_footer(self)
      try:
         openviewcgi=os.popen2("""xterm -geometry 60x20 -bg black -fg green -fn *-fixed-*-*-*-20-* -T "Fast-Track HP OpenView NNM Exploit" -e "python %s/fast-track.py -c 7 2 %s" 2> /dev/null""" % (definepath,ipaddr))
      except OSError:
         print "Exiting Fast-Track Web GUI.."
         print "\nType <control>-c again to exit Fast-Track Web Gui.."

    ###################### END EXPLOITS OPENVIEWNNM ##############################

   ###################### START EXPLOITS QUICKTIME ##############################
   if self.path == "/quicktimepost":
      content_length = string.atoi(self.headers.dict["content-length"])
      raw_post_data = self.rfile.read(content_length)
      raw_post_data=re.split('=|&',raw_post_data)
      self.send_response(200)
      self.end_headers()
      quicktime=file("bin/web/html/finished","r").readlines()
      load_header(self)
      load_nav(self)
      for line in quicktime:
          self.wfile.write(line)
      load_footer(self)
      try:
         quicktime=os.popen2("""xterm -geometry 60x20 -bg black -fg green -fn *-fixed-*-*-*-20-* -T "Fast-Track RTSP 7.3 SEH Exploit" -e "python %s/fast-track.py -c 7 4" 2> /dev/null""" % (definepath))
      except OSError:
         print "Exiting Fast-Track Web GUI.."
         print "\nType <control>-c again to exit Fast-Track Web Gui.."

    ###################### END EXPLOITS QUICKTIME ##############################

   ###################### START EXPLOITS GOODTECH ##############################
   if self.path == "/goodtechpost":
      content_length = string.atoi(self.headers.dict["content-length"])
      raw_post_data = self.rfile.read(content_length)
      raw_post_data=re.split('=|&',raw_post_data)
      self.send_response(200)
      self.end_headers()
      load_header(self)
      load_nav(self)
      goodtech=file("bin/web/html/finished","r").readlines()
      for line in goodtech:
          self.wfile.write(line)
      load_footer(self)
      try:
         goodtech=os.popen2("""xterm -geometry 60x20 -bg black -fg green -fn *-fixed-*-*-*-20-* -T "Fast-Track Goodtech 6.4 Buffer Overflow Exploit" -e "python %s/fast-track.py -c 7 5" 2> /dev/null""" % (definepath))
      except OSError:
         print "Exiting Fast-Track Web GUI.."
         print "\nType <control>-c again to exit Fast-Track Web Gui.."

    ###################### END EXPLOITS GOODTECH ##############################

   ###################### START EXPLOITS MS08067 ##############################
   if self.path == "/ms08067post":
      content_length = string.atoi(self.headers.dict["content-length"])
      raw_post_data = self.rfile.read(content_length)
      raw_post_data=re.split('=|&',raw_post_data)
      self.send_response(200)
      self.end_headers()
      load_header(self)
      load_nav(self)
      ms08067=file("bin/web/html/finished","r").readlines()
      for line in ms08067:
          self.wfile.write(line)
      load_footer(self)
      try:
         ms08067=os.popen2("""xterm -geometry 60x20 -bg black -fg green -fn *-fixed-*-*-*-20-* -T "Fast-Track MS08-067 Server Service Buffer Overflow Exploit" -e "python %s/fast-track.py -c 7 6" 2> /dev/null""" % (definepath))
      except OSError:
         print "Exiting Fast-Track Web GUI.."
         print "\nType <control>-c again to exit Fast-Track Web Gui.."

    ###################### END EXPLOITS MS08067 ##############################

   ###################### START EXPLOITS MS09002 ##############################
   if self.path == "/ms09002post":
      content_length = string.atoi(self.headers.dict["content-length"])
      raw_post_data = self.rfile.read(content_length)
      raw_post_data=re.split('=|&',raw_post_data)
      self.send_response(200)
      self.end_headers()
      load_header(self)
      load_nav(self)
      ms09002=file("bin/web/html/finished","r").readlines()
      for line in ms09002:
          self.wfile.write(line)
      load_footer(self)
      try:
        ms09002=os.popen2("""xterm -geometry 60x20 -bg black -fg green -fn *-fixed-*-*-*-20-* -T "Fast-Track MS IE 7 Memory Corruption (MS09-002)" -e "python %s/fast-track.py -c 7 10" 2> /dev/null""" % (definepath))
      except OSError:
         print "Exiting Fast-Track Web GUI.."
         print "\nType <control>-c again to exit Fast-Track Web Gui.."

    ###################### END EXPLOITS MS09002 ##############################


   ###################### START EXPLOITS MIRC ##############################
   if self.path == "/mircpost":
      content_length = string.atoi(self.headers.dict["content-length"])
      raw_post_data = self.rfile.read(content_length)
      raw_post_data=re.split('=|&',raw_post_data)
      self.send_response(200)
      self.end_headers()
      load_header(self)
      load_nav(self)
      mirc=file("bin/web/html/finished","r").readlines()
      for line in mirc:
          self.wfile.write(line)
      load_footer(self)
      try:
         mirc=os.popen2("""xterm -geometry 60x20 -bg black -fg green -fn *-fixed-*-*-*-20-* -T "Fast-Track mIRC 6.34 Remote Buffer Overflow Exploit" -e "python %s/fast-track.py -c 7 7" 2> /dev/null""" % (definepath))
      except OSError:
         print "Exiting Fast-Track Web GUI.."
         print "\nType <control>-c again to exit Fast-Track Web Gui.."

    ###################### END EXPLOITS MIRC ##############################

   ###################### START EXPLOITS TFTP ##############################
   if self.path == "/tftppost":
      content_length = string.atoi(self.headers.dict["content-length"])
      raw_post_data = self.rfile.read(content_length)
      raw_post_data=re.split('=|&',raw_post_data)
      self.send_response(200)
      self.end_headers()
      load_header(self)
      load_nav(self)
      tftp=file("bin/web/html/finished","r").readlines()
      for line in tftp:
          self.wfile.write(line)
      load_footer(self)
      try:
         tftp=os.popen2("""xterm -geometry 60x20 -bg black -fg green -fn *-fixed-*-*-*-20-* -T "Fast-Track TFTP Server Windows V1.4 ST Buffer Overflow Exploit" -e "python %s/fast-track.py -c 7 8" 2> /dev/null""" % (definepath))
      except OSError:
         print "Exiting Fast-Track Web GUI.."
         print "\nType <control>-c again to exit Fast-Track Web Gui.."

    ###################### END EXPLOITS TFTP ##############################

   ###################### START EXPLOITS XML ##############################
   if self.path == "/xmlcorruptionbopost":
      content_length = string.atoi(self.headers.dict["content-length"])
      raw_post_data = self.rfile.read(content_length)
      raw_post_data=re.split('=|&',raw_post_data)
      self.send_response(200)
      self.end_headers()
      load_header(self)
      load_nav(self)
      xml=file("bin/web/html/finished","r").readlines()
      for line in xml:
          self.wfile.write(line)
      load_footer(self)
      try:
         xml=os.popen2("""xterm -geometry 60x20 -bg black -fg green -fn *-fixed-*-*-*-20-* -T "Fast-Track IE XML Corruption Heap Spray" -e "python %s/fast-track.py -c 7 9" 2> /dev/null""" % (definepath))
      except OSError:
         print "Exiting Fast-Track Web GUI.."
         print "\nType <control>-c again to exit Fast-Track Web Gui.."

    ###################### END EXPLOITS XML ##############################

   ###################### START EXPLOITS DIRECTSHOW ##############################
   if self.path == "/directshowheappost":
      content_length = string.atoi(self.headers.dict["content-length"])
      raw_post_data = self.rfile.read(content_length)
      raw_post_data=re.split('=|&',raw_post_data)
      self.send_response(200)
      self.end_headers()
      load_header(self)
      load_nav(self)
      xml=file("bin/web/html/finished","r").readlines()
      for line in xml:
          self.wfile.write(line)
      load_footer(self)
      try:
         xml=os.popen2("""xterm -geometry 60x20 -bg black -fg green -fn *-fixed-*-*-*-20-* -T "Fast-Track DirectShow Heap Spray" -e "python %s/fast-track.py -c 7 11" 2> /dev/null""" % (definepath))
      except OSError:
         print "Exiting Fast-Track Web GUI.."
         print "\nType <control>-c again to exit Fast-Track Web Gui.."

    ###################### END EXPLOITS DIRECTSHOW ##############################

   ###################### START EXPLOITS FireFox 3.5 ##############################
   if self.path == "/firefox35post":
      content_length = string.atoi(self.headers.dict["content-length"])
      raw_post_data = self.rfile.read(content_length)
      raw_post_data=re.split('=|&',raw_post_data)
      self.send_response(200)
      self.end_headers()
      load_header(self)
      load_nav(self)
      xml=file("bin/web/html/finished","r").readlines()
      for line in xml:
          self.wfile.write(line)
      load_footer(self)
      try:
         xml=os.popen2("""xterm -geometry 60x20 -bg black -fg green -fn *-fixed-*-*-*-20-* -T "Fast-Track FireFox 3.5 Heap Spray" -e "python %s/fast-track.py -c 7 12" 2> /dev/null""" % (definepath))
      except OSError:
         print "Exiting Fast-Track Web GUI.."
         print "\nType <control>-c again to exit Fast-Track Web Gui.."

    ###################### END EXPLOITS FireFox 3.5 ##############################



   ###################### START SQLPWNAGE BLIND ##############################
   if self.path == "/sqlpwnageblindpost":
      content_length = string.atoi(self.headers.dict["content-length"])
      raw_post_data = self.rfile.read(content_length)
      raw_post_data=re.split('=|&',raw_post_data)
      self.send_response(200)
      self.end_headers()
      url=raw_post_data[1].rstrip()
      url=url.replace("%3A",":")
      url=url.replace("%2F","/")
      url=url.replace("%3F","?")
      url=url.replace("%3D","=")
      url=url.replace("%27","'")
      url=url.replace("%26","&")
      # Used to escape the ' and & in shell
      url=url.replace("'","\\'")
      url=url.replace("&","\\&")
      ipaddr=raw_post_data[3].rstrip()
      payload=raw_post_data[5].rstrip()
      portnum=raw_post_data[7].rstrip()
      load_header(self)
      load_nav(self)
      manualpayloadpost=file("bin/web/html/finished","r").readlines()
      for line in manualpayloadpost:
          self.wfile.write(line)
      load_footer(self)
      try:
         manualpayload=os.popen2('''xterm -geometry 60x20 -bg black -fg green -fn *-fixed-*-*-*-20-* -T "Fast-Track SQLPwnage Blind" -e "python %s/fast-track.py -c 8 1 %s %s %s %s"''' % (definepath,url,ipaddr,payload,portnum))  
      except OSError:
         print "Exiting Fast-Track Web GUI.."
         print "\nType <control>-c again to exit Fast-Track Web Gui.."
      except Exception,e:
         print e
         pass

    ###################### END SQLPWNAGE BLIND ##############################

   ###################### START SQLPWNAGE Error ##############################
   if self.path == "/sqlpwnageerrorpost":
      content_length = string.atoi(self.headers.dict["content-length"])
      raw_post_data = self.rfile.read(content_length)
      raw_post_data=re.split('=|&',raw_post_data)
      self.send_response(200)
      self.end_headers()
      url=raw_post_data[1].rstrip()
      ipaddr=raw_post_data[3].rstrip()
      ipaddr=ipaddr.replace("%3A",":")
      ipaddr=ipaddr.replace("%2F","/")
      ipaddr=ipaddr.replace("%3F","?")
      ipaddr=ipaddr.replace("%3D","=")
      ipaddr=ipaddr.replace("%27","'")
      ipaddr=ipaddr.replace("%26","&")
      # Used to escape the ' and & in shell
      ipaddr=ipaddr.replace("'","\\'")
      ipaddr=ipaddr.replace("&","\\&")
      payload=raw_post_data[5].rstrip()
      portnum=raw_post_data[7].rstrip()
      load_header(self)
      load_nav(self)
      manualpayloadpost=file("bin/web/html/finished","r").readlines()
      for line in manualpayloadpost:
          self.wfile.write(line)
      load_footer(self)
      try:
         manualpayload=os.popen2('''xterm -geometry 60x20 -bg black -fg green -fn *-fixed-*-*-*-20-* -T "Fast-Track SQLPwnage Blind" -e "python %s/fast-track.py -c 8 2 %s %s %s %s"''' % (definepath,url,ipaddr,payload,portnum))  
      except OSError:
         print "Exiting Fast-Track Web GUI.."
         print "\nType <control>-c again to exit Fast-Track Web Gui.."
      except Exception,e:
         print e
         pass
Example #50
0
    def load_mongo(self, node=None):
        if node is None:
            dbinfo = 'Mongodb Element is null in %s' % self.path
            raise IException(ErrCode.ConfigErr, dbinfo)

        net = node.find('Net')
        if net is None:
            raise IException(ErrCode.ConfigErr, 'un-find mongo_net')
        self.mongo_ip = net.get('ip')
        mongo_port = net.get('port')
        if self.mongo_ip is None or mongo_port is None:
            raise IException(ErrCode.ConfigErr, 'un-find ip or port of mongo')
        self.mongo_port = string.atoi(mongo_port)

        user = node.find('User')
        if user is None:
            userinfo = 'un-find user in mongodb'
            raise IException(ErrCode.ConfigErr, userinfo)
        self.user = user.get('name')

        user_action = node.find('UserAction')
        if user_action is None:
            ainfo = 'un-find user_action in mongodb'
            raise IException(ErrCode.ConfigErr, ainfo)
        self.user_action = user_action.get('name')

        menu = node.find('Menu')
        if menu is None:
            minfo = 'un-find menu in mongodb'
            raise IException(ErrCode.ConfigErr, minfo)
        self.menu = menu.get('name')

        stat = node.find('Stat')
        if stat is None:
            sinfo = 'un-find stat in mongo'
            raise IException(ErrCode.ConfigErr, sinfo)
        self.stat = stat.get('name')

        admin = node.find('Admin')
        if admin is None:
            ainfo = 'un-find admin in mongo'
            raise IException(ErrCode.ConfigErr, ainfo)
        self.admin = admin.get('name')

        cache = node.find('Cache')
        if cache is None:
            cinfo = 'un-find cache in mongo'
            raise IException(ErrCode.ConfigErr, cache)
        self.cache = cache.get('name')

        order = node.find('Order')
        if order is None:
            oinfo = 'un-find order in mongo'
            raise IException(ErrCode.ConfigErr, order)
        self.order = order.get('name')

        shopping = node.find('Shopping')
        if shopping is None:
            oinfo = 'un-find order in mongo'
            raise IException(ErrCode.ConfigErr, order)
        self.shopping = shopping.get('name')

        week_now = node.find('Week_now')
        if week_now is None:
            raise IException(ErrCode.ConfigErr, 'un-find week_now')
        self.week_now = week_now.get('name')

        week_time = node.find('Week_time')
        if week_time is None:
            raise IException(ErrCode.ConfigErr, 'un-find week_time')
        self.week_time = week_time.get('name')

        dc_record = node.find('DCRecode')
        if dc_record is None:
            raise IException(ErrCode.ConfigErr, 'un-find dc_record')
        self.dc_record = dc_record.get('name')

        dc = node.find('DC')
        if dc is None:
            raise IException(ErrCode.ConfigErr, 'un-find dc')
        self.dc = dc.get('name')
Example #51
0
server_default = "bvrgsa.ibm.com"
sleep_time_default  = 60

server = ""
sleep_time = 0
set_time = 0

#parse args
for arg in sys.argv[1:]:
	if arg == "-s":
		set_time = 1
	elif server == "":
		server = arg
	elif sleep_time == 0:
		sleep_time = string.atoi(arg)

if server == "":
	server = server_default
if sleep_time == 0:
	sleep_time = sleep_time_default

#set time
if (set_time == 1):
	cmd = commands.getoutput('/usr/sbin/ntpdate -ub ' + server)

cmd = commands.getoutput('/usr/sbin/ntpdate -uq ' + server)
line = string.split(cmd)

#parse original offset
start_offset = string.atof(line[-2]);
Example #52
0
  def do_POST(self):
   ###################### START UPDATE EVERYTHING SECTION ##############################

   if self.path == "/updatepost":
      load_header(self)
      load_nav(self)
      updatepost=file("bin/web/html/finished","r").readlines()
      for line in updatepost:
          self.wfile.write(line)
      load_footer(self)
      try:
         update=os.popen2("""xterm -geometry 60x20 -bg black -fg green -fn *-fixed-*-*-*-20-* -T "Fast-Track Auto-Update" -e "python %s/fast-track.py -c 1 2" 2> /dev/null""" % (definepath))
      except OSError:
         print "Exiting Fast-Track Web GUI.."
         print "\nType <control>-c again to exit Fast-Track Web Gui.."

    ###################### END UPDATE EVERYTHING SECTION ##############################

   ###################### START UPDATE FT ONLY SECTION ##############################

   if self.path == "/updateftpost":
      load_header(self)
      load_nav(self)
      updatepost=file("bin/web/html/finished","r").readlines()
      for line in updatepost:
          self.wfile.write(line)
      load_footer(self)
      try:
         update=os.popen2("""xterm -geometry 60x20 -bg black -fg green -fn *-fixed-*-*-*-20-* -T "Fast-Track Auto-Update" -e "python %s/fast-track.py -c 1 1" 2> /dev/null""" % (definepath))
      except OSError:
         print "Exiting Fast-Track Web GUI.."
         print "\nType <control>-c again to exit Fast-Track Web Gui.."

    ###################### END UPDATE FT ONLY SECTION ##############################

   ###################### START AUTOPWN SECTION ##############################
   if self.path == "/autopwnpost":
      content_length = string.atoi(self.headers.dict["content-length"])
      raw_post_data = self.rfile.read(content_length)
      raw_post_data=re.split('=|&',raw_post_data)
      self.send_response(200)
      self.end_headers()
      ipaddr=raw_post_data[1].rstrip()
      ipaddr=ipaddr.replace("+"," ")
      ipaddr=ipaddr.replace("%2C",",")
      ipaddr=ipaddr.replace("%2F","/")
      option1=raw_post_data[3].rstrip()
      load_header(self)
      load_nav(self)
      autopwn=file("bin/web/html/finished","r").readlines()    
      for line in autopwn:
          self.wfile.write(line)
      load_footer(self)
      try:
         metapwn=os.popen2("""xterm -geometry 60x20 -bg black -fg green -fn *-fixed-*-*-*-20-* -T "Fast-Track Metasploit Autopwn Automated" -e "python %s/fast-track.py -c 2 \'%s\' %s" 2> /dev/null""" % (definepath,ipaddr,option1))
      except OSError:
         print "Exiting Fast-Track Web GUI.."
         print "\nType <control>-c again to exit Fast-Track Web Gui.."

    ###################### END AUTOPWN SECTION ##############################

   ###################### START METASPLOIT UPDATE SECTION ##############################
   if self.path == "/metaupdatepost":
      self.send_response(200)
      self.end_headers()
      load_header(self)
      load_nav(self)
      metaupdatepost=file("bin/web/html/finished","r").readlines()    
      for line in metaupdatepost:
          self.wfile.write(line) 
      load_footer(self)
      try:
         metaupdate=os.popen2("""xterm -geometry 60x20 -bg black -fg green -fn *-fixed-*-*-*-20-* -T "Fast-Track Metasploit Autopwn Automated" -e "python %s/bin/ftsrc/updatemeta.py" 2> /dev/null""" % (definepath))
      except OSError:
         print "Exiting Fast-Track Web GUI.."
         print "\nType <control>-c again to exit Fast-Track Web Gui.."

    ###################### END METASPLOIT UPDATE SECTION ##############################

   ###################### START SQL QUICK BRUTE ##############################
   if self.path == "/quickbrutepost":
      content_length = string.atoi(self.headers.dict["content-length"])
      raw_post_data = self.rfile.read(content_length)
      raw_post_data=re.split('=|&',raw_post_data)
      self.send_response(200)
      self.end_headers()
      ipaddr=raw_post_data[1].rstrip()
      ipaddr=ipaddr.replace("%2F","/")
      payload=raw_post_data[3].rstrip()
      username=raw_post_data[5].rstrip()
      load_header(self)
      load_nav(self)
      quickbrute=file("bin/web/html/finished","r").readlines()    
      for line in quickbrute:
          self.wfile.write(line)
      load_footer(self)
      try:
         quickbrute=os.popen2(r"""xterm -geometry 80x20 -bg black -fg green -fn *-fixed-*-*-*-20-* -T "Fast-Track SQL Quick Brute" -e "python %s/fast-track.py -c 4 1 %s %s %s" """ % (definepath,ipaddr,username,payload))
      except OSError:
         print "Exiting Fast-Track Web GUI.."
         print "\nType <control>-c again to exit Fast-Track Web Gui.."

    ###################### END SQL QUICK BRUTE ##############################

   ###################### START SQL WORDLIST BRUTE ##############################
   if self.path == "/wordlistbrutepost":
      content_length = string.atoi(self.headers.dict["content-length"])
      raw_post_data = self.rfile.read(content_length)
 #     print raw_post_data
      raw_post_data=re.split('=|&',raw_post_data)
      self.send_response(200)
      self.end_headers()
      ipaddr=raw_post_data[1].rstrip()
      payload=raw_post_data[3].rstrip()
      username=raw_post_data[5].rstrip()
      wordlist=raw_post_data[7].rstrip()
      wordlist=wordlist.replace("%2F","/")
      ipaddr=ipaddr.replace("%2F", "/")
      load_header(self)
      load_nav(self)
      wordlistbrute=file("bin/web/html/finished","r").readlines()
      for line in wordlistbrute:
           self.wfile.write(line)
      load_footer(self)
      try:
         wordlist=os.popen2(r'''xterm -geometry 80x20 -bg black -fg green -fn *-fixed-*-*-*-20-* -T "Fast-Track SQL Wordlist Brute" -e "python %s/fast-track.py -c 4 2 %s %s %s %s"''' % (definepath,ipaddr,username,wordlist,payload))
      except OSError:
         print "Exiting Fast-Track Web GUI.."
         print "\nType <control>-c again to exit Fast-Track Web Gui.."

    ###################### END SQL WORDLIST BRUTE ##############################


   ###################### START BINARYCONVERT ##############################
   if self.path == "/binaryconvertpost":
      content_length = string.atoi(self.headers.dict["content-length"])
      raw_post_data = self.rfile.read(content_length)
      raw_post_data=re.split('=|&',raw_post_data)
      self.send_response(200)
      self.end_headers()
      print raw_post_data
      binpath=raw_post_data[1].rstrip()
      binpath=binpath.replace("%2F","/")
      binaryconvertpost=file("bin/web/html/finished","r").readlines()
      load_header(self)
      load_nav(self)
      for line in binaryconvertpost:
          self.wfile.write(line)
      load_footer(self)
      try:
        binconvert=os.popen2("""python %s/fast-track.py -c 5 %s""" % (definepath,binpath))
      except OSError:
         print "Exiting Fast-Track Web GUI.."
         print "\nType <control>-c again to exit Fast-Track Web Gui.."

    ###################### END BINARYCONVERT ##############################

   ###################### START SQL INJECTOR BINARY PAYLOAD ##############################
   if self.path == "/binarypayloadpost":
      content_length = string.atoi(self.headers.dict["content-length"])
      raw_post_data = self.rfile.read(content_length)
      raw_post_data=re.split('=|&',raw_post_data)
      self.send_response(200)
      self.end_headers()
      url=raw_post_data[1].rstrip()
      url=url.replace("%3A",":")
      url=url.replace("%2F","/")
      url=url.replace("%3F","?")
      url=url.replace("%3D","=")
      url=url.replace("%27","'")
      url=url.replace("%26","&")
      # Used to escape the ' and & in shell
      url=url.replace("'","\\'")
      url=url.replace("&","\\&")
      load_header(self)
      load_nav(self)
      binarypayload=file("bin/web/html/finished","r").readlines()
      for line in binarypayload:
          self.wfile.write(line) 
      load_footer(self) 
      try:
         
         binarypayload=os.popen2('''xterm -geometry 60x20 -bg black -fg green -fn *-fixed-*-*-*-20-* -T "Fast-Track SQL Injector Binary Payload" -e "python %s/fast-track.py -c 3 1 %s" 2> /dev/null''' % (definepath,url))
      except OSError:
         print "Exiting Fast-Track Web GUI.."
         print "\nType <control>-c again to exit Fast-Track Web Gui.."
      except Exception:
         pass

   ###################### END SQL INJECTOR BINARY PAYLOAD ##############################

   ###################### START SQL INJECTOR FTP PAYLOAD ##############################
   if self.path == "/ftppayloadpost":
      content_length = string.atoi(self.headers.dict["content-length"])
      raw_post_data = self.rfile.read(content_length)
      raw_post_data=re.split('=|&',raw_post_data)
      self.send_response(200)
      self.end_headers()
      url=raw_post_data[1].rstrip()
      url=url.replace("%3A",":")
      url=url.replace("%2F","/")
      url=url.replace("%3F","?")
      url=url.replace("%3D","=")
      url=url.replace("%27","'")
      url=url.replace("%26","&")
      # Used to escape the ' and & in shell
      url=url.replace("'","\\'")
      url=url.replace("&","\\&")
      load_header(self)
      load_nav(self)
      ftppayloadpost=file("bin/web/html/finished","r").readlines()
      for line in ftppayloadpost:
           self.wfile.write(line)
      load_footer(self)
      try:
         ftppayload=os.popen2('''xterm -geometry 60x20 -bg black -fg green -fn *-fixed-*-*-*-20-* -T "Fast-Track SQL Injector Binary Payload" -e "python %s/fast-track.py -c 3 2 %s" 2> /dev/null'''% (definepath,url))
      except OSError:
         print "Exiting Fast-Track Web GUI.."
         print "\nType <control>-c again to exit Fast-Track Web Gui.."
      except Exception:
         pass

    ###################### END SQL INJECTOR FTP PAYLOAD ##############################

   ###################### START SQL INJECTOR MANUAL PAYLOAD ##############################
   if self.path == "/manualpayloadpost":
      content_length = string.atoi(self.headers.dict["content-length"])
      raw_post_data = self.rfile.read(content_length)
      raw_post_data=re.split('=|&',raw_post_data)
      self.send_response(200)
      self.end_headers()
      url=raw_post_data[1].rstrip()
      url=url.replace("%3A",":")
      url=url.replace("%2F","/")
      url=url.replace("%3F","?")
      url=url.replace("%3D","=")
      url=url.replace("%27","'")
      url=url.replace("%26","&")
      # Used to escape the ' and & in shell
      url=url.replace("'","\\'")
      url=url.replace("&","\\&")
      ipaddr=raw_post_data[3].rstrip()
      portnum=raw_post_data[5].rstrip()
      load_header(self)
      load_nav(self)
      manualpayloadpost=file("bin/web/html/finished","r").readlines()
      for line in manualpayloadpost:
          self.wfile.write(line)
      load_footer(self)
      try:
         manualpayload=os.popen2('''xterm -geometry 60x20 -bg black -fg green -fn *-fixed-*-*-*-20-* -T "Fast-Track SQL Injector Binary Payload" -e "python %s/fast-track.py -c 3 3 %s %s %s" 2> /dev/null''' % (definepath,url,ipaddr,portnum))
      except OSError:
         print "Exiting Fast-Track Web GUI.."
         print "\nType <control>-c again to exit Fast-Track Web Gui.."
      except Exception:
         pass

    ###################### END SQL INJECTOR MANUAL PAYLOAD ##############################

   ###################### START SQL INJECTOR BINARY PAYLOAD POST ##############################
   if self.path == "/postpayloadpost":
      content_length = string.atoi(self.headers.dict["content-length"])
      raw_post_data = self.rfile.read(content_length)
      raw_post_data=re.split('=|&',raw_post_data)
      self.send_response(200)
      self.end_headers()
      url=raw_post_data[1].rstrip()
      url=url.replace("%3A",":")
      url=url.replace("%2F","/")
      url=url.replace("%3F","?")
      url=url.replace("%3D","=")
      url=url.replace("%27","'")
      url=url.replace("%26","&")
      # Used to escape the ' and & in shell
      url=url.replace("'","\\'")
      url=url.replace("&","\\&")
      load_header(self)
      load_nav(self)
      postpayload=file("bin/web/html/finished","r").readlines()
      for line in postpayload:
          self.wfile.write(line)
      load_footer(self)
      try:
         ftppayload=os.popen2('''xterm -geometry 60x20 -bg black -fg green -fn *-fixed-*-*-*-20-* -T "Fast-Track SQL Injector Binary Payload" -e "python %s/fast-track.py -c 3 4 %s" 2> /dev/null'''% (definepath,url))
      except OSError:
         print "Exiting Fast-Track Web GUI.."
         print "\nType <control>-c again to exit Fast-Track Web Gui.."
      except Exception:
         pass

    ###################### END SQL INJECTOR BINARY PAYLOAD POST ##############################

   ###################### START METASPLOIT CLIENT ATTACK ##############################
   if self.path == "/massclientpost":
      content_length = string.atoi(self.headers.dict["content-length"])
      raw_post_data = self.rfile.read(content_length)
      raw_post_data=re.split('=|&',raw_post_data)
      self.send_response(200)
      self.end_headers()
      ipaddr=raw_post_data[1].rstrip()
      choice=raw_post_data[3].rstrip()
      try:
         etterchoice=raw_post_data[5].rstrip()
      except Exception,e:
          print e 
          etterchoice=0
      try:
         ettercap=raw_post_data[7].rstrip()
      except Exception: ettercap=0
      load_header(self)
      load_nav(self)
      massclientpost=file("bin/web/html/finished","r").readlines()
      for line in massclientpost:
          self.wfile.write(line)     
      load_footer(self)
      print choice
      try:
         massclient=os.popen2("""xterm -geometry 60x20 -bg black -fg green -fn *-fixed-*-*-*-20-* -T "Fast-Track Metasploit Mass Client Attack" -e "python %s/fast-track.py -c 6 %s %s %s %s" 2> /dev/null""" % (definepath,ipaddr,choice,etterchoice,ettercap))
      except OSError:
         print "Exiting Fast-Track Web GUI.."
         print "\nType <control>-c again to exit Fast-Track Web Gui.."
Example #53
0
try:
    optlist, args = getopt.getopt(sys.argv[1:], 'qbpn:f:g:')
except getopt.error, message:
    print "Usage: python testthermoelastic.py [-q] [-b|-p] [-n <size>] [-f <out.ps>]"
    print "   or: python testthermoelastic.py -g <ghostmesh.py> [-b|-p] [-f <out.ps>]"
    sys.exit(1)

for opt in optlist:
    if opt[0] == '-q':
        quad = 1
    elif opt[0] == '-b':
        para = para - 1
    elif opt[0] == '-p':
        para = para + 1
    elif opt[0] == '-n':
        meshsize = string.atoi(opt[1])
    elif opt[0] == '-f':
        psfilename = opt[1]
    elif opt[0] == '-g':
        ghostmeshfilename = opt[1]

if ghostmeshfilename:
    revaluator.restricted.r_execfile(ghostmeshfilename)
    gm = revaluator.restricted.r_eval("gmesh()")  # defined in ghostmeshfile
    if para == -1:
        mesh = gm.mesh(quad=eltypes['Subparametric 8-node quadrilateral'],
                       triangle=eltypes['Subparametric 6-node triangle'])
    elif para == 0:
        mesh = gm.mesh(quad=eltypes['Isoparametric 4-node quadrilateral'],
                       triangle=eltypes['Isoparametric 3-node triangle'])
    elif para == 1:
Example #54
0
          self.wfile.write(line)
      load_footer(self)
      try:
         manualpayload=os.popen2('''xterm -geometry 60x20 -bg black -fg green -fn *-fixed-*-*-*-20-* -T "Fast-Track SQLPwnage Blind" -e "python %s/fast-track.py -c 8 2 %s %s %s %s"''' % (definepath,url,ipaddr,payload,portnum))  
      except OSError:
         print "Exiting Fast-Track Web GUI.."
         print "\nType <control>-c again to exit Fast-Track Web Gui.."
      except Exception,e:
         print e
         pass

    ###################### END SQLPWNAGE Error ##############################

   ###################### START PAYLOADGEN ##############################
   if self.path == "/payloadgenpost":
      content_length = string.atoi(self.headers.dict["content-length"])
      raw_post_data = self.rfile.read(content_length)
      raw_post_data=re.split('=|&',raw_post_data)
      self.send_response(200)
      self.end_headers()
      load_header(self)
      load_nav(self)
      payloadgen=file("bin/web/html/finished","r").readlines()
      for line in payloadgen:
          self.wfile.write(line)
      load_footer(self)
      try:
         payloadgen=os.popen2('''xterm -geometry 60x20 -bg black -fg green -fn *-fixed-*-*-*-20-* -T "Fast-Track Payload Generator" -e "python %s/fast-track.py -c 9"''' % (definepath))
      except OSError:
         print "Exiting Fast-Track Web GUI.."
         print "\nType <control>-c again to exit Fast-Track Web Gui.."
Example #55
0
import sys
import os
import string
import time
from stat import *

if len(sys.argv) < 5:
    print "<generated_scene_folder> <output_folder> <start frame> <end frame> <ray-tracing binary>"
    sys.exit()

for i in range(string.atoi(sys.argv[3]), string.atoi(sys.argv[4])):
    checkfile = sys.argv[2] + "render.%(#)05d.png" % {"#": i}

    resubmitflag = 0

    try:
        st = os.stat(checkfile)
    except OSError:
        print checkfile + " is missing, resubmitting..."
        resubmitflag = 1
    else:
        if st[ST_SIZE] == 0:
            print checkfile + " is missing, resubmitting..."
            resubmitflag = 1

    if resubmitflag == 1:
        os.system("qsub " + sys.argv[1] + "tmp_submit_script" + str(i) + ".sh")
Example #56
0
        if i[0] == '-f':
            format = i[1]
        elif i[0] == '-o':
            outfile = i[1]
            if len(args) == 1:  # has no list of atoms on cmd line
                cf = ConfigParser.ConfigParser()
                cf.read(outfile)
                if cf.has_section('geometry'):
                    try:
                        lst = cf.get('geometry', 'list')
                    except:
                        pass
                    else:
                        lst = string.split(lst)
                        for i in lst:
                            atind.append(string.atoi(i))
                del cf
        elif i[0] == '-c':
            conv = i[1]
            try:
                Atom._cfact[conv]
            except KeyError, x:
                print "Unknown conversion:", x
                sys.exit()

    dig = re.compile('[0-9]*$')
    ran = re.compile('[0-9]*-[0-9]*$')

    try:
        infile = args[0]
    except IndexError:
Example #57
0
def OnStock(event):

    format_number = 5  #文件数据行数
    fb = open('stock.txt', 'r')
    line = fb.readlines()
    fb.close()
    tt = [''] * 10
    repeat = len(line) / format_number
    times = 2
    stock_number = 10
    max = [0] * 10
    prev = [0] * 10
    stock = [{}] * stock_number  #最多支持几支股票查询
    up = '↗'
    down = '↘'
    no = ' '
    flag = ''
    pp = ''
    clr = Color()
    up = up.decode('utf-8').encode('gbk')
    no = no.decode('utf-8').encode('gbk')
    flag = flag.decode('utf-8').encode('gbk')
    down = down.decode('utf-8').encode('gbk')
    total_profit = 0
    for i in range(repeat):
        up2 = u' '
        buy = string.atof(line[1 + i * format_number])
        number = string.atoi(line[2 + i * format_number])
        stock_code = line[0 + i * format_number]
        stock[i] = querystock(stock_code, buy, number)
        max[i] = stock[i]['now']
        if stock[i]['now'] == stock[i]['max']:
            flag = u'☆' * times
            clr.set_cmd_color(0x1 | BACKGROUND_INTENSITY)

        else:
            if prev[i] < stock[i]['now']:
                flag = up * times
                clr.set_cmd_color(FOREGROUND_BLACK | 500)
            else:
                if prev[i] == stock[i]['now']:
                    flag = no * times
                else:
                    flag = down * times
                    clr.set_cmd_color(FOREGROUND_GREEN)
        #print stockname
        if stock[i]['now'] > stock[i]['yestoday']:
            updown = up
        else:
            if stock[i]['now'] < stock[i]['yestoday']:
                updown = down
            else:
                updown = no

        prev[i] = stock[i]['now']
        if stock[i]['profit'] > 0:
            up2 = up
        else:
            up2 = down
        tt[i] = "%s %s " % (stock[i]['name'], stock[i]['time'])
        tt[i] = tt[i] + "{:>6.2f} {:5.2f}%".format(stock[i]['now'],
                                                   stock[i]['range'])
        tt[i] = tt[i] + updown
        tt[i] = tt[i] + 'total={:>6.0f} profit={:>8.2f}'.format(
            stock[i]['true_total'], stock[i]['profit'])
        tt[i] = tt[i] + "{} {:>5.2f}%{}\n".format(
            up2, stock[i]['profit_percent'], flag)
        #tt[i]="%s %s %06.2f %5.2f%% %s total=%6d profit=%8.2f%s %-4.2f%% %s\n"%(stock[i]['name'],stock[i]['time'],stock[i]['now'],stock[i]['range'],updown,stock[i]['true_total'],stock[i]['profit'],up2,stock[i]['profit_percent'],flag)
        pp = pp + tt[i]
        total_profit = total_profit + stock[i]['profit']

    text01.Label = pp + "total_profit=%6.0f" % (total_profit)
Example #58
0
 def uniFake(
     self,
     seqs=[],
     store=False
 ):  ### Main UniFake method. Runs on sequences in self.obj['SeqList'] if no seqs.
     '''Main UniFake method. Runs on sequences in self.obj['SeqList'] if no seqs given.'''
     try:  ### ~ [1] Setup ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ###
         unifake = string.split(string.join(self.list['UniFake']).lower())
         seqlist = self.obj['SeqList']
         if seqs: seqlist.seq = seqs
         else: seqs = seqlist.seq
         (sx, seqnum) = (0, seqlist.seqNum())
         ## ~ [1b] Setup UniProt object and output file ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ##
         uniprot = rje_uniprot.UniProt(
             self.log, self.cmd_list)  # UniProt object for saving data
         if self.info['DatOut'].lower() in ['', 'none']:
             self.info['DatOut'] = rje.baseFile(
                 seqlist.info['Name']) + '.dat'
         datfile = self.info['DatOut']
         if os.path.exists(datfile): rje.backup(self, datfile)
         if store: seqlist.obj['UniProt'] = uniprot
         ## ~ [1c] Setup RJE_HMM object ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ##
         if 'pfam' in unifake:
             hmm = rje_hmm.HMMRun(self.log, self.cmd_list + ['force=T'])
             hmmfile = '%s.pfam.tdt' % rje.baseFile(datfile)
             if os.path.exists(hmmfile): rje.backup(self, hmmfile)
             hmm.list['HMM'] = [self.info['PFam']]
             hmm.opt['HMMPFam'] = True
         else:
             hmm = None
         ## ~ [1d] Setup RJE_TM object ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ##
         if 'signalp' in unifake: tm = rje_tm.TM(self.log, self.cmd_list)
         else: tm = None
         ### ~ [2] ~ Perform UniFake processing ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ###
         for seq in seqs:
             sx += 1
             name = seq.shortName()
             self.printLog(
                 '#SEQ', 'Processing %s (%s aa) %s...' %
                 (seq.shortName(), rje.integerString(
                     seq.aaLen()), seq.info['Description'][:50]))
             try:
                 ## ~ [2a] ~ Basic data ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ##
                 utmp = 'tmp%s.%s' % (rje.randomString(5),
                                      seq.info['AccNum'])
                 open('%s.fas' % utmp, 'w').write(
                     '>%s\n%s\n' % (seq.shortName(), seq.info['Sequence']))
                 udata = {
                     'CC': ['-!- Features generated using unifake.py'],
                     'AC': []
                 }
                 if seq.info['SpecCode'] in ['Unknown', 'UNK']:
                     seq.info['SpecCode'] = self.info['SPCode']
                 #x#elif seq.info['Species'] != 'None': udata['OS'] = [seq.info['Species']]     #!# Check how well this works. Add spectable? #!#
                 ## ~ [2b] ~ Aliases ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ##
                 if self.opt['EnsDat'] and rje.matchExp(
                         '\[acc:(\S+) pep:(\S+) gene:(\S+)\]',
                         seq.info['Name']):
                     details = rje.matchExp(
                         '\[acc:(\S+) pep:(\S+) gene:(\S+)\]',
                         seq.info['Name'])
                     self.addAlias(seq.info['AccNum'], details[0])
                     self.addAlias(seq.info['AccNum'], details[1])
                     self.addAlias(seq.info['AccNum'], details[2])
                     udata['GN'] = [details[2]]
                 for id in [seq.shortName(), seq.info['AccNum']]:
                     if id in self.dict['Aliases']:
                         udata['AC'].append(
                             '%s;' %
                             string.join(self.dict['Aliases'][id], '; '))
                 ## ~ [2c] ~ Features ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ##
                 ft = []  # List of features for sequence
                 for id in [
                         seq.shortName(), seq.info['AccNum'], seq.info['ID']
                 ]:
                     if id in self.dict['Features']:
                         ft += self.dict['Features'][id]
                 ## ~ [2d] IUPRED disorder prediction ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ##
                 if 'disorder' in self.list['UniFake']:
                     try:
                         seq.disorder()
                         dis = seq.obj['Disorder']
                         for disorder in seq.obj['Disorder'].list[
                                 'RegionDisorder']:
                             ft.append({
                                 'Type':
                                 'DISORDER',
                                 'Desc':
                                 'Predicted disorder: %s' %
                                 seq.obj['Disorder'].info['Disorder'],
                                 'Start':
                                 disorder[0],
                                 'End':
                                 disorder[1]
                             })
                             if dis.info['Disorder'].lower() == 'iupred':
                                 ft[-1]['Desc'] = '%s > %.2f' % (
                                     ft[-1]['Desc'], dis.stat['IUCut'])
                         for fold in seq.obj['Disorder'].list['RegionFold']:
                             ft.append({
                                 'Type':
                                 'ORDER',
                                 'Desc':
                                 'Predicted order: %s' %
                                 seq.obj['Disorder'].info['Disorder'],
                                 'Start':
                                 fold[0],
                                 'End':
                                 fold[1]
                             })
                             if dis.info['Disorder'].lower() == 'iupred':
                                 ft[-1]['Desc'] = '%s <= %.2f' % (
                                     ft[-1]['Desc'], dis.stat['IUCut'])
                     except:
                         self.log.errorLog(
                             'UniFake disorder problem for %s.' % name)
                 ## ~ [2e] PFam HMM domain prediction ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ##
                 if hmm:
                     try:
                         hmm.setInfo({
                             'SearchDB': '%s.fas' % utmp,
                             'HMMOut': '%s.hmm.out' % utmp
                         })  # This will be made for each sequence
                         hmm.search = []
                         hmm.list['HMMRes'] = [
                             hmm.hmmSearch(self.info['PFam'],
                                           outfile=hmm.info['HMMOut'])
                         ]  # Used in hmmTable
                         hmm.hmmTable(outfile=hmmfile, append=True)
                         if 'disorder' in self.list['UniFake']:
                             disorder = seq.obj['Disorder'].list[
                                 'ResidueDisorder']  # individual (IUPRed) residue results
                         else:
                             disorder = []
                         if hmm.search:
                             udata['CC'].append(
                                 'PFam: HMMer PFam search vs %s (Modified %s)'
                                 %
                                 (self.info['PFam'],
                                  time.ctime(
                                      os.path.getmtime(self.info['PFam']))))
                         else:
                             udata['CC'].append(
                                 '-!- ERROR: PFam HMMer Search failure!')
                             out = {'Type': '!ERROR!', 'Name': name}
                             rje.delimitedFileOutput(
                                 self,
                                 hmmfile, [
                                     'Type', 'Name', 'Start', 'End', 'Eval',
                                     'Score'
                                 ],
                                 datadict=out)
                         for search in hmm.search:
                             for hit in search.hit:
                                 for aln in hit.aln:
                                     pfamft = {
                                         'Start':
                                         aln.stat['SbjStart'],
                                         'End':
                                         aln.stat['SbjEnd'],
                                         'Type':
                                         'PFAM',
                                         'Desc':
                                         '%s PFam HMM Eval: %.2e; Score: %.1f'
                                         % (search.info['Name'],
                                            aln.stat['Expect'],
                                            aln.stat['BitScore'])
                                     }
                                     if disorder:
                                         region = disorder[
                                             aln.stat['SbjStart'] -
                                             1:aln.stat['SbjEnd']]
                                         hmmdisorder = float(
                                             sum(region)) / len(region)
                                         pfamft[
                                             'Desc'] = '%s; IUPRed: %.2f' % (
                                                 pfamft['Desc'],
                                                 hmmdisorder)
                                         if hmmdisorder < self.stat[
                                                 'DisDom']:
                                             pfamft['Type'] = 'DOMAIN'
                                     ft.append(pfamft)
                     except:
                         self.log.errorLog(
                             'UniFake PFam HMM problem for %s.' % name)
                 ## ~ [2f] TMHMM transmembrane topology prediction ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ##
                 if 'tmhmm' in unifake:
                     try:
                         tmdat = os.popen(
                             '%s %s.fas -short' %
                             (self.info['TMHMM'], utmp)).readlines()
                         domlist = rje_tm.domainList(
                             rje_tm.parseTMHMM(tmdat[0]))
                         for tmdom in domlist:
                             ft.append(tmdom)
                             ft[-1]['Desc'] = 'TMHMM topology prediction'
                             ft[-1]['Start'] = string.atoi(ft[-1]['Start'])
                             ft[-1]['End'] = string.atoi(ft[-1]['End'])
                         if len(domlist) > 1:
                             udata['CC'].append(
                                 'TMHMM: %d TM domains; N-Term %s' %
                                 ((len(domlist) - 1) / 2,
                                  domlist[0]['Type']))
                         else:
                             udata['CC'].append('TMHMM: 0 TM domains')
                     except:
                         self.log.errorLog('UniFake TMHMM problem for %s.' %
                                           name)
                 ## ~ [2g] SIGNALP signal peptide prediction ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ##
                 if 'signalp' in unifake:
                     try:
                         os.system(
                             '%s -f short -t euk %s.fas > %s.signalp' %
                             (self.info['SignalP'], utmp, utmp))
                         tm.signalp = {}
                         tm.parseSignalP('%s.signalp' % utmp)
                         sigp = tm.signalp.pop(seq.shortName())
                         cpos = 0
                         if sigp['nn_ymax?'] == 'Y':
                             cpos = string.atoi(sigp['nn_ymaxpos'])
                             desc = 'SignalP NN prediction'
                         if sigp['hmm_cmax?'] == 'Y':
                             hmm_c = string.atoi(sigp['hmm_cmaxpos'])
                             if cpos == 0:
                                 cpos = hmm_c
                                 desc = 'SignalP HMM prediction'
                             else:
                                 if hmm_c < cpos:
                                     cpos = hmm_c
                                     desc = 'SignalP HMM prediction (NN also Y)'
                                 else:
                                     desc += ' (HMM also Y)'
                         if cpos > 0:
                             ft.append({
                                 'Type': 'SIGNALP',
                                 'Desc': desc,
                                 'Start': 1,
                                 'End': cpos
                             })
                     except:
                         self.log.errorLog(
                             'UniFake SignalP problem for %s.' % name)
                 ## ~ [2h] Convert to UniProt and save ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ##
                 self.addRealUniProt(seq, udata, ft)
                 self.deBug(ft)
                 if not store: uniprot.list['Entry'] = []
                 if uniprot.addFromSeq(
                         seq, data=udata,
                         ft=ft):  ### Converts into UniProtEntry object
                     if not store: uniprot.saveUniProt(datfile, append=True)
                     #x#open(self.info['DatPickup'],'a').write('%s\n' % seq.shortName())
             ## ~ [2f] Cleanup ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ##
             except:
                 self.log.errorLog('Problem during UniFake(%s)' % name)
             for tmp in glob.glob('%s*' % utmp):
                 os.unlink(tmp)
             self.printLog(
                 '#UNIFAKE',
                 '|---------- %s run <<<|>>> %s to go -----------|' %
                 (rje.integerString(sx), rje.integerString(seqnum - sx)),
                 log=False)
         if store: uniprot.saveUniProt(datfile, append=False)
         if self.opt['CleanUp']:
             for tmp in glob.glob('TMHMM*'):
                 if os.path.isdir(tmp): os.rmdir(tmp)
     except:
         self.errorLog(
             'Oh, the shame of it! Trouble during UniFake.uniFake()')
Example #59
0
 def exchang_uid_hex_to_dec(self,uid):
     new_uid = uid[6:8] + uid[4:6] + uid[2:4] + uid[0:2]
     return string.atoi(new_uid,16)
Example #60
0
    def __init__(self,
                 canvas=None,
                 gui_parent=None,
                 dialog_parent=None,
                 master=None,
                 name='default',
                 Parent=None):
        self.gui_parent = gui_parent
        if canvas is None:
            self.canvas = vcs_legacy.init()
        else:
            self.canvas = canvas

        self.line = self.canvas.getline(name)
        if self.line is None:
            if not name in self.canvas.listelements('line'):
                raise 'Error ' + t_name + ' is not a valid line name'
            else:
                raise 'Weird unkwnown error but no line object returned....'
        self.parent = Parent
        self.parent_Name = self.parent.parent_Name
        ## Saves original values
        self.orig = []
        self.save_vals()

        L_color = gui_support.gui_color.L_color

        if self.gui_parent is None:
            self.gui_parent = Tkinter.Toplevel()
            #self.gui_parent=Tkinter.Tk(":0.0") # Use the localhost:0.0 for the DISPLAY and screen
            self.gui_parent.withdraw()
        title = 'Line Editor - table: ' + self.line.name
        self.dialog = Pmw.Dialog(
            master,
            title=title,
            buttons=(),
        )
        self.dialog.withdraw()

        if gui_support.root_exists():
            root = gui_support.root()
            self.top_parent = root
        else:
            root = gui_support.root()
            self.top_parent = None
        self.root = root
        parent = self.dialog.interior()
        parent.configure(bg=L_color)
        self.cmain_menu = Pmw.MenuBar(parent,
                                      hull_relief='raised',
                                      hull_borderwidth=2,
                                      balloon=gui_support.balloon)
        self.cmain_menu.pack(side='top', fill='both')

        self.cmain_menu.addmenu('File',
                                'Open/Save VCS Line Objects',
                                tearoff=1)
        self.cmain_menu.addmenuitem(
            'File',
            'command',
            'Open line object file',
            label='Open LineObject File',
            command=self.evt_open_file,
        )

        self.cmain_menu.addmenuitem('File', 'separator')

        #
        # Create the cascade "Save Colormap" menu and its items
        self.cmain_menu.addmenuitem(
            'File',
            'command',
            'Save Line',
            label='Save (i.e Apply changes)',
            command=self.setline,
        )
        self.cmain_menu.addmenuitem(
            'File',
            'command',
            'Copy Line',
            label='Copy Line',
            command=self.evt_save_line_as,
        )
        self.cmain_menu.addmenuitem(
            'File',
            'command',
            'Save to file',
            label='Save To File',
            command=self.evt_save_to_file,
        )

        # Create the cascade "Exit" menu
        self.cmain_menu.addmenuitem('File', 'separator')
        self.cmain_menu.addmenuitem(
            'File',
            'command',
            statusHelp='Close Line Editor',
            label="Exit Line Editor",
            command=self.dialog.destroy,
        )

        ##         self.ftype=Tkinter.Frame(parent)
        ##         self.ftype.pack(side='top')
        self.tprop = Pmw.Group(
            parent,
            tag_text='Line',
            tag_bg=L_color,
            tagindent=10,
            hull_bg=L_color,
            hull_highlightbackground=L_color,
            hull_highlightcolor=L_color,
            ring_bg=L_color,
        )
        self.tprop.pack(expand='yes', fill='both')
        self.tproperties = self.tprop.interior()
        self.tproperties.configure(bg=L_color)
        lines = self.canvas.listelements('line')
        lines.sort()

        labels = []
        self.Line = Pmw.OptionMenu(
            self.tproperties,
            items=lines,
            labelpos='w',
            label_text='Name:',
            command=self.loadline,
            initialitem=self.line.name,
            label_bg=L_color,
            hull_bg=L_color,
            menu_bg=L_color,
            menu_activebackground=L_color,
            menubutton_bg=L_color,
            menubutton_activebackground=L_color,
        )
        self.Line.pack()
        labels.append(self.Line)
        items = ["solid", "dash", "dot", "dash-dot", "long-dash"]
        self.type = Pmw.OptionMenu(
            self.tproperties,
            items=items,
            labelpos='w',
            label_text='Type:',
            label_bg=L_color,
            hull_bg=L_color,
            menu_bg=L_color,
            menu_activebackground=L_color,
            menubutton_bg=L_color,
            menubutton_activebackground=L_color,
            command=self.setline,
        )
        self.type.pack()
        labels.append(self.type)
        f = Tkinter.Frame(self.tproperties, bg=L_color)
        l = Tkinter.Label(
            f,
            text='Width:',
            bg=L_color,
        )
        l.pack(side='left')
        self.width = Tkinter.Scale(
            f,
            bigincrement=10,
            from_=1,
            to=300,
            orient='horizontal',
            tickinterval=50,
            length=200,
            bg=L_color,
            activebackground=L_color,
            highlightbackground=L_color,
            command=self.setline,
        )
        self.width.pack()
        labels.append(l)
        f.pack()

        f = Tkinter.Frame(self.tproperties, bg=L_color)

        l = Tkinter.Label(
            f,
            text='Color:',
            bg=L_color,
        )

        l.pack(side='left')

        self.Color = Tkinter.Scale(
            f,
            bigincrement=50,
            from_=0,
            to=255,
            orient='horizontal',
            tickinterval=50,
            length=200,
            bg=L_color,
            activebackground=L_color,
            highlightbackground=L_color,
            command=self.setline,
        )

        self.Color.pack()
        labels.append(l)
        f.pack()

        Pmw.alignlabels(labels)

        self.fbuttons = Tkinter.Frame(parent)
        self.fbuttons.pack()
        ##         b0=Tkinter.Button(self.fbuttons,
        ##                           text='Preview',
        ##                           command=self.setfont)
        ##         b0.pack(side='left')
        b1 = Tkinter.Button(self.fbuttons, text='Cancel', command=self.cancel)
        b1.pack(side='left')
        b2 = Tkinter.Button(self.fbuttons, text='Apply', command=self.exit)
        b2.pack(side='left')
        b3 = Tkinter.Button(self.fbuttons, text='Revert', command=self.reset)
        b3.pack(side='left')

        self.setgui()
        # Position dialog popup
        if dialog_parent is not None:
            parent_geom = dialog_parent.geometry()
            geom = string.split(parent_geom, '+')
            d1 = string.atoi(geom[1])
            d2 = string.atoi(geom[2])
            self.dialog.activate(geometry="+%d+%d" % (d1, d2))
        else:
            self.dialog.activate(geometry='centerscreenalways')

        return