import sys
import os
import subprocess
from multiprocessing import Process
import csv
from collections import defaultdict
from pprint import pprint
import random
import time

class TestGenerator(object):

    def __init__(self, testclasses, test_suites):
        self.tool = ""
        self.testclasses = testclasses
        self.suffix = ""
        self.folder_suffix = ""
        self.test_suites = test_suites

    HEADERS_JACOCO_COVERAGE = [
        "INSTRUCTION_MISSED",
        "INSTRUCTION_COVERED",
        "BRANCH_MISSED",
        "BRANCH_COVERED",
        "LINE_MISSED",
        "LINE_COVERED",
        "COMPLEXITY_MISSED",
        "COMPLEXITY_COVERED",
        "METHOD_MISSED",
        "METHOD_COVERED",
    ]

    STATUS_MUTATIONS = [
        "KILLED",
        "SURVIVED",
        "NO_COVERAGE"
    ]

    def genFolders(self, path):
        exec_command = ""
        if sys.platform != 'win32':
            exec_command += "mkdir -p "
        else:
            exec_command = "cmd /c mkdir "
        subprocess.run(exec_command + path)

    def deleteFolder(self, path):
        exec_command = ""
        if sys.platform != 'win32':
            exec_command += "rm -rf "
        else:
            exec_command = "cmd /c rmdir /S /Q "
        print(exec_command + path)
        subprocess.run(exec_command + path)

    def deleteTestFolders(self):
        self.deleteFolder("tests")

    def deleteReportsFolders(self):
        self.deleteFolder("reports")

    def getResultsCsvCoverage(self, t, n):
        results = {}
        testSuiteName = self.generateTestSuiteName(t, n)
        csv_filename = os.path.join(
            self.getReportPath(), testSuiteName) + ".csv"
        with open(csv_filename, "r") as coverage_results:
            for row in csv.DictReader(coverage_results):
                for h in TestGenerator.HEADERS_JACOCO_COVERAGE:
                    results.setdefault(h, 0)
                    results[h] = int(row[h])
        return results

    def getResultsMutations(self, t, n):
        resultsMutation = {
            status: 0 for status in TestGenerator.STATUS_MUTATIONS
        }
        csv_filename = os.path.join(
            self.getMutationsReportPath(t, n), "mutations.csv")
        with open(csv_filename, "r") as mutation_results:
            reader = csv.reader(mutation_results)
            for row in reader:
                for status in TestGenerator.STATUS_MUTATIONS:
                    if status in row:
                        resultsMutation[status] += 1
        return resultsMutation

    def genTestCommand(self, t, testSuiteNumber):
        raise NotImplementedError

    def compileTestCommand(self, testclass):
        src = os.path.join(self.getSrcPath(), *self.getPackage(testclass))
        bin_ = self.getBinPath()
        classpath = os.pathsep.join(
            [".", os.path.join("jars", "*"), bin_, "bin"]
        )
        to_compile = os.path.join(src, "*.java")
        command = "javac -cp {classpath} {to_compile} -d {bin}".format(
            **{
                "classpath": classpath,
                "to_compile": to_compile,
                "bin": bin_
            }
        )
        print(command)
        return command

    def mutationTestCommand(self, testclass, testSuite):
        classpath_folders = [
            "bin", self.getBinPath(), os.path.join("jars", "*")]
        classpath = os.pathsep.join(classpath_folders)
        pit_classpath = ",".join(classpath_folders)
        src_dirs = ["src", self.getSrcPath()]
        pitest = "org.pitest.mutationtest.commandline.MutationCoverageReport"
        options = " ".join([
            "--reportDir {0}".format(
                self.getMutationsReportPath(testclass, testSuite)),
            "--targetClasses {0}".format(testclass),
            "--targetTests {0}".format(
                self.generateTestSuiteName(testclass, testSuite)),
            "--sourceDirs {dirs}".format(
                **{
                    "dirs": ",".join(src_dirs)
                }
            ),
            "--outputFormats CSV",
            "--timestampedReports=false"
        ])
        command = "java -cp {classpath}  {pitest} {options}".format(
            **{
                "classpath": classpath,
                "pitest": pitest,
                "options": options,
            }
        )
        print(command)
        return command

    def runTestCommands(self, testclass, testSuite=""):
        jars = os.path.join("jars", "*")
        testSuiteName = self.generateTestSuiteName(testclass, testSuite)
        classpath = os.pathsep.join([".", "bin", self.getBinPath(), jars])
        jacoco = "{jar}=destfile={report_out}.exec".format(
            **{
                "jar": os.path.join("jars", "jacocoagent.jar"),
                "report_out": os.path.join(self.getReportPath(), testSuiteName),
            }
        )
        command = "java -cp {classpath} -javaagent:{jacoco} org.junit.runner.JUnitCore {classname}".format(
            **{
                "classpath": classpath,
                "jacoco": jacoco,
                "classname": testSuiteName
            }
        )
        print(command)
        return command

    def genReportCommand(self, testclass, testSuite=""):
        testSuiteName = self.generateTestSuiteName(testclass, testSuite)
        report_file_name = os.path.join(
            self.getReportPath(), testSuiteName
        )
        exec_file = report_file_name + ".exec"
        csv_file = report_file_name + ".csv"

        jacococli = os.path.join("jars", "jacococli.jar")
        classfiles = os.path.join(
            "bin", testclass.replace(".", os.path.sep)) + ".class"
        command = "java -jar {jacococli} report {exec_file} --classfiles {classfiles} --csv {csv_file} --name {tool}".format(
            **{
                "jacococli": jacococli,
                "exec_file": exec_file,
                "classfiles": classfiles,
                "csv_file": csv_file,
                "tool": self.tool
            }
        )
        print(command)
        return command

    def executeCommands(self, commands):
        processes = [Process(target=subprocess.run, args=(c,))
                     for c in commands]
        processors = os.cpu_count()
        if processors is None:
            processors = 4
        if len(processes) <= processors:
            for p in processes:
                p.start()
            for p in processes:
                p.join()
        else:
            pieces = len(processes) // processors
            for x in range(pieces):
                for i in range(processors):
                    processes[x * processors + i].start()
                for i in range(processors):
                    processes[x * processors + i].join()

            remaining = len(processes) % processors
            if remaining > 0:
                for i in range(remaining):
                    processes[pieces * processors + i].start()
                for i in range(remaining):
                    processes[pieces * processors + i].join()

    def generateReportsFolders(self):
        self.genFolders(self.getBinPath())
        self.genFolders(self.getReportPath())
        for t in self.testclasses:
            for n in range(self.test_suites):
                self.genFolders(self.getMutationsReportPath(t, str(n)))

    def generateTestSuites(self):
        generate_tests_commands = [self.genTestCommand(t, n) for t in self.testclasses
                                   for n in range(self.test_suites)]
        self.executeCommands(generate_tests_commands)

    def run(self):
        self.generateReportsFolders()

        compile_commands = [self.compileTestCommand(t)
                            for t in self.testclasses]
        run_commands = [self.runTestCommands(t, n)
                        for t in self.testclasses
                        for n in range(self.test_suites)]
        gen_reports_commands = [self.genReportCommand(t, n)
                                for t in self.testclasses
                                for n in range(self.test_suites)]
        mutation_commands = [self.mutationTestCommand(t, str(n))
                             for t in self.testclasses
                             for n in range(self.test_suites)]

        self.executeCommands(compile_commands)
        self.executeCommands(mutation_commands)
        self.executeCommands(run_commands)
        self.executeCommands(gen_reports_commands)

        return self.generateResults()

    def generateResults(self):
        results = {t: defaultdict(float) for t in self.testclasses}
        for t in self.testclasses:
            for n in range(self.test_suites):
                coverage = self.getResultsCsvCoverage(t, str(n))
                mutations = self.getResultsMutations(t, str(n))

                line_coverage = self.getLineCoveragePercentage(coverage)
                branch_coverage = self.getBranchCoveragePercentage(coverage)
                mutation_score = self.getMutationScorePercentage(mutations)

                self.writeOutputToCsv({
                    "class": t,
                    "tool": self.tool,
                    "line_coverage_%": line_coverage,
                    "branch_coverage_%": branch_coverage,
                    "mutation_score_%": mutation_score
                })

                results[t]["LINE_COVERAGE"] += line_coverage
                results[t]["BRANCH_COVERAGE"] += branch_coverage
                results[t]["MUTATION_SCORE"] += mutation_score

        for t in self.testclasses:
            results[t]["LINE_COVERAGE"] /= float(self.test_suites)
            results[t]["BRANCH_COVERAGE"] /= float(self.test_suites)
            results[t]["MUTATION_SCORE"] /= float(self.test_suites)
        return results

    def writeOutputToCsv(self, results_run):
        with open('results.csv', 'a', newline='') as csvfile:
            header = ["class", "tool", "line_coverage_%",
                      "branch_coverage_%", "mutation_score_%"]
            writer = csv.DictWriter(csvfile, fieldnames=header)
            writer.writerow(results_run)

    def getLineCoveragePercentage(self, results):
        covered_lines = results['LINE_COVERED']
        total_lines = covered_lines + results['LINE_MISSED']
        return covered_lines / total_lines

    def getBranchCoveragePercentage(self, results):
        covered_branches = results['BRANCH_COVERED']
        total_branches = covered_branches + results['BRANCH_MISSED']
        return covered_branches / total_branches

    def getMutationScorePercentage(self, results):
        total_mutants = sum((results[s]
                             for s in TestGenerator.STATUS_MUTATIONS))
        return results["KILLED"] / total_mutants

    def getSrcPath(self):
        return os.path.join("tests", self.tool, "src", self.folder_suffix)

    def getBinPath(self):
        return os.path.join("tests", self.tool, "bin")

    def getPackage(self, testclass):
        return filter(lambda s: s[0] >= 'a', testclass.split("."))

    def getClassName(self, testclass):
        return testclass.split(".")[-1]

    def getReportPath(self):
        return os.path.join("reports", self.tool)

    def getMutationsReportPath(self, testclass, testSuite):
        return os.path.join(self.getReportPath(), "mutationReport", testclass, testSuite)

    def generateTestSuiteName(self, testclass, testSuiteNumber):
        return "".join([testclass, str(testSuiteNumber), self.suffix])

class RandoopTestGenerator(TestGenerator):

    def __init__(self, testclasses, test_suites):
        super(RandoopTestGenerator, self).__init__(testclasses, test_suites)
        self.tool = "Randoop"
        self.suffix = "_Test"
        self.genFolders(self.getSrcPath())

    def genTestCommand(self, testclass, testSuiteNumber):
        classpath = os.pathsep.join(
            [os.path.join("jars", "*"), "bin"]
        )
        random.seed(int(time.time() * 10))
        randoop = "randoop.main.Main gentests"
        options = " ".join([
            "--no-error-revealing-tests=true",
            "--timelimit=60",
            "--regression-test-basename={testclass}".format(
                **{
                    "testclass": self.generateTestSuiteName(self.getClassName(testclass), testSuiteNumber)
                }
            ),
            "--junit-package-name={package}".format(
                **{
                    "package": ".".join(self.getPackage(testclass))
                }
            ),
            "--classlist=classlist_randoop.txt",
            "--randomseed={0}".format(int(random.random() * 1000))
        ])
        command = "java -ea -classpath {classpath} {randoop} --testclass={testclass} {options} --junit-output-dir={output_dir}".format(
            **{
                "classpath": classpath,
                "randoop": randoop,
                "testclass": testclass,
                "options": options,
                "output_dir": os.path.join("tests", self.tool, "src")
            }
        )
        print(command)
        return command

