Exemplo n.º 1
0
def main():
    tests = [test_print_welcome, test_print_goodbye, test_calc_boarded, test_run_sim, test_main]
#    tests = [test_run_sim]
    for test in tests:
        test()

    print('', end = '\n\n')
    for test in tests:
        name = test.__name__[5:]

        string = c.cyan('Final score for ') + c.purple('{0:<13} ') + c.cyan('is ') + c.purple('{1:.2f}')
        print(string.format(name, pts[name]))
        if deduct[name] != []:
            for deduction in deduct[name]:
                print(deduction + '\n')

    print(string.format('user input', pts['ui']))
    if deduct['ui'] != []:
        for deduction in deduct['ui']: print(deduction)
    print(string.format('formatting', pts['format']))
    if deduct['format'] != []:
        for deduction in deduct['format']: print(deduction)

    total = str(sum(pts[k] for k in pts.keys()))
    print(c.cyan('\n\nTotal score for ') + c.blue('p2p2_sim.py') + c.cyan(' is ') + c.purple(total))
Exemplo n.º 2
0
    def build_tree(items, level=0):
        """
        Builds a list-of-lists tree (in forward order) from a stack (reversed order),
        and formats the elements on the fly, discarding everything not eligible for
        inclusion.
        """
        subtree = []

        while items:
            nested = []
            while items[0].level > level:
                nested.append(items.pop(0))
            if nested:
                subtree.append(build_tree(nested, level + 1))

            item = items.pop(0)
            if item.string:
                string = item.string
                if level == 0:
                    subtree.append(string.format(**kwargs))
                else:
                    fields = re.findall(r"({(\w+)[^}]*})", string)
                    successful_fields = 0
                    for fieldspec, fieldname in fields:
                        if kwargs.get(fieldname, False):
                            successful_fields += 1
                    if successful_fields == len(fields):
                        subtree.append(string.format(**kwargs))
                    else:
                        return []
        return subtree
Exemplo n.º 3
0
    def build_tree(items, level=0):
        """
        Builds a list-of-lists tree (in forward order) from a stack (reversed order),
        and formats the elements on the fly, discarding everything not eligible for
        inclusion.
        """
        subtree = []

        while items:
            nested = []
            while items[0].level > level:
                nested.append(items.pop(0))
            if nested:
                subtree.append(build_tree(nested, level + 1))

            item = items.pop(0)
            if item.string:
                string = item.string
                if level == 0:
                    subtree.append(string.format(**kwargs))
                else:
                    fields = formatp.field_re.findall(string)
                    successful_fields = 0
                    for fieldspec, fieldname in fields:
                        if kwargs.get(fieldname, False):
                            successful_fields += 1
                    if successful_fields == len(fields):
                        subtree.append(string.format(**kwargs))
                    else:
                        return []
        return subtree
Exemplo n.º 4
0
def finish(rslt):
    """This function simply finalizes the logging."""
    # We want to record the overall performance.
    num_tests_total, num_success = 0, 0
    for module in sorted(rslt.keys()):
        for test in sorted(rslt[module].keys()):
            num_tests_total += np.sum(rslt[module][test])
            num_success += rslt[module][test][0]

    with open("property.soepy.info", "a") as outfile:
        string = "{:>18}{:>15}\n"
        outfile.write(string.format(*["Success", num_tests_total]))
        outfile.write(string.format(*["Total", num_success]))

        outfile.write("\n TERMINATED")
Exemplo n.º 5
0
def finish(rslt):
    """This function simply finalizes the logging."""
    # We want to record the overall performance.
    num_tests_total, num_success = 0, 0
    for module in sorted(rslt.keys()):
        for test in sorted(rslt[module].keys()):
            num_tests_total += np.sum(rslt[module][test])
            num_success += rslt[module][test][0]

    with open('property.grmpy.info', 'a') as outfile:
        string = '{:>18}{:>15}\n'
        outfile.write(string.format(*['Success', num_tests_total]))
        outfile.write(string.format(*['Total', num_success]))

        outfile.write('\n TERMINATED')
