import warcraftAPI
import datetime
import pandas as pd
import numpy as np

df = pd.DataFrame()

#   2KMBwR79kP6fWZqC
dates = []
auth_token = warcraftAPI.get_new_token()
total_kills = 0
playerRankingLogs = warcraftAPI.getPlayerDmgOnOneBoss("Greezie", auth_token, 755)
all_kills = playerRankingLogs['data']['characterData']['character']['encounterRankings']['ranks']
for kill in all_kills:

    total_kills +=1
    peeps = {}
    attempts = 0
    report_code = kill['report']['code']
    startTime = kill['report']['startTime']
    startTime = datetime.datetime.fromtimestamp(startTime / 1000, tz=datetime.timezone.utc)
    print(startTime)
    log_of_fights = warcraftAPI.getFightIDs(report_code, auth_token)
    fights = log_of_fights['data']['reportData']['report']['fights']
    prevDate = 0
    for fight in fights:
        attempts+=1
        fight_id = fight['id']

        # get player IDS for this report
        playerNames = [0] * 1000
        shadowCrashHits = [0] * 1000
        playerInfo = warcraftAPI.getPlayerInfo(report_code, auth_token, fight_id)
        players = playerInfo['data']['reportData']['report']['playerDetails']['data']['playerDetails']
        healers = players['healers']
        for player in healers:
            playerNames[player['id']] = player['name']
            if not player['name'] in peeps:
                peeps[player['name']] = 0
        dps = players['dps']
        for player in dps:
            playerNames[player['id']] = player['name']
            if player['name'] == "Kazootie":
                print("KAZOOTIEEEEEEE")
            if not player['name'] in peeps:
                peeps[player['name']] = 0
        shadowCrashLog = warcraftAPI.getShadowCrash(report_code, auth_token, fight_id)
        crashes = shadowCrashLog['data']['reportData']['report']['events']['data']
        for crash in crashes:
            shadowCrashHits[crash['targetID']] += 1

        index = 0
        for hit in shadowCrashHits:
            if playerNames[index] != 0:
                peeps[playerNames[index]] += hit
            index+=1

    #print(peeps)
    date = startTime.date()
    dates.append(date)
    #date = str(date.month) + "/" + str(date.day) + '/' + str(date.year)
    for peep in peeps:
        df.loc[peep, date] = peeps[peep]
    #df2 = pd.DataFrame.from_dict(peeps)
    #print(df2)
    #print(attempts)

df.sort_index(axis=1, inplace=True)
dates.sort()
df_total = pd.DataFrame(columns=dates)
print(df_total)
print(df)
df.to_csv("shadowCrash.csv")
print(total_kills)


import itertools, sympy

from codepage import codepage
from ka2sym import mapping as kanamap

from utils import *

GLOBAL_REGISTER = 0

skanalist = [x for x in codepage if x not in "」アエイオ"]

numcharmap = {
    "１": "1",
    "２": "2",
    "３": "3",
    "４": "4",
    "５": "5",
    "６": "6",
    "７": "7",
    "８": "8",
    "９": "9",
    "０": "0",
    "ー": "-",
    "。": ".",
    "イ": "i",
    "シ": "j"
}

def const(x):
    return lambda: x

def parsenum(s):
    if "," in s:
        return list(map(parsenum, s.split(",")))
    if "i" in s:
        x, y = s.split("i")
        return parsenum(x or "0") + sympy.I * parsenum(y or "1")
    if "j" in s:
        x, y = s.split("j")
        return parsenum(x or "1") * sympy.Rational(10) ** parsenum(y or "3")
    if s[0] == "-":
        return -parsenum(s[1:] or "1")
    if "." in s:
        x, y = s.split(".")
        s = (x or "0") + "." + (y or "5")
    return sympy.Rational(s)

def getcalls(code):
    result = [[]]
    while code:
        if code[0] == "〜":
            code.pop(0)
            result.append([])
            continue
        call = getcall(code)
        if call is not None:
            result[-1].append(call)
    return result

def split(a, x, sub = False):
    a, x = listnumord(a, x, listdigits)
    if not sub:
        x = [x]
    xl = len(x)
    if isinstance(a, seq):
        class splitseq(seq):
            def __init__(self, pseq, psplit):
                seq.__init__(self, None)
                self.pseq = pseq
                self.psplit = psplit
                self.psl = len(psplit)
                self.index = 1
            def __iter__(self):
                self.index = 1
            def __next__(self):
                result = []
                while self.pseq[self.index:self.index + self.psl] != self.psplit:
                    result.append(self.pseq[self.index])
                    self.index += 1
                self.index += self.psl
                self.cache.append(result)
                return result
        return splitseq(a, x)
    results = [[]]
    i = 0
    while i < len(a):
        if a[i:i + xl] == x:
            results.append([])
            i += xl
        else:
            results[-1].append(a[i])
            i += 1
    return results

def stringify(x):
    if stringQ(x):
        return "".join(x)
    else:
        return str(x)

def anystr(*x):
    return any(isinstance(q, str) or stringQ(q) for q in x)

def getfun(code):
    result = []
    while code and code[0] not in ["〜", "；"]:
        call = getcall(code)
        if call is not None:
            result.append(call)
    if code:
        code.pop(0)
    return result

def yrange(x, lo, hi):
    if isinstance(x, str):
        x = sympy.Number(ord(x))
    re, im = x.as_real_imag()
    if re > 0:
        main = list(map(sympy.Number, range(lo, int(re) + hi)))
    else:
        main = list(map(sympy.Number, range(lo - 1, int(sympy.ceiling(re)) - hi, -1)))
    if im == 0:
        return main
    else:
        if im > 0:
            dim = list(map(sympy.Number, range(int(im) + 1)))
        else:
            dim = list(map(sympy.Number, range(0, int(sympy.ceiling(im)) - 1, -1)))
        return [[x + y * sympy.I for y in dim] for x in main]

def ispyiter(x):
    return isinstance(x, list) or isinstance(x, tuple) or isinstance(x, set) or isinstance(x, dict)

def isiter(x):
    return isinstance(x, list) or isinstance(x, seq)

def listrange(x):
    return listcoerce(x) if ispyiter(x) else yrange(x, 1, 1)

def listwrap(x):
    return listcoerce(x) if ispyiter(x) else [x]

def listdigits(x):
    return listcoerce(x) if ispyiter(x) else list(map(int, str(x))) if x % 1 == 0 else list(str(x))

def listcoerce(x):
    return list(x) if ispyiter(x) and not isinstance(x, list) else x

def listnumord(x, y, autolist = lambda x: x):
    if not isiter(x) and isiter(y):
        return (y, x)
    if not isiter(x):
        return (autolist(x), y)
    return (x, y)

def getnextcall(code):
    call = None
    while call is None:
        call = getcall(code)
    return call

def frombase(digits, base):
    tot = sympy.Number(0)
    for x in digits[::-1]:
        tot *= base
        tot += x
    return tot

