コード例 #1
0
 def TwikiTableLine(self, lumi):
     tableString = '|' + string.ljust(str(self.coupling),
                                      9) + '|' + string.ljust(
                                          str(int(self.mass)), 6) + '|'
     tableString += string.ljust(self.channel, 6) + '|'
     if not self.optMassWindowLow is None:
         tableString += str(int(self.optMassWindowLow)) + ' to ' + str(
             int(self.optMassWindowHigh))
     else:
         tableString += str(
             int(self.mass - 3 * self.halfWidth)) + ' to ' + str(
                 int(self.mass + 3 * self.halfWidth))
     tableString += '|' + string.ljust('%0.3f' % self.totalEff, 8) + '|'
     expectedSignalEvents = lumi * self.totalXSec * self.totalEff
     tableString += string.center(str(round(expectedSignalEvents, 2)),
                                  9) + '|'
     if (self.nBackground < 1):
         backExpString = '%s' % float(
             '%.2g' % self.nBackground) + '+/-' + '%s' % float(
                 '%.2g' %
                 self.nBackgroundErrStat) + ' (stat) +/-' + '%s' % float(
                     '%.2g' % self.nBackgroundErrSyst) + ' (syst)'
     else:
         backExpString = '%0.2f' % self.nBackground + '+/-' + '%0.2f' % self.nBackgroundErrStat + ' (stat) +/-' + '%0.2f' % self.nBackgroundErrSyst + ' (syst)'
     tableString += string.center(backExpString, 18) + '|' + string.center(
         str(self.nDataObs), 10) + '|'
     try:
         tableString += string.center(str(round(self.expLimit, 6)),
                                      10) + '|'
         tableString += string.center(str(round(self.obsLimit, 6)),
                                      12) + '|'
     except TypeError:
         pass
     return tableString
コード例 #2
0
ファイル: lcdclock.py プロジェクト: pmiguelr/piClock
def mainClock():
    # global weatherRefreshInterval
    global timeSinceRefresh
    while True:
        if hourFormat12H == True:
            lcd.lcd_display_string(
                string.center(time.strftime("%I:%M %p"), 20),
                1)  #Outputs time in 12H Minutes AM or PM Format
        elif hourFormat12H == False:
            lcd.lcd_display_string(string.center(time.strftime("%H:%M"), 20),
                                   1)  #Outputs time in 24H Minutes Format

        lcd.lcd_display_string(
            string.center(time.strftime("%a %b %d"), 20),
            2)  #Outputs the date in DayName MonthName DayNumber

        CurrentPlayingSong()

        time.sleep(refreshInterval)
        if weatherRefreshInterval == timeSinceRefresh:
            # WeatherResponse = getWeather()
            lcd.lcd_display_string(string.center(getWeather(), 20), 4)
            timeSinceRefresh = 0
        else:
            timeSinceRefresh += 1
コード例 #3
0
 def StringTableLine(self, lumi):
     tableString = string.ljust(str(self.coupling), 6) + string.ljust(
         str(int(self.mass)), 6)
     tableString += string.ljust(self.channel, 10)
     massWindowString = str(int(self.optMassWindowLow)) + '-' + str(
         int(self.optMassWindowHigh))
     tableString += string.ljust(massWindowString, 11)
     tableString += string.ljust('%0.3f' % self.totalEff, 8)
     expectedSignalEvents = lumi * self.totalXSec * self.totalEff
     tableString += string.ljust(str(round(expectedSignalEvents, 3)), 10)
     #backExpString = '%0.4f'%self.nBackground+'+/-'+'%0.4f'%self.nBackgroundErr
     #backExpString = str(self.nBackground)+'+/-'+str(self.nBackgroundErr)
     if (self.nBackground < 1):
         backExpString = '%s' % float(
             '%.2g' % self.nBackground) + '+/-' + '%s' % float(
                 '%.2g' %
                 self.nBackgroundErrStat) + ' (stat) +/-' + '%s' % float(
                     '%.2g' % self.nBackgroundErrSyst) + ' (syst)'
     else:
         backExpString = '%0.2f' % self.nBackground + '+/-' + '%0.2f' % self.nBackgroundErrStat + ' (stat) +/-' + '%0.2f' % self.nBackgroundErrSyst + ' (syst)'
     tableString += string.ljust(backExpString, 41) + string.center(
         str(self.nDataObs), 10)
     tableString += string.center('%.1E' % float(self.totalXSec), 10)
     try:
         tableString += string.center(str(round(self.expLimit, 6)), 10)
         tableString += string.center(str(round(self.obsLimit, 6)), 12)
     except TypeError:
         pass
     return tableString
コード例 #4
0
def get_playerOrder(players, playerOrder_val):
    playerOrder = [0, 0, 0]
    print "We will now play the Toss-Up Spin for possession of The Wheel in the first"
    print "round."
    print string.center(("-" * 80), 80)
    raw_input ("Press 'ENTER' to continue: ")
    for i in (0, 1, 2):
        if i == 0:
            print players[i] + " will spin first."
        print "Get ready! " + players[i] + " is up next."
        print "It is " + players[i] + "'s turn to spin."
##        print string.center(("-" * 80), 80)
        raw_input("Press 'ENTER' to spin The Wheel. ")
        print string.center(("-" * 80), 80)
        print string.center((players[i] + " received $" + str(i * 100) + "."), 80)
        print string.center(("-" * 80), 80)
        for j in (0, 1):
            if j == 0:
                playerOrder_val[i][j] = (i * 100)
            else:
                playerOrder_val[i][j] = players[i]
    playerOrder_val.sort(reverse=True)
    for i in range(3):
        playerOrder[i] = playerOrder_val[i][1]
    print "Congratulations,", playerOrder[0] + "! You have won the Toss-Up Spin and will take possession"
    print "of The Wheel at the beginning of the first round."
    print ""
    print playerOrder[1] + " will Take possession of The Wheel after", playerOrder[0] + ", followed by", playerOrder[2] + "."
    print string.center(("-" * 80), 80)
    raw_input ("Press 'ENTER' to continue: ")
    return playerOrder
コード例 #5
0
ファイル: cconvert.py プロジェクト: 3c7/seahub
	def convert1(self, strIn):
		"Convert Unicode strIn to PinYin"
		length, strOutKey, strOutValue, i=len(strIn), "", "", 0
		while i<length:
			code1 =ord(strIn[i:i+1])
			if code1>=0x4e02 and code1<=0xe863:
				strTemp   = self.getIndex(strIn[i:i+1])
				if not self.has_shengdiao:
					strTemp  = strTemp[:-1]
				strLength = len(strTemp)
				if strLength<1:strLength=1
				strOutKey   += string.center(strIn[i:i+1], strLength)+" "
				strOutValue += self.spliter + string.center(strTemp, strLength) + self.spliter
			else:#ascii code;
				strOutKey+=strIn[i:i+1]+" "
				strOutValue+=strIn[i:i+1] + ' '
			i+=1
			#############################
			#txlist = utf8String.split()
			#out=convert.convert(utf8String)
			#l=[]
			#for t in map(convert.convert, txlist):
			#	l.append(t[0])
			#v = '-'.join(l).replace(' ','').replace(u'--','-').strip('-')
			#############################
		return [strOutValue, strOutKey]
コード例 #6
0
ファイル: _io.py プロジェクト: alphaomega-technology/ADTM
 def writerow(self, row, sep=None, *args, **kwargs):
     """
     Write General Data row to file
     """
     if not self.has_header:  # Write basic header for raw data
         self.file.write(self.encode.write_header() + '\n')
         self.has_header = True
     if sep is None:
         sep = self.default_sep
     if sep not in [',', ';', '|', ':']:
         raise AdtmError('Invalid Row Value Seperator ("{0:s}") provided, '
                         'must be ( "," | ";" | "|" | ":" )'.format(sep))
     self.offset += 1
     if self.offset - self.last_headerrow == 5*5:
         self.file.write("#" + sep.join((string.center(h, w) for h, w in
                                         izip_longest(self.headers,
                                                      self.col_width,
                                                      fillvalue=0)))[1:]
                         + "\n")
         self.last_headerrow = self.offset
         self.last_seprow = self.offset
         self.offset += 1
     elif self.offset - self.last_seprow == 5:
         self.file.write("#" + sep.join((string.center(" ", w) for w in
                                         self.col_width))[1:]
                         + "\n")
         self.last_seprow = self.offset
         self.offset += 1
     self.file.write(sep.join((string.center(self.encode(i), w) for i, w in
                               izip_longest(row,
                                            self.col_width,
                                            fillvalue=0)))
                     + "\n")
