コード例 #1
0
ファイル: jecretz.py プロジェクト: the-taj/jecretz
def display_results(results, save, out=None):
    table_data = []
    table_data.append(['Issue ID', 'Description', 'Comments'])
    table = AsciiTable(table_data)
    max_width = table.column_max_width(1)
    align_width = int(max_width / 2)
    for result in results:
        description = results[result]["description"]
        comments = results[result]["comments"]
        if not description and not comments:
            continue
        if not description:
            description = "--"
        if not comments:
            comments = "--"
        if len(str(description)) > align_width:
            description = '\n'.join(wrap(str(description), align_width))
        if len(str(comments)) > align_width:
            comments = '\n'.join(wrap(str(comments), align_width))
        table.table_data.append([result, description, comments])
    table.inner_row_border = True
    print(table.table)
    print("[+] Returned " + str(len(table.table_data) - 1) + " items\n")
    if save:
        output = "\n[+] Jecretz Results\n\n" + table.table + "\n\n[+] Returned " + str(
            len(table.table_data) - 1) + " items\n\n"
        with open(out, "w") as file:
            file.write(output)
コード例 #2
0
def create_image(data):
    black = (255, 255, 255, 255)
    font_size = 50
    font_size_2 = 30
    fnt = ImageFont.truetype('Arial-Unicode-Regular.ttf', font_size)
    fnt2 = ImageFont.truetype('Arial-Unicode-Regular.ttf', font_size_2)
    img = Image.open('background2.png').convert('RGBA')
    draw = ImageDraw.Draw(img)
    lines = wrap(data['MeetingSubjectChi'], width=(int)(1200/font_size_2)) #1200/font_size
    committee = get_committee(data)
    draw.text((20, 20), committee + '就', font=fnt, fill=black)
    i = 0
    y = 0
    for line in lines:
        y = 30 + font_size + 20 + i * font_size_2
        draw.text((20, y), line, font=fnt2, fill=black)
        i += 1
        draw.text((20, 30 + y + font_size_2), u'邀請各界提交意見書', font=fnt, fill=black)
        deadline = data['SubmissionClosingDate'].split('T')[0]
        #截止日期
        draw.text((20, 500), u'截止日期:' + deadline, font=fnt, fill=black)
    bytes_io = io.BytesIO()
    img.save(bytes_io, format='PNG')
    bytes_io.seek(0)
    return bytes_io
コード例 #3
0
def check_file_last_update_date(file_name):
    curr = wrap(str(file_name.split('.')[0][2:]), 2)
    m = datetime(
        int(str(custom_today_date().split('-')[0][0:2]) + str(curr[2])),
        int(curr[1]), int(curr[0]))
    print(custom_today_date())
    print(m.strftime('%Y-%m-%d'))
    return m.strftime('%Y-%m-%d') == custom_today_date()
コード例 #4
0
def convert_back(value):
    """
        This function converts a given 8 bit ASCII to its equivalent character.
    """
    value = textwrap3.wrap(value, 8)
    alphabets = []
    for i in value:
        alphabets.append(chr(int(i, 2)))
    return ''.join(alphabets)