class EvoTestGenerator(TestGenerator):

    def __init__(self, testclasses, test_suites):
        super(EvoTestGenerator, self).__init__(testclasses, test_suites)
        self.tool = "EvoSuite"
        self.suffix = "_ESTest"
        self.folder_suffix = "evosuite-tests"
        self.genFolders(self.getSrcPath())

    def genTestCommand(self, testclass, testSuiteNumber):
        jars = os.path.join("jars", "evosuite-master-1.0.5.jar")
        classpath = os.path.abspath("bin")
        options = " ".join([
            "-generateSuite",
            "-Dsearch_budget=60",
            "-Dstopping_condition=MaxTime",
            "-Duse_separate_classloader=false",
            "-Dsave_all_data=false",
            "-Djunit_suffix={0}{1}".format(testSuiteNumber, self.suffix)
        ])
        command = "java -ea -jar {jars} -projectCP {classpath} {options} -class {testclass} -base_dir {output_dir}".format(
            **{
                "jars": jars,
                "classpath": classpath,
                "options": options,
                "testclass": testclass,
                "output_dir": os.path.join("tests", self.tool, "src")
                # solo para este caso dejar asi!
            }
        )
        print(command)
        return command

testclasses = [
    "collections.comparators.FixedOrderComparator",
    "collections.iterators.FilterIterator",
    "collections.map.PredicatedMap",
    "math.genetics.ElitisticListPopulation",
]

def print_results_markdown(results):
    print("_____________________________________________________|Avg Line Coverage|Avg Branch Coverage|Avg Mutation Score")
    print("-------|-------|-------|-------")
    print()
    print("Class|Randoop|Evosuite|Randoop|Evosuite|Randoop|Evosuite")
    print("-------|-------|-------|-------|-------|-------|-------")
    for t in testclasses:
        print("{classname}|{r_line:.3f}|{e_line:.3f}|{r_branch:.3f}|{e_branch:.3f}|{r_mutation:.3f}|{e_mutation:.3f}".format(
            **{
                "classname": t,
                "r_line": results['Randoop'][t]["LINE_COVERAGE"],
                "e_line": results['EvoSuite'][t]["LINE_COVERAGE"],
                "r_branch": results["Randoop"][t]["BRANCH_COVERAGE"],
                "e_branch": results["EvoSuite"][t]["BRANCH_COVERAGE"],
                "r_mutation": results["Randoop"][t]["MUTATION_SCORE"],
                "e_mutation": results["EvoSuite"][t]["MUTATION_SCORE"]
            }
        ))

if __name__ == '__main__':

    exec_command = ""
    if sys.platform != 'win32':
        exec_command += "rm "
    else:
        exec_command = "cmd /c del"
    subprocess.run(exec_command + " results.csv")

    test_suites = 30
    generate = False
    generators = [RandoopTestGenerator(testclasses, test_suites),
                  EvoTestGenerator(testclasses, test_suites)]

    # generate tests
    if generate:
        for g in generators:
            g.generateTestSuites()

    results = {}

    for g in generators:
        results[g.tool] = g.run()

    print_results_markdown(results)


from typing import Dict, List

from ...enable_configuation import enable_configuation
from ...struct.config_properties import ConfigProperties

class ReceiverItem:
    dingding_robot = None
    enterprise_wechat_robot = None
    enterprise_wechat_app = None

    def __init__(self, dingding_robot,
                 enterprise_wechat_robot,
                 enterprise_wechat_app):
        super().__init__()
        self.dingding_robot = dingding_robot
        self.enterprise_wechat_robot = enterprise_wechat_robot
        self.enterprise_wechat_app = enterprise_wechat_app

@enable_configuation(prefix="receiver")
class ReceiveProperties(ConfigProperties):
    _users: Dict[str, ReceiverItem] = {}
    _groups: Dict[str, List[str]] = {}

    def __init__(self, config=None):
        super().__init__(config=config)

    def load_config(self, config):
        for (key, value) in config.users.items():
            self._users[key] = ReceiverItem(
                value.get('dingding-robot', None),
                value.get('enterprise-wechat-robot', None),
                value.get('enterprise-wechat-app', None)
            )
        self._groups = config.groups

    def get_usernames_by_groupnames(self, group_names: List[str]):
        user_sets = set()
        for group_name in group_names:
            sub_user_in_group = self._groups.get(group_name, [])
            for user_name in sub_user_in_group:
                user_sets.add(user_name)
        return user_sets

    def get_usernames_by_groupname(self, group_name: str):
        return self.get_usernames_by_groupnames([group_name])

    def get_user_configs_by_usernames(self, usernames):
        result: List[ReceiverItem] = []
        for user_name in usernames:
            user = self._users.get(user_name, None)
            if user is None:
                continue
            result.append(user)
        return result

    def get_user_configs_by_username(self, username):
        return self.get_user_configs_by_usernames([username])


from tkinter import*
from tkinter import ttk
from PIL import Image, ImageTk
from tkinter import messagebox
import mysql.connector
import cv2
import os
import csv
from tkinter import filedialog
import numpy as np

mydata = []