コード例 #7
0
ファイル: bench_xml.py プロジェクト: pombredanne/itools
def output_result(results, file):
    # file output
    filename, file_size = file
    filename = ljust(filename[:19], 19)
    file_size = get_string_size(file_size)
    file_size = rjust(file_size[:9], 9)
    file_string = u'%s  %s' % (filename, file_size)

    parser_output = u''
    # output 1
    parser_name, result = results[0]
    if result is None:
        output1 = center(u'FAILED',  21)
    else:
        time_spent, memory = result
        memory = get_string_size(memory)
        # time_spent ok already like ___.___ ms or s or mn
        output1 = rjust(u'%s / %s' % (time_spent, memory), 21)

    # output 2
    parser_name, result = results[1]
    if result is None:
        output2 = center(u'FAILED',  21)
    else:
        time_spent, memory = result
        memory = get_string_size(memory)
        # time_spent ok already like ___.___ ms or s or mn
        output2 = rjust(u'%s / %s' % (time_spent, memory), 21)

    print '%s | %s | %s ' % (file_string, output1, output2)
コード例 #8
0
ファイル: scythe.py プロジェクト: marcwickenden/Scythe
def output_success():
    # print information about success matches

    if opts.summary or opts.verbose:
        print "\n ------------------------------------------------------------------------------"
        print string.center(">>>>> Successful matches <<<<<", 80)
        print " ------------------------------------------------------------------------------"
        s_success = sorted(success, key=lambda k: k['name']) # group by site name
        # print normal summary table on request (--summary)
        if not opts.verbose and opts.summary:
            print "\n ------------------------------------------------------------------------------"
            print " ", "| Module |".ljust(35), "| Account |".ljust(28)
            print " ------------------------------------------------------------------------------"
            for s in s_success:
                print "  " + s['name'].ljust(37) + s['account'].ljust(30)
            print " ------------------------------------------------------------------------------\n"
        # print verbose summary on request (-v --summary)
        elif opts.verbose and opts.summary:
            for s in s_success:
                print textwrap.fill((" NAME: \t\t\t%s" % s['name']),
                    initial_indent='', subsequent_indent='\t -> ', width=80)
                print textwrap.fill((" ACCOUNT: \t\t%s" % s['account']),
                    initial_indent='', subsequent_indent='\t -> ', width=80)
                print textwrap.fill((" URL: \t\t\t%s" % s['url']),
                    initial_indent='', subsequent_indent='\t -> ', width=80)
                print textwrap.fill((" METHOD: \t\t%s" % s['method']),
                    initial_indent='', subsequent_indent='\t -> ', width=80)
                print textwrap.fill((" POST PARAMETERS: \t%s" % s['postParameters']),
                    initial_indent='', subsequent_indent='\t -> ', width=80)
                print " ------------------------------------------------------------------------------"
    else:
        print " ------------------------------------------------------------------------------\n"
コード例 #9
0
 def convert1(self, strIn):
     "Convert Unicode strIn to PinYin"
     length, strOutKey, strOutValue, i = len(strIn), "", "", 0
     while i < length:
         code1 = ord(strIn[i:i + 1])
         if code1 >= 0x4e02 and code1 <= 0xe863:
             strTemp = self.getIndex(strIn[i:i + 1])
             if not self.has_shengdiao:
                 strTemp = strTemp[:-1]
             strLength = len(strTemp)
             if strLength < 1: strLength = 1
             strOutKey += string.center(strIn[i:i + 1], strLength) + " "
             strOutValue += self.spliter + string.center(
                 strTemp, strLength) + self.spliter
         else:  #ascii code;
             strOutKey += strIn[i:i + 1] + " "
             strOutValue += strIn[i:i + 1] + ' '
         i += 1
         #############################
         #txlist = utf8String.split()
         #out=convert.convert(utf8String)
         #l=[]
         #for t in map(convert.convert, txlist):
         #	l.append(t[0])
         #v = '-'.join(l).replace(' ','').replace(u'--','-').strip('-')
         #############################
     return [strOutValue, strOutKey]
コード例 #10
0
ファイル: MOPplot.py プロジェクト: OSSOS/MOP
def load_edbfile(file=None):
    """Load the targets from a file"""
    import ephem,string,math
    if file is None:
        import tkFileDialog
	try:
            file=tkFileDialog.askopenfilename()
        except:
            return 
    if file is None or file == '':
        return
    f=open(file)
    lines=f.readlines()
    f.close()
    for line in lines:
        p=line.split(',')
	name=p[0].strip().upper()
	mpc_objs[name]=ephem.readdb(line)
	mpc_objs[name].compute()
        objInfoDict[name]="%6s %6s %6s\n" % ( string.center("a",6),
				            string.center("e",6),
	 				    string.center("i",6) ) 
        objInfoDict[name]+="%6.2f %6.3f %6.2f\n" % (mpc_objs[name]._a,mpc_objs[name]._e,math.degrees(mpc_objs[name]._inc))
        objInfoDict[name]+="%7.2f %7.2f\n" % ( mpc_objs[name].earth_distance, mpc_objs[name].mag)
    doplot(mpc_objs)
コード例 #11
0
def get_playerOrder(players, playerOrder_val):
    playerOrder = [0, 0, 0]
    print "We will now play the Toss-Up Spin for possession of The Wheel in the first"
    print "round."
    print string.center(("-" * 80), 80)
    raw_input("Press 'ENTER' to continue: ")
    for i in (0, 1, 2):
        if i == 0:
            print players[i] + " will spin first."
        print "Get ready! " + players[i] + " is up next."
        print "It is " + players[i] + "'s turn to spin."
        ##        print string.center(("-" * 80), 80)
        raw_input("Press 'ENTER' to spin The Wheel. ")
        print string.center(("-" * 80), 80)
        print string.center((players[i] + " received $" + str(i * 100) + "."),
                            80)
        print string.center(("-" * 80), 80)
        for j in (0, 1):
            if j == 0:
                playerOrder_val[i][j] = (i * 100)
            else:
                playerOrder_val[i][j] = players[i]
    playerOrder_val.sort(reverse=True)
    for i in range(3):
        playerOrder[i] = playerOrder_val[i][1]
    print "Congratulations,", playerOrder[
        0] + "! You have won the Toss-Up Spin and will take possession"
    print "of The Wheel at the beginning of the first round."
    print ""
    print playerOrder[
        1] + " will Take possession of The Wheel after", playerOrder[
            0] + ", followed by", playerOrder[2] + "."
    print string.center(("-" * 80), 80)
    raw_input("Press 'ENTER' to continue: ")
    return playerOrder