コード例 #5
0
def process(
    lines: list, number: int, website: str
) -> str:  # Process the lines : format them, highlight and stuff
    """
        Process the lines :
        Highlight and stuff
    """
    text = ""
    if website == 'nsf':
        text = wrap(''.join(lines), 54)
        return '\n'.join((line.center(54, " ") for line in text))
    try:
        for l in lines:
            if l == '':
                continue
            if l[0] == '*':
                text += color.ITALIC + l + color.END + "\n"
                continue
            if ('<' in l and '>' in l) and l[0] == '<':
                if (':' in l and l.find(':') > l.find('<')) or ':' not in l:
                    l = l.split(">", 1)
                    l[0] = color.BOLD + l[0] + ">" + color.END
                    text += ''.join(l) + "\n"
                elif ':' not in l:
                    text += l + "\n"
            elif ('[' in l and ']' in l) and l[0] == '[':
                l = l.split("]", 1)
                if ':' in l[0]:
                    l[0] = color.BOLD + color.GREEN + l[0] + "]" + color.END
                else:
                    l[0] = color.BOLD + l[0] + "]" + color.END
                if ":" in l[1]:
                    t = l[1].split(":", 1)
                    l[1] = color.BOLD + t[0] + ":" + color.END + t[1]
                elif '<' in l[1] and '>' in l[1]:
                    t = l[1].split(">", 1)
                    l[1] = color.BOLD + t[0] + '>' + color.END + t[1]
                text += ''.join(l) + "\n"
            elif ('(' in l and ')' in l) and l[0] == '(':
                l = l.split(')', 1)
                l[0] = color.BOLD + l[0] + ')' + color.END
                text += ''.join(l) + "\n"
            elif ':' in l:
                l = l.split(":", 1)
                l[0] = color.BOLD + l[0] + ":" + color.END
                text += ''.join(l) + "\n"
            else:
                text += ''.join(l) + "\n"
    except IndexError:
        print(f'Error while processing {website} n°{number}, url {{}}'.format({
            'dtc':
            "https://danstonchat.com/{}.html",
            'qdb':
            "bash.org/?{}"
        }[website].format(number)))
        sexit(1)
    return text[:-1]
コード例 #6
0
def line_feed2(text, num):
    new_text = ""
    for j in text.split('\n'):
        for i in wrap(j, num):
            if i[0] == " ":
                i = i[1:]
            new_text += i
            new_text += '\n'
        if new_text[-1:] != '\n':
            new_text += '\n'

    return new_text
コード例 #7
0
    def test_initial_indent(self):
        # Test initial_indent parameter

        expect = [
            "     This paragraph will be filled,",
            "first without any indentation, and then",
            "with some (including a hanging indent)."
        ]
        result = wrap(self.text, 40, initial_indent="     ")
        self.check(result, expect)

        expect = "\n".join(expect)
        result = fill(self.text, 40, initial_indent="     ")
        self.check(result, expect)
コード例 #8
0
    def test_nobreak_long(self):
        # Test with break_long_words disabled
        self.wrapper.break_long_words = 0
        self.wrapper.width = 30
        expect = [
            'Did you say', '"supercalifragilisticexpialidocious?"',
            'How *do* you spell that odd', 'word, anyways?'
        ]
        result = self.wrapper.wrap(self.text)
        self.check(result, expect)

        # Same thing with kwargs passed to standalone wrap() function.
        result = wrap(self.text, width=30, break_long_words=0)
        self.check(result, expect)
コード例 #9
0
ファイル: analys.py プロジェクト: Seb-Leb/bioinfokit
    def fqtofa(file="fastq_file"):
        x = fastq_format_check(file)
        if x == 1:
            print("Error: Sequences are not in fastq format")
            sys.exit(1)

        read_file = open(file, "rU")
        out_file = open("output.fasta", 'w')
        for line in read_file:
            header_1 = line.rstrip()
            read = next(read_file).rstrip()
            header_2 = next(read_file).rstrip()
            read_qual = next(read_file).rstrip()
            out_file.write(header_1 + "\n" + '\n'.join(wrap(read, 60)) + "\n")
        read_file.close()
コード例 #10
0
 def visualizeTotalEnergy(self, path="noPath.png", hyperplane=None):
     # plots the total magnetization with time
     plt.close()
     fig = plt.figure()
     plt.plot(self.systemDataTimeSeries[0], self.systemDataTimeSeries[2],
              "+k")
     plt.title("\n".join(
         wrap(
             "Ising Model, Dimension = " + str(self.d) + ", N = " +
             str(self.n) + ", Tc = " +
             str(sigfig.round(float(self.tc), sigfigs=4)) + "K, T = " +
             str(sigfig.round(float(self.t), sigfigs=4)) + "K, Time = " +
             str(self.timeStep) + "au", 60)))
     plt.xlabel("Time steps / a.u.")
     plt.ylabel("Total energy / J")
     return fig
