from contextlib import contextmanager
from typing import ContextManager

from zkay.zkay_ast.analysis.partition_state import PartitionState
from zkay.zkay_ast.analysis.side_effects import has_side_effects
from zkay.zkay_ast.ast import VariableDeclarationStatement, IfStatement, \
    Block, ExpressionStatement, MeExpr, AssignmentStatement, RequireStatement, AllExpr, ReturnStatement, \
    FunctionCallExpr, BuiltinFunction, ConstructorOrFunctionDefinition, StatementList, WhileStatement, ForStatement, \
    ContinueStatement, BreakStatement, DoWhileStatement, LocationExpr, TupleExpr, PrivacyLabelExpr
from zkay.zkay_ast.visitor.visitor import AstVisitor

def alias_analysis(ast):
    v = AliasAnalysisVisitor()
    v.visit(ast)

class AliasAnalysisVisitor(AstVisitor):

    def __init__(self, log=False):
        super().__init__('node-or-children', log)
        self.cond_analyzer = GuardConditionAnalyzer()

    def visitConstructorOrFunctionDefinition(self, ast: ConstructorOrFunctionDefinition):
        s: PartitionState[PrivacyLabelExpr] = PartitionState()
        s.insert(MeExpr().privacy_annotation_label())
        s.insert(AllExpr().privacy_annotation_label())
        for d in ast.parent.state_variable_declarations:
            s.insert(d.idf)
        for p in ast.parameters:
            s.insert(p.idf)
        ast.body.before_analysis = s
        return self.visit(ast.body)

    def propagate(self, statements, before_analysis: PartitionState[PrivacyLabelExpr]) -> PartitionState[PrivacyLabelExpr]:
        last = before_analysis.copy()
        # push state through each statement
        for statement in statements:
            statement.before_analysis = last
            # print('before', statement, last)
            self.visit(statement)
            last = statement.after_analysis
        # print('after', statement, last)
        return last.copy()

    def visitStatementList(self, ast: StatementList):
        ast.after_analysis = self.propagate(ast.statements, ast.before_analysis)

    def visitBlock(self, ast: Block):
        last = ast.before_analysis.copy()

        # add fresh names from this block
        for name in ast.names.values():
            last.insert(name)

        ast.after_analysis = self.propagate(ast.statements, last)

        # remove names falling out of scope
        for name in ast.names.values():
            ast.after_analysis.remove(name)

    def visitIfStatement(self, ast: IfStatement):
        # condition
        before_then = self.cond_analyzer.analyze(ast.condition, ast.before_analysis)

        # then
        ast.then_branch.before_analysis = before_then
        self.visit(ast.then_branch)
        after_then = ast.then_branch.after_analysis

        # else
        if ast.else_branch:
            before_else = self.cond_analyzer.analyze(ast.condition.unop('!'), ast.before_analysis)
            ast.else_branch.before_analysis = before_else
            self.visit(ast.else_branch)
            after_else = ast.else_branch.after_analysis
        else:
            after_else = ast.before_analysis

        # join branches
        ast.after_analysis = after_then.join(after_else)

    def visitWhileStatement(self, ast: WhileStatement):
        # Body always executes after the condition, but it is also possible that it is not executed at all
        # Condition is true before the body
        # After the loop, the condition is false

        if has_side_effects(ast.condition) or has_side_effects(ast.body):
            ast.before_analysis = ast.before_analysis.separate_all()

        before_body = self.cond_analyzer.analyze(ast.condition, ast.before_analysis)
        ast.body.before_analysis = before_body
        self.visit(ast.body)

        # Either no loop iteration or at least one loop iteration
        skip_loop = self.cond_analyzer.analyze(ast.condition.unop('!'), ast.before_analysis)
        did_loop = self.cond_analyzer.analyze(ast.condition.unop('!'), ast.body.after_analysis)

        # join
        ast.after_analysis = skip_loop.join(did_loop)

    def visitDoWhileStatement(self, ast: DoWhileStatement):
        # Body either executes with or without condition, but it is also possible that it is not executed at all
        # No information about condition before the body
        # After the loop, the condition is false

        # Could be subsequent loop iteration after condition with side effect
        cond_se = has_side_effects(ast.condition)
        if cond_se or has_side_effects(ast.body):
            ast.before_analysis = ast.before_analysis.separate_all()

        ast.body.before_analysis = ast.before_analysis.copy()
        self.visit(ast.body)

        # ast.before_analysis is only used by expressions inside condition -> body has already happened at that point
        ast.before_analysis = ast.body.after_analysis.copy()
        ast.after_analysis = self.cond_analyzer.analyze(ast.condition.unop('!'), ast.before_analysis)

    def visitForStatement(self, ast: ForStatement):
        last = ast.before_analysis.copy()

        # add names introduced in init
        for name in ast.names.values():
            last.insert(name)

        if ast.init is not None:
            ast.init.before_analysis = last.copy()
            self.visit(ast.init)
            ast.before_analysis = ast.init.after_analysis.copy() # init should be taken into account when looking up things in the condition

        if has_side_effects(ast.condition) or has_side_effects(ast.body) or (ast.update is not None and has_side_effects(ast.update)):
            ast.before_analysis = last.separate_all()

        ast.body.before_analysis = self.cond_analyzer.analyze(ast.condition, ast.before_analysis)
        self.visit(ast.body)
        if ast.update is not None:
            # Update is always executed after the body (if it is executed)
            ast.update.before_analysis = ast.body.after_analysis.copy()
            self.visit(ast.update)

        skip_loop = self.cond_analyzer.analyze(ast.condition.unop('!'), ast.init.after_analysis)
        did_loop = self.cond_analyzer.analyze(ast.condition.unop('!'), ast.update.after_analysis if ast.update else ast.body.after_analysis)

        # join
        ast.after_analysis = skip_loop.join(did_loop)

        # drop names introduced in init
        for name in ast.names.values():
            ast.after_analysis.remove(name)

    def visitVariableDeclarationStatement(self, ast: VariableDeclarationStatement):
        e = ast.expr
        if e and has_side_effects(e):
            ast.before_analysis = ast.before_analysis.separate_all()

        # visit expression
        if e:
            self.visit(e)

        # state after declaration
        after = ast.before_analysis.copy()

        # name of variable is already in list
        name = ast.variable_declaration.idf
        assert (after.has(name))

        # make state more precise
        if e and e.privacy_annotation_label():
            after.merge(name, e.privacy_annotation_label())

        ast.after_analysis = after

    def visitRequireStatement(self, ast: RequireStatement):
        if has_side_effects(ast.condition):
            ast.before_analysis = ast.before_analysis.separate_all()

        self.visit(ast.condition)

        # state after require
        after = ast.before_analysis.copy()

        # make state more precise
        c = ast.condition
        if isinstance(c, FunctionCallExpr) and isinstance(c.func, BuiltinFunction) and c.func.op == '==':
            lhs = c.args[0].privacy_annotation_label()
            rhs = c.args[1].privacy_annotation_label()
            if lhs and rhs:
                after.merge(lhs, rhs)

        ast.after_analysis = after

    def visitAssignmentStatement(self, ast: AssignmentStatement):
        lhs = ast.lhs
        rhs = ast.rhs
        if has_side_effects(lhs) or has_side_effects(rhs):
            ast.before_analysis = ast.before_analysis.separate_all()

        # visit expression
        self.visit(ast.lhs)
        self.visit(ast.rhs)

        # state after assignment
        after = ast.before_analysis.copy()
        recursive_assign(lhs, rhs, after)

        # save state
        ast.after_analysis = after

    def visitExpressionStatement(self, ast: ExpressionStatement):
        if has_side_effects(ast.expr):
            ast.before_analysis = ast.before_analysis.separate_all()

        # visit expression
        self.visit(ast.expr)

        # if expression has effect, we are already at TOP
        ast.after_analysis = ast.before_analysis.copy()

    def visitReturnStatement(self, ast: ReturnStatement):
        ast.after_analysis = ast.before_analysis

    def visitContinueStatement(self, ast: ContinueStatement):
        ast.after_analysis = ast.before_analysis

    def visitBreakStatement(self, ast: BreakStatement):
        ast.after_analysis = ast.before_analysis

    def visitStatement(self, _):
        raise NotImplementedError()

class GuardConditionAnalyzer(AstVisitor):
    def __init__(self, log=False):
        super().__init__('node-or-children', log)
        self._neg = False
        self._analysis = None

    def analyze(self, cond, before_analysis: PartitionState) -> PartitionState:
        if has_side_effects(cond):
            return before_analysis.copy().separate_all()
        else:
            self._neg = False
            self._analysis = before_analysis.copy()
            self.visit(cond)
            return self._analysis

    @contextmanager
    def _negated(self) -> ContextManager:
        self._neg = not self._neg
        yield
        self._neg = not self._neg

    def visitFunctionCallExpr(self, ast: FunctionCallExpr):
        if isinstance(ast.func, BuiltinFunction):
            op = ast.func.op
            if op == '!':
                with self._negated():
                    self.visit(ast.args[0])
            elif (op == '&&' and not self._neg) or (op == '||' and self._neg):
                self.visit(ast.args[0])
                self.visit(ast.args[1])
            elif op == 'parenthesis':
                self.visit(ast.args[0])
            elif (op == '==' and not self._neg) or (op == '!=' and self._neg):
                recursive_merge(ast.args[0], ast.args[1], self._analysis)

def _recursive_update(lhs, rhs, analysis: PartitionState, merge: bool):
    if isinstance(lhs, TupleExpr) and isinstance(rhs, TupleExpr):
        for l, r in zip(lhs.elements, rhs.elements):
            _recursive_update(l, r, analysis, merge)
    else:
        lhs = lhs.privacy_annotation_label()
        rhs = rhs.privacy_annotation_label()
        if lhs and rhs and analysis.has(rhs):
            if merge:
                analysis.merge(lhs, rhs)
            else:
                analysis.move_to(lhs, rhs)
        elif lhs:
            analysis.move_to_separate(lhs)

def recursive_merge(lhs, rhs, analysis: PartitionState):
    _recursive_update(lhs, rhs, analysis, True)

def recursive_assign(lhs, rhs, analysis: PartitionState):
    _recursive_update(lhs, rhs, analysis, False)


import matplotlib.pyplot as plt

class Plotter:
    def plot(self, xy_df, sort_column=None, x_label=None, y_label=None):
        if sort_column is not None:
            xy_df = xy_df.sort_values([sort_column])

        plt.plot(xy_df.iloc[:, 0], xy_df.iloc[:, 1].to_list())

        if x_label is not None:
            plt.xlabel(x_label)

        if y_label is not None:
            plt.ylabel(y_label)

        plt.show()

    def show_histogram(self, df):
        df.hist()
        plt.show()

    def show_box_plot(self, df):
        plt.figure(figsize=(8, 4), dpi=288)
        df.plot(kind='box', subplots=True)
        plt.show()


from ..Commons import *
from ..Language.DataStructure import *
from ..Language.Syntax import *

DEFI_COMPOSITE=OPER(nom="DEFI_COMPOSITE",op=56,sd_prod=mater_sdaster,reentrant='n',
                    fr=tr("Déterminer les caractéristiques matériaux homogénéisées d'une coque multicouche à partir"
                        " des caractéristiques de chaque couche"),
         COUCHE          =FACT(statut='o',max='**',
           EPAIS           =SIMP(statut='o',typ='R',val_min=0.E+0 ),
           MATER           =SIMP(statut='o',typ=(mater_sdaster) ),
           ORIENTATION     =SIMP(statut='f',typ='R',defaut= 0.E+0,
                                 val_min=-90.E+0,val_max=90.E+0   ),
         ),
         IMPRESSION      =FACT(statut='f',
           UNITE           =SIMP(statut='f',typ=UnitType(),defaut=8, inout='out'),
         ),
)  ;


import discord
from discord_components import *
from discord.ext import commands
from random import choice
from asyncio import TimeoutError

ch1 = ["Rock", "Scissors", "Paper"]

