Esempio n. 1
0
def events():
    if var.event in var.close:
        var.terminate = True
    elif var.event == "Checkin":
        var.active = 2
        var.window.close()
        f.exgenwin()
    elif var.event == "override":
        var.active = 1
        var.window.close()
        f.exgenwin()
def events4():
    if var.event in var.close:
        var.terminate = True
    elif var.event == 'Home':
        var.active = 0
        var.window.close()
        f.exgenwin()
    elif var.event == 'Back':
        var.active = 2
        var.window.close()
        f.exgenwin()
Esempio n. 3
0
 def __init__(
     self,
     frame,
     func=None,
     arg=None
 ):  # initialises the stream and video size, frames and video capture, func can be used to
     # alter stream
     self.frame = frame
     self.func = func
     self.arg = arg
     self.vcap = None
     self.vWidth = None
     self.vHeight = None
     self.vFPS = None
     self.vFrame = tk.Frame(self.frame.frame.gui.FrameRight.frame,
                            width=400)
     self.stream = tk.Label(self.vFrame)
     self.stream.grid(row=0, column=0)
     try:
         self.vcap = Func.openVideoCapture()
         self.vWidth = self.vcap.get(cv2.CAP_PROP_FRAME_WIDTH)
         self.vHeight = self.vcap.get(cv2.CAP_PROP_FRAME_HEIGHT)
         self.vFPS = self.vcap.get(cv2.CAP_PROP_FPS)
         self.stream.after(int(1000 / self.vFPS / 2),
                           lambda: self.streamFrame(self.stream, self.vcap))
     except:
         self.frame.frame.writeToInfo("Camera not connected")
Esempio n. 4
0
    def Send(self, text):
        # Geheimen inladen
        smtp = self.config["Runtime"]["secrets"]["email_server"]
        user = self.config["Runtime"]["secrets"]["email_username"]
        password = self.config["Runtime"]["secrets"]["email_password"]

        # Verbind met mailserver
        mailserver = smtplib.SMTP(smtp)
        mailserver.ehlo()
        mailserver.starttls()
        mailserver.ehlo()
        mailserver.login(user, password)

        # Mailbericht opbouwen
        message = MIMEMultipart('alternative')

        goede = f.Goede(self.config)

        message['Subject'] = goede
        message['From'] = goede + " <" + user + ">"
        message['To'] = self.emailadres

        html = text
        message.attach(MIMEText(html, "html", "utf-8"))

        # E-mail versturen
        mailserver.sendmail(user, self.emailadres, message.as_string())

        # Verbinding sluiten
        mailserver.close()
Esempio n. 5
0
    def Run(self):
        # Load the database
        self.conn = f.getDatabase(
            self.config_full, "muspy", "CREATE TABLE Muspy (id text, title text, updated text, notified int)")
        cursor = self.conn.cursor()

        # Haal de feed op
        feed = feedparser.parse(self.config["feed"])
        for item in feed["items"]:
            # Werk database bij
            self.UpdateDB(item["id"], item["title"], item["updated"])

        # Opslaan
        self.conn.commit()

        c_update = self.conn.cursor()
        # Zoek alle ongemelde releases voor vandaag, of het verleden. Sqlite heeft geen date functies, maar zo kan het ook
        results = cursor.execute("SELECT id, title, updated FROM Muspy WHERE substr(updated,0, 5) || substr(updated, 6, 2) || substr(updated, 9, 2) < ? and notified = 0;",
                                 (datetime.datetime.now().strftime("%Y%m%d"),))
        for release in results:
            self.hasText = True
            self.text += release[1] + "<br/>"

            # Opslaan dat de notificatie verstuurd is.
            c_update.execute(
                "UPDATE Muspy SET notified = 1 WHERE id = ?", (release[0],))

        # Header toevoegen
        if self.hasText:
            self.conn.commit()
            self.text = "<h2>Nieuwe releases</h2>" + self.text

        cursor.close()
        c_update.close()
        self.conn.close()