コード例 #11
0
def same_behavior(text, width, **kwargs):
    """
    Comparison fixture. Did ansiwrap wrap the text to the same number
    of lines, with the same number of visible characters per line, as textwrap
    did to the text without ANSI codes?
    """
    no_ansi = strip_color(text)
    clean_wrap = textwrap.wrap(no_ansi, width, **kwargs)
    clean_fill = textwrap.fill(no_ansi, width, **kwargs)
    ansi_wrap = wrap(text, width, **kwargs)
    ansi_fill = fill(text, width, **kwargs)

    clean_wrap_lens = lengths(clean_wrap)
    ansi_wrap_lens = lengths(striplines(ansi_wrap))

    assert len(clean_wrap) == len(ansi_wrap)
    assert len(clean_fill) == len(strip_color(ansi_fill))
    assert clean_wrap_lens == ansi_wrap_lens
コード例 #12
0
 def test_placeholder(self):
     self.check_wrap(self.text,
                     12, ["Hello..."],
                     max_lines=1,
                     placeholder='...')
     self.check_wrap(self.text,
                     12, ["Hello there,", "how are..."],
                     max_lines=2,
                     placeholder='...')
     # long placeholder and indentation
     if _PY26:
         # the with context manager testing form below was not
         # supported until PY27. So this is a testing outlier
         # to make the backport work.
         self.assertRaises(
             ValueError, lambda: wrap(self.text,
                                      16,
                                      initial_indent='    ',
                                      max_lines=1,
                                      placeholder=' [truncated]...'))
         self.assertRaises(
             ValueError, lambda: wrap(self.text,
                                      16,
                                      subsequent_indent='    ',
                                      max_lines=2,
                                      placeholder=' [truncated]...'))
     else:
         with self.assertRaises(ValueError):
             wrap(self.text,
                  16,
                  initial_indent='    ',
                  max_lines=1,
                  placeholder=' [truncated]...')
         with self.assertRaises(ValueError):
             wrap(self.text,
                  16,
                  subsequent_indent='    ',
                  max_lines=2,
                  placeholder=' [truncated]...')
     self.check_wrap(self.text,
                     16, ["    Hello there,", "  [truncated]..."],
                     max_lines=2,
                     initial_indent='    ',
                     subsequent_indent='  ',
                     placeholder=' [truncated]...')
     self.check_wrap(self.text,
                     16, ["  [truncated]..."],
                     max_lines=1,
                     initial_indent='  ',
                     subsequent_indent='    ',
                     placeholder=' [truncated]...')
     self.check_wrap(self.text, 80, [self.text], placeholder='.' * 1000)
コード例 #13
0
def split_at_length(dataframe, column, length, PIMS_ID=True):
    wrapped = []
    for i in dataframe[column]:
        wrapped.append(wrap(i, length))

    dataframe = dataframe.assign(wrapped=wrapped)
    dataframe['wrapped'] = dataframe['wrapped'].apply(
        lambda x: '; '.join(map(str, x)))

    if PIMS_ID == True:
        splitted = pd.concat([
            pd.Series(
                row['PIMS_ID'],
                row['wrapped'].split("; "),
            ) for _, row in dataframe.iterrows()
        ]).reset_index()
        splitted = splitted.rename(columns={"index": "text", 0: "PIMS_ID"})

    else:
        splitted = []

    return dataframe, splitted
コード例 #14
0
def convert_image(sentence):
    # Break text
    sentence = wrap(sentence, 20)

    # Load image and font
    img = Image.open(os.path.join(dir, '../', 'images', 'original.png'))
    font = ImageFont.truetype(
        os.path.join(dir, '../', 'assets', 'Pangolin-Regular.ttf'), 65)

    # Manipulate image
    converted = img.resize((800, 800))
    converted = converted.filter(ImageFilter.GaussianBlur)
    enhancer = ImageEnhance.Brightness(converted)
    converted = enhancer.enhance(0.5)

    # Insert text into image
    draw = ImageDraw.Draw(converted)

    text_total_height = 0

    for line in sentence:
        line_x_size, line_y_size = draw.textsize(line, font=font)
        text_total_height += line_y_size

    current_height = (800 - text_total_height) / 2

    for line in sentence:
        line_x_size, line_y_size = draw.textsize(line, font=font)
        draw.text((((800 - line_x_size) / 2), current_height),
                  line,
                  fill="white",
                  font=font)
        current_height += line_y_size

    # Save final image
    converted.save(os.path.join(dir, '../', 'images', 'converted.png'))