def getcall(code):
    char = code.pop(0)
    if char == "　":
        return None
    elif char == "「":
        slist = [[]]
        while code and code[0] not in "」アエイオ":
            if code[0] == "「":
                slist.append([])
            else:
                slist[-1].append(code[0])
            code.pop(0)
        term = code.pop(0) if code else "」"
        if term == "」":
            slist = [list("".join([kanamap[x] for x in row])) for row in slist]
        elif term == "ア":
            slist = [[skanalist.index(x) for x in row] for row in slist]
        elif term == "エ":
            slist = [list("".join(x)) for x in slist]
        elif term == "オ":
            slist = [frombase([skanalist.index(x) for x in row], 250) for row in slist]
        else:
            slist = ["TODO - string ending with " + term]
        if len(slist) == 1:
            slist = slist[0]
        return (0, const(slist))
    elif char in "１２３４５６７８９０。イシー":
        neg = char == "ー"
        dec = False
        exp = False
        cmp = False
        s = numcharmap[char]
        while code and (code[0] in "１２３４５６７８９０" or \
                           not dec and code[0] == "。" or \
                           not exp and code[0] == "シ" or \
                           not cmp and code[0] == "イ" or \
                           not neg and code[0] == "ー" or \
                           code[0] == "、" and len(code) > 1 and code[1] in "１２３４５６７８９０。イシー"):
            char = code.pop(0)
            if char in "１２３４５６７８９０":
                s += numcharmap[char]
            elif char == "、":
                neg = dec = exp = cmp = False
                s += ","
            elif char == "。":
                dec = True
                s += "."
            elif char == "ー":
                neg = True
                s += "-"
            elif char == "シ":
                neg = False
                exp = True
                dec = False
                s += "j"
            elif char == "イ":
                neg = False
                cmp = True
                exp = False
                dec = False
                s += "i"
        return (0, const(parsenum(s)))
    elif char == "」":
        if code:
            char = kanamap[code.pop(0)]
        else:
            char = " "
        return (0, const(char))
    elif char == "カ":
        if code:
            char = code.pop(0)
        else:
            char = "　"
        return (0, const(char))
    elif char == "ア":
        def add(x, y):
            if anystr(x, y):
                return list(stringify(x) + stringify(y))
            return x + y
        return (2, sqvecd(add))
    elif char == "ミ":
        def sub(x, y):
            if stringQ(x) or stringQ(y) or isinstance(x, str) or isinstance(y, str):
                raise SystemExit("No implementation for subtracting strings yet.")
            return x - y
        return (2, sqvecd(sub))
    elif char == "ム":
        def mul(x, y):
            if anystr(x, y):
                raise SystemExit("No implementation for multiplying strings yet (use repetition).")
            return x * y
        return (2, sqvecd(mul))
    elif char == "ディ":
        def tdiv(x, y):
            if anystr(x, y):
                raise SystemExit("No implementation for true-dividing strings yet (use list cutting).")
            if y == 0:
                return sympy.Number(0)
            return x / y
        return (2, sqvecd(tdiv))
    elif char == "ヂ":
        def fdiv(x, y):
            if anystr(x, y):
                raise SystemExit("No implementation for floor-dividing strings yet (use list cutting).")
            if y == 0:
                return sympy.Number(0)
            return x // y
        return (2, sqvecd(fdiv))
    elif char == "％":
        def modulo(x, y):
            if anystr(x, y):
                raise SystemExit("No implementation for modulo on strings yet.")
            if y == 0:
                return sympy.Number(0)
            return x % y
        return (2, sqvecd(modulo))
    elif char == "ラ":
        return (1, lambda x: vecm(lambda y: yrange(y, 1, 1), x))
    elif char == "レ":
        return (1, lambda x: vecm(lambda y: yrange(y, 0, 1), x))
    elif char == "リ":
        return (1, lambda x: vecm(lambda y: yrange(y, 1, 0), x))
    elif char == "ロ":
        return (1, lambda x: vecm(lambda y: yrange(y, 0, 0), x))
    elif char == "ン":
        return (1, lambda x: vecm(lambda y: y + 1, x))
    elif char == "デ":
        return (1, lambda x: vecm(lambda y: y - 1, x))
    elif char == "コ":
        arity, func = getnextcall(code)
        def handle(*a):
            a = list(a)
            re, im = a[0].as_real_imag()
            a[0] = im
            out = run(_program, _index, a, [(arity, func)])
            return tuple(re + x * sympy.I for x in out)
        return (arity, handle)
    elif char == "＄":
        a1, f1 = getnextcall(code)
        a2, f2 = getnextcall(code)
        return (a1, lambda *a: (lambda b: f2(*(b[-a2:] if a2 != -1 else b)))(listwrap(f1(*a))))
    elif char == "ネ":
        return (1, lambda x: vecm(lambda y: y.swapcase() if isinstance(y, str) else -y, x))
    elif char == "マ":
        arity, func = getnextcall(code)
        def handle(*a):
            a = list(a)
            if isinstance(a[0], seq):
                return fseq(lambda i: run(_program, _index, [a[0][i], *a[1:]], [(arity, func)]))
            if not isinstance(a[0], list):
                a[0] = yrange(a[0], 1, 1)
            return [listcoerce(run(_program, _index, [q, *a[1:]], [(arity, func)])) for q in a[0]]
        return (arity, handle)
    elif char == "メ":
        arity, func = getnextcall(code)
        def handle(*a):
            a = list(a)
            if isinstance(a[1], seq):
                return fseq(lambda i: run(_program, _index, [a[0], a[1][i], *a[2:]], [(arity, func)]))
            if not isinstance(a[1], list):
                a[1] = yrange(a[1], 1, 1)
            return [listcoerce(run(_program, _index, [a[0], q, *a[2:]], [(arity, func)])) for q in a[1]]
        return (arity, handle)
    elif char == "ヌ":
        return (1, lambda x: vecm(lambda k: len(k) if isinstance(k, list) or isinstance(k, str) else len(str(k).replace(" ", "")), x, lambda k: not isinstance(k, seq)))
    elif char == "ッキャ":
        return (-1, lambda *a: tuple(run(_program, _index, list(a))))
    elif char == "ッキョ":
        return (-1, lambda *a: tuple(run(_program, _index - 1, list(a))))
    elif char == "ッキュ":
        return (-1, lambda *a: tuple(run(_program, _index + 1, list(a))))
    elif char == "？":
        a1, f1 = getnextcall(code)
        a2, f2 = getnextcall(code)
        a3, f3 = getnextcall(code)
        def handle(*a):
            stack = list(a)
            res = listwrap(run(_program, _index, stack[:], [(a1, f1)]))[-1]
            return tuple(run(_program, _index, stack, [(a2, f2) if res else (a3, f3)]))
        return (-1, handle)
    elif char == "フ":
        fs = []
        while code and code[0] != "；":
            call = getcall(code)
            if call is not None:
                fs.append(call)
        if code:
            code.pop(0)
        return (fs[0][0] if fs else arity, lambda *a: tuple(listwrap(run(_program, _index, list(a), fs))))
    elif char == "モ":
        code.insert(0, "マ")
        code.insert(1, "フ")
        return None
    elif char == "、":
        return (2, lambda a, b: [a, b])
    elif char == "ップ":
        code.insert(0, "メ")
        code.insert(1, "マ")
        return None
    elif char == "ｒ":
        return (0, lambda: GLOBAL_REGISTER)
    elif char == "Ｒ":
        def setreg(x):
            global GLOBAL_REGISTER
            GLOBAL_REGISTER = x
            return x
        return (1, setreg)
    elif char == "ル":
        a1, f1 = getnextcall(code)
        def handle():
            global GLOBAL_REGISTER
            stack = [GLOBAL_REGISTER]
            GLOBAL_REGISTER = (listwrap(run(_program, _index, stack, [(a1, f1)])) or [sympy.Number(0)])[-1]
            return ()
        return (0, handle)
    elif char == "ドゥ":
        return (1, lambda a: (a, a))
    elif char == "＠":
        return (2, lambda a, b: (b, a))
    elif char == "パ":
        return (2, lambda a, b: listwrap(a) + listwrap(b))
    elif char == "タ":
        return (2, lambda a, b: listwrap(b) + listwrap(a))
    elif char == "ス":
        return (2, split)
    elif char == "ッス":
        return (2, lambda x, y: split(x, y, True))
    elif char == "ッパ":
        def prefixes(a):
            if isinstance(a, list):
                return [a[:i] for i in range(len(a) + 1)]
            elif isinstance(a, seq):
                return fseq(lambda i: a[:i])
            else:
                return prefixes(yrange(a, 1, 1))
        return (1, prefixes)
    elif char == "ッペ":
        def permutations(a):
            return list(map(list, itertools.permutations(a)))
        return (1, permutations)
    elif char == "ヴェ":
        arity, func = getnextcall(code)
        def handle(*a):
            a = list(map(listrange, a))
            return [func(*x) for x in zip(*a)]
        return (arity, handle)
    elif char == "ジ":
        return (1, lambda a: (lambda q: [[k[i] for k in a] for i in range(q)])(max(map(len, a))))
    elif char == "ッタ":
        return (2, lambda a, b: (lambda x, y: vecm(lambda q: x[q - 1:], y))(*listnumord(a, b, listrange)))
    elif char == "ヘ":
        return (2, lambda a, b: (lambda x, y: vecm(lambda q: x[:q], y))(*listnumord(a, b, listrange)))
    elif char == "ジョ":
        def join(a, b):
            a, b = listnumord(a, b, listrange)
            b = listwrap(b)
            if isinstance(a, list):
                if not a:
                    return []
                res = []
                for x in a[:-1]:
                    res += listwrap(x)
                    res += b[:]
                return res + listwrap(a[-1])
            elif isinstance(a, seq):
                class joinseq(seq):
                    def __init__(self, pseq, joiner):
                        seq.__init__(self, None)
                        self.pseq = pseq
                        self.joiner = joiner
                        self.queue = []
                        self.psindex = 1
                    def __iter__(self):
                        self.queue = []
                        self.psindex = 1
                    def __next__(self):
                        while not self.queue:
                            self.queue.extend(listwrap(self.pseq[self.psindex]))
                            self.queue.extend(self.joiner)
                            self.psindex += 1
                        val = self.queue.pop(0)
                        self.cache.append(val)
                        return val
                return joinseq(a, b)
        return (2, join)
    elif char == "ソ":
        return (1, lambda x: vecm(sorted, listdigits(x), lambda q: isinstance(q, list)))
    elif char == "リャ":
        return (2, lambda a, b: vecd(lambda x, y: x[-(y % len(x)):] + x[:-(y % len(x))], *listnumord(a, b, listrange), lambda x: isinstance(x, list)))
    elif char == "リョ":
        return (2, lambda a, b: vecd(lambda x, y: x[(y % len(x)):] + x[:(y % len(x))], *listnumord(a, b, listrange), lambda x: isinstance(x, list)))
    elif char == "ッシュ":
        def sublists(a):
            if not isiter(a):
                a = listrange(a)
            if isinstance(a, list):
                results = []
                for length in range(1, len(a) + 1):
                    for start in range(len(a) - length + 1):
                        results.append(a[start:start + length])
                return results
            elif isinstance(a, seq):
                class subseq(seq):
                    def __init__(self, pseq):
                        seq.__init__(self, None)
                        self.pseq = pseq
                        self.queue = [[]]
                        self.qi = 1
                        self.vi = 1
                    def __iter__(self):
                        self.queue = [[]]
                        self.qi = 1
                        self.vi = 1
                    def __next__(self):
                        if self.qi >= len(self.queue):
                            self.queue.extend([[*x, self.pseq[self.vi]] for x in self.queue])
                            self.vi += 1
                        val = self.queue[self.qi]
                        self.qi += 1
                        self.cache.append(val)
                        return val
                return subseq(a)
        return (1, sublists)
    elif char == "フィ":
        arity, func = getnextcall(code)
        def handle(*a):
            a = list(a)
            if isinstance(a[0], seq):
                return filterseq(a[0], lambda x: run(_program, _index, [x, *a[1:]], [(arity, func)]))
            if not isinstance(a[0], list):
                a[0] = yrange(a[0], 1, 1)
            return [q for q in a[0] if (run(_program, _index, [q, *a[1:]], [(arity, func)]) or [0])[-1]]
        return (arity, handle)
    elif char == "フェ":
        code.insert(0, "フィ")
        code.insert(1, "フ")
        return None
    elif char == "ビ":
        return (1, lambda x: vecm(lambda y: y % 2, x))
    elif char == "ッコ":
        def count(x, y):
            if isinstance(y, seq):
                return fseq(lambda i: count(x, y[i]))
            return x.count(y)
        return (2, lambda x, y: (lambda a, b: vecm(lambda q: count(q, b), a, lambda v: isinstance(v, list)))(*listnumord(x, y, listdigits)))
    elif char == "ッキ":
        def recursivecount(x, y):
            if isinstance(y, seq):
                return fseq(lambda i: recursivecount(x, y[i]))
            normcount = x.count(y)
            if normcount == 0 and isinstance(y, list):
                subcounts = [recursivecount(x, b) for b in y]
                if any(subcounts):
                    return subcounts
            return normcount
        return (2, lambda x, y: (lambda a, b: vecm(lambda q: recursivecount(q, b), a, lambda v: isinstance(v, list)))(*listnumord(x, y, listdigits)))
    elif char == "イェ":
        return (1, lambda x: x)
    elif char == "ッカ":
        def allequal(x):
            x = listdigits(x)
            return sympy.Number(all(y == x[0] for y in x[1:])) if x else sympy.Number(1)
        return (1, allequal)
    elif char == "ハ":
        return (1, lambda x: listdigits(x)[0])
    elif char == "テ":
        return (1, lambda x: listdigits(x)[-1])
    elif char == "プ":
        return (1, lambda x: output(x) or x)
    elif char == "リュ":
        return (2, lambda x, y: (lambda a, b: vecd(lambda q, r: q * r, a, b, lambda v: isinstance(v, list)))(*listnumord(x, y, listwrap)))

def run(program, index = -1, stack = None, override = None):
    global _program, _index, _stack, _override
    index %= len(program)
    code = override or program[index]
    if stack is None:
        stack = []
    stack = list(stack)
    for arity, func in code:
        _program = [*program[:index], code, *program[index + 1:]]
        _index = index
        _stack = stack
        _override = override
        while len(stack) < arity:
            stack = [get_input()] + stack
        if arity == 0:
            val = []
        elif arity == -1:
            stack, val = [], stack
        else:
            stack, val = stack[:-arity], stack[-arity:]
        res = func(*val)
        if type(res) == tuple:
            stack += list(map(simpl, res))
        else:
            stack.append(simpl(res))
    return stack

def simpl(r):
    if isinstance(r, list):
        return list(map(simpl, r))
    if isinstance(r, seq):
        return fseq(lambda i: simpl(r[i]))
    if isinstance(r, str):
        return r
    try:
        return sympy.simplify(r)
    except:
        return r


import argparse
import subprocess
import os.path
from time import sleep
from datetime import time, datetime

parser = argparse.ArgumentParser(description='Switch bitday wallpapers', prog='bdswitch')
parser.add_argument('dir', help='The directory with wallpapers.')

args = parser.parse_args()

#wallpapers = [
#    ("10-Early-Night.png", time (0)),
#    ("11-Mid-Night.png", time(2)),
#    ("12-Late-Night.png", time(4)),
#    ("01-Early-Morning.png", time(6)),
#    ("02-Mid-Morning.png", time(8)),
#    ("03-Late-Morning.png", time(10)),
#    ("04-Early-Afternoon.png", time(12)),
#    ("05-Mid-Afternoon.png", time(14)),
#    ("06-Late-Afternoon.png", time(16)),
#    ("07-Early-Evening.png", time(18)),
#    ("08-Mid-Evening.png", time(20)),
#    ("09-Late-Evening.png", time (22))
#]

wallpapers = [
    ("01.png", time(0)),
    ("02.png", time(3)),
    ("03.png", time(6)),
    ("04.png", time(9)),
    ("05.png", time(12)),
    ("06.png", time(15)),
    ("07.png", time(18)),
    ("08.png", time(21))
]

while True:
    now = datetime.now().time()
    chosen = -1
    for wp, tm in reversed(wallpapers):
        if now > tm:
            chosen = wp
            break
    print("selecting wallpaper {}".format(chosen))
    subprocess.run(["feh", "--bg-scale", os.path.join(args.dir, chosen)])
    sleep(15 * 60) # sleep for 15 minutes