Esempio n. 6
0
    def Caldav(self):
        # Verbinding maken met CalDav agenda
        client = caldav.DAVClient(self.config["url"])
        principal = client.principal()
        calendars = principal.calendars()

        first_all = True
        # Lus door de beschikbare agenda's heen
        for calendar in calendars:
            # Zoek de naam hiervan op
            calendar_name = calendar.get_properties([
                dav.DisplayName(),
            ])["{DAV:}displayname"]

            # Alleen doorgaan indien de agenda in de 'calendars' config regel staat
            if calendar_name in self.config["calendars"]:
                first = True

                now = f.Now(self.config_full)

                # Evenementen voor vandaag zoeken, met een beetje buffer terug in de tijd.
                results = calendar.date_search(now - timedelta(hours=2),
                                               now + timedelta(days=1))
                for vevent in results:
                    event = Event(client=client, url=vevent.url)
                    event.load()

                    # Oke.. in de documentatie niks over hoe hier een nette string van te maken
                    # En in het object zelf zit ook niet echt een functie daarvoor, los van __str()__
                    start = event.instance.vevent.dtstart.__str__()
                    summary = event.instance.vevent.summary.__str__()
                    # Zo kan het ook.
                    summary = summary.replace("<SUMMARY{}", "")[:-1]
                    # Dit komt binnen: <DTSTART{'X-VOBJ-ORIGINAL-TZID': ['Europe/Amsterdam']}
                    # Dus split op } en dan de eerste verwijderen, en het > teken achteraan verwijderen
                    start = parse(''.join(start.split("}")[1:])[:-1])

                    # Eerste event in deze agenda? Toon de agenda naam
                    if first:
                        # Niet de eerste agenda? Extra witregel
                        if not first_all:
                            self.text += "<br/>"

                        self.text += "<h3>" + calendar_name + "</h3>"
                        first = False
                        first_all = False

                    # Event samenvatting (tijd + omschijving) toevoegen aan de text
                    dt = "%A %H:%M"
                    if (calendar_name.lower().find("birthday") >= 0
                            or calendar_name.lower().find("verjaardag") >= 0):
                        dt = "%A"

                    self.text += "{0} {1}<br/>".format(start.strftime(dt),
                                                       summary)

        if not first_all:
            self.hasText = True
Esempio n. 7
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("-c", "--clear", default=False, action="store_true", help="Clears all settings")
    parser.add_argument("-i", "--ip", nargs=2, help="Block or allow a certain ip **Usage: -i (block | block+ | allow) ip**")
    parser.add_argument('-s', '--start', default=False, action='store_true', help="Starts the firewall")
    parser.add_argument('-d', '--download', default=False, action='store_true', help='downloads dependencies')
    parser.add_argument('-r', '--restart', default=False, action='store_true', help='restarts system')
    parser.add_argument('-p', '--printstatus', default=False, action='store_true', help='Prints status')
    args = parser.parse_args()


    if(args.ip is not None):
        try:
            socket.inet_aton(args.ip[1])
        except socket.error:
            print("IP address was not valid, please enter a valid ip address")
            args.print_help()
            sys.exit(0)
        if(args.ip[0] == "block+"):
            os.system("sudo iptables -A INPUT -p tcp --dport ssh -s {} -j DROP".format(args.ip[1]))
        elif(args.ip[0] == "block"):
            os.system("sudo iptables -A INPUT -s {} -j DROP".format(args.ip[1]))
        elif(args.ip[0] == "allow"):
            os.system("sudo iptables -A INPUT -s {} -j ACCEPT".format(args.ip[1]))
        else:
            print("You entered something wrong")
            args.print_help()
            sys.exit()
    elif(args.clear):
        Stop.new()
        clear_all_rules.new()
    elif(args.start):
        Start.new()
        input_config.new()
    elif(args.download):
        Functions.install()
    elif(args.restart):
        Stop.new()
        clear_all_rules.new()
        Start.new()
        input_config.new()
    elif(args.printstatus):
        CheckIp.new()
    else:
        args.print_help()