コード例 #15
0
ファイル: shape.py プロジェクト: sorojara/text-processing
def wrap_text_to_array(text, size):
    ret = wrap(text, size)
    return ret
コード例 #16
0
def wrap_text(string, max_width):
    return '\n'.join(wrap(string, max_width))
コード例 #17
0
    "font.sans-serif": ["Helvetica"],
    "font.size": 16,
    "axes.titlepad": 25
})

L = ct.Ljsns2  #int(input("Digite um valor para a distância: "))
E = np.arange(10e-15, ct.muonmass / 2, 0.01)

plt.plot(E, flx.Fluxve(L, E, ct.Ue4_2, ct.DelM2), 'r', linewidth=1.0)
plt.vlines(ct.NuMuenergy,
           0,
           flx.nvevmu,
           colors='blue',
           label='\n'.join(
               wrap(
                   r'{0:.2e} neutrinos do decaimento de dois corpos'.format(
                       flx.nvevmu), 25)))
plt.legend(loc='upper left')
plt.title(
    r'Fluxo de neutrinos do elétron por energia emitidos para L={0}m'.format(
        L))
plt.grid(True)
textstr = '\n'.join((r'$|U_{{e4}}|^{{2}}$= {0}'.format(ct.Ue4_2),
                     r'$|U_{{\mu 4}}|^{{2}}$= {0}'.format(ct.Umu4_2),
                     r'$\Delta m^{{2}}$= {0}eV$^{{2}}$'.format(ct.DelM2)))
plt.text(-1.2,
         3.5e16,
         textstr,
         fontsize=16,
         bbox=dict(facecolor='white', alpha=1))
plt.xlabel(r'Energia dos neutrinos [MeV]')
コード例 #18
0
         'g',
         linewidth=1.5,
         label=r'$|U_{e4}|^{2}$=0, $|U_{\mu4}|^{2}$=0')
plt.plot(Enu,
         evt.dNdEvebar(Enu, ct.Ue4_2, ct.Umu4_2, ct.DelM2),
         'b',
         linewidth=1.5,
         label=r'$|U_{e4}|^{2}$=0.019, $|U_{\mu4}|^{2}$=0.015')
plt.plot(Enu,
         evt.dNdEvebar(Enu, 2 * ct.Ue4_2, 2 * ct.Umu4_2, ct.DelM2),
         'r',
         linewidth=1.5,
         label=r'$|U_{e4}|^{2}$=2*0.019, $|U_{\mu4}|^{2}$=2*0.015')
plt.title('\n'.join(
    wrap(
        r'Espectro dos antineutrinos do elétron para L={0}m IBD em PPO/Paraffin/LAB'
        .format(exp.Ljsns2), 50)))
plt.legend()
plt.grid(True)
textstr = '\n'.join((r'$\Delta m^{{2}}$= {0}eV$^{{2}}$'.format(ct.DelM2), ))
plt.text(1, 4.5, textstr, fontsize=16, bbox=dict(facecolor='white', alpha=1))
plt.xlabel(r"Energia dos neutrinos [MeV]")
plt.ylabel(r'dN/dE [MeV$^{-1}$]')
plt.tight_layout()
plt.savefig('EnergySpectrumOfNeutrinos/NuebarIBDSpec.pdf')
plt.close()

#Considering 208Pb (1ton) (charged current electron neutrino)

plt.plot(EnuPb,
         evt.dNdEvee(EnuPb, 0, ct.DelM2),
コード例 #19
0
    "font.size": 16,
    "axes.titlepad": 25
})

L = ct.Ljsns2  #int(input("Digite um valor para a distância: "))
E = np.arange(10e-15, ct.muonmass / 2, 0.01)

plt.plot(E, flx.Fluxve(L, E, ct.Ue4_2, ct.DelM2), 'r', linewidth=1.0)
plt.vlines(
    ct.NuMuenergy,
    0,
    flx.nvevmu,
    colors='blue',
    label='\n'.join(
        wrap(
            r'{0:.2e} neutrinos por ano por m$^{{2}}$ do decaimento de dois corpos'
            .format(flx.nvevmu), 28)))
plt.legend(loc='upper left')
plt.title(
    r'Fluxo de $\nu_{{e}}$ por energia emitidos para L={0}m em um ano'.format(
        L))