Exemplo n.º 6
0
def processGPSChunk(chunk):
    data = struct.unpack("?3f", chunk)
    fix = data[0]
    if fix:
        print(string.format("GPS FIX\t%2.6f\t%2.6f\t%3.1f"), data[1], data[2],
              data[3])
    else:
        print("No gps fix")
Exemplo n.º 7
0
def _format_lazy(string, *args, **kwargs):
    """Lazily format a lazy string."""
    allow_markup = kwargs.pop('allow_markup', False)
    string = str(string)
    string = string.format(*args, **kwargs)
    if allow_markup:
        string = markupsafe.Markup(string)

    return string
Exemplo n.º 8
0
def format_lazy(string, *args, **kwargs):
    """Implements a lazy variant of the ``format`` string method.  For
    example, you might say::

        verbose_name = format_lazy(_(u"Raman {0} measurement"), 1)

    Here, “``_``” is ``ugettext_lazy``.
    """
    return string.format(*args, **kwargs)
Exemplo n.º 9
0
def format_lazy(string, *args, **kwargs):
    """Implements a lazy variant of the ``format`` string method.  For
    example, you might say::

        verbose_name = format_lazy(_(u"Raman {0} measurement"), 1)

    Here, “``_``” is ``ugettext_lazy``.
    """
    return string.format(*args, **kwargs)
Exemplo n.º 10
0
def print_rslt_ext(start, timeout, rslt, err_msg):
    """This function print out the current state of the property tests."""

    start_time = start.strftime("%Y-%m-%d %H:%M:%S")
    end_time = (start + timeout).strftime("%Y-%m-%d %H:%M:%S")
    current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")

    with open('property.grmpy.info', 'w') as outfile:

        # Write out some header information.
        outfile.write('\n\n')
        str_ = '\t{0[0]:<15}{0[1]:<20}\n\n'
        outfile.write(str_.format(['START', start_time]))
        outfile.write(str_.format(['FINISH', end_time]))
        outfile.write(str_.format(['UPDATE', current_time]))

        modules = sorted(rslt.keys())

        for module in modules:

            outfile.write('\n ' + module.replace('.py', '') + '\n\n')

            string = '{:>18}{:>15}{:>15}\n\n'
            outfile.write(string.format('Test', 'Success', 'Failure'))

            for test in sorted(rslt[module].keys()):

                stat = rslt[module][test]

                string = '{:>18}{:>15}{:>15}\n'
                outfile.write(string.format(*[test] + stat))

            outfile.write('\n')
        outfile.write('\n' + '-' * 79 + '\n\n')

        for err in err_msg:

            module, test, seed, msg = err

            string = 'MODULE {:<25} TEST {:<15} SEED {:<15}\n\n'
            outfile.write(string.format(*[module, test, seed]))
            outfile.write(msg)
            outfile.write('\n' + '-' * 79 + '\n\n')
Exemplo n.º 11
0
 def process_reply(self, string):
     """This version of process_reply does Eliza style swapping of first and
     second person, and creates a match dictionary containing swapped versions
     of all the match variables that it then passes to str.format
     """
     reflected_matches = {}
     for k, v in self.match.items():
         reflected_matches[k] = v
         reflected_matches["refl_" + k] = self.reflect(v)
     return string.format(*[], **reflected_matches)
Exemplo n.º 12
0
 def process_reply(self, string):
     """This version of process_reply does Eliza style swapping of first and
     second person, and creates a match dictionary containing swapped versions
     of all the match variables that it then passes to str.format
     """
     reflected_matches = {}
     for k, v in self.match.items():
         reflected_matches[k] = v
         reflected_matches["refl_" + k] = self.reflect(v)
     return string.format(*[], **reflected_matches)
