我们从Python开源项目中,提取了以下47个代码示例,用于说明如何使用string.uppercase()。
def ex3(argv): password = '' for i in range(len(argv)): for j in range(int(argv[i])): if i == 0: password += string.uppercase[random.randint(0,len(string.uppercase)-1)] elif i == 1: password += string.lowercase[random.randint(0,len(string.lowercase)-1)] elif i == 2: password += string.digits[random.randint(0,len(string.digits)-1)] elif i == 3: password += string.punctuation[random.randint(0,len(string.punctuation)-1)] return ''.join(random.sample(password,len(password)))
def getLogLineBNF(): global logLineBNF if logLineBNF is None: integer = Word( nums ) ipAddress = delimitedList( integer, ".", combine=True ) timeZoneOffset = Word("+-",nums) month = Word(string.uppercase, string.lowercase, exact=3) serverDateTime = Group( Suppress("[") + Combine( integer + "/" + month + "/" + integer + ":" + integer + ":" + integer + ":" + integer ) + timeZoneOffset + Suppress("]") ) logLineBNF = ( ipAddress.setResultsName("ipAddr") + Suppress("-") + ("-" | Word( alphas+nums+"@._" )).setResultsName("auth") + serverDateTime.setResultsName("timestamp") + dblQuotedString.setResultsName("cmd").setParseAction(getCmdFields) + (integer | "-").setResultsName("statusCode") + (integer | "-").setResultsName("numBytesSent") + dblQuotedString.setResultsName("referrer").setParseAction(removeQuotes) + dblQuotedString.setResultsName("clientSfw").setParseAction(removeQuotes) ) return logLineBNF
def detectCapitalUse(self, word): """ :type word: str :rtype: bool """ ud = set(string.uppercase) ld = set(string.lowercase) n = len(word) cap = 0 for c in word: if c in ud: cap += 1 if cap == n: return True if cap == 1 and word[0] in ud: return True return False if cap > 0 else True
def get_species(fullseq, homophobic) : ''' Split a sequence of multiple molecules ('&') into a list: :param: homophobic Choose whether to return homo-dimers or not :return: [(name, seq), (name&name, seq&seq), ...] ''' subseqs = c.OrderedDict.fromkeys(fullseq.split('&')) species = list(string.uppercase[:len(subseqs)]) monomers = zip(species, subseqs) dim = len(monomers) dimers = [] for x in range(dim): for y in range(x, dim): if (homophobic and x == y) : continue (speX, seqX) = monomers[x] (speY, seqY) = monomers[y] dimers.append((speX+'&'+speY, seqX+'&'+seqY)) return monomers + dimers
def encode_name(name, type, scope = None): """ Perform first and second level encoding of name as specified in RFC 1001 (Section 4) """ if name == '*': name = name + '\0' * 15 elif len(name) > 15: name = name[:15] + chr(type) else: name = string.ljust(name, 15) + chr(type) def _do_first_level_encoding(m): s = ord(m.group(0)) return string.uppercase[s >> 4] + string.uppercase[s & 0x0f] encoded_name = chr(len(name) * 2) + re.sub('.', _do_first_level_encoding, name) if scope: encoded_scope = '' for s in string.split(scope, '.'): encoded_scope = encoded_scope + chr(len(s)) + s return encoded_name + encoded_scope + '\0' else: return encoded_name + '\0'
def increment(s): if not s: return '1' for sequence in string.digits, string.lowercase, string.uppercase: lastc = s[-1] if lastc in sequence: i = sequence.index(lastc) + 1 if i >= len(sequence): if len(s) == 1: s = sequence[0]*2 if s == '00': s = '10' else: s = increment(s[:-1]) + sequence[0] else: s = s[:-1] + sequence[i] return s return s # Don't increment
def dump_single(self): checked = self.destination_group.checkedId() if checked == 0: bank = 0x7f prog = 0 elif checked == 1: bank = 0x7f prog = self.multi_spin.value() - 1 else: bank = self.bank_combo.currentIndex() prog = self.prog_spin.value() - 1 res = QtGui.QMessageBox.question(self, 'Dump selected sound', 'You are going to send a sound dump to the Blofeld at location "{}{:03}".\nThis action cannot be undone. Do you want to proceed?'.format(uppercase[bank], prog+1), QtGui.QMessageBox.Ok|QtGui.QMessageBox.Cancel ) if not res == QtGui.QMessageBox.Ok: return row = self.sounds_table.selectedIndexes()[0].row() copy = self.sound_list[row].copy() copy.bank = bank copy.prog = prog self.dump_send.emit(copy)
def exec_(self, sound): self.summary_widget.setSoundData(sound.data) self.editor_chk.setChecked(True) self.store_chk.setChecked(False) self.bank_combo.addItems([uppercase[b] for b in range(self.main.blofeld_library.banks)]) self.dump_sound_lbl.setText(sound.name) if not None in self.main.blofeld_current: bank, prog = self.main.blofeld_current self.bank_combo.setCurrentIndex(bank) self.prog_spin.setValue(prog+1) res = QtGui.QDialog.exec_(self) if not res: return False return self.editor_chk.isChecked(), (self.bank_combo.currentIndex(), self.prog_spin.value()-1) if self.store_chk.isChecked() else False # def resizeEvent(self, event): # self.setFixedSize(self.size())
def __init__(self, main, parent): QtGui.QDialog.__init__(self, parent) load_ui(self, 'dialogs/summary.ui') self.main = main dump_btn = QtGui.QPushButton('Dump') dump_btn.clicked.connect(self.sound_dump) dump_btn.setIcon(self.style().standardIcon(QtGui.QStyle.SP_ArrowRight)) self.buttonBox.addButton(dump_btn, QtGui.QDialogButtonBox.ActionRole) dial_icon = QtGui.QIcon() dial_icon.addFile(local_path('dial_icon.png')) edit_btn = QtGui.QPushButton('Edit') edit_btn.clicked.connect(self.sound_edit) edit_btn.setIcon(dial_icon) self.buttonBox.addButton(edit_btn, QtGui.QDialogButtonBox.AcceptRole) self.bank_combo.addItems([uppercase[l] for l in range(8)]) self.import_btn.clicked.connect(self.open) self.buttonBox.button(QtGui.QDialogButtonBox.Discard).clicked.connect(self.reject) self.summary_widget.setFocus()
def __init__(self, parent): QtGui.QComboBox.__init__(self, parent) self.model = QtGui.QStandardItemModel() self.state_item = QtGui.QStandardItem('all') self.state_item.setEnabled(False) self.model.appendRow(self.state_item) all_item = QtGui.QStandardItem('select all') self.model.appendRow(all_item) none_item = QtGui.QStandardItem('select none') self.model.appendRow(none_item) self.bank_items = [] for i in range(8): item = QtGui.QStandardItem(uppercase[i]) item.setCheckable(True) item.setCheckState(2) item.setTristate(False) self.model.appendRow(item) self.bank_items.append(item) self.setModel(self.model) self.activated.connect(self.check) self.setCurrentIndex(0) self.installEventFilter(self)
def check(self, index): if index == 1: for item in self.bank_items: item.setCheckState(2) self.state_item.setText('all') self.selectionChanged.emit(tuple(range(8))) self.setCurrentIndex(0) return elif index == 2: for item in self.bank_items: item.setCheckState(0) self.state_item.setText('none') self.selectionChanged.emit(()) self.setCurrentIndex(0) return item = self.model.item(index) state = item.checkState() item.setCheckState(state^2) selected = [] for i, item in enumerate(self.bank_items): if not item.checkState(): continue selected.append(i) self.state_item.setText(', '.join(uppercase[i] for i in selected) if selected else 'none') self.selectionChanged.emit(selected) self.setCurrentIndex(0)
def __init__(self, library): self.by_bank = library.data self.by_cat = {i: [] for i in range(len(categories))} self.by_alpha = {l: [] for l in ['0..9']+list(uppercase)}
def dump_send_create(self, dest=None): data = [] for i, attr in enumerate(self.params.iter_attr()): if attr is None: data.append(self.sound.data[i]) else: data.append(getattr(self, attr)) if dest is None: bank, prog = sound.bank, sound.prog elif dest == SMEB: bank, prog = SMEB elif dest == MIEB: #show messagebox? bank, prog = SMEB else: bank, prog = dest res = QtGui.QMessageBox.warning(self, 'Dump sound to Blofeld', 'You are going to send a sound dump to the Blofeld at location "{}{:03}".\nThis action cannot be undone. Do you want to proceed?'.format(uppercase[bank], prog+1), QtGui.QMessageBox.Ok|QtGui.QMessageBox.Cancel ) if res != QtGui.QMessageBox.Ok: return self.dump_send.emit(Sound([bank, prog]+data))
def _targets_to_annotations(self, targets): natural = zip([0, 2, 3, 5, 7, 8, 10], string.uppercase[:7]) sharp = map(lambda v: ((v[0] + 1) % 12, v[1] + '#'), natural) semitone_to_label = dict(sharp + natural + [(12, 'N')]) spf = 1. / self.fps labels = [(i * spf, semitone_to_label[p]) for i, p in enumerate(targets)] # join same consequtive predictions prev_label = (None, None) uniq_labels = [] for label in labels: if label[1] != prev_label[1]: uniq_labels.append(label) prev_label = label # end time of last label is one frame duration after # the last prediction time start_times, chord_labels = zip(*uniq_labels) end_times = start_times[1:] + (labels[-1][0] + spf,) return zip(start_times, end_times, chord_labels)
def soundex(source): "convert string to Soundex equivalent" # Soundex requirements: # source string must be at least 1 character # and must consist entirely of letters if (not source) or (not source.isalpha()): return "0000" # Soundex algorithm: # 1. make first character uppercase # 2. translate all other characters to Soundex digits digits = source[0].upper() + source[1:].translate(charToSoundex) # 3. remove consecutive duplicates digits2 = digits[0] for d in digits[1:]: if digits2[-1] != d: digits2 += d # 4. remove all "9"s # 5. pad end with "0"s to 4 characters return (digits2.replace('9', '') + '000')[:4]
def _get_provider_auth(self): """Get provider authentication for the volume. :return: string of auth method and credentials """ if not self.jovian_chap_auth: return None field = string.lowercase + string.uppercase + string.digits chap_password = ''.join(random.sample(field, int(self.jovian_chap_pass_len))) if self.jovian_chap_username is not None: return '%(auth)s %(user)s %(pass)s' % { 'auth': 'CHAP', 'user': self.jovian_chap_username, 'pass': chap_password } return None
def __init__(self, image_set, devkit_path): imdb.__init__(self, image_set) self._image_set = image_set self._devkit_path = devkit_path self._data_path = self._devkit_path # yeah! self._classes = tuple(['__background__'] + # always index 0 list(string.digits + string.lowercase + string.uppercase)) self._class_to_idx = dict(zip(self.classes, xrange(self.num_classes))) self._image_ext = ['.jpg', '.png'] self._image_index = self._load_image_set_index() self._salt = str(uuid.uuid4()) self._comp_id = 'comp4' self.config = {'cleanup': True, 'use_salt': True, 'top_k': 2000, 'use_diff': False, 'rpn_file': None} assert os.path.exists(self._devkit_path), \ 'Devkit path does not exist: {}'.format(self._devkit_path) assert os.path.exists(self._data_path), \ 'Path does not exist: {}'.format(self._data_path)
def cyclic(self, length = None, n = 4): charset = [] charset += ["ABCDEFGHIJKLMNOPQRSTUVWXYZ"] # string.uppercase charset += ["abcdefghijklmnopqrstuvwxyz"] # string.lowercase charset += ["0123456789"] # string.digits charset[1] = "%$-;" + re.sub("[sn]", "", charset[1]) charset[2] = "sn()" + charset[2] mixed_charset = mixed = '' k = 0 while True: for i in range(0, len(charset)): mixed += charset[i][k:k+1] if not mixed: break mixed_charset += mixed mixed = '' k+=1 pattern = self.de_bruijn(mixed_charset, 3, length) return pattern
def int_to_alphabetic(number): """Convert non-negative integer to base 26 representation using uppercase A-Z as symbols. Can use this instead of numbers in feature delimiters because: -- gives shorter full context model names (esp. with many features) -- trivially, split-context-balanced.py expects delimiters to contain no digits """ assert number >= 0,"Function not intended to handle negative input values" if number == 0: return string.uppercase[0] alphabetic = "" current = number while current!=0: remainder = current % 26 remainder_string = string.uppercase[remainder] alphabetic = remainder_string + alphabetic current = current / 26 return alphabetic
def setPageCounter(counter=None, style=None): global _counter, _counterStyle if counter is not None: _counter = counter if style is not None: _counterStyle = style if _counterStyle=='lowerroman': ptext=toRoman(_counter).lower() elif _counterStyle=='roman': ptext=toRoman(_counter).upper() elif _counterStyle=='alpha': ptext=string.uppercase[_counter%26] elif _counterStyle=='loweralpha': ptext=string.lowercase[_counter%26] else: ptext=unicode(_counter) return ptext
def random_str(n=8): allow = list(string.uppercase + string.digits) r = [] for i in range(n): r.append(random.choice(allow)) return ''.join(r) # return ''.join(random.sample(allow, n)) # ??ssdb_008.py ???????????
def is_interface_enum(enumtype): return not (enumtype[0] in string.uppercase and enumtype[2] in string.uppercase)
def _do_first_level_encoding(m): s = ord(m.group(0)) return string.uppercase[s >> 4] + string.uppercase[s & 0x0f]
def makePSFontName(name): """Create a postscript filename out of a regular postscript fontname, using the old fashioned macintosh 5:3:3 convention. """ import string parts = [] current = [] final = [] notAllowed = '-_+=,-' index = 0 for c in name: if c in notAllowed: continue if c in string.uppercase or index == 0: c = string.upper(c) if current: parts.append("".join(current)) current = [c] else: current.append(c) index = index + 1 if current: parts.append("".join(current)) final.append(parts[0][:5]) for p in parts[1:]: final.append(p[:3]) return "".join(final) # # # # stuff for glyphs # # #
def random_password(self): import string import random password = '' specials = r'!#$*' for i in range(0, 3): password += random.choice(string.lowercase) password += random.choice(string.uppercase) password += random.choice(string.digits) password += random.choice(specials) return ''.join(random.sample(password, len(password)))
def test_attrs(self): string.whitespace string.lowercase string.uppercase string.letters string.digits string.hexdigits string.octdigits string.punctuation string.printable
def set_accounts(_acc): f = shelve.open(STORE) _out = {} for k,v in _acc.items(): _out[k] = v if '#' in v['instrument']: _out[k]['instrument'] = '#' elif '@' in v['instrument']: _out[k]['instrument'] = '@' else: _instrument = v['instrument'].split('+') _instrument.sort(reverse=True) if '' in _instrument: _pos = _instrument.index('') _instrument = _instrument[:_pos] _list = [] for one in _instrument: if '=' in one: one = filter(lambda x:x in _chars+_CHARS,one)+'=' _list.append(one) else: _list.append(one) _out[k]['instrument'] = '+'.join(_list) f['accounts'] = _out f.close() start_accounts(get_accounts())
def make_random_string(length): return ''.join(choice(lowercase + uppercase + digits) for _ in range(length))
def num_capitals(entity): capital=[] for line in entity: capital.append(len(filter(lambda x: x in string.uppercase, line[2]))) return sum(capital)
def compute_metrics(self): self.font_metrics = QtGui.QFontMetrics(self.font) cat = max([self.font_metrics.width(c) for c in digits+uppercase])*4 + self.font_metrics.width(' ') name = max([self.font_metrics.width(c) for c in self.chars])*16 + self.spacing self.prog_size = cat+name
def compute(self, cols=1, vertical=False): text = 'Blofeld preset list:\n\n' for b, bank in enumerate(self.main.blofeld_library.data): if b not in self.bank_selection: continue sounds = [] for sound in bank: sounds.append('{}{:03}\t{}'.format(uppercase[sound.bank], sound.prog+1, sound.name)) if sounds: text += 'Bank {}:\n=======\n'.format(uppercase[sound.bank]) if cols == 1: text += '\n'.join(sounds) else: if vertical: div = len(sounds)/cols if div*cols < len(sounds): div += 1 for d in range(div): for col in range(cols): try: text += sounds[d + div*col] if col == cols-1: text += '\n' else: text += '\t\t' except: text += '\n' break else: col = 0 for txt in sounds: text += txt col += 1 if col == cols: text += '\n' col = 0 else: text += '\t\t' text += '\n\n' self.text = text
def checkout(self): invalid = [] for i, (param, value) in enumerate(zip(Params, self._data)): if param.range == 'reserved': continue if isinstance(param.values, AdvParam): # if value & param.values.forbidden: # print 'FORBIDDEN! {}{:03} "{}" {}: {:07b} {:07b}'.format(uppercase[self.bank], self.prog, self.name, param.attr, param.values.forbidden, value) res = param.values.is_valid(value) if res is not True: invalid.append((i, res)) continue p_min, p_max = param.range[:-1] if not p_min <= value <= p_max: invalid.append(i) return invalid if invalid else None