Esempio n. 8
0
def events():
    if var.event in var.close:
        var.terminate = True
    elif var.event == 'Home':
        var.active == 0
    elif len(var.passw) == 4:
        if var.passw == var.correctPass:
            var.LoggedIn = True
            var.window.close()
        else:
            var.passw = ''
    elif var.event in var.numbers:
        var.passw += var.event
        var.window.FindElement('passShow').update(
            value=f.PassToSecret(var.passw))
    elif var.event == 'Correct':
        var.passw = ''
        var.window.FindElement('passShow').update(
            value=f.PassToSecret(var.passw))
Esempio n. 9
0
    def Run(self):
        now = f.Now(self.config_full)

        with urllib.request.urlopen(self.config["url"]) as url:
            data = url.read()

        servers = json.loads(data)

        for server in servers:
            if not server in self.config["servers"]:
                continue

            ping = f.GetDateTimeWithTZ(self.config_full,
                                       (datetime.datetime.fromtimestamp(
                                           int(servers[server]["ping"]))))
            diffhour = ((now - ping).total_seconds() / 60 / 60)

            if (diffhour > int(self.config["servers"][server])):
                self.text += server + " is al " + \
                    str(round(diffhour, 2)) + " uur stil.<br />"
                self.hasText = True
Esempio n. 10
0
    def Run(self):
        # Load the syncthing API
        s = SyncthingWrapper(self.config["apikey"], self.config["host"],
                             str(self.config["port"]))

        # Load a database to keep the status
        conn = f.getDatabase(
            self.config_full, "syncthing",
            "CREATE TABLE Syncthing (folder text, file text, modified_date text)"
        )
        cursor = conn.cursor()

        folders_metadata = s.system.config()["folders"]

        for folder_id in self.config["folders"]:
            # Default label als de folder label niet gevonden kan worden
            label = "Nieuwe bestanden"

            # Find the label
            for metadata in folders_metadata:
                if metadata["id"] == folder_id:
                    label = metadata["label"]

            # Load all filenames with API
            for file, metadata in s.database.browse(folder_id).items():
                modified_date = metadata[0]

                # Check if the notification for this file has already been sent
                cursor.execute(
                    "SELECT file FROM Syncthing WHERE folder = ? AND file = ?",
                    (
                        folder_id,
                        file,
                    ))
                result = cursor.fetchone()

                # If not, send the notification and keep history
                if result is None:
                    cursor.execute("INSERT INTO Syncthing values (?, ?, ?)",
                                   (folder_id, file, modified_date))

                    if label:
                        self.text += "<h3>" + label + "</h3>"
                        label = ""

                    self.text += (file + "<br />")
                    self.hasText = True

        cursor.close()

        # Opslaan
        conn.commit()
Esempio n. 11
0
    def Run(self):
        now = f.Now(self.config_full)

        # Na 11u is het toch al te laat
        if now.hour < 11:
            # Dag van vandaag
            weekday = now.weekday()

            # Staat vandaag in de config file?
            if str(weekday) in self.config:
                self.hasText = True
                self.text = "Vandaag moet het " + \
                    self.config[str(weekday)] + " bij de weg"
Esempio n. 12
0
 def streamFrame(self, label,
                 vcap):  # streams the video and refreshes matching the fps
     if self.vcap:
         success, img = vcap.read()
         try:
             self.func(img, self.arg)
         except:
             pass
         wHeight = self.frame.frame.gui.window.winfo_height()
         wWidth = self.frame.frame.gui.window.winfo_width()
         tempWidth = int(wWidth / self.vWidth * 0.5 * self.vWidth)
         tempHeight = int(wWidth / self.vWidth * 0.5 * self.vHeight)
         img = cv2.resize(img, (tempWidth, tempHeight))
         label.after(int(1000 / self.vFPS / 2),
                     lambda: self.streamFrame(label, vcap))
         photo = Func.cv2ToTk(img)
         label.config(image=photo)
         label.image = photo