class Student_attendence:
    def __init__(self, root):
        self.root = root
        self.root.geometry("1530x790+0+0")
        self.root.configure(bg="#e6fae1")
        self.root.title("Student Management System Student Attendence Details")

        # variable for filf the predefiened values

        self.var_attendence_id = StringVar()
        self.var_attendence_name = StringVar()
        self.var_attendence_roll = StringVar()
        self.var_attendence_dep = StringVar()
        self.var_attendence_time = StringVar()
        self.var_attendence_date = StringVar()
        self.var_attendence_status = StringVar()

        # First header image

        img1 = Image.open("images/mh1.jpg")
        img1 = img1.resize((510, 130), Image.ANTIALIAS)
        self.photoimg1 = ImageTk.PhotoImage(img1)

        f_lbl = Label(self.root, image=self.photoimg1)
        f_lbl.place(x=0, y=0, width=510, height=130)

        # Middle header image

        img2 = Image.open("images/mh2.jpg")
        img2 = img2.resize((520, 130), Image.ANTIALIAS)
        self.photoimg2 = ImageTk.PhotoImage(img2)

        f_lbl = Label(self.root, image=self.photoimg2)
        f_lbl.place(x=510, y=0, width=510, height=130)

        # Third header image

        img3 = Image.open("images/mh3.jpg")
        img3 = img3.resize((520, 130), Image.ANTIALIAS)
        self.photoimg3 = ImageTk.PhotoImage(img3)

        f_lbl = Label(self.root, image=self.photoimg3)
        f_lbl.place(x=1020, y=0, width=520, height=130)

    # <----------- image frame for background of remaining window except header window -------------->
        img4 = Image.open("images/bgmain4.jpg")
        img4 = img4.resize((1530, 710), Image.ANTIALIAS)
        self.photoimg4 = ImageTk.PhotoImage(img4)

        bg_img = Label(self.root, image=self.photoimg4)
        bg_img.place(x=0, y=130, width=1530, height=710)

        title_lbl = Label(bg_img, text="Save The Attendence In DataBases And Show In A Table On Attendence Window", font=(
            "'Fredoka One', sans-serif", 30, "bold"), bg="#b0c4de", fg="blue")
        title_lbl.place(x=0, y=0, width=1530, height=50)

        # Creating s sub frame inside the image frame
        main_frame = Frame(bg_img, bd=2)
        main_frame.place(x=0, y=52, width=1530, height=650)

        # inside the sub frame we create another frame

        # Left frame
        Left_frame = LabelFrame(
            main_frame, bd=2, relief=RIDGE, text="Student Attendence Details", font=(
                "'Fredoka One', sans-serif", 12, "bold"), fg="blue")
        Left_frame.place(x=0, y=0, width=750, height=600)

        # left frame top image
        img_left_top = Image.open("images/mh1.jpg")
        img_left_top = img_left_top.resize((740, 130), Image.ANTIALIAS)
        self.photoimg_left_top = ImageTk.PhotoImage(img_left_top)

        f_lbl = Label(Left_frame, image=self.photoimg_left_top)
        f_lbl.place(x=0, y=0, width=747, height=130)

        # Current Course frame

        # For the grid inside the Current course frame
        class_student_frame = LabelFrame(
            Left_frame, bd=2, relief=RIDGE, text="", font=(
                "'Fredoka One', sans-serif", 11, "bold"), fg="blue")
        class_student_frame.place(x=0, y=130, width=745, height=443)
        # for department

        # <=------------Attendence Id -------------->

        attendence_label = Label(class_student_frame, text="Attendence Id", font=(
            "'Fredoka One', sans-serif", 11, "bold"), fg="Green")
        attendence_label.grid(row=0, column=0, padx=10, pady=10, sticky=W)

        attendence_entry = ttk.Entry(class_student_frame, textvariable=self.var_attendence_id, width=20, font=(
            "'Fredoka One', sans-serif", 11, "bold"))
        attendence_entry.grid(row=0, column=1, padx=10, pady=10, sticky=W)

        # Name Field and Entry fields

        name_label = Label(class_student_frame, text="Name", font=(
            "'Fredoka One', sans-serif", 11, "bold"), fg="Green")
        name_label.grid(row=1, column=0, padx=10, pady=10, sticky=W)

        name_entry = ttk.Entry(class_student_frame, textvariable=self.var_attendence_name, width=20, font=(
            "'Fredoka One', sans-serif", 11, "bold"))
        name_entry.grid(row=1, column=1, padx=10, pady=10, sticky=W)
        # time Field and Entry fields

        time_label = Label(class_student_frame, text="Time", font=(
            "'Fredoka One', sans-serif", 11, "bold"), fg="Green")
        time_label.grid(row=2, column=0, padx=10, pady=10, sticky=W)

        time_entry = ttk.Entry(class_student_frame, textvariable=self.var_attendence_time, width=20, font=(
            "'Fredoka One', sans-serif", 11, "bold"))
        time_entry.grid(row=2, column=1, padx=10, pady=10, sticky=W)

        # <----------for Roll number fields -------------->

        roll_label = Label(class_student_frame, text="Roll", font=(
            "'Fredoka One', sans-serif", 11, "bold"), fg="Green")
        roll_label.grid(row=0, column=2, padx=10, pady=10, sticky=W)

        roll_entry = ttk.Entry(class_student_frame, textvariable=self.var_attendence_roll, width=20, font=(
            "'Fredoka One', sans-serif", 11, "bold"))
        roll_entry.grid(row=0, column=3, padx=10, pady=10, sticky=W)

        # Name Field and Entry fields

        dep_label = Label(class_student_frame, text="Department", font=(
            "'Fredoka One', sans-serif", 11, "bold"), fg="Green")
        dep_label.grid(row=1, column=2, padx=10, pady=10, sticky=W)

        dep_entry = ttk.Entry(class_student_frame, textvariable=self.var_attendence_dep, width=20, font=(
            "'Fredoka One', sans-serif", 11, "bold"))
        dep_entry.grid(row=1, column=3, padx=10, pady=10, sticky=W)
        # time Field and Entry fields

        date_label = Label(class_student_frame, text="Date", font=(
            "'Fredoka One', sans-serif", 11, "bold"), fg="Green")
        date_label.grid(row=2, column=2, padx=10, pady=10, sticky=W)

        date_entry = ttk.Entry(class_student_frame, textvariable=self.var_attendence_date, width=20, font=(
            "'Fredoka One', sans-serif", 11, "bold"))
        date_entry.grid(row=2, column=3, padx=10, pady=10, sticky=W)

        # for status of attendence

        status_label = Label(class_student_frame, text="Status", font=(
            "'Fredoka One', sans-serif", 11, "bold"), fg="Green")
        status_label.grid(row=3, column=0, padx=6, pady=10, sticky=W)

        # <----------- combobox field value  ----------------->
        status_combo = ttk.Combobox(class_student_frame, textvariable=self.var_attendence_status, font=(
            "'Fredoka One', sans-serif", 11, "bold"), state="readonly", width=18)
        status_combo["values"] = ("Status",
                                  "Present", "Abscent")
        status_combo.current(0)
        status_combo.grid(row=3, column=1, padx=6, pady=10, sticky=W)

        btn_frme = Frame(class_student_frame, bd=2, relief=RIDGE)
        btn_frme.place(x=0, y=396, width=740, height=40)

        # save button
        import_btn = Button(btn_frme, command=self.import_csv, text="Import", width=19, font=(
            "'Fredoka One', sans-serif", 11, "bold"), fg="Green")
        import_btn.grid(row=0, column=0)

        # Update button
        export_btn = Button(btn_frme, command=self.export_csv, text="Export", width=20, font=(
            "'Fredoka One', sans-serif", 11, "bold"), fg="Green")
        export_btn.grid(row=0, column=1)

        # delete buttn
        update_btn = Button(btn_frme,  text="Update", width=19, font=(
            "'Fredoka One', sans-serif", 11, "bold"), fg="Green")
        update_btn.grid(row=0, column=2)

        # Reset  button

        reset_btn = Button(btn_frme, command=self.reset_data, text="Reset", width=19, font=(
            "'Fredoka One', sans-serif", 11, "bold"), fg="Green")
        reset_btn.grid(row=0, column=3)

        # <-------------right frame---------------->
        Right_frame = LabelFrame(
            main_frame, bd=2, relief=RIDGE, text="Student Details", font=(
                "'Fredoka One', sans-serif", 12, "bold"), fg="blue")
        Right_frame.place(x=760, y=0, width=760, height=600)

        # left frame top image
        right_top = Image.open("images/mh1.jpg")
        right_top = right_top.resize((750, 130), Image.ANTIALIAS)
        self.photoimg_right_top = ImageTk.PhotoImage(right_top)

        f_lbl = Label(Right_frame, image=self.photoimg_right_top)
        f_lbl.place(x=0, y=0, width=756, height=130)

        # table frame
        table_frame = Frame(Right_frame, bd=2, relief=RIDGE)
        table_frame.place(x=0, y=130, width=752, height=444)

        # to set scroll bar
        scroll_x = ttk.Scrollbar(table_frame, orient=HORIZONTAL)
        scroll_y = ttk.Scrollbar(table_frame, orient=VERTICAL)

        self.attendence_table = ttk.Treeview(table_frame, column=(
            "id", "name", "roll", "department", "time", "date", "attendence"), xscrollcommand=scroll_x.set, yscrollcommand=scroll_y.set)
        scroll_x.pack(side=BOTTOM, fill=X)
        scroll_y.pack(side=RIGHT, fill=Y)

        scroll_x.config(command=self.attendence_table.xview)
        scroll_y.config(command=self.attendence_table.yview)

        self.attendence_table.heading("id", text="Attendence_Id")
        self.attendence_table.heading("name", text="Name")
        self.attendence_table.heading("roll", text="Roll")
        self.attendence_table.heading("department", text="Department")
        self.attendence_table.heading("time", text="Time")
        self.attendence_table.heading("date", text="Date")
        self.attendence_table.heading("attendence", text="Attendence_Status")

        self.attendence_table["show"] = "headings"

        self.attendence_table.column("id", width=120)
        self.attendence_table.column("name", width=120)
        self.attendence_table.column("roll", width=120)
        self.attendence_table.column("department", width=120)
        self.attendence_table.column("time", width=120)
        self.attendence_table.column("date", width=120)
        self.attendence_table.column("attendence", width=120)

        self.attendence_table.pack(fill=BOTH, expand=1)
        self.attendence_table.bind("<ButtonRelease>", self.get_cursor)

    def fetch_data(self, rows):
        self.attendence_table.delete(*self.attendence_table.get_children())
        for i in rows:
            self.attendence_table.insert("", END, values=i)

        # <------------------- for import csv ----------------->

    def import_csv(self):
        global mydata
        mydata.clear()
        fln = filedialog.askopenfilename(initialdir=os.getcwd(), title="Open CSV", filetypes=(
            ("CSV File"), ("All File", "*.*")), parent=self.root)
        with open(fln) as myfile:
            csvread = csv.reader(myfile, delimiter=",")
            for i in csvread:
                mydata.append(i)
            self.fetch_data(mydata)

            # <------------- for export csv data --------------->
    def export_csv(self):
        try:
            if len(mydata) < 1:
                messagebox.showerror(
                    "No data found to export", parent=self.root)
                return False
            fln = filedialog.asksaveasfilename(initialdir=os.getcwd(), title="Open CSV", filetypes=(
                ("CSV File"), ("All File", "*.*")), parent=self.root)
            with open(fln, mode="w", newline="")as myfile:
                exp_write = csv.writer(myfile, delimiter=",")
                for i in mydata:
                    exp_write.writerow(i)
                messagebox.showinfo(
                    "Data Export", "Data Exportedto "+os.path.basename(fln)+" Successfully")
        except Exception as es:
            messagebox.showerror(
                "Error", f"Due to:{str(es)}", parent=self.root)

    def get_cursor(self, event=""):
        cursor_row = self.attendence_table.focus()
        content = self.attendence_table.item(cursor_row)
        rows = content['values']
        self.var_attendence_id.set(rows[0])
        self.var_attendence_name.set(rows[1])
        self.var_attendence_roll.set(rows[2])
        self.var_attendence_dep.set(rows[3])
        self.var_attendence_time.set(rows[4])
        self.var_attendence_date.set(rows[5])
        self.var_attendence_status.set(rows[6])

    def reset_data(self):
        self.var_attendence_id.set("")
        self.var_attendence_name.set("")
        self.var_attendence_roll.set("")
        self.var_attendence_dep.set("")
        self.var_attendence_time.set("")
        self.var_attendence_date.set("")
        self.var_attendence_status.set("Status")

if __name__ == "__main__":
    root = Tk()
    obj = Student_attendence(root)
    root.mainloop()


import csv
from flask.cli import FlaskGroup

from project import create_app, db
from project.api.models import Person

app = create_app()
cli = FlaskGroup(create_app=create_app)

@cli.command('recreate_db')
def recreate_db():
    """ Method to recreate a database
    """
    db.drop_all()
    db.create_all()
    db.session.commit()

@cli.command('seed_db')
def seed_db():
    """Command line argument to seed db with titanic csv

    Method loops over a csv file skipping first row and inserting values into
    respective rows.
    O, 1 for survived variable is converted to a boolean type.
    """

    with open('titanic.csv', 'r') as f:
        reader = csv.reader(f)
        next(reader)  # Skip the header row.
        for row in reader:
            survived_bool = None
            if row[0] == '1':
                survived_bool = True

            elif row[0] == '2':
                survived_bool = False

            db.session.add(Person(
                                survived=survived_bool,
                                passengerClass=row[1],
                                name=row[2],
                                sex=row[3],
                                age=int(float(row[4])),
                                siblingsOrSpousesAboard=row[5],
                                parentsOrChildrenAboard=row[6],
                                fare=row[7]
                                ))

    db.session.commit()

if __name__ == '__main__':
    cli()


import numpy as np
from sklearn.linear_model import LinearRegression

y = np.array([3, 9, 20, 24, 30, 38])

x = [[1, 10, -19], [2, 15, -13], [3, 20, 0], [4, 25, 10], [5, 30, 14], [6, 35, 20]]
x = np.array(x)

model = LinearRegression().fit(x, y)

# Getting the slope of the regression line.
print('The estimates (b1-b2):', model.coef_)

# Getting the intercept value of the regression line.
print('The intercept (b0):', model.intercept_)

# Predicting the values of y based on the model.
y_Predicted = model.predict(x)
print('Predicted y values:', y_Predicted)

# Specifying a new set of x values to forecast y for.
x_New = [[7, 40, -21], [8, 45, -11], [9, 50, 2], [10, 55, 12], [11, 60, 13], [7, 34, 22]]
x_New = np.array(x_New)
y_Predicted_New = model.predict(x_New)
print('New predicted y values:', y_Predicted_New)


#!/usr/bin/python
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.

import hashlib
import logging
import os
from optparse import OptionParser

logger = logging.getLogger("checksums.py")

def digest_file(filename, digest, chunk_size=131072):
    """Produce a checksum for the file specified by 'filename'.  'filename'
    is a string path to a file that is opened and read in this function.  The
    checksum algorithm is specified by 'digest' and is a valid OpenSSL
    algorithm.  If the digest used is not valid or Python's hashlib doesn't
    work, the None object will be returned instead.  The size of blocks
    that this function will read from the file object it opens based on
    'filename' can be specified by 'chunk_size', which defaults to 1K"""
    assert not os.path.isdir(filename), "this function only works with files"

    logger.debug("Creating new %s object" % digest)
    h = hashlib.new(digest)
    with open(filename, "rb") as f:
        while True:
            data = f.read(chunk_size)
            if not data:
                logger.debug("Finished reading in file")
                break
            h.update(data)
    hash = h.hexdigest()
    logger.debug("Hash for %s is %s" % (filename, hash))
    return hash

def process_files(dirs, output_filename, digests):
    """This function takes a list of directory names, 'drs'. It will then
    compute the checksum for each of the files in these by by opening the files.
    Once each file is read and its checksum is computed, this function
    will write the information to the file specified by 'output_filename'.
    The path written in the output file will have anything specified by 'strip'
    removed from the path.  The output file is closed before returning nothing
    The algorithm to compute checksums with can be specified by 'digests'
    and needs to be a list of valid OpenSSL algorithms.

    The output file is written in the format:
        <hash> <algorithm> <filesize> <filepath>
    Example:
        d1fa09a<snip>e4220 sha1 14250744 firefox-4.0b6pre.en-US.mac64.dmg
    """

    if os.path.exists(output_filename):
        logger.debug('Overwriting existing checksums file "%s"' % output_filename)
    else:
        logger.debug('Creating a new checksums file "%s"' % output_filename)
    with open(output_filename, "w+") as output:
        for d in dirs:
            for root, dirs, files in os.walk(d):
                for f in files:
                    full = os.path.join(root, f)
                    rel = os.path.relpath(full, d)

                    for digest in digests:
                        hash = digest_file(full, digest)

                        output.write(
                            "%s %s %s %s\n" % (hash, digest, os.path.getsize(full), rel)
                        )