Exemplo n.º 13
0
def print_rslt_ext(start, timeout, rslt, err_msg):
    """This function print out the current state of the property tests."""

    start_time = start.strftime("%Y-%m-%d %H:%M:%S")
    end_time = (start + timeout).strftime("%Y-%m-%d %H:%M:%S")
    current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")

    with open("property.soepy.info", "w") as outfile:

        # Write out some header information.
        outfile.write("\n\n")
        str_ = "\t{0[0]:<15}{0[1]:<20}\n\n"
        outfile.write(str_.format(["START", start_time]))
        outfile.write(str_.format(["FINISH", end_time]))
        outfile.write(str_.format(["UPDATE", current_time]))

        modules = sorted(rslt.keys())

        for module in modules:

            outfile.write("\n " + module.replace(".py", "") + "\n\n")

            string = "{:>18}{:>15}{:>15}\n\n"
            outfile.write(string.format("Test", "Success", "Failure"))

            for test in sorted(rslt[module].keys()):

                stat = rslt[module][test]

                string = "{:>18}{:>15}{:>15}\n"
                outfile.write(string.format(*[test] + stat))

            outfile.write("\n")
        outfile.write("\n" + "-" * 79 + "\n\n")

        for err in err_msg:

            module, test, seed, msg = err

            string = "MODULE {:<25} TEST {:<15} SEED {:<15}\n\n"
            outfile.write(string.format(*[module, test, seed]))
            outfile.write(msg)
            outfile.write("\n" + "-" * 79 + "\n\n")
Exemplo n.º 14
0
def create_format_dict(conf, streamers, utcdate=None, truedate=None):
    thistz = None
    datestring = None
    if truedate == None:
        try:
            # https://stackoverflow.com/a/37097784/13977827
            sign, hours, minutes = re.match('([+\-]?)(\d{2})(\d{2})',
                                            conf['stage_timezone']).groups()
            sign = -1 if sign == '-' else 1
            hours, minutes = int(hours), int(minutes)

            thistz = timezone(sign * timedelta(hours=hours, minutes=minutes))
        except:
            util.exit_prog(73, f"Unknown timezone {conf['stage_timezone']}")
        date = datetime.strptime(
            utcdate, "%Y-%m-%dT%H:%M:%SZ").replace(tzinfo=timezone.utc)
        datestring = date.astimezone(thistz).strftime("%Y/%m/%d")
    else:
        datestring = truedate

    formatdict = {
        "date": datestring,
        "link": f"https://twitch.tv/{streamers[0]}",
        "streamer": streamers[0],
        "links": " ".join([f"https://twitch.tv/{s}" for s in streamers]),
        "streamers": streamers,
    }

    # first pass format
    for x in range(2):
        for item, string in conf["stage_format"].items():
            try:
                string = string.format(**formatdict)
                formatdict[item] = string
            except KeyError as err:
                # ignore errors on first pass
                if x == 1:
                    util.exit_prog(81, f"Format failed: {err}")

    return formatdict, datestring
Exemplo n.º 15
0
    def fmt(self, string, **kwargs):
        """ Format a string.
        self.fmt(string) vs string.format(self=self)
        self.fmt(string, foo=2) vs string.format(foo=2, self=self)

        Adds self as formatting argument, and prefix keys with self., if key not in arguments.
        {foo} => {self.foo}.format(self=self)
        {foo} kwargs(foo=2) => {foo}.format(foo=foo)
        {foo.bar} kwargs(foo=2) => {foo}.format(self=self)
        """
        for times in range(6):
            keys = []
            if isinstance(string, basestring):
                string = self.escape_bad_matches(string)
                if '{' not in string:
                    break
                keys = self.fmtkeys(string)
            else:
                return string
            kwargs_keys = kwargs.keys()
            for key in keys:
                if key not in kwargs_keys:
                    if not key.startswith('self.'):
                        realkey = key.split('.')[0]
                        if hasattr(self, realkey):
                            if self.strict_fmt and getattr(self, realkey) is None:
                                raise Exception("Undefined key: {}".format(realkey))
                            string = string.replace('{'+key+'}', '{self.'+key+'}')
                        else:
                            if not self.strict_fmt:
                                kwargs.setdefault(key, '')
            if '{self.' in string:
                kwargs['self'] = self
            try:
                string = string.format(**kwargs)
            except AttributeError, e:
                print 'FMT failed for: {} with {}'.format(string, kwargs)
                raise