Esempio n. 13
0
def genwin2():
    var.layout = [[sg.Text('information read from the QR code')],
                  [
                      sg.Text("begin: " + str(var.Date.time()) + ", end: " +
                              str(f.get_end(var.Date, var.Time)))
                  ],
                  [
                      sg.Text("Time Remaining: "),
                      sg.Text("", size=(20, 1), key="Time")
                  ],
                  [
                      sg.ProgressBar(var.length,
                                     orientation='h',
                                     size=(70, 20),
                                     key='status')
                  ], [sg.Button('Back'), sg.Button('Home')]]

    var.window = sg.Window('Checkedin', var.layout, size=(1024, 600))
Esempio n. 14
0
    def Run(self):
        # Generate the API URL
        api_url = "{0}/rest/getNewestPodcasts?u={1}&p={2}&v=1.12.0&c=goedemorgen".format(
            self.config["url"], self.config["user"], self.config["password"])

        # Download the API response
        response = requests.get(api_url, stream=True)
        response.raw.decode_content = True

        # Parse the API response
        parser = etree.XMLParser(ns_clean=True, recover=True)
        tree = etree.parse(response.raw, parser)

        # Load up the database
        self.conn = f.getDatabase(self.config_full, "subsonic",
                                  "CREATE TABLE Subsonic (id text, podcast text, title text)")

        for elem in tree.iter():
            # Filter out the episodes from the result
            if elem.tag.endswith("episode"):
                id = elem.attrib['id']
                podcast = elem.attrib['album']
                title = elem.attrib['title']

                cursor = self.conn.cursor()

                # Check if the episode has already been notified
                cursor.execute(
                    "SELECT title FROM Subsonic WHERE id = ?", (id,))
                result = cursor.fetchone()

                # If not, notify.
                if result is None:
                    cursor.execute(
                        "insert into Subsonic values (?, ?, ?)", (id, podcast, title))
                    self.text += ("{0} - {1}<br />".format(podcast, title))
                    self.hasText = True

                cursor.close()

        self.conn.commit()

        if self.hasText:
            self.text = "<h3>Nieuwe podcasts</h3>" + self.text
Esempio n. 15
0
def events2():
    if var.countdown:
        if datetime.now().time() < var.end:
            var.remaining = f.totime(
                datetime.combine(date.today(), var.end) - datetime.now())
            var.window.FindElement("Time").update(value=str(var.remaining))
            var.window['status'].update_bar(var.length -
                                            f.toseconds(var.remaining))
    if var.event in var.close:
        var.terminate = True
    elif var.event == 'Home':
        var.active = 0
        var.window.close()
        f.exgenwin()
    elif var.event == 'Back':
        var.active = 2
        var.window.close()
        f.exgenwin()
Esempio n. 16
0
 def safeScreenshot(self):  # safes a screenshot, but without function
     success, img = self.vcap.read()
     filename = "screenshot " + Func.getTimeStamp(
         "%d-%b-%Y %H-%M-%S") + ".jpg"
     cv2.imwrite(filename, img)
     self.frame.frame.writeToInfo("Screenshot saved")