コード例 #12
0
def get_playerOrder(players, playerOrder_val):
    playerOrder = []
    print "We will now play the Toss-Up Puzzle for possession of The Wheel in the first"
    print "round."
    print ""
    print players[0] + " will spin first."
    print ""
    print string.center(("-" * 80), 80)
    raw_input("Press 'ENTER' to continue: ")
    for i in (0, 1, 2):
        print ""
        print players[i] + ", get ready. You're up next!"
        print players[i] + " prepares to spin The Wheel."
        print ""
        raw_input("Press 'ENTER' to spin The Wheel. ")
        print ""
        prize = prize = get_prize(0)
        print string.center(("-" * 80), 80)
        print string.center((players[i] + " received $" + str(prize) + "."),
                            80)
        print string.center(("-" * 80), 80)
        for j in (0, 1):
            if j == 0:
                playerOrder_val[i][j] = prize
            else:
                playerOrder_val[i][j] = players[i]
    playerOrder_val.sort(reverse=True)
    for i in range(3):
        if i == 0:
            playerOrder.insert(0, playerOrder_val[i][1])
        else:
            if i == 1:
                if playerOrder_val[i][0] > playerOrder_val[0][0]:
                    playerOrder.insert(0, playerOrder_val[i][1])
                else:
                    playerOrder.insert(1, playerOrder_val[i][1])
            else:
                if playerOrder_val[i][0] > playerOrder_val[0][
                        0] and playerOrder_val[1][0]:
                    playerOrder.insert(0, playerOrder_val[i][1])
                elif playerOrder_val[i][0] < playerOrder_val[0][
                        0] and playerOrder_val[1][0]:
                    playerOrder.insert(2, playerOrder_val[i][1])
                else:
                    playerOrder.insert(1, playerOrder_val[i][1])
    print ""
    print "Congratulations,", playerOrder[
        0] + "! You have won the Toss-Up Spin and will take possession"
    print "of The Wheel at the beginning of the first round."
    print ""
    print playerOrder[
        1] + " will Take possession of The Wheel after", playerOrder[
            0] + ", followed by", playerOrder[2] + "."
    print ""
    print string.center(("-" * 80), 80)
    raw_input("Press 'ENTER' to begin the first round: ")
    print ""

    return playerOrder
コード例 #13
0
ファイル: mcvQC.py プロジェクト: mgijax/mcvload
def createSecMarkerReport ():
    global annot, nonfatalCount, nonfatalReportNames

    print 'Create the secondary marker report'
    sys.stdout.flush()
    fpSecMrkRpt.write(string.center('Secondary Marker Report',130) + NL)
    fpSecMrkRpt.write(string.center('(' + timestamp + ')',130) + 2*NL)
    fpSecMrkRpt.write('%-20s  %-16s  %-50s  %-16s%s' %
                     ('Term ID', 'Secondary MGI ID',
                      'Marker Symbol','Primary MGI ID',NL))
    fpSecMrkRpt.write(20*'-' + '  ' + 16*'-' + '  ' + \
                      50*'-' + '  ' + 16*'-' + NL)

    cmds = []

    #
    # Find any MGI IDs from the input data that are secondary IDs
    # for a marker.
    #
    cmds.append('''
    	select tmp.termID, 
               tmp.mgiID, 
               m.symbol, 
               a2.accID 
        from %s tmp, 
                     ACC_Accession a1, 
                     ACC_Accession a2, 
                     MRK_Marker m 
        where tmp.mgiID is not null and 
                      lower(tmp.mgiID) = lower(a1.accID) and 
                      a1._MGIType_key = 2 and 
                      a1._LogicalDB_key = 1 and 
                      a1.preferred = 0 and 
                      a1._Object_key = a2._Object_key and 
                      a2._MGIType_key = 2 and 
                      a2._LogicalDB_key = 1 and 
                      a2.preferred = 1 and 
                      a2._Object_key = m._Marker_key 
        order by lower(tmp.mgiID), lower(tmp.termID)
	''' % (tempTable))

    results = db.sql(cmds,'auto')

    #
    # Write the records to the report.
    #
    for r in results[0]:
        termID = r['termID']
        mgiID = r['mgiID']

        fpSecMrkRpt.write('%-20s  %-16s  %-50s  %-16s%s' %
            (termID, mgiID, r['symbol'], r['accID'], NL))

    numErrors = len(results[0])
    fpSecMrkRpt.write(NL + 'Number of Rows: ' + str(numErrors) + NL)
    if numErrors > 0:
        if not secMrkRptFile in nonfatalReportNames:
            nonfatalReportNames.append(secMrkRptFile + NL)
    nonfatalCount += numErrors
コード例 #14
0
ファイル: instruments.py プロジェクト: jordanrossdunn/pierrot
def print_instruments():
	"""Prints a display of all instruments by category and family"""

	for title, category in instruments.iteritems():
		print "\n" + string.center(" " + title + " ", 50, "~")
		for name, family in category.iteritems():
			print "\n" + string.center(" " + name + " ", 50, "-") + "\n"
			print_instrument_family(family)
コード例 #15
0
def test4():
    print r'/n', u'abc', ur'Hello\nWorld!'
    s, t, g = 'fofff1', 'obr2', 'lilang'
    nex = zip(s, t, g)
    print nex
    print string.capitalize(s)
    print string.center(s, 10), string.count(s, 'f'), s.find('f', 5,
                                                             5), s.isalnum()
コード例 #16
0
def lose_a_turn(player_turn, playerOrder):
    
    print ""
    print playerOrder[player_turn], "spun for LOSE A TURN!"
    print ""
    print "Sorry, " + playerOrder[player_turn] + ". Possession of The Wheel passes to " + playerOrder[(player_turn + 1) % 3] + "."
    print string.center(("-" * 80), 80)
    time.sleep(2.5)
コード例 #17
0
 def title(self,title):
     _l = len(title)
     _p = max(_l%2 +_l,40)
     _x = self.parlen -_p
     if (_x > 2):
         print (_x/2)*self.sep + string.center(title,_p) + (_x/2)*self.sep
     else:
         print string.center(text,self.parlen)
コード例 #18
0
ファイル: py2048.py プロジェクト: rgnote/Py2048
 def printGrid(self):
     system("clear")
     print "_" * self.rowsize
     for i in range(self.size):
         print "|",
         for j in range(self.size):
             print center(str(self.grid[i][j]), self.cellwidth) + "|",
         print "\n" + "_" * self.rowsize
     print "Score: ", self.score
コード例 #19
0
def guess_previously_called(player_turn, playerOrder, guess):
    print ""
    print "Sorry, '" + guess + "' has already been called in this round."
    print playerOrder[(player_turn + 1) % 3] + " now takes possession of The Wheel."
    print ""
    print string.center(("-" * 80), 80)
    time.sleep(1.5)

    return playerOrder
コード例 #20
0
ファイル: py2048.py プロジェクト: rakeshgariganti/Py2048
	def printGrid(self):
		system("clear")
		print "_"*self.rowsize
		for i in range(self.size):
			print "|",
			for j in range(self.size):
				print center(str(self.grid[i][j]),self.cellwidth)+"|",
			print "\n"+"_"*self.rowsize
		print "Score: ",self.score
コード例 #21
0
ファイル: StoreCredit.py プロジェクト: repstd/algorithm
def slove(C,I,P,N):
	fout=open("fout.out","w")
	for i in range(N):
		for j in range(I[i]-1):
			for k in range(j+1,I[i]):
				if P[i][j]+P[i][k]==C[i]:
					# print P[i][j],P[i][k],C[i]
					fout.write(str("Case #"+str(i+1)+":"+string.center(str(j+1),3)+" "+string.center(str(k+1),2)+"\r"))
					continue
コード例 #22
0
def draw_grid(
    screen, questions,
    selected_question, answered_questions,
    player_scores ):
    height, width = screen.getmaxyx()

    columns = len(questions)
    rows = len(questions[0]["questions"])

    # take the total screen width, subtract the border zone,
    # and allow INNER_GRID_BORDER space between each column
    category_width = ( width-GRID_HORIZ_BORDER*2-
                       (columns-1)*INNER_GRID_BORDER ) // columns

    question_grid_start = GRID_VERT_OFFSET + SPACE_FROM_CATEGORY_TO_LEVELS

    for i, category in enumerate(questions):
        category_name = (category["name"]
                         if len(category["name"]) <= category_width
                         else category["abrev_name"][:category_width]
                         )[:category_width]

        horizontal_position = (
            GRID_HORIZ_BORDER + i*category_width +
            i*INNER_GRID_BORDER
            )

        screen.addstr(
            GRID_VERT_OFFSET,
            horizontal_position,
            center(category_name, category_width, " "),
            CURSES_COLOUR_PAIR_GOOD_FEEL
            )

        for j, score in enumerate(POINTS):
            cur_color = CURSES_COLOUR_PAIR_GOOD_FEEL
            if (i, score) == tuple(selected_question):
                if (i, score) in answered_questions:
                    cur_color = CURSES_COLOUR_PAIR_MEH
                else:
                    cur_color = CURSES_COLOUR_PAIR_REALLY_GOOD
            elif (i, score) in answered_questions:
                cur_color = CURSES_COLOUR_PAIR_BAD_FEEL

            screen.addstr(
                question_grid_start + j+j*VERT_INNER_GRID_BORDER,
                horizontal_position,
                center(str(score), category_width, " "),
                cur_color )
    
    player_scores_str = PLAYER_SEP_CHARS.join(player_scores)
    player_scores_str = \
        player_scores_str[:(width-GRID_PLAYER_SCORES_HORIZ_OFFSET)]
    screen.addstr(height-2, GRID_PLAYER_SCORES_HORIZ_OFFSET,
                  player_scores_str,
                  CURSES_COLOUR_PAIR_MAX_CONTRAST )
