def isticify(thing):
    if s('(my|ry|cy|hy|gy|ve|ne)$', thing):
        thing = thing[:-1]
    if s('(my|ry)$', thing):
        return thing[:-1] + "ic"
    elif s('ics?$', thing):  # catch loops
        return thing
    return thing + "istic"
def rootize(thing):
    if s('o.{,1}(h|g)y$', thing):
        m = s('o.{,1}(h|g)y$', thing)
        thing = thing[:m.start() - 1]
    elif s('(ural|ics?|ine|ion|ve|.{,2}y)$', thing):
        m = s('(ural|ics?|ine|ion|ve|.{,2}y)$', thing)
        thing = thing[:m.start()] + "o"
    return thing + "-"
示例#3
0
def gerundize(w):
    try:
        if s('[bcdghjklmnopqsvxyz]$', w):
            w += "ing"
        elif s('[frut]$', w):
            w += w[-1] + "ing"
        elif s('[aie]$', w):
            w = w[0:-1] + "ing"
    except:
        pass
    return w
示例#4
0
def check_job(job_id):
    """ Check a job_id, if it is running return state, else return False """
    qstat = rn(['qstat', job_id]).decode('utf8').split('\n')[2:3]

    if not qstat:
        return (False)

    return (s(r' +', qstat[0].rstrip())[4])
示例#5
0
def check_job(job_id):
    """ Check a job_id, if it is running return state, else return False """
    qstat = rn(['qstat', job_id]).decode('utf8').split('\n')[2:3]

    if not qstat:
        return(False)

    return(s(r' +', qstat[0].rstrip())[4])
def check_bank_details_format(account_number, sort_code, account_name):
    """ Check an account_number, sort_code and account_name are all of
    valid formatting. This function does not verify whether or not a
    bank account exists, or whether it could exist. It simply checks the
    length of the three arguments. The responsibility of verifying the
    legitimacy of the account details lies with the client. If any of
    the three values are not the correct formatting, throw an error.

    :Args:
     account_number - An account_number provided by the post.customer()
        function
     sort_code - A sort_code provided by the post.customer()
        function
     account_name - An account_name provided by the post.customer()
        function
    """
    num_r = s(
        '^[0-9]{8}$', account_number
    )
    sort_r = s(
        '^[0-9]{6}$', sort_code
    )
    name_r = s(
        '^[A-Z0-9\-\/& ]{3,18}$', account_name.upper()
    )
    if not num_r:
        raise InvalidParameterError(
            '%s is not formatted as a UK bank account number. UK bank'
            ' account numbers are 8 digits long. Please check the bank'
            ' account number and re-submit.' % account_number
        )
    elif not sort_r:
        raise InvalidParameterError(
            '%s is not formatted as a UK sort code. UK sort codes are 6 digits'
            ' long. Make sure to not include any hyphens. Please check the'
            ' sort code and re-submit.' % sort_code
        )
    elif not name_r:
        raise InvalidParameterError(
            '%s is not formatted as an account holder name. Account holder'
            ' names must be between 3 and 18 characters, contain only capital'
            ' letters (A-7), ampersands (&), hyphens (-), forward'
            ' slashes (/), and spaces ( ).' % account_name
        )
    else:
        pass