import argparse
import logging
import sys
from logging import Formatter

from mlsp.log_handler import LanguageServerLoggingHandler
from mlsp.server import new_with_stdio

def setup_arguments():
    parser = argparse.ArgumentParser()
    parser.add_argument('--debug', action='store_true', default=False, help='Increase verbosity')
    parser.add_argument('--tcp', default=0, help='Specify TCP port to use (default: use stdio)', type=int)
    return parser

def main():
    parser = setup_arguments()
    namespace = parser.parse_args()

    # Not supporting options for now
    logger = logging.getLogger()
    sh = logging.StreamHandler(sys.stderr)
    sh.setLevel(0)
    logger.addHandler(sh)
    if namespace.debug:
        logger.setLevel(logging.DEBUG)
    else:
        logger.setLevel(logging.WARNING)
    server = new_with_stdio(namespace)
    lsp_handler = LanguageServerLoggingHandler(server.endpoint)
    lsp_handler.setFormatter(Formatter(fmt="[%(module)s - %(asctime)-8s] %(message)s", datefmt="%H:%M:%S"))
    logger.addHandler(lsp_handler)

    try:
        server.start()
    except Exception as ex:
        logger.exception("Server exception")


# -*- coding: utf-8 -*-
import argparse
import logging
import sys

from exodus_bundler import root_logger
from exodus_bundler.bundling import create_bundle
from exodus_bundler.errors import FatalError
from exodus_bundler.input_parsing import extract_paths

logger = logging.getLogger(__name__)

def parse_args(args=None, namespace=None):
    """Constructs an argument parser and parses the arguments. The default behavior is
    to parse the arguments from `sys.argv`. A dictionary is returned rather than the
    typical namespace produced by `argparse`."""
    formatter = argparse.ArgumentDefaultsHelpFormatter
    parser = argparse.ArgumentParser(formatter_class=formatter, description=(
        'Bundle ELF binary executables with all of their runtime dependencies '
        'so that they can be relocated to other systems with incompatible system '
        'libraries.'
    ))

    parser.add_argument('executables', metavar='EXECUTABLE', nargs='+', help=(
        'One or more ELF executables to include in the exodus bundle.'
    ))

    parser.add_argument('-c', '--chroot', metavar='CHROOT_PATH',
        default=None,
        help=(
            'A directory that will be treated as the root during linking. Useful for testing and '
            'bundling extracted packages that won\t run without a chroot.'
        ),
    )

    parser.add_argument('-a', '--add', '--additional-file', metavar='DEPENDENCY', action='append',
        default=[],
        help=(
            'Specifies an additional file to include in the bundle, useful for adding '
            'programatically loaded libraries and other non-library dependencies. '
            'The argument can be used more than once to include multiple files, and '
            'directories will be included recursively.'
        ),
    )

    parser.add_argument('-d', '--detect', action='store_true', help=(
        'Attempt to autodetect direct dependencies using the system package manager. '
        'Operating system support is limited.'
    ))

    parser.add_argument('--no-symlink', metavar='FILE', action='append',
        default=[],
        help=(
            'Signifies that a file must not be symlinked to the deduplicated data directory. This '
            'is useful if a file looks for other resources based on paths relative its own '
            'location. This is enabled by default for executables.'
        ),
    )

    parser.add_argument('-o', '--output', metavar='OUTPUT_FILE',
        default=None,
        help=(
            'The file where the bundle will be written out to. The extension depends on the '
            'output type. The "{{executables}}" and "{{extension}}" template strings can be '
            ' used in the provided filename. If omitted, the output will go to stdout when '
            'it is being piped, or to "./exodus-{{executables}}-bundle.{{extension}}" otherwise.'
        ),
    )

    parser.add_argument('-q', '--quiet', action='store_true', help=(
        'Suppress warning messages.'
    ))

    parser.add_argument('-r', '--rename', metavar='NEW_NAME', nargs='?', action='append',
        default=[], help=(
            'Renames the binary executable(s) before packaging. The order of rename tags must '
            'match the order of positional executable arguments.'
        ),
    )

    parser.add_argument('--shell-launchers', action='store_true', help=(
        'Force the use of shell launchers instead of attempting to compile statically linked ones.'
    ))

    parser.add_argument('-t', '--tarball', action='store_true', help=(
        'Creates a tarball for manual extraction instead of an installation script. '
        'Note that this will change the output extension from ".sh" to ".tgz".'
    ))

    parser.add_argument('-v', '--verbose', action='store_true', help=(
        'Output additional informational messages.'
    ))

    return vars(parser.parse_args(args, namespace))

def configure_logging(quiet, verbose, suppress_stdout=False):
    # Set the level.
    log_level = logging.WARN
    if quiet and not verbose:
        log_level = logging.ERROR
    elif verbose and not quiet:
        log_level = logging.INFO
    root_logger.setLevel(log_level)

    class StderrFilter(logging.Filter):
        def filter(self, record):
            return record.levelno in (logging.WARN, logging.ERROR)

    stderr_handler = logging.StreamHandler(sys.stderr)
    stderr_formatter = logging.Formatter('%(levelname)s: %(message)s')
    stderr_handler.setFormatter(stderr_formatter)
    stderr_handler.addFilter(StderrFilter())
    root_logger.addHandler(stderr_handler)

    # We won't even configure/add the stdout handler if this is specified.
    if suppress_stdout:
        return

    class StdoutFilter(logging.Filter):
        def filter(self, record):
            return record.levelno in (logging.DEBUG, logging.INFO)

    stdout_formatter = logging.Formatter('%(message)s')
    stdout_handler = logging.StreamHandler(sys.stdout)
    stdout_handler.setFormatter(stdout_formatter)
    stdout_handler.addFilter(StdoutFilter())
    root_logger.addHandler(stdout_handler)

def main(args=None, namespace=None):
    args = parse_args(args, namespace)

    # Dynamically set the default output to stdout if it is being piped.
    if args['output'] is None:
        if sys.stdout.isatty():
            args['output'] = './exodus-{{executables}}-bundle.{{extension}}'
        else:
            args['output'] = '-'

    # Handle the CLI specific options here, removing them from `args` in the process.
    quiet, verbose = args.pop('quiet'), args.pop('verbose')
    suppress_stdout = args['output'] == '-'
    configure_logging(quiet=quiet, verbose=verbose, suppress_stdout=suppress_stdout)

    # Allow piping in additional files.
    if not sys.stdin.isatty():
        args['add'] += extract_paths(sys.stdin.read())

    # Create the bundle with all of the arguments.
    try:
        create_bundle(**args)
    except FatalError as fatal_error:
        logger.error('Fatal error encountered, exiting.')
        logger.error(fatal_error, exc_info=verbose)
        sys.exit(1)


from tkinter import *
from data import Data

BACKGROUND_COLOR = "#B1DDC6"
ANSWER_COLOR = "white"
CARD_COLOR = "#8EC3B0"
SHADOW_1 = "#332E33"
SHADOW_2 = "#332E33"
SHADOW_3 = "#665C66"
SHADOW_4 = "#807380"
SHADOW_5 = "#998A99"
TIME = 3
FONT_NAME = "Ariel"
LANGUAGE = "English"
TRANSLATE = "Lietuvių"

after_holder = ""

def count_down(count):
	if count > 0:
		global after_holder
		label_time.config(text=count, bg=CARD_COLOR)
		after_holder = window.after(1000, count_down, count - 1)
	else:
		show_answer()

def show_word():
	dictionary.flag = False
	canvas.itemconfig(card, fill=CARD_COLOR)
	word = dictionary.get_word()
	label_language.config(text=LANGUAGE, bg=CARD_COLOR, fg=ANSWER_COLOR)
	label_warning.config(bg=CARD_COLOR, fg=ANSWER_COLOR, text=f"Correct answers: "
															  f"{dictionary.correct} / {dictionary.tries}. "
															  f"{len(dictionary.data)} words left")
	if word != "|EXIT|":
		label_word.config(text=word, bg=CARD_COLOR, fg=ANSWER_COLOR)
		count_down(TIME)
	else:
		label_word.config(text="")
		label_warning.config(text="No more new words in dictionary")

def show_answer():
	dictionary.flag = True
	canvas.itemconfig(card, fill=ANSWER_COLOR)
	label_time.config(text="", bg=ANSWER_COLOR)
	label_language.config(text=TRANSLATE, bg=ANSWER_COLOR, fg=CARD_COLOR)
	label_word.config(text=dictionary.translate, bg=ANSWER_COLOR, fg=CARD_COLOR)
	label_warning.config(bg=ANSWER_COLOR, fg=CARD_COLOR, text=f"Correct answers: "
															  f"{dictionary.correct} / {dictionary.tries}. "
															  f"{len(dictionary.data)} words left")

def press_right():
	if dictionary.flag:
		dictionary.correct_word()
		show_word()
	else:
		label_warning.config(text="Wait until translation is shown")

def press_wrong():
	if dictionary.flag:
		show_word()
	else:
		label_warning.config(text="Wait until translation is shown")

def press_new():
	global after_holder
	dictionary.new_list()
	window.after_cancel(after_holder)
	show_word()

def round_rectangle(x1, y1, x2, y2, radius=25, **kwargs):
	points = [x1 + radius, y1,
			  x1 + radius, y1,
			  x2 - radius, y1,
			  x2 - radius, y1,
			  x2, y1,
			  x2, y1 + radius,
			  x2, y1 + radius,
			  x2, y2 - radius,
			  x2, y2 - radius,
			  x2, y2,
			  x2 - radius, y2,
			  x2 - radius, y2,
			  x1 + radius, y2,
			  x1 + radius, y2,
			  x1, y2,
			  x1, y2 - radius,
			  x1, y2 - radius,
			  x1, y1 + radius,
			  x1, y1 + radius,
			  x1, y1]

	return canvas.create_polygon(points, **kwargs, smooth=True)

dictionary = Data()
window = Tk()
window.title("Flash cards")
window.config(padx=50, pady=50, bg=BACKGROUND_COLOR)

canvas = Canvas(width=710, height=700, bg=BACKGROUND_COLOR, highlightthickness=0)
canvas.pack()

card_shadow = round_rectangle(10, 10, 710, 510, radius=100, fill=SHADOW_4)
card = round_rectangle(0, 0, 700, 500, radius=100, fill=CARD_COLOR)

image_right = PhotoImage(file="images/right.png")
button_right = Button(image=image_right, highlightthickness=0, bg=CARD_COLOR, command=press_right)
button_right.place(x=500, y=520)

image_wrong = PhotoImage(file="images/wrong.png")
button_wrong = Button(image=image_wrong, highlightthickness=0, bg=CARD_COLOR, command=press_wrong)
button_wrong.place(x=100, y=520)

button_new_list = Button(text="start new card pack", highlightthickness=0, bg=CARD_COLOR, fg="yellow", command=press_new)
button_new_list.place(x=350, y=560, anchor="center")

label_time = Label(text="", font=(FONT_NAME, 40, "italic"), fg="white", bg=CARD_COLOR)
label_time.place(x=350, y=40, anchor="center")

label_language = Label(text="language", font=(FONT_NAME, 40, "italic"), fg="white", bg=CARD_COLOR)
label_language.place(x=350, y=100, anchor="center")

label_word = Label(text="", font=(FONT_NAME, 80, "italic"), fg="white", bg=CARD_COLOR)
label_word.place(x=350, y=250, anchor="center")

label_warning = Label(text="", font=(FONT_NAME, 20, "italic"), bg=CARD_COLOR)
label_warning.place(x=350, y=480, anchor="center")