Esempio n. 17
0
    def Run(self):
        now = f.Now(self.config_full)
        dag = now.strftime("%A").lower()

        # Url checken en eventueel fixen zodat ik folder+file kan doen
        if self.config["folder"][-1:] != "/":
            self.config["folder"] += "/"

        if "weekly" in self.config:
            if self.config["weekly"][:1] == "/":
                self.config["weekly"] = self.config["weekly"][1:]

            weekly_url = self.config["folder"] + self.config["weekly"]

            weekly_url = weekly_url.replace("[year]", "[jaar]")
            weekly_url = weekly_url.replace("[week]",
                                            str(now.isocalendar()[1]))
            weekly_url = weekly_url.replace("[jaar]", str(now.year))

            response = requests.get(weekly_url)

            if response.status_code == 200:
                weekly = response.text

                # Zoek op ## Dag
                weeklyDagIndex = weekly.lower().find("## " + dag)
                # index = start van ## Dag t/m eof, GetBlock kapt hem op de volgende ## af
                weeklyDag = self.GetBlock(weekly[weeklyDagIndex:])

                # Filter alle uitgevoerde taken
                weeklyDag = self.FilterDone(weeklyDag)

                # Openstaande punten uit vorige dagen
                laatsteDag = ""
                firstDag = True
                histText = ""
                # DagIndex = index van vandaag, alles daarvoor is al geweest, dus scannen op gemist.
                for regel in weekly[:weeklyDagIndex].split("\n"):
                    if regel.find(
                            "## "
                    ) >= 0:  # Dag onthouden om in het bericht te zetten
                        laatsteDag = regel
                        firstDag = True
                    if regel.find("[ ]") >= 0:
                        if firstDag:
                            histText += laatsteDag + "\n"
                            firstDag = False

                        histText += regel + "\n"

                histText = histText.rstrip()

                # Openstaande punten in de algemene ## TODO
                # .find = start van ## todo t/m eof, GetBlock kapt hem op de volgende ## af
                weeklyTodo = self.GetBlock(
                    weekly[weekly.lower().find("## todo"):])

                # Todo tekst opbouwen, alleen openstaande vinkjes
                todoText = self.FilterDone(weeklyTodo)

                # *# Tekst opbouwen

                # Gemiste punten van deze week toevoegen
                if histText != "":
                    self.hasText = True
                    self.text += histText + "\n\n"

                # Alle punten van vandaag toevoegen, indien er minimaal 1 openstaande is.
                if weeklyDag.find("[ ]") > 0:
                    self.hasText = True
                    self.text += weeklyDag + "\n\n"

                # Open algemene TODO toevoegen
                if todoText.find("[ ]") > 0:
                    self.hasText = True
                    self.text += todoText + "\n\n"

            # Omzetten naar HTML gezien main dat verwacht.
            self.text = f.plain2hml(self.text).rstrip()
Esempio n. 18
0
 def getAngles(self, batAngles):
     self.vcap = Func.openVideoCapture()
     success, img = self.vcap.read()
     Func.anglesBatteries(img, self.gui.config.batpos, batAngles)
     Func.closeVideoCapture(self.vcap)
Esempio n. 19
0
def events():
    if var.event in var.close:
        var.terminate = True
    elif var.event == 'Home':
        var.active = 0
        var.window.close()
        f.exgenwin()
    elif var.event == 'Checkin':
        var.QR_String = var.values['qr']
        f.QR_Extraction(var.QR_String)
        if var.Date.date() > datetime.now().date():
            var.indays = (var.Date.date() - datetime.now().date()).days
            var.active = 4
            var.window.close()
            f.exgenwin()
        elif var.Date > datetime.now():
            var.active = 5
            var.window.close()
            f.exgenwin()
#        elif datetime.combine(var.Date.date(),f.get_end(var.Date, var.Time)) < datetime.now() < var.Date:
        else:
            var.length = f.toseconds(
                datetime.strptime(var.Time, "%H:%M").time())
            var.end = f.get_end(var.Date, var.Time)
            var.countdown = True
            var.active = 3
            var.window.close()
            f.exgenwin()