def setup_logging(level=logging.DEBUG):
    """This function sets up the logging module using a speficiable logging
    module logging level.  The default log level is DEBUG.

    The output is in the format:
        <level> - <message>
    Example:
        DEBUG - Finished reading in file"""

    logger = logging.getLogger("checksums.py")
    logger.setLevel(logging.DEBUG)
    handler = logging.StreamHandler()
    handler.setLevel(level)
    formatter = logging.Formatter("%(levelname)s - %(message)s")
    handler.setFormatter(formatter)
    logger.addHandler(handler)

def main():
    """This is a main function that parses arguments, sets up logging
    and generates a checksum file"""
    # Parse command line arguments
    parser = OptionParser()
    parser.add_option(
        "-d",
        "--digest",
        help="checksum algorithm to use",
        action="append",
        dest="digests",
    )
    parser.add_option(
        "-o",
        "--output",
        help="output file to use",
        action="store",
        dest="outfile",
        default="checksums",
    )
    parser.add_option(
        "-v",
        "--verbose",
        help="Be noisy (takes precedence over quiet)",
        action="store_true",
        dest="verbose",
        default=False,
    )
    parser.add_option(
        "-q",
        "--quiet",
        help="Be quiet",
        action="store_true",
        dest="quiet",
        default=False,
    )

    options, args = parser.parse_args()

    # Figure out which logging level to use
    if options.verbose:
        loglevel = logging.DEBUG
    elif options.quiet:
        loglevel = logging.ERROR
    else:
        loglevel = logging.INFO

    # Set up logging
    setup_logging(loglevel)

    # Validate the digest type to use
    if not options.digests:
        options.digests = ["sha1"]

    for i in args:
        if not os.path.isdir(i):
            logger.error("%s is not a directory" % i)
            exit(1)

    process_files(args, options.outfile, options.digests)

if __name__ == "__main__":
    main()


#!/usr/bin/env python
# coding: utf-8

# ---------------------------
# Import modules ------------
# ---------------------------
from splinter import Browser
from bs4 import BeautifulSoup
import pandas as pd
import time

# ---------------------------
# Initialize browser --------
# ---------------------------
def init_browser():
    # @NOTE: Replace the path with your actual path to the chromedriver
    executable_path = {"executable_path": "chromedriver"}
    return Browser("chrome", **executable_path, headless=False)

def scrape():
    browser = init_browser()

    # ---------------------------
    # Retrieve headline & summary
    # ---------------------------
    url = "https://mars.nasa.gov/news/"
    browser.visit(url)
    time.sleep(1)

    # Assistance from Benjamen Alford - change from [] to {}
    mars_info = {}

    html = browser.html
    soup = BeautifulSoup(html, "html.parser")
    results = soup.find("li", class_="slide")
    for r in results:
        try:
            mars_info = {}
            mars_info["news_title"] = r.find("div", class_="content_title").get_text()
            mars_info["news_p"] = r.find("div", class_="article_teaser_body").get_text()

        except:
            break

    # -----------------------
    # Retrieve featured image
    # -----------------------
    img_site = "https://www.jpl.nasa.gov/spaceimages/?search=&category=Mars"
    browser.visit(img_site)
    time.sleep(1)
    browser.links.find_by_partial_text('FULL').click()
    time.sleep(1)
    browser.links.find_by_partial_href('/spaceimages/details').click()
    time.sleep(1)
    browser.links.find_by_partial_href('/spaceimages/images/largesize/').click()

    # https://splinter.readthedocs.io/en/latest/browser.html#verifying-page-url-with-browser-url
    mars_info["featured_image_url"] = browser.url

    # -----------------------
    # Retrieve facts table --
    # -----------------------
    facts_url ='https://space-facts.com/mars/'
    mars_facts = pd.read_html(facts_url)

    facts_table = mars_facts[0]
    mars_info["facts_table"] = facts_table.to_html(header=False, index=False, justify="left", classes="table-striped")

    # ------------------------------------------------
    # Create dictionary for hemispheres and image urls
    # ------------------------------------------------
    hemisphere_image_urls = []
    hemisphere_names = []

    hems_url = 'https://astrogeology.usgs.gov/search/results?q=hemisphere+enhanced&k1=target&v1=Mars'
    browser.visit(hems_url)
    html = browser.html
    soup = BeautifulSoup(html, "html.parser")
    titles = soup.find_all("div", class_="description")
    for t in titles:
        try:
            result = []
            result = t.find("h3").get_text()
            hemisphere_names.append(result)
        except:
            pass

    for h in hemisphere_names:
        hems_url = 'https://astrogeology.usgs.gov/search/results?q=hemisphere+enhanced&k1=target&v1=Mars'
        browser.visit(hems_url)
        time.sleep(1)
        html = browser.html
        soup = BeautifulSoup(html, "html.parser")
        browser.links.find_by_partial_text(h).click()

        result = {}
        result["title"] = h
        html = browser.html
        soup = BeautifulSoup(html, "html.parser")
        result["img_url"] = soup.find("div", class_="downloads").find("a")["href"]
        hemisphere_image_urls.append(result)
    mars_info["cerberus"] = hemisphere_image_urls[0]
    mars_info["schia"] = hemisphere_image_urls[1]
    mars_info["syr"] = hemisphere_image_urls[2]
    mars_info["valles"] = hemisphere_image_urls[3]

    # mars_info["hemispheres"] = hemisphere_image_urls

    browser.quit()

    return mars_info


from copy import deepcopy
from dataclasses import dataclass

import pennylane as qml
import pennylane.numpy as pnp
from catalyst_benchmark.types import Problem

@dataclass
class ProblemPL(Problem):
    """Catalyst implementation details of the VQE problem"""

    def __init__(self, dev, nlayers=None, **qnode_kwargs):
        super().__init__(dev, **qnode_kwargs)
        self.qcircuit = None
        self.nlayers = nlayers if nlayers else 1

    def trial_params(self, i: int):
        return pnp.array([1.0 / (2.0 * (1 + i) * pnp.pi)], dtype=pnp.float64)

def qcompile(p: ProblemPL, params):
    """Compile the quantum parts of the problem"""

    def _circuit(params):
        N = p.nqubits
        L = p.nlayers
        for wG in range(N):
            qml.Hadamard(wires=[wG])
        for _ in range(L):
            for wG in range(N):
                for wC in range(wG + 1, N):
                    phi = (2 ** (wC - wG)) / params[0]
                    qml.ctrl(qml.PhaseShift, control=wC)(phi=phi, wires=[wG])
        return qml.state()

    qcircuit = qml.QNode(_circuit, p.dev, **p.qnode_kwargs)
    qcircuit.construct([params], {})
    p.qcircuit = qcircuit
    return p

def workflow(p: ProblemPL, params):
    """Problem workflow"""
    return p.qcircuit(params)

def size(p: ProblemPL) -> int:
    """Compute the size of the problem circuit"""
    qnode_kwargs = deepcopy(p.qnode_kwargs)
    qnode_kwargs.update({"expansion_strategy": "device"})
    qcompile(p, p.trial_params(0))
    return len(p.qcircuit.tape.operations)

SHOTS = None

def run_jax_lightning_qubit(N=6):
    """Test problem entry point"""

    import jax  # pylint: disable=import-outside-toplevel

    jax.config.update("jax_enable_x64", True)

    p = ProblemPL(dev=qml.device("lightning.qubit", wires=N, shots=SHOTS), interface="jax")

    @jax.jit
    def _main(params):
        qcompile(p, params)
        return workflow(p, params)

    params = p.trial_params(0)
    result = _main(params)
    print(f"Result: {result}")

def run_lightning_qubit(N=6):
    """Test problem entry point"""

    p = ProblemPL(dev=qml.device("lightning.qubit", wires=N, shots=SHOTS))

    def _main(params):
        qcompile(p, params)
        return workflow(p, params)

    params = p.trial_params(0)
    result = _main(params)
    print(f"Result: {result}")

def run_default_qubit(N=6):
    """Test problem entry point"""

    p = ProblemPL(dev=qml.device("default.qubit", wires=N, shots=SHOTS))

    def _main(params):
        qcompile(p, params)
        return workflow(p, params)

    params = p.trial_params(0)
    result = _main(params)
    print(f"Result: {result}")


from django.contrib.auth.decorators import login_required
from django.shortcuts import render, get_object_or_404
from glide.app.inbox.models import Message, Conversation
from glide.app.inbox.forms import ReplyMessageForm, NewMessageForm
from django.db.models import Q
from django.http import HttpResponsePermanentRedirect
from glide.core.profiles.models import Profile
from glide.core.notifications.models import Notification
@login_required
def inbox(request):
	conversations = Conversation.objects.filter(Q(receiver=request.user) | Q(sender=request.user)).order_by('-last_message')
	return render(request, 'inbox/inbox.html', {'conversations':conversations})

def mark_as_read(user, conversation):
	messages = Message.objects.filter(conversation=conversation).exclude(read=True).exclude(author=user)
	for message in messages:
		message.read = True
		message.save()

@login_required
def view_conversation(request, id):
	conversation = get_object_or_404(Conversation, pk=id)
	mark_as_read(request.user, conversation)
	messages = Message.objects.filter(conversation=conversation).order_by('-date')
	return render(request, 'inbox/conversation.html', {'messages':messages,
														'conversation':conversation})

@login_required
def reply(request):
	if request.method == 'POST':
		form = ReplyMessageForm(request.POST)
		if form.is_valid():
			item = form.save(commit=False)
			item.author = request.user
			item.save()
			conversation = item.conversation
			conversation.save()
			return HttpResponsePermanentRedirect(conversation.get_absolute_url())

@login_required
def new_message(request, id):
	profile = get_object_or_404(Profile, pk=id)
	receiver = profile.user
	conversation = None
	if conversation == None:
		try:
			conversation = Conversation.objects.get(sender=request.user, receiver=receiver)
			return view_conversation(request, conversation.pk)
		except:
			pass
	if conversation == None:
		try:
			conversation = Conversation.objects.get(sender=receiver, receiver=request.user)
			return view_conversation(request, conversation.pk)
		except:
			pass

	form = NewMessageForm()
	if request.method == 'POST':
		form = NewMessageForm(request.POST)
		if form.is_valid():
			conversation = Conversation(sender=request.user, receiver=receiver)
			conversation.save()
			item = form.save(commit=False)
			item.conversation = conversation
			item.author = request.user
			item.save()
			return view_conversation(request, conversation.pk)
	return render(request, 'inbox/form.html', {'form':form})


