def developAttribute(attribute): developpedList = [] code = "" developpedList.append(attribute.lower()) m = re.search('du code',attribute) if m is not None: art = attribute[:m.start()] code = attribute[m.start()+3:] developpedList.append(code.lower()) if attribute[1] == " ": ind = art.rfind('-') while(ind!=-1): art = art[:ind] developpedList.append(art+" du "+code) ind = art.rfind('-') #print attribute,code.lower() if attribute[2] == "0": livre = "Livre 0 du "+code else: livre = "Livre "+roman.toRoman(int(attribute[2]))+" du "+code developpedList.append(livre.lower()) if attribute[3].isdigit(): if attribute[3] == "0": titre = "Titre 0 du "+livre else: titre = "Titre "+roman.toRoman(int(attribute[3]))+" du "+livre developpedList.append(titre.lower()) return developpedList
def get_next (self): """ Get the next label. """ if self.type == 'none': res = '' elif self.type == '*': res = u'•' if self.encoding == 'utf-8' else '-' elif self.type == '-': res = u'-' elif self.type == '+': res = u'+' elif self.type == 'arabic': res = "%d" % self.start elif self.type == 'loweralpha': res = "%c" % (self.start + ord ('a') - 1) elif self.type == 'upperalpha': res = "%c" % (self.start + ord ('A') - 1) elif self.type == 'upperroman': res = roman.toRoman (self.start).upper () elif self.type == 'lowerroman': res = roman.toRoman (self.start).lower () else: res = "%d" % self.start self.start += 1 return self.prefix + res + self.suffix
def ResolutionInfo(ownerId, resolutionId, englishResolution, spanishResolution, committeeId, status, index, topic, comments, assigneeId, originalAssigneeId, committeeAbbreviationEnglish, committeeAbbreviationSpanish): englishTag = "%s/%s/%s%d" % (committeeAbbreviationEnglish, toRoman(topic, True), "DRAFT" if isDraft(status) else "", index) spanishTag = "%s/%s/%s%d" % (committeeAbbreviationSpanish, toRoman(topic, True), "PREL" if isDraft(status) else "", index) return {"ownerId": ownerId, "resolutionId": resolutionId, "englishResolution": englishResolution, "spanishResolution": spanishResolution, "committeeId": committeeId, "status": status, "index": index, "topic": topic, "comments": comments, "assigneeId": assigneeId, "originalAssigneeId": originalAssigneeId, "englishTag": englishTag, "spanishTag": spanishTag}
def test_to_roman(integer, numeral): """docstring which starts at the left""" d = [1,2, 3, 4] print integer, numeral, roman.toRoman(integer) print "this line takes 2 %s lines" \ % 'long' assert roman.toRoman(integer) == numeral
def romanize(src, args=None): # Check if instance is int or long if isinstance(src, int) or isinstance(src, long): if args != None: # If args is 'lowercase' return lowercased roman numerical if args.lower() == 'lowercase': return toRoman(src).lower() # Return the roman numerical equivalent return toRoman(src) else: # src wasn't int or long so we just return it return src
def generate_id(counter, depth, separator=".", prefix="part-", suffix=""): o = [] i = depth while i >= 1: o.append(counter[i]) i -= 1 if current_level == 0: return prefix + roman.toRoman(articles[current_level]).lower() elif args.parts: return prefix + roman.toRoman(articles[0]).lower() + '-' + separator.join([id_str(x, n, separator) for n, x in enumerate(reversed(o))]) + suffix else: return separator.join([id_str(x, n, separator) for n, x in enumerate(reversed(o))]) + suffix
def testSanity(self): """fromRoman(toRoman(n)) == n for all n""" for integer in range(1, 5000): numeral = roman.toRoman(integer) result = roman.fromRoman(numeral) self.assertEqual(integer, result)
def get_urls(self): """ Returns a list of URLs to scrape """ # This predefined list of URLs is chosen to include all types of # inquiries possible in the Austrian parliament in order to provide a # suitable testing surface for new functions. # urls = ["https://www.parlament.gv.at/PAKT/VHG/XXV/JPR/JPR_00019/index.shtml", "https://www.parlament.gv.at/PAKT/VHG/XXV/JPR/JPR_00016/index.shtml", "https://www.parlament.gv.at/PAKT/VHG/XXV/J/J_06954/index.shtml", "https://www.parlament.gv.at/PAKT/VHG/XXV/M/M_00178/index.shtml", "https://www.parlament.gv.at/PAKT/VHG/XXV/JEU/JEU_00003/index.shtml", "https://www.parlament.gv.at/PAKT/VHG/XXV/J/J_06758/index.shtml", "https://www.parlament.gv.at/PAKT/VHG/BR/J-BR/J-BR_03089/index.shtml", # "https://www.parlament.gv.at/PAKT/VHG/BR/J-BR/J-BR_03091/index.shtml", "http://www.parlament.gv.at/PAKT/VHG/BR/J-BR/J-BR_01155/index.shtml", "http://www.parlament.gv.at/PAKT/VHG/XX/J/J_06110/index.shtml", "http://www.parlament.gv.at/PAKT/VHG/XX/J/J_06651/index.shtml", "http://www.parlament.gv.at/PAKT/VHG/XX/J/J_04024/index.shtml", "http://www.parlament.gv.at/PAKT/VHG/XX/J/J_04025/index.shtml", "https://www.parlament.gv.at/PAKT/VHG/XX/M/M_00178/index.shtml"] urls = [] if self.LLP: for i in self.LLP: for nrbr in ['NR', 'BR']: roman_numeral = roman.toRoman(i) options = self.URLOPTIONS.copy() options['GP'] = roman_numeral options['NRBR'] = nrbr url_options = urlencode(options) url_llp = "{}?{}".format(self.BASE_URL, url_options) rss = feedparser.parse(url_llp) print "GP {}: {} inquiries from {} [{}]".format( roman_numeral, len(rss['entries']), nrbr, url_llp) urls = urls + [entry['link'] for entry in rss['entries']] return urls
def page_index_to_page_number_string (self, page_index): pn = self.get_page_numbering() if (type(pn) == types.IntType): return str(pn + page_index) elif (type(pn) == types.ListType): for pagerange, numbering_type, fpn in pn: first_page = pagerange[0] if len(pagerange) > 1: last_page = pagerange[1] else: last_page = pagerange[0] if (page_index >= first_page) and (page_index <= last_page): if numbering_type == 'b': return "" elif numbering_type == 'd': return str(page_index - first_page + fpn) elif numbering_type == 'r': # roman numeral value = page_index - first_page + fpn from roman import toRoman return toRoman(value).lower() else: return "" return "" else: note("document %s: bad page numbering %s", self.id, pn) self.__pagenumbering = 1 return str(page_index + 1)
def get_urls(self): """ Returns a list of URLs to scrape """ urls = [] # NR comittees are LLP based if self.LLP: for i in self.LLP: roman_numeral = roman.toRoman(i) options = self.URLOPTIONS.copy() options['GP'] = roman_numeral options['NRBR'] = 'NR' url_options = urlencode(options) url_llp = "{}?{}".format(self.BASE_URL, url_options) rss = feedparser.parse(url_llp) print "GP {}: NR: {} Comittees".format( roman_numeral, len(rss['entries'])) urls = urls + [entry['link'] for entry in rss['entries']] # AKT = aktiv, AUF = aufgeloest for aktauf in ['AKT', 'AUF']: options['NRBR'] = 'BR' options['R_AKTAUF'] = aktauf url_options = urlencode(options) url_br = "{}?{}".format(self.BASE_URL, url_options) rss = feedparser.parse(url_br) print "BR {}: {} Comittees".format( aktauf, len(rss['entries'])) urls = urls + [entry['link'] for entry in rss['entries']] return urls
def testFromRomanCase(): """fromRoman should only accept uppercase input""" for integer in range(1, 5000): numeral = roman.toRoman(integer) roman.fromRoman(numeral.upper()) with pytest.raises(roman.InvalidRomanNumeralError): roman.fromRoman(numeral.lower())
def les_republicains(self, msg): today = date.today() # find the current month in republican calendar current_republican_month = '' for month, bounds in months.items(): start = date(today.year, bounds[1], bounds[0]) end = date(today.year, bounds[3], bounds[2]) if start <= today <= end: current_republican_month = month current_month_start = start break # list the days of the current month until we find the right one date_republican = current_month_start current_republican_day = '' for day, day_name in enumerate(days.get(current_republican_month, [])): if date_republican == today: current_republican_day = day_name break date_republican += timedelta(days=1) # compute the year if today >= date(today.year, 9, 22): # republican calendar starts on 22th september 1792 current_republican_year = today.year - 1791 else: current_republican_year = today.year - 1792 msg.reply("Nous sommes le {} {} an {} ({})".format( day + 1, # days start on 1 current_republican_month, roman.toRoman(current_republican_year), current_republican_day # day name ))
def get_max_length_roman(first, last, increment): max_length = 0 current_num = int(first) run_loop = True while run_loop == True: roman_str = roman.toRoman(current_num) length = len(roman.toRoman(current_num)) if max_length < length: max_length = length current_num += int(increment) run_loop = continue_loop(current_num, last, increment) return max_length
def get_urls(self): """ Returns a list of URLs to scrape """ urls = [] if self.LLP: for i in self.LLP: for nrbr in ['NR', 'BR']: for bbet in ['BI', 'PET', 'PET-BR', 'VOLKBG']: roman_numeral = roman.toRoman(i) options = self.URLOPTIONS.copy() options['GP'] = roman_numeral options['NRBR'] = nrbr options['BBET'] = bbet url_options = urlencode(options) url_llp = "{}?{}".format(self.BASE_URL, url_options) rss = feedparser.parse(url_llp) print "GP {}: {}: {} {}".format( roman_numeral, nrbr, len(rss['entries']), bbet) urls = urls + [entry['link'] for entry in rss['entries']] self.TOTAL_COUNTER = len(urls) return urls
def RomanOrRounded(value, rounding, convert=True): """Try to round the value to the closest integer and return it as a roman numeral. If the conversion is disabled, or if the roman module could not be loaded, round the value to the specified level and return it. @type value: number @param value: value to convert @type rounding: integer @param rounding: how many decimal digits the number should be rounded to @type convert: boolean @param convert: if False, don't try conversion at all @rtype: string @return: roman numeral for val, or formatted string representing val if conversion didn't succeed """ def _FormatOutput(val, r): format_string = "%0." + str(r) + "f" return format_string % val if roman is not None and convert: try: return roman.toRoman(round(value, 0)) except roman.RomanError: return _FormatOutput(value, rounding) return _FormatOutput(value, rounding)
def testFromRomanCase(self): """fromRoman should only accept uppercase input""" for integer in range(1, 4000): numeral = roman.toRoman(integer) roman.fromRoman(numeral.upper()) self.assertRaises(roman.InvalidRomanNumeralError, roman.fromRoman, numeral.lower())
def _peptide_header_display_data(self, vaccine_peptide, rank): """ Returns a dictionary with info used to populate the header section of a peptide table. Parameters ---------- vaccine_peptide : VaccinePeptide The given peptide to convert to display form rank : int Rank of vaccine peptide in list """ mutant_protein_fragment = vaccine_peptide.mutant_protein_fragment amino_acids = mutant_protein_fragment.amino_acids mutation_start = mutant_protein_fragment.mutant_amino_acid_start_offset mutation_end = mutant_protein_fragment.mutant_amino_acid_end_offset aa_before_mutation = amino_acids[:mutation_start] aa_mutant = amino_acids[mutation_start:mutation_end] aa_after_mutation = amino_acids[mutation_end:] header_display_data = { 'num': roman.toRoman(rank + 1).lower(), 'aa_before_mutation': aa_before_mutation, 'aa_mutant': aa_mutant, 'aa_after_mutation': aa_after_mutation, } return header_display_data
def get_level_index(lvl, indx): if lvl % 3 == 0: return u'%d' % indx if lvl % 3 == 1: return [u'', u'a', u'b', u'c', u'd', u'e', u'f', u'g', u'h', u'j', u'k', u'l', u'm', u'n', u'o', u'p', u'q', u'r', u's', u't', u'v', u'w', u'x', u'y', u'z'][indx] if lvl % 3 == 2: return toRoman(indx, False)
def __init__(self, **kw): super(StatementSpider, self).__init__(**kw) if 'type' in kw and kw['type'] in self.DEBATETYPES: self.DEBATETYPES = [kw['type']] if 'llp' in kw and kw['llp'] != 'all': try: self.LLP = [roman.toRoman(int(kw['llp']))] except: self.LLP = [kw['llp']] else: self.LLP = [roman.toRoman(llp) for llp in self.ALLOWED_LLPS] self.SNR = kw['snr'] if 'snr' in kw else None self.start_urls = [self.BASE_URL]
def romanize_filter(value, to_upper=True): """ Change int or long into Roman Numeral Usage: {{ object.id|romanize:to_upper }} After: integer turned to roman numeral """ if isinstance(value, int) or isinstance(value, long): if value == 0: return "0" else: if to_upper: return toRoman(value) else: return toRoman(value).lower() else: return value
def get_urls(): urls = [] for i in LLP: roman_numeral = roman.toRoman(i) rss = feedparser.parse(get_laws_url(roman_numeral)) print "GP {}: {} laws".format(roman_numeral, len(rss['entries'])) urls = urls + [entry['link'] for entry in rss['entries']] return urls
def to_roman(number): """ Converts an arabic number within range from 1 to 4999 to the corresponding roman number. Returns None on error conditions. """ try: return roman.toRoman(number) except (roman.NotIntegerError, roman.OutOfRangeError): return None
def romanize_filter(value, args=None): """Change int or long into Roman Numeral all other types are passed out You can add an argument like this: ... {{ object.id|romanize:"upper" }} ... For upper case roman numerals. The tag defaults to lowercase numerals for no good reason other than I prefer the look of them.""" if isinstance(value, int) or isinstance(value, long): if args is not None: if args.lower() == "upper": return toRoman(value) else: return toRoman(value).lower() else: return toRoman(value).lower() else: return value
def to_roman(number: int) -> str: """ Converts an arabic number within range from 1 to 4999 to the corresponding roman number. Returns the input converted as string on error conditions or higher numbers. """ try: return roman.toRoman(number) except (roman.NotIntegerError, roman.OutOfRangeError): return str(number)
def subroman(match): import roman try: groupdict = match.groupdict() num = int(groupdict['num']) if num == 0: return '' return roman.toRoman(num) except Exception as ex: util_dbg.printex(ex, keys=['groupdict']) raise
def fix_media(textBufferArray, directory_prepend, footnotes_roman, footnote_title, citations_title): text_holder = [] # try not writing an overly-greedy regex if you don't want to lose text! footnote_format = re.compile("(.*)(\[\^)(\d+)(\])") citation_format = re.compile("(.*)(\[@)(.+?)(\])") graphics_link = re.compile("(!\[.*?\])(\(graphics)(.*?\))") for line in textBufferArray: if footnote_format.match(line): # instead of rewriting in a separate function, just get the match object and use it here footnote_iter = footnote_format.finditer(line) foot_holder = [] for match in footnote_iter: theNumber = match.group(3) if footnotes_roman == "True": theNumber = toRoman(int(match.group(3))) foot_frag = match.group(1)+"<sup>["+theNumber+"]("+directory_prepend+footnote_title+"/README.html)</sup>" foot_holder.append(foot_frag) foot_holder.append(line[match.end():]) line = "".join(foot_holder) if citation_format.match(line): # instead of rewriting in a separate function, just get the match object and use it here citation_iter = citation_format.finditer(line) new_holder = [] for match in citation_iter: #print match.group(1) line_frag = match.group(1)+"<sup><a href="+directory_prepend+citations_title+"/index.html>"+str(citation_counter)+"</a></sup>" new_holder.append(line_frag) global citation_counter citation_counter+=1 new_holder.append(line[match.end():]) line = "".join(new_holder) if graphics_link.match(line): # instead of rewriting in a separate function, just get the match object and use it here #print(line) graphics_matchObj = graphics_link.match(line) line = graphics_matchObj.group(1)+"("+directory_prepend+"graphics"+graphics_matchObj.group(3) # while we're at it, we might as well get real newlines into our footnote sections line = re.sub(r"\\\n", "\n\n", line) text_holder.append(line) return text_holder
def make_initial_plot(fig, valences): fig.clf() ax = fig.add_subplot(111) h, b = numpy.histogram(valences, bins=100, range=[0.0, 2*cation_valence]) width = b[1] - b[0] x = b[1:] - width/2.0 ax.bar(x, h, width=width) ax.set_xlim([0.0, 2*cation_valence]) ax.set_xlabel("bond valence sum $V_i$", fontsize=plot_labelsize) ax.set_ylabel("number of binding sites", fontsize=plot_labelsize) ax.text(1.5*cation_valence, 0.95*max(h), "%s(%s)" % (cation_element,roman.toRoman(cation_valence)), fontsize=32) return x, h
def get_page_number(self, index): """ Given an index, return page label as specified by catalog['PageLabels']['Nums'] Nums == [ 0 << /S /r >> 4 << /S /D >> 7 << /S /D /P (A−) /St 8>> ] /S = [ D Decimal arabic numerals R Uppercase roman numerals r Lowercase roman numerals A Uppercase letters (A to Z for the first 26 pages, AA to ZZ for the next 26, and so on) a Lowercase letters (a to z for the first 26 pages, aa to zz for the next 26, and so on) ] (if no /S, just use prefix ...) /P = text string label /St = integer start value """ try: nums = resolve1(self.catalog['PageLabels'])['Nums'] # e.g. [ 0 {settings} 2 {settings} 20 # {settings} ...] assert len(nums) > 1 and len(nums) % 2 == 0 except: return "" for i in range(len(nums)-2,-1,-2): # find highest page number lower than requested page if nums[i] <= index: break settings = nums[i+1].resolve() page_num = "" if 'S' in settings: # show a digit page_num = index - nums[i] if 'St' in settings: # alternate start value page_num += settings['St'] else: page_num += 1 num_type = settings['S'].name if num_type.lower() == 'r': # roman (upper or lower) import roman page_num = roman.toRoman(page_num) if num_type == 'r': page_num = page_num.lower() elif num_type.lower() == 'a': # letters # a to z for the first 26 pages, aa to zz for the next 26, and so on letter = chr(page_num % 26 + 65) letter *= page_num / 26 + 1 if num_type == 'a': letter = letter.lower() page_num = letter else: #if num_type == 'D': # decimal arabic page_num = unicode(page_num) if 'P' in settings: # page prefix page_num = settings['P']+page_num return page_num
def metadata(self): title = self.recording.work.pretty_title(show_year=False) if self.recording.movements.count() > 1: title += u" - %s. %s" % (roman.toRoman(self.num), self.title) title += u" (%s)" % self.recording.short_name() return { 'date': str(self.recording.year) or '', 'title': title, 'artist': u"%s" % self.recording.work.composer, 'genre': 'Classical', 'tracknumber': str(self.num), }
def generate_document(res, lang, topic_name, committee_salutation_name, committee_abbr, res_index, topic_index, isDraft, sponsors): salutation = u'<text:p text:style-name="preams"><text:span text:style-name="clause_keyword">%s,</text:span></text:p>' % committee_salutation_name preams_outline = string.join([u'<text:p text:style-name="preams"><text:span text:style-name="clause_keyword">%s </text:span><text:span text:style-name="clause_body">%s,</text:span></text:p>' % (clause["keyword"], clause["content"]) for clause in res["preambulars"]], u'\n') max_level = -1 last_level = -1 current_indices = [] ops = [] for idx, clause in enumerate(res["operatives"]): for i in range(len(current_indices), clause["level"] + 1): current_indices.append(1) if last_level > clause["level"]: current_indices = current_indices[:clause["level"] + 1] current_indices[clause["level"]] += 1 elif last_level == clause["level"]: current_indices[clause["level"]] += 1 last_level = clause["level"] if last_level > max_level: max_level = last_level index = current_indices[last_level] if clause["level"] == 0: ops.append(u'<text:p text:style-name="ops-%d">%s. <text:span text:style-name="clause_keyword">%s </text:span><text:span text:style-name="clause_body">%s%s</text:span></text:p>' % (clause["level"], get_level_index(clause["level"], index), clause["keyword"], clause["content"], get_op_separator(res["operatives"], idx))) else: ops.append(u'<text:p text:style-name="ops-%d">%s. <text:span text:style-name="clause_body">%s%s</text:span></text:p>' % (clause["level"], get_level_index(clause["level"], index), clause["content"], get_op_separator(res["operatives"], idx))) ops_outline = string.join(ops, u'\n') styles = u'<style:style style:family="text" style:name="clause_keyword"><style:text-properties fo:font-style="italic" style:font-name-complex="Times New Roman"/></style:style>\n<style:style style:family="text" style:name="clause_body"><style:text-properties fo:font-style="normal" style:font-name-complex="Times New Roman"/></style:style>\n<style:style style:family="paragraph" style:name="preams"><style:paragraph-properties fo:margin-left="0.5in" fo:margin-bottom="0.14in"/></style:style>' styles += string.join([u'<style:style style:family="paragraph" style:name="ops-%d"><style:paragraph-properties fo:margin-left="%fin" fo:margin-bottom="0.14in"/></style:style>' % (idx, 0.5 * (idx + 1)) for idx in range(max_level + 1)], u'\n') if lang == ENGLISH: sponsors = [{"name": s["englishName"], "longName": s["englishLongName"]} for s in sponsors] elif lang == SPANISH: sponsors = [{"name": s["spanishName"], "longName": s["spanishLongName"]} for s in sponsors] #FIXME: need two separate names for sponsors (one for sort order and one for full name) ??? names = [s["longName"] for s in sorted(sponsors, key=lambda d: d["name"])] countries = string.join(names, ', ') tagline = u'%s/%s/%s%d' % (committee_abbr, toRoman(topic_index, True), get_str('DRAFT', lang) if isDraft else u'', res_index) templateValues = { 'styles': styles, 'azmun': get_str('ARIZONA_MODEL_UNITED_NATIONS', lang), 'st': get_str('ST', lang), 'annual_conference': get_str('ANNUAL_CONFERENCE', lang), 'tagline': tagline, 'subj_of': get_str('TOPIC_OF', lang), 'sub_to': get_str('SUBMITTED_TO', lang), 'sub_by': get_str('SUBMITTED_BY', lang), 'outline': u'%s\n%s\n%s' % (salutation, preams_outline, ops_outline), 'topic': topic_name, 'committee': committee_salutation_name, 'countries': countries } return template.render('2013/template.fodt', templateValues)
def __str__(self): strval = roman.toRoman(self._val) if self._case == 'lower': return strval.lower() else: return strval
def get_page_number(self, index): """ Given an index, return page label as specified by catalog['PageLabels']['Nums'] In a PDF, page labels are stored as a list of pairs, like [starting_index, label_format, starting_index, label_format ...] For example: [0, {'S': 'D', 'St': 151}, 4, {'S':'R', 'P':'Foo'}] So we have to first find the correct label_format based on the closest starting_index lower than the requested index, then use the label_format to convert the index to a page label. Label format meaning: /S = [ D Decimal arabic numerals R Uppercase roman numerals r Lowercase roman numerals A Uppercase letters (A to Z for the first 26 pages, AA to ZZ for the next 26, and so on) a Lowercase letters (a to z for the first 26 pages, aa to zz for the next 26, and so on) ] (if no /S, just use prefix ...) /P = text string label /St = integer start value """ # get and cache page ranges if not hasattr(self, 'page_range_pairs'): try: page_ranges = resolve1(self.catalog['PageLabels'])['Nums'] assert len(page_ranges) > 1 and len(page_ranges) % 2 == 0 self.page_range_pairs = list( reversed(list(zip(page_ranges[::2], page_ranges[1::2])))) except: self.page_range_pairs = [] if not self.page_range_pairs: return "" # find page range containing index for starting_index, label_format in self.page_range_pairs: if starting_index <= index: break # we found correct label_format label_format = resolve1(label_format) page_label = "" # handle numeric part of label if 'S' in label_format: # first find number for this page ... page_label = index - starting_index if 'St' in label_format: # alternate start value page_label += label_format['St'] else: page_label += 1 # ... then convert to correct format num_type = label_format['S'].name # roman (upper or lower) if num_type.lower() == 'r': import roman page_label = roman.toRoman(page_label) if num_type == 'r': page_label = page_label.lower() # letters elif num_type.lower() == 'a': # a to z for the first 26 pages, aa to zz for the next 26, and # so on letter = chr(page_label % 26 + 65) letter *= page_label / 26 + 1 if num_type == 'a': letter = letter.lower() page_label = letter # decimal arabic else: # if num_type == 'D': page_label = obj_to_string(page_label) # handle string prefix if 'P' in label_format: page_label = label_format['P'] + page_label return page_label
def __get_context_data(self): if 'journal_id' in self.kwargs: journal = get_object_or_404(Journal, id=self.kwargs['journal_id']) character = journal.game_attendance.attending_character game_id = journal.game_attendance.relevant_game.id else: character = get_object_or_404(Character, id=self.kwargs['character_id']) game_id = self.kwargs[ 'game_id'] if 'game_id' in self.kwargs else None viewer_can_write = character.player_can_edit(self.request.user) completed_attendances = character.completed_games() cover = get_object_or_none(JournalCover, character=character) journal_pages = [] cover_id = "journal_page_cover" journal_page = { "header": "cover", "id": cover_id, "empty": False, "cover": cover if cover else { "title": "", "content": "" }, } journal_pages.append(journal_page) for i, attendance in enumerate(completed_attendances, start=1): if attendance.is_death(): continue journal_page = { "header": roman.toRoman(i), "game": attendance.relevant_game, "id": "journal_page_{}".format(attendance.relevant_game.id), "game_journal": None, "downtime_journals": [], "empty": False, } journals = attendance.journal_set.filter(is_deleted=False) if journals.count() == 0: if viewer_can_write: journal_page["empty"] = True journal_pages.append(journal_page) else: game_journal = get_object_or_none(Journal, game_attendance=attendance, is_deleted=False, is_downtime=False) if game_journal: game_journal.inject_viewable(self.request.user) journal_page["game_journal"] = game_journal journal_page["downtime_journals"] = journals.filter( is_downtime=True).order_by("created_date").all() for journal in journal_page["downtime_journals"]: journal.inject_viewable(self.request.user) journal_pages.append(journal_page) death = character.real_death() if death: journal_page = { "header": "death", "game": death.game_attendance.relevant_game if hasattr(death, 'game_attendance') and death.game_attendance else None, "id": "journal_page_death", "game_journal": None, "downtime_journals": [], "empty": False, "death": death, } journal_pages.append(journal_page) prev_page = None for journal_page in journal_pages: if prev_page: prev_page['next_id'] = journal_page['id'] journal_page['prev_id'] = prev_page['id'] prev_page = journal_page num_journals_until_improvement = Journal.get_num_journals_until_improvement( character) if viewer_can_write else 0 next_reward_is_improvement = num_journals_until_improvement <= 1 context = { 'view_game_id': "journal_page_{}".format(game_id) if game_id else cover_id, 'character': character, 'viewer_can_write': viewer_can_write, 'journal_pages': journal_pages, 'next_reward_is_improvement': next_reward_is_improvement, 'num_journals_until_improvement': num_journals_until_improvement, } return context
def abbreviation(self) -> str: return roman.toRoman(self.column).lower()
def __enumber(self, file, operation): numberStyle = operation.numberingPanel.Style numberParams = operation.numberingPanel.Params start = numberParams[0] count = numberParams[1] reset = numberParams[2] dirReset = numberParams[3] countByDir = numberParams[4] repeat = numberParams[5] maxNumb = numberParams[6] incrementOnDiff = numberParams[7] lastDir = main.lastDir curDir = main.curDir lastName = main.lastName curName = main.curName maxNumb = abs((len(main.items) + (start - 1)) * count) if repeat > 0: maxNumb = maxNumb / (repeat + 1) # to reset count by directory if lastDir != curDir and lastDir is not False and dirReset: self.counter = 0 if lastDir != curDir and lastDir is not False and countByDir: self.counter += 1 # to reset by identical name if incrementOnDiff and curName is not False and lastName != curName: self.counter = 0 # calculate current number based on user settings: i = start + (self.counter * int(count)) # numerical counting: if numberStyle[0] == u'digit': padChar = unicode(numberStyle[1]) # padding enabled and non-empty pad charcter: if numberStyle[3] and padChar: if numberStyle[2] == u'auto': padWidth = len(unicode(maxNumb)) y = unicode(i).rjust(padWidth, padChar) else: y = unicode(i).rjust(int(numberStyle[2]), padChar) # no padding: else: y = i # alphabetical numbering: elif numberStyle[0] == u'alpha': i = abs(i) if i == 0: i = 1 y = self.__to_alpha(i) # uppercase if numberStyle[1]: y = y.upper() # roman numerals elif numberStyle[0] == u'roman': try: y = roman.toRoman(i) if not numberStyle[1]: y = y.lower() except: if main.bad.count(main.ec) < 1: main.bad.append(main.ec) main.errorLog.insert( 0, (main.ec, file, _(u"Roman numeral error: %s") % sys.exc_info()[1], u'bad')) y = "" def increment_reset_count(): # see if count is at reset level: if self.counter == reset and self.counter != 0: self.counter = 0 elif not countByDir: self.counter += 1 # repeat the same number if repeat > 0: if self.auxCount == repeat: increment_reset_count() self.auxCount = 0 elif self.auxCount < repeat: self.auxCount += 1 else: self.auxCount = 0 else: increment_reset_count() return unicode(y)
return a def param(param_list): def decorator(func): def yielder(): for params in param_list: yield (func,) + params return yielder return decorator def test_to_roman(integer, numeral): """docstring which starts at the left""" d = [1,2, 3, 4] print integer, numeral, roman.toRoman(integer) print "this line takes 2 %s lines" \ % 'long' test_to_roman = test(param(known_values)(test_to_roman)) assert roman.toRoman(integer) == numeral class testing123: def wtf(): print "yyyo" wtf = test(wtf) for i in test_to_roman(): #how in the world is this supposed to be used? i[0](i[1], i[2].upper()) print "passed"
def title(self): if self.name is None: offset = the_algorithm.ps_offset_from_date(self.date) return 'Pub Standards ' + roman.toRoman(offset) return self.name
def roman_release_year(self): return roman.toRoman(self.release_year)
#!/usr/bin/python3 # Challenge 010 # # Challenge #1 # Write a script to encode/decode Roman numerals. For example, given Roman # numeral CCXLVI, it should return 246. Similarly, for decimal number 39, it # should return XXXIX. Checkout wikipedia page for more information. import sys import roman if len(sys.argv)==2: if sys.argv[1]=="-test": for i in range(1, 3001): s = roman.toRoman(i) n = roman.fromRoman(s) if i!=n: print(f"{i} => {s} => {n}") sys.exit(1) elif sys.argv[1].isdigit(): n = int(sys.argv[1]) s = roman.toRoman(n) print(f"{n} => {s}") else: s = sys.argv[1] n = roman.fromRoman(s) print(f"{s} => {n}")
def testToRomanKnownValues(self): """toRoman should give known result with known input""" for integer, numeral in self.knownValues: result = roman.toRoman(integer) self.assertEqual(numeral, result)
def testSanity(self): """fromRoman(toRoman(n))==n for all n""" for integer in range(1, 5000): numeral = roman.toRoman(integer) result = roman.fromRoman(numeral) self.assertEqual(integer, result)
def testToRomanCase(self): """toRoman should always return uppercase""" for integer in range(1, 5000): numeral = roman.toRoman(integer) self.assertEqual(numeral, numeral.upper())
def xt(cls, response): mandates_raw = response.xpath(cls.XPATH).extract() mandates = [] for mandate in mandates_raw: mandate = _clean(remove_tags(mandate, 'li')) if "<div" in mandate and "</div>" in mandate: mandate = _clean(remove_tags( Selector(text=mandate).xpath("//div").extract()[0], 'div')) function = mandate.split(u'<br>')[0].split(',')[0] party = mandate.split(u'<br>')[0].split(',')[1] if ',' in mandate.split(u'<br />')[0] else '' llp_raw = re.match( '^.*\((.*)\. GP\).*$', function ) function = re.sub( '\((.*)\. GP\)','', function ).strip() m_llp_roman_begin = \ m_llp_roman_end = \ llp_raw.group(1) if llp_raw else '' if u'–' in m_llp_roman_begin: m_llp_roman_begin,m_llp_roman_end = m_llp_roman_begin.split(u'–') for llp in range(roman.fromRoman(m_llp_roman_begin.strip('. ')), roman.fromRoman(m_llp_roman_end.strip('. '))+1 ) if m_llp_roman_begin else [None]: llp_roman = roman.toRoman(llp) if llp else None # Start Date try: start_date = _clean( mandate.split('<br>')[1].split(u'\u2013')[0]) start_date = datetime.datetime.strptime( start_date, "%d.%m.%Y").date() except: logger.error( u"Failed to parse mandate start date: {}".format(start_date)) start_date = None # End Date try: end_date = mandate.split( '<br>')[1].split(u'\u2013') if len(end_date) > 1 and end_date[1]: end_date = datetime.datetime.strptime( _clean(end_date[1]), "%d.%m.%Y").date() else: end_date = None except: logger.error( u"Failed to parse mandate end date: {}".format(end_date)) end_date = None mandates.append({ 'function': function, 'party': _clean(party), 'start_date': start_date, 'end_date': end_date, 'llp': llp, 'llp_roman': llp_roman, }) return mandates
import roman # External library from roman_numbers import RomanNumber rn = RomanNumber() test = True for integer in range(1, 1001): if roman.toRoman(integer) == rn.toInt(integer): test and True else: test and False print(integer) break if test: print("OK")
def test_against_known_implementation(): s = Solution() for x in range(1, 4000): assert s.romanToInt(roman.toRoman(x)) == x
def roman_repl(m): return roman.toRoman(int(m.group(1)))
def convert_roots_to_chord_chart(roots, scale_notes): return [roman.toRoman(scale_notes.index(root) + 1) for root in roots]
def __plotSimple(self, x, targt, rcmpt, error, ax, maxRanges, i, legend): #print(maxRanges-i, targt[-1],"\t", rcmpt[-1], "\t", error[-1],"\t", abs(targt[-1]-rcmpt[-1])) cm = plt.get_cmap('gist_earth') ax.text(0.5, 0.95, r"$" + roman.toRoman(maxRanges - i) + r"$", color="gray", transform=ax.transAxes) ax.set_xlabel(r"$Prod.\cdot10$") lgRcmpt, = ax.plot(x, rcmpt, ls="dashed", solid_capstyle="round", lw=5, alpha=0.6, color=cm(1 / 3), label="Recomputed AE") lgTargt, = ax.plot(x, targt, "-", solid_capstyle="round", lw=5, alpha=0.6, color=cm(2 / 3), label="Activation energy") ax2 = ax.twinx() lgError, = ax2.plot(x, error, ls="dotted", solid_capstyle="round", lw=5, color=cm(3 / 4), label="relative error") #ax.set_ylim(0,5) ax2.set_ylim(0, 1) # maxY = max(error[30:])+0.015 # get maximum for the arrow (>30% co2) # if maxY > 1: # maxY = 1 # ax2.annotate(' ', xy=(.6, maxY), xytext=(.2, maxY-1e-2), arrowprops=dict(arrowstyle="->", connectionstyle="angle3", edgecolor=cm(3/4), facecolor=cm(3/4))) # maxYlabel = "{:03.2f}%".format(maxY*100) if i != maxRanges - 1: ax2.yaxis.set_major_formatter(plticker.NullFormatter()) else: ax2.set_ylabel("Relative error") # Annotate last energies and absolute error font = FontProperties() font.set_size(6) label = "{:03.4f}".format(rcmpt[-1]) bbox_props = dict(boxstyle="round", fc=cm(1 / 3), ec=cm(1 / 3), alpha=0.7) ax.text(30, rcmpt[-1] + 1, label, bbox=bbox_props, fontproperties=font) label = "{:03.4f}".format(targt[-1]) bbox_props = dict(boxstyle="round", fc=cm(2 / 3), ec=cm(2 / 3), alpha=0.7) ax.text(30, targt[-1] - 1, label, bbox=bbox_props, fontproperties=font) label = "{:03.4f}".format(abs(rcmpt[-1] - targt[-1])) bbox_props = dict(boxstyle="round", fc=cm(3 / 3), ec=cm(3 / 3), alpha=0.7) ax.text(30, targt[-1] - 0.5, label, bbox=bbox_props, fontproperties=font) bbox_props = dict(boxstyle="round", fc="w", ec="1", alpha=0.8) #ax2.text(0.65, maxY, maxYlabel, bbox=bbox_props) handles = [lgTargt, lgRcmpt, lgError] if legend and i == maxRanges - 1: ax.legend(handles=handles, loc="upper right", prop={'size': 8}) return handles
print s """ stanzas = [s for s in stanzas[1:] if len(s)>1 and s != ' '] for i,s in enumerate(stanzas): print "\n==========\nStanza %d\n==========" %(i) """ tweet = s.split('\n') fd = open("../tweets/%d-%02d.txt"%(chapt_num, i), 'w') for j in range(6, -1, -1): fd.write(tweet[2 * j] + '\n' + tweet[2 * j + 1] + "\\\\\n") fd.write("Глава %d, %s"%(chapt_num,toRoman(i + 1))) """ tweet = s.split('\n') tweets = [] tweets += ['\n'.join(tweet[11:14]) + "\\\\\n"] tweets += ['\n'.join(tweet[8:11]) + "\\\\\n"] tweets += ['\n'.join(tweet[4:8]) + "\\\\\n"] tweets += ['\n'.join(tweet[0:4]) + "\\\\\n"] for t in tweets: if len(t) > 140: print "Problem in stanza %d: len = %d"%(i, len(t)) print t sleep(3) fd = codecs.open("../tweets/%d-%02d.txt"%(chapt_num, i), 'w', 'utf-8') for t in tweets: fd.write(t) fd.write(u"Глава %d, %s"%(chapt_num, toRoman(i + 1))) fd.close
#!/usr/bin/python3 from sys import argv from os.path import exists from os import system from roman import toRoman try: header = argv[1] path = argv[2] assert exists(argv[2]) nb_chr = int(argv[3]) except: print( 'Usage: ./rename_chromosomes.py <header> <path> <# chromosomes>.\n\te.g.: ./rename_chromosomes.py "Kyo_" Kyokai7.fasta 16' ) exit() for i in range(1, nb_chr + 1): roman = toRoman(i) system('sed -i \'s/{0}{1}$/{0}{2}/\' {3}'.format(header, roman, i, path))
text_commentId = '' document_text = '' page_number = 0 for element in document_root.iter(): if f'{namespace}t' == element.tag: document_text += element.text elif f'{namespace}commentRangeStart' == element.tag: text_commentId = element.get(f'{namespace}id') document_text = '' elif f'{namespace}lastRenderedPageBreak' == element.tag: page_number += 1 elif f'{namespace}commentRangeEnd' == element.tag: if page_number < page_offset: pulled_text[text_commentId] = (document_text, toRoman(page_number), page_number) else: pulled_text[text_commentId] = (document_text, page_number - page_offset + 1, page_number) #Extract Comment ID, comment, and author from comments.xml. Start #running count that gets increased with each comment tag. commentId = '' comment_text = '' author = '' for element in comments_root.iter(): if f'{namespace}comment' == element.tag:
def _get_new_name(self, oldName): ''' return a new name, based on the old name, and settings from our dialog. ''' newName = self.pattern ### START PATTERNIZE OPTIONS ### #for number substiution for index, match in enumerate(self.num_pat.finditer(newName)): number = self.nums.get(str(index), 0) start = match.groupdict().get('start') fill = match.groupdict().get('fill') if start == None: start = 1 substitute = str(number + int(start)).zfill(int(fill)) newName = self.num_pat.sub(substitute, newName, 1) self.nums[str(index)] = number + 1 # roman pattern for index, match in enumerate(self.roman_pat.finditer(newName)): if not roman: print "python-roman is not installed." break number = self.romans.get(str(index), 0) start = match.groupdict().get('start') if start == None: start = 1 substitute = roman.toRoman(number + int(start)) newName = self.roman_pat.sub(substitute, newName, 1) self.romans[str(index)] = number + 1 for index, match in enumerate(self.alphau_pat.finditer(self.pattern)): nxt = self.alphaus[str(index)].next() subst = ''.join(nxt) newName = self.alphau_pat.sub(subst, newName, 1) for index, match in enumerate(self.alpha_pat.finditer(self.pattern)): nxt = self.alphas[str(index)].next() subst = ''.join(nxt) newName = self.alpha_pat.sub(subst, newName, 1) # for random number insertion for index, match in enumerate(self.ran_pat.finditer(newName)): if not self.ran_seq[str(index)]: # if random number sequence is None print "Not Enought Random Number Range" show_error(_("Not Enough Random Number Range"), _("Please, use a larger range")) self.exit() #return False randint = random.choice(self.ran_seq[str(index)]) self.ran_seq[str(index)].remove(randint) subst = str(randint).zfill(self.ran_fill[str(index)]) newName = self.ran_pat.sub(subst, newName, 1) dir, file = os.path.split(os.path.abspath(oldName)) name, ext = os.path.splitext(file) dirname = os.path.basename(dir) #replace filename related Tags newName = newName.replace('/filename/', oldName) newName = newName.replace('/dir/', dirname) newName = newName.replace('/name/', name) newName = newName.replace('/ext/', ext) #for /name,offset(:length)/ for match in self.name_slice.finditer(newName): offset = match.groupdict().get('offset') length = match.groupdict().get('length') if length == None: offset = int(offset) substitute = name[offset:] else: offset = int(offset) length = int(length) if length < 0: if offset == 0: substitute = name[offset + length:] else: substitute = name[offset + length:offset] else: if (len(name[offset:]) > length): substitute = name[offset:offset + length] else: substitute = name[offset:] newName = self.name_slice.sub(substitute, newName, 1) #for /filename|offset(:length)/ for match in self.filename_slice.finditer(newName): offset = match.groupdict().get('offset') length = match.groupdict().get('length') if length == None: offset = int(offset) substitute = oldName[offset:] else: offset = int(offset) length = int(length) if length < 0: if offset == 0: substitute = oldName[offset + length:] else: substitute = oldName[offset + length:offset] else: if (len(name[offset:]) > length): substitute = name[offset:offset + length] else: substitute = name[offset:] newName = self.filename_slice.sub(substitute, newName, 1) #Some Time/Date Replacements newName = newName.replace('/date/', time.strftime('%d%b%Y', time.localtime())) newName = newName.replace('/year/', time.strftime('%Y', time.localtime())) newName = newName.replace('/month/', time.strftime('%m', time.localtime())) newName = newName.replace('/monthname/', time.strftime('%B', time.localtime())) newName = newName.replace('/monthsimp/', time.strftime('%b', time.localtime())) newName = newName.replace('/day/', time.strftime('%d', time.localtime())) newName = newName.replace('/dayname/', time.strftime('%A', time.localtime())) newName = newName.replace('/daysimp/', time.strftime('%a', time.localtime())) ### END PATTERNIZE OPTIONS ### if not self.ext: name, ext = os.path.splitext(newName) else: name = newName # Handle Substitute if self.substitute_p: for i in xrange(0, len(self.replees)): if i < len(self.replers): name = name.replace(self.replees[i], self.replers[i]) else: # if there is no corresponding word to replace, use the last one name = name.replace(self.replees[i], self.replers[-1]) # pattern = re.compile (self.replees[i]) # if i < len (self.replers): # name = pattern.sub (self.replers[i], name) # else: # name = pattern.sub (self.replers[-1], name) # Handle Case if self.case_opt == CASE_ALL_CAP: name = name.upper() elif self.case_opt == CASE_ALL_LOW: name = name.lower() elif self.case_opt == CASE_FIRST_CAP: name = name.capitalize() elif self.case_opt == CASE_EACH_CAP: name = name.title() elif self.case_opt == CASE_CAP_AFTER: if self.cap_first.get_active(): name = name.capitalize() seps = self.cap_entry.get_text() # print name, seps for sep in seps.split('/'): if not sep == '': lst = [l for l in name.split(sep)] for i in xrange(1, len(lst)): if lst[i] is not '': lst[i] = lst[i][0].upper() + lst[i][1:] name = sep.join(lst) if self.ext: return name else: return name + ext
def encrypt3(message): """Reprezentarea valorii ascii in sistem roman.""" return ", ".join([roman.toRoman(ord(letter)) for letter in message])
""" Generate Anki cards for Roman numerals from 1 to 4999. Probably a bad idea. Works with Python 2 and 3. """ import csv import roman # pip/pip3 install roman with open('roman_numerals.csv', 'w') as csvfile: writer = csv.writer(csvfile) for i in range(1, 5000): writer.writerow([roman.toRoman(i), i])
def to_roman(n): return roman.toRoman(n)
def out_tables_list(text_between): '''This function takes the text between start and end patterns of heading as input and returns the list of table names referenced in the text but presented some where else in pdf. Parameters: text_between(str): The text in between the start and end patterns in the text of the pdf returns: table_start_list(list): List of tables referenced in the heading (like 'Precision') text table_end_list(list): List of table names which are expected as the end patterns for table_start_list ''' integers = list(range(1, 50)) roman_num = list(range(1, 50)) for integer in range(0, len(roman_num)): roman_num[integer] = roman.toRoman(int(roman_num[integer])) table_start, table_start1, table_end, table_end1 = "", "", "", "" textdata_temp = str(text_between).split(" ") for word in range(0, len(textdata_temp)): textdata_temp[word] = re.sub('\'|\"|\,|\.|\\\\|\[|\]', "", textdata_temp[word]) for number in range(0, len(roman_num)): if textdata_temp[word] == roman_num[ number] or textdata_temp[word] == str( integers[number]) and "ble" in textdata_temp[word - 1]: table_start = table_start + ",Table " + roman_num[number] table_end = table_end + ",Table " + roman_num[number + 1] table_start1 = table_start1 + ",Table " + str( (integers[number])) table_end1 = table_end1 + ",Table " + str(integers[number + 1]) table_start = pd.DataFrame( table_start[1:len(table_start)].split(","))[0].unique() table_start1 = pd.DataFrame( table_start1[1:len(table_start1)].split(","))[0].unique() table_end = pd.DataFrame( table_end[1:len(table_end)].split(","))[0].unique() table_end1 = pd.DataFrame( (table_end1[1:len(table_end1)].split(",")))[0].unique() table_start = table_start + "," + table_start1 table_end = table_end + "," + table_end1 for tablename in range(0, len(table_start)): table_start[tablename] = table_start[tablename].split(",") table_end[tablename] = table_end[tablename].split(",") table_start = re.sub(r'\)|\(|\[|\]|\'', "", str(table_start)) table_start = re.sub(r'list|\n', ",", str(table_start)) table_start = re.sub(r"\s*T|\s*able \d{1,2}T", 'T', str(table_start)) table_start = re.sub(r"\s\,", ',', str(table_start)) table_start_list = table_start.split(",")[1:len(table_start)] table_end = re.sub(r'\)|\(|\[|\]|\'', "", str(table_end)) table_end = re.sub(r'list|\n', ",", str(table_end)) table_end = re.sub(r"\s*T", 'T', str(table_end)) table_end = re.sub(r"\s\,", ',', str(table_end)) table_end_list = table_end.split(",")[1:len(table_end)] return table_start_list, table_end_list
def ionic_naming(): polyatomic=False compound=str(input('What is the chemical formula for the compound (' 'with brackets around polyatomic ions and for subscripts just place the number) \n')) if '(' in compound: polyatomic=True if not polyatomic: chemicals = re.sub(r"[^A-Za-z]+", '', compound) split_compound = re.findall('[A-Z][^A-Z]*', chemicals) cation = Element.get(split_compound[1], '') anion_multivalence = Element.get(split_compound[0], '')[6] cation = cation[2] cation_ide = cation + 'ide' anion = Element.get(split_compound[0], '')[1] if not anion_multivalence: compound_name = anion + ' ' + cation_ide return compound_name else: different_elements = re.findall('[A-Z][^A-Z]*', compound) subscripts_array = [0, 1] for i in range(0,2): subscripts_array[i] = re.sub("\D", '', different_elements[i]) if subscripts_array[i] == '': subscripts_array[i] = 1 else: subscripts_array[i] = int(subscripts_array[i]) cation_charge = abs(int(Element.get(split_compound[1], '')[7])) anion_charge = int((cation_charge*subscripts_array[1])/subscripts_array[0]) roman_translation = roman.toRoman(anion_charge) compound_name = anion + ' (' + roman_translation + ') ' + cation_ide return compound_name if polyatomic: component_one = compound.split(')')[0] if(compound[0] == '('): anion = 'Ammonium' component_two = compound.split(')')[1] component_two = re.sub(r"[^A-Za-z]+", '', component_two) cation = Element.get(component_two, '')[2] cation_ide = cation + 'ide' return anion + ' ' + cation_ide else: component_two = compound.split('(')[0] anion_symbol = re.sub(r"[^A-Za-z]+", '', component_two) anion = Element.get(anion_symbol, '') anion_name = anion[1] anion_multivalence = anion[6] component_one = component_one.split('(')[1] polyatomic_ion = polyatomic_formula.get(component_one, '') cation = polyatomic_ion if anion_multivalence: cation_charge = polyatomic_ions.get(cation, '')[1] if compound[-1] == ')': cation_subscript = 1 else: cation_subscript = compound.split(')')[1] cation_subscript = re.sub("\D", "", cation_subscript) if not cation_subscript == '': cation_subscript = int(cation_subscript) else: cation_subscript = 1 anion_subscript = re.sub("\D", "", component_two) if not anion_subscript == '': anion_subscript = int(anion_subscript) else: anion_subscript = 1 anion_charge = abs(int((cation_charge * cation_subscript) / anion_subscript)) roman_translation = roman.toRoman(anion_charge) compound_name = anion_name + ' (' + roman_translation + ') ' + cation return compound_name else: return anion_name + ' ' + cation
5: 'V', 9: 'IX', 10: 'X', 40: 'XL', 50: 'L', 90: 'XC', 100: 'C', 400: 'CD', 500: 'D', 900: 'CM', 1000: 'M' } r_num = '' if dec_num != 0 else 'N' while dec_num != 0: for i, numeral in enumerate([numeral for numeral in numerals.keys()][::-1]): if dec_num - numeral >= 0: r_num += numerals[numeral] dec_num -= numeral break return r_num for i in range(1000): my = decimal_to_roman(i) truth = roman.toRoman(i) print(my == truth, i, my, truth)
def __init__(self, position, title): self.title = title self.position = position self.numeral = roman.toRoman(int(self.position))
def plot_8x2(startswith=1): base_geom = np.array([[7, 8], [6, 9], [5, 10], [4, 11], [3, 12], [2, 13], [1, 14], [0, 15]]) nrows, ncols = base_geom.shape coordinates = { "LB": base_geom + startswith, "LT": np.flipud(base_geom) + startswith, "RT": np.flipud(np.fliplr(base_geom)) + startswith, "RB": np.fliplr(base_geom) + startswith } fig = plt.figure(facecolor="white") axsel = AxesSelector() axs = [] for ii, coord in enumerate(["LB", "LT", "RT", "RB"]): ax = fig.add_subplot(2, 2, ii + 1) ax.text(.05, .95, toRoman(ii + 1), transform=ax.transAxes, horizontalalignment="left", verticalalignment="top", fontsize=20, color=[.7, .7, .7], fontweight="bold") ax.set_label(coord) e_numbers = coordinates[coord] for row in xrange(nrows): for col in xrange(ncols): enum = e_numbers[row, col] ax.text(col, nrows - row, "%d" % enum, horizontalalignment="center", verticalalignment="center") ax.set_ylim([0, 9]) ax.set_xlim([-1, 2]) ax.set_xticks([]) ax.set_yticks([]) for sp in ax.spines.values(): sp.set_color([0.7, 0.7, 0.7]) axsel.append(ax, e_numbers) axs.append(ax) # Add descriptive texts x = axs[0].get_position().x1 y = np.mean([axs[0].get_position().y0, axs[2].get_position().y1]) fig.text(x, y, "$\leftarrow$ Medial", verticalalignment="center", horizontalalignment="right", fontsize=20) x = axs[1].get_position().x0 fig.text(x, y, "Lateral $\\rightarrow$", verticalalignment="center", horizontalalignment="left", fontsize=20) x = np.mean([axs[0].get_position().x1, axs[1].get_position().x0]) y = axs[0].get_position().y0 fig.text(x, y, "Rostral $\\rightarrow$", verticalalignment="bottom", horizontalalignment="center", rotation=90, fontsize=20) y = axs[2].get_position().y1 fig.text(x, y, "$\leftarrow$ Caudal", verticalalignment="top", horizontalalignment="center", rotation=90, fontsize=20) plt.show() axsel.connect() axsel.wait_until() axsel.disconnect() chosen = axsel.chosen # plt.close(plt.gcf()) # Some real bullshit going on here... but it's close # del axsel return chosen