show_word()
window.mainloop()


from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.service import Service
import time
import unittest

# NOTE: In order to access the select period page, the user must be logged in.

class BaseTestCase(unittest.TestCase):
    def setUp(self):
        service = Service(r'PATH_TO_GOOGLE_CHROME_DRIVER')    # Add the path to your local installation of Google Chrome Driver
        self.driver = webdriver.Chrome(service=service)
        self.driver.maximize_window()

    def tearDown(self):
        self.driver.quit()

class TestSelectPeriodPage(BaseTestCase):

    def test_select_prehistory(self):
        self.driver.get('http://127.0.0.1:5000/select_period')

        # Click on the prehistory selector button
        prehistory_button = self.driver.find_element(By.ID, "buttonPre")
        prehistory_button.click()
        time.sleep(3)

        # Assert that you are redirected to the correct page
        self.assertEqual(self.driver.current_url, "http://127.0.0.1:5000/guessing_game/prehistory")

    def test_select_ancient_history(self):
        self.driver.get('http://127.0.0.1:5000/select_period')

        # Click on the ancient history selector button
        ancient_history_button = self.driver.find_element(By.ID, "buttonAncient")
        ancient_history_button.click()
        time.sleep(3)

        # Assert that you are redirected to the correct page
        self.assertEqual(self.driver.current_url, "http://127.0.0.1:5000/guessing_game/ancient%20history")

    def test_select_post_classical_history(self):
        self.driver.get('http://127.0.0.1:5000/select_period')

        # Click on the post classical history selector button
        post_classical_history_button = self.driver.find_element(By.ID, "buttonPCH")
        post_classical_history_button.click()
        time.sleep(3)

        # Assert that you are redirected to the correct page
        self.assertEqual(self.driver.current_url, "http://127.0.0.1:5000/guessing_game/post-classical%20history")

    def test_select_modern_history(self):
        self.driver.get('http://127.0.0.1:5000/select_period')

        # Click on the modern history selector button
        modern_history_button = self.driver.find_element(By.ID, "buttonModern")
        modern_history_button.click()
        time.sleep(3)

        # Assert that you are redirected to the correct page
        self.assertEqual(self.driver.current_url, "http://127.0.0.1:5000/guessing_game/modern%20history")

if __name__ == '__main__':
    unittest.main()


"""
Count the number of prime numbers less than a
non-negative number, n.
"""

def countPrimes(n):
    if n < 2:
        return 0
    counter = 0
    nums = [True] * n
    nums[0] = False
    nums[1] = False
    for i in range(2, n):
        if nums[i] == True:
            counter += 1
            j = 2
            while i * j < n:
                nums[i * j] = False
                j += 1
    return counter

print(countPrimes(1))
print(countPrimes(3))
print(countPrimes(10))
print("The values above should be 0, 1, and 4.")


# Function Description
#
# Complete the function countSwaps in the editor below.
#
# countSwaps has the following parameter(s):
#
# int a[n]: an array of integers to sort
# Prints
#
# Print the three lines required, then return. No return value is expected.
#
# Input Format
#
# The first line contains an integer, , the size of the array .
# The second line contains  space-separated integers .
#
# Constraints
#
# Output Format
#
# Sample Input 0
#
# STDIN   Function
# -----   --------
# 3       a[] size n = 3
# 1 2 3   a = [1, 2, 3]
# Sample Output 0
#
# Array is sorted in 0 swaps.
# First Element: 1
# Last Element: 3
# Explanation 0
# The array is already sorted, so  swaps take place.
#
# Sample Input 1
#
# 3
# 3 2 1
# Sample Output 1
#
# Array is sorted in 3 swaps.
# First Element: 1
# Last Element: 3
# Explanation 1
# The array is not sorted, and its initial values are: . The following  swaps take place:
#
# At this point the array is sorted and the three lines of output are printed to stdout.
import math
import os
import random
import re
import sys

def countSwaps(a):
    swaps = 0
    n = len(a)

    for i in range(n):
        for j in range(n - 1):
            if a[j] > a[j + 1]:
                a[j], a[j + 1] = a[j + 1], a[j]
                swaps += 1

    print("Array is sorted in", swaps, "swaps.")
    print("First Element:", a[0])
    print("Last Element:", a[-1])

if __name__ == '__main__':
    n = int(input().strip())
    a = list(map(int, input().rstrip().split()))

    countSwaps(a)


from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.keys import Keys
import time
import numpy as np
import os.path
import pathlib
import pandas as pd
from datetime import date, datetime, timedelta
from pandas import DataFrame
from openpyxl.workbook import Workbook

chrome_options = Options()
#chrome_options.add_argument("--headless")

#chrome_path = which("chromedriver")

driver = webdriver.Chrome(executable_path="/Users/pedrocampelo/Projects/selenium/chromedriver", options = chrome_options)
driver.get("https://exame.abril.com.br/?s=coronav%C3%ADrus")

i=1
j=1

titulos = []
subtitulos = []
datas = []
conteudos = []

while i < 11:

    xpath = "(//span[@class='list-item-title'])[{0}]//a".format(i)

    search_btn = driver.find_element_by_xpath(xpath)
    search_btn.click()

    time.sleep(2)

    titulo = driver.find_element_by_xpath("//h1[@class='article-title']").text
    titulos.append(str(titulo))

    subtitulo = driver.find_element_by_xpath("//h2[@class='article-subtitle']").text
    subtitulos.append(str(subtitulo))

    data = driver.find_element_by_xpath("//div[@class='article-date']//span").text
    datas.append(str(data))

    content = driver.find_elements_by_xpath("//section[@class='article-content']/p")

    texto_full = []

    for k in range(1, len(content)):

        xpath_texto = "//section[@class='article-content']/p[{0}]".format(k)

        texto = driver.find_element_by_xpath(xpath_texto).text

        time.sleep(.5)

        texto_full.append(str(texto))

    conteudos.append(str(texto_full))

    driver.back()

    if i==10 and j==1:

        next_btn = driver.find_element_by_xpath("//div[@class='pagination-releases']//a")
        next_btn.click()
        time.sleep(2)
        i=0
        j=2

        print(titulos)
        print(subtitulos)
        print(datas)
        print(conteudos)

    if i==10 and j==2:

        next_btn = driver.find_element_by_xpath("//div[@class='pagination-releases']//a[2]")
        next_btn.click()
        time.sleep(2)
        i=0
        print(titulos)
        print(subtitulos)
        print(datas)
        print(conteudos)

    i +=1

time.sleep(2)

#driver.close()


from django.urls import include, path
from audit import views

urlpatterns = [
    path('checklistentry/', views.ChecklistEntry.as_view(), name='checklistentry'),
    path('checklistview/', views.ChecklistView.as_view(), name='checklistview'),
    path('checklistupdate/(?P<pk>[\w-]+)', views.ChecklistUpdate.as_view(), name='checklistupdate'),
    path('checklistdelete/(?P<pk>[\w-]+)', views.ChecklistDelete.as_view(), name='checklistdelete'),
    path('auditreport/', views.AuditReportCreate.as_view(), name='auditreport'),
    path('auditreportview/', views.AuditReportView.as_view(), name='auditreportview'),
    path('audititemsview/', views.AuditItemsView.as_view(), name='audititemsview'),
    path('auditchart', views.AuditChart.as_view(), name='auditchart'),
 ]


import json
from os import path

import requests
from flask import request, session

from ...consts import demo_docs_path, pattern
from ...ds_config import DS_CONFIG