from django.urls import path
from article import views
#
urlpatterns = [
  path('',views.articleIndex , name='article_home'),
  path('createnew',views.createNew , name='create_new'),
  path('delete/<str:id>',views.deteleArticle , name='delete_article'),
  path('edit/<str:id>',views.editArticle , name='edit_article'),
  path('likearticle/<str:article_id>',views.likeArticle , name='like_article'),
  path('likecomment/<str:commentId>',views.likeComment , name='like_comment'),
  path('postacomment/<str:id>',views.postAComment , name='post_a_comment'),
  path('sendreply/<int:id>',views.sendReplay , name='sent_replay'),
  # path('getarticlesof/<str:username>',views.getArticleForASpecificUser , name='get_article_for_username'),
  path('<str:id>',views.previewArticle , name='article_preview'),
]


"""
Complexity reports
"""

import shlex

from navio_tasks import settings as settings
from navio_tasks.cli_commands import check_command_exists, execute, prepinform_simple
from navio_tasks.settings import COMPLEXITY_CUT_OFF

def do_mccabe() -> str:
    """
    Complexity Checker
    """

    check_command_exists("flake8")  # yes, flake8, this is a plug in.
    # mccabe doesn't have a direct way to run it

    command_text = (
        f"flake8 --max-complexity {COMPLEXITY_CUT_OFF} "
        f"--config {settings.CONFIG_FOLDER}/.flake8"
    )
    command_text = prepinform_simple(command_text)
    command = shlex.split(command_text)
    execute(*command)
    return "mccabe succeeded"


from pymongo import MongoClient

class BookSaver:
    def __init__(self):
        mongo_client = MongoClient('localhost', 27017)
        self.books = mongo_client.book_db

    def insert_chapter(self, book_name, chapter):
        book_chapter = {
            'book_name': book_name,
            'chapter_title': chapter['chapter_title'],
            'index': chapter['index'],
            'url': chapter['url']
        }
        self.books[book_name].insert_one(book_chapter)

    def get_chapter_by_index(self, index, book_name):
        return self.books[book_name].find_one({'index': index})


# coding=utf-8
"""
Track modification on SQLAlchemy objects.
"""
from contextlib import contextmanager
from datetime import datetime

from src.constants import CTX_ADMIN
from src.interface_adapter.sql.model.models import Modification, Utilisateur
from src.interface_adapter.sql.model.trackable import RubyHashTrackable

@contextmanager
def track_modifications(ctx, session, obj: RubyHashTrackable):
    """
    Track the modifications of the specified entry and create a new entry in the modification table containing the diff.

    Object must inherit from RubyHashTrackable.
    """
    snap_before = obj.take_snapshot()  # Save the state of the object before actually modifying it.
    try:
        yield
    finally:
        diff = _get_diff(session, snap_before, obj)
        if diff is None:
            return  # No modification.

        now = datetime.now()
        admin = ctx.get(CTX_ADMIN)
        member = obj.get_related_member()

        admin_id = session.query(Utilisateur).filter(Utilisateur.login == admin.login).one().id

        m = Modification(
            adherent_id=member.id,
            action=diff,
            created_at=now,
            updated_at=now,
            utilisateur_id=admin_id,
        )
        session.add(m)

def _get_diff(session, snap_before, obj):
    if obj in session.new:
        return obj.serialize_snapshot_diff(None, obj.take_snapshot())

    if obj in session.deleted:
        return obj.serialize_snapshot_diff(snap_before, None)

    # Not deleted nor created, flush it to the database (not commit!) and compare the current state with the old state.
    #
    # Note: We need to flush here to put the object in a consistent state. For instance if we modify Member.room the
    # foreign key Member.room_id will not be updated until we flush it.
    #
    # Note2: flushing is not commit! The transaction can still be roll-backed if something goes wrong.
    session.flush()
    if snap_before != obj.take_snapshot():
        return obj.serialize_snapshot_diff(snap_before, obj.take_snapshot())


from abc import ABC, abstractmethod
from copy import deepcopy
from math import floor
from typing import Optional

import mujoco_py
import numpy as np
from init_args_serializer import Serializable
from mujoco_py.generated.const import RND_FOG

import pyrado
from pyrado.environments.sim_base import SimEnv
from pyrado.spaces.base import Space
from pyrado.tasks.base import Task
from pyrado.utils.data_types import RenderMode
from pyrado.utils.input_output import print_cbt

class MujocoSimEnv(SimEnv, ABC, Serializable):
    """
    Base class for MuJoCo environments.
    Uses Serializable to facilitate proper serialization.

    .. seealso::
        https://github.com/openai/gym/blob/master/gym/envs/mujoco/mujoco_env.py
    """

    def __init__(
        self,
        model_path: str,
        frame_skip: int = 1,
        dt: Optional[float] = None,
        max_steps: int = pyrado.inf,
        task_args: Optional[dict] = None,
    ):
        """
        Constructor

        :param model_path: path to the MuJoCo xml model config file
        :param frame_skip: number of simulation frames for which the same action is held, results in a multiplier of
                           the time step size `dt`
        :param dt: by default the time step size is the one from the mujoco config file multiplied by the number of
                   frame skips (legacy from OpenAI environments). By passing an explicit `dt` value, this can be
                   overwritten. Possible use case if if you know that you recorded a trajectory with a specific `dt`.
        :param max_steps: max number of simulation time steps
        :param task_args: arguments for the task construction, e.g `dict(fwd_rew_weight=1.)`
        """
        Serializable._init(self, locals())

        # Initialize
        self.model_path = model_path
        self._domain_param = self.get_nominal_domain_param()
        if dt is None:
            # Specify the time step size as a multiple of MuJoCo's simulation time step size
            self.frame_skip = frame_skip
        else:
            # Specify the time step size explicitly
            with open(self.model_path, mode="r") as file_raw:
                xml_model_temp = file_raw.read()
            xml_model_temp = self._adapt_model_file(xml_model_temp, self.domain_param)
            # Create a dummy model to extract the solver's time step size
            model_tmp = mujoco_py.load_model_from_xml(xml_model_temp)
            frame_skip = dt / model_tmp.opt.timestep
            if frame_skip.is_integer():
                self.frame_skip = int(frame_skip)
            elif dt > model_tmp.opt.timestep:
                print_cbt(
                    f"The desired time step size is {dt} s, but solver's time step size in the MuJoCo config file is "
                    f"{model_tmp.opt.timestep} s. Thus, frame_skip is rounded down to {floor(frame_skip)}.",
                    "y",
                )
                self.frame_skip = floor(frame_skip)
            else:
                # The number of skipped frames must be >= 1
                pyrado.ValueErr(given=dt, ge_constraint=model_tmp.opt.timestep)

        # Creat the MuJoCo model
        with open(self.model_path, mode="r") as file_raw:
            # Save raw (with placeholders) XML-file as attribute since we need it for resetting the domain params
            self.xml_model_template = file_raw.read()
        self._create_mujoco_model()

        # Call SimEnv's constructor
        super().__init__(dt=self.model.opt.timestep * self.frame_skip, max_steps=max_steps)

        # Memorize the initial states of the model from the xml (for fixed init space or later reset)
        self.init_qpos = self.sim.data.qpos.copy()
        self.init_qvel = self.sim.data.qvel.copy()

        # Initialize space (to be overwritten in constructor of subclasses)
        self._init_space = None

        # Create task
        if not (isinstance(task_args, dict) or task_args is None):
            raise pyrado.TypeErr(given=task_args, expected_type=dict)
        self.task_args = dict() if task_args is None else task_args
        self._task = self._create_task(self.task_args)

        # Visualization
        self.camera_config = dict()
        self.viewer = None
        self._curr_act = np.zeros(self.act_space.shape)

    @property
    @abstractmethod
    def state_space(self) -> Space:
        raise NotImplementedError

    @property
    @abstractmethod
    def obs_space(self) -> Space:
        raise NotImplementedError

    @property
    @abstractmethod
    def act_space(self) -> Space:
        raise NotImplementedError

    @property
    def init_space(self) -> Space:
        return self._init_space

    @init_space.setter
    def init_space(self, space: Space):
        if not isinstance(space, Space):
            raise pyrado.TypeErr(given=space, expected_type=Space)
        self._init_space = space

    @property
    def task(self) -> Task:
        return self._task

    @abstractmethod
    def _create_task(self, task_args: dict) -> Task:
        # Needs to implemented by subclasses
        raise NotImplementedError

    @property
    def domain_param(self) -> dict:
        return deepcopy(self._domain_param)

    @domain_param.setter
    def domain_param(self, domain_param: dict):
        if not isinstance(domain_param, dict):
            raise pyrado.TypeErr(given=domain_param, expected_type=dict)
        # Update the parameters
        self._domain_param.update(domain_param)

        # Update MuJoCo model
        self._create_mujoco_model()

        if self.viewer is not None:
            # If the viewer already exists and we reset the domain parameters, we must also recreate the viewer since
            # it references to the simulation object which get's reconstructed during _create_mujoco_model()
            import glfw

            glfw.destroy_window(self.viewer.window)
            self.viewer = None

        # Update task
        self._task = self._create_task(self.task_args)

    def _adapt_model_file(self, xml_model: str, domain_param: dict) -> str:
        """
        Changes the model's XML-file given the current domain parameters before constructing the MuJoCo simulation.
        One use case is for example the cup_scale for the `WAMBallInCupSim` where multiple values in the model's
        XML-file are changed based on one domain parameter.

        .. note::
            It is mandatory to call this function in case you modified the mxl config file with tags like `[DP_NAME]`.

        :param xml_model: parsed model file
        :param domain_param: copy of the environments domain parameters
        :return: adapted model file where the placeholders are filled with numerical values
        """
        # The mesh dir is not resolved when later passed as a string, thus we do it manually
        xml_model = xml_model.replace(f"[ASSETS_DIR]", pyrado.MUJOCO_ASSETS_DIR)

        # Replace all occurrences of the domain parameter placeholder with its value
        for key, value in domain_param.items():
            xml_model = xml_model.replace(f"[{key}]", str(value))

        return xml_model

    @abstractmethod
    def _mujoco_step(self, act: np.ndarray) -> dict:
        """
        Apply the given action to the MuJoCo simulation. This executes one step of the physics simulation.

        :param act: action
        :return: dictionary with optional information from MuJoCo
        """

    def _create_mujoco_model(self):
        """
        Called to update the MuJoCo model by rewriting and reloading the XML file.

        .. note::
            This function is called from the constructor and from the domain parameter setter.
        """
        xml_model = self.xml_model_template  # don't change the template
        xml_model = self._adapt_model_file(xml_model, self.domain_param)

        # Create MuJoCo model from parsed XML file
        self.model = mujoco_py.load_model_from_xml(xml_model)
        self.sim = mujoco_py.MjSim(self.model, nsubsteps=self.frame_skip)

    def configure_viewer(self):
        """Configure the camera when the viewer is initialized. You need to set `self.camera_config` before."""
        # Render a fog around the scene by default
        if self.camera_config.pop("render_fog", True):
            self.viewer.scn.flags[RND_FOG] = 1

        # Parse all other options
        for key, value in self.camera_config.items():
            if isinstance(value, np.ndarray):
                getattr(self.viewer.cam, key)[:] = value
            else:
                setattr(self.viewer.cam, key, value)

    def reset(self, init_state: np.ndarray = None, domain_param: dict = None) -> np.ndarray:
        # Reset time
        self._curr_step = 0

        # Reset the domain parameters
        if domain_param is not None:
            self.domain_param = domain_param

        # Sample or set the initial simulation state
        if init_state is None:
            # Sample init state from init state space
            init_state = self.init_space.sample_uniform()
        elif not isinstance(init_state, np.ndarray):
            # Make sure init state is a numpy array
            try:
                init_state = np.asarray(init_state)
            except Exception:
                raise pyrado.TypeErr(given=init_state, expected_type=np.ndarray)
        if not self.init_space.contains(init_state, verbose=True):
            raise pyrado.ValueErr(msg="The init state must be within init state space!")

        # Update the state attribute
        self.state = init_state.copy()

        # Reset the task which also resets the reward function if necessary
        self._task.reset(env_spec=self.spec, init_state=init_state.copy())

        # Reset MuJoCo simulation model (only reset the joint configuration)
        self.sim.reset()
        old_state = self.sim.get_state()
        nq = self.model.nq
        nv = self.model.nv
        if not init_state[:nq].shape == old_state.qpos.shape:  # check joint positions dimension
            raise pyrado.ShapeErr(given=init_state[:nq], expected_match=old_state.qpos)
        # Exclude everything that is appended to the state (at the end), e.g. the ball position for WAMBallInCupSim
        if not init_state[nq : nq + nv].shape == old_state.qvel.shape:  # check joint velocities dimension
            raise pyrado.ShapeErr(given=init_state[nq : nq + nv], expected_match=old_state.qvel)
        new_state = mujoco_py.MjSimState(
            # Exclude everything that is appended to the state (at the end), e.g. the ball position for WAMBallInCupSim
            old_state.time,
            init_state[:nq],
            init_state[nq : nq + nv],
            old_state.act,
            old_state.udd_state,
        )
        self.sim.set_state(new_state)
        self.sim.forward()

        # Return an observation
        return self.observe(self.state)

    def step(self, act: np.ndarray) -> tuple:
        # Current reward depending on the state (before step) and the (unlimited) action
        remaining_steps = self._max_steps - (self._curr_step + 1) if self._max_steps is not pyrado.inf else 0
        self._curr_rew = self.task.step_rew(self.state, act, remaining_steps)

        # Apply actuator limits
        act = self.limit_act(act)
        self._curr_act = act  # just for the render function

        # Apply the action and simulate the resulting dynamics
        info = self._mujoco_step(act)
        self._curr_step += 1

        # Check if the environment is done due to a failure within the mujoco simulation (e.g. bad inputs)
        mjsim_done = info.get("failed", False)

        # Check if the task is done
        task_done = self._task.is_done(self.state)

        # Handle done case
        done = mjsim_done or task_done
        if self._curr_step >= self._max_steps:
            done = True

        if done:
            # Add final reward if done
            self._curr_rew += self._task.final_rew(self.state, remaining_steps)

        return self.observe(self.state), self._curr_rew, done, info

    def render(self, mode: RenderMode = RenderMode(), render_step: int = 1):
        if self._curr_step % render_step == 0:
            # Call base class
            super().render(mode)

            # Print to console
            if mode.text:
                print(
                    f"step: {self._curr_step:4d}  |  r_t: {self._curr_rew: 1.3f}  |  a_t: {self._curr_act}  |  s_t+1: {self.state}"
                )

            # Forward to MuJoCo viewer
            if mode.video:
                if self.viewer is None:
                    # Create viewer if not existent (see 'human' mode of OpenAI Gym's MujocoEnv)
                    self.viewer = mujoco_py.MjViewer(self.sim)

                    # Adjust window size and position to custom values
                    import glfw

                    glfw.make_context_current(self.viewer.window)
                    glfw.set_window_size(self.viewer.window, 1280, 720)
                    glfw.set_window_pos(self.viewer.window, 50, 50)

                    self.configure_viewer()
                self.viewer.render()