Exemplo n.º 16
0
def code_string(string, *args, **kwargs):
    """
    Fix an indented multi-line string. Example:

        csharp = helpers.code_string('''
                    Console.WriteLine("{arg1}" + "{arg2}");
                    ''', arg1='ex', arg2='ample')

    This will de-indent the code, remove the leading newline, remove trailing
    whitespace, and call `string.format()` on it.

    :param string: String to format
    :param *args: Arguments to pass to `string.format()`
    :param *kwargs: Keyword arguments to pass to `string.format()`
    :return: Formatted code
    """

    # pre-format de-indent
    string = textwrap.dedent(string)

    # format string
    if kwargs or args:
        string = string.format(*args, **kwargs)

    # remove leading newline
    if string.startswith('\n'):
        string = string[1:]

    # remove last line if it's empty or just whitespace
    lines = string.splitlines()
    if not lines[-1] or lines[-1].isspace():
        string = '\n'.join(lines[:-1])

    # post-format de-indent
    string = textwrap.dedent(string)

    return string
Exemplo n.º 17
0
def fmt(string, environ):
    '''String formatting and sanitization function'''
    return string.format(**environ)
Exemplo n.º 18
0
def mysql_connect(user, password, host, db, **kwargs):
    """Return a SQLAlchemy connection to the specified server."""

    string = r"mysql+pymysql://{user}:{password}@{host}/{db}?charset=utf8"
    cxn_string = string.format(user=user, password=password, host=host, db=db)
    return sqlalchemy.create_engine(cxn_string, **kwargs)
Exemplo n.º 19
0
def f(string):
    "like the f-string in 3.6+"
    frame = sys._getframe(1)
    return string.format(**frame.f_locals)