plt.grid(True)
textstr = '\n'.join((r'$|U_{{e4}}|^{{2}}$= {0}'.format(ct.Ue4_2),
                     r'$|U_{{\mu 4}}|^{{2}}$= {0}'.format(ct.Umu4_2),
                     r'$\Delta m^{{2}}$= {0}eV$^{{2}}$'.format(ct.DelM2)))
plt.text(-1.2,
         3.5e16,
         textstr,
         fontsize=16,
         bbox=dict(facecolor='white', alpha=1))
plt.xlabel(r'Energia dos neutrinos [MeV]')
コード例 #20
0
def convert_phased(population):
    """
	Convert phased HapMap3 data to GWAsimulator format where the biallelic SNP are encoded by 0 or 1:
	For 23 chromosomes (22 autosomal chromosomes, X chromosome) 
	Chromosome X is denoted by 'chr23'

	Args:

		population: str: specify the HapMap3 population name, such as "ceu" or yri".

	Returns:

		Print output phased file for each chromosome.

	"""

    for ch in range(1, 24):

        # Input files path
        file = population + '/hapmap3_r2_b36_fwd.consensus.qc.poly.chr' + str(
            ch) + '_' + population + '.phased'

        # Transform phased file into pandas Dataframe object
        chrom = pd.read_csv(file, delim_whitespace=True)

        # Delete extra columns
        chrom = chrom.drop(chrom.columns[0], axis=1)
        chrom = chrom.drop(chrom.columns[0], axis=1)

        # Merge all columns
        chrom = chrom.astype(str).sum(axis=1)

        # Convert it to list
        chrom_list = []
        for ind in chrom.index:
            chrom_list.append(chrom[ind])

        # Determine the major and the minor allele for each SNP
        alleles = [list(set(i)) for i in chrom_list]

        # Remove useless charecters
        for i in range(len(alleles)):
            if "-" in alleles[i]:
                alleles[i].remove("-")
            if 'n' in alleles[i]:
                alleles[i].remove('n')

        # Converting
        phased = []
        for ic in range(len(chrom_list)):

            if len(alleles[ic]) == 2:
                allele_1 = alleles[ic][0]
                allele_2 = alleles[ic][1]

                count_allele_1 = chrom_list[ic].count(allele_1)
                count_allele_2 = chrom_list[ic].count(allele_2)

                if count_allele_1 >= count_allele_2:
                    major_allele = allele_1
                    minor_allele = allele_2
                elif count_allele_1 < count_allele_2:
                    major_allele = allele_2
                    minor_allele = allele_1

            if len(alleles[ic]) == 1:
                major_allele = alleles[ic][0]

            SNP = ""
            for jc in range(len(chrom_list[ic])):

                if chrom_list[ic][jc] == major_allele:
                    SNP = SNP + '1'
                elif chrom_list[ic][jc] == minor_allele:
                    SNP = SNP + '0'
                elif chrom_list[ic][jc] == "-":
                    SNP = SNP + '0'
                elif chrom_list[ic][jc] == "a":
                    SNP = SNP + '0'
            phased.append(SNP)

        # join bi-allelic SNP in one item
        phased_wrapped = [wrap(i, 2) for i in phased]

        # transpose the list from [SNPsxSAMPLES] to [SAMLESxSNPS]
        # on Python 2, map() returns a list, this not the case for Pyhton 3!!!
        phased_tr = map(list, map(None, *phased_wrapped))

        # final dataframe
        df = pd.DataFrame(phased_tr)

        # save data in text files
        # each file contains data for one chromosome
        result_dir = population + '_encoded/'

        if not os.path.exists(result_dir):
            os.makedirs(result_dir)

        output = result_dir + 'chr' + str(ch) + '_' + population + '.phased'
        df.to_csv(output, sep=' ', header=None, index=False)
コード例 #21
0
 def test_at_width(w, kw1, kw2):
     ansi_lines = wrap(text, w, **kw1)
     clean_lines = textwrap.wrap(no_ansi, w, **kw2)
     ansi_lens = lengths(striplines(ansi_lines))
     clean_lens = lengths(clean_lines)
     assert ansi_lens == clean_lens