"""
1680. Concatenation of Consecutive Binary Numbers
Medium

Given an integer n, return the decimal value of the binary string formed
by concatenating the binary representations of 1 to n in order, modulo 10^9 + 7.

Example 1:

Input: n = 1
Output: 1
Explanation: "1" in binary corresponds to the decimal value 1.
Example 2:

Input: n = 3
Output: 27
Explanation: In binary, 1, 2, and 3 corresponds to "1", "10", and "11".
After concatenating them, we have "11011", which corresponds to the decimal value 27.
Example 3:

Input: n = 12
Output: 505379714
Explanation: The concatenation results in "1101110010111011110001001101010111100".
The decimal value of that is 118505380540.
After modulo 10^9 + 7, the result is 505379714.

Constraints:

1 <= n <= 105

Explaination:

110 = 1 * 100 + 10 (all in binary representation),
11011 = 110 * 100 + 11, 11011100 = 11011 * 1000 + 100 and so on.
We can see that on each step we need to multiply number by lenght of new number and add new number
(and use %M) and that is all!
"""

class Solution:
    def concatenatedBinary1(self, n: int) -> int:
        m = ""
        for i in range(1, n + 1):
            m += bin(i)[2:]
        return int(m, 2) % (10**9 + 7)

    def concatenatedBinary(self, n):
        ans, M = 0, 10**9 + 7
        # 5:    101 = 1*2^2 + 0*2^1 + 1*2^0
        # 54:   101,100
        #       (101)*2^3-> 1*2^(2+3) + 0*2^(1+3) + 1*2^(0+3)
        #       pow(2, k) <=> 1<<k
        #       Therefore, k is the length of binary number
        for x in range(n):
            ans = (ans * (1 << (len(bin(x + 1)) - 2)) + x + 1) % M
        return ans


import socket
import threading

bind_ip = "0.0.0.0"
bind_port = 9999

server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

server.bind((bind_ip,bind_port))

server.listen(5)

print("[*] Listing on %s:%d" % (bind_ip, bind_port))

def handelClient(clientSocket):

    recived = clientSocket.recv(1024).decode()
    print("[*] Recived: %s" % recived)

    clientSocket.send(("ACK!").encode())

    recived = clientSocket.recv(1024).decode()
    print("[*] Recived: %s" % recived)

    clientSocket.close()

def custom_handel(clientSocket):
    while True:
        recived = clientSocket.recv(1024).decode()
        print("[*] Recived: %s" % recived)

        clientSocket.send(("ACK!").encode())

while True:
    client, addr = server.accept()
    print("[*] Accepted connection from %s:%d" % (addr[0], addr[1]))

    clientHandler = threading.Thread(target=custom_handel, args=(client,))
    clientHandler.start()


"""
Headline Parser

Functions to extract structured data from raw html pages.
"""

from .utilities import dir_check, load_all_json_in_dir, load_json, \
    get_webpage_html, connected_to_internet, is_website_up, save_json
from .html_parsing import findall_href, extract_headline_row

def headline_parser(start_page_url="https://www.fark.com/archives/"):
    """
    Function to extract all the headlines and their metadata from the Fark.com
    site.

    :param start_page_url: The Fark URL archive to start searching.
    :type start_page_url: str
    :return:
    """

    # Check that the folders to store the data exist
    for dir_ in ["scraped_data", "program_info"]:
        if not dir_check(dir_):
            raise Exception(f"The folder {dir_} "
                            f"could not be found or created.")

    # Load the old data files
    visited_webpages = load_json("program_info/visited_webpages.JSON", False)
    headline_data = load_json("program_info/headlines.JSON", False)
    websites_to_visit = list(load_json("program_info/websites_to_visit.JSON",
                                       False))

    # Add the base archive url to the list of website to visit
    if start_page_url not in websites_to_visit:
        websites_to_visit.append(start_page_url)

    # Scrape the site for site headline pages
    while websites_to_visit:

        # Save All Data to Disk
        save_json(visited_webpages, "program_info/visited_webpages.JSON")
        save_json(headline_data, "program_info/headlines.JSON")
        save_json(list(websites_to_visit), "program_info/websites_to_visit.JSON")

        if not connected_to_internet() or not is_website_up(start_page_url):
            break

        # Pick a websites_to_visit
        url = websites_to_visit.pop()

        # Don't revisit websites
        if url in visited_webpages:
            continue

        # Load the html for the webpage
        raw_html_text = get_webpage_html(url)

        # Extract all links on the page
        websites_to_visit += findall_href(raw_html_text, url)

        # Remove duplicates
        websites_to_visit = list(set(websites_to_visit))

        # See if there are any headlines on the page
        new_headlines = extract_headline_row(raw_html_text)
        headline_data = {**headline_data, **new_headlines}

        # Update the record of visited websites
        visited_webpages[url] = None


"""Support for processing input/output."""

from contextlib import contextmanager
import os
import shutil
from tempfile import gettempdir, mkdtemp
from typing import Iterator

from topshelfsoftware_util.log import get_logger
logger = get_logger(__name__, stream=None)

@contextmanager
def cdtmp(tmpdir: str = None, sub_dirname: str = None, cleanup: bool = True) -> Iterator[None]:
    """Context manager to work in temporary directory.

    Provisions directory, changes to it, then removes once context is complete.

    >>> os.chdir('/home')
    >>> with cdtmp():
    >>>     # do stuff or
    >>>     raise Exception("There's no place like home.")
    >>> # Directory is now back to '/home' and the temporary directory no longer exists
    """
    if tmpdir is not None:
        os.environ["TMPDIR"] = tmpdir

    try:
        prev_dir = os.getcwd()
    except FileNotFoundError:
        prev_dir = gettempdir()
        logger.warning(f"Unable to get current working directory, using {prev_dir}")

    if sub_dirname is not None:
        temp_dir = os.path.join(gettempdir(), sub_dirname)
        os.makedirs(temp_dir, exist_ok=True)
    else:
        temp_dir = mkdtemp()
    logger.debug(f"temp directory: {temp_dir}")

    os.chdir(temp_dir)
    try:
        yield
    finally:
        os.chdir(prev_dir)
        if cleanup:
            shutil.rmtree(temp_dir, ignore_errors=True)
            logger.debug(f"deleted temp directory: {temp_dir}")


import bot
from settings import app_secrets
import time
import datetime as dt
from datetime import datetime
import os
import notify
import centre_schedule_scrapper

def current_date():
	now = datetime.now()
	dt_string = now.strftime("%d/%m/%Y")
	return dt_string

def isNowInTimePeriod(startTime, endTime, nowTime):
    if startTime < endTime:
        return nowTime >= startTime and nowTime <= endTime
    else:
        #Over midnight:
        return nowTime >= startTime or nowTime <= endTime

def send_doc(text):
	bot.bot.send_document(app_secrets._18plus_groupid, text , caption = "Vaccine Centre Plan List\nYou can contact ANMs incase you want")
	bot.bot.send_document(app_secrets._45plus_groupid, text , caption = "Vaccine Centre Plan List\nYou can contact ANMs incase you want")