コード例 #23
0
ファイル: mrkcoordQC.py プロジェクト: mgijax/mrkcoordload
def writeInvcoordStrandHeader():
    print 'Create the invalid coordinate and strand report'
    fpInvCoordStrandRpt.write(string.center('Invalid Coordinate and Strand Report',110) + NL)
    fpInvCoordStrandRpt.write(string.center('(' + timestamp + ')',110) + 2*NL)
    fpInvCoordStrandRpt.write('%-12s  %-20s  %-20s  %-10s  %-20s  %-30s%s' %
                     ('MGI ID','Start Coordinate','End Coordinate', 'Strand',
                      'Provider','Reason',NL))
    fpInvCoordStrandRpt.write(12*'-' + '  ' + 20*'-' + '  ' + 20*'-' + '  ' + \
                      10*'-' + '  ' + 20*'-' + '  ' + 30*'-' + NL)
    return
コード例 #24
0
ファイル: scythe.py プロジェクト: marcwickenden/Scythe
def output_accounts():
    # print information about the accounts loaded from accountfile

    print "\n ------------------------------------------------------------------------------"
    print string.center(">>>>> Accounts Loaded <<<<<", 80)
    print " ------------------------------------------------------------------------------"
    for a in accounts:
        print textwrap.fill((" Account name: %s" % a),
            initial_indent='', subsequent_indent=' -> ', width=80)
    print " ------------------------------------------------------------------------------\n"
コード例 #25
0
def lose_a_turn(player_turn, playerOrder):

    print ""
    print playerOrder[player_turn], "spun for LOSE A TURN!"
    print ""
    print "Sorry, " + playerOrder[
        player_turn] + ". Possession of The Wheel passes to " + playerOrder[
            (player_turn + 1) % 3] + "."
    print string.center(("-" * 80), 80)
    time.sleep(2.5)
コード例 #26
0
def guess_previously_called(player_turn, playerOrder, guess):
    print ""
    print "Sorry, '" + guess + "' has already been called in this round."
    print playerOrder[(player_turn + 1) %
                      3] + " now takes possession of The Wheel."
    print ""
    print string.center(("-" * 80), 80)
    time.sleep(1.5)

    return playerOrder
コード例 #27
0
ファイル: test_center.py プロジェクト: veronikam/aspp_d1
	def test_TypeError(self):
		#Given
		s = 'abc'
		width = 7
		list_fillchar = ['', 'ab']
		
		for fillch in list_fillchar:
			#Then
			with  self.assertRaises(TypeError):
				#When
				string.center(s, width, fillch)
コード例 #28
0
ファイル: Commuter.py プロジェクト: asottile/ancient-pythons
 def show(self):  # proc
    if self.name: print lj(self.name, 12),
    else: print center('-', 12),
    if self.surname: print lj(self.surname, 12),
    else: print center('-', 12),
    if self.job: print lj(self.job, 12),
    else: print center('-', 12),
    if self.dest: print lj(self.dest, 12),
    else: print center('-', 12),
    if self.sport: print lj(self.sport, 12)
    else: print center('-', 12)
コード例 #29
0
ファイル: Commuter.py プロジェクト: 8Banana/py1.0
 def show(self):  # proc
     if self.name: print lj(self.name, 12),
     else: print center('-', 12),
     if self.surname: print lj(self.surname, 12),
     else: print center('-', 12),
     if self.job: print lj(self.job, 12),
     else: print center('-', 12),
     if self.dest: print lj(self.dest, 12),
     else: print center('-', 12),
     if self.sport: print lj(self.sport, 12)
     else: print center('-', 12)
コード例 #30
0
def bankrupt(player_turn, playerOrder, playerOrder_val_round):

    print ""
    print playerOrder[player_turn], "spun for BANKRUPT, bringing his total prize for this round to $0."
    playerOrder_val_round[player_turn][0] = 0
    print "Possession of The Wheel passes to", playerOrder[((player_turn + 1) % 3)] + "."
    print ""
    print string.center(("-" * 80), 80)
    time.sleep(2.5)

    return playerOrder_val_round
コード例 #31
0
def get_playerOrder(players, playerOrder_val):
    playerOrder = []
    print "We will now play the Toss-Up Puzzle for possession of The Wheel in the first"
    print "round."
    print ""
    print players[0] + " will spin first."
    print ""
    print string.center(("-" * 80), 80)
    raw_input ("Press 'ENTER' to continue: ")
    for i in (0, 1, 2):
        print ""
        print players[i] + ", get ready. You're up next!"
        print players[i] + " prepares to spin The Wheel."
        print ""
        raw_input("Press 'ENTER' to spin The Wheel. ")
        print ""
        prize = prize = get_prize(0)
        print string.center(("-" * 80), 80)
        print string.center((players[i] + " received $" + str(prize) + "."), 80)
        print string.center(("-" * 80), 80)
        for j in (0, 1):
            if j == 0:
                playerOrder_val[i][j] = prize
            else:
                playerOrder_val[i][j] = players[i]
    playerOrder_val.sort(reverse=True)
    for i in range(3):
        if i == 0:
            playerOrder.insert(0, playerOrder_val[i][1])
        else:
            if i == 1:
                if playerOrder_val[i][0] > playerOrder_val[0][0]:
                    playerOrder.insert(0, playerOrder_val[i][1])
                else:
                    playerOrder.insert(1, playerOrder_val[i][1])
            else:
                if playerOrder_val[i][0] > playerOrder_val[0][0] and playerOrder_val[1][0]:
                    playerOrder.insert(0, playerOrder_val[i][1])
                elif playerOrder_val[i][0] < playerOrder_val[0][0] and playerOrder_val[1][0]:
                    playerOrder.insert(2, playerOrder_val[i][1])
                else:
                    playerOrder.insert(1, playerOrder_val[i][1])
    print ""
    print "Congratulations,", playerOrder[0] + "! You have won the Toss-Up Spin and will take possession"
    print "of The Wheel at the beginning of the first round."
    print ""
    print playerOrder[1] + " will Take possession of The Wheel after", playerOrder[0] + ", followed by", playerOrder[2] + "."
    print ""
    print string.center(("-" * 80), 80)
    raw_input ("Press 'ENTER' to begin the first round: ")
    print ""         
    
    return playerOrder
コード例 #32
0
def bankrupt(player_turn, playerOrder, playerOrder_val_round):

    print ""
    print playerOrder[
        player_turn], "spun for BANKRUPT, bringing his total prize for this round to $0."
    playerOrder_val_round[player_turn][0] = 0
    print "Possession of The Wheel passes to", playerOrder[(
        (player_turn + 1) % 3)] + "."
    print string.center(("-" * 80), 80)
    time.sleep(2.5)

    return playerOrder_val_round
コード例 #33
0
 def AfficherJeu (self) :
   largeur_max = len(self.ReprDisque(self.hauteur)) + 2
   print (string.center("o", largeur_max)+" ")*3
   etages = range(1, self.hauteur+1)
   etages.reverse()
   for disque in etages :
     for tour in self.hanoi.tours :
       taille = tour.disque(disque)
       repr = self.ReprDisque(taille)
       print string.center(repr, largeur_max),
     print
   print ("~"*largeur_max+" ")*3