示例#7
0
    def toSymbol(self, inputSen):
        doneCurrencyNames = self.doneCurrencyNames
        for k, v in doneCurrencyNames.items():
            if v['symbol'] is not None:
                if isinstance(v['symbol'],list):
                    symbol = v['symbol'][0]
                else:
                    symbol = v['symbol']
                nounCurrency = s('^.* ','',k,flags=IGNORECASE)                                                                      # fm('[a-z]+', k, flags=IGNORECASE) != None
                if ' ' not in k:                                                                                                # exception: one-word currency: euro, bitcoin
                    nounCurrency = k
                if v['plural'] is not None:
                    pluralPrefix = f'{v["plural"]}|{ud(v["plural"])}|'                                  # orders matter. It's always {plural|singular} rather than {singular|plural}
                else:
                    pluralPrefix = ''
                allInstances = fa(f'[0-9\\,\\.]+ (?:{pluralPrefix}{k}|{ud(k)}|{nounCurrency}|{ud(nounCurrency)})(?:e?s)?', inputSen, flags=IGNORECASE)    # all should be uncaptured. Use (?:) instead of ()   <- captured
                trailingZeroRegex = r"\.0$"
                for i in allInstances:
                    numberPart = fa(f'[0-9\\,\\.]+', i)
                    # Left or right ?
                    if len(numberPart) > 0:
                        if symbol.isalpha():  # Cyrillic and zloty are alphas !
                            # rpmt = f'{numberPart[0]} {symbol}'
                            rpmt = f'{s(trailingZeroRegex,"","{:,}".format(float(numberPart[0].replace(",",""))).replace(","," "))} {symbol}'
                        else:
                            # rpmt = f'{symbol}{numberPart[0]}'
                            rpmt = f'{symbol}{s(trailingZeroRegex,"","{:,}".format(float(numberPart[0].replace(",",""))).replace(","," "))}'
                        inputSen = s(i, rpmt, inputSen, flags=IGNORECASE)

                # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

                if v['fractional']['name'] is not None:
                    nounFraction = v['fractional']['name']
                    allInstances = fa(f'[0-9\\,\\.]+ (?:{k}|{ud(k)}|{nounFraction}|{ud(nounFraction)})(?:e?s)?', inputSen, flags=IGNORECASE)    # all should be uncaptured. Use (?:) instead of ()   <- captured
                    for i in allInstances:
                        numberPart = fa(f'[0-9\\,\\.]+', i)
                        # Left or right ?
                        if len(numberPart) > 0:
                            if symbol.isalpha():  # Cyrillic and zloty are alphas !
                                rpmt = f'{s(trailingZeroRegex,"","{:,}".format(float(numberPart[0].replace(",","")) / v["fractional"]["numToBasic"]).replace(","," "))} {symbol}'
                            else:
                                rpmt = f'{symbol}{s(trailingZeroRegex,"","{:,}".format(float(numberPart[0].replace(",","")) / v["fractional"]["numToBasic"]).replace(","," "))}'
                            inputSen = s(i, rpmt, inputSen, flags=IGNORECASE)
        return inputSen
示例#8
0
 def replace(self, inputSen):
     for key in self.jp:
         pp(key)
         print(
             '(' + '|'.join(self.jp[key]['variants']).replace('U+', r'\u') +
             ')', self.jp[key]['replaceWith'].replace('U+', r'\u'))
         inputSen = s(
             '(' + '|'.join(self.jp[key]['variants']).replace('U+', r'\u') +
             ')',
             chr(int(self.jp[key]['replaceWith'].replace('U+', '0x'),
                     16)), inputSen)
     return inputSen
示例#9
0
def evaluateexp(exp):
    factre = 'fact\\(([0-9]+)(\\))'
    varre = 'var\\((\\d+)(, )(\\d+)(\\))'
    comre = 'com\\((\\d+)(, )(\\d+)(\\))'
    res = exp
    if s(factre, res):
        res = sub(factre, str(factorial(int(s(factre, res).group(1)))), res)
    if s(varre, res):
        res = sub(
            varre,
            str(
                variation(int(s(varre, res).group(1)),
                          int(s(varre, res).group(3)))), res)
    if s(comre, res):
        res = sub(
            comre,
            str(
                combination(int(s(comre, res).group(1)),
                            int(s(comre, res).group(3)))), res)
    return res
def sationify(thing):
    if s('(cy|my|ry|gy|hy|cy|ve|ne)$', thing):
        thing = thing[:-1] + "iz"
    elif s('(ize)$', thing):
        thing = thing[:-3] + "iz"
    elif s('c?(al|er|n)$', thing):
        thing += "iz"
    elif s('ics?$', thing):
        thing = (thing[:-1] if thing[-1] == "s" else thing) + "iz"
    elif s('(ism)$', thing):  # catch isms
        thing = thing[:-3] + "iz"
    elif s('ion$', thing):  # catch loops
        return thing
    return thing + "ation"
def check_email_address_format(email_address):
    """ Check an email_address is of valid formatting. This function
    will not verify whether a email_address actually exists, instead
    it checks that an email could exist. The responsibility of checking
    that an email actually exists lies with the client. If the email
    formatting is invalid, throw an error.

    :Args:
     email_address - An email_address provided by the post.customer()
        function
    """
    r = s(
        '(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)', email_address
    )
    if not r:
        raise InvalidParameterError(
            '%s is not a valid email address. Please check the email address'
            ' and re-submit.' % email_address
        )
    else:
        pass