Exemplo n.º 20
0
async def send_note(chat_id, group_id, msg_id, note_name,
                    show_none=False, noformat=False, preview=False,
                    from_id=""):
    file_id = None
    note_name = note_name.lower()
    note = mongodb.notes.find_one({'chat_id': int(group_id), 'name': note_name})
    if not note and show_none is True:
        text = get_string("notes", "note_not_found", chat_id)
        all_notes = mongodb.notes.find({'chat_id': group_id})
        if all_notes.count() > 0:
            check = difflib.get_close_matches(note_name, [d['name'] for d in all_notes])
            if len(check) > 0:
                text += "\nDid you mean `#{}`?".format(check[0])

        await tbot.send_message(chat_id, text, reply_to=msg_id)
        return
    elif not note:
        return None

    if note['file_id']:
        file_id = note['file_id']

    if not file_id:
        file_id = None

    if 'encrypted' not in note or note['encrypted'] is False:
        raw_note_text = note['text']

    elif 'encrypted' in note:
        if note['encrypted'] == 'particle-v1':
            raw_note_text = bz2.decompress(base64.urlsafe_b64decode(note['text'])).decode()

    if noformat is True:
        format = None
        string = raw_note_text
        buttons = ""
    else:
        string, buttons = button_parser(group_id, raw_note_text)
        h = re.search(r"(\[format:(markdown|md|html|none)\])", string)
        if h:
            string = string.replace(h.group(1), "")
            format_raw = h.group(2).lower()
            if format_raw == 'markdown' or format_raw == 'md':
                format = 'md'
            elif format_raw == 'html':
                format = 'html'
            elif format_raw == 'none':
                format = None
        else:
            format = 'md'

        r = re.search(r"(\[preview:(yes|no)\])", string)
        if r:
            string = string.replace(r.group(1), "")
            preview_raw = r.group(2).lower()
            if preview_raw == "yes":
                preview = True
            elif preview_raw == "no":
                preview = False

    if len(string.rstrip()) == 0:
        if noformat is True:
            string = "Note {}\n\n".format(note_name)
        else:
            string = "**Note {}**\n\n".format(note_name)

    if not buttons:
        buttons = None

    if from_id:
        user = mongodb.user_list.find_one({"user_id": from_id})
        if not user:
            user = await add_user_to_db(await tbot(GetFullUserRequest(int(from_id))))
        if 'last_name' in user:
            last_name = user['last_name']
            if not last_name:
                last_name = ""
            full_name = user['first_name'] + " " + last_name
        else:
            last_name = None
            full_name = user['first_name']

        if 'username' in user and user['username']:
            username = "******" + user['username']
        else:
            username = None

        chatname = mongodb.chat_list.find_one({'chat_id': group_id})
        if chatname:
            chatname = chatname['chat_title']
        else:
            chatname = "None"

        if noformat is False:
            if format == "md":
                mention_str = await user_link(from_id)
            elif format == "html":
                mention_str = await user_link_html(from_id)
            elif format == "none":
                mention_str = full_name

            try:
                string = string.format(
                    first=user['first_name'],
                    last=last_name,
                    fullname=full_name,
                    username=username,
                    id=from_id,
                    mention=mention_str,
                    chatname=chatname
                )
            except KeyError as var:
                await tbot.send_message(chat_id, f"variable `{var}` not supported! Please delete it from note.", reply_to=msg_id)
                return

    try:
        return await tbot.send_message(
            chat_id,
            string,
            buttons=buttons,
            parse_mode=format,
            reply_to=msg_id,
            file=file_id,
            link_preview=preview
        )
    except Exception as err:
        await tbot.send_message(chat_id, str(err))
        logger.error("Error in send_note/send_message: " + str(err))