コード例 #34
0
def ckill():
    count = kill_count()

    if count is None:
        print >> sys.stderr, "Could not run ckill."
        sys.exit(3)

    # Only need to actually do the killing if the count was > 0
    if count > 0:
        total_count = count
        total_progress = 50
        progress = 0.

        lev = 'SIGINT'
        print "Killing %d processes now..." % (total_count)

        print string.center("PROGRESS", total_progress, "=")

        # Start by killing all roslaunch processes
        subprocess.call([
            'sudo', 'ckill', 'kill', '--sig', lev, '--regex',
            'python .*/roslaunch'
        ])

        for lev in ['SIGINT', 'SIGTERM', 'SIGKILL', 'SIGKILL']:
            start = time.time()
            while True:
                while float(total_count -
                            count) / total_count > progress / total_progress:
                    sys.stdout.write('#')
                    sys.stdout.flush()
                    progress += 1.

                if (count == 0):
                    break
                time.sleep(.1)
                last_count = count
                count = kill_count()
                if (count < last_count):
                    continue
                if (time.time() - start > 3):
                    subprocess.call(['sudo', 'ckill', 'kill', '--sig', lev])
                    break
        print ""
        if (count > 0):
            print "Some processes may have been left running:"
            for l in plist():
                print l
        else:
            print "All processes killed successfully."
    else:
        print "No processes to kill."
コード例 #35
0
ファイル: robot.py プロジェクト: archielee/pr2
def ckill():
    count = kill_count()

    if count is None:
        print >> sys.stderr, "Could not run ckill."
        sys.exit(3)

    # Only need to actually do the killing if the count was > 0
    if count > 0:
        total_count = count
        total_progress = 50
        progress = 0.

        lev='SIGINT'
        print "Killing %d processes now..."%(total_count)


        print string.center("PROGRESS",total_progress,"=")

        # Start by killing all roslaunch processes
        subprocess.call(['sudo', 'ckill', 'kill', '--sig', lev, '--regex', 'python .*/roslaunch'])

        for lev in ['SIGINT','SIGTERM','SIGKILL','SIGKILL']:
            start = time.time()
            while True:
                while float(total_count - count)/total_count > progress/total_progress:
                    sys.stdout.write('#')
                    sys.stdout.flush()
                    progress += 1.

                if (count == 0):
                    break
                time.sleep(.1)
                last_count = count
                count = kill_count()
                if (count < last_count):
                    continue
                if (time.time() - start > 3):
                    subprocess.call(['sudo', 'ckill', 'kill', '--sig', lev])
                    break
        print ""
        if (count > 0):
            print "Some processes may have been left running:"
            for l in plist():
                print l
        else:
            if os.path.exists(PID_FILE):
                try:
                    os.remove(PID_FILE)
                except OSError, e:
                    print "%s still remains, but could not be removed.: (%d) %s" % (PID_FILE, e.errno, e.strerror)
            print "All processes killed successfully."
コード例 #36
0
    def saveSelectedMarkers(self, filename=None):
        if self.selectedPolygon == "":
            self.statusMessage("no polygon selected")
            return

        if filename == None:
            filename = asksaveasfilename(title="Save points into a doc file")
            if len(filename) == 0:
                return
        print filename
        if type(filename) == type((1, 2)):
            print 'filename is a tuple!'

        poly = self.Polygons[self.selectedPolygon]
        e = poly.elements
        e.sort()

        E = []
        # make header for doc file and column headings
        E.append(Spiderutils.makeDocfileHeader(filename))
        xaxis = self.xaxisVar.get()
        if xaxis == "": xaxis = 'x axis'
        if len(xaxis) > 11:
            xaxis = xaxis[:11]  # just use first 11 chars
        else:
            xaxis = string.center(xaxis, 11)

        yaxis = self.yaxisVar.get()
        if yaxis == "": yaxis = 'y axis'
        if len(yaxis) > 11:
            yaxis = yaxis[:11]  # just use first 11 chars
        else:
            yaxis = string.center(yaxis, 11)
        keyhdr = string.center('keys', 11)
        E.append(" ; /        %s %s %s\n" % (keyhdr, xaxis, yaxis))

        n = len(e)
        for i in range(n):
            key = i + 1
            val = e[i]
            x, y = self.D[val][0], self.D[val][1]
            line = "%5d %2d %11.1f %11f %11f\n" % (key, 3, float(e[i]), x, y)
            E.append(line)

        try:
            fp = open(filename, 'w')
            fp.writelines(E)
            fp.close()
            self.statusMessage('Data written to %s' % filename)
        except:
            self.statusMessage('ERROR: unable to write to %s' % filename,
                               timeout=0)
コード例 #37
0
ファイル: PlotResults.py プロジェクト: jturkewitz/UserCode
 def StringTableLine(self):
   tableString = string.ljust(self.name,19)+string.ljust(self.ptCut,6)+string.ljust(self.iasCut,6)
   tableString+=string.center(str(self.massCut),8)+string.center(str(round(self.sigEff,4)),10)
   backExpString = str(round(self.expBg,4))+' +/- '+str(round(self.expBgStatErr,4))
   tableString+=string.center(backExpString,22)+string.center(str(self.obsEvts),10)
   tableString+=string.center(str(round(float(self.thCrossSection),6)),10)+string.center(str(round(self.expLimit,6)),10)
   tableString+=string.center(str(round(self.obsLimit,6)),10)+string.center(str(round(self.fiveSigmaXSec,6)),12)
   tableString+=string.center(str(round(self.obsSignalSignif,6)),10)
   return tableString
コード例 #38
0
ファイル: robot.py プロジェクト: imclab/PR2-usr-lib-robot
def ckill():
    count = kill_count()

    if count is None:
        print >> sys.stderr, "Could not run ckill."
        sys.exit(3)

    # Only need to actually do the killing if the count was > 0
    if count > 0:
        print "Tilting the head back in preparation for shutdown."
        subprocess.call(["/usr/lib/robot/look_up.sh"])

        total_count = count
        total_progress = 50
        progress = 0.

        lev='SIGINT'
        print "Killing %d processes now..."%(total_count)


        print string.center("PROGRESS",total_progress,"=")

        # Start by killing all roslaunch processes
        subprocess.call(['sudo', 'ckill', 'kill', '--sig', lev, '--regex', 'python .*/roslaunch'])

        for lev in ['SIGINT','SIGTERM','SIGKILL','SIGKILL']:
            start = time.time()
            while True:
                while float(total_count - count)/total_count > progress/total_progress:
                    sys.stdout.write('#')
                    sys.stdout.flush()
                    progress += 1.

                if (count == 0):
                    break
                time.sleep(.1)
                last_count = count
                count = kill_count()
                if (count < last_count):
                    continue
                if (time.time() - start > 3):
                    subprocess.call(['sudo', 'ckill', 'kill', '--sig', lev])
                    break
        print ""
        if (count > 0):
            print "Some processes may have been left running:"
            for l in plist():
                print l
        else:
            print "All processes killed successfully."
    else:
        print "No processes to kill."