def check_postcode_is_valid_uk_format(post_code):
    """ Check a post_code is of valid formatting. This function will not
    verify whether a post_code actually exists, that responsibility lies
    with the client. This function does not take BFPO post_code. If the
    post code is not valid, throw an error.

    :Args:
     post_code - A post_code provided by the post.customer()
        function
    """
    r = s(
        '^([A-Za-z][A-Ha-hJ-Yj-y]?[0-9][A-Za-z0-9]? ?[0-9][A-Za-z]{2}|[Gg][Ii]'
        '[Rr] ?0[Aa]{2})$', post_code
    )
    if not r:
        raise InvalidParameterError(
            '%s is not formatted as a UK post code. Please check the post code'
            ' and re-submit.' % post_code
        )
    else:
        pass
示例#13
0
def getPlural(key):
    # f'https://en.wiktionary.org/wiki/{123}'
    v = u(f'https://en.wikipedia.org/w/index.php?title={q(key)}&action=edit')
    h = v.read().decode('utf-8')
    soup = b(h, 'html.parser')
    infoBoxTry = soup.select('#wpTextbox1')
    if len(infoBoxTry) > 0:
        editArea = infoBoxTry[0].text
        infoBox = fa('(?<=plural = ).*', editArea)
        if len(infoBox) > 0:
            formatted = s(
                r'(\{.*\}|\(.*\)|\t| |&nbsp;|\'\'.*\'\'|.*\: |<br>|<!--.*-->|/.*|\{\{.*\|)',
                '', infoBox[0]
            )  # TODO: {{plainlist}} not supported, needs a workaround
            if len(formatted) > 1:
                print(f'{key}: {formatted.lower()}')
                return formatted.lower()
            else:
                return None
        else:
            return None
    else:
        return None
示例#14
0
currencies = "https://en.wikipedia.org/wiki/List_of_circulating_currencies"

v = u(currencies)
h = v.read().decode('utf-8')
soup = b(h, 'html.parser')
shift = 0
se = soup.select("#mw-content-text > div > table > tbody > tr")
for i in range(len(se)):
    print(f'{i+1}/{len(se)}')
    tdList = se[i].findAll('td')
    if len(tdList) >= 5:
        if len(tdList) == 5:
            shift = 1
        else:
            shift = 0
        currName = s(r'\[.*\]', '', tdList[1 - shift].text).replace('\n', '')
        if currName == '(none)':
            continue

        currSymb = s(r'\[.*\]', '', tdList[2 - shift].text).replace('\n', '')
        if currSymb == '(none)':
            currSymb = None
        elif ' or ' in currSymb:
            currSymb = currSymb.split(' or ')

        currIso4217Elem = tdList[3 - shift].findAll()
        if len(currIso4217Elem) >= 2:
            currIso4217 = currIso4217Elem[0].text.replace('\n', '')
        else:
            currIso4217 = tdList[3 - shift].text.replace('\n', '')
        if currIso4217 == '(none)':
def ismify(thing):
    if s('(ry|my|cy|hy|gy|ve|ne)$', thing):
        thing = thing[:-1]
    elif s('ics?$', thing):
        thing = thing[:-1] if thing[-1] == "s" else thing
    return thing + "ism"
示例#16
0
def check_queue(uid):
    """ Check the queue for any uid string, return job list with running
        node information. """
    from re import compile as mkregex

    qstat = rn(['qstat', '-u', uid, '-n',
                '-1']).decode('utf8').rstrip().split('\n')[5:]

    # If there are no job return nothing
    if not qstat:
        return

    jobs = {}
    for i in qstat:
        f = s(r' +', i.rstrip())

        # Only look at jobs in the interactive queue
        if not f[2] == short_queue_name:
            continue

        # Skip completed jobs
        if f[9] == 'C':
            continue

        # Get node name, if there is one
        if f[11] == '--':
            node = ''
        else:
            nodes = set(find(r'node[0-9][0-9]', f[11]))
            if len(nodes) > 1:
                continue
            node = str(list(nodes)[0])

        # Get job number
        job_id = find(r'[0-9]+', f[0])[0]

        # Now that we have a limited job set, use qstat -f to get the
        # complete job and queue name
        find_queue = mkregex(r'queue = (.*)$')
        find_name = mkregex(r'Job_Name = (.*)$')

        for i in subprocess.check_output(['qstat', '-f', job_id
                                          ]).decode().rstrip().split('\n'):
            # Get Queue Name
            if find_queue.search(i):
                try:
                    queue = find_queue.findall(i)[0]
                except IndexError:
                    # Queue parsing failed, report this and continue
                    print(
                        "Failed to parse queue for job number:{:^3}\nskipping".
                        format(job_id),
                        file=stderr)
                    continue
                if not queue == interactive_queue:
                    continue
            elif find_name.search(i):
                try:
                    names = find_name.findall(i)[0].split('_')
                except IndexError:
                    # Queue parsing failed, report this and continue
                    print(
                        "Failed to parse queue for job number:{:^3}\nskipping".
                        format(job_id),
                        file=stderr)
                    continue

        # Check that this is actually one of our jobs
        identifier = '_'.join(names[-2:])
        if identifier == 'int_tmux':
            type = 'tmux'
        elif identifier == 'int_vnc':
            type = 'vnc'
        elif identifier == 'int_gui':
            type = 'gui'
        else:
            continue

        # Fix queue name
        name = '_'.join(names[:-2])
        name = name if name else type

        # Assemble the dictionary
        jobs[job_id] = {
            'queue': queue,
            'job_name': name,
            'type': type,
            'node': node,
            'state': f[9]
        }

    # Sort the dictionary
    jobs = OrderedDict(sorted(jobs.items()))

    return (jobs)