class Eg010SendBinaryDocsController:
    @staticmethod
    def get_args():
        """Get required session and request arguments"""
        # More data validation would be a good idea here
        # Strip anything other than characters listed
        signer_email = pattern.sub("", request.form.get("signer_email"))
        signer_name = pattern.sub("", request.form.get("signer_name"))
        cc_email = pattern.sub("", request.form.get("cc_email"))
        cc_name = pattern.sub("", request.form.get("cc_name"))
        envelope_args = {
            "signer_email": signer_email,
            "signer_name": signer_name,
            "cc_email": cc_email,
            "cc_name": cc_name,
            "status": "sent",
        }
        args = {
            "account_id": session["ds_account_id"],
            "base_path": session["ds_base_path"],
            "access_token": session["ds_access_token"],
            "envelope_args": envelope_args
        }
        return args

    @classmethod
    def worker(cls, args):
        """
        This function does the work of creating the envelope by using
        the API directly with multipart mime
        @param {object} args An object with the following args:

        <tt>account_id</tt>: Current account Id

        <tt> base_path</tt>: base path for making API call

        <tt> access_token</tt>: a valid access token

        <tt>demo_docs_path</tt>: relative path for the demo docs

        <tt>envelope_args</tt>: envelopeArgs, an object with elements

        <tt>signer_email</tt>, <tt>signer_name</tt>, <tt>cc_email</tt>, <tt>cc_name</tt>
        """

        # Make the envelope JSON request body
        #ds-snippet-start:eSign10Step3
        envelope_json = cls.make_envelope_json(args["envelope_args"])

        # Gather documents and their headers
        # Read files 2 and 3 from a local directory
        # The reads could raise an exception if the file is not available!
        # Note: the fles are not binary encoded!
        with open(path.join(demo_docs_path, DS_CONFIG["doc_docx"]), "rb") as file:
            doc2_docx_bytes = file.read()
        with open(path.join(demo_docs_path, DS_CONFIG["doc_pdf"]), "rb") as file:
            doc3_pdf_bytes = file.read()

        documents = [
            {"mime": "text/html", "filename": envelope_json["documents"][0]["name"],
             "document_id": envelope_json["documents"][0]["documentId"],
             "bytes": cls.create_document1(args["envelope_args"]).encode("utf-8")},
            {"mime": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
             "filename": envelope_json["documents"][1]["name"],
             "document_id": envelope_json["documents"][1]["documentId"],
             "bytes": doc2_docx_bytes},
            {"mime": "application/pdf", "filename": envelope_json["documents"][2]["name"],
             "document_id": envelope_json["documents"][2]["documentId"],
             "bytes": doc3_pdf_bytes}
        ]

        # Create the multipart body
        CRLF = b"\r\n"
        boundary = b"multipartboundary_multipartboundary"
        hyphens = b"--"

        req_body = b"".join([
            hyphens, boundary,
            CRLF, b"Content-Type: application/json",
            CRLF, b"Content-Disposition: form-data",
            CRLF,
            CRLF, json.dumps(envelope_json, indent=4).encode("utf-8")])

        # Loop to add the documents.
        # See section Multipart Form Requests on page
        # https://developers.docusign.com/esign-rest-api/guides/requests-and-responses
        for d in documents:
            content_disposition = (f"Content-Disposition: file; filename={d['filename']};" +
                                   f"documentid={d['document_id']}").encode("utf-8")
            req_body = b"".join([req_body,
                                 CRLF, hyphens, boundary,
                                 CRLF, f"Content-Type: {d['mime']}".encode("utf-8"),
                                 CRLF, content_disposition,
                                 CRLF,
                                 CRLF, d["bytes"]])

        # Add closing boundary
        req_body = b"".join([req_body, CRLF, hyphens, boundary, hyphens, CRLF])
        #ds-snippet-end:eSign10Step3

        # Call Envelopes::create API method
        # Exceptions will be caught by the calling function
        #ds-snippet-start:eSign10Step2
        headers = {
            "Authorization": "bearer " + args['access_token'],
            "Accept": "application/json",
            "Content-Type": f"multipart/form-data; boundary={boundary.decode('utf-8')}"
        }
        #ds-snippet-end:eSign10Step2

        #ds-snippet-start:eSign10Step4
        results = requests.post(
            url=f"{args['base_path']}/v2.1/accounts/{args['account_id']}/envelopes",
            headers=headers,
            data=req_body
        )
        return {"status_code": results.status_code, "results": results.json()}
        #ds-snippet-end:eSign10Step4

    #ds-snippet-start:eSign10Step3
    @classmethod
    def make_envelope_json(cls, args):
        """
        Create envelope JSON

Document 1: An HTML document.

Document 2: A Word .docx document.

Document 3: A PDF document.

DocuSign will convert all of the documents to the PDF format.

The recipients" field tags are placed using anchor strings.
        @param {Object} args parameters for the envelope:
          <tt>signerEmail</tt>, <tt>signerName</tt>, <tt>cc_email</tt>, <tt>cc_name</tt>
        @returns {Envelope} An envelope definition
        """

        # document 1 (html) has tag **signature_1**
        # document 2 (docx) has tag /sn1/
        # document 3 (pdf) has tag /sn1/
        #
        # The envelope has two recipients.
        # recipient 1 - signer
        # recipient 2 - cc
        # The envelope will be sent first to the signer.
        # After it is signed, a copy is sent to the cc person.

        # create the envelope definition
        env_json = {
            "emailSubject": "Please sign this document set"
        }
        # add the documents
        doc1 = {
            "name": "Order acknowledgement",  # can be different from actual file name
            "fileExtension": "html",  # Source data format. Signed docs are always pdf.
            "documentId": "1"}  # a label used to reference the doc
        doc2 = {
            "name": "Battle Plan", "fileExtension": "docx", "documentId": "2"}
        doc3 = {
            "name": "Lorem Ipsum", "fileExtension": "pdf", "documentId": "3"}
        # The order in the docs array determines the order in the envelope
        env_json["documents"] = [doc1, doc2, doc3]

        # create a signer recipient to sign the document, identified by name and email
        signer1 = {
            "email": args["signer_email"], "name": args["signer_name"],
            "recipientId": "1", "routingOrder": "1"}
        # routingOrder (lower means earlier) determines the order of deliveries
        # to the recipients. Parallel routing order is supported by using the
        # same integer as the order for two or more recipients.

        # create a cc recipient to receive a copy of the documents, identified by name and email
        cc1 = {
            "email": args["cc_email"], "name": args["cc_name"],
            "routingOrder": "2", "recipientId": "2"}

        # Create signHere fields (also known as tabs) on the documents,
        # We"re using anchor (autoPlace) positioning
        #
        # The DocuSign platform searches throughout your envelope"s
        # documents for matching anchor strings. So the
        # signHere2 tab will be used in both document 2 and 3 since they
        # use the same anchor string for their "signer 1" tabs.
        sign_here1 = {
            "anchorString": "**signature_1**", "anchorYOffset": "10", "anchorUnits": "pixels",
            "anchorXOffset": "20"}
        sign_here2 = {
            "anchorString": "/sn1/", "anchorYOffset": "10", "anchorUnits": "pixels",
            "anchorXOffset": "20"}

        # Tabs are set per recipient / signer
        signer1_tabs = {"signHereTabs": [sign_here1, sign_here2]}
        signer1["tabs"] = signer1_tabs

        # Add the recipients to the envelope object
        recipients = {"signers": [signer1], "carbonCopies": [cc1]}
        env_json["recipients"] = recipients

        # Request that the envelope be sent by setting |status| to "sent".
        # To request that the envelope be created as a draft, set to "created"
        env_json["status"] = "sent"

        return env_json

    @classmethod
    def create_document1(cls, args):
        """ Creates document 1 -- an html document"""

        return f"""
        <!DOCTYPE html>

              <meta charset="UTF-8">

World Wide Corp

Order Processing Division

Ordered by {args["signer_name"]}

Email: {args["signer_email"]}

Copy to: {args["cc_name"]}, {args["cc_email"]}

                Candy bonbon pastry jujubes lollipop wafer biscuit biscuit. Topping brownie sesame snaps sweet roll pie.
                Croissant danish biscuit soufflé caramels jujubes jelly. Dragée danish caramels lemon drops dragée.
                Gummi bears cupcake biscuit tiramisu sugar plum pastry. Dragée gummies applicake pudding liquorice.
                Donut jujubes oat cake jelly-o.
                Dessert bear claw chocolate cake gummies lollipop sugar plum ice cream gummies cheesecake.

Agreed: **signature_1**/

      """
    #ds-snippet-end:eSign10Step3


# encoding: utf-8

"""
General Pyparsing classes used to parse pyloggr configuration files
"""

__author__ = 'stef'

import ast
import re
import sys
from itertools import product
from copy import copy

from pyparsing import Keyword, Suppress, Literal, quotedString, Word, delimitedList, Group, pythonStyleComment
from pyparsing import alphanums, alphas, operatorPrecedence, opAssoc, nums
from future.builtins import str as text
from .fix_unicode import to_unicode

# noinspection PyUnusedLocal
def _make_plain_field(s, loc, toks):
    return PlainField(toks[0])

def _compile_condition(toks):
    toks = toks[0]
    if isinstance(toks, Condition):
        cond = toks
    else:
        cond = Condition.factory(toks[1], toks[0], toks[2])
    cond.gen_lambda()
    return cond

thismodule = sys.modules[__name__]
field_names = [
    "severity", "facility", "app_name", "source", "programname", "syslogtag", "message", "uuid",
    "timereported", "timegenerated", "trusted_comm", "trusted_exe", "trusted_cmdline"
]

for field_name in field_names:
    setattr(thismodule, field_name, Keyword(field_name).setParseAction(
        _make_plain_field
    ))

class BuiltString(object):
    """
    Complex built string
    """
    def __init__(self, part_strings):
        self.part_strings = part_strings

    def _str(self):
        return "BString({})".format('+'.join(str(part) for part in self.part_strings))

    def __str__(self):
        return self._str()

    def __repr__(self):
        return self._str()

    def apply(self, ev):
        """
        Return the string value for the given event

        :param ev: event
        """
        strings = map(lambda s: s.apply(ev), self.part_strings)
        # eliminate empty strings
        strings = filter(lambda s: bool(s), strings)
        # some of the calculated part_strings may actually be sets, because of structured data multiple values
        copy_of_strings = map(lambda s: {s} if not isinstance(s, set) else s, strings)
        combinators = product(*copy_of_strings)
        return [''.join(combi) for combi in combinators]

    @classmethod
    def from_tokens(cls, toks):
        return BuiltString(toks)

def _make_built_string(toks):
    return BuiltString(toks[0])

class Constant(object):
    """
    Represents a constant value
    """
    def __init__(self, name):
        self.name = to_unicode(name)

    def _str(self):
        return "C({})".format(self.name)

    def __str__(self):
        return self._str()

    def __repr__(self):
        return self._str()

    # noinspection PyUnusedLocal
    def apply(self, ev):
        """
        Return the value of constant

        :param ev: event
        """
        return self.name

    def gen_ast(self):
        """
        Generate the AST for the constant value
        """
        return ast.Str(self.name)

# noinspection PyUnusedLocal
def _quoted_string_to_constant(s, loc, toks):
    return Constant(ast.literal_eval(toks[0]))

class Field(object):
    """
    Abstract field
    """
    def __init__(self, name):
        self.name = to_unicode(name)

    def _str(self):
        return "F({})".format(self.name)

    def __str__(self):
        return self._str()

    def __repr__(self):
        return self._str()

    def apply(self, ev):
        """
        Return the value of the field for the given event

        :param ev: event
        """
        raise NotImplementedError

    def gen_ast(self):
        """
        Generate the abstract syntax tree corresponding to the field access
        """
        raise NotImplementedError

class CustomField(Field):
    """
    Represents access to a custom event field
    """
    def __init__(self, name):
        Field.__init__(self, name)
        self.name = to_unicode(self.name.name if isinstance(self.name, Constant) else self.name)

    def _str(self):
        return "EField({})".format(self.name)

    def __str__(self):
        return self._str()

    def __repr__(self):
        return self._str()

    def apply(self, ev):
        """
        Return the value of the custom field for the given event

        :param ev: event
        """
        return ev[self.name]

    def gen_ast(self):
        """
        Generate the Abstract syntax tree corresponding to the custom field access
        """
        return ast.Subscript(value=ast.Name(id='ev', ctx=ast.Load()), slice=ast.Index(value=ast.Str(s=self.name)))

class PlainField(Field):
    """
    Represents access to a plain event field
    """
    def _str(self):
        return "PField({})".format(self.name)

    def __str__(self):
        return self._str()

    def __repr__(self):
        return self._str()

    def apply(self, ev):
        """
        Return the field value for the given event

        :param ev: event
        """
        return ev.__getattribute__(self.name)

    def gen_ast(self):
        """
        Generate the Abstract syntax tree corresponding to the field access
        """
        return ast.Call(
            func=ast.Name(id='getattr', ctx=ast.Load()),
            args=[ast.Name(id='ev', ctx=ast.Load()), ast.Str(s=self.name)],
            keywords=[],
            starargs=None,
            kwargs=None
        )

class Condition(object):
    """
    Abstract condition
    """
    def __init__(self):
        self.fun = None

    @classmethod
    def factory(cls, operande, left, right):
        """
        Factory method to make the concrete conditions

        :param operande: 'and' or 'or' or 'not'
        :param left: left part of condition
        :param right: right part of condition (can be None)
        :return: concrete condition
        :rtype: Condition
        """
        if operande == "and":
            return AndCondition(left, right)
        elif operande == "or":
            return OrCondition(left, right)
        elif operande == "not":
            return NotCondition(left)

    def _str(self):
        raise NotImplementedError

    def __str__(self):
        return self._str()

    def __repr__(self):
        return self._str()

    def apply(self, ev):
        """
        Return the condition value for the given event

        :param ev: event
        """
        raise NotImplementedError

    def gen_ast(self):
        """
        Generate the abstract syntax tree corresponding to the condition
        """
        raise NotImplementedError

    def gen_lambda(self):
        """
        Compile the condition and store in self.fun
        """
        tree = ast.Expression(
            ast.Lambda(
                args=ast.arguments(
                    args=[ast.Name(id='ev', ctx=ast.Param())],
                    vararg=None, kwarg=None, defaults=[]
                ),
                body=self.gen_ast()
            )
        )
        compiled = compile(ast.fix_missing_locations(tree), '<string>', 'eval')
        self.fun = eval(compiled, {'re': re})

    def eval(self, ev):
        """
        Evaluate the condition using the compiled self.fun

        :param ev: event
        :return: bool
        """
        return self.fun(ev)

class AlwaysTrueCondition(Condition):
    def __init__(self):
        super(AlwaysTrueCondition, self).__init__()
        self.fun = lambda ev: True

    def apply(self, ev):
        return True

always_true_singleton = AlwaysTrueCondition()

class NotCondition(Condition):
    """
    NOT A condition
    """
    def __init__(self, left):
        super(NotCondition, self).__init__()
        self.operand = "not"
        self.left = left

    def _str(self):
        return "NOT({})".format(self.left)

    def apply(self, ev):
        """
        Test if the condition apply to the event

        :param ev: event
        :return: bool
        """
        return not self.left.apply(ev)

    def gen_ast(self):
        """
        Generate the Abstract syntax tree corresponding to the condition
        """
        return ast.UnaryOp(op=ast.Not(), operand=self.left.gen_ast())

class AndCondition(Condition):
    """
    A AND B condition
    """
    def __init__(self, left, right):
        super(AndCondition, self).__init__()
        self.operand = "and"
        self.left = left
        self.right = right

    def _str(self):
        return "AND({}, {})".format(self.left, self.right)

    def apply(self, ev):
        """
        Test if the condition apply to the event

        :param ev: event
        :return: bool
        """
        return self.left.apply(ev) and self.right.apply(ev)

    def gen_ast(self):
        """
        Generate the Abstract syntax tree corresponding to the condition
        """
        return ast.BoolOp(op=ast.And(), values=[self.left.gen_ast(), self.right.gen_ast()])