コード例 #22
0
from textwrap3 import wrap
import textwrap3, nltk

filename = "E:/Eclipse/workspace/py27/temp111.txt"
filename2 = ("E:/Eclipse/workspace/py27/temp2.txt")
#data = file(filename).read() #print by letters
#data.sort()#AttributeError: 'str' object has no attribute 'sort'
data = file(filename).readlines()  #<type 'list'>
#file(filename).close()
for i in range(len(data)):
    print data[i]

text = "".join(data)
x = wrap(text, 60)
for i in range(len(x)):
    print(x[i])
print("--------------------1-------------------------")
for i in range(len(data)):
    dedented_text = textwrap3.dedent(data[i]).strip()
    print dedented_text
print("---------------------2------------------------")
with open(filename2, 'r') as file1:
    lines_in_file = file1.read()
    nltk_tokens = nltk.word_tokenize(lines_in_file)
    print nltk_tokens
    print("\n")
    print("Number of words:", len(nltk_tokens))
コード例 #23
0
def add_new_line(comment):
    split_text = textwrap3.wrap(comment, width=25)
    final = '<br> '.join(split_text)
    return final
コード例 #24
0
 def check_wrap(self, text, width, expect, **kwargs):
     result = wrap(text, width, **kwargs)
     self.check(result, expect)
コード例 #25
0
fig = plt.figure()
ax = fig.gca()
ax = fig.add_subplot(111)
ax.set_aspect(1)
ax.set_xticks(np.arange(0, 15, 1))
ax.set_yticks(np.arange(0, 15, 1))
plt.xlabel('n medido')
plt.ylabel(r'$\mu$')

x1, x2 = N, N
y1, y2 = min(MU), max(MU)
plt.plot(
    [x1, x2], [y1, y2],
    'blue',
    label='\n'.join(
        wrap('Representação do intervalo para uma medida de n={0}'.format(N),
             20)))

plt.plot(x0_plot, y_plot, 'r')
plt.plot(x1_plot, y_plot, 'r')
plt.xlim(0, 15)
plt.ylim(0, 15)
plt.grid()
plt.title('\n'.join(
    wrap(
        r'Intervalos de Confiança para medidas de Poisson com background médio b={0}'
        .format(b), 50)))
plt.legend(loc=2)
plt.savefig('FCPoisson.pdf')
plt.show()

