def show_from_cache(self): cache = inventory.CachedInventory() if self.args.type == 'instances': for inst in cache.instances(self.customer): if self.args.ec2_region != 'all' and self.args.ec2_region != inst['region']: continue print inst['_id'], string.rjust(inst['region'], 10), string.rjust(inst['state'], 10) elif self.args.type == 'volumes': for vol in cache.volumes(self.customer): if self.args.ec2_region != 'all' and self.args.ec2_region != vol['region']: continue if self.args.instance != None and self.args.instance != vol['instance_id']: continue print vol['_id'], vol['instance_id'], string.rjust(vol['region'], 10), string.rjust(vol['status'], 10), string.rjust(vol['device'], 10) elif self.args.type == 'snapshots': for snap in cache.snapshots(self.customer): #.limit(10): if self.args.ec2_region != 'all' and self.args.ec2_region != snap['region']: continue if self.args.volume != None and self.args.volume != snap['volume_id']: continue print "%s %s %s %s %s" % ( snap['_id'], snap['volume_id'], snap['region'], snap['status'], snap['volume_size'], )
def print_title(self): print string.rjust('ncalls', 9), print string.rjust('tottime', 8), print string.rjust('percall', 8), print string.rjust('cumtime', 8), print string.rjust('percall', 8), print 'filename:lineno(function)'
def performList(self, ch): currency = self.getLocation()._zone._currency ch.writeToSelf(string.capitalize( utils.substNames(self._shopMessages["showList"], self, ch, None))+"\r\n") ch.writeToSelf(string.center("#", 4) +string.ljust("Description",46) +string.rjust("Stock",5) +string.rjust("Price",15) +"\r\n"+"-"*70+"\r\n") idx = 0 for id, qty in self._products: p = self._world.getObject(id) if not p: self.warning("shopkeeper with invalid product "+id) continue price = utils.convertCurrency(p._value, CUR_DOLLAR, currency) price = utils.getMoneyText(price, currency) if qty == 0: qty = "-" else: qty = str(qty) idx = idx + 1 ch.writeToSelf(string.ljust('#'+`idx`, 4) +string.ljust(p.getName(),46) +string.rjust(qty, 5) +string.rjust(price, 15)+"\r\n")
def avgValue(self, element, stats): # Takes in values, averages, formats, and returns them # Scalar input: (val1, val2) # Vector input: vectorRange:(mag1, mag2, dir1, dir2) valStr = "" if stats is None: return valStr if element.dataType() == "Vector": mag1 = stats[0] mag2 = stats[1] #print "stats", stats dir1 = stats[2] dir2 = stats[3] mag, dir = self.vectorAverage((mag1, dir1),(mag2, dir2)) mag = self.callMethod(mag, element.conversion()) mag = self.round(mag, "Nearest", element.roundVal()) if mag <= self.table_wind_threshold(): valStr = self.table_light_winds_phrase() else: valStr = self.fformat(mag, element.roundVal()) valStr = string.rjust(valStr, element.maxWidth()) # put in the direction dir = self.convertDirection(dir) valStr = string.rjust(dir, 2) + valStr else: val1 = self.average(stats[0], stats[1]) val1 = self.callMethod(val1, element.conversion()) val = self.round(val1, "Nearest", element.roundVal()) valStr = self.fformat(val, element.roundVal()) valStr = string.rjust(valStr, element.maxWidth()) return valStr
def search(filename, searching, TEXTCASE, DISPLAY): print "Searching identifier " + searching + " in " + filename global counter f = openread(filename) # Local function if not f: return slen = len(searching) linenum = 0 while 1: line = f.readline() if not line: break linenum = linenum + 1 old = counter words = split(line) # local split for cmp in words: if searching == cmp: counter = counter + 1 else: if TEXTCASE == FALSE: if string.lower(searching) == string.lower(cmp): counter = counter + 1 if counter > old: if DISPLAY == TRUE: # A trailing comma to avoid new line print string.rjust(str(linenum), 4), line, f.close() return counter
def singleValue(self, element, stats): # Takes in one value, formats, and returns it # If vector type, stats is mag,dir where direction can # be mag or dir valStr = "" if stats is None: return valStr if element.dataType() == "Vector": mag = self.callMethod(stats[0], element.conversion()) mag = self.round(mag,"Nearest",element.roundVal()) if mag <= self.table_wind_threshold(): valStr = self.table_light_winds_phrase() else: magStr = self.fformat(mag, element.roundVal()) magStr = string.rjust(magStr, element.maxWidth()) dir = stats[1] if type(dir) is not types.StringType: dir = self.round(dir,"Nearest",element.roundVal()) dirStr = self.convertDirection(dir) else: dirStr = dir valStr = string.rjust(dirStr,2) + magStr else: val = self.callMethod(stats, element.conversion()) value = self.round(val, "Nearest", element.roundVal()) valueStr = self.fformat(value, element.roundVal()) valStr = string.rjust(valueStr, element.maxWidth()) return valStr
def getCalibration(self): """ Get the adc and current values from device at different points """ for index in range(app_calib_im.NO_OF_POINTS): timeout = TIMEOUT_INTERVAL i, adc, current, timeout = libxsmu.CM_getCalibration( self.deviceID, index, timeout) if (timeout == 0.0): self._vOnDeviceTimeout() return FAIL self.adcValues.append(adc) self.actualCurrentValues.append(current) print "ADC and current values obtained successfully : " print "Index | ADC Values | Actual Current (" + str( self.currentUnitLabel[self.currentMeasureRange]) + ")" for index in range(app_calib_im.NO_OF_POINTS): print ' ' + string.rjust(str(index), 2) + ' | ' + string.rjust( str(self.adcValues[index]), 8) + ' | ' + string.rjust( str( round((self.actualCurrentValues[index] / self.currentUnit[self.currentMeasureRange]), PRECISION)), 10) print "\n" return SUCCESS
def _addSnowEntries(self, analysisList, timePeriods, editArea): # Snow entry processing. Returns ranges of snow values in the # edit area for each of the periods. # Example: 0102/0202/0000. Will return "MMMM" for missing periods. # This function will "calculate" a snow range if a single value # is provided to it, to make the output more realistic. returnString = " " for period, label in timePeriods: statDict = self.getStatDict(self._sampler, analysisList, period, editArea) stats = self.getStats(statDict, "SnowAmt__minMaxSum") if stats is None: returnString = returnString + "MMMM/" #Missing Data else: minV, maxV, sumV = stats minAdj, maxAdj = self._adjustSnowAmounts(minV, maxV, sumV) minString = string.rjust(`int(round(minAdj))`, 2) maxString = string.rjust(`int(round(maxAdj))`, 2) if minString[0] == " ": # fill in leading zero minString = "0" + minString[1:] if maxString[0] == " ": # fill in leading zero maxString = "0" + maxString[1:] returnString = returnString + minString + maxString + "/" # strip off the final "/" if returnString[-1] == "/": returnString = returnString[:-1] return returnString
def searchstr(srcname, searching, TEXTCASE, DISPLAY): global counter print "Searching string \"" + searching + "\" in " + srcname src = openread(srcname) if not src: return linenum = 0 if TEXTCASE == FALSE: searching = string.lower(searching) while 1: line = src.readline() if not line: break linenum = linenum + 1 if TEXTCASE == FALSE: line = string.lower(line) # Locating, counting and displaying if string.find(line, searching) != -1: if DISPLAY == TRUE: print string.rjust(str(linenum), 4), line, counter = counter + string.count(line, searching) src.close() return counter
def WriteXVFile(filename,vectors,speciesnumber,atomnumber,xyz,\ InUnits='Ang',OutUnits='Bohr',Velocity=[]): "Writes (vectors,speciesnumber,atomnumber,xyz,[V],) to the XV-file format" print 'SiestaIO.WriteXVFile: Writing',filename if (InUnits=='Bohr') and (OutUnits=='Ang'): convFactor = Bohr2Ang elif (InUnits=='Ang') and (OutUnits=='Bohr'): convFactor = Ang2Bohr elif (((InUnits=='Ang') and (OutUnits=='Ang')) \ or ((InUnits=='Bohr') and (OutUnits=='Bohr'))): convFactor = 1 else: print 'SiestaIO.WriteXVFile: Unit conversion error!' file = open(filename,'w') # Write basis vectors (lines 1-3) for i in range(3): line = ' ' for j in range(3): line += string.rjust('%.9f'%(vectors[i][j]*convFactor),16) line += ' 0.00 0.00 0.00 \n' file.write(line) # Write number of atoms (line 4) numberOfAtoms = len(speciesnumber) file.write(' %i\n' %numberOfAtoms) # Go through the remaining lines for i in range(numberOfAtoms): line = ' %i' %speciesnumber[i] line += ' %i ' %atomnumber[i] for j in range(3): line += string.rjust('%.9f'%(xyz[i][j]*convFactor),16) if len(Velocity)==0: line += ' 0.00 0.00 0.00 ' else: for j in range(3): line += string.rjust('%.9f'%(Velocity[i][j]*convFactor),16) file.write(line+'\n') file.close()
def disassemble(co, lasti): code = co.co_code labels = findlabels(code) n = len(code) i = 0 while i < n: c = code[i] op = ord(c) if op = SET_LINENO and i > 0: print # Extra blank line if i = lasti: print '-->', else: print ' ', if i in labels: print '>>', else: print ' ', print string.rjust(`i`, 4), print string.ljust(opname[op], 15), i = i+1 if op >= HAVE_ARGUMENT: oparg = ord(code[i]) + ord(code[i+1])*256 i = i+2 print string.rjust(`oparg`, 5), if op in hasconst: print '(' + `co.co_consts[oparg]` + ')', elif op in hasname: print '(' + co.co_names[oparg] + ')', elif op in hasjrel: print '(to ' + `i + oparg` + ')', print
def getPQRString(self, chainflag=False): """ Returns a string of the new atom type. Uses the ATOM string output but changes the first field to either by ATOM or HETATM as necessary. This is used to create the output for pqr files! No touchy! Returns str: String with ATOM/HETATM field set appropriately """ outstr = self.getCommonStringRep(chainflag=chainflag) if self.ffcharge != None: ffcharge = "%.4f" % self.ffcharge else: ffcharge = "0.0000" outstr += string.rjust(ffcharge, 8)[:8] if self.radius != None: ffradius = "%.4f" % self.radius else: ffradius = "0.0000" outstr += string.rjust(ffradius, 7)[:7] return outstr
def wealth(character): print "\nWEALTH" data = character['wealth'] print "\t%s gold" % (string.rjust(str(data['gold']), 5)) print "\t%s silver" % (string.rjust(str(data['silver']), 5)) print "\t%s copper" % (string.rjust(str(data['copper']), 5)) print "\t%s" % (data['notes'])
def stats_get(command, options): ''' Resident set size (RSS) The portion of memory occupied by a process that is held in main memory (RAM). The rest of the occupied memory exists in the swap space or file system, either because some parts of the occupied memory were paged out, or because some parts of the executable were never loaded. Apparently done away with in free -m display in 16.04 where as it was in 14.04 the Mem used(kb_main_used) field value is now calculated like this: used = total - free - cached - buffer Previously, it used to be: used = total - free Actual formula in 16.0x: cache = mb_main_free + buffers (mb_main_buffers) + cached (mb_main_cached) https://askubuntu.com/questions/770108/what-do-the-changes-in-free-output-from-14-04-to-16-04-mean/770125 ''' dictionary = {} if options.vmstat == True: for line in shell_exec(command).split('\n'): digits = '' for char in line.split(): if char.isdigit(): digits += char key = line.replace(digits, '', 1).strip() try: dictionary[key] = int(digits) except: pass dictionary['rss'] = str(dictionary['M free memory'] + dictionary['M buffer memory'] + dictionary['M swap cache']) dictionary['cache'] = str(dictionary['M swap cache']) dictionary['swap'] = str(dictionary['M used swap']) dictionary['usage'] = str(dictionary['M free memory'] + dictionary['M buffer memory'] + dictionary['M swap cache']) dictionary['max_held'] = str(0) dictionary['limit'] = str(dictionary['M used memory']) else: dictionary['rss'] = str( int(shell_exec("free -m | grep '^-/+ buffers/cache:'").split()[2])) dictionary['cache'] = str( int(shell_exec("free -m | grep '^Mem:'").split()[6])) dictionary['swap'] = str( int(shell_exec("free -m | grep '^Swap:'").split()[2])) dictionary['usage'] = str( int(shell_exec("free -m | grep '^-/+ buffers/cache:'").split()[2])) dictionary['max_held'] = str(0) dictionary['limit'] = str( int(shell_exec("free -m | grep '^Mem:'").split()[1])) if (options.verbose): print '- Active: ' + string.rjust(dictionary['rss'], 10) + ' MB' print '- Cache: ' + string.rjust(dictionary['cache'], 10) + ' MB' print '- Swap: ' + string.rjust(dictionary['swap'], 10) + ' MB' print '- Max Held:' + string.rjust(dictionary['max_held'], 10) + ' MB' print '- Limit: ' + string.rjust(dictionary['limit'], 10) + ' MB' # return onl items of concern return dictionary
def endElement(self, name): # end of </keybind> item if name == 'keybind': self.in_action = 0 self.has_command = 0 # remove last keybinding from the current keychain self.in_keybind -= 1 self.keybind2 = re.sub(" [^ ]+$","",self.keybind2) # make sure we don't carry unused names across to next keybinding self.name = '' # end of </name> item elif (name == 'name'): self.in_name = 0 # print menu item after end of </command> item (which is in a <keybind ...> item) elif (name == 'command') and self.in_keybind: print '<item label="' + self.keybind2 + rjust(strip(self.name),100) + \ '">\n<action name="execute"><execute>' + self.editCommand() + '</execute></action>\n</item>' self.name = '' # print menu item after end of </action> item (within <keybind ...> item) # unless a <command> item has already been printed elif (name =='action') and (self.in_keybind > 0) and (not self.has_command): # if there's no <name> item for this action, print the action name if self.name == '': print '<item label="' + self.keybind2 + rjust(self.action,100) + \ '">\n<action name="execute"><execute>' + self.editCommand() + '</execute></action>\n</item>' # otherwise print the <name> else: print '<item label="' + self.keybind2 + rjust(strip(self.name),100) + \ '">\n<action name="execute"><execute>' + self.editCommand() + '</execute></action>\n</item>' self.name = ''
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
def display(self, cols): # Create the maxCols list which represents the max # length of each row element. maxCols = [] for i in range(0, len(cols[0])): maxCols.append(0) for row in cols: for i in range(0, len(row)): if len(row[i]) > maxCols[i]: maxCols[i] = len(row[i]) # Print the table using maxCols list to force all # columns in the rows to line up. The first column # (hostname) is left justified, and the subsequent # columns are right justified. for row in cols: for i in range(0, len(row)): if i == 0: print string.ljust(row[i], maxCols[i]), else: print string.rjust(row[i], maxCols[i]), if i < len(row) - 1: print '\t', print
def dump(self): print("PanTau::InformationHandler: Printing stored information") print("PanTau::InformationHandler: \tIntegers:") for iInfo in sorted(self.m_Infos_Int.iterkeys()): print("\t\t" + string.ljust(iInfo, 50) + ": " + string.rjust(str(self.m_Infos_Int[iInfo]), 10)) print("PanTau::InformationHandler: \tDoubles:") for iInfo in sorted(self.m_Infos_Double.iterkeys()): print("\t\t" + string.ljust(iInfo, 50) + ": " + string.rjust(str(self.m_Infos_Double[iInfo]), 10)) print("PanTau::InformationHandler: \tStrings:") for iInfo in sorted(self.m_Infos_String.iterkeys()): print("\t\t" + string.ljust(iInfo, 50) + ": " + string.ljust(self.m_Infos_String[iInfo], 80)) print("PanTau::InformationHandler: \tVecDoubles:") for iInfo in sorted(self.m_Infos_VecDouble.iterkeys()): print("InformationHandler: \t\t" + string.ljust(iInfo, 50) + ":") for iVal in self.m_Infos_VecDouble[iInfo]: print("InformationHandler: \t\t\t" + string.rjust(str(iVal), 10)) print("PanTau::InformationHandler: \tVecStrings:") for iInfo in sorted(self.m_Infos_VecString.iterkeys()): print("InformationHandler: \t\t" + string.ljust(iInfo, 50) + ":") for iVal in self.m_Infos_VecString[iInfo]: print("InformationHandler: \t\t\t" + string.ljust(str(iVal), 80)) print("PanTau::InformationHandler: Done printing stored information")
def __str__(self): name = 'Name' base_url = 'Base URL' app_key = 'Application key' app_secret = 'Application secret' consumer_key = 'Consumer key' maxsize = 0 for size in [ len(name), len(base_url), len(app_key), len(app_secret), len(consumer_key) ]: if size > maxsize: maxsize = size output = '%s: %s' % (string.rjust(name, maxsize), self.name) output += '\n%s: %s' % (string.rjust(base_url, maxsize), self.base_url) output += '\n%s: %s' % (string.rjust(app_key, maxsize), self.app_key) output += '\n%s: %s' % (string.rjust(app_secret, maxsize), self.app_secret) output += '\n%s: %s' % (string.rjust(consumer_key, maxsize), self.consumer_key) return output
def PrintReceipt(self,event): import os try: if os.uname()[0]=="Linux": ON_LINUX=True # : ) except: ON_LINUX=False # :( if ON_LINUX: receiptfile=open(string.replace("/tmp/receipt-%s.txt" % datetime.datetime.today()," ",""),'w') else: receiptfile=open("C:\\Documents and Settings\\user\\My Documents\\infoshopkeeper\\receipts\\" + string.replace("%s" % datetime.datetime.today(),":","-") + ".txt",'w') receipttext="" receipttext=receipttext+"\n\n\nSale Made at %s" % ("%s" % (datetime.datetime.today()))[0:16] receipttext=receipttext+ "\n\n" for i in self.parent.orderbox.items: receipttext=receipttext+ i.getName() + string.rjust(" %.2f\n" % i.getPrice(),80-len(i.getName())) receipttext=receipttext+"\n" receipttext=receipttext+ string.rjust("Subtotal: %.2f\n" % self.parent.orderbox.getTaxableTotal(),80) receipttext=receipttext+ string.rjust("Tax: %.2f\n" % self.parent.orderbox.tax_amount,80) receipttext=receipttext+ string.rjust("Total: %.2f\n" % self.parent.orderbox.total_with_tax,80) receipttext=receipttext+ string.rjust("Payment method: %s\n"% self.payment_info,80) receiptfile.write(receipttext) receiptfile.close() self.OrderFinished(event)
def print_items(self, max_items): import os import string from findtorrent.core.colors import colors from hurry.filesize import size, si cols = int(os.popen('stty size', 'r').read().split()[1]) print colors.HEADER + \ 'No. Name' + (cols - 33) * ' ' + 'Size Files Seed Leech' print cols * '-' for index, item in enumerate(Items.sorted): if (max_items != -1 and index + 1 > max_items): break print colors.INDEX + string.ljust(str(index + 1) + '.', 5) + \ colors.NAME + string.ljust(item['name'][:cols - 31], cols - 31) + \ colors.SIZE + string.rjust(size(item['size'], system=si), 6) + \ colors.FILES + string.rjust(str(item['files']) \ .replace('-1', 'N/A'), 7) + \ colors.SEED + string.rjust(str(item['seed']) \ .replace('-1', 'N/A'), 6) + \ colors.LEECH + string.rjust(str(item['leech']) \ .replace('-1', 'N/A'), 7) + \ colors.ENDC
def printData(self): fd = self.getOutputFD() entries = self.getData() mostrecent = None largest = 0 for entry in entries: datestring = entry.YYYYMMDD dateint = string.atoi(datestring) if dateint > largest: largest = dateint fd.write(self.getServer() + ' -- ' + str(largest) + '\n') print "Partition K_DiskSize K_Free %_Committed" for entry in entries: if string.atoi(entry.YYYYMMDD) == largest: partstring = string.rjust(entry.partition, 9) kdiskstring = string.rjust(entry.kdisksize, 12) kfreestring = string.rjust(entry.kfree, 12) kfreeint = string.atoi(kfreestring) try: floater = string.atof(entry.perccomm) except: pass if floater > self.getPercentCommittedThreshold() or kfreeint < self.getKFreeThreshold(): WarnString = '*** WARNING! ***' else: WarnString = '' perccommstring = str('%.2f' % floater) perccommstring = string.rjust(perccommstring, 10) print partstring, kdiskstring, kfreestring, perccommstring, WarnString
def credits(): '''Shows the credits for compmake.''' print(banner) print "Compmake is brought to you by:\n" for credits in contributors: print string.rjust(credits.name, 30) + (" " * 10) + credits.what
def dictview(d,sep=','): if d is None: return u"None" if len(d)==0: return u"Empty" if isinstance(d,basestring): return d if isinstance(d,(list,tuple)): s = u"[len=(%d)|" % len(d) s += u','.join([dictview(v) for v in d]) s += u"]" return unicode(s) # now is dict L = [ len(k) for k in d.keys()] if len(L)==0: return 'EMPTY' lrg = max([ len(k) for k in d.keys()]) s = "{\n" for k,v in sorted(d.items()): if isinstance(v,dict): if len(v)==0: s += " None" continue s+="%s = { \n" % rjust(k,lrg) lrg1 = max([ len(k1) for k1 in v.keys()]) for c,w in sorted(v.items()): s+=" %s %s = %s | %s \n" % (rjust(' ',lrg),rjust(c,lrg1),w,type(w)) s+=" %s }\n"%( rjust(' ',lrg) ) else: s+="%s = %s | %s\n"%( rjust(k,lrg),v,type(v)) s += "}" return s
def write_vibs(self): if not self.atoms_read: self.read_atoms() self.modes = [] nmodes = 0 nmo = open('nmodes.inp', 'w') while 'STANDARD THERMODYNAMIC' not in self.line and len(self.line) > 0: self.read_to('Frequency:') nmo.write( ' ' + self.line[12:] + ' -------------------- -------------------- --------------------\n' ) self.read_for(7) while 'TransDip' not in self.line and len(self.line) > 0: nmo.write(self.line) self.line = self.file.readline() self.read_for(2) nmo.write('\n\n') nmo.close() atm = open('atomicmass.inp', 'w') for i in range(0, len(self.atoms)): atm.write( string.rjust(str(i), 5) + '. ' + string.ljust(self.atoms[i].elem, 3) + string.rjust('%.8f' % self.atoms[i].mass, 12) + '\n') atm.close()
def _write_atomic_coordinates(self, f, atoms): """Write atomic coordinates. Parameters: - f: An open file object. - atoms: An atoms object. """ species, species_numbers = self.species(atoms) f.write('\n') f.write('AtomicCoordinatesFormat Ang\n') f.write('%block AtomicCoordinatesAndAtomicSpecies\n') for atom, number in zip(atoms, species_numbers): xyz = atom.position line = string.rjust(' %.9f' % xyz[0], 16) + ' ' line += string.rjust(' %.9f' % xyz[1], 16) + ' ' line += string.rjust(' %.9f' % xyz[2], 16) + ' ' line += str(number) + '\n' f.write(line) f.write('%endblock AtomicCoordinatesAndAtomicSpecies\n') f.write('\n') origin = tuple(-atoms.get_celldisp().flatten()) f.write('%block AtomicCoordinatesOrigin\n') f.write(' %.4f %.4f %.4f\n' % origin) f.write('%endblock AtomicCoordinatesOrigin\n') f.write('\n')
def show_config(file): # @ReservedAssignment config_sections = CompmakeGlobalState.config_sections config_switches = CompmakeGlobalState.config_switches ordered_sections = sorted(config_sections.values(), key=lambda section: section.order) max_len_name = 1 + max([len(s.name) for s in config_switches.values()]) max_len_val = 1 + max([len(str(get_compmake_config(s.name))) for s in config_switches.values()]) for section in ordered_sections: file.write(" ---- %s ---- \n" % section.name) if section.desc: # XXX multiline file.write(" | %s \n" % section.desc) for name in section.switches: switch = config_switches[name] value = get_compmake_config(name) changed = (value != switch.default_value) if changed: attrs = ['bold'] else: attrs = [] value = str(value) desc = str(switch.desc) file.write(" | %s %s %s\n" % (compmake_colored(rjust(name, max_len_name), attrs=['bold']), compmake_colored(rjust(value, max_len_val), attrs=attrs), desc))
def __repr__(self): if len(self) > 0: lflag = "" tl = self.longest() + 2 if tl > 3: lflag = " " tml = self.longestargtype() tl = tl + tml s = "" t = self.keys() for i in t: ss = self.switch ss = ss + i astr = self.argtype(i) if len(astr) < 1: s = s + "%s%s %s" % ( string.rjust(self.switch + i + astr, tl), self.argparen, self.docstring(i), ) else: s = s + "%s%s %s" % ( string.rjust(self.switch + i + lflag + astr, tl), self.argparen, self.docstring(i), ) s = s + "\n" return s return None
def display(self, cols): # Create the maxCols list which represents the max # length of each row element. maxCols = [] for i in range(0, len(cols[0])): maxCols.append(0) for row in cols: for i in range(0, len(row)): if len(row[i]) > maxCols[i]: maxCols[i] = len(row[i]) # Print the table using maxCols list to force all # columns in the rows to line up. The first column # (hostname) is left justified, and the subsequent # columns are right justified. for row in cols: for i in range(0, len(row)): if i == 0: print string.ljust(row[i], maxCols[i]), else: print string.rjust(row[i], maxCols[i]), if i < len(row)-1: print '\t', print
def show_config(file): from compmake.utils.visualization import colored ordered_sections = sorted(config_sections.values(), key=lambda section: section.order) max_len_name = 1 + max([len(s.name) for s in config_switches.values()]) max_len_val = 1 + max([len(str(compmake_config.__dict__[s.name])) for s in config_switches.values()]) for section in ordered_sections: file.write(" ---- %s ---- \n" % section.name) if section.desc: # XXX multiline file.write(" | %s \n" % section.desc) for name in section.switches: switch = config_switches[name] value = compmake_config.__dict__[name] changed = (value != switch.default_value) if changed: attrs = ['bold'] else: attrs = [] value = str(value) desc = str(switch.desc) file.write(" | %s %s %s\n" % (colored(rjust(name, max_len_name), attrs=['bold']), colored(rjust(value, max_len_val), attrs=attrs), desc))
def WritePOSCAR(filename,vectors,specieslabels,speciesnumbers,xyz,label='LABEL',scalefactor=1.0,constrained=[]): "Write POSCAR file" print 'VaspIO.WritePOSCAR: Writing',filename file = open(filename,'w') if label[:-2]!='\n': file.write(label+'\n') else: file.write(label) file.write(' %.12f \n'%scalefactor) for ii in range(3): for jj in range(3): file.write(string.rjust('%.9f'%vectors[ii][jj],16)+' ') file.write('\n') for ii in range(len(specieslabels)): file.write(' %s'%specieslabels[ii]) file.write('\n') for ii in range(len(speciesnumbers)): file.write(' %i'%speciesnumbers[ii]) file.write('\n') file.write('Selective dynamics\nCartesian\n') for ii in range(len(xyz)): line = string.rjust('%.9f'%xyz[ii][0],16)+' ' line += string.rjust('%.9f'%xyz[ii][1],16)+' ' line += string.rjust('%.9f'%xyz[ii][2],16)+' ' if len(constrained)>0: for jj in range(3): if constrained[ii,jj] > 0: line += ' T' else: line += ' F' line += '\n' else: line += ' F F F\n' file.write(line)
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)
def write_as_table(self,Nev,path_out): ''' Write as simple ascii table for gmt plotting ''' from numpy import zeros,savetxt from string import rjust segment_boundaries=self.segment_boundaries[Nev] segment_data=self.segment_data[Nev] Nsegments=len(segment_boundaries) for k in range(Nsegments): fault=segment_data[k] boundary=segment_boundaries[k] out=zeros((len(fault),3)) out[:,0]=fault[:,1] out[:,1]=fault[:,0] out[:,2]=fault[:,3]/100. #save fault data fname=path_out+self.IDs[Nev]+'.'+rjust(str(k),2,'0')+'.fault.txt' savetxt(fname,out,fmt='%.4f\t%.4f\t%.4f') #Save boundary data fname=path_out+self.IDs[Nev]+'.'+rjust(str(k),2,'0')+'.boundary.txt' savetxt(fname,boundary,fmt='%.4f\t%.4f\t%.4f')
def convertASEtoXV(atoms, specie_dict, filename='siesta.XV'): vectors = atoms.get_cell() convFactor = 1/Bohr atomnumbers = atoms.get_atomic_numbers() speciesnumbers = [specie_dict[atomnumber] for atomnumber in atomnumbers] xyz = atoms.get_positions() with open(filename, 'w') as f: for i in range(3): line = ' ' for j in range(3): line += string.rjust('%.9f'%(vectors[i][j]*convFactor),16) line += ' 0.00 0.00 0.00 \n' f.write(line) # Write number of atoms (line 4) numberOfAtoms = len(speciesnumbers) f.write(' %i\n' %numberOfAtoms) # Go through the remaining lines for i in range(numberOfAtoms): line = ' %i' %speciesnumbers[i] line += ' %i ' %atomnumbers[i] for j in range(3): line += string.rjust('%.9f'%(xyz[i][j]*convFactor),16) line += ' 0.00 0.00 0.00 ' f.write(line+'\n')
def SearchNextEpisode(SHOW,LASTEPISODECOMPLETE): LASTSEASON="%s" % (int(round(LASTEPISODECOMPLETE/100))) LASTSEASON=string.rjust(LASTSEASON,2,"0") Message("Last season = %s" % LASTSEASON,3) LASTEPISODE="%s" % int(LASTEPISODECOMPLETE-(int(LASTSEASON)*100)) LASTEPISODE=string.rjust(LASTEPISODE,2,"0") Message("Last episode = %s" % LASTEPISODE,3) NEXTEPISODE=int(LASTEPISODE)+1 NEXTEPISODE="S%sE%s" % (LASTSEASON,string.rjust("%s" % NEXTEPISODE,2,"0")) NEXTSEASON=string.rjust("%s" % (int(LASTSEASON)+1),2,"0") ANOTHERNEXTEPISODE="S%sE01" % NEXTSEASON Message("III Possible next episodes are '%s' and '%s'" % (NEXTEPISODE,ANOTHERNEXTEPISODE)) URL="%s/%s.%s/" % (URLBASE,SHOW,NEXTEPISODE) CONTENT=GetURLContent(URL) NEXTREALEPISODE="0000" if CONTENT == False or "did not match any documents" in CONTENT: URL="%s/%s.%s/" % (URLBASE,SHOW,ANOTHERNEXTEPISODE) CONTENT=GetURLContent(URL) if CONTENT == False or "did not match any documents" in CONTENT: Message("WWW I couldn't find any episode available for '%s'" % SHOW) else: NEXTREALEPISODE=ANOTHERNEXTEPISODE else: NEXTREALEPISODE=NEXTEPISODE Message("III Found next episode '%s'" % NEXTREALEPISODE) return CONTENT,NEXTREALEPISODE
def sendFile(self,sock, file): sock.send(filFlag) user = os.environ['USER'] command = filFlag size = os.stat(file)[6] try: f = open(file,'r') except: ret = 0 else: pos = 0 while 1: if pos == 0: buffer = f.read(5000000-282) if not buffer: break: count = sock.send(command + ':' + \ string.rjust(os.path.basename(file), 214) + ':' + \ string.rjust(str(size).strip(),30) + ':' + \ string.rjust(str(user).strip(),30) + \ buffer) pos = 1 else: buffer = f.read(5000000) if not buffer: break: count = sock.send(buffer) ret = 1 return ret
def draw_alarm(color): frontbuffer(TRUE) Gl.c3i(color) pushmatrix() rotate(-((Gl.alarm_time/12)%3600), 'z') bgnpolygon() v2f( 0.00,1.00) v2f( 0.04,1.05) v2f(-0.04,1.05) endpolygon() popmatrix() # pushmatrix() rotate(-((Gl.alarm_time)%3600), 'z') bgnpolygon() v2f( 0.00,1.05) v2f( 0.07,1.10) v2f(-0.07,1.10) endpolygon() popmatrix() # cmov2(-1.06, -1.06) charstr(string.rjust(`Gl.alarm_time/3600`,2)) charstr(':') charstr(string.zfill((Gl.alarm_time/60)%60,2)) frontbuffer(FALSE)
def create_top_sense_tables(doc_list): documents = doc_list if documents is None: documents = default_document_list() log.info("Top words") log.info("=" * 80) for document in documents: log.info("=" * 80) log.info(document.name) try: for word, _ in document.top_words(): log.info(word) except AttributeError: log.exception("No top words found. Trying to calculate them.") with open("paper/top_senses_%s.tex" % clean_name(document.name), "w") as tex_table: tex_table.write(""" \\begin{center} \\begin{tabular}{ | l | l | l | } \hline \multicolumn{3}{|c|}{%s} \\\\ \hline \# & Word \\\\ \hline\n""" % document.name[:30]) top_senses = document.top_senses() last = len(top_senses) for index, sense in enumerate(top_senses, start=1): log.info("Sense %s -- %s " % (string.rjust(sense.name, 35), string.rjust(sense.definition, 55))) tex_table.write("%s & %s & %s \\\\ \hline" % (index, string.rjust(sense.name, 35).split('.')[0].strip().replace('_', '\_'), sense.definition)) if index != last: tex_table.write("\n") tex_table.write("""\end{tabular}\n\end{center}""")
def getTopRaters(n=5): #get users that rated the most movies users = loadUserRatings() rsort = sorted(users.items(), key=lambda x: len(x[1]), reverse=True) print '\nTop 5 users by most ratings:' print string.ljust('User', 12), string.rjust('Number of Ratings', 3) print string.ljust('------', 12), string.rjust('----------------', 3) for x in range(0, n): print string.ljust(rsort[x][0], 12), string.rjust(str(len(rsort[x][1])), 3)
def show_registers(self): column_width = 3 print 'R:', for register in self.registers: print rjust(str(register), column_width), print ' F:', for float_register in self.float_registers: print rjust(str(float_register), column_width), print
def hexDump(bytes): """Useful utility; prints the string in hexadecimal""" for i in range(len(bytes)): sys.stdout.write("%2x " % (ord(bytes[i]))) if (i + 1) % 8 == 0: print repr(bytes[i - 7:i + 1]) if (len(bytes) % 8 != 0): print string.rjust("", 11), repr(bytes[i - 7:i + 1])
def marker_string(length): output = '' printed = 0 for i in xrange(10, length, 10): if length - i > len(str(length)): output += string.rjust(str(i), 10, '_') printed += 10 output += string.rjust(str(length), length - printed, '_') return output
def do_list(self, line): names = self.people.keys() # the keys are the names if names == []: return # if there are no names, exit names.sort() # we want them in alphabetic order print '=' * 41 for name in names: print string.rjust(name, 20), ":", string.ljust(self.people[name], 20) print '=' * 41
def print_metrics(self): keys = self.metrics.keys() keys.sort() for glyph in keys: width = self.metrics[glyph]['WX'] bbox = self.metrics[glyph]['B'] print " " + string.rjust(glyph, 12), print " " + string.rjust(width, 5), print " %4d %4d %4d %4d" % (bbox[0], bbox[1], bbox[2], bbox[3])
def explore_menu(mySelector, myHost, myPort): list = menu_display(mySelector, myHost, myPort) while 1: print '----- GOPHERS Server MENU -----' #Dislay Menu print 'Selector:', repr(mySelector) print 'Host:', myHost, ' Port:', myPort print for i in range(len(list)): #Range of types is 0-6 item = list[i] typechar, description = item[0], item[1] print string.rjust(repr(i + 1), 3) + ':', description, if type_dictionary.has_key(typechar): print type_dictionary[typechar] else: #if type is not matched print '<TYPE=' + repr(typechar) + '>' print for key, value in type_dictionary.iteritems(): temp = [key, value] list.append(temp) while 1: try: #user choice of function str = raw_input('Choice [CR == up a level]:') except EOFError: print for key, value in type_dictionary.iteritems(): temp = [key, value] list.append(temp) return if not str: return try: #handle choice related errors choice = string.atoi(str) except string.atoi_error: print 'Choice must be a number; try again:' continue if not 0 < choice <= len(list): print 'Choice is out of range; try again:' continue print('Operation Successfull') print('Continuing.use ctrl-c to break') break typechar = 0 i_selector = SEL i_host = HOST i_port = PORT if typeexplorer.has_key(typechar): explorerfunc = typeexplorer[typechar] try: explorerfunc(i_selector, i_host, i_port) except (IOError, socket.error): print '***', sys.exc_type, ':', sys.exc_value else: print
def dict_to_string(self, d, level="", res=None, suffix=", ", ljust=None): """Weird routine from couchbase testrunner""" res = res or [] scalars = [] complex = [] for key in d.keys(): if type(d[key]) == DICT_TYPE: complex.append(key) else: scalars.append(key) scalars.sort() complex.sort() # Special case for histogram output. histo_max = 0 histo_sum = 0 if scalars and not complex: for key in scalars: d[key] = float(d[key]) v = d[key] histo_max = max(v, histo_max) histo_sum = histo_sum + v histo_cur = 0 # Running total for histogram output. for key in scalars: try: k = re.sub("0*$", "", "%.7f" % (float(key))) except: k = str(key) if ljust: k = string.ljust(k, ljust) x = d[key] if histo_max: histo_cur = histo_cur + x v = str(x) if histo_max: v = string.rjust(v, 8) v += " " v += string.rjust( "{0:.1%}".format(histo_cur / float(histo_sum)), 8) v += " " v += ("*" * int(math.ceil(50.0 * d[key] / histo_max))) res.append(level + k + ": " + v + suffix) # Recurse for nested, dictionary values. if complex: res.append("\n") for key in complex: res.append(level + str(key) + ":\n") self.dict_to_string(d[key], level + " ", res, "\n", 9) return res
def printTree(tree, num, depth): #num for formatting depth for printing if (num >= 0): print(string.rjust("Lexeme: " + str(tree.category) + ", " + str(tree.value) + ", " + str(depth) + " " * num ,55)) else: print(string.rjust("Lexeme: " + str(tree.category) + ", " + str(tree.value) + ", " + str(depth),55 - num)) if(tree.left != None): #print("LEFT " + str(num)) printTree(tree.left, num + 1, depth + 1) if(tree.right != None): print("RIGHT " + str(depth)) printTree(tree.right, num - 1, depth + 1)
def repr_data(data): '''Print data in a concrete manner.''' longest = 0 for stock in data: for tupl in stock: if len(tupl[0]) > longest: longest = len(tupl[0]) for stock in data: for tupl in stock: print string.rjust(tupl[0] + ':', longest + 1), tupl[1] print
def printAnswer(): sys.stderr.write(str(pattern) + " 探索回数:" + str(count) + "\n") print "探索回数:" + str(count) print "解答表示" for y in (range(8)): for x in (range(8)): if ([x, y] in answer): print string.rjust(str(answer.index([x, y])), 2), else: print "x ", print "" print ""
def __getattr__(self, name): if name.startswith('plus') and name[4:].isdigit(): return self.digit and string.rjust( str(self.value + int(name[4:])), self.digit, '0') or str(self.value + int(name[4:])) elif name.startswith('minus') and name[5:].isdigit(): return self.digit and string.rjust( str(self.value - int(name[5:])), self.digit, '0') or str(self.value - int(name[5:])) else: return self.digit and string.rjust(str(self.value), self.digit, '0') or str(self.value)
def displayTime(screen, time): global endtime, laptime str = string.rjust(fpformat.fix(float(laptime) / 1000, 2), 6) str2 = string.rjust(fpformat.fix(float(time) / 1000, 2), 6) globals.font12x9.blit(str2, screen, (2, 0.5), 80) if endtime != 0: t = pygame.time.get_ticks() - endtime if t > 3000: endtime = 0 globals.font12x9.center("TIME:" + str, screen, 19) globals.font12x9.center(" ", screen, 19, int(255 * (float(t) / 3000)))