bot.bot.send_message(app_secrets.Group_Owner , "Started...")
print("Started...")
print(dt.datetime.now().time())
num = 0
run_doc = 0
while True:
	if isNowInTimePeriod(dt.time(8,00), dt.time(9,00), dt.datetime.now().time()):
		try:
			if run_doc == 0:
				text = centre_schedule_scrapper.scrape()
				if text[1] == current_date():
					send_doc(text[0])
					run_doc = 1
		except Exception as e:
			bot.bot.send_message(app_secrets.Group_Owner , "Error!!!")
			bot.bot.send_message(app_secrets.Group_Owner , e)

	if isNowInTimePeriod(dt.time(9,00), dt.time(23,00), dt.datetime.now().time()):
		try:
			notify.RUN()
			print(num)
			num+=1
			time.sleep(int(os.environ.get('SLEEP_TIME')))
		except Exception as e:
			if "Max retries exceeded with url:" not in str(e):
				try:
					bot.bot.send_message(app_secrets.Group_Owner , "Error!!!")
					bot.bot.send_message(app_secrets.Group_Owner , e)
				except:
					print("............\n")
					print(e , end = "\n")
			else:
				print("............\n")
				print(e , end = "\n")

			time.sleep(5)

	if isNowInTimePeriod(dt.time(12,00), dt.time(13,00), dt.datetime.now().time()):
		run_doc = 0


"""
https://edabit.com/challenge/KjCnfEm8WzJcnuPYt

Indices of Zeroes for the Longest Run of Contiguous Ones
You are given a list of binary integers and k, the number of flips allowed.

Write a function that returns the indices of zeroes of which, when flipped,
return the longest contiguous sequence of ones.

Examples
zero_indices([1, 0, 1, 1, 0, 0, 0, 1], 1) ➞ [1]

zero_indices([1, 0, 0, 0, 0, 1], 1) ➞ [1]

zero_indices([1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0], 3) ➞ [6, 7, 9]

zero_indices([1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0], 3) ➞ [7, 8, 9]
Notes
If multiple combinations of indices tie for longest one sequence,
return the indices which occur first (see examples #2, #3).

"""

def zero_indices(lst, k):

    start, count, block = 0, 0, 0
    index = 0
    for i in range(len(lst)):

        if lst[i] == 0: count = count + 1
        while count > k:
            if lst[start] == 0: count = count - 1
            start += 1
        if i - start + 1 > block:
            block = i - start + 1
            index = start
    rr=[]
    for i in range(index, index + block):
        if lst[i] == 0: rr.append(i)

    return (rr)

#zero_indices([1, 0, 1, 1, 0, 0, 0, 1], 1) #➞ [1]
#zero_indices([1, 0, 0, 0, 0, 1], 1) #➞ [1]
zero_indices([1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0], 3) #➞ [6, 7, 9]
#zero_indices([1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0], 3) #➞ [7, 8, 9]


import pandas as pd
import matplotlib.pyplot as plt
import os
import argparse

def avg_drop(directory, benchmark):
    df = pd.DataFrame()
    file = pd.read_csv(f'{directory}/MLFFR_o1_t.txt', index_col=0)
    df["index"] = list(file.index)
    df.set_index("index", inplace=True)
    versions = ["o1", "o2", "k0", "k1", "k2", "k3", "k4"]
    if benchmark == "xdp2" or benchmark == "xdp_router_ipv4":
        versions.remove("k2")
    for i in versions:
        file = pd.read_csv(f'{directory}/MLFFR_{i}_t.txt', index_col=0)
        file['mean'] = file.mean(axis=1)
        #print(file)
        df[i] = file['mean']

    #print(df)
    fig = plt.figure()
    plt.plot(df, marker="o")
    plt.title(f'Measuring {benchmark} AVG Drop Rate')
    plt.xlabel('TX rate (Mpps)',)
    plt.ylabel('Drop Rate')
    plt.legend(df.columns)
    savePath = f'{directory}/drop/'
    if not os.path.exists(savePath):
        os.makedirs(savePath)
    fig.savefig(f'{savePath}/avg.png', bbox_inches='tight')

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='Information about Data')
    parser.add_argument('-d', dest="directory", type=str, help='Directory', required=True)
    parser.add_argument('-b', dest="benchmark", type=str, help='Benchmark', required=True)
    args = parser.parse_args()
    avg_drop(args.directory, args.benchmark)


import os
from collections import Counter

import spacy

DATA_DIR = "data"
DATA_FILES = [os.path.join(DATA_DIR, f) for f in os.listdir(DATA_DIR) if f.endswith(".txt")]

nlp = spacy.load("en")
all_pos = set()
hists = {}
for data_file in DATA_FILES:
    with open(data_file, encoding="utf-8") as f:
        pos_hist = Counter(token.pos_ for doc in nlp.pipe(f) for token in doc)
    all_pos.update(pos_hist)
    hists[data_file] = pos_hist

all_pos = sorted(all_pos)
print("", *all_pos, sep="\t")
for data_file, pos_hist in sorted(hists.items()):
    print(os.path.basename(os.path.splitext(data_file)[0]), *[pos_hist[p] for p in all_pos], sep="\t")


import discord

from discord.ext import commands
from random import *

from .server_only_cog import *

vowels = ['a', 'e', 'i', 'o', 'u']
exclude = ["the", "i\'m", "and"]
markdownSymbols = ["*", "**", "***", "__", "~~", "`", "__*", "__**", "__***", "<", ">", ";", "'", "!"]
excludefirsts = ['w']
locFileName = "res/Locations.txt"

# Generic text commands that are not very useful
class FunTextCog(ServerOnlyCog, name = "Fun Text"):

    def __init__(self, bot: commands.Bot):
        self.bot = bot
        self.locations_def = str()
        self.reread_loc_file()

    def reread_loc_file(self):
        with open(locFileName, "r") as locFile:
            self.fortnitelocations_def = locFile.readlines()
            locFile.close()

    def letterify(self, originalStr, replace: str):
        words = originalStr
        finalJimmify = []
        for word in words:
            if len(word) <= 0:
                continue

            if len(word) > 2 and word[0].lower() != replace and word.lower() not in exclude and word[0].lower() not in excludefirsts:

                # Brute-force check for markdown/symbols to skip in the word
                markDownEnd = 0
                wordLen = len(word)
                while not word[markDownEnd].isalpha() and markDownEnd < wordLen:
                    markDownEnd += 1

                # Replace first letter in the string.
                # If it's capitalized, capitalize the replacement letter and lower the old one.
                jRep = replace.upper() if word[markDownEnd].isupper() else replace
                if word[markDownEnd].lower() in vowels:
                    if word[markDownEnd].islower():
                        word = word[0:markDownEnd] + jRep + word[markDownEnd:-1] + word[-1]
                    else:
                        word = word[0:markDownEnd] + jRep + word[markDownEnd].lower() + word[markDownEnd+1:-1] + word[-1]
                else:
                    word = word.replace(word[markDownEnd], jRep, 1)

            finalJimmify.append(word)

        return finalJimmify

    @commands.command(name='Jimmify')
    async def jimmify(self, ctx, *args):

        msg = str(ctx.message.content).split(' ')
        msg.pop(0)
        if len(args) == 0:
            msg = [message async for message in ctx.channel.history(limit=2)]
            msg = msg[1].content.split(' ')

        finalJimmify = self.letterify(msg, 'j')
        await ctx.send(" ".join(finalJimmify))

    @commands.command(name='Mattify')
    async def mattify(self, ctx, *args):

        msg = str(ctx.message.content).split(' ')
        msg.pop(0)
        if len(args) == 0:
            msg = [message async for message in ctx.channel.history(limit=2)]
            msg = msg[1].content.split(' ')

        finalJimmify = self.letterify(msg, 'm')
        await ctx.send(" ".join(finalJimmify))

    @commands.command(name='Droppin')
    async def droppin(self, ctx):
        val = randint(0, len(self.fortnitelocations_def) - 1)
        await ctx.send(self.fortnitelocations_def[val])
        pass

    @commands.command(name='SetDroppin')
    async def set_droppin(self, ctx, *args):

        if args == None:
            await ctx.send("Error: no locations given with command. Locations are unchanged.")
            return

        final = []
        for i in range(len(args)):
            final.append(args[i] + "\n")

        print(final)
        with open (locFileName, "w") as locFile:
            locFile.writelines(final)
            locFile.close()

        self.reread_loc_file()
        await ctx.send("Locations list successfully overwritten and changed to: \n" + ", ".join(args))

    @commands.command(name='AddDroppin')
    async def add_droppin(self, ctx, *args):
        if args == None:
            await ctx.send("Error: no locations given with command. Locations are unchanged.")
            return

        toAdd = " ".join(args).strip()
        with open(locFileName, "a") as locFile:
            locFile.writelines(["\n", f"{toAdd}"])
            locFile.close()

        self.reread_loc_file()
        await ctx.send(f"Added {toAdd} to locations list")

    @commands.command(name='RemoveDroppin')
    async def remove_droppin(self, ctx, *args):

        original = " ".join(args)
        toRem = original.lower()
        ind = None

        locs = self.fortnitelocations_def.copy()
        for i in range(len(locs)):
            locs[i] = locs[i].lower().strip("\n")

        try:
            locs.index(toRem)
        except ValueError as e:
            await ctx.send(f'Could not find: {toRem} in droppin list!')
            return
        else:
            ind = locs.index(toRem)
            self.fortnitelocations_def.pop(ind)

        with open(locFileName, "w") as locFile:
            locFile.writelines(self.fortnitelocations_def)
            locFile.close()

        await ctx.send(f"Successfully removed the location: {original}")

    @commands.command(name='ShowDroppin')
    async def show_droppin(self, ctx):

        toPrint = self.fortnitelocations_def
        if randint(1, 1000) == 1:
            secrets = ["Jimmy Junction", "Matt Mansion"]
            val = randint(0, len(secrets))
            toPrint = secrets[val]

        await ctx.send("Current droppin' locations: \n" + "".join(toPrint))

async def setup(bot):
    await bot.add_cog(FunTextCog(bot))


"""
3n+1 problem
7  -> 22 -> 11 -> 34 -> 17 -> 52 -> 26 -> 13 -> 40 -> 20 -> 10 -> 5
16 ->  8 ->  4 ->  2 -> (1)
14:25
"""

def fun(n):
    sequence = [n]
    while n > 1:
        n = n // 2 if n % 2 == 0 else 3 * n + 1
        sequence.append(n)
    return sequence

sequences = []
for n in range(2, 1_000_000):
    sequence = fun(n)
    sequences.append(sequence)
    # print(f"{n}: {len(sequence)}")

sequences.sort(key=lambda sequence: len(sequence), reverse=True)
print(f"{sequences[0][0]}: {len(sequences[0])}")
print(sequences[0])
# 837799 = 653 * 1283


#!/usr/bin/env python
import pika

# basic queue receiver example
credentials = pika.PlainCredentials('rabbitmq', 'rabbitmq')
parameters = pika.ConnectionParameters('queenbee.local',
                                       5673,
                                       '/',
                                       credentials)
connection = pika.BlockingConnection(parameters)

channel = connection.channel()

# declare our queue - this name needs to match value in send.py
channel.queue_declare(queue='hello')