class rps(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @commands.command()
    async def rps(self, ctx):

        comp = choice(ch1)

        yet = discord.Embed(title=f"{ctx.author.display_name}'s Rock Paper Scissors Game!", description=">Status: You haven't click on any button yet!", color=0xFFEA00)

        win = discord.Embed(title=f"{ctx.author.display_name}, You Won!", description=f">Status: **You have won!** Bot had chosen {comp}", color=0x00FF00)

        out = discord.Embed(title=f"{ctx.author.display_name}, You didn't click on time", description=">Status: **Timed Out!**", color=discord.Color.red())

        lost = discord.Embed(title=f"{ctx.author.display_name}, You Lost!", description=f">Status: **You have lost!** Bot had chosen {comp}", color=0x00FF00)

        tie = discord.Embed(title=f"{ctx.author.display_name}, It was a Tie!", description=f">Status: **Tie!** Bot has chosen {comp}", color=0x00FF00)

        m = await ctx.send(
            embed=yet,
            components=[[Button(style=1, label="Rock"), Button(
                style=3, label="Paper"), Button(style=4, label="Scissors")]]
        )

        def check(res):
            return ctx.author == res.user and res.channel == ctx.channel

        try:
            res = await self.bot.wait_for("button_click", check=check, timeout=15)
            player = res.component.label

            if player == comp:
                await m.edit(embed=tie, components=[])

            if player == "Rock" and comp == "Paper":
                await m.edit(embed=lost, components=[])

            if player != "Rock" and comp == "Scissors":
                await m.edit(embed=win, components=[])

            if player == "Paper" and comp == "Rock":
                await m.edit(embed=win, components=[])

            if player == "Paper" and comp == "Scissors":
                await m.edit(embed=lost, components=[])

            if player == "Scissors" and comp != "Rock":
                await m.edit(embed=lost, components=[])

            if player == "Scissors" and comp == "Paper":
                await m.edit(embed=win, components=[])

        except TimeoutError:
            await m.edit(
                embed=out,
                components=[],
            )

def setup(bot):
    bot.add_cog(rps(bot))


import os
import sys
import time
import pyaudio
import threading
from datetime import datetime
import numpy as np
from picamera import PiCamera

mambrane_fix_date = "13-11-2018"
date = time.strftime("%d-%m-%Y")
mambrane_age = datetime.strptime(date, "%d-%m-%Y") - datetime.strptime(mambrane_fix_date, "%d-%m-%Y")

###################### CAPTURE INFO #####################
ampli_info = "Little Devil"
ampli_volume = "3"
laser_info = "Green class 2"
camera_info = "Sony IMX219 V2.1 8 MPX 1080p30 - 720p60"
mambrane_info = str(mambrane_age.days) + " days"
#########################################################

camera = PiCamera()
camera.resolution = (1280, 720)
camera.start_preview()

nb_f = 2
f = [] * nb_f
if (len(sys.argv) > 1):
    f.insert(0, float(sys.argv[1]))
f.insert(1, 0.0)
a = 2.0

volume = 0.1    # range [0.0, 1.0]
fs = 44100
duration = 3.0
samples = [0.0] * nb_f
file_name = 0

path = "./dataset_lissajous/"
if not  os.path.exists(path):
    os.mkdir(path)
csv =  open(path + date + ".info.csv", "w")
csv.write("ampli : " + ampli_info + ",\nampli_volume : " + ampli_volume + ",\ncode_volume : " + str(volume) + ",\nlaser : " + laser_info + ",\ncamera : " + camera_info + ",\nmambrane_old : " + mambrane_info + ",\n")
csv.close()

p = pyaudio.PyAudio()
stream = [] * nb_f
for x in range(nb_f):
    stream.insert(x, p.open(format = pyaudio.paFloat32, channels = 1, rate = fs, output = True))

class freq_1_thread(threading.Thread):
    def run(self):
        stream[0].write(volume * samples[0])

class freq_2_thread(threading.Thread):
    def run(self):
        stream[1].write(volume * samples[1])

class capture_thread(threading.Thread):
    def run(self):
        camera.capture(path + file_name)

def start_threads():
    play_freq_1 = freq_1_thread()
    play_freq_2 = freq_2_thread()
    cap_laser = capture_thread()
    play_freq_1.start()
    play_freq_2.start()
    time.sleep(0.5)
    cap_laser.start()
    cap_laser.join()
    play_freq_1.join()
    play_freq_2.join()

def stop_stream():
    for x in range(nb_f):
        stream[x].stop_stream()
        stream[x].close()
        stream.stop_stream()
        stream.close()

if (len(sys.argv) > 1):
    while f[0] <= float(sys.argv[2]):
        try:
            f[1] = (a + 1.0) / a * f[0]
            for x in range(nb_f):
                samples.insert(0, (np.sin(2 * np.pi * np.arange(fs * duration) * f[x] / fs)).astype(np.float32))
            file_name = "dataset:" + date + "_hz:" + str(round(f[0], 1)) + "_" + str(round(f[1],3)) + "_lsj:" + str(int(a + 1)) + "." + str(int(a)) + ".jpg"
            start_threads()
            sys.stdout.write("\033[1;32;40m" + str(f[0]) +  "\033[0;37;40m + " + "\033[1;34;40m" +  str(round(f[1], 3)) + "\t\033[0;37;40m hz\t" + "\033[1;33;40m" + str(int(a + 1)) + "/" + str(int(a)) + "\n\033[0;37;40m")
            sys.stdout.flush()
            a += 1
            if a == 10.0:
                sys.stdout.write("\n")
                sys.stdout.flush()
                a = 1
                f[0] += 1.0
        except KeyboardInterrupt:
            exit(0)
    stop_stream()
else:
    sys.stdout.write("\033[1;31;40musage: frequence_min frequence_max\n\033[0;37;40m")
    sys.stdout.flush()
p.terminate()


import calendar
from datetime import date, datetime

class CalendarUtil:
    def __init__(self, year=date.today().year, month=date.today().month):
        self.year = year
        self.month = month
        self.weekdays = [
            'Segunda-Feira',
            'Terça-Feira',
            'Quarta-Feira',
            'Quinta-Feira',
            'Sexta-Feira',
            'Sábado',
            'Domingo'
        ]
        self.months = [
            'Janeiro',
            'Fevereiro',
            'Março',
            'Abril',
            'Maio',
            'Junho',
            'Julho',
            'Agosto',
            'Setembro',
            'Outubro',
            'Novembro',
            'Dezembro,'
        ]

    def get_current_month_range(self):
        _, day_count = calendar.monthrange(self.year, self.month)

        return [i+1 for i in range(day_count)]

    def get_weekday(self, day):
        date_obj = date(self.year, self.month, day)
        return (date_obj.weekday(), self.weekdays[date_obj.weekday()])

if __name__ == '__main__':
    print(CalendarUtil().get_current_month_range())


import random
cont = True
money = int(input("How much money do you have?"))

while(cont):
    game = input("What game do you want to play? Slots or Acey Duecy?")
    bet = int(input("How much do you want to bet?"))

    if (game == "Slots" or game == "slots"):
        type = input("What type of slot? 50%, 25%, 10%?")
        if (type == "50%"):
            if (random.random() < .5):
                money += bet*2
            else:
                money -= bet
            print(money)
        elif (type == "25%"):
            if (random.random() < .25):
                money += bet*(1/.25)
            else:
                money -= bet
            print(money)
        elif (type == "10%"):
            if (random.random() < .1):
                money += bet*(1/.1)
            else:
                money -= bet
            print(money)
    temp = input("Want to play again?")
    if (temp == "yes"):
        cont = True
    elif (temp == "no"):
        cont = False


import os
from datetime import datetime
from time import sleep
from typing import Any, Iterable, List, Optional, Type

import click

from tutor import config as tutor_config
from tutor import env as tutor_env
from tutor import exceptions, fmt, hooks
from tutor import interactive as interactive_config
from tutor import serialize, utils
from tutor.commands import jobs
from tutor.commands.config import save as config_save_command
from tutor.commands.context import BaseTaskContext
from tutor.commands.upgrade import OPENEDX_RELEASE_NAMES
from tutor.commands.upgrade.k8s import upgrade_from
from tutor.tasks import BaseTaskRunner
from tutor.types import Config, get_typed

class K8sClients:
    _instance = None

    def __init__(self) -> None:
        # Loading the kubernetes module here to avoid import overhead
        # pylint: disable=import-outside-toplevel
        from kubernetes import client, config

        if os.path.exists(
            os.path.expanduser(config.kube_config.KUBE_CONFIG_DEFAULT_LOCATION)
        ):
            # found the kubeconfig file, let's load it!
            config.load_kube_config()
        elif (
            config.incluster_config.SERVICE_HOST_ENV_NAME in os.environ
            and config.incluster_config.SERVICE_PORT_ENV_NAME in os.environ
        ):
            # We are running inside a cluster, let's load the in-cluster configuration.
            config.load_incluster_config()
        else:
            raise exceptions.TutorError(
                f"there is no Kubernetes configuration file located in {config.kube_config.KUBE_CONFIG_DEFAULT_LOCATION}, and the service environment variables {config.incluster_config.SERVICE_HOST_ENV_NAME} and {config.incluster_config.SERVICE_PORT_ENV_NAME} have not been defined. To connect to a cluster, please configure your host appropriately."
            )

        self._batch_api = None
        self._core_api = None
        self._client = client

    @classmethod
    def instance(cls: Type["K8sClients"]) -> "K8sClients":
        if cls._instance is None:
            cls._instance = cls()
        return cls._instance

    @property
    def batch_api(self):  # type: ignore
        if self._batch_api is None:
            self._batch_api = self._client.BatchV1Api()
        return self._batch_api

    @property
    def core_api(self):  # type: ignore
        if self._core_api is None:
            self._core_api = self._client.CoreV1Api()
        return self._core_api

class K8sTaskRunner(BaseTaskRunner):
    """
    Run tasks (bash commands) in Kubernetes-managed services.

    Note: a single Tutor "task" correspond to a Kubernetes "job":
    https://kubernetes.io/docs/concepts/workloads/controllers/job/
    A Tutor "job" is composed of multiple Tutor tasks run in different services.

    In Kubernetes, each task that is expected to run in a "myservice" container will
    trigger the "myservice-job" Kubernetes job. This job definition must be present in
    the "k8s/jobs.yml" template.
    """

    def run_task(self, service: str, command: str) -> int:
        canonical_job_name = f"{service}-job"
        all_jobs = list(self._load_jobs())
        job = self._find_job(canonical_job_name, all_jobs)
        # Create a unique job name to make it deduplicate jobs and make it easier to
        # find later. Logs of older jobs will remain available for some time.
        job_name = canonical_job_name + "-" + datetime.now().strftime("%Y%m%d%H%M%S")

        # Wait until all other jobs are completed
        while True:
            active_jobs = self.active_job_names()
            if not active_jobs:
                break
            fmt.echo_info(
                f"Waiting for active jobs to terminate: {' '.join(active_jobs)}"
            )
            sleep(5)

        # Configure job
        job["metadata"]["name"] = job_name
        job["metadata"].setdefault("labels", {})
        job["metadata"]["labels"]["app.kubernetes.io/name"] = job_name
        # Define k8s entrypoint/args
        shell_command = ["sh", "-e", "-c"]
        if job["spec"]["template"]["spec"]["containers"][0].get("command") == []:
            # In some cases, we need to bypass the container entrypoint.
            # Unfortunately, AFAIK, there is no way to do so in K8s manifests. So we mark
            # some jobs with "command: []". For these jobs, the entrypoint becomes "sh -e -c".
            # We do not do this for every job, because some (most) entrypoints are actually useful.
            job["spec"]["template"]["spec"]["containers"][0]["command"] = shell_command
            container_args = [command]
        else:
            container_args = shell_command + [command]
        job["spec"]["template"]["spec"]["containers"][0]["args"] = container_args
        job["spec"]["backoffLimit"] = 1
        job["spec"]["ttlSecondsAfterFinished"] = 3600

        with open(
            tutor_env.pathjoin(self.root, "k8s", "jobs.yml"), "w", encoding="utf-8"
        ) as job_file:
            serialize.dump_all(all_jobs, job_file)

        # We cannot use the k8s API to create the job: configMap and volume names need
        # to be found with the right suffixes.
        kubectl_apply(
            self.root,
            "--selector",
            f"app.kubernetes.io/name={job_name}",
        )

        message = (
            "Job {job_name} is running. To view the logs from this job, run:\n\n"
            """    kubectl logs --namespace={namespace} --follow $(kubectl get --namespace={namespace} pods """
            """--selector=job-name={job_name} -o=jsonpath="{{.items[0].metadata.name}}")\n\n"""
            "Waiting for job completion..."
        ).format(job_name=job_name, namespace=k8s_namespace(self.config))
        fmt.echo_info(message)

        # Wait for completion
        field_selector = f"metadata.name={job_name}"
        while True:
            namespaced_jobs = K8sClients.instance().batch_api.list_namespaced_job(
                k8s_namespace(self.config), field_selector=field_selector
            )
            if not namespaced_jobs.items:
                continue
            job = namespaced_jobs.items[0]
            if not job.status.active:
                if job.status.succeeded:
                    fmt.echo_info(f"Job {job_name} successful.")
                    break
                if job.status.failed:
                    raise exceptions.TutorError(
                        f"Job {job_name} failed. View the job logs to debug this issue."
                    )
            sleep(5)
        return 0

    def load_job(self, name: str) -> Any:
        """
        Find a given job definition in the rendered k8s/jobs.yml template.
        """
        return self._find_job(name, self._load_jobs())

    def _find_job(self, name: str, all_jobs: Iterable[Any]) -> Any:
        """
        Find the matching job definition in the in the list of jobs provided.

        Returns the found job's manifest.
        """
        for job in all_jobs:
            job_name = job["metadata"]["name"]
            if not isinstance(job_name, str):
                raise exceptions.TutorError(
                    f"Invalid job name: '{job_name}'. Expected str."
                )
            if job_name == name:
                return job
        raise exceptions.TutorError(f"Could not find job '{name}'")

    def _load_jobs(self) -> Iterable[Any]:
        manifests = self.render("k8s", "jobs.yml")
        for manifest in serialize.load_all(manifests):
            if manifest["kind"] == "Job":
                yield manifest

    def active_job_names(self) -> List[str]:
        """
        Return a list of active job names
        Docs:
        https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.18/#list-job-v1-batch

        This is necessary to make sure that we don't run the same job multiple times at
        the same time.
        """
        api = K8sClients.instance().batch_api
        return [
            job.metadata.name
            for job in api.list_namespaced_job(k8s_namespace(self.config)).items
            if job.status.active
        ]

class K8sContext(BaseTaskContext):
    def job_runner(self, config: Config) -> K8sTaskRunner:
        return K8sTaskRunner(self.root, config)

@click.group(help="Run Open edX on Kubernetes")
@click.pass_context
def k8s(context: click.Context) -> None:
    context.obj = K8sContext(context.obj.root)

@click.command(help="Configure and run Open edX from scratch")
@click.option("-I", "--non-interactive", is_flag=True, help="Run non-interactively")
@click.pass_context
def launch(context: click.Context, non_interactive: bool) -> None:
    run_upgrade_from_release = tutor_env.should_upgrade_from_release(context.obj.root)
    if run_upgrade_from_release is not None:
        click.echo(fmt.title("Upgrading from an older release"))
        context.invoke(
            upgrade,
            from_release=tutor_env.get_env_release(context.obj.root),
        )

    click.echo(fmt.title("Interactive platform configuration"))
    config = tutor_config.load_minimal(context.obj.root)
    if not non_interactive:
        interactive_config.ask_questions(config, run_for_prod=True)
    tutor_config.save_config_file(context.obj.root, config)
    config = tutor_config.load_full(context.obj.root)
    tutor_env.save(context.obj.root, config)

    if run_upgrade_from_release and not non_interactive:
        question = f"""Your platform is being upgraded from {run_upgrade_from_release.capitalize()}.

If you run custom Docker images, you must rebuild and push them to your private repository now by running the following
commands in a different shell:

    tutor images build all # add your custom images here
    tutor images push all

Press enter when you are ready to continue"""
        click.confirm(
            fmt.question(question), default=True, abort=True, prompt_suffix=" "
        )

    click.echo(fmt.title("Starting the platform"))
    context.invoke(start)

    click.echo(fmt.title("Database creation and migrations"))
    context.invoke(init, limit=None)

    config = tutor_config.load(context.obj.root)
    fmt.echo_info(
        """Your Open edX platform is ready and can be accessed at the following urls:

    {http}://{lms_host}
    {http}://{cms_host}
    """.format(
            http="https" if config["ENABLE_HTTPS"] else "http",
            lms_host=config["LMS_HOST"],
            cms_host=config["CMS_HOST"],
        )
    )

@click.command(
    short_help="Run all configured Open edX resources",
    help=(
        "Run all configured Open edX resources. You may limit this command to "
        "some resources by passing name arguments."
    ),
)
@click.argument("names", metavar="name", nargs=-1)
@click.pass_obj
def start(context: K8sContext, names: List[str]) -> None:
    config = tutor_config.load(context.root)
    # Create namespace, if necessary
    # Note that this step should not be run for some users, in particular those
    # who do not have permission to edit the namespace.
    try:
        utils.kubectl("get", "namespaces", k8s_namespace(config))
        fmt.echo_info("Namespace already exists: skipping creation.")
    except exceptions.TutorError:
        fmt.echo_info("Namespace does not exist: now creating it...")
        kubectl_apply(
            context.root,
            "--wait",
            "--selector",
            "app.kubernetes.io/component=namespace",
        )

    names = names or ["all"]
    for name in names:
        if name == "all":
            # Create volumes
            kubectl_apply(
                context.root,
                "--wait",
                "--selector",
                "app.kubernetes.io/component=volume",
            )
            # Create everything else except jobs
            kubectl_apply(
                context.root,
                "--selector",
                "app.kubernetes.io/component notin (job,volume,namespace)",
            )
        else:
            kubectl_apply(
                context.root,
                "--selector",
                f"app.kubernetes.io/name={name}",
            )

@click.command(
    short_help="Stop a running platform",
    help=(
        "Stop a running platform by deleting all resources, except for volumes. "
        "You may limit this command to some resources by passing name arguments."
    ),
)
@click.argument("names", metavar="name", nargs=-1)
@click.pass_obj
def stop(context: K8sContext, names: List[str]) -> None:
    config = tutor_config.load(context.root)
    names = names or ["all"]
    for name in names:
        if name == "all":
            delete_resources(config)
        else:
            delete_resources(config, name=name)

def delete_resources(
    config: Config, resources: Optional[List[str]] = None, name: Optional[str] = None
) -> None:
    """
    Delete resources by type and name.

    The load balancer is never deleted.
    """
    resources = resources or ["deployments", "services", "configmaps", "jobs"]
    not_lb_selector = "app.kubernetes.io/component!=loadbalancer"
    name_selector = [f"app.kubernetes.io/name={name}"] if name else []
    utils.kubectl(
        "delete",
        *resource_selector(config, not_lb_selector, *name_selector),
        ",".join(resources),
    )

@click.command(help="Reboot an existing platform")
@click.pass_context
def reboot(context: click.Context) -> None:
    context.invoke(stop)
    context.invoke(start)

@click.command(help="Completely delete an existing platform")
@click.option("-y", "--yes", is_flag=True, help="Do not ask for confirmation")
@click.pass_obj
def delete(context: K8sContext, yes: bool) -> None:
    if not yes:
        click.confirm(
            "Are you sure you want to delete the platform? All data will be removed.",
            abort=True,
        )
    utils.kubectl(
        "delete",
        "-k",
        tutor_env.pathjoin(context.root),
        "--ignore-not-found=true",
        "--wait",
    )

@jobs.do_group
@click.pass_obj
def do(context: K8sContext) -> None:
    """
    Run a custom job in the right container(s).

    We make sure that some essential containers (databases, proxy) are up before we
    launch the jobs.
    """

    @hooks.Actions.DO_JOB.add()
    def _start_base_deployments(_job_name: str, *_args: Any, **_kwargs: Any) -> None:
        """
        We add this logic to an action callback because we do not want to trigger it
        whenever we run `tutor k8s do <job> --help`.
        """
        config = tutor_config.load(context.root)
        wait_for_deployment_ready(config, "caddy")
        for name in ["elasticsearch", "mysql", "mongodb"]:
            if tutor_config.is_service_activated(config, name):
                wait_for_deployment_ready(config, name)

@click.command(help="Initialise all applications")
@click.option("-l", "--limit", help="Limit initialisation to this service or plugin")
@click.pass_context
def init(context: click.Context, limit: Optional[str]) -> None:
    context.invoke(do.commands["init"], limit=limit)

@click.command(help="Scale the number of replicas of a given deployment")
@click.argument("deployment")
@click.argument("replicas", type=int)
@click.pass_obj
def scale(context: K8sContext, deployment: str, replicas: int) -> None:
    config = tutor_config.load(context.root)
    utils.kubectl(
        "scale",
        # Note that we don't use the full resource selector because selectors
        # are not compatible with the deployment/<name> argument.
        *resource_namespace_selector(
            config,
        ),
        f"--replicas={replicas}",
        f"deployment/{deployment}",
    )

@click.command(
    name="exec",
    help="Execute a command in a pod of the given application",
    context_settings={"ignore_unknown_options": True},
)
@click.argument("service")
@click.argument("args", nargs=-1, required=True)
@click.pass_obj
def exec_command(context: K8sContext, service: str, args: List[str]) -> None:
    config = tutor_config.load(context.root)
    kubectl_exec(config, service, args)

@click.command(help="View output from containers")
@click.option("-c", "--container", help="Print the logs of this specific container")
@click.option("-f", "--follow", is_flag=True, help="Follow log output")
@click.option("--tail", type=int, help="Number of lines to show from each container")
@click.argument("service")
@click.pass_obj
def logs(
    context: K8sContext, container: str, follow: bool, tail: bool, service: str
) -> None:
    config = tutor_config.load(context.root)

    command = ["logs"]
    selectors = ["app.kubernetes.io/name=" + service] if service else []
    command += resource_selector(config, *selectors)

    if container:
        command += ["-c", container]
    if follow:
        command += ["--follow"]
    if tail is not None:
        command += ["--tail", str(tail)]

    utils.kubectl(*command)

@click.command(help="Wait for a pod to become ready")
@click.argument("name")
@click.pass_obj
def wait(context: K8sContext, name: str) -> None:
    config = tutor_config.load(context.root)
    wait_for_deployment_ready(config, name)

@click.command(
    short_help="Perform release-specific upgrade tasks",
    help="Perform release-specific upgrade tasks. To perform a full upgrade remember to run `launch`.",
)
@click.option(
    "--from",
    "from_release",
    type=click.Choice(OPENEDX_RELEASE_NAMES),
)
@click.pass_context
def upgrade(context: click.Context, from_release: Optional[str]) -> None:
    if from_release is None:
        from_release = tutor_env.get_env_release(context.obj.root)
    if from_release is None:
        fmt.echo_info("Your environment is already up-to-date")
    else:
        fmt.echo_alert(
            "This command only performs a partial upgrade of your Open edX platform. "
            "To perform a full upgrade, you should run `tutor k8s launch`."
        )
        upgrade_from(context, from_release)
    # We update the environment to update the version
    context.invoke(config_save_command)

@click.command(
    short_help="Direct interface to `kubectl apply`.",
    help=(
        "Direct interface to `kubnectl-apply`. This is a wrapper around `kubectl apply`. A;; options and"
        " arguments passed to this command will be forwarded as-is to `kubectl apply`."
    ),
    context_settings={"ignore_unknown_options": True},
    name="apply",
)
@click.argument("args", nargs=-1)
@click.pass_obj
def apply_command(context: K8sContext, args: List[str]) -> None:
    kubectl_apply(context.root, *args)

def kubectl_apply(root: str, *args: str) -> None:
    utils.kubectl("apply", "--kustomize", tutor_env.pathjoin(root), *args)

@click.command(help="Print status information for all k8s resources")
@click.pass_obj
def status(context: K8sContext) -> int:
    config = tutor_config.load(context.root)
    return utils.kubectl("get", "all", *resource_namespace_selector(config))

def kubectl_exec(config: Config, service: str, command: List[str]) -> int:
    selector = f"app.kubernetes.io/name={service}"
    pods = K8sClients.instance().core_api.list_namespaced_pod(
        namespace=k8s_namespace(config), label_selector=selector
    )
    if not pods.items:
        raise exceptions.TutorError(
            f"Could not find an active pod for the {service} service"
        )
    pod_name = pods.items[0].metadata.name

    # Run command
    return utils.kubectl(
        "exec",
        "--stdin",
        "--tty",
        "--namespace",
        k8s_namespace(config),
        pod_name,
        "--",
        *command,
    )

def wait_for_deployment_ready(config: Config, service: str) -> None:
    fmt.echo_info(f"Waiting for a {service} deployment to be ready...")
    utils.kubectl(
        "wait",
        *resource_selector(config, f"app.kubernetes.io/name={service}"),
        "--for=condition=Available=True",
        "--timeout=600s",
        "deployment",
    )

def resource_selector(config: Config, *selectors: str) -> List[str]:
    """
    Convenient utility to filter the resources that belong to this project.
    """
    selector = ",".join(
        ["app.kubernetes.io/instance=openedx-" + get_typed(config, "ID", str)]
        + list(selectors)
    )
    return resource_namespace_selector(config) + ["--selector=" + selector]

def resource_namespace_selector(config: Config) -> List[str]:
    """
    Convenient utility to filter the resources that belong to this project namespace.
    """
    return ["--namespace", k8s_namespace(config)]

def k8s_namespace(config: Config) -> str:
    return get_typed(config, "K8S_NAMESPACE", str)

k8s.add_command(launch)
k8s.add_command(start)
k8s.add_command(stop)
k8s.add_command(reboot)
k8s.add_command(delete)
k8s.add_command(init)
k8s.add_command(scale)
k8s.add_command(exec_command)
k8s.add_command(logs)
k8s.add_command(wait)
k8s.add_command(upgrade)
k8s.add_command(apply_command)
k8s.add_command(status)

@hooks.Actions.PLUGINS_LOADED.add()
def _add_k8s_do_commands() -> None:
    jobs.add_job_commands(do)
    k8s.add_command(do)


from binary_tree import get_sample_binary_tree,get_sample_bst

def is_leaf(node):
    return node.left is None and node.right is None

def get_new_paths(curr_paths, child_val, root_val):
    paths = []
    for path in curr_paths:
        if path[len(path)-1] == child_val:
            new_path = []
            new_path.extend(path)
            new_path.append(root_val)
            paths.append(new_path)
    return paths

def get_paths(root):
    if is_leaf(root):
        return [[root.val]]
    paths = []
    paths.append([root.val])
    lp = get_paths(root.left)
    rp = get_paths(root.right)
    lp_new = get_new_paths(lp,root.left.val,root.val)
    rp_new = get_new_paths(rp,root.right.val,root.val)

    paths.extend(lp)
    paths.extend(rp)
    paths.extend(lp_new)
    paths.extend(rp_new)
    return paths

def paths_with_sum(bt,gvn_sum):
    tot_paths = get_paths(bt)
    cnt = 0
    for path in tot_paths:
        if sum(path) == gvn_sum:
            print(path)
            cnt = cnt+1
    return cnt

def main():
    bt = get_sample_binary_tree()
    print( paths_with_sum(bt,3) )

if __name__ == '__main__':
    main()


import numpy as np
import itertools
import kernel_learning as kler
import matplotlib.pyplot as plt
import jax_math as jmath
import database_preparation as datprep
datapath = "/home/stuke/Databases/QM9_XYZ_below10/"

def cleanup_results(result_file, multiple_runs = False, Choose_Folder = False, rep_no = 1):
    ''' gets data from resultfile and returns plottable Curve objects
    Variables
    ---------
    resultsfile : string, path to file containing pickled Result objects
    multiple_runs : if True, calculate mean of runs with same lamda and sigma
    Choose_Folder: boolean, if True, file is directly stored to result_file.
                    if not, result file is stored in ./Pickled/Kernel_Results folder

    Returns
    -------
    this_curve : LearningResults object
    '''

    if not Choose_Folder:
        #print("your results were stored to ./Pickled/Kernel_Results/")
        result_file = "./Pickled/Kernel_Results/" + result_file + "_" + str(rep_no)+ "reps"

    plottable_curves = []
    if rep_no > 1:
        multiple_runs = True

    if multiple_runs:
        lamdas = []
        sigmas = []

    results_list = datprep.read_compounds(result_file)
    #print("len results_list:", len(results_list))

    for result in results_list:
        #print("type result:", type(result))
        lamda = result.lamda
        sigma = result.sigma
        xlist = result.set_sizes
        ylist = result.maes
        if not multiple_runs:
            name = curve_name(sigma, lamda)
            curve = CurveObj(name)
            curve.xnparray = xlist
            curve.ynparray = ylist

            plottable_curves.append(curve)

        else:
            lamdas.append(lamda)
            sigmas.append(sigma)

    #probably plottable_curves could already be returned here for False
    if multiple_runs:
        for l in list(set(lamdas)): #get all unique occurances for lamda
            for s in list(set(sigmas)): #get all unique occurances for sigma
                same_x = []
                same_y = []

                #find all results with these s and l
                for result in results_list:
                    if result.lamda == l and result.sigma == s:
                        same_x.append(result.set_sizes)
                        same_y.append(result.maes)
                #print("all arrays of same y:\n", same_y)
                #calculate average now
                av_ylist, yerror = jmath.calculate_mean(same_y)
                print("the calculated mean and it's error are:\n mean:", av_ylist, "\n error:", yerror)
                #add Curve object
                name = curve_name(s,l)
                curve = CurveObj(name)
                curve.xnparray = same_x[0]
                curve.ynparray = av_ylist
                curve.yerror = yerror

                plottable_curves.append(curve)

    return(plottable_curves)

def curve_name( sigma, lamda):
    name = ', sigma = %s, lambda = %s'% (str(sigma), str(lamda))
    return(name)

def plot_learning(set_sizes ,\
        maes,\
        labels = [],\
        xtitle = 'Training Set Size',\
        ytitle = 'MAE [kcal/mol]',\
        title = "sigma = 20\nlambda = 1e-3",\
        filename = "QML_learning"):

    '''
    plots x and y values of learning curves
    '''

    #standard settings for plotting:
    fontsize = 30

    plt.rc('font',       size=fontsize) # controls default text sizes
    plt.rc('axes',  titlesize=fontsize) # fontsize of the axes title
    plt.rc('axes',  labelsize=fontsize) # fontsize of the x and y labels
    plt.rc('xtick', labelsize=fontsize*0.8) # fontsize of the tick labels
    plt.rc('ytick', labelsize=fontsize*0.8) # fontsize of the tick labels
    plt.rc('legend', fontsize=fontsize*0.8) # legend fontsize
    plt.rc('figure',titlesize=fontsize*1.2) # fontsize of the figure title
    plt.rcParams['axes.titlepad'] = 20

    f, ax = plt.subplots(nrows = 1, ncols = 1, figsize = (12, 8))

    for m in range(len(maes)):
        mae_list = maes[m]
        name = labels[m]
        ax.loglog(set_sizes, mae_list, label = name, linewidth = 2)

    ax.spines['right'].set_color('none')
    ax.spines['top'].set_color('none')
    ax.spines['bottom'].set_position(('axes', -0.05))
    ax.spines['bottom'].set_color('black')
    ax.spines['left'].set_color('black')
    ax.yaxis.set_ticks_position('left')
    ax.xaxis.set_ticks_position('bottom')
    ax.spines['left'].set_position(('axes', -0.05))

    ax.xaxis.set_tick_params(width=2.5, length=20)
    ax.yaxis.set_tick_params(width=2.5, length=20)

    #set x and y axis label
    ax.set_xlabel(xtitle)
    ax.set_ylabel(ytitle)

    #add legend
    ax.legend()

    #save figure
    f.savefig(filename, bbox_inches = 'tight')

    return(print("figure was saved to", filename))

def plot_scatter(y_test, y_predicted, label = "OM",\
        title = "OM Representation Gaussian Kernel",\
        figuretitle = "Scatterplot_OM",\
        xtitle = "Atomic Energies [kcal/mol]",\
        ytitle = "Predicted Atomic Energies [kcal/mol]"):
    #standard settings for plotting:
    fontsize = 30

    plt.rc('font',       size=fontsize) # controls default text sizes
    plt.rc('axes',  titlesize=fontsize) # fontsize of the axes title
    plt.rc('axes',  labelsize=fontsize) # fontsize of the x and y labels
    plt.rc('xtick', labelsize=fontsize*0.8) # fontsize of the tick labels
    plt.rc('ytick', labelsize=fontsize*0.8) # fontsize of the tick labels
    plt.rc('legend', fontsize=fontsize*0.8) # legend fontsize
    plt.rc('figure',titlesize=fontsize*1.2) # fontsize of the figure title
    plt.rcParams['axes.titlepad'] = 20

    #prep figure
    f, ax = plt.subplots(nrows = 1, ncols = 1, figsize = (12, 8))

    ax.set_xlabel(xtitle)
    ax.set_ylabel(ytitle)

    ax.spines['right'].set_color('none')
    ax.spines['top'].set_color('none')
    ax.spines['bottom'].set_position(('axes', -0.05))
    ax.spines['bottom'].set_color('black')
    ax.spines['left'].set_color('black')
    ax.yaxis.set_ticks_position('left')
    ax.xaxis.set_ticks_position('bottom')
    ax.spines['left'].set_position(('axes', -0.05))

    ax.xaxis.set_tick_params(width=2.5, length=20)
    ax.yaxis.set_tick_params(width=2.5, length=20)

    st = f.suptitle(title)

    #plot results
    ax.scatter(y_test, y_predicted, label = label)

    #make x and y ticks the same
    multiplier = 10 ** -2
    min_tick = int(min(y_test)*multiplier) / multiplier

    plt.xticks(np.arange(min_tick, max(y_test)+100, 200))
    plt.yticks(np.arange(min_tick, max(y_test)+100, 200))
    #save figure

    f.savefig(figuretitle, bbox_inches = 'tight')
    return(print("figure was saved to", figuretitle))

def plot_curves(curve_list, file_title = "TrialLearning",\
        plottitle = 'Learning Curves of CM Eigenvector Representation on QM9 Dataset\n 1000 molecules, 2 Runs Averaged',\
        xtitle = 'Training Set Size',\
        ytitle = 'MAE [kcal/mol]',\
        multiple_runs = False,\
        include_title = False):

    '''plots learning curves from hartree to kcal/mol
    curve_list: list of CurveObj class objects
    file_title: string, where to store plot to
    plottitle = title over plot
    xtitle : string, title of x axis
    ytitle : string, title of y axis
    mutliple_runs : boolean, if true, plot curves with variation shadowed
    include_title : boolean, if true, plot title
    '''

    #standard settings for plotting:
    fontsize = 30

    plt.rc('font',       size=fontsize) # controls default text sizes
    plt.rc('axes',  titlesize=fontsize) # fontsize of the axes title
    plt.rc('axes',  labelsize=fontsize) # fontsize of the x and y labels
    plt.rc('xtick', labelsize=fontsize*0.8) # fontsize of the tick labels
    plt.rc('ytick', labelsize=fontsize*0.8) # fontsize of the tick labels
    plt.rc('legend', fontsize=fontsize*0.8) # legend fontsize
    plt.rc('figure',titlesize=fontsize*1.2) # fontsize of the figure title
    plt.rcParams['axes.titlepad'] = 20

    f, ax = plt.subplots(nrows = 1, ncols = 1, figsize = (12, 8))

    #plot title if included
    if include_title:
        st = f.suptitle(plottitle)

    ax.set_xlabel(xtitle)
    ax.set_ylabel(ytitle)

    ax.set_xscale('log')
    ax.set_yscale('log')

    ax.spines['right'].set_color('none')
    ax.spines['top'].set_color('none')
    ax.spines['bottom'].set_position(('axes', -0.05))
    ax.spines['bottom'].set_color('black')
    ax.spines['left'].set_color('black')
    ax.yaxis.set_ticks_position('left')
    ax.xaxis.set_ticks_position('bottom')
    ax.spines['left'].set_position(('axes', -0.05))

    ax.xaxis.set_tick_params(width=2.5, length=20)
    ax.yaxis.set_tick_params(width=2.5, length=20)

    #assign marker for better differentiation
    marker = itertools.cycle((',', '+', '.', 'o', '*', "1", "2", "3", "4", "8", "H", "D"))

    #all the plotting has to be done below
    for curve in curve_list:

        yarray = curve.ynparray

        ax.plot(curve.xnparray, curve.ynparray, linewidth = 2, marker = next(marker), label = curve.name)
        print('x:' ,curve.xnparray,'\ny:', yarray)

    #all the plotting has to be done above

    f.legend = ax.legend(loc = 'lower left')

    #handles, labels = ax.get_legend_handles_labels()

    #f.legend(handles, labels, bbox_to_anchor=(1,1), loc="upper left")

    figuretitle = "./Images/" + file_title + ".png"
    f.savefig(figuretitle, bbox_inches = 'tight')
    return(print("figure was saved to", figuretitle))


import serpent
from pyethereum import tester, utils, abi

serpent_code = '''
def transfer(amount, recipient):
    log(amount, recipient)
    return(amount)
'''

s = tester.state()
c = s.abi_contract(serpent_code)
public_key1 = utils.privtoaddr(tester.k1)
data = c.transfer(500, public_key1, sender=tester.k0)

print(str(data))


from turtle import *

class GameElement(Turtle):
    def __init__(self, gotox, gotoy, shape_size_wid=1, shape_size_len=1, spd=0, col="white", shap="square",
                 hide_turtle=False):
        # Inherits all methods and properties from Turle()
        super().__init__()

        # Sets speed for maximum speed
        self.speed(spd)

        self.shape(shap)
        self.color(col)

        if shape_size_wid != 0 | shape_size_len != 0:
            self.shapesize(stretch_wid=shape_size_wid, stretch_len=shape_size_len)

        self.penup()
        self.goto(gotox, gotoy)

        if hide_turtle:
            self.hideturtle()


import os
import time
import logging as log

from virttest import virsh
from virttest import data_dir
from virttest import utils_disk
from virttest import utils_misc
from virttest.utils_test import libvirt
from virttest.libvirt_xml import vm_xml

# Using as lower capital is not the best way to do, but this is just a
# workaround to avoid changing the entire file.
logging = log.getLogger('avocado.' + __name__)

def run(test, params, env):
    """
    Test command: virsh qemu-agent-command.
    """
    vm_name = params.get("main_vm")
    vm = env.get_vm(vm_name)
    status_cmd = params.get("status_cmd", "")
    freeze_cmd = params.get("freeze_cmd", "")
    thaw_cmd = params.get("thaw_cmd", "")
    xml_backup = vm_xml.VMXML.new_from_inactive_dumpxml(vm_name)
    try:
        def get_dirty(session, frozen=False):
            """
            Get dirty data of guest
            """
            try:
                data_cmd = "cat /proc/meminfo | grep Dirty"
                if not frozen:
                    result = utils_misc.wait_for(lambda:
                                                 int(session.
                                                     cmd_output(data_cmd).
                                                     strip().split()[1]) != 0,
                                                 60)
                    if result:
                        return int(session.cmd_output(data_cmd).strip().
                                   split()[1])
                    else:
                        return 0
                    dirty_info = session.cmd_output(data_cmd).strip()
                    return int(dirty_info.split()[1])
                else:
                    result = utils_misc.wait_for(lambda:
                                                 int(session.
                                                     cmd_output(data_cmd).
                                                     strip().split()[1]) == 0,
                                                 60)
                    if result:
                        return 0
                    else:
                        return int(session.cmd_output(data_cmd).strip().
                                   split()[1])
            except (IndexError, ValueError) as details:
                test.fail("Get dirty info failed: %s" % details)

        device_source_path = os.path.join(data_dir.get_tmp_dir(), "disk.img")
        device_source = libvirt.create_local_disk("file", path=device_source_path,
                                                  disk_format="qcow2")
        vm.prepare_guest_agent()

        # Do operation before freeze guest filesystem
        session = vm.wait_for_login()
        tmp_file = "/mnt/test.file"
        try:
            # Create extra image and attach to guest, then mount
            old_parts = utils_disk.get_parts_list(session)
            ret = virsh.attach_disk(vm_name, device_source, "vdd")
            if ret.exit_status:
                test.fail("Attaching device failed before testing agent:%s" % ret.stdout.strip())
            time.sleep(1)
            new_parts = utils_disk.get_parts_list(session)
            added_part = list(set(new_parts).difference(set(old_parts)))
            session.cmd("mkfs.ext3 -F /dev/{0} && mount /dev/{0} /mnt".format(added_part[0]))

            # Generate dirty memory
            session.cmd("rm -f %s" % tmp_file)
            session.cmd_output("cp /dev/zero %s 2>/dev/null &" % tmp_file)
            # Get original dirty data
            org_dirty_info = get_dirty(session)
            fz_cmd_result = virsh.qemu_agent_command(vm_name, freeze_cmd,
                                                     ignore_status=True,
                                                     debug=True)
            libvirt.check_exit_status(fz_cmd_result)

            # Get frozen dirty data
            fz_dirty_info = get_dirty(session, True)
            st_cmd_result = virsh.qemu_agent_command(vm_name, status_cmd,
                                                     ignore_status=True,
                                                     debug=True)
            libvirt.check_exit_status(st_cmd_result)
            if not st_cmd_result.stdout.strip().count("frozen"):
                test.fail("Guest filesystem status is not frozen: %s"
                          % st_cmd_result.stdout.strip())

            tw_cmd_result = virsh.qemu_agent_command(vm_name, thaw_cmd,
                                                     ignore_status=True,
                                                     debug=True)
            libvirt.check_exit_status(tw_cmd_result)

            # Get thawed dirty data
            tw_dirty_info = get_dirty(session)
            st_cmd_result = virsh.qemu_agent_command(vm_name, status_cmd,
                                                     ignore_status=True,
                                                     debug=True)
            libvirt.check_exit_status(st_cmd_result)
            if not st_cmd_result.stdout.strip().count("thawed"):
                test.fail("Guest filesystem status is not thawed: %s"
                          % st_cmd_result.stdout.strip())
            logging.info("Original dirty data: %s" % org_dirty_info)
            logging.info("Frozen dirty data: %s" % fz_dirty_info)
            logging.info("Thawed dirty data: %s" % tw_dirty_info)
            if not tw_dirty_info or not org_dirty_info:
                test.fail("The thawed dirty data should not be 0!")
            if fz_dirty_info:
                test.fail("The frozen dirty data should be 0!")
        finally:
            # Thaw the file system that remove action can be done
            virsh.qemu_agent_command(vm_name, thaw_cmd, ignore_status=True)
            session.cmd("rm -f %s" % tmp_file)
            session.close()
    finally:
        xml_backup.sync()
        os.remove(device_source_path)


# available items
pizzas = {
  "Margherita": 100,
  "Pepperoni": 120,
  "Meat Lovers": 150,
  "Chicken": 130
}
burgers = {"Beef": 100, "Chicken": 80, "Bacon": 120}
drinks = {"Coke": 30, "Sprite": 25, "Fanta": 25, "Pepsi": 30}
soups = {"Chicken Soup": 50, "Beef Soup": 60, "Mushroom Soup": 40}
desserts = {"Ice Cream": 50, "Chocolate Cake": 60, "Cheese Cake": 70}

menu = {
  'Pizzas': pizzas,
  'Burgers': burgers,
  'Drinks': drinks,
  'Soups': soups,
  'Desserts': desserts
}

order = {}

options_message = ('''\n1. Add another item
2. View the order
3. Clear the order
4. Remove item from the order
5. Exit
Please enter your choice: ''')

print('Welcome to Codezilla restaurant')

while True:
  while True:
    #display the main menu
    print('\nOur delecious menu')
    for i, item in enumerate(menu, 1):
      print(f'{i}. {item.title()}')
    #get th order item from the user
    user_input = input(
      '\nPlease, enter the number of the item you want (Press enter to go to the options menu): '
    )
    #if the user press enter to exit
    if user_input == '':
      break
    #if the user enter valid number of the item from the menu
    elif user_input.isdigit():
      #create a list of items in main menu
      menu_lst = list(menu.keys())
      #convert the user choice to integer
      user_input = int(user_input)
      #if the valid number in the items range
      if user_input in range(len(menu_lst) + 1):
        #get the order item
        order_category = menu_lst[user_input - 1]
        #display the sub-menu with the prices
        for i, item in enumerate(menu[order_category], 1):
          print(f'{i}. {item.title()}: {menu[order_category][item]} EGP')
        #get th order sub-item number from the user
        user_order = input(
          '\nPlease, enter the number of the item you want (Press 0 to return to the previous menu): '
        )
        #if the user press 0 to return back to the main menu
        if user_order == "0":
          continue
        #if the user enter valid number of the sub-item from the sub-menu
        elif user_order.isdigit():
          #convert the user choice to integer
          user_order = int(user_order)
          #create a list of sub-items in sub-menu
          sub_menu_lst = list(menu[order_category].keys())
          #if the valid number in the items range
          if user_order in range(len(sub_menu_lst) + 1):
            #get the order sub-item
            order_item = sub_menu_lst[user_order - 1]
            #get the sub-item price
            order_price = menu[order_category][order_item]
            #get the user needed quantity
            user_order_quantity = int(input('\nPlease, enter the quantity: '))

            #update the order quantity
            order_quantity = order.get(order_item, {}).get(
              'quantity', 0) + user_order_quantity
            #the total price of the single sub-item
            item_total_price = order_quantity * order_price

            print(
              f'{order_item} {order_category} added to the order successfully')

            #check and ask the user to add a comment
            check = input(
              '\nDo you want to add a comment to the order (y/n)? ').lower()
            if check == 'y':
              comment = input('\nAdd your comment here: ')
              print('\nWe will take your comment into consideration.')
            elif check == 'n':
              comment = 'No comment'
            else:
              print('\nInvalid choice, please renter your choice')
              continue
            #create an order info
            order_info = {
              order_item: {
                'category': order_category,
                'comment': comment,
                'price': order_price,
                'quantity': order_quantity,
                'item_total_price': item_total_price
              }
            }
            #update the order
            order.update(order_info)
            break
          else:
            print('\nInvalid choice,please renter your choice')
            continue
        else:
          print('\nInvalid choice,please renter your choice')
          continue
      else:
        print('\nInvalid choice,please renter your choice')
        continue
    else:
      print('\nInvalid choice,please renter your choice')
      continue
      #display the options menu
  user_option = input(options_message)

  #if the user chooses number 1 to add an order
  if user_option == '1':
    check = input(
      '\nAre you sure you want to add an order? (y: to return back to the menu / n: to exit the program) '
    ).lower()
    if check == 'y':
      continue
    elif check == 'n':
      break
    else:
      print('\nInvalid choice, please renter your choice')
      continue
  #if the user chooses number 2 to view the order
  elif user_option == '2':
    if order:
      #display the order
      for item, info in order.items():
        print(f"""\nItem: {item} {info['category']}
Price: {info['price']} EGP
Quantity: {info['quantity']} units
----------------------
Item Total price: {info['item_total_price']}\n""")
    else:
      print('\nThere is no order yet!!')
      continue
  #if the user chooses number 3 to clear the order
  elif user_option == '3':
    #check if the user sure to clear the order
    if order:
      check = input(
        '\nAre you sure you want to clear the order? (Y/N): ').lower()
      if check == 'y':
        order.clear()
        print('\nOrder cleared successfully!')
      elif check == 'n':
        continue
      else:
        print('Invalid choice,please renter your choice')
        continue
    else:
      print('\nThere is no order to clear!')

  #elif user chooses 4 to remove item from the order
  elif user_option == '4':
    #if there is order
    if order:
      #display the order for the user
      print('Your current order is:\n-------------------------')
      for item, info in order.items():
        print(f"""\nItem: {item}
Price: {info['price']} EGP
Quantity: {info['quantity']} units""")
      #ask the user for the item he want to delete
      item_to_remove = input(
        '\nPlease, enter the item you want to remove: ').title().strip()
      #check meassge
      check = input(
        '\nAre you sure you want to remove this item (y/n): ').lower()
      if check == 'y':
        #check if the item is in the order
        if item_to_remove in order:
          del order[item_to_remove]
          print(f'{item_to_remove} has been removed from the order')
        else:
          print(f'{item_to_remove} is not in the order')
      elif check == 'n':
        continue
      else:
        print('Invalid choice,please renter your choice')
        continue
    else:
      print('There is no order yet.')
  #if the user chooses 5 to exit
  elif user_option == '5':
    break
  #if user_option is invalid
  else:
    print('\nInvalid choice,please renter your choice')
    continue

#greeting message
print('\nThanks for choosing Codezilla restaurant')
print('****************************************')
if order:
  print('\nYour order is:')
  #print the order to the user
  for item, info in order.items():
    print(f"""\nItem: {item} {info['category']}
Client comment: {info['comment']}
Price: {info['price']} EGP
Quantity: {info['quantity']} units
----------------------
Item Total price: {info['item_total_price']}\n""")
  Total_price = sum([info['item_total_price'] for item, info in order.items()])

  print(f'''***********************
The total price is: {Total_price}''')


import os
import torch.optim as optim
import torch.nn as nn

from lpd.trainer import Trainer
from lpd.predictor import Predictor
from lpd.callbacks import SchedulerStep, StatsPrint, ModelCheckPoint, LossOptimizerHandler, CallbackMonitor
from lpd.extensions.custom_schedulers import DoNothingToLR
from lpd.enums import Phase, State, MonitorType, StatsType, MonitorMode
from lpd.metrics import BinaryAccuracyWithLogits, MetricBase
import lpd.utils.torch_utils as tu
import lpd.utils.general_utils as gu
import examples.utils as eu

gu.seed_all(42)  # BECAUSE ITS THE ANSWER TO LIFE AND THE UNIVERSE

save_to_dir = os.path.dirname(__file__) + '/trainer_checkpoint/'
trainer_file_name = 'trainer'

def get_parameters():
    # N is batch size; D_in is input dimension;
    # H is hidden dimension; D_out is output dimension.
    N, D_in, H, D_out = 64, 100, 100, 1
    num_epochs = 3
    data_loader = eu.examples_data_generator(N, D_in, D_out, binary_out=True)
    data_loader_steps = 100
    return N, D_in, H, D_out, num_epochs, data_loader, data_loader_steps

def get_trainer_base(D_in, H, D_out):
    device = tu.get_gpu_device_if_available()

    model = eu.get_basic_model(D_in, H, D_out).to(device)

    loss_func = nn.BCEWithLogitsLoss().to(device)

    optimizer = optim.Adam(model.parameters(), lr=1e-4)

    scheduler = DoNothingToLR() #CAN ALSO USE scheduler=None, BUT DoNothingToLR IS MORE EXPLICIT

    metrics = BinaryAccuracyWithLogits(name='Accuracy')

    return device, model, loss_func, optimizer, scheduler, metrics

def get_trainer(N, D_in, H, D_out, num_epochs, data_loader, data_loader_steps):
    device, model, loss_func, optimizer, scheduler, metrics = get_trainer_base(D_in, H, D_out)

    callbacks = [
                    LossOptimizerHandler(),
                    #ADDING ModelCheckPoint WITH save_full_trainer=True TO SAVE FULL TRAINER
                    ModelCheckPoint(checkpoint_dir=save_to_dir,
                                    checkpoint_file_name=trainer_file_name,
                                    callback_monitor=CallbackMonitor(monitor_type=MonitorType.LOSS,
                                                                     stats_type=StatsType.VAL,
                                                                     monitor_mode=MonitorMode.MIN),
                                    save_best_only=True,
                                    save_full_trainer=True),
                    SchedulerStep(),
                    # SINCE ACCURACY NEEDS TO GO UP AND INACCURACY NEEDS TO GO DOWN, LETS DEFINE CallbackMonitors for StatsPrint PER EACH METRIC
                    StatsPrint(train_metrics_monitors=CallbackMonitor(monitor_type=MonitorType.METRIC,
                                                                       stats_type=StatsType.TRAIN,
                                                                       monitor_mode=MonitorMode.MAX,
                                                                       metric_name='Accuracy'))
                ]

    trainer = Trainer(model=model,
                      device=device,
                      loss_func=loss_func,
                      optimizer=optimizer,
                      scheduler=scheduler,
                      metrics=metrics,
                      train_data_loader=data_loader,
                      val_data_loader=data_loader,
                      train_steps=data_loader_steps,
                      val_steps=data_loader_steps,
                      callbacks=callbacks,
                      name='Train-Save-Load-Predict-Example')
    return trainer

def run():
    N, D_in, H, D_out, num_epochs, data_loader, data_loader_steps = get_parameters()

    current_trainer = get_trainer(N, D_in, H, D_out, num_epochs, data_loader, data_loader_steps)

    # TRAINING WILL SAVE current_trainer IN ModelCheckPoint
    current_trainer.train(num_epochs)

    # YOU CAN ALSO SAVE THIS TRAINER MANUALLY, LIKE THE CODE BELOW
    current_trainer.save_trainer(save_to_dir, trainer_file_name + '_manual_save')

    # NOW LETS CREATE A PREDICTOR FROM THE SAVED FILE
    device = tu.get_gpu_device_if_available()
    model = eu.get_basic_model(D_in, H, D_out).to(device)
    predictor = Predictor(model=model, device=device)

    data_generator_for_predictions = eu.examples_prediction_data_generator(data_loader, data_loader_steps)

    #PREDICT ON A SINGLE SAMPLE
    sample = next(data_generator_for_predictions)[0]
    sample_prediction = predictor.predict_sample(sample)

    # PREDICT ON A SINGLE BATCH
    batch = next(data_generator_for_predictions)
    batch_prediction = predictor.predict_batch(batch)

    # PREDICTION ON A DATA LOADER
    data_loader_predictions = predictor.predict_data_loader(data_generator_for_predictions, data_loader_steps)


from tests.test import test, checkIfSorted

def userInput():
		print('Choose a sorting algoritm/s: ')
		print('1.quickSort 2.mergeSort 3.bubbleSort ')
		print('4.insertSort 5.selectSortMin 6.selectSortMax ')
		algorithm = input('ALL for all ')
		print('Which test would you like to run? ')
		case = input('1.tiny 2.small 3.medium 4.big a.all ')
		repeat = int(input('How many repeats? '))

		if algorithm == 'all' or algorithm == 'ALL':
			algorithm = ['1', '2', '3', '4', '5', '6']
		else:
			algorithm = [size for size in algorithm if size.isdigit()]

		if case == 'all' or case == 'ALL' or case == 'a':
			case = ['1', '2', '3', '4']
		else:
			case = [size for size in case if size.isdigit()]
		return {'alg': algorithm, 'size': case, 'times': repeat }

# main I/O function for running specific tests
def main():
	run = True
	while run:
		print('\nSorting algoritm tester')
		choice = userInput()

		# run test function with chosen allgorithms
		# takes list size, times of repeat and choosen algorithms and *args
		test(choice['size'], choice['times'], choice['alg'])

		cont = input('Would you like to take another test? y/n ')
		while cont != 'y' and cont != 'n':
			cont = input('Wrong input, run? y/n ')
		if cont == 'n': break

if __name__ == '__main__':

	main()


#!/usr/bin/python3
""" Script that takes in a letter and sends
    a POST request to url with the letter as
    a parameter. """
import requests
from sys import argv

if __name__ == "__main__":
    if len(argv) == 2:
        q = argv[1]
    else:
        q = ''
    url = 'http://0.0.0.0:5000/search_user'
    req = requests.post(url, data={'q': q})
    try:
        data = req.json()
        if not data:
            print('No result')
        else:
            print('[{}] {}'.format(data.get('id'), data.get('name')))
    except Exception:
        print('Not a valid JSON')


import streamlit as st
import pandas as pd
from sklearn.metrics.pairwise import cosine_similarity
import numpy as np

st.title('Books recommender')
html_temp = """

Books recommender

"""
st.markdown(html_temp,unsafe_allow_html= True)
books1 = pd.read_csv("https://raw.githubusercontent.com/asaikiran1999/books-recommender/main/data/books1.csv")
books2 = pd.read_csv("https://raw.githubusercontent.com/asaikiran1999/books-recommender/main/data/books2.csv")
books3 = pd.read_csv("https://raw.githubusercontent.com/asaikiran1999/books-recommender/main/data/books3.csv")
books4 = pd.read_csv("https://raw.githubusercontent.com/asaikiran1999/books-recommender/main/data/books4.csv")
books1= books1.append(books2)
books1= books1.append(books3)
books1= books1.append(books4)
books = books1.copy()
page = st.selectbox("Choose your page", ["Top 50 book recommendation", "selected book recommender"])
def paginator(label, items, items_per_page=10, on_sidebar=True):
	"""Lets the user paginate a set of items.
	Parameters
	----------
	label : str
	    The label to display over the pagination widget.
	items : Iterator[Any]
	    The items to display in the paginator.
	items_per_page: int
	    The number of items to display per page.
	on_sidebar: bool
	    Whether to display the paginator widget on the sidebar.

	Returns
	-------
	Iterator[Tuple[int, Any]]
	    An iterator over *only the items on that page*, including
	    the item's index.
	Example
	-------
	This shows how to display a few pages of fruit.
	>>> fruit_list = [
	...     'Kiwifruit', 'Honeydew', 'Cherry', 'Honeyberry', 'Pear',
	...     'Apple', 'Nectarine', 'Soursop', 'Pineapple', 'Satsuma',
	...     'Fig', 'Huckleberry', 'Coconut', 'Plantain', 'Jujube',
	...     'Guava', 'Clementine', 'Grape', 'Tayberry', 'Salak',
	...     'Raspberry', 'Loquat', 'Nance', 'Peach', 'Akee'
	... ]
	...
	... for i, fruit in paginator("Select a fruit page", fruit_list):
	...     st.write('%s. **%s**' % (i, fruit))
	"""

	# Figure out where to display the paginator
	if on_sidebar:
	    location = st.sidebar.empty()
	else:
	    location = st.empty()

	# Display a pagination selectbox in the specified location.
	items = list(items)
	n_pages = len(items)
	n_pages = (len(items) - 1) // items_per_page + 1
	page_format_func = lambda i: "Page %s" % i
	page_number = location.selectbox(label, range(n_pages), format_func=page_format_func)

	# Iterate over the items in the page to let the user display them.
	min_index = page_number * items_per_page
	max_index = min_index + items_per_page
	import itertools
	return itertools.islice(enumerate(items), min_index, max_index)

if page == "Top 50 book recommendation":
	items2 = []
	items3 = []
	x =  pd.read_csv("https://raw.githubusercontent.com/asaikiran1999/books-recommender/main/data/top50book.csv")
	for i in range(50):
		items2.append(x['Image-URL-M'][i])
		items3.append(x['Book-Title'][i])
	i=0

	image_iterator = paginator("Select next page", items2)
	indices_on_page, images_on_page = map(list, zip(*image_iterator))
	st.image(images_on_page, width=200)

elif page == "selected book recommender":
	users= pd.read_csv("https://raw.githubusercontent.com/asaikiran1999/books-recommender/main/data/Users.csv")
	ratings = pd.read_csv("https://raw.githubusercontent.com/asaikiran1999/books-recommender/main/data/Ratings.csv")
	ratings_and_books = ratings.merge(books,on='ISBN')
	x=ratings_and_books.groupby('User-ID').count()['Book-Rating']>200
	best_users=x[x].index
	filtered_ratings =ratings_and_books[ratings_and_books['User-ID'].isin(best_users)]
	y=filtered_ratings.groupby('Book-Title').count()['Book-Rating']>=50
	famous_books=y[y].index
	filtered_famous = filtered_ratings[filtered_ratings['Book-Title'].isin(famous_books)]
	pivot = filtered_famous.pivot_table(index ='Book-Title',columns='User-ID',values='Book-Rating')
	pivot.fillna(0,inplace=True)
	similarity_scores = cosine_similarity(pivot)

	def recommend(book_name):
	  index = np.where(pivot.index == book_name)[0][0]
	  similar_items =sorted(list(enumerate(similarity_scores[index])),key=lambda x:x[1],reverse=True)[1:6]
	  items=[]
	  for i in similar_items:
	    #print(pivot.index[i[0]])
	    temp_df = books[books['Book-Title']==pivot.index[i[0]]]
	    items.append(list(temp_df.drop_duplicates('Book-Title')['Image-URL-M']))
	  return items
	input = st.text_input("Book_Name","")
	st.text('most search books are :')
	st.text("Harry Potter and the Sorcerer's Stone (Book 1)")
	st.text('The Da Vinci Code')
	st.text('The Secret Life of Bees')
	st.text('Girl with a Pearl Earring')
	st.text('About a Boy')

	if st.button('recommend'):
		r=[]
		y=list(recommend(input))
		for i in range(5):
			r.append(y[i][0])
		image_iterators = paginator("Select next page", r)
		indices_on_pages, images_on_pages = map(list, zip(*image_iterators))
		st.image(images_on_pages, width=200)


# @author Yu Tongxin
# @data 2020-08-28
import re
import xlwt
import os

def read_log():
    value = []
    value.append(["date", "type", "info"])
    with open("Apache_log/Apache_2k.log", "r") as log:
        for line in log:
            value.append(extract_data(line))
    book_name_xls = 'Apache_log.xls'
    sheet_name_xls = 'apache_log'
    if os.path.exists(book_name_xls):
        os.remove(book_name_xls)

    write_excel_xls(book_name_xls, sheet_name_xls, value)

def extract_data(line):
    list = []
    matchObj = re.match(r'(\[.*\]) (\[.*\]) (.*)', line, re.M | re.I)
    if matchObj:
        date = matchObj.group(1).strip().replace("[", "").replace("]", "")
        type = matchObj.group(2).strip().replace("[", "").replace("]", "")
        info = matchObj.group(3)
        list.append(date)
        list.append(type)
        list.append(info)
        return list
    else:
        print("No match!!")

def write_excel_xls(path, sheet_name, value):
    index = len(value)  # 获取需要写入数据的行数
    workbook = xlwt.Workbook()  # 新建一个工作簿
    sheet = workbook.add_sheet(sheet_name)  # 在工作簿中新建一个表格
    for i in range(0, index):
        for j in range(0, len(value[i])):
            sheet.write(i, j, value[i][j])  # 像表格中写入数据（对应的行和列）
    workbook.save(path)  # 保存工作簿
    print("xls格式表格写入数据成功！")

read_log()


import graphviz
from collections import deque
from Regex import RegexToPostfix

class State:
    def __init__(self, label=None, arrow=None):
        self.label = label
        self.arrow = arrow if arrow else []

class NFA:
    def __init__(self, start, accept):
        self.start = start
        self.accept = accept

class PostfixToNFA:
    def __init__(self, postfix):
        self.postfix = postfix
        self.states_count = 0

    def new_state(self, label=None, arrow=None):
        self.states_count += 1
        return State("q{}".format(self.states_count), arrow)

    def thompsons_algorithm(self):
        stack = deque()

        for char in self.postfix:
            if char.isalnum() or char == 'ε' or char == '_':
                s1 = self.new_state()
                s2 = self.new_state()
                s1.arrow.append((char, s2))
                nfa = NFA(s1, s2)
                stack.append(nfa)
            elif char == '|':
                nfa2 = stack.pop()
                nfa1 = stack.pop()
                s1 = self.new_state(
                    arrow=[('ε', nfa1.start), ('ε', nfa2.start)])
                s2 = self.new_state()
                nfa1.accept.arrow.append(('ε', s2))
                nfa2.accept.arrow.append(('ε', s2))
                nfa = NFA(s1, s2)
                stack.append(nfa)
            elif char == '$':
                nfa2 = stack.pop()
                nfa1 = stack.pop()
                nfa1.accept.arrow.append(('ε', nfa2.start))
                nfa = NFA(nfa1.start, nfa2.accept)
                stack.append(nfa)
            elif char == '*':
                nfa1 = stack.pop()
                s1 = self.new_state(arrow=[('ε', nfa1.start)])
                s2 = self.new_state()
                nfa1.accept.arrow.append(('ε', s2))
                s1.arrow.append(('ε', s2))
                nfa = NFA(s1, nfa1.accept)
                stack.append(nfa)
            elif char == '?':
                nfa1 = stack.pop()
                s1 = self.new_state(arrow=[('ε', nfa1.start)])
                s2 = self.new_state()
                nfa1.accept.arrow.append(('ε', s2))
                s1.arrow.append(('ε', s2))
                nfa = NFA(s1, s2)
                stack.append(nfa)

        return stack.pop()

    def draw_nfa(self, nfa):
        graph = graphviz.Digraph(format='png', engine='dot')
        graph.graph_attr['rankdir'] = 'LR'
        graph.graph_attr['splines'] = 'polyline'

        visited = set()

        def visit(state):
            if state in visited:
                return
            visited.add(state)

            for label, next_state in state.arrow:
                graph.edge(state.label, next_state.label, label=label)
                visit(next_state)

        visit(nfa.start)
        graph.node(nfa.accept.label, shape='doublecircle')
        graph.render('./images/nfa', view=True)

    def print_states(self, nfa):
        print("Initial State:", nfa.start.label)
        print("Acceptance State:", nfa.accept.label)

        def visit(state, visited=None):
            if visited is None:
                visited = set()
            if state in visited:
                return
            visited.add(state)

            for label, next_state in state.arrow:
                visit(next_state, visited)

            return visited

        all_states = visit(nfa.start)
        non_accept_states = all_states - {nfa.start, nfa.accept}
        print("Non-Acceptance States:",
              ', '.join(s.label for s in non_accept_states))

    def get_all_states(self, nfa):
        visited = set()

        def visit(state):
            if state in visited:
                return
            visited.add(state)

            for label, next_state in state.arrow:
                visit(next_state)

            return visited

        return visit(nfa.start)

    def print_transition_table(self, nfa):
        all_states = self.get_all_states(nfa)
        symbols = {
            transition[0] for state in all_states for transition in state.arrow if transition[0] != 'ε'}

        print("NFA Transition Table:")
        print("State", end="\t")
        for symbol in sorted(symbols):
            print(symbol, end="\t")
        print("ε")

        for state in sorted(all_states, key=lambda s: int(s.label[1:])):
            print(state.label, end="\t")
            for symbol in sorted(symbols):
                next_states = [
                    arrow[1].label for arrow in state.arrow if arrow[0] == symbol]
                print(",".join(next_states) if next_states else "-", end="\t")
            epsilon_transitions = [
                arrow[1].label for arrow in state.arrow if arrow[0] == 'ε']
            print(",".join(epsilon_transitions)
                  if epsilon_transitions else "-")

    def nfa_to_dict(self, nfa):
        all_states = self.get_all_states(nfa)
        nfa_dict = {}

        for state in all_states:
            transitions = {}
            for symbol, next_state in state.arrow:
                if symbol not in transitions:
                    transitions[symbol] = []
                transitions[symbol].append(next_state.label)
            nfa_dict[state.label] = transitions

        return nfa_dict

    def get_start_state(self, nfa):
        return nfa.start.label

    def get_final_state(self, nfa):
        return nfa.accept.label

    def get_accept_states(self, nfa):
        return [nfa.accept.label]

if __name__ == "__main__":
    regex = "(a*|b*)$c"
    cadena = 'aabc'
    r2p = RegexToPostfix(regex)
    postfix = r2p.to_postfix()
    print("Postfix expression:", postfix)
    p2n = PostfixToNFA(postfix)
    nfa = p2n.thompsons_algorithm()
    p2n.print_states(nfa)
    p2n.print_transition_table(nfa)
    p2n.draw_nfa(nfa)
    print("NFA Dictionary:")
    print(p2n.nfa_to_dict(nfa))
    print("Start State:", p2n.get_start_state(nfa))
    print("Final State:", p2n.get_final_state(nfa))
    print("Accept States:", p2n.get_accept_states(nfa))


import os
import torch
import numpy as np
from torch.autograd import Variable
import torch.nn as nn
from torch.nn import init

def build_embed(path):
    embed = {}
    eword = []
    with open(path, 'r') as f:
        for line in f:
            token = line.split()
            word = token[0]
            eword.append(word)
            value = np.asarray(token[1:], dtype='float32')
            embed[word] = value
        f.close()
    print('Found %s word vectors.' % len(embed))
    return embed, eword

def build_corpus(path):
    word2idx = {}
    idx2word = []
    trainlbl = []
    testlbl = []

    assert os.path.exists(path)

    train = os.path.join(path, 'train.txt')
    test = os.path.join(path, 'test.txt')

    with open(train, 'r') as f:
        for line in f:
            sents = line.split('\t')
            trainlbl.append(sents[0])
            words = sents[2].split()
            for word in words:
                if word not in word2idx:
                    idx2word.append(word)
                    word2idx[word] = len(idx2word) - 1
            words = sents[6].split()
            for word in words:
                if word not in word2idx:
                    idx2word.append(word)
                    word2idx[word] = len(idx2word) - 1

    with open(test, 'r') as f:
        for line in f:
            sents = line.split('\t')
            testlbl.append(sents[0])
            words = sents[2].split()
            for word in words:
                if word not in word2idx:
                    idx2word.append(word)
                    word2idx[word] = len(idx2word) - 1
            words = sents[6].split()
            for word in words:
                if word not in word2idx:
                    idx2word.append(word)
                    word2idx[word] = len(idx2word) - 1

    return word2idx, idx2word, trainlbl, testlbl

def build_vector(embed, dim, vocab, line):
    sents = line.split('\t')
    lsent = sents[2].split()
    rsent = sents[6].split()

    lsentm = Variable(torch.FloatTensor(torch.zeros(len(lsent), dim)))
    rsentm = Variable(torch.FloatTensor(torch.zeros(len(rsent), dim)))

    for i in range(len(lsent)):
        if lsent[i] in vocab:
            #print embed[lsent[i]]
            lsentm[i] = torch.from_numpy(embed[lsent[i]]).view(1, dim)
        else:
            w = torch.Tensor(1, dim)
            w = nn.init.normal(w, 0, 0.1)
            lsentm[i] = w

    for i in range(len(rsent)):
        if rsent[i] in vocab:
            #print embed[rsent[i]]
            rsentm[i] = torch.from_numpy(embed[rsent[i]]).view(1, dim)
        else:
            w = torch.Tensor(1, dim)
            w = nn.init.normal(w, 0, 0.1)
            rsentm[i] = w

    return lsentm, rsentm

# path = "/home/hjp/Downloads/msc/"
# word2idx, idx2word, trainlbl, testlbl = build_corpus(path)
# print word2idx
# print idx2word
# print len(word2idx)
# print len(idx2word)
# print trainlbl
# print len(trainlbl)
# print len(testlbl)
#def word2emb(word, emb):

#
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#
# class Dictionary(object):
#     def __init__(self):
#         self.word2idx = {}
#         self.idx2word = []
#
#     def add_word(self, word):
#         if word not in self.word2idx:
#             self.idx2word.append(word)
#             self.word2idx[word] = len(self.idx2word) - 1
#         return self.word2idx[word]
#
#     def __len__(self):
#         return len(self.idx2word)
#
#
#
# def vocab(x):
#     x.sum()
#
# with open('/home/hjp/Downloads/msc/glove.6B.50d.txt') as f:
#     for line in f:
#         print line
#
# def readMSC():
#     return


import numpy as np
import matplotlib.pyplot as plt
from matplotlib import image as mpimg
from matplotlib import pyplot as plt
from unit_tests import TEST_IMG_DIR
from copy import deepcopy
import os
from carnd_vehicle_detection import DEFAULT_EXTRACT_PARAMS
from carnd_vehicle_detection.preprocess import single_img_features, extract_prediction_features, extract_global_hog_features, convert_color
from carnd_vehicle_detection.visualize import one_by_two_plot
from carnd_vehicle_detection.traverse_image import get_global_hog_features, get_image_hog_features, \
    get_hog_extraction_coordinates
import pickle
from carnd_vehicle_detection import ROOT_DIR
import os
import cv2

def _discard_alpha_channel(img):
    return img[:, :, :3]

FULL_IMAGE = _discard_alpha_channel(mpimg.imread(os.path.join(TEST_IMG_DIR, 'test_frame_1.png')))
SUBIMAGE_SKY_64_64 = _discard_alpha_channel(mpimg.imread(os.path.join(TEST_IMG_DIR, 'test_subframe_1_1.png')))
SUBIMAGE_ROAD_64_64 = _discard_alpha_channel(mpimg.imread(os.path.join(TEST_IMG_DIR, 'test_subframe_1_3.png')))
SUBIMAGE_ROAD_2_64_64 = _discard_alpha_channel(mpimg.imread(os.path.join(TEST_IMG_DIR, 'test_subframe_1_4.png')))
SUBIMAGE_ROAD_SCALED = _discard_alpha_channel(mpimg.imread(os.path.join(TEST_IMG_DIR, 'test_subframe_1_5.png')))
SUBIMAGE_ROAD_SCALED_2 = _discard_alpha_channel(mpimg.imread(os.path.join(TEST_IMG_DIR, 'test_subframe_1_6.png')))
SCALER_PATH = os.path.join(ROOT_DIR, 'classifier_scaler.p')
with open(SCALER_PATH, 'rb') as scalerfile:
    SCALER = pickle.load(scalerfile)

def visualize_feature_vectors():
    """Visualize the feature vectors chosen from a couple of subimages from a frame. The selections have been picked
    manually."""

    # Extract and scale the params for non-scaled windows
    features_sky = SCALER.transform(np.ravel(single_img_features(SUBIMAGE_SKY_64_64, **DEFAULT_EXTRACT_PARAMS)))
    features_road = SCALER.transform(np.ravel(single_img_features(SUBIMAGE_ROAD_64_64, **DEFAULT_EXTRACT_PARAMS)))
    features_road_2 = SCALER.transform(np.ravel(single_img_features(SUBIMAGE_ROAD_2_64_64, **DEFAULT_EXTRACT_PARAMS)))

    # Extract and scale params for 1.5 scaled windows
    extract_params = deepcopy(DEFAULT_EXTRACT_PARAMS)
    extract_params['pix_per_cell'] = 12
    features_road_scaled = SCALER.transform(np.ravel(single_img_features(SUBIMAGE_ROAD_SCALED, **extract_params)))
    features_road_scaled_2 = SCALER.transform(np.ravel(single_img_features(SUBIMAGE_ROAD_SCALED_2, **extract_params)))

    plt.imshow(FULL_IMAGE)
    plt.show()
    one_by_two_plot(SUBIMAGE_SKY_64_64, SUBIMAGE_ROAD_64_64, None, None, "sky", "Road")

    f, (ax1, ax2) = plt.subplots(1, 2, figsize=(20, 10))
    ax1.set_title("Non-vehicle, scaled features")
    ax1.plot(list(range(len(features_sky))), features_sky)
    ax2.set_title("Vehicle, scaled features")
    ax2.plot(list(range(len(features_road))), features_road)
    plt.show()

    window_params = {'window': 64, 'ystart': 0, 'ystop': None}

    img_tosearch = FULL_IMAGE[window_params['ystart']:window_params['ystop'], :, :]
    ctrans_tosearch = convert_color(img_tosearch, conv=extract_params['color_space'])

    wins_per_scale = {1: [((128, 400), (192, 464)), ((248, 400), (312, 464))], 1.5: [((120, 396), (216, 492)), ((144, 420), (240, 516))]}
    ref_feat_per_scale = {1: [features_road, features_road_2], 1.5: [features_road_scaled, features_road_scaled_2]}
    for scale in (1, 1.5):
        windows = wins_per_scale[scale]

        for window in windows:
            xpos, ypos = window[0]
            window_params['ypos'] = ypos
            window_params['xpos'] = xpos
            xleft, ytop = xpos * extract_params['pix_per_cell'], ypos * extract_params['pix_per_cell']
            window_params['xleft'] = xleft
            window_params['ytop'] = ytop
            window_params['scale'] = scale
            nblocks_per_window = (window_params['window'] // extract_params['pix_per_cell']) - extract_params['cell_per_block'] + 1
            window_params['nblocks_per_window'] = nblocks_per_window

            ch0 = ctrans_tosearch[:, :, 0]
            ch1 = ctrans_tosearch[:, :, 1]
            ch2 = ctrans_tosearch[:, :, 2]

            # Let us put the channels into a dict for easier dynamic lookup
            channels_dict = {0: ch0, 1: ch1, 2: ch2}
            global_hog_features = extract_global_hog_features(channels_dict, extract_params['orient'],
                                                              extract_params['pix_per_cell'],
                                                              extract_params['cell_per_block'],
                                                              extract_params['hog_channel'])
        params = {'global_hog_features': global_hog_features,
                  'window_params': window_params,
                  'extract_params': extract_params}

        scaled_features = extract_prediction_features(ctrans_tosearch, SCALER, **params)

        f2, (ax21, ax22) = plt.subplots(1, 2, figsize=(20, 10))
        ax21.set_title("Single-pass HOG extraction results")
        ax21.plot(list(range(len(scaled_features))), scaled_features)
        ax22.set_title("Per-image HOG extraction results")
        ax22.plot(list(range(len(ref_feat_per_scale[scale][0]))), ref_feat_per_scale[scale][0])
        f2.suptitle("First window for scale {}".format(scale))
        plt.show()

        # plt.plot(list(range(81)), features_vehicle[120:201] - subfeatures_vehicle[120:201])
        plt.plot(list(range(len(scaled_features))), ref_feat_per_scale[scale][0] - scaled_features)
        plt.show()

    # f3, (ax31, ax32) = plt.subplots(1, 2, figsize=(20, 10))
    # ax31.set_title("Final image, Single-pass HOG extraction results")
    # ax31.plot(list(range(len(features_road_2))), features_road_2)
    # ax32.set_title("Final image, Per-image 64x64 features")
    # ax32.plot(list(range(len(subfeatures_from_64_64))), subfeatures_from_64_64)
    # plt.show()

    # plt.plot(list(range(len(features_road_2))), subfeatures_from_64_64 - subfeatures_vehicle_2)
    # plt.plot(list(range(81)), ref_feat_per_scale[scale][1][120:201] - subfeatures_vehicle_2[120:201])
    # plt.show()

if __name__ == "__main__":
    visualize_feature_vectors()


import pytest

from rss_parser.news_parser.news_parser import (NotRssFeedUrlError,
                                                rss_feed_type_checker,
                                                validate_url_is_rss_feed, parse_rss_feed_regularly)

@pytest.mark.parametrize('expected_exception, url', [(NotRssFeedUrlError, 'http://www.google.com')])
def test_validate_url_is_rss_feed(expected_exception, url):
    with pytest.raises(expected_exception):
        validate_url_is_rss_feed(url)

@pytest.mark.parametrize('url, expected_result', [('https://lifehacker.com/rss', True),
                                                  ('https://news.yahoo.com/rss', False),
                                                  ('https://rss.dw.com/xml/rss-ru-ger', False)])
def test_rss_feed_type_checker(url, expected_result):
    assert rss_feed_type_checker(url) == expected_result


import pytest
import pandas as pd
import numpy as np
from shapely import wkt

from tenzing.core.model_implementations import *

_test_suite = [
    pd.Series([1, 2, 3], name='int_series'),
    pd.Series([1, 2, 3], name='categorical_int_series', dtype='category'),
    pd.Series([1, 2, np.nan], name='int_nan_series'),

    pd.Series([1.0, 2.1, 3.0], name='float_series'),
    pd.Series([1.0, 2.5, np.nan], name='float_nan_series'),
    pd.Series([1.0, 2.0, 3.1], dtype='category', name='categorical_float_series'),

    pd.Series(['hello', 'world'], name='string_series'),
    pd.Series(['hello', 'world'], dtype='category', name='categorical_string_series'),
    pd.Series(['2017-10-01', '12/05/2017'], name='timestamp_string_series'),

    pd.Series([True, False], name='bool_series'),

    pd.Series([np.complex(0, 0), np.complex(1, 2), np.complex(3, -1), np.nan], name='complex_series'),
    pd.Series([np.complex(0, 0), np.complex(1, 2), np.complex(3, -1), np.nan], name='categorical_complex_series',
              dtype='category'),

    pd.Series([pd.datetime(2017, 3, 5), pd.datetime(2019, 12, 4)], name='timestamp_series'),

    pd.Series(['POINT (-92 42)', 'POINT (-92 42.1)', 'POINT (-92 42.2)'], name='geometry_string_series'),
    pd.Series([wkt.loads('POINT (-92 42)'), wkt.loads('POINT (-92 42.1)'),
               wkt.loads('POINT (-92 42.2)')], name='geometry_series'),
]

def make_pytest_parameterization(true_series):
    def mark_pytest_param(item):
        mark = pytest.mark.basic() if (item.name in true_series) else pytest.mark.xfail()
        return pytest.param(item, marks=mark, id=item.name)
    test_marks = [mark_pytest_param(item) for item in _test_suite]
    return pytest.mark.parametrize('series', test_marks)

@pytest.fixture(params=_test_suite, ids=lambda series: series.name)
def test_series(request):
    yield request.param

@make_pytest_parameterization(['int_series', 'int_nan_series'])
def test_int_contains(series):
    type = tenzing_integer
    assert series in type

@make_pytest_parameterization(['float_series', 'float_nan_series'])
def test_float_contains(series):
    type = tenzing_float
    assert series in type

@make_pytest_parameterization(['categorical_int_series', 'categorical_float_series', 'categorical_string_series',
                               'categorical_complex_series'])
def test_categorical_contains(series):
    type = tenzing_categorical
    assert series in type

@make_pytest_parameterization(['bool_series'])
def test_bool_contains(series):
    type = tenzing_bool
    assert series in type

@make_pytest_parameterization(['complex_series'])
def test_complex_contains(series):
    type = tenzing_complex
    assert series in type

@make_pytest_parameterization(['timestamp_series'])
def test_timestamp_contains(series):
    type = tenzing_timestamp
    assert series in type

@make_pytest_parameterization(['timestamp_string_series', 'string_series', 'geometry_string_series'])
def test_string_contains(series):
    type = tenzing_string
    assert series in type

@make_pytest_parameterization(['geometry_series'])
def test_geometry_contains(series):
    type = tenzing_geometry
    assert series in type