示例#17
0
def check_queue(uid):
    """ Check the queue for any uid string, return job list with running
        node information. """
    from re import compile as mkregex

    qstat = rn(['qstat', '-u', uid, '-n', '-1']).decode('utf8').rstrip().split('\n')[5:]

    # If there are no job return nothing
    if not qstat:
        return

    jobs = {}
    for i in qstat:
        f = s(r' +', i.rstrip())

        # Only look at jobs in the interactive queue
        if not f[2] == short_queue_name:
            continue

        # Skip completed jobs
        if f[9] == 'C':
            continue

        # Get node name, if there is one
        if f[11] == '--':
            node = ''
        else:
            nodes = set(find(r'node[0-9][0-9]', f[11]))
            if len(nodes) > 1:
                continue
            node = str(list(nodes)[0])

        # Get job number
        job_id = find(r'[0-9]+', f[0])[0]

        # Now that we have a limited job set, use qstat -f to get the
        # complete job and queue name
        find_queue = mkregex(r'queue = (.*)$')
        find_name  = mkregex(r'Job_Name = (.*)$')

        for i in subprocess.check_output(['qstat', '-f', job_id]).decode().rstrip().split('\n'):
            # Get Queue Name
            if find_queue.search(i):
                try:
                    queue = find_queue.findall(i)[0]
                except IndexError:
                    # Queue parsing failed, report this and continue
                    print("Failed to parse queue for job number:{:^3}\nskipping".format(job_id), file=stderr)
                    continue
                if not queue == interactive_queue:
                    continue
            elif find_name.search(i):
                try:
                    names = find_name.findall(i)[0].split('_')
                except IndexError:
                    # Queue parsing failed, report this and continue
                    print("Failed to parse queue for job number:{:^3}\nskipping".format(job_id), file=stderr)
                    continue

        # Check that this is actually one of our jobs
        identifier = '_'.join(names[-2:])
        if identifier == 'int_tmux':
            type = 'tmux'
        elif identifier == 'int_vnc':
            type = 'vnc'
        elif identifier == 'int_gui':
            type = 'gui'
        else:
            continue

        # Fix queue name
        name = '_'.join(names[:-2])
        name = name if name else type

        # Assemble the dictionary
        jobs[job_id] = {'queue'    : queue,
                        'job_name' : name,
                        'type'     : type,
                        'node'     : node,
                        'state'    : f[9]}

    # Sort the dictionary
    jobs = OrderedDict(sorted(jobs.items()))

    return(jobs)
示例#18
0
def f1(x,y):v="[aeiou]";a,b=s(v,x)[0],s(v,y)[0];return b+x[len(a):],a+y[len(b):]    #106 bytes

from re import split as s
示例#19
0
def f6(x,y):v="[aeiou]";a,b=s(v,x)[0],s(v,y)[0];return b+x[len(a):],a+y[len(b):]    #100 bytes

def f4(*g):a,b=[re.split("[aeiou]",r)[0] for r in g];x,y=g;return b+x[len(a):],a+y[len(b):]
示例#20
0
#import re
#def spoonerize(word1, word2):
#    vowels = "[aeiou]"
#    a, b = re.split(vowels, word1)[0], re.split(vowels, word2)[0]
#    return b+word1[len(a):], a+word2[len(b):]

#from re import split as s;v="[aeiou]";f=lambda *a: (s(v,a[1])[0]

from re import split as s
def f1(x,y):v="[aeiou]";a,b=s(v,x)[0],s(v,y)[0];return b+x[len(a):],a+y[len(b):]    #106 bytes