コード例 #39
0
ファイル: mrkcoordQC.py プロジェクト: mgijax/mrkcoordload
def createChrDiscrepReport ():
    global errorCount, errorReportNames, invChrList

    print 'Create the chromosome discrepancy report'
    fpChrDiscrepRpt.write(string.center('Chromosome Discrepancy Report',96) + NL)
    fpChrDiscrepRpt.write(string.center('(' + timestamp + ')',96) + 2*NL)
    fpChrDiscrepRpt.write('%-20s  %-50s  %-10s  %-10s%s' %
                         ('MGI ID', 'Marker Symbol', 'Marker Chr','Feature Chr',NL))
    fpChrDiscrepRpt.write(20*'-' + '  ' + 50*'-' + '  ' +
                          10*'-' + '  ' + 10*'-' + NL)

    #
    # Find any cases where the marker in the coordinate file has
    # a different chromosome than the feature in the coordinate file
    #
    
    # exclude invalid chromosomes
    ic = string.join(invChrList, ',')
    results = db.sql('''select tc.mgiID, 
                       tc.chromosome as fChr, 
                       m.symbol, 
                       m.chromosome as mChr
                from %s tc, 
                     ACC_Accession a, 
                     MRK_Marker m 
                where tc.chromosome not in (%s)
		and tc.mgiID = a.accID 
		and a._MGIType_key = 2 
                and a._LogicalDB_key = 1 
                and a.preferred = 1 
                and a._Object_key = m._Marker_key 
                and m.chromosome != tc.chromosome 
                order by mgiID''' % (coordTempTable, ic), 'auto')


    #
    # Write the records to the report.
    #
    for r in results:
        mgiID = r['mgiID']

        fpChrDiscrepRpt.write('%-20s  %-50s  %-10s  %-10s%s' %
            (mgiID, r['symbol'], r['mChr'], r['fChr'], NL))

    numErrors = len(results)
    fpChrDiscrepRpt.write(NL + 'Number of Rows: ' + str(numErrors) + NL)

    errorCount += numErrors
    if numErrors > 0:
	if not chrDiscrepRptFile in errorReportNames:
            errorReportNames.append(chrDiscrepRptFile + NL)
    return
コード例 #40
0
ファイル: lvs.py プロジェクト: lpther/LVS
    def __str__(self):
        # Get protocol name
        if self.protocol is socket.SOL_TCP:
            protocol_str = 'TCP'

        elif self.protocol is socket.SOL_UDP:
            protocol_str = 'UDP'

        else:
            protocol_str = str(self.protocol)

        # Get expiration format
        expire = '%3d:%2s' % (self.timeout / 60, str(self.timeout % 60).zfill(2))

        # Get s/v/d client:protocol pair
        caddr, vaddr , daddr = (self.caddr, self.vaddr, self.daddr)
        addrspacer = ''

        if self.name_resolution:
            addrspacer = ' '
            try:
                caddr = socket.gethostbyaddr(caddr)[0]

                if not LVSSYNC_FQDN_NR:
                    caddr = caddr.split('.')[0]
            except:
                pass

            try:
                vaddr = socket.gethostbyaddr(vaddr)[0]

                if not LVSSYNC_FQDN_NR:
                    vaddr = vaddr.split('.')[0]
            except:
                pass

            try:
                daddr = socket.gethostbyaddr(daddr)[0]

                if not LVSSYNC_FQDN_NR:
                    daddr = daddr.split('.')[0]
            except:
                pass

        source = '%s:%s' % (caddr, self.cport) + addrspacer
        virtual = '%s:%s' % (vaddr, self.vport) + addrspacer
        destination = '%s:%s' % (daddr, self.dport) + addrspacer

        return '%s%s%s%s%s%s%s' % (string.center(protocol_str, 4), string.center(expire, 7), \
                                                string.center(IP_VS_TCP_S_CONNECTION_STATES[self.state], 13), string.center(source, 22), \
                                                string.center(virtual, 22), string.center(destination, 22), ' '.join(self.decode_flags(self.flags)))
コード例 #41
0
ファイル: scythe.py プロジェクト: marcwickenden/Scythe
def make_requests(testcases):
    # make a requests present in testcases

    print "\n ------------------------------------------------------------------------------"
    print string.center(">>>>> Testcases <<<<<", 80)
    print " ------------------------------------------------------------------------------"
    print " [" + color['yellow'] + "-" + color['end'] \
        +"] Starting testcases (%d in total)\n" % len(testcases)
    progress = 0 # initiate progress count
    progress_last = 0

    for test in testcases:
        if len(testcases) > 50: # only show progress on tests of > 50
            if not progress == 0:
                progress_percentage = int(100 / (float(len(testcases)) / float(progress)))
                if progress_percentage - progress_last > 20: # only update percentage in 20% chunks
                    print " [" + color['yellow'] + "-" + color['end'] +"] [%s] %s%% complete\n" \
                        % ((color['yellow'] + ("#"*(progress_percentage / 10)) + \
                        color['end']).ljust(10, "."),progress_percentage),
                    progress_last = progress_percentage
        if test['method'] == 'GET':
            test, resp = get_request(test)
            if resp and test['successmatch']:
                matched = success_check(resp, test['successmatch'])
                if matched:
                    print " [" + color['green'] + "X" + color['end'] + "] Account %s exists on %s" \
                        % (test['account'], test['name'])
                    success.append(test)
            if resp and test['negativematch']:
                matched = negative_check(resp, test['negativematch'])
                if matched and opts.verbose:
                    print " [" + color['red'] + "X" + color['end'] + "] Negative matched %s on %s" \
                        % (test['account'], test['name'])
        elif test['method'] == 'POST':
            test, resp = post_request(test)
            if resp and test['successmatch']:
                matched = success_check(resp, test['successmatch'])
                if matched:
                    print " [" + color['green'] + "X" + color['end'] + "] Account %s exists on %s" \
                        % (test['account'], test['name'])
                    success.append(test)
            if resp and test['negativematch']:
                matched = negative_check(resp, test['negativematch'])
                if matched and opts.verbose:
                    print " [" + color['red'] + "X" + color['end'] + "] Negative matched %s on %s" \
                        % (test['account'], test['name'])
        else:
            print "[" + color['red'] + "!" + color['end'] + "] Unknown Method %s : %s" \
                % test['method'], test['url']

        progress = progress +1 # iterate progress value for the progress bar
コード例 #42
0
ファイル: scat.py プロジェクト: spider-em/SPIDER
    def saveSelectedMarkers(self, filename=None):
        if self.selectedPolygon == "":
            self.statusMessage("no polygon selected")
            return
            
        if filename == None:
            filename = asksaveasfilename(title="Save points into a doc file")
            if len(filename) == 0:
                return
        print filename
        if type(filename) == type( (1,2) ):
            print 'filename is a tuple!'
            
        poly = self.Polygons[self.selectedPolygon]
        e = poly.elements
        e.sort()

        E = []
        # make header for doc file and column headings
        E.append(spiderutils.makeDocfileHeader(filename))
        xaxis = self.xaxisVar.get()
        if xaxis == "": xaxis = 'x axis'
        if len(xaxis) > 11:
            xaxis = xaxis[:11] # just use first 11 chars
        else:
            xaxis = string.center(xaxis,11)
            
        yaxis = self.yaxisVar.get()
        if yaxis == "": yaxis = 'y axis'
        if len(yaxis) > 11:
            yaxis = yaxis[:11] # just use first 11 chars
        else:
            yaxis = string.center(yaxis,11)
        keyhdr = string.center('keys',11)
        E.append(" /        %s %s %s\n" %(keyhdr, xaxis, yaxis))
            
        n = len(e)
        for i in range(n): 
            key = i+1
            val = e[i]
            x,y = self.D[val][0], self.D[val][1]
            line =  "%5d %2d %11.1f %11f %11f\n" % (key, 3, float(e[i]), x, y)
            E.append(line)

        try:
            fp = open(filename,'w')
            fp.writelines(E)
            fp.close()
            self.statusMessage('Data written to %s' % filename)
        except:
            self.statusMessage('ERROR: unable to write to %s' % filename, timeout=0)
コード例 #43
0
def get_guessConsonant():
    check = False
    while check == False:
        guess = string.upper(raw_input("Please guess a letter: ", ))
        if len(guess) == 1 and guess in [
                'B', 'C', 'D', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P',
                'Q', 'R', 'S', 'T', 'V', 'W', 'X', 'Y', 'Z'
        ]:
            check = True
        if len(guess) != 1:
            print ""
            print string.center(("-" * 80), 80)
            print "ERROR: INVALID ENTRY!"
            print "Please enter one letter per guess."
            print string.center(("-" * 80), 80)
            print ""
            check = False
        if guess in ["a", "e", "i", "o", "u", "y"]:
            print ""
            print string.center(("-" * 80), 80)
            print "ERROR: INVALID ENTRY!"
            print "Entry must be a consonant."
            print string.center(("-" * 80), 80)
            print ""
            check = False

    return guess