Esempio n. 20
0
 pedopt,pedcov,pedxdata,pedydata,pedyunc = GainFinder.FitPedestal(
         thehist, init_params["PedParams"],init_params["PedFitRange"],
         fit_tail = FIT_TAIL, exp_fit_range = exp_fit_range)
 if pedopt is None:
     print("PEDESTAL FIT FULLY FAILED... LIKELY A BUNK CHANNEL.  SKIPPING")
     PedFitComplete = True
     GoodPedFit = False
     FitComplete = True
     GoodFit = False
     continue
 pl.PlotPedestal(pedxdata,pedydata,fu.gauss1,pedxdata,pedopt,"GaussPlusExpo")
 above_ped = 0
 past_ped = np.where(pedxdata > (pedopt[1] + 3*pedopt[2]))[0]
 if FIT_TAIL:
     plt.plot(pedxdata[past_ped],pedydata[past_ped])
     plt.plot(pedxdata[past_ped],fu.expo(pedxdata[past_ped],pedopt[3],
                        pedopt[4],pedopt[5]))
     above_ped = np.sum(pedydata[past_ped] - fu.expo(pedxdata[past_ped],pedopt[3],
                        pedopt[4],pedopt[5]))
 else:
     above_ped = np.sum(pedydata[past_ped] - fu.gauss1(pedxdata[past_ped],pedopt[0],
                       pedopt[1],pedopt[2]))
 plt.show()
 print("4SIGMA PAST PED, EXP. SUBTRACTED: " + str(above_ped))
 if (above_ped < 300):
     print("Low statistics beyond pedestal!  May just be fitting on fluctuations.")
     skip_fit = str(raw_input("Skip this fit?"))
     if skip_fit in ["y","Y","yes","Yes","YES"]:
         PedFitComplete = True
         GoodPedFit = False
         FitComplete = True
         GoodFit = False
Esempio n. 21
0
    def Run(self):
        # Grab 2 pages from sonarr since there is a lot more activity. This should be dynamic but ohwell it works.
        urls = [
            "{0}/history?apikey={1}&sortKey=date&sortDir=desc&pageSize=20&page=1".format(
                self.config["sonarr"]["url"], self.config["sonarr"]["apikey"]),
            "{0}/history?apikey={1}&sortKey=date&sortDir=desc&pageSize=20&page=2".format(
                self.config["sonarr"]["url"], self.config["sonarr"]["apikey"]),
            "{0}/history?apikey={1}&sortKey=date&sortDir=desc&pageSize=20&page=1".format(
                self.config["radarr"]["url"], self.config["radarr"]["apikey"])
        ]

        # Setup DB to keep the notified history
        self.conn = f.getDatabase(
            self.config_full, "sonarrradarr", "CREATE TABLE Records (id text, title text)")
        cursor = self.conn.cursor()

        # Download each api result
        for url in urls:
            with urllib.request.urlopen(url) as url:
                data = json.loads(url.read())
                records = data["records"]

                for record in records:
                    # Only use the 'import' event so you only get notified if the download was successfull
                    if record["eventType"] != "downloadFolderImported":
                        continue

                    # Generate the 'unique' and 'title' values for episodes or movies
                    if "episode" in record:
                        unique = "episode_{0}_{1}".format(
                            record["seriesId"], record["episodeId"])
                        serieTitle = record["series"]["title"]
                        episodeTitle = record["episode"]["title"]
                        episodeNumber = "S{:02}E{:02}".format(
                            record["episode"]["seasonNumber"], record["episode"]["episodeNumber"])

                        title = "{0}: {1} - {2}".format(
                            episodeNumber, serieTitle, episodeTitle)

                    elif "movie" in record:
                        unique = "movie_{0}".format(record["movieId"])
                        title = record["movie"]["title"]
                    else:
                        continue

                    # Check if the episode/movie has already been notified
                    cursor.execute(
                        "SELECT title FROM Records WHERE id = ?", (unique,))
                    result = cursor.fetchone()

                    # If not, notify.
                    if result is None:
                        cursor.execute(
                            "insert into Records values (?, ?)", (unique, title))

                        self.text += ("{0}<br />".format(title))
                        self.hasText = True

        cursor.close()

        # Save the history to sqlite
        self.conn.commit()