from re import split as s
v="[aeiou]";
f2=lambda x,y:(s(v,y)[0]+x[len(s(v,x)[0]):],s(v,x)[0]+y[len(s(v,y)[0]):])    #112 bytes

import re
def f3(x,y):v="[aeiou]";a,b=re.split(v,x)[0],re.split(v,y)[0];return b+x[len(a):],a+y[len(b):]    #104 bytes

re.split=s
def f6(x,y):v="[aeiou]";a,b=s(v,x)[0],s(v,y)[0];return b+x[len(a):],a+y[len(b):]    #100 bytes

def f4(*g):a,b=[re.split("[aeiou]",r)[0] for r in g];x,y=g;return b+x[len(a):],a+y[len(b):]

def f5(*g):a,b=[re.split("[aeiou]",r)[0] for r in g];return b+g[0][len(a):],a+g[1][len(b):]    #10 bytes plus import

def f7(*g):a,b=map(re.split,["[aeiou]"]*2,g);a,b=a[0],b[0];return b+g[0][len(a):],a+g[1][len(b):]    #107 bytes

z=lambda*x:re.split(*x)[0]
def f8(*g):a,b=map(z,["[aeiou]"]*2,g);return b+g[0][len(a):],a+g[1][len(b):]
#return b+g[0][len(a):],a+g[1][len(b):]
示例#21
0
#!usr/bin/env python2
import os
from re import search as s

spritelist = [] # list with filenames of usable files
# adding (case-indep) .png and .jpg files to spritelist
for filename in sorted(os.listdir('./sprites')):
  if filename[-4:].lower() == '.png' or\
    filename[-4:].lower() == '.jpg':
      spritelist.append(filename)

s2 = ''; s4 = ''; s6 = ''; s8 = '';
# defining 'sources' object, which holds relative paths+filenames to sourcefiles:
for filename in spritelist:
  s2 += "  {}: '{}',\n".\
    format( s('(\w+)_',filename).group(1), 'sprites/'+filename )
# defining 'frames' object, which holds the number of frames per file:
for filename in spritelist:
  s4 += "  {}: {},\n".\
    format( s('(\w+)_',filename).group(1), s('f=(\w+)_',filename).group(1) )
# defining 'width' object, which holds the width of each file:
for filename in spritelist:
  s6 += "  {}: {},\n".\
    format( s('(\w+)_',filename).group(1), s('w=(\w+)_',filename).group(1) )
# defining 'height' object, which holds the height of each file:
for filename in spritelist:
  s8 += "  {}: {},\n".\
    format( s('(\w+)_',filename).group(1), s('h=(\w+).',filename).group(1) ) 

s1 = '''// code generated by get_imagesnames.py\n\nvar images = {};    // container for the images
var sources = {  // sources of the images\n'''
示例#22
0
    "T": 20,
    "U": 21,
    "V": 22,
    "W": 23,
    "X": 24,
    "Y": 25,
    "Z": 26
}

magic_phrase = input()
print(magic_phrase, file=sys.stderr)

# Find repetitive pattern
pattern = "(.+?)\\1+"
possibleLoops = []
patternsFound = re.s(pattern, magic_phrase)
for patternFound in patternsFound:
    print("Group: ",
          patternFound.group(1),
          patternFound.start(1),
          patternFound.end(1),
          patternFound.end(0),
          file=sys.stderr)

# Find repetitive pattern
allmatch = re.findall("(.+?)\\1+", magic_phrase)
print(allmatch, file=sys.stderr)

# magic_number = [letters[letter] for letter in magic_phrase]
# print(magic_number,file= sys.stderr)
示例#23
0
else:
    width = col_count

# Generating matrix subplots
i = 0
os.chdir(lyrics_dir)
plt.figure(figsize=(10 * width, 11 * height), dpi=dpi)
for file in glob('*.txt'):
    i += 1

    lyrics = []
    with open(file) as file_lines:
        for line in file_lines:
            line_words = line.split(' ')
            for word in line_words:
                sanitized_word = s('[^a-zA-Z0-9_]+', '', word.lower())
                lyrics.append(sanitized_word)

    matrix = []
    for y in lyrics:
        row = []
        for x in lyrics:
            if x == y:
                row.append(1)
            else:
                row.append(0)
        matrix.append(row)

    if formatted_title is True:
        track_no, artist, album, title = file.split('_')
        artist = s('-', ' ', artist)