コード例 #44
0
def guess_result(player_turn, playerOrder, playerOrder_val_round, guess, subPrize, letter_app):

    if letter_app == 0:
        print ""
        print "I'm sorry", playerOrder[player_turn] + ", but there are no '" + guess + "s in the puzzle."
        print "Your Free Play, however, means that you keep possession of The Wheel."
        print ""
        print string.center(("-" * 80), 80)
    if letter_app == 1:
        playerOrder_val_round[player_turn][0] = letter_app_sing(player_turn, playerOrder, playerOrder_val_round, guess, subPrize, letter_app)
    if letter_app >= 2:
        playerOrder_val_round[player_turn][0] = letter_app_plur(player_turn, playerOrder, playerOrder_val_round, guess, subPrize, letter_app)

    return playerOrder_val_round[player_turn][0]
コード例 #45
0
def get_guessVowel():
    check = False
    while check == False:
        guess = string.upper(raw_input("Please guess a vowel: ", ))
        if len(guess) == 1 and guess in ["A", "E", "I", "O", "U"]:
            check = True
        if len(guess) != 1:
            print ""
            print string.center(("-" * 80), 80)
            print "ERROR: INVALID ENTRY!"
            print "Please enter one letter per guess."
            print string.center(("-" * 80), 80)
            print ""
            check = False
        if guess in [
                'B', 'C', 'D', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P',
                'Q', 'R', 'S', 'T', 'V', 'W', 'X', 'Y', 'Z'
        ]:
            print ""
            print string.center(("-" * 80), 80)
            print "ERROR: INVALID ENTRY!"
            print "Entry must be a vowel."
            print string.center(("-" * 80), 80)
            print ""
            check = False

    return guess
コード例 #46
0
ファイル: PDB_util.py プロジェクト: jfried23/pdbedit
def Atom2pdb(atmobj):
    try:
        if atmobj.valid != True: return ''
    except:
        return None

    atm_type = ljust(str(atmobj.atm_type), 6).upper()
    atm_number = rjust(str(atmobj.atm_number), 5)

    if atmobj.atm_name[0].isdigit() and atmobj.atm_name[-1].isdigit():
        atm_name = ' ' + center(str(atmobj.atm_name), 4).upper()
    elif atmobj.atm_name[-1].isdigit():
        atm_name = ' ' + ljust(str(atmobj.atm_name), 4).upper()
    elif (atmobj.atm_name[-1] == '\''):
        atm_name = ' ' + rjust(str(atmobj.atm_name), 4).upper()
    else:
        atm_name = ' ' + center(str(atmobj.atm_name), 4).upper()

    alt_loc = center(str(atmobj.alt_loc), 1)
    resi_name = center(str(atmobj.resi_name), 3).upper() + ' '
    chain = center(str(atmobj.chain), 1).upper()
    resSeq = rjust(str(atmobj.resSeq), 4)
    icode = center(str(atmobj.icode), 1) + 3 * ' '
    pos = rjust("%.3f" % atmobj.pos[0], 8) + rjust(
        "%.3f" % atmobj.pos[1], 8) + rjust("%.3f" % atmobj.pos[2], 8)
    occ = rjust(str(atmobj.occ), 6)
    bfac = rjust(str(atmobj.bfac), 5) + 11 * ' '
    elem = center(str(atmobj.elem), 2)
    charge = center(str(atmobj.charge), 2)

    return atm_type + atm_number + atm_name + alt_loc + resi_name + chain + resSeq + icode + pos + occ + bfac + elem + charge + '\n'
コード例 #47
0
ファイル: mrkcoordQC.py プロジェクト: mgijax/mrkcoordload
def createNonMirnaMarkerReport ():
    global errorCount, errorReportNames

    print 'Create the non-miRNA marker report'
    fpNonMirnaMrkRpt.write(string.center('Non-miRNA Marker Report',108) + NL)
    fpNonMirnaMrkRpt.write(string.center('(' + timestamp + ')',108) + 2*NL)
    fpNonMirnaMrkRpt.write('%-16s  %-50s  %-16s%s' %
                     ('MGI ID','Feature Type','miRBase ID',NL))
    fpNonMirnaMrkRpt.write(16*'-' + '  ' + 50*'-' + '  ' + 16*'-' + NL)

    #
    # Find any MGI IDs from the coordinate file that are supposed to be
    # associated with a miRBase ID, but the marker does not have a
    # "miRNA gene" feature type.
    #
    # we use tc.mirbaseID like "%MI%" because mirbaseID is a text field
    #  and only like is allowed for a text field in the where clause 
    #
    sql = 'select tc.mgiID, tc.mirbaseID, m.term from %s tc, ACC_Accession a, MRK_MCV_Cache m ' % (coordTempTable)
    results = db.sql(sql + \
    	'''where tc.mirbaseID like '%MI%' and
          tc.mgiID = a.accID and 
          a._MGIType_key = 2 and 
          a._LogicalDB_key = 1 and 
          a.preferred = 1 and 
          a._Object_key = m._Marker_key and 
          m.qualifier = 'D' and 
          m.term != 'miRNA gene'
        order by mgiID
	''', 'auto')

    #
    # Write the records to the report.
    #
    for r in results:
        mgiID = r['mgiID']
        mirbaseID = r['mirbaseID']
        featureType = r['term']

        fpNonMirnaMrkRpt.write('%-16s  %-50s  %-16s%s' %
            (mgiID, featureType, mirbaseID, NL))

    numErrors = len(results)
    fpNonMirnaMrkRpt.write(NL + 'Number of Rows: ' + str(numErrors) + NL)

    errorCount += numErrors
    if numErrors > 0:
	if not nonMirnaMrkRptFile in errorReportNames:
	    errorReportNames.append(nonMirnaMrkRptFile + NL)
    return
コード例 #48
0
def apply_encryption(text):

    encrypted_text = apply_shifts(text, create_rand_shifts(text))

    print ""
    print string.center("-" * 80, 80)
    print "Encrypting, please be patient..."

    plain_text = apply_decryption(encrypted_text)

    while plain_text != text:
        encrypted_text = apply_shifts(text, create_rand_shifts(text))
        plain_text = apply_decryption(encrypted_text)

    return encrypted_text
コード例 #49
0
ファイル: igra_aryfm.py プロジェクト: kvykhrov/aryfm_game
def aryfm():
    a = random.randint(2, 11)
    b = random.randint(0, 8)

    result = a * b

    line1 = '%i  %i ' % (a, b)

    print line1

    time.sleep(random.randint(2, 5))

    line2 = '#### =%i ####' % result
    centerarg = random.randint(14, 25)
    print string.center(line2, centerarg)
コード例 #50
0
ファイル: output.py プロジェクト: tacaswell/sardana
    def _writeRecord(self, record):
        cells = []
        for i, (name, cell) in enumerate(self._scan_line_t):
            cell_data = record.data[name]
            if isinstance(cell_data, numpy.ndarray):
                cell = str(cell_data.shape)
            elif cell_data is None:
                cell = "<nodata>"
            elif isinstance(cell_data, (str, unicode)):
                # TODO: for SEP2 needs strings are enabled for visualizing
                # value refs, previously "<string>" was printed. This may
                # have side effects e.g. alignment of columns etc.. Check
                # and fix it.
                cell = cell_data
            else:
                cell %= record.data
            cell = string.center(cell.strip(), self._col_sizes[i])
            cells.append(cell)
        scan_line = self._col_sep.join(cells)

        if self._output_block:
            self._stream()._outputBlock(scan_line)
        else:
            self._stream()._output(scan_line)

        self._stream()._flushOutput()