# callback for received message
def callback(ch, method, properties, body):
    print(" [x] Received %r" % body)

# Register listener
# no_ack parameter turns off message acknowledgement
channel.basic_consume(callback,
                      queue='hello',
                      no_ack=True)

print(' [*] Waiting for messages. To exit press CTRL+C')

# loop until canceled
channel.start_consuming()


#!/usr/bin/python
# -*- coding: utf-8 -*-
# coding=utf-8

import csv
import ldap
import logging
import os

from biblib.services import config_service

config = config_service.config["ldap"]

def ldap_search(ldap_base_dn, ldap_filter, ldap_attrs):
    ldap_con = ldap.initialize(config["host"], config["port"])
    ldap_con.simple_bind_s(config["dn"], config["password"])
    ldap_results = ldap_con.search_s(ldap_base_dn, ldap.SCOPE_SUBTREE, ldap_filter, ldap_attrs)
    results = []
    for dn, entry in ldap_results:
        results.append(entry)
    #logging.debug(results)
    return results

def ldap_search_user_by_identifier(identifier):
    ldap_base_dn = 'ou=Users,o=sciences-po, c=fr'
    ldap_filter = "(|(scpoLibraryNumber=*{0})(scpoBannerID=*{0})(scpoTeacherNumber=*{0})(scpoStudentNumber=*{0})(uid=*{0}))".format(identifier)
    ldap_attrs = ['uid', 'employeeType', 'scpoLibraryNumber', 'scpoBannerID', 'scpoTeacherNumber', 'scpoStudentNumber']
    ldap_search(ldap_base_dn, ldap_filter, ldap_attrs)

def ldap_search_user_by_employeetype(employeetype):
    ldap_base_dn = 'ou=Users,o=sciences-po, c=fr'
    ldap_filter = "(employeeType=*{0})".format(employeetype)
    ldap_attrs = ['uid', 'givenName', 'sn', 'employeeType', 'scpoActifSI', 'scpoLibraryNumber', 'scpoBannerID', 'scpoTeacherNumber', 'scpoStudentNumber', 'scpoDateEntree', 'scpoDateSortie', 'mailForwardingAddress', 'scpoBannerStatus', 'scpoSynchroBanner', 'scpoGestionnairePrincipal', 'scpoEmployeeDSP']
    results = ldap_search(ldap_base_dn, ldap_filter, ldap_attrs)
    csv_file_name = "".join(["ldap-", employeetype, ".csv"])
    csv_file_path = os.path.join(os.path.dirname(__file__), os.pardir, os.pardir, "data", "result", csv_file_name)
    with open(csv_file_path, "wb") as csv_file:
        fieldnames = ldap_attrs
        csvwriter = csv.DictWriter(csv_file, delimiter=',', fieldnames=fieldnames)
        csvwriter.writeheader()
        for item in results:
            for key, value in item.items():
                item[key] = "; ".join(sorted(value))
            csvwriter.writerow(item)

def ldap_search_user_by_scporesearchcommunity():
    ldap_base_dn = 'ou=Users,o=sciences-po, c=fr'
    ldap_filter = "(scpoResearchCommunity=1)"
    ldap_attrs = ['uid', 'givenName', 'sn', 'employeeType', 'scpoActifSI', 'scpoLibraryNumber', 'scpoBannerID', 'scpoTeacherNumber', 'scpoStudentNumber', 'scpoResearchResearchCenter', 'scpoDateEntree', 'scpoDateSortie', 'mailForwardingAddress', 'scpoBannerStatus', 'scpoSynchroBanner', 'scpoGestionnairePrincipal', 'scpoEmployeeDSP']
    results = ldap_search(ldap_base_dn, ldap_filter, ldap_attrs)
    csv_file_name = "".join(["ldap-scporesearchcommunity.csv"])
    csv_file_path = os.path.join(os.path.dirname(__file__), os.pardir, os.pardir, "data", "result", csv_file_name)
    with open(csv_file_path, "wb") as csv_file:
        fieldnames = ldap_attrs
        csvwriter = csv.DictWriter(csv_file, delimiter=',', fieldnames=fieldnames)
        csvwriter.writeheader()
        for item in results:
            for key, value in item.items():
                item[key] = "; ".join(sorted(value))
            csvwriter.writerow(item)

#ldap_search_user_by_identifier("11001829")
#ldap_search_user_by_employeetype("LECTEUR")
ldap_search_user_by_scporesearchcommunity()


import socket

sock = socket.socket()

address = 'localhost'
port = input('Input port: ')
#ort = 9000
if not port:
    port = 9000
else:
    port = int(port)

sock.setblocking(True)
sock.connect((address, port))
print('Server connection')

while True:
    sent = input('Input sentence: ')
    if sent == 'exit':
        sock.close()
        print('Disconnection')
        break

    sock.send(sent.encode())
    data = sock.recv(1024)
    print(data.decode())
    print('Receiving data')

print('Sending data')


#!/usr/bin/env python
# -*- coding: utf-8 -*-

from io import open

import sys
import os
import re
import tempfile

multiproc = False
try:
    from multiprocessing import Pool
    multiproc = True
except:
    pass

from difflib import unified_diff

from LedgerHarness import LedgerHarness

args = sys.argv
jobs = 1
match = re.match('-j([0-9]+)?', args[1])
if match:
    args = [args[0]] + args[2:]
    if match.group(1):
        jobs = int(match.group(1))
if jobs == 1:
    multiproc = False

harness = LedgerHarness(args)
tests   = args[3]

if not os.path.isdir(tests) and not os.path.isfile(tests):
    sys.stderr.write("'%s' is not a directory or file (cwd %s)" %
                     (tests, os.getcwd()))
    sys.exit(1)

class RegressFile(object):
    def __init__(self, filename):
        self.filename = filename
        self.fd = open(self.filename, encoding='utf-8')

    def transform_line(self, line):
        line = line.replace('$sourcepath', harness.sourcepath)
        line = line.replace('$FILE', os.path.realpath(self.filename))
        return line

    def read_test(self):
        test = {
            'command':  None,
            'output':   None,
            'error':    None,
            'exitcode': 0
        }

        in_output = False
        in_error  = False

        line = self.fd.readline()
        if sys.version_info.major == 2 and type(line) is str:
            line = unicode(line, 'utf-8')
        while line:
            if line.startswith("test "):
                command = line[5:]
                match = re.match('(.*) -> ([0-9]+)', command)
                if match:
                    test['command'] = self.transform_line(match.group(1))
                    test['exitcode'] = int(match.group(2))
                else:
                    test['command'] = command
                in_output = True

            elif in_output:
                if line.startswith("end test"):
                    in_output = in_error = False
                    break
                elif in_error:
                    if test['error'] is None:
                        test['error'] = []
                    test['error'].append(self.transform_line(line))
                else:
                    if line.startswith("__ERROR__"):
                        in_error = True
                    else:
                        if test['output'] is None:
                            test['output'] = []
                        test['output'].append(self.transform_line(line))

            line = self.fd.readline()
            if sys.version_info.major == 2 and type(line) is str:
               line = unicode(line, 'utf-8')
            #print("line =", line)

        return test['command'] and test

    def notify_user(self, msg, test):
        print(msg)
        print("--")
        print(self.transform_line(test['command']),)
        print("--")

    def run_test(self, test):
        use_stdin = False
        if sys.platform == 'win32':
            test['command'] = test['command'].replace('/dev/null', 'nul')
            # There is no equivalent to /dev/stdout, /dev/stderr, /dev/stdin
            # on Windows, so skip tests that require them.
            if '/dev/std' in test['command']:
                harness.success()
                return
        if test['command'].find("-f ") != -1:
            test['command'] = '$ledger ' + test['command']
            if re.search("-f (-|/dev/stdin)(\s|$)", test['command']):
                use_stdin = True
        else:
            test['command'] = (('$ledger -f "%s" ' %
                                os.path.realpath(self.filename)) +
                               test['command'])

        p = harness.run(test['command'],
                        columns=(not re.search('--columns', test['command'])))

        if use_stdin:
            fd = open(self.filename, encoding='utf-8')
            try:
                stdin = fd.read()
                if sys.version_info.major > 2:
                    stdin = stdin.encode('utf-8')
                p.stdin.write(stdin)
            finally:
                fd.close()
        p.stdin.close()

        success = True
        printed = False
        index   = 0
        if test['output'] is not None:
            process_output = harness.readlines(p.stdout)
            expected_output = test['output']
            if sys.platform == 'win32':
                process_output = [l.replace('\r\n', '\n').replace('\\', '/')
                                  for l in process_output]
                # Replace \ with / in the expected output because the line above
                # makes it impossible for the process output to have a \.
                expected_output = [l.replace('\\', '/') for l in expected_output]

            for line in unified_diff(expected_output, process_output):
                index += 1
                if index < 3:
                    continue
                if not printed:
                    if success: print
                    self.notify_user("FAILURE in output from %s:" % self.filename, test)
                    success = False
                    printed = True
                if sys.version_info.major == 2 and type(line) is str:
                    line = unicode(line, 'utf-8')
                print(' ', line,)

        printed = False
        index   = 0
        process_error = harness.readlines(p.stderr)
        if test['error'] is not None or process_error is not None:
            if test['error'] is None:
                test['error'] = []
            if sys.platform == 'win32':
                process_error = [l.replace('\r\n', '\n').replace('\\', '/')
                                 for l in process_error]
                test['error'] = [l.replace('\\', '/') for l in test['error']]
            for line in unified_diff(test['error'], process_error):
                index += 1
                if index < 3:
                    continue
                if not printed:
                    if success: print
                    self.notify_user("FAILURE in error output from %s:"
                                     % self.filename, test)
                    success = False
                    printed = True
                print(" ", line,)

        if test['exitcode'] == p.wait():
            if success:
                harness.success()
            else:
                harness.failure(os.path.basename(self.filename))
                print("STDERR:")
                print(p.stderr.read())
        else:
            if success: print
            self.notify_user("FAILURE in exit code (%d != %d) from %s:"
                             % (test['exitcode'], p.returncode, self.filename),
                             test)
            harness.failure(os.path.basename(self.filename))

    def run_tests(self):
        if os.path.getsize(self.filename) == 0:
          print("WARNING: Empty testfile detected: %s" % (self.filename), file=sys.stderr)
          harness.failure(os.path.basename(self.filename))
          return False
        test = self.read_test()
        while test:
            self.run_test(test)
            test = self.read_test()

    def close(self):
        self.fd.close()

def do_test(path):
    entry = RegressFile(path)
    entry.run_tests()
    entry.close()

if __name__ == '__main__':
    if multiproc:
        pool = Pool(jobs*2)
    else:
        pool = None

    if os.path.isdir(tests):
        tests = [os.path.join(tests, x)
                 for x in os.listdir(tests)
                 if (x.endswith('.test') and
                     (not '_py.test' in x or (harness.python and
                                              not harness.verify)))]
        if pool:
            pool.map(do_test, tests, 1)
        else:
            map(do_test, tests)
    else:
        entry = RegressFile(tests)
        entry.run_tests()
        entry.close()

    if pool:
        pool.close()
        pool.join()

    harness.exit()