def OrderStat(x,A,n,mu,s):
    return (n/s)*fu.gauss1(x,A,mu,s)*((1./2)*((1 + sps.erf((x-mu)/s)))**(n-1))
Esempio n. 23
0
 def Send(self, text):
     pb = Pushbullet(self.config["Pushbullet"]["apikey"])
     pb.push_note(f.Goede(self.config), f.html2plain(text))
Esempio n. 24
0
import lib.GlobalVariables as var
import lib.Functions as f
from datetime import datetime, date
f.exgenwin()
while True:
    if var.terminate:
        break
    else:
        var.event, var.values = var.window.read(timeout=0)
        f.eventcheck()
Esempio n. 25
0
#Import modules
import os
from lib import Functions

run = "y"

while run == "y":
        if os.name == "nt":
                os.system("cls")
        else:
                os.system("clear")

        Functions.splitcsv()

        print("\n\n\nEnd of program. Would you like to run another task?")
        print("(Y/N) ", end="")
        run = input().lower()

Esempio n. 26
0
 def writeToLogFile(self, content):
     self.logFile = open(self.logFileName, "a")
     self.logFile.write(Func.getTimeStamp() + " " + content + '\n')
     self.logFile.close()
Esempio n. 27
0
    def Run(self):
        # Een textfile met de API-key. Met name om de key uit git te houden, en niet te hardcoden.
        apikey = self.config_full["Runtime"]["secrets"]["darksky_apikey"]

        temperatureKey = "temperature"
        if 'gevoel' in self.config:
            if self.config["gevoel"]:
                temperatureKey = "apparentTemperature"

        # Cache de API verzoeken in een map per dag.
        filename = "{0}/Weer{1}_{2}.json".format(self.config_full["Runtime"]["datadir"], str(
            self.config["lang"]), str(self.config["long"]))

        now = f.Now(self.config_full)

        # Alleen cachen op test verzoeken, ik blijf toch wel onder de max api calls
        if os.path.exists(filename) and not self.config_full["Runtime"]["production"]:
            data = open(filename).read()

        else:
            # Bouw de URL voor de API-call op en maak een weer object
            with urllib.request.urlopen("https://api.darksky.net/forecast/{0}/{1},{2}?units=si".format(apikey, str(self.config["lang"]), str(self.config["long"]))) as url:
                data = url.read()

            with open(filename, 'w') as outfile:
                json.dump(json.loads(data), outfile)

        weather = json.loads(data)

        # Weerbericht opbouwen op basis van voorkeurs tijden.
        if "tijden" in self.config:
            text_builder = ""

            weekday = now.weekday()

            # Wil je vandaag een voorspelling?
            if str(weekday) in self.config["tijden"]:

                # Stats voor het advies
                minTemp = 99
                maxTemp = -99
                maxRegen = 0

                # Voor elk uur de voorspelling opzoeken
                for data in weather["hourly"]["data"]:
                    hour = datetime.datetime.utcfromtimestamp(
                        data["time"]).hour
                    day = datetime.datetime.utcfromtimestamp(data["time"]).day

                    # Alleen de voorspelling van vandaag gebruiken
                    if day == now.day:
                        # Staat het uur in de gewenste tijden, en na het huidige uur?
                        if hour in self.config["tijden"][str(weekday)] and hour >= now.hour:
                            # Text opbouwen per tijd.
                            text_builder += "Om {0} uur is het {1}°".format(
                                hour, data[temperatureKey])
                            if (data["precipProbability"] >= 0.1):
                                perciptype = "regen"
                                if data["precipType"] == "snow":
                                    perciptype = "sneeuw"

                                text_builder += " met {0}% kans op {1}".format(
                                    round(data["precipProbability"]*100), perciptype)

                            if data[temperatureKey] < minTemp:
                                minTemp = data[temperatureKey]
                            if data[temperatureKey] > maxTemp:
                                maxTemp = data[temperatureKey]

                            if (data["precipProbability"] * 100) > maxRegen:
                                maxRegen = (data["precipProbability"] * 100)

                            text_builder += "<br/>"

                if text_builder != "":
                    # Advies opbouwen
                    advies = ""
                    if "advies" in self.config:
                        for key in self.config["advies"]:
                            if minTemp >= self.config["advies"][key]["min"] and maxTemp <= self.config["advies"][key]["max"] and maxRegen <= self.config["advies"][key]["regen"]:
                                advies = self.config["advies"][key]["advies"]
                                break

                    # Het instellen van advies op basis van parameters is een onmogelijke taak.
                    # Dus of heel veel in de config tweaken en super kleine advies sets maken, of nog iets in code verzinnen.
                    # We gaan het meemaken.. ok doei.
                    if advies != "":
                        text_builder += "Advies: " + advies

                    self.text = text_builder

                else:
                    self.hasText = False

            else:
                self.hasText = False

        else:
            # Standaard tekst
            self.text = u"Het is nu {0}° en het wordt vandaag tussen de {1}° en {2}°".format(
                weather["currently"][temperatureKey],
                weather["daily"]["data"][0]["temperatureLow"],
                weather["daily"]["data"][0]["temperatureHigh"])