コード例 #51
0
 def _preProcessProduct(self, fcst, argDict):
     # Set up format spacing and title line spacing
     
     numElements = len(self._elementList)
     if numElements > 2:
         self._spaceStr = ""
     else:
         self._spaceStr = "   "
     if self._includeTitle == 0:
         return fcst
         
     self._titles = self._titleDict()
     if numElements > 2:
         if self._productType == "Morning":
             self._headingLen = 15
         else:
             self._headingLen = 19
     else:
         if self._productType == "Morning":
             self._headingLen = 21
         else:
             self._headingLen = 28
                 
     # Create title line
     title = self._introLetters + "        "
     index = 0
     for element in self._elementList:
         title = title + string.center(
                 self._titles[element], self._headingLen)
         if index < len(self._elementList)-1:
             title = title + "/"
         index += 1
     return fcst + title + "\n"
コード例 #52
0
ファイル: genparserCommands.py プロジェクト: lisarosalina/App
 def indexLabel(self):
     """ creates a label that indexes each space-separated field """
     text = self.idf.entryByName['fileView']['widget'].get()
     lines = string.split(text, '\n')
     w = self.idf.entryByName['index_label']['widget']
     for l in lines:
         if l[:4]=='ATOM':
             labeltext = l
             recs = string.split(l)
             self.maxIndex = len(recs)-1
             j = 1
             for rec in recs[1:]:
                 if j > 9 and len(rec)==1:
                     rec = ' ' + rec
                     num = str(j)
                 else:
                     num = string.center('%i'%j, len(rec))
                 ind = string.find(labeltext, '%i'%(j-1))
                 if j==1: ind = 0
                 labeltext = labeltext[:ind] + \
                             string.replace(labeltext[ind:],rec,num,1)
                 j = j + 1
             labeltext = 'Index' + labeltext[5:]
             w.configure(text = labeltext)
             if hasattr(self, 'smallidf'):
                 self.smallidf.entryByName['index']['widget'].configure(validate = {'validator':'numeric', 'min':1, 'max':self.maxIndex})
             return
     w.configure(text = '')
     self.maxIndex = None
     if hasattr(self, 'smallidf'):
         self.smallidf.entryByName['index']['widget'].configure(validate = {'validator':'numeric', 'min':1, 'max':self.maxIndex})
コード例 #53
0
    def dump(self, n=-1, reset=False):
        """
		Dumps n rows of the table to console.
		If reset=True, the dump starts over from the 1st row
		"""
        if n == -1:
            n = self.numRows()
        if reset:
            self.dumpcnt = 0
        colwidth = 17
        join = lambda l: '| ' + ' | '.join(l) + ' |'
        dump = join([
            string.center(name[:colwidth], colwidth) for name in self.attrs()
        ])
        sep = '+' * len(dump)
        dump = sep + '\n' + dump + '\n' + sep
        for i in [x + self.dumpcnt for x in range(n)]:
            if i >= len(self.data):
                break
            dump += '\n' + join([
                string.ljust(str(val)[:colwidth], colwidth)
                for val in self.data[i]
            ])
            self.dumpcnt += 1
        dump += '\n' + sep
        print dump
コード例 #54
0
 def dump(self,n=-1,reset=False,*cols):
   """
   Dumps n rows of the table to console.
   If n is not given, the full table is dumped.
   If reset=True, the dump starts over from the 1st row.
   """
   if len(cols) == 0:
     colidx = range(len(self.cols))
   else:
     colidx = self.getColIndexes(cols) 
   if n == -1:
     n = self.numrows()
   if reset:
     self.dumpcnt = 0
   colwidth = 17
   makedumprow = lambda l: '| '+' | '.join(l)+' |\n'
   # Build the header by arranging column labels in rows
   labels = map(list,[self.cols[i] for i in colidx])
   maxnumlabels = max(map(len,labels))
   labels = [l+['']*(maxnumlabels-len(l)) for l in labels]
   labelrows = zip(*labels)
   headerrows = map(makedumprow,[[string.center(label[:colwidth],colwidth) for label in lr] for lr in labelrows])
   dump = ''.join(headerrows)
   sep = '+'*(len(headerrows[0])-1)+'\n'
   dump = sep + dump + sep
   # Dump appropriate number of rows
   for i in [x+self.dumpcnt for x in range(n)]:
     if i >= len(self.data):
       break
     dump += makedumprow([string.ljust(unicode(self.data[i][j])[:colwidth],colwidth) for j in colidx])
     self.dumpcnt += 1
   dump += sep
   print dump
コード例 #55
0
 def writeCenteredLine(self, lineNum, text):
     """
     This function writes a line of text (param text), with the text centered on the line (line number specified by lineNum). The text should be a string, maximum length of 20 chracters. lineNum should be an integer from 1 to 4.
     @param lineNum (int) - the line number, 0 to 3
     @param text (string) - the text to write (max len 20)
     """
     self.writeLineFromLeft(lineNum, string.center(text, 20))
コード例 #56
0
def tableWrite(t, fileName=None, **args) :
    '''Output a table out of a list of lists; elements number i
    of each list form row i of the table
    Usage :
    tableWrite((list1,list2...)) - write table to stdout
    tableWrite((list1,list2...), fileName) - write table to file
    '''

        
    import sys

    if fileName is not None :
        fileHandle = open(fileName, "w")
    else :
        fileHandle = sys.stdout

    if 'headings' in args :
        headings = args['headings']
    else :
        headings = None
        
    d = len(t)
    n = len(t[0])
    print d,n
    maxlen=numpy.zeros(d)

    if headings != None :
        assert len(headings) == d
        
    for i in range(n) :
        for j in range(d) :
            if type(t[j][i]) == type(1.0) :
                s = "%f" % t[j][i]
            else :
                s = str(t[j][i])
            if len(s) > maxlen[j] :
                maxlen[j] = len(s)

    
    if headings != None :
        for j in range(d) :
            if len(headings[j]) > maxlen[j] :
                maxlen[j] = len(headings[j])
            print >> fileHandle, "%s" % string.center(headings[j], maxlen[j]),
        print >> fileHandle
            
    for i in range(n) :
        for j in range(d) :
            
            if type(t[j][i]) == type("") :
                print >> fileHandle, "%s" % string.ljust(t[j][i], maxlen[j]),
            elif type(t[j][i]) == type(1) :
                print >> fileHandle, "%s" % string.rjust(str(t[j][i]), maxlen[j]),
            elif type(t[j][i]) == type(1.0) :
                s = "%f" % t[j][i]
                print >> fileHandle, "%s" % string.rjust(s, maxlen[j]),
            else :
                print >> fileHandle, "%s" % ' ' * maxlen[j],
                print "unknown data type"
        print >> fileHandle
コード例 #57
0
def banner(lst_str):
    middle_sec = ""
    for str in lst_str:
        middle_sec += " " * 46 + string.center(str, 54, " ") + "\n"
    return "{}{}{}\n\n".format(heading_bar(),
		  middle_sec,
          heading_bar())
コード例 #58
0
    def _print_board(self, matrix):
        ROW_WIDTH = 7
        COLUMN_SEPARATOR = u"|"
        ROW_SEPARATOR = u"-"

        # Create a horizontal line to separate rows.
        row = (ROW_SEPARATOR * ROW_WIDTH for _ in xrange(self.DIMENSIONS))
        horizontal_line = u"+".join(row)

        # Create a list of strings, one for each row.
        row_strings = []
        for x in xrange(self.DIMENSIONS):

            # Create a list of cell strings, one for each column.
            column_strings = []
            for y in xrange(self.DIMENSIONS):
                marker = matrix[x][y]
                cell_value = marker if marker else "({0},{1})".format(x, y)
                padded_cell_string = string.center(cell_value, ROW_WIDTH)
                column_strings.append(padded_cell_string)

            # Add a horizontal line in front of each row, for all but the
            # first line.
            is_first_row = x > 0
            if is_first_row:
                row_strings.append(horizontal_line)

            # Join columns by their separators to generate the final row
            # string.
            row_string = COLUMN_SEPARATOR.join(column_strings)
            row_strings.append(row_string)

        return u"\n".join(row_strings)