class OrCondition(Condition):
    """
    A OR B condition
    """
    def __init__(self, left, right):
        super(OrCondition, self).__init__()
        self.operand = "or"
        self.left = left
        self.right = right

    def _str(self):
        return "OR({}, {})".format(self.left, self.right)

    def apply(self, ev):
        """
        Test if the condition apply to the event

        :param ev: event
        :return: bool
        """
        return self.left.apply(ev) or self.right.apply(ev)

    def gen_ast(self):
        """
        Generate the Abstract syntax tree corresponding to the condition
        """
        return ast.BoolOp(op=ast.Or(), values=[self.left.gen_ast(), self.right.gen_ast()])

class Predicate(Condition):
    """
    Abstract predicate
    """
    def __init__(self):
        super(Predicate, self).__init__()

    @classmethod
    def factory(cls, operation, left, right):
        """
        Factory method the make the concrete objects

        :param operation: type of predicate
        :param left: left part of predicate
        :param right: right part of predicate
        :return: concrete predicate
        :rtype: Predicate
        """
        if operation == '==':
            return Equals(left, right)
        elif operation == '!=':
            return Different(left, right)
        elif operation == 'in':
            return In(left, right)
        elif operation == 'notin':
            return Notin(left, right)
        elif operation == '~':
            return RegexpP(left, right)
        elif operation == '~*':
            return RegexpIP(left, right)

    def _str(self):
        raise NotImplementedError

    def gen_ast(self):
        """
        Generate the Abstract syntax tree corresponding to the predicate
        """
        raise NotImplementedError

    def apply(self, ev):
        """
        Apply the predicate to the given event

        :param ev: event
        :return: bool
        """
        raise NotImplementedError

class Equals(Predicate):
    """
    EQUALS predicate
    """
    def __init__(self, left, right):
        super(Equals, self).__init__()
        self.left = left
        self.right = right

    def _str(self):
        return "EQ({} == {})".format(self.left, self.right)

    def apply(self, ev):
        """
        Apply the predicate to the given event

        :param ev: event
        :return: bool
        """
        return self.left.apply(ev) == self.right.apply(ev)

    def gen_ast(self):
        """
        Generate the Abstract syntax tree corresponding to the predicate
        """
        return ast.Compare(left=self.left.gen_ast(), ops=[ast.Eq()], comparators=[self.right.gen_ast()])

class RegexpP(Predicate):
    """
    CASE SENSITIVE predicate
    """
    def __init__(self, left, right):
        super(RegexpP, self).__init__()
        self.left = left
        self.right = right

    def _str(self):
        return "REGEXP({} ~ {})".format(self.left, self.right)

    def apply(self, ev):
        """
        Apply the predicate to the given event

        :param ev: event
        :return: bool
        """
        return re.search(self.right.apply(ev), self.left.apply(ev))

    def gen_ast(self):
        """
        Generate the Abstract syntax tree corresponding to the predicate
        """
        return ast.Call(
            func=ast.Attribute(
                value=ast.Name(id='re', ctx=ast.Load()),
                attr='search',
                ctx=ast.Load()
            ),
            args=[
                self.right.gen_ast(),
                self.left.gen_ast()
            ],
            keywords=[],
            starargs=None,
            kwargs=None
        )

class RegexpIP(Predicate):
    """
    CASE INSENSITIVE REGEXP predicate
    """
    def __init__(self, left, right):
        super(RegexpIP, self).__init__()
        self.left = left
        self.right = right

    def _str(self):
        return "REGEXP_I({} ~* {})".format(self.left, self.right)

    def apply(self, ev):
        """
        Apply the predicate to the given event

        :param ev: event
        :return: bool
        """
        return re.search(self.right.apply(ev), self.left.apply(ev), flags=re.IGNORECASE)

    def gen_ast(self):
        """
        Generate the Abstract syntax tree corresponding to the predicate
        """
        return ast.Call(
            func=ast.Attribute(
                value=ast.Name(id='re', ctx=ast.Load()),
                attr='search',
                ctx=ast.Load()
            ),
            args=[
                self.right.gen_ast(),
                self.left.gen_ast()
            ],
            keywords=[
                ast.keyword(
                    arg='flags',
                    value=ast.Attribute(
                        value=ast.Name(id='re', ctx=ast.Load()),
                        attr='IGNORECASE',
                        ctx=ast.Load()
                    )
                )
            ],
            starargs=None,
            kwargs=None
        )

class Different(Predicate):
    """
    DIFFERENT predicate
    """
    def __init__(self, left, right):
        super(Different, self).__init__()
        self.left = left
        self.right = right

    def _str(self):
        return "NEQ({} != {})".format(self.left, self.right)

    def apply(self, ev):
        """
        Apply the predicate to the given event

        :param ev: event
        :return: bool
        """
        return self.left.apply(ev) != self.right.apply(ev)

    def gen_ast(self):
        """
        Generate the Abstract syntax tree corresponding to the predicate
        """
        return ast.Compare(left=self.left.gen_ast(), ops=[ast.NotEq()],
                           comparators=[self.right.gen_ast()])

class In(Predicate):
    """
    IN predicate
    """
    def __init__(self, left, right):
        super(In, self).__init__()
        self.left = left
        self.right = right

    def _str(self):
        return "IN({} in {})".format(self.left, self.right)

    def apply(self, ev):
        """
        Apply the predicate to the given event

        :param ev: event
        :return: bool
        """
        left = self.left if isinstance(self.left, text) else self.left.apply(ev)
        if self.right == "tags":
            return left in ev.tags
        elif self.right == "custom_fields":
            return left in ev
        else:
            raise ValueError

    def gen_ast(self):
        """
        Generate the Abstract syntax tree corresponding to the predicate
        """
        left = ast.Str(self.left) if isinstance(self.left, text) else self.left.gen_ast()
        if self.right == "tags":
            return ast.Compare(left=left, ops=[ast.In()], comparators=[
                ast.Attribute(
                    value=ast.Name(id='ev', ctx=ast.Load()),
                    attr='tags',
                    ctx=ast.Load()
                )
            ])
        elif self.right == "custom_fields":
            return ast.Compare(left=left, ops=[ast.In()], comparators=[ast.Name(id='ev', ctx=ast.Load())])
        else:
            raise ValueError

class Notin(Predicate):
    """
    NOT IN predicate
    """
    def __init__(self, left, right):
        super(Notin, self).__init__()
        self.left = left
        self.right = right

    def _str(self):
        return "NOTIN({} notin {})".format(self.left, self.right)

    def apply(self, ev):
        """
        Apply the predicate to the given event

        :param ev: event
        :return: bool
        """
        left = self.left if isinstance(self.left, text) else self.left.apply(ev)
        if self.right == "tags":
            return left not in ev.tags
        elif self.right == "custom_fields":
            return left not in ev
        else:
            raise ValueError

    def gen_ast(self):
        """
        Generate the Abstract syntax tree corresponding to the predicate
        """
        left = ast.Str(self.left) if isinstance(self.left, text) else self.left.gen_ast()
        if self.right == "tags":
            return ast.Compare(left=left, ops=[ast.NotIn()], comparators=[
                ast.Attribute(
                    value=ast.Name(id='ev', ctx=ast.Load()),
                    attr='tags',
                    ctx=ast.Load()
                )
            ])
        elif self.right == "custom_fields":
            return ast.Compare(left=left, ops=[ast.NotIn], comparators=[ast.Name(id='ev', ctx=ast.Load())])
        else:
            raise ValueError

custom_fields   = Keyword("custom_fields")
tags            = Keyword("tags")

if_cond         = Suppress(Keyword("if"))
else_cond       = Suppress(Keyword("else"))

geoip           = Keyword("geoip")
grok            = Keyword("grok")
useragent       = Keyword("useragent")
router          = Keyword("router")

drop            = Keyword("drop")
stop            = Keyword("stop")

and_operand     = Keyword('and')
or_operand      = Keyword('or')
not_operand     = Keyword('not')

equals          = Literal('==')
assign          = Suppress(Literal(':='))
kw_arg_assign   = Suppress(Literal('=') | Literal(':'))
tags_assign     = Literal('+=') | Literal('-=')
different       = Literal('!=')
in_op           = Keyword('in')
notin_op        = Keyword('notin')
regexp_op       = Literal('~')
regexp_i_op     = Literal('~*')

open_par        = Literal('(')
open_acc        = Literal('{')
close_par       = Literal(')')
close_acc       = Literal('}')

open_delim      = Suppress(open_par | open_acc)
close_delim     = Suppress(close_par | close_acc)

integer         = Word(nums).setParseAction(lambda toks: int(toks[0]))

my_qs = quotedString.setParseAction(_quoted_string_to_constant)
label = Word(initChars=alphas, bodyChars=alphanums + "_")

# noinspection PyUnresolvedReferences
plain_field = severity | facility | app_name | source | programname | syslogtag | message | uuid | \
              timereported | timegenerated | trusted_comm | trusted_exe | trusted_cmdline

custom_field_name = my_qs | label
custom_field = (Literal('[') + custom_field_name + Literal(']')).setParseAction(
    lambda s, loc, toks: CustomField(toks[1])
)

filter_name = (geoip | grok | useragent | router)

comment_line = Suppress(pythonStyleComment)

equals_predicate = (
    (plain_field | custom_field | my_qs)
    + equals
    + (plain_field | custom_field | my_qs)
)

different_predicate = (
    (plain_field | custom_field | my_qs)
    + different
    + (plain_field | custom_field | my_qs)
)

in_predicate = (
    (my_qs | label)
    + in_op
    + (tags | custom_fields)
)

notin_predicate = (
    (my_qs | label)
    + notin_op
    + (tags | custom_fields)
)

regexp_predicate = (
    (plain_field | custom_field)
    + regexp_op
    + my_qs
)

regexpi_predicate = (
    (plain_field | custom_field)
    + regexp_i_op
    + my_qs
)

predicate = (equals_predicate | different_predicate | in_predicate | notin_predicate | regexp_predicate | regexpi_predicate).setParseAction(
    lambda s, loc, toks: Predicate.factory(toks[1], toks[0], toks[2])
)

condition = operatorPrecedence(
    predicate,
    [
        (not_operand, 1, opAssoc.RIGHT),
        (and_operand, 2, opAssoc.LEFT),
        (or_operand, 2, opAssoc.LEFT),
    ]
)
condition = condition.setParseAction(_compile_condition)
condition = condition.setResultsName('condition')

built_string = Group(delimitedList(expr=(plain_field | custom_field | my_qs), delim='+')).setParseAction(
    _make_built_string
)


"""Serializer module.

This module is used as a step between the model and the Rest part.
It aim to serialize the objects before sending them to the user,
as well as to recreate the models from the serialized data.

"""
from rest_framework import serializers
from . import models
from django.core.exceptions import ObjectDoesNotExist
from django.http import Http404
import hoshins

class UserSerializer(serializers.ModelSerializer):
    """Serialize all the User model except the password field."""
    class Meta:
        model = models.User
        exclude = ('password',)

class UserMinimalSerializer(serializers.ModelSerializer):
    """Serialize the main user attributes."""
    class Meta:
        model = models.User
        fields = (
                    'id',
                    'username',
                    'first_name',
                    'last_name',
                 )
        extra_kwargs = {
            'username': {'validators': []},
        }