Exemplo n.º 21
0
async def send_note(chat_id, group_id, msg_id, note_name,
                    show_none=False, noformat=False, preview=False,
                    from_id="", key=False):
    file_id = None
    note_name = note_name.lower()
    note = mongodb.notes.find_one({'chat_id': int(group_id), 'name': note_name})
    if not note and show_none is True:
        text = get_string("notes", "note_not_found", chat_id)
        all_notes = mongodb.notes.find({'chat_id': group_id})
        if all_notes.count() > 0:
            check = difflib.get_close_matches(note_name, [d['name'] for d in all_notes])
            if len(check) > 0:
                text += "\nDid you mean `#{}`?".format(check[0])

        await tbot.send_message(chat_id, text, reply_to=msg_id)
        return
    elif not note:
        return None

    if note['file_id']:
        file_id = note['file_id']

    if not file_id:
        file_id = None

    if 'encrypted' not in note or note['encrypted'] is False:
        raw_note_text = note['text']

    elif 'encrypted' in note:
        if note['encrypted'] == 'particle-v1':
            raw_note_text = bz2.decompress(base64.urlsafe_b64decode(note['text'])).decode()
        else:
            if not key:
                await tbot.send_message(chat_id, "This note encrypted! Please write a password!",
                                        reply_to=msg_id)
                return
            salt = note['encrypted']
            kdf = PBKDF2HMAC(
                algorithm=hashes.SHA256(),
                length=32,
                salt=salt,
                iterations=100000,
                backend=default_backend()
            )
            key = base64.urlsafe_b64encode(kdf.derive(key.encode()))
            f = Fernet(key)
            try:
                raw_note_text = f.decrypt(note['text']).decode()
                if file_id:
                    file_id = f.decrypt(file_id).decode()
            except InvalidToken:
                await tbot.send_message(chat_id, "Invalid password!", reply_to=msg_id)
                return

    if noformat is True:
        format = None
        string = raw_note_text
        buttons = ""
    else:
        string, buttons = button_parser(group_id, raw_note_text)
        h = re.search(r"(\[format:(markdown|md|html|none)\])", string)
        if h:
            string = string.replace(h.group(1), "")
            format_raw = h.group(2).lower()
            if format_raw == 'markdown' or format_raw == 'md':
                format = 'md'
            elif format_raw == 'html':
                format = 'html'
            elif format_raw == 'none':
                format = None
        else:
            format = 'md'

        r = re.search(r"(\[preview:(yes|no)\])", string)
        if r:
            string = string.replace(r.group(1), "")
            preview_raw = r.group(2).lower()
            if preview_raw == "yes":
                preview = True
            elif preview_raw == "no":
                preview = False

    if len(string.rstrip()) == 0:
        if noformat is True:
            string = "Note {}\n\n".format(note_name)
        else:
            string = "**Note {}**\n\n".format(note_name)

    if not buttons:
        buttons = None

    if from_id:
        user = mongodb.user_list.find_one({"user_id": from_id})
        if not user:
            user = await add_user_to_db(await tbot(GetFullUserRequest(int(from_id))))
        if 'last_name' in user:
            last_name = user['last_name']
            if not last_name:
                last_name = ""
            full_name = user['first_name'] + " " + last_name
        else:
            last_name = None
            full_name = user['first_name']

        if 'username' in user and user['username']:
            username = "******" + user['username']
        else:
            username = None

        chatname = mongodb.chat_list.find_one({'chat_id': group_id})
        if chatname:
            chatname = chatname['chat_title']
        else:
            chatname = "None"

        if noformat is True:
            string = string.format(
                first="{first}",
                last="{last}",
                fullname="{fullname}",
                username="******",
                mention="{mention}",
                id="{id}",
                chatname="{chatname}",
            )
        else:
            if format == "md":
                mention_str = await user_link(from_id)
            elif format == "html":
                mention_str = await user_link_html(from_id)
            elif format == "none":
                mention_str = full_name

            string = string.format(
                first=user['first_name'],
                last=last_name,
                fullname=full_name,
                username=username,
                id=from_id,
                mention=mention_str,
                chatname=chatname
            )

    try:
        return await tbot.send_message(
            chat_id,
            string,
            buttons=buttons,
            parse_mode=format,
            reply_to=msg_id,
            file=file_id,
            link_preview=preview
        )
    except Exception as err:
        await tbot.send_message(chat_id, str(err))
        logger.error("Error in send_note/send_message: " + str(err))
Exemplo n.º 22
0
 def formatter(**dic):
     return dic[u'_formatter'].format_command(string.format(**dic))
Exemplo n.º 23
0
def _format_lazy(string, *args, **kwargs):
    """Lazily format a lazy string."""
    string = str(string)
    return string.format(*args, **kwargs)
Exemplo n.º 24
0
#!/usr/bin/python3
import dectobin #Module...defined later
import string #Module.....defined later

a=int(raw_input("Enter a decimal number: "))

if a<0:
	print ("Try entering a positive number/0 ")
elif a==0:
	print ("Binary: 0")
else:
	list=dectobin.conv(a)
	list1=string.format(list)

print ("Binary: " ,list1)
Exemplo n.º 25
0
 def formatter(**kwargs):
     return string.format(**kwargs)
Exemplo n.º 26
0
def _format_lazy(string, *args, **kwargs):
    """Lazily format a lazy string."""
    string = str(string)
    return string.format(*args, **kwargs)
Exemplo n.º 27
0
def fmt(string, environ):
    '''String formatting and sanitization function'''
    return string.format(**environ)
Exemplo n.º 28
0
 def writeRow(i, a, q, x, y, string):
     print string.format(i, a, q, x, y)