Esempio n. 28
0
 def __init__(self, name='log'):
     self.name = 'log'
     self.logFileName = name + ' ' + Func.getTimeStamp("%d-%b-%Y %H-%M-%S") + ".log"
     self.logFile = open(self.logFileName, "w+")
     self.logFile.write(Func.getTimeStamp() + " " + "Start" + "\n")
     self.logFile.close()
Esempio n. 29
0
        config = Config(user).GetConfig()
    except Exception as e:
        print("Error: de config van {0} is niet correct.".format(user))
        run = False
        pass

    if run:
        # Set de locale, voor de tijd functies (agenda) en de tijd van de cron
        if 'Locale' in config:
            locale.setlocale(locale.LC_TIME,
                             '{0}.UTF-8'.format(config["Locale"]))

        # Checken of je de notificatie dit uur wilt ontvangen?
        run = False
        if 'Tijd' in config:
            if f.Now(config).hour in config["Tijd"]:
                run = True

    if run:

        userdir = "data/{0}/".format(user)
        if not os.path.isdir(userdir):
            os.makedirs(userdir)

        # Config extenden met runtime variabelen
        with open('secrets/secrets.json') as secrets:
            config['Runtime'] = {
                "datadir": datadir,
                "userdir": userdir,
                "secrets": json.load(secrets),
                "production": prod,
import matplotlib.pyplot as plt
import numpy as np
import scipy as scp
import scipy.optimize as sco
import scipy.stats as sts
import scipy.special as sps
import lib.Functions as fu

def OrderStat(x,A,n,mu,s):
    return (n/s)*fu.gauss1(x,A,mu,s)*((1./2)*((1 + sps.erf((x-mu)/s)))**(n-1))

maxes = []
for i in range(10000):
    maxes.append(np.max(scp.randn(30)))
    
bin_height, bin_edges = np.histogram(maxes,bins=100)
bin_width = bin_edges[1]-bin_edges[0]
bin_edges_t = bin_edges[0:len(bin_edges) -1]
bin_centers = np.array(bin_edges_t) - (bin_width/2)
popt,pcov = sco.curve_fit(fu.gauss1,bin_centers,bin_height,p0=[1000,2,2])
yfit = fu.gauss1(bin_centers,popt[0],popt[1],popt[2])
plt.hist(maxes,bins=100)
plt.plot(bin_centers,yfit)
plt.show()
popt,pcov = sco.curve_fit(OrderStat,bin_centers,bin_height,p0=[300,30,1,2],maxfev=10000)
yfit = OrderStat(bin_centers,popt[0],popt[1],popt[2],popt[3])
plt.hist(maxes,bins=100)
plt.plot(bin_centers,yfit)
plt.show()