print("Para o valor N = {0}, os limites de confiança são {1} e {2}".format(
コード例 #26
0
ファイル: nudge.py プロジェクト: jtaleric/nudge
    for nudge in nudges:
        if len(nudge['COMMENTS']) > 0:
            latestCommentID = nudge['COMMENTS'].pop()
            latestComment = conn.comment(nudge['ID'], latestCommentID).body
        else:
            latestComment = "No comments"
        if nudge['STATUS'] == "To Do":
            continue

        epic = conn.search_issues(
            "project = PerfScale AND id={} AND \"Epic Link\" is not EMPTY".
            format(nudge['ID']))

        print("+{}+".format("=" * 100))
        if len(epic) == 0:
            print(
                " -- NOTE:: {} has no EPIC assigned, please link to an EPIC -- "
                .format(nudge['JIRA']))
        print(
            "{} - {} \nLabels: {}\nOwner: {}\nCreator: {}\nStatus: {}\nLink: {}\nLast Comment:\n{}\n\n"
            .format(nudge['JIRA'], nudge['SUMM'], nudge['LABELS'],
                    nudge['OWNER'], nudge['CREATOR'], nudge['STATUS'],
                    nudge['LINK'], "\n".join(wrap(latestComment, 100))))
        if len(nudge['TASKS']) > 0:
            print("Sub-Tasks for {}".format(nudge['JIRA']))
            for tasks in nudge['TASKS']:
                print("JIRA : {}\nStatus : {}\nSummary :{}\n".format(
                    tasks['key'], tasks['fields']['status']['name'],
                    tasks['fields']['summary']))
        print("+{}+".format("=" * 100))
コード例 #27
0
    # Problem statement div
    problem_div = soup.find('div', class_=re.compile(r'content\w+ question-content\w+'))
    return problem_div.text


if __name__ == "__main__":
    if len(sys.argv) != 2:
        print('Invalid Usage!\nRun: python3 leet_code_scraper.py [problem code]', file=sys.stderr)
        sys.exit(1)
    try:
        problem_code = sys.argv[1]
        parsed_problem = parse_problem_statement(problem_code)

        with open(problem_code + '.txt', 'wt') as fout:
            parsed_lines = parsed_problem.split('\n')
            for line in parsed_lines:
                if len(line) < 81:
                    print(line, file=fout)
                else:
                    wrapped_lines = wrap(line, width=80)    # Splitting long line into multiple lines
                    for l in wrapped_lines:
                        print(l, file=fout)

        print(f"Successfully scraped {problem_code} and saved as {problem_code}.py!")

    except InvalidCodeException:
        print("Invalid Problem Code! Please check the problem code provided!")

    except Exception as e:
        print('Fatal: \n' + str(e))
コード例 #28
0
      except ValueError:
        print(error)


equal = ["=", "equal", "e"]   # Used if discriminant is 0
lower = ["<", "lower", "l"]   # Used if discriminant is < 0
higher = [">", "higher", "h"]   # Used if discriminant is > 0
answer = []   # Collect discriminant values
wrong_list = []   # Collect incorrect questions
num_list = []
start = 1
incorrect = 0
# Basic introduction and explanation
text = 'Hello user! Thank you for agreeing to take this test. In this test, you are expected to find the discriminant of an equation generated by the program using the formula: b^2 - 4ac. At any time you may forget the formula, type "a" or "A"...'
# Format paragraphs (improves aesthetics)
x = wrap(text, 39)
for i in range(len(x)):
    print(x[i])
print()
# What is the discriminant?
text_2 = 'If you are wondering, the discriminant tells us whether there are two solutions, one solution, or no solutions for finding the values of x or any other variable in a quadratic equation. For example, 2x^2 + 4x + 2 = 0. The discriminant (using the formula b^2 - 4ac) is 0, therefore x has only one possible value. If asked a question like this, you would be expected to type "e" ,"equal" or "=" since the discriminant is equal to 0.'
x = wrap(text_2, 41)
for i in range(len(x)):
  print(x[i])
print()
# Show user how to answer questions
text_3 = 'When answering a question please type either <, > or =. You may also use "equal", "lower", "higher" or just the first letters of each option.'
x = wrap(text_3, 39)
for i in range(len(x)):
  print(x[i])
print()
コード例 #29
0
ファイル: ueEfix.py プロジェクト: pietro-chimenti/SterileDAR
    "figure.dpi": 72.0,
    "text.usetex": True,
    "font.family": "sans-serif",
    "font.sans-serif": ["Helvetica"],
    "font.size": 16,
    "axes.titlepad": 25
})

L = np.arange(0, 2 * ct.Ljsns2, 0.01)
E = 30  #float(input('Digite um valor fixo para a energia: '))

plt.ticklabel_format(axis='y', scilimits=(0, 0))
plt.plot(L, model.Pme(L, E, ct.Ue4_2, ct.Umu4_2, ct.DelM2), 'r')
plt.title('\n'.join(
    wrap(
        r'Oscilação do neutrino do múon para o neutrino do elétron com E={0}MeV'
        .format(E), 50)))
plt.grid(True)
textstr = '\n'.join((r'$|U_{{e4}}|^{{2}}$= {0}'.format(ct.Ue4_2),
                     r'$|U_{{\mu 4}}|^{{2}}$= {0}'.format(ct.Umu4_2),
                     r'$\Delta m^{{2}}$= {0}eV$^{{2}}$'.format(ct.DelM2)))
plt.text(-1,
         0.0008,
         textstr,
         fontsize=16,
         bbox=dict(facecolor='white', alpha=1))
plt.xlabel(r'Distância [m]')
plt.ylabel(r'Probabilidade de oscilação')
plt.tight_layout()
plt.savefig('NUmuNUeosc{0}Mev.pdf'.format(E))
#plt.show()
コード例 #30
0
ファイル: shape.py プロジェクト: sorojara/text-processing
def wrap_text(text, size):
    buffer_list = wrap(text, size)
    join_char = '\n'
    ret = join_char.join(buffer_list)
    return ret