class MemberShipSerializer(serializers.ModelSerializer):
    """Serialize the membership model."""
    member = UserMinimalSerializer(read_only=True)
    type = serializers.CharField()

    class Meta:
        model = models.Membership
        fields = ('type', 'id', 'member')

    def create(self, validated_data):
        """Create the instance form the serializer.

        Args:
            validated_data (dict): The verified data.

        Returns:
            Returns the instance crated.
        """
        data = self.context['view'].request.data
        username = data['member']['username']
        try:
            validated_data['member'] = models.User.objects.get(username=username)
        except models.User.DoesNotExist:
            try:
                full_name = username.split(' ')
                validated_data['member'] = models.User.objects.get(first_name=full_name[0],
                                                                   last_name=' '.join(full_name[1:]))
            except models.User.DoesNotExist:
                raise Http404("User does not exist")

        kwargs = self.context['view'].kwargs
        team = kwargs['team']
        try:
            validated_data['team'] = hoshins.models.Team.objects.get(name=team)
        except models.User.DoesNotExist:
            raise Http404("Team does not exist")

        model_query = models.Membership.objects.filter(member=validated_data['member'],
                                                       team=validated_data['team'])
        if model_query.exists():
            return model_query.first()
        else:
            return self.Meta.model.objects.create(**validated_data)

class UserMembershipSerializer(serializers.ModelSerializer):
    """Serialize an user as well as his membership."""
    member_type = serializers.SerializerMethodField()

    def get_member_type(self, obj):
        """Function bound to the member_type attribute.

        This function is used to get the membership type of the member
        for the team present in the kwargs.

        Args:
            obj: The current instance of the member.

        Returns:
            Returns the type of the membership if it exists,
                NOT_A_MEMBER otherwise.
        """
        try:
            kwargs = self.context['view'].kwargs
            if 'team' in kwargs:
                team = models.Team.objects.get(name=kwargs['team'])
                ms = models.Membership.objects.get(member=obj, team=team)
                return ms.type

        except ObjectDoesNotExist:
            pass

        return models.Membership.NOT_A_MEMBER

    class Meta:
        model = models.User
        fields = (
            'id',
            'username',
            'first_name',
            'last_name',
            'last_login',
            'date_joined',
            'member_type',
         )

    def update(self, instance, validated_data):
        """Update the user instance.

        Update or create the membership relation between the
        user instance and the current team.

        Args:
            instance (User): The user instance.
            validated_data (dict): The updated attributes,

        Returns:
            User: Return the user instance.
        """
        kwargs = self.context['view'].kwargs
        data = self.context['view'].request.data

        if 'team' in kwargs:
            team = models.Team.objects.get(name=kwargs['team'])
            member_type = data.pop('member_type', models.Membership.NORMAL_USER)

            if member_type not in [x[0] for x in models.Membership.TYPES]:
                member_type = models.Membership.NORMAL_USER

            ms, _ = models.Membership.objects.get_or_create(member=instance, team=team)
            ms.type = member_type
            ms.save()

        return super().update(instance, validated_data)


'''
    This file is part of PM4Py (More Info: https://pm4py.fit.fraunhofer.de).

    PM4Py is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    PM4Py is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with PM4Py.  If not, see <https://www.gnu.org/licenses/>.
'''
from typing import Set
from pm4py.objects.process_tree.obj import ProcessTree
from pm4py.objects.process_tree.utils.generic import is_leaf, is_tau_leaf
from pm4py.objects.process_tree.obj import Operator

def __get_activity_set(pt: ProcessTree, a_set=None) -> Set[str]:
    if a_set is None:
        a_set = set()
    if is_leaf(pt):
        a_set.add(pt.label)
    else:
        for c in pt.children:
            __get_activity_set(c, a_set)
    return a_set

def __get_start_activity_set_binary_tree(pt: ProcessTree, sa_set=None) -> Set[str]:
    assert pt.children is None or len(pt.children) <= 2
    if sa_set is None:
        sa_set = set()
    if is_leaf(pt) and not is_tau_leaf(pt):
        sa_set.add(pt.label)
    elif not is_tau_leaf(pt):
        assert len(pt.children) == 2
        tau_in_language_sub_pt_1 = __check_empty_sequence_accepted(pt.children[0])

        if pt.operator == Operator.SEQUENCE:
            if not tau_in_language_sub_pt_1:
                return __get_start_activity_set_binary_tree(pt.children[0], sa_set)
            else:
                for c in pt.children:
                    sa_set.union(__get_start_activity_set_binary_tree(c, sa_set))
        elif pt.operator == Operator.PARALLEL or pt.operator == Operator.XOR:
            for c in pt.children:
                sa_set.union(__get_start_activity_set_binary_tree(c, sa_set))
        elif pt.operator == Operator.LOOP:
            if not tau_in_language_sub_pt_1:
                return __get_start_activity_set_binary_tree(pt.children[0], sa_set)
            else:
                for c in pt.children:
                    sa_set.union(__get_start_activity_set_binary_tree(c, sa_set))
    return sa_set

def __get_end_activity_set_binary_tree(pt: ProcessTree, ea_set=None) -> Set[str]:
    assert pt.children is None or len(pt.children) <= 2
    if ea_set is None:
        ea_set = set()
    if is_leaf(pt) and not is_tau_leaf(pt):
        ea_set.add(pt.label)
    elif not is_tau_leaf(pt):
        assert len(pt.children) == 2
        tau_in_language_sub_pt_1 = __check_empty_sequence_accepted(pt.children[0])
        tau_in_language_sub_pt_2 = __check_empty_sequence_accepted(pt.children[1])

        if pt.operator == Operator.SEQUENCE:
            if not tau_in_language_sub_pt_2:
                return __get_end_activity_set_binary_tree(pt.children[1], ea_set)
            else:
                for c in pt.children:
                    ea_set.union(__get_end_activity_set_binary_tree(c, ea_set))
        elif pt.operator == Operator.PARALLEL or pt.operator == Operator.XOR:
            for c in pt.children:
                ea_set.union(__get_end_activity_set_binary_tree(c, ea_set))
        elif pt.operator == Operator.LOOP:
            if not tau_in_language_sub_pt_1:
                return __get_end_activity_set_binary_tree(pt.children[0], ea_set)
            else:
                for c in pt.children:
                    ea_set.union(__get_end_activity_set_binary_tree(c, ea_set))
    return ea_set

def __check_empty_sequence_accepted(pt: ProcessTree) -> bool:
    if is_leaf(pt):
        if is_tau_leaf(pt):
            return True
        else:
            return False
    else:
        assert len(pt.children) == 2
        if pt.operator == Operator.SEQUENCE or pt.operator == Operator.PARALLEL:
            return __check_empty_sequence_accepted(pt.children[0]) and __check_empty_sequence_accepted(pt.children[1])
        elif pt.operator == Operator.XOR:
            return __check_empty_sequence_accepted(pt.children[0]) or __check_empty_sequence_accepted(pt.children[1])
        else:
            assert pt.operator == Operator.LOOP
            return __check_empty_sequence_accepted(pt.children[0])

def initialize_a_sa_ea_tau_sets(pt: ProcessTree, a_sets=None, sa_sets=None, ea_sets=None, tau_sets=None):
    if a_sets is None:
        a_sets = {}
    if sa_sets is None:
        sa_sets = {}
    if ea_sets is None:
        ea_sets = {}
    if tau_sets is None:
        tau_sets = {}

    a_sets[pt] = __get_activity_set(pt)
    sa_sets[pt] = __get_start_activity_set_binary_tree(pt)
    ea_sets[pt] = __get_end_activity_set_binary_tree(pt)
    tau_sets[pt] = __check_empty_sequence_accepted(pt)

    for c in pt.children:
        a_sets, sa_sets, ea_sets, tau_sets = initialize_a_sa_ea_tau_sets(c, a_sets=a_sets, sa_sets=sa_sets,
                                                                         ea_sets=ea_sets, tau_sets=tau_sets)
    return a_sets, sa_sets, ea_sets, tau_sets


import meteorite_data_class

data = open("MeteoriteDataFile.txt", "r")
data.readline()

massList = []
yearList = []
while True:
    currentLine = data.readline()

    #check if finished reading file
    if currentLine == "":
        #print("finished reading")
        break

    currentLine = currentLine.strip()
    lineList = currentLine.split('\t')

    #create empty array of 12 Nones
    currentList = [None] * 12
    for i in range(len(lineList)-1):
        if lineList[i] != "":
            currentList[i] = lineList[i]

    #easier to just make meteor object before checking mass/year and adding to list after?
    currentMeteor = meteorite_data_class.MeteorDataEntry(currentList[0],
                                                         currentList[1],
                                                         currentList[2],
                                                         currentList[3],
                                                         currentList[4],
                                                         currentList[5],
                                                         currentList[6],
                                                         currentList[7],
                                                         currentList[8],
                                                         currentList[9],
                                                         currentList[10],
                                                         currentList[11])

    #print(currentMeteor.year)
    if currentMeteor.mass != None and float(currentMeteor.mass) > 2900000:
        massList.append(currentMeteor)

    if currentMeteor.year != None and int(currentMeteor.year) >=2013:
        yearList.append(currentMeteor)

nameLabel = "NAME"
massLabel = "MASS (g)"
yearLabel = "YEAR"
print(f'{nameLabel:<24}{massLabel:<24}')
print("="*40)
for i in range(len(massList)):
    currentName=massList[i].name
    currentMass=massList[i].mass
    print(f'{currentName:<24}{currentMass:<24}')
print("="*40)

print(f'{nameLabel:<24}{yearLabel:<24}')

for i in range(len(yearList)):
    currentName=yearList[i].name
    currentYear=yearList[i].year
    print(f'{currentName:<24}{currentYear:<24}')


#Find peak element in an array

def find_peak_element(arr:list[int])->int:

    '''Find peak element in an arrray:'''

    low,high=0,len(arr)-1
    while low<=high:
        mid=(low+high)//2
        if mid>0 and mid<len(arr)-1:
            if arr[mid]>arr[mid-1] and arr[mid]>arr[mid+1]:
                return mid
            else:
                if arr[mid]<arr[mid-1]:
                    high=mid-1
                else:
                    low=mid+1
        elif mid==0:
            if arr[mid]>arr[mid+1]:
                return mid
            else:
                low=mid+1
        elif mid==len(arr)-1:
            if arr[mid]>arr[mid-1]:
                return mid
            else:
                high=mid-1
    return -1

if __name__=="__main__":
    print("=========================")
    print("Find peak element in an array:")
    arr=[5, 10, 20, 15]
    index=find_peak_element(arr)
    print(f"The peak element is {arr[index]}")
    print("==============================")


import collections

#create an empty dequeue
d= collections.deque()

#adding elements to right side of deque
d.append(1)
d.append(2.4)
d.append('python')
print(d)

#adding elements to the left of deque
d.appendleft('hello world')
d.appendleft(123)
print(d)
#deleting element from right side
d.pop()
print(d)

#deleting element from left side
d.popleft()
print(d)


from PIL import Image, ImageDraw, ImageFont
import random

txt = "..."
mtxt = ""
while txt != "":
	txt = input()
	mtxt += txt + "\n"
mtxt = mtxt[:-2]

font = ImageFont.truetype("Macondo-Regular.ttf", 56)
img = Image.new("RGBA", (1920, 1080), (0,0,0,0))
txtmg = Image.new("RGBA", (1920, 1080), (255,255,255,0))
draw = ImageDraw.Draw(txtmg)
cx, cy = draw.textsize(mtxt, font=font)
cx //= 2
cy //= 2
draw.text((960-cx, 540-cy), mtxt, font=font, fill=(47,197,247,255))
cx += 60
cy += 30
out = Image.alpha_composite(img, txtmg)
bgimg = Image.new("RGB", (1920, 1080), (0, 0, 0))
ddraw = ImageDraw.Draw(bgimg)
for i in range(8192):
	x1 = random.randrange(1920)
	x2 = random.randrange(1920)
	y1 = random.randrange(1080)
	y2 = random.randrange(1080)
	cl = random.randrange(64)
	ddraw.line([x1, y1, x2, y2], fill=(cl, cl, cl))

bgimg.paste(out, (0, 0), out)
endout = bgimg.crop((960-cx, 540-cy, 960+cx, 540+cy))
endout.save("textbild.jpg", "JPEG", quality=95)


def pretty_print(arr):
    for i in arr:
        print(i)
def solve(start, goal, lines):
    dx = [-1, 0, 1, 0]
    dy = [0, 1, 0, -1]

    que = []
    que.append(start)
    while que:
        x, y = que.pop(0)
        value = lines[x][y]
        for i in range(4):
            nx = x + dx[i]
            ny = y + dy[i]
            if nx < 0 or ny < 0 or nx >= n or ny >= m:
                continue

            tmp_value = lines[nx][ny]

            if tmp_value < 1:
                continue

            if tmp_value == 1 or value + 1 < tmp_value:
                lines[nx][ny] = value + 1
                que.append((nx, ny))
    return lines

if __name__ == "__main__":
    n, m = map(int, input().strip().split())
    lines = []
    for i in range(n):
        line = list(map(int, list(input().strip())))
        lines.append(line)
    print(lines)
    start = (0, 0)
    goal = (n-1, m-1)
    print(solve(start, goal, lines))


# Zed-Thon
# Copyright (C) 2023 Zed-Thon . All Rights Reserved
#
# This file is a part of < https://github.com/Zed-Thon/ZelZal/ >
# PLease read the GNU Affero General Public License in
# <https://www.github.com/Zed-Thon/ZelZal/blob/master/LICENSE/>.

import base64
import contextlib
import io
import os

from telethon import types
from telethon.errors.rpcerrorlist import YouBlockedUserError
from telethon.tl.functions.contacts import UnblockRequest as unblock
from validators.url import url

from ..core.logger import logging
from ..helpers.functions import delete_conv
from ..core.managers import edit_delete, edit_or_reply
from ..helpers.utils import reply_id
from . import zedub

LOGS = logging.getLogger(__name__)

# =========================================================== #
#                           الملـــف كتـــابـــة مـــن الصفـــر - T.me/ZedThon                           #
# =========================================================== #
Warn = "تخمـط بـدون ذكـر المصـدر - ابلعــك نعــال وراح اهينــك"
REPO_SEARCH_STRING = "╮ جـارِ التحميـل مـن كيثـاب ...♥╰"
REPO_NOT_FOUND = "⎉╎عـذراً .. لـم استطـع ايجـاد المطلـوب"
# =========================================================== #
#                                      زلـــزال الهيبـــه - T.me/zzzzl1l                                  #
# =========================================================== #

#Write Code By T.me/zzzzl1l
@zedub.zed_cmd(pattern="repo(?:\s|$)([\s\S]*)")
async def zelzal2(event):
    zelzal = event.pattern_match.group(1)
    chat = "@GitHub_Download_robot"
    reply_id_ = await reply_id(event)
    zedthon = await edit_or_reply(event, REPO_SEARCH_STRING, parse_mode="html")
    async with event.client.conversation(chat) as conv:
        try:
            await conv.send_message("/start")
            await conv.get_response()
            purgeflag = await conv.send_message(zelzal)
        except YouBlockedUserError:
            await zedub(unblock("GitHub_Download_robot"))
            await conv.send_message("/start")
            await conv.get_response()
            purgeflag = await conv.send_message(zelzal)
        repo = await conv.get_response()
        await event.client.send_read_acknowledge(conv.chat_id)
        if not repo.document:
            return await edit_delete(zedthon, REPO_NOT_FOUND, parse_mode="html")
        await event.client.send_read_acknowledge(conv.chat_id)
        await event.client.send_file(
            event.chat_id,
            repo,
            caption=f"⎉╎الريبـو :- {zelzal}\n⎉╎تم التحميـل بواسطـة زدثــون :- @ZedThon",
            parse_mode="html",
            reply_to=reply_id_,
        )
        await zedthon.delete()
        await delete_conv(event, chat, purgeflag)


from typing import List
from collections import defaultdict

class Node:
    def __init__(self, chr):
        self.chr = chr
        self.ended = False
        self.children = defaultdict(lambda: None)

class Trie:
    def __init__(self):
        self.root = Node(None)

    @classmethod
    def insert(cls, node, w, i):
        if not node:
            node = Node(w[i])

        if i == len(w) - 1:
            node.ended = True
        else:
            nxt = w[i + 1]
            node.children[nxt] = cls.insert(node.children[nxt], w, i + 1)

        return node

    @classmethod
    def search(cls, node, w, i):
        if not node:
            return

        if node.chr != w[i]:
            return

        if node.ended:
            return w[:i+1]
        elif i + 1 < len(w):
            return cls.search(node.children[w[i + 1]], w, i + 1)
        else:
            return

class Solution:
    def replaceWords(self, dic: List[str], sentence: str) -> str:
        trie = Trie()
        for word in dic:
            root = trie.root
            root.children[word[0]] = Trie.insert(root.children[word[0]], word, 0)

        ret = []
        for word in sentence.split(" "):
            for child in trie.root.children.values():
                searched = Trie.search(child, word, 0)
                if searched:
                    ret.append(searched)
                    break
            else:
                ret.append(word)

        return " ".join(ret)

if __name__ == "__main__":
    assert Solution().replaceWords(["cat", "bat", "rat"], "the cattle was rattled by the battery") == "the cat was rat by the bat"


import heapq
import time as time_mod

class Event:
    '''Base class for schedulable objects.'''

    __slots__ = ['function', 'args', 'kwargs', 'canceled', 'finished']

    def __init__(self, function, args=None, kwargs=None):
        self.function = function
        self.args = args or []
        self.kwargs = kwargs or {}
        self.canceled = False
        self.finished = False

    def cancel(self):
        '''Mark the timer as canceled to avoid a callback.'''
        self.canceled = True

    def __call__(self, deadline):
        if not self.canceled:
            self.function(*self.args, **self.kwargs)
        self.finished = True

class EventWithTime(Event):
    '''Event that passes deadline to event handler.'''
    def __call__(self, deadline):
        if not self.canceled:
            self.function(deadline, *self.args, **self.kwargs)
        self.finished = True

class RecurringEvent(Event):
    __slots__ = ['period']

    def __init__(self, period, function, args=None, kwargs=None):
        super(RecurringEvent, self).__init__(function, args, kwargs)
        self.period = period

    def __call__(self, deadline):
        if not self.canceled:
            self.function(*self.args, **self.kwargs)
            if not self.canceled:
                return deadline + self.period
        self.finished = True

class Queue:
    def __init__(self):
        self._queue = []

    def schedule(self, time, event):
        heapq.heappush(self._queue, (time, event))

    def execute(self, time):
        if not self._queue:
            return
        deadline, callback = event = self._queue[0]
        if deadline > time:
            return
        assert heapq.heappop(self._queue) == event
        time = callback(deadline)
        if time is not None:
            if hasattr(time, 'timetuple'):
                time = time_mod.mktime(time.timetuple())
            heapq.heappush(self._queue, (time, callback))
        return True

    def delay(self, time):
        if not self._queue:
            return
        deadline, _ = self._queue[0]
        return deadline - time if deadline > time else 0

    def __bool__(self):
        return bool(self._queue)


#!/usr/bin/python3

'''
Control the Brightness of LED using PWM on Raspberry Pi
http://www.electronicwings.com
'''

import RPi.GPIO as GPIO
from time import sleep

def sonar():
    scale_up = [261.63, 293.66, 329.63, 349.23, 392.00, 440.00, 493.88, 523.25]
    scale_down = scale_up[::-1]
    pin = 12				# PWM pin connected to LED
    GPIO.setwarnings(False)			#disable warnings
    GPIO.setmode(GPIO.BOARD)		#set pin numbering system
    GPIO.setup(pin,GPIO.OUT)
    pi_pwm = GPIO.PWM(pin,1000)		#create PWM instance with frequency
    pi_pwm.start(50)				#start PWM of required Duty Cycle
    for i in range(len(scale_up)):
        pi_pwm.ChangeFrequency(scale_up[i])
        sleep(.20)
    for i in range(len(scale_down)):
        pi_pwm.ChangeFrequency(scale_down[i])
        sleep(.20)
    pi_pwm.stop()


import os
import sys

cr2Folder = sys.argv[1]

def hasJpgExtension(filename):
    extension = os.path.splitext(filename)[1].lower()
    return extension == '.jpg' or extension == '.jpeg'

jpgFolder = os.path.join(cr2Folder, 'JPEG')
jpgFiles = [os.path.splitext(os.path.basename(filename))[0] for filename in os.listdir(jpgFolder) if os.path.isfile(os.path.join(jpgFolder, filename)) and hasJpgExtension(filename)]
print('Jpg files: ' + ', '.join(jpgFiles))

for _, _, filenames in os.walk(cr2Folder):
    for filename in filenames:
        basenameWithoutExt = os.path.splitext(os.path.basename(filename))[0]
        if not basenameWithoutExt in jpgFiles:
            filePath = os.path.join(cr2Folder, filename)
            print('Removing ' + filePath)
            os.remove(filePath)
    break


from flask_app.config.mysqlconnection import connectToMySQL
from flask import flash

class Saleyear:
    db_name = 'salesrevenue'

    def __init__(self,db_data):
        self.id = db_data['id']
        self.first_name = db_data['first_name']
        self.last_name = db_data['last_name']
        self.sales = db_data['sales']

    @classmethod
    def sum_each(cls):
        query = "SELECT users.id as id, users.first_name, users.last_name, sum(sales.sale) as sales FROM users LEFT JOIN sales ON users.id=sales.user_id GROUP BY users.id;"
        results =  connectToMySQL(cls.db_name).query_db(query)
        all_sales = []
        for row in results:
            all_sales.append( cls(row) )
        return all_sales

    @classmethod
    def sum_each_labels(cls):
        query = "SELECT users.id as id, users.first_name, users.last_name, sum(sales.sale) as sales FROM users LEFT JOIN sales ON users.id=sales.user_id GROUP BY users.id;"
        results =  connectToMySQL(cls.db_name).query_db(query)

                                                # lista de objectos de la clase Saleyear
        labels = []
        for row in results:
            labels.append(row["first_name"])

        return labels

    @classmethod
    def sum_each_values(cls):
        query = "SELECT users.id as id, users.first_name, users.last_name, sum(sales.sale) as sales FROM users LEFT JOIN sales ON users.id=sales.user_id GROUP BY users.id;"
        results =  connectToMySQL(cls.db_name).query_db(query)

                                                # lista de objectos de la clase Saley

        values = []
        for row in results:
            values.append(int(row["sales"]))
        return values


# Agenda: Let's close PyGame with QUIT event

import pygame

# Intialize the pygame
pygame.init()

# create the screen
screen = pygame.display.set_mode((800, 600))

# Game Loop
running = True
while running:

    # https://www.pygame.org/docs/ref/event.html?highlight=pygame%20event#module-pygame.event
    # https://www.pygame.org/docs/ref/event.html?highlight=pygame%20event%20get#pygame.event.get

    # Capture and check events one by one
    for event in pygame.event.get(): #   <<<<<<<<<< ====================
        # https://www.pygame.org/docs/ref/pygame.html?highlight=quit#pygame.quit
        if event.type == pygame.QUIT:
            running = False