from abc import ABCMeta, abstractmethod
from random import randint

class Account:
    @abstractmethod
    def create_account(self):
        return 0

    @abstractmethod
    def authenticate(self):
        return 0

    @abstractmethod
    def withdraw(self):
        return 0

    @abstractmethod
    def deposit(self):
        return 0

    @abstractmethod
    def display_balance(self):
        return 0

class SavingAccount(Account):
    def __init__(self):
        self.savingAccounts = {12345: ["ahmed", 200], 10002: ["salim", 350], 12354: ["ali", 1500]}

    def create_account(self, name, initial_deposit):
        self.account_number = randint(10000, 99999)
        self.savingAccounts[self.account_number] = [name, initial_deposit]
        print("\nYour account is successfully created, Your account number is {}\n".format(self.account_number))

    def authenticate(self, name, account_number):
        if account_number in self.savingAccounts.keys():
            if self.savingAccounts[account_number][0] == name:
                print("You have been authenticated successfully :) \n")
                self.account_number = account_number
                return True
            else:
                print("Wrong!, the name or the account number is wrong\n")
                return False
        else:
            print("Wrong!, the name or the account number is is wrong\n")
            return False

    def withdraw(self, withdraw_amount):
        if withdraw_amount > self.savingAccounts[self.account_number][1]:
            print("You don't have all that money ")
            self.display_balance(self.account_number)
        else:
            self.savingAccounts[self.account_number][1] -= withdraw_amount
            print("Withdraw Successful\n")
            self.display_balance(self.account_number)

    def deposit(self, deposit_amount):
        self.savingAccounts[self.account_number][1] += deposit_amount
        print("Deposited Successfully\n")
        self.display_balance(self.account_number)

    def display_balance(self, account_number):
        print("Available balance: {}\n".format(self.savingAccounts[account_number][1]))

savingAccount = SavingAccount()

while True:
    user_choice = input("""Enter 1 to create a new account
Enter 2 to access an existing account
Enter 3 to exit
> """)
    if user_choice == '1':
        name = input("Enter your name: ")
        while name == "":
            name = input("Enter your name: ")
        user_input = input("Enter an initial deposit: ")
        while not user_input.isdigit():
            user_input = input("Wrong input type, deposit should be a number, try again: ")
        initial_deposit = int(user_input)

        savingAccount.create_account(name, initial_deposit)

    elif user_choice == '2':
        auth = False
        name = input("Enter the name: ")
        user_input = input("Enter the account number: ")
        while not user_input.isdigit():
            user_input = input("Wrong input type, the account number should be a number, try again: ")
        accountNumber = int(user_input)
        while not savingAccount.authenticate(name, accountNumber):
            if input("press q to quit, or anything to continue > ") == "q":
                break
            name = input("Enter the name: ")
            user_input = input("Enter the account number: ")
            while not user_input.isdigit():
                user_input = input("Wrong input type, the account number should be a number, try again: ")
            accountNumber = int(user_input)
        else:
            auth = True
        while auth:
            user_choice = input(f"""Enter 1 to withdraw"
Enter 2 to deposit
Enter 3 to display balance
Enter 4 to exit
> """)
            if user_choice == '1':
                user_input = input("Enter withdraw amount : ")
                while not user_input.isdigit():
                    user_input = input("Wrong input type, the withdraw amount should be a number, try again: ")
                withdrawAmount = int(user_input)
                savingAccount.withdraw(withdrawAmount)
            elif user_choice == '2':
                user_input = input("Enter deposit amount : ")
                while not user_input.isdigit():
                    user_input = input("Wrong input type, the deposit amount should be a number, try again: ")
                deposit_amount = int(user_input)
                savingAccount.deposit(deposit_amount)
            elif user_choice == '3':
                savingAccount.display_balance(accountNumber)
            elif user_choice == '4':
                break
            else:
                print("I don't understand !!\n")
    elif user_choice == '3':
        quit()
    else:
        print("I don't understand !!\n")


import argparse
import numpy as np
import random as rnd
import librosa as lr
import os

import kissdsp.beamformer as bf
import kissdsp.filterbank as fb
import kissdsp.io as io
import kissdsp.masking as mk
import kissdsp.mixing as mx
import kissdsp.micarray as ma
import kissdsp.reverb as rb
import kissdsp.spatial as sp
import kissdsp.visualize as vz

import matplotlib.pyplot as plt

def main():

    parser = argparse.ArgumentParser()
    parser.add_argument('--speech_files', default='', type=str, help='File with list of wave files for speech.')
    parser.add_argument('--wave_duration', default=30, type=float, help='Wave file duration in second.')
    parser.add_argument('--silence_duration', default=0.5, type=float, help='Silence duration in second.')
    parser.add_argument('--sample_rate', default=16000, type=int, help='Sample rate (in samples/sec).')
    parser.add_argument('--number_sources', default=2, type=int, help='Number of speech sources.')
    parser.add_argument('--number_trials', default=10, type=int, help='Number of trials to fit speech signals in long sequence.')
    parser.add_argument('--index_start', default=1, type=int, help='Index of first feature to be generated.')
    parser.add_argument('--index_stop', default=1, type=int, help='Index of last feature to be generated.')
    parser.add_argument('--output', default='', type=str, help='Output directory to store features.')
    args = parser.parse_args()

    # Get list of files
    f = open(args.speech_files, 'r')
    paths = f.readlines()

    # Generate feature for each index
    for index in range(args.index_start, args.index_stop+1):

        # Create speech sources
        cs = []
        for source_index in range(0, args.number_sources):
            cs.append(concatenate_waves(files=paths,
                                        wave_duration=args.wave_duration,
                                        silence_duration=args.silence_duration,
                                        sample_rate=args.sample_rate,
                                        number_trials=args.number_trials))

        # Generate room
        room = configure_room(size=rnd.choice(['small', 'medium', 'large']),
                              micarray=rnd.choice(['respeaker_usb', 'respeaker_core', 'matrix_creator', 'matrix_voice', 'minidsp_uma']),
                              number_sources=args.number_sources,
                              rotate=True)

        # Create RIRs
        hs = rb.rir(room, sample_rate=args.sample_rate)

        # Split RIRs in target and interf
        hs_target = hs[[0], :, :]
        hs_interf = hs[1:, :, :]

        # Create target and interf sources
        snrs = np.random.uniform(low=-10, high=+10, size=(args.number_sources,))
        ss = np.zeros((len(cs), cs[0].shape[1]), dtype=np.float32)
        for source_index in range(0, args.number_sources):
            ss[source_index, :] = mx.pwr(cs[source_index], snrs[[source_index]])

        # Apply reverb
        xs_target = rb.conv(hs_target, ss[[0],:])
        xs_target += np.random.normal(size=xs_target.shape) * 1e-4
        xs_interf = rb.conv(hs_interf, ss[1:,:])
        xs_interf += np.random.normal(size=xs_interf.shape) * 1e-4
        xs = xs_target + xs_interf

        # STFT
        Xs = fb.stft(xs)

        # Compute time-difference-of-arrival of target speech
        tdoas = rb.tdoa(room)
        tdoa_t = tdoas[0,:]

        # Compute steering vectors using tdoa
        ws = sp.steering_tdoa(tdoa_t)

        # Perform phase-based frequency masking using the steering vector
        Zs = bf.pfm(Xs, ws)
        Ys_target = Zs[[0],:,:]
        Ys_interf = Zs[[1],:,:]

        # Go back to time-domain
        ys_target = fb.istft(Ys_target)
        ys_interf = fb.istft(Ys_interf)

        # Span full range
        vol_norm = max([ np.amax(np.abs(ys_target)),
                         np.amax(np.abs(ys_interf))])
        ys_target /= vol_norm
        ys_interf /= vol_norm

        # Apply new volume
        volume = np.random.uniform(low=-20, high=0)
        ys_target = mx.gain(ys_target, np.asarray([volume]))
        ys_interf = mx.gain(ys_interf, np.asarray([volume]))

        # Grabbing the ideal signal directly from the clean data
        ys_ideal = ss[[0],:]

        # Concatenate to a single multi-channel audio signal
        ys = np.concatenate([ ys_target, ys_interf, ys_ideal ], axis=0)

        # Save to file
        output_path = os.path.join(args.output, '%010d.wav' % index)
        io.write(ys, output_path)
        print(output_path)

def concatenate_waves(files, wave_duration, silence_duration, sample_rate, number_trials):

    wave_samples = int(wave_duration * sample_rate)
    silence_samples = int(silence_duration * sample_rate)

    s = np.zeros((1,wave_samples), dtype=np.float32)
    wave_samples_count = 0

    for trial in range(0, number_trials):

        while True:

            this_path = rnd.choice(files).rstrip()
            segment, _ = lr.load(path=this_path,
                                 sr=sample_rate,
                                 dtype=np.float32)

            segment = np.expand_dims(segment, axis=0)
            wave_samples_total = wave_samples_count + segment.shape[1]

            if wave_samples_count > 0:
                if wave_samples_total > wave_samples:
                    break
            else:
                if wave_samples_total > wave_samples:
                    segment = np.resize(segment,(1,wave_samples))
                    wave_samples_total = wave_samples

            segment_0dB = mx.pwr(segment, levels=np.asarray([0.0]))

            s[0, wave_samples_count:wave_samples_total] = segment_0dB
            wave_samples_count += segment.shape[1] + silence_samples

    return s

def configure_room(size, micarray, number_sources, margin=0.5, rotate=True):

    # Setup room dimensions

    if size == 'small':
        width = np.random.uniform(low=1, high=10, size=(1,))
        length = np.random.uniform(low=1, high=10, size=(1,))

    if size == 'medium':
        width = np.random.uniform(low=10, high=30, size=(1,))
        length = np.random.uniform(low=10, high=30, size=(1,))

    if size == 'large':
        width = np.random.uniform(low=30, high=50, size=(1,))
        length = np.random.uniform(low=30, high=50, size=(1,))

    height = np.random.uniform(low=2, high=5, size=(1,))

    box = np.concatenate([width, length, height], axis=0)

    # Choose microphone array (and rotate)

    if micarray == 'respeaker_usb':
        mics = ma.respeaker_usb()

    if micarray == 'respeaker_core':
        mics = ma.respeaker_core()

    if micarray == 'matrix_creator':
        mics = ma.matrix_creator()

    if micarray == 'matrix_voice':
        mics = ma.matrix_voice()

    if micarray == 'minidsp_uma':
        mics = ma.minidsp_uma()

    if rotate == True:

        theta_x = np.random.uniform(low=0, high=2*np.pi)
        theta_y = np.random.uniform(low=0, high=2*np.pi)
        theta_z = np.random.uniform(low=0, high=2*np.pi)

        Rx = np.asarray([[1, 0, 0],
                         [0, np.cos(theta_x), -np.sin(theta_x)],
                         [0, np.sin(theta_x), np.cos(theta_x)]])
        Ry = np.asarray([[np.cos(theta_y), 0, np.sin(theta_y)],
                         [0, 1, 0],
                         [-np.sin(theta_y), 0, np.cos(theta_y)]])
        Rz = np.asarray([[np.cos(theta_z), -np.sin(theta_z), 0],
                         [np.sin(theta_z), np.cos(theta_z), 0],
                         [0, 0, 1]])

        mics = (Rx @ Rz @ Rz @ mics.T).T

    # Define absorption

    absorption = np.random.uniform(low=0.2, high=0.8)
    alphas = absorption * np.ones(6, dtype=np.float32)

    # Position microphone array

    origin = np.concatenate([np.random.uniform(low=margin, high=box[0]-margin, size=(1,)),
                             np.random.uniform(low=margin, high=box[1]-margin, size=(1,)),
                             np.random.uniform(low=margin, high=box[2]-margin, size=(1,))], axis=0)

    # Position sources

    srcs = np.concatenate([np.random.uniform(low=margin, high=box[0]-margin, size=(number_sources, 1)),
                           np.random.uniform(low=margin, high=box[1]-margin, size=(number_sources, 1)),
                           np.random.uniform(low=margin, high=box[2]-margin, size=(number_sources, 1))], axis=1)

    # Speed of sound
    c = np.random.uniform(low=330.0, high=355.0)

    # Create room
    return rb.room(mics, box, srcs, origin, alphas, c)

if __name__ == "__main__":

    main()


"""Adjust data - download deliverables, clean and upload to BigQuery."""
import csv
import json
import tempfile
from argparse import ArgumentParser

import requests
from google.cloud import bigquery

API_URI = "api.adjust.com"
ENDPOINT = "kpis"
API_VERSION = "v1"

"""The APP_TOKEN_LIST is a list of dictionaries.
Keys are the app_name, and app_token in the form:
{"app_name":"<specific app name from Adjust dash>". "app_token":"<unique Adjust app token>}"
Look here to see the apps we are tracking: https://dash.adjust.com/#/.
It is important to maintain this list in order for the script to work especially in the case of new apps
being added to track in Adjust
"""

CSV_FIELDS = [
    "date",
    "app",
    "app_token",
    "network",
    "network_token",
    "campaign",
    "campaign_token",
    "adgroup",
    "adgroup_token",
    "creative",
    "creative_token",
    "country",
    "os",
    "device",
    "clicks",
    "installs",
    "limit_ad_tracking_install_rate",
    "click_conversion_rate",
    "impression_conversion_rate",
    "sessions",
    "daus",
    "waus",
    "maus",
]

def read_json(filename: str) -> dict:
    """Read JSON file."""
    with open(filename, "r") as f:
        data = json.loads(f.read())
    return data

def write_dict_to_csv(json_data, filename):
    """Write a dictionary to a csv."""
    with open(filename, "w") as out_file:
        dict_writer = csv.DictWriter(out_file, CSV_FIELDS)
        dict_writer.writeheader()
        dict_writer.writerows(json_data)

def download_adjust_kpi_data(date, api_token, app_token):
    """Download data from Adjust - API token and APP tokens are called here."""
    start_date = date
    end_date = date

    kpis = [
        "clicks",
        "installs",
        "limit_ad_tracking_install_rate",
        "click_conversion_rate",
        "impression_conversion_rate",
        "sessions",
        "daus",
        "waus",
        "maus",
    ]
    groupings = [
        "days",
        "apps",
        "networks",
        "campaigns",
        "adgroups",
        "creatives",
        "countries",
        "os_names",
        "device_types",
    ]
    # getting overview metrics for different kpis / Deliverables
    url = f"https://api.adjust.com/kpis/v1/{app_token}"  # overview
    url_params = f"start_date={start_date}&end_date={end_date}&kpis={','.join(kpis)}&grouping={','.join(groupings)}"
    headers = {
        "Authorization": f"Token token={api_token}",
    }

    response = requests.get(url, headers=headers, params=url_params)
    if (response.status_code == 401) or (response.status_code == 400):
        print(f"***Error: {response.status_code}***")
        print(response.text)

    return response

def check_json(adjust_response_text):
    """Script will return an empty dictionary for apps on days when there is no data. Check for that here."""
    with tempfile.NamedTemporaryFile() as tmp_json:
        with open(tmp_json.name, "w") as f_json:
            f_json.write(adjust_response_text)
            try:
                query_export = read_json(f_json.name)
            except (
                ValueError
            ):  # ex. json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
                return None
    return query_export

def clean_json(query_export):
    """JSON sometimes has missing keys, need to clean up the data."""
    fields_list = []
    for date in query_export["result_set"]["dates"]:
        r_date = date["date"]
        for app in date["apps"]:
            r_app = app.get("name", "no_app_name")
            r_app_token = app.get("token", "no_app_token")
            for network in app["networks"]:
                r_network = network.get("name", "no_network_name")
                r_network_token = network.get("token", "no_network_token")
                for campaign in network["campaigns"]:
                    r_campaign = campaign.get("name", "no_campaign_name")
                    r_campaign_token = campaign.get("token", "no_campaign_token")
                    for adgroup in campaign["adgroups"]:
                        r_adgroup = adgroup.get("name", "no_ad_group_name")
                        r_adgroup_token = adgroup.get("token", "no_adgroup_token")
                        for creative in adgroup["creatives"]:
                            r_creative = creative.get("name", "no_creative_name")
                            r_creative_token = creative.get(
                                "token", "no_creative_token"
                            )
                            for country in creative["countries"]:
                                r_country = country["country"]
                                for os_name in country["os_names"]:
                                    r_os_name = os_name["os_name"]
                                    for device in os_name["device_types"]:
                                        r_device = device["device_type"]
                                        field_dict = {
                                            "date": (r_date),
                                            "app": (r_app),
                                            "app_token": (r_app_token),
                                            "network": (r_network),
                                            "network_token": (r_network_token),
                                            "campaign": (r_campaign),
                                            "campaign_token": (r_campaign_token),
                                            "adgroup": (r_adgroup),
                                            "adgroup_token": (r_adgroup_token),
                                            "creative": (r_creative),
                                            "creative_token": (r_creative_token),
                                            "country": (r_country),
                                            "os": (r_os_name),
                                            "device": (r_device),
                                            "clicks": device["kpi_values"][0],
                                            "installs": device["kpi_values"][1],
                                            "limit_ad_tracking_install_rate": device[
                                                "kpi_values"
                                            ][2],
                                            "click_conversion_rate": device[
                                                "kpi_values"
                                            ][3],
                                            "impression_conversion_rate": device[
                                                "kpi_values"
                                            ][4],
                                            "sessions": device["kpi_values"][5],
                                            "daus": device["kpi_values"][6],
                                            "waus": device["kpi_values"][7],
                                            "maus": device["kpi_values"][8],
                                        }
                                        fields_list.append(field_dict)

    return fields_list

def upload_to_bigquery(csv_data, project, dataset, date):
    """Upload the data to bigquery."""
    print("writing json to csv")

    partition = f"{date}".replace("-", "")

    with tempfile.NamedTemporaryFile() as tmp_csv:
        with open(tmp_csv.name, "w+b") as f_csv:
            write_dict_to_csv(csv_data, f_csv.name)

            client = bigquery.Client(project)

            job_config = bigquery.LoadJobConfig(
                create_disposition="CREATE_IF_NEEDED",
                write_disposition="WRITE_TRUNCATE",
                time_partitioning=bigquery.TimePartitioning(
                    type_=bigquery.TimePartitioningType.DAY,
                    field="date",
                ),
                skip_leading_rows=1,
                schema=[
                    bigquery.SchemaField("date", "DATE"),
                    bigquery.SchemaField("app", "STRING"),
                    bigquery.SchemaField("app_token", "STRING"),
                    bigquery.SchemaField("network", "STRING"),
                    bigquery.SchemaField("network_token", "STRING"),
                    bigquery.SchemaField("campaign", "STRING"),
                    bigquery.SchemaField("campaign_token", "STRING"),
                    bigquery.SchemaField("adgroup", "STRING"),
                    bigquery.SchemaField("adgroup_token", "STRING"),
                    bigquery.SchemaField("creative", "STRING"),
                    bigquery.SchemaField("creative_token", "STRING"),
                    bigquery.SchemaField("country", "STRING"),
                    bigquery.SchemaField("os", "STRING"),
                    bigquery.SchemaField("device", "STRING"),
                    bigquery.SchemaField("clicks", "INTEGER"),
                    bigquery.SchemaField("installs", "INTEGER"),
                    bigquery.SchemaField("limit_ad_tracking_install_rate", "FLOAT"),
                    bigquery.SchemaField("click_conversion_rate", "FLOAT"),
                    bigquery.SchemaField("impression_conversion_rate", "FLOAT"),
                    bigquery.SchemaField("sessions", "INTEGER"),
                    bigquery.SchemaField("daus", "INTEGER"),
                    bigquery.SchemaField("waus", "INTEGER"),
                    bigquery.SchemaField("maus", "INTEGER"),
                ],
            )

            # Table names are based on the app name seen in the Adjust dashboard"
            destination = f"{project}.{dataset}.adjust_deliverables_v1${partition}"

            job = client.load_table_from_file(f_csv, destination, job_config=job_config)

            print(
                f"Writing adjust data for all apps to {destination}. BigQuery job ID: {job.job_id}"
            )
            job.result()

def main():
    """Input data, call functions, get stuff done."""
    parser = ArgumentParser(description=__doc__)
    parser.add_argument("--date", required=True)
    parser.add_argument("--adjust_api_token", required=True)
    parser.add_argument("--adjust_app_list", required=True)
    parser.add_argument("--project", default="moz-fx-data-shared-prod")
    parser.add_argument("--dataset", default="adjust_derived")

    args = parser.parse_args()

    app_list = json.loads(args.adjust_app_list)

    data = []

    # Cycle through the apps to get the relevant kpi data
    for app in app_list:
        print(f'This is data for {app["app_name"]}')
        # Ping the Adjust URL and get a response
        json_file = download_adjust_kpi_data(
            args.date, args.adjust_api_token, app["app_token"]
        )

        query_export = check_json(json_file.text)

        if query_export is not None:
            # This section writes the tmp json data into a temp CSV file which will then be put into a BigQuery table
            adjust_data = clean_json(query_export)
            data.extend(adjust_data)
        else:
            print(f'no data for {app["app_name"]} today')

    upload_to_bigquery(data, args.project, args.dataset, args.date)

if __name__ == "__main__":
    main()


#
import numpy

#

#
class SimplePipe:

    def __init__(self, data, items, items_args, X_names, Y_names, output_spec, verbose=False):

        self.data = data

        self.items = items
        self.items_args = items_args

        self.X_names = X_names
        self.Y_names = Y_names
        self.output_spec = output_spec

        self.the_pipe = []

        self.verbose = verbose

    def _output_names(self, j):

        return list(self.output_spec[j].keys())

    def _determine_names(self, j, blade_runner):

        if isinstance(self.X_names[j], int):
            if self.X_names[j] == 0:
                self.X_names[j] = [x for x in blade_runner.train.columns.values if x not in self._output_names(j)]
            else:
                self.X_names[j] = list(self.output_spec[(j + self.X_names[j])].keys())
        if self.Y_names[j] is None:
            raise Exception("Y_names anyway should be specified as non-None value, set something pls")

    def _fit_predict(self, j, blade_runner):

        self.the_pipe[j].fit(blade_runner.train[self.X_names[j]].values,
                             blade_runner.train[self.Y_names[j]].values)

        if self.output_spec[j] is None:
            cols = numpy.array(self.X_names[j])[self.the_pipe[j].support].tolist()
            self.output_spec[j] = {x: blade_runner.train[x].dtype.name for x in cols}
        blade_runner.train[self._output_names(j)] = self.the_pipe[j].predict(blade_runner.train[self.X_names[j]].values)

        return blade_runner

    def _predict(self, j, blade_runner, on='train'):

        if on == 'train':
            blade_runner.train[self._output_names(j)] = self.the_pipe[j].predict(blade_runner.train[self.X_names[j]].values)
        else:
            blade_runner.test[self._output_names(j)] = self.the_pipe[j].predict(blade_runner.test[self.X_names[j]].values)

        return blade_runner

    def _inverse(self, j, blade_runner, on='train'):

        if on == 'train':
            blade_runner.train[self._output_names(j)] = self.the_pipe[j].inverse(blade_runner.train[self.X_names[j]].values)
        else:
            blade_runner.test[self._output_names(j)] = self.the_pipe[j].inverse(blade_runner.test[self.X_names[j]].values)

        return blade_runner

    def fit(self):

        blade_runner = self.data.copy()

        for j in range(len(self.items)):

            # determine names

            self._determine_names(j, blade_runner)

            # append item

            self.the_pipe.append(self.items[j](**self.items_args[j]))

            # fit and predict

            blade_runner = self._fit_predict(j, blade_runner)

            # print current state

            if self.verbose:
                print(self.the_pipe[j])

    def infer(self, on='train'):

        blade_runner = self.data.copy()

        for j in range(len(self.items)):
            blade_runner = self._predict(j, blade_runner, on=on)

        return blade_runner

    def assess(self, assessor, on, target, where='inner'):
        if where == 'inner':
            if on == 'train':
                bench = self.data.train[target]
                peppa = self.infer(on=on).train[target]
            else:
                bench = self.data.test[target]
                peppa = self.infer(on=on).test[target]
            return assessor(y_true=bench.values, y_hat=peppa.values)
        elif where == 'outer':
            raise Exception("Not realised")
        else:
            raise Exception("Unacceptable plane")


# -*- coding: utf-8 -*-
import os
import sys
import argparse
import datetime
import pdb
import logging
import pprint
import numpy
import torch

from eznlp import auto_device
from eznlp.token import TokenSequence
from eznlp.dataset import Dataset
from eznlp.config import ConfigDict
from eznlp.model import OneHotConfig, EncoderConfig
from eznlp.model import ELMoConfig, BertLikeConfig, FlairConfig
from eznlp.model import TextClassificationDecoderConfig
from eznlp.model import ClassifierConfig
from eznlp.model.bert_like import truecase_for_bert_like, truncate_for_bert_like
from eznlp.training import Trainer, count_params, evaluate_text_classification

from utils import add_base_arguments, parse_to_args
from utils import load_data, dataset2language, load_pretrained, load_vectors, build_trainer, header_format

def parse_arguments(parser: argparse.ArgumentParser):
    parser = add_base_arguments(parser)

    group_data = parser.add_argument_group('dataset')
    group_data.add_argument('--dataset', type=str, default='imdb',
                            help="dataset name")
    group_data.add_argument('--pre_truecase', default=False, action='store_true',
                            help="whether to pre-truecase data")
    group_data.add_argument('--save_preds', default=False, action='store_true',
                            help="whether to save predictions on the test split (typically in case without ground truth)")

    group_decoder = parser.add_argument_group('decoder configurations')
    group_decoder.add_argument('--agg_mode', type=str, default='multiplicative_attention',
                               help="aggregating mode")

    return parse_to_args(parser)

def collect_TC_assembly_config(args: argparse.Namespace):
    drop_rates = (0.0, 0.05, args.drop_rate) if args.use_locked_drop else (args.drop_rate, 0.0, 0.0)

    if args.emb_dim > 0:
        vectors = load_vectors(args.language, args.emb_dim)
        ohots_config = ConfigDict({'text': OneHotConfig(field='text', min_freq=5, vectors=vectors, emb_dim=args.emb_dim, freeze=args.emb_freeze)})
    else:
        ohots_config = None

    if args.use_interm1:
        interm1_config = EncoderConfig(arch=args.enc_arch, hid_dim=args.hid_dim, num_layers=args.num_layers, in_drop_rates=drop_rates)
    else:
        interm1_config = None

    if args.use_interm2:
        interm2_config = EncoderConfig(arch=args.enc_arch, hid_dim=args.hid_dim, num_layers=args.num_layers, in_drop_rates=drop_rates)
    else:
        interm2_config = None

    if args.language.lower() == 'english' and args.use_elmo:
        elmo_config = ELMoConfig(elmo=load_pretrained('elmo'))
    else:
        elmo_config = None

    if args.language.lower() == 'english' and args.use_flair:
        flair_fw_lm, flair_bw_lm = load_pretrained('flair')
        flair_fw_config, flair_bw_config = FlairConfig(flair_lm=flair_fw_lm), FlairConfig(flair_lm=flair_bw_lm)
        if interm2_config is not None:
            interm2_config.in_proj = True
    else:
        flair_fw_config, flair_bw_config = None, None

    if args.bert_arch.lower() != 'none':
        # Uncased tokenizer for text classification
        bert_like, tokenizer = load_pretrained(args.bert_arch, args, cased=False)
        bert_like_config = BertLikeConfig(tokenizer=tokenizer, bert_like=bert_like, arch=args.bert_arch, freeze=False, paired_inputs=args.paired_inputs)
    else:
        bert_like_config = None

    return {'ohots': ohots_config,
            'intermediate1': interm1_config,
            'elmo': elmo_config,
            'flair_fw': flair_fw_config,
            'flair_bw': flair_bw_config,
            'bert_like': bert_like_config,
            'intermediate2': interm2_config, }

def build_TC_config(args: argparse.Namespace):
    drop_rates = (0.0, 0.05, args.drop_rate) if args.use_locked_drop else (args.drop_rate, 0.0, 0.0)
    decoder_config = TextClassificationDecoderConfig(agg_mode=args.agg_mode, in_drop_rates=drop_rates)
    return ClassifierConfig(**collect_TC_assembly_config(args), decoder=decoder_config)

def process_TC_data(train_data, dev_data, test_data, args, config):
    if args.pre_truecase:
        assert config.bert_like is not None
        assert not getattr(config.bert_like.tokenizer, 'do_lower_case', False)
        train_data = truecase_for_bert_like(train_data, verbose=args.log_terminal)
        dev_data   = truecase_for_bert_like(dev_data,   verbose=args.log_terminal)
        test_data  = truecase_for_bert_like(test_data,  verbose=args.log_terminal)

    # Truncate too long sentences
    if config.bert_like is not None:
        train_data = truncate_for_bert_like(train_data, config.bert_like.tokenizer, verbose=args.log_terminal)
        dev_data   = truncate_for_bert_like(dev_data,   config.bert_like.tokenizer, verbose=args.log_terminal)
        test_data  = truncate_for_bert_like(test_data,  config.bert_like.tokenizer, verbose=args.log_terminal)

    elif args.dataset in ('ChnSentiCorp', 'THUCNews_10'):
        # Too long sentences even for RNN
        for data in [train_data, dev_data, test_data]:
            for entry in data:
                if len(entry['tokens']) > 1200:
                    entry['tokens'] = entry['tokens'][:300] + entry['tokens'][-900:]

    if config.bert_like is not None and config.bert_like.paired_inputs:
        logger.info("Paired text exists, concatenating as input...")
        for data in [train_data, dev_data, test_data]:
            for entry in data:
                entry['tokens'] = entry['tokens'] + TokenSequence.from_tokenized_text([config.bert_like.tokenizer.sep_token]) + entry['paired_tokens']

    return train_data, dev_data, test_data

if __name__ == '__main__':
    parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter,
                                     fromfile_prefix_chars='@')
    args = parse_arguments(parser)

    # Use micro-seconds to ensure different timestamps while adopting multiprocessing
    timestamp = datetime.datetime.now().strftime("%Y%m%d-%H%M%S-%f")
    save_path =  f"cache/{args.dataset}-TC/{timestamp}"
    if not os.path.exists(save_path):
        os.makedirs(save_path)

    handlers = [logging.FileHandler(f"{save_path}/training.log")]
    if args.log_terminal:
        handlers.append(logging.StreamHandler(sys.stdout))
    logging.basicConfig(level=logging.INFO,
                        format="[%(asctime)s %(levelname)s] %(message)s",
                        datefmt="%Y-%m-%d %H:%M:%S",
                        handlers=handlers)

    logger = logging.getLogger(__name__)
    logger.info(header_format("Starting", sep='='))
    logger.info(" ".join(sys.argv))
    logger.info(pprint.pformat(args.__dict__))

    logger.info(header_format("Preparing", sep='-'))
    device = auto_device()
    if device.type.startswith('cuda'):
        torch.cuda.set_device(device)
        temp = torch.randn(100).to(device)

    train_data, dev_data, test_data = load_data(args)
    args.language = dataset2language[args.dataset]
    args.paired_inputs = ('paired_tokens' in train_data[0])

    # train_data, dev_data, test_data = train_data[:1000], dev_data[:1000], test_data[:1000]
    config = build_TC_config(args)
    train_data, dev_data, test_data = process_TC_data(train_data, dev_data, test_data, args, config)

    train_set = Dataset(train_data, config, training=True)
    train_set.build_vocabs_and_dims(dev_data)
    dev_set   = Dataset(dev_data,  train_set.config, training=False)
    test_set  = Dataset(test_data, train_set.config, training=False)

    logger.info(train_set.summary)
    train_loader = torch.utils.data.DataLoader(train_set, batch_size=args.batch_size, shuffle=True,  collate_fn=train_set.collate)
    dev_loader   = torch.utils.data.DataLoader(dev_set,   batch_size=args.batch_size, shuffle=False, collate_fn=dev_set.collate)

    logger.info(header_format("Building", sep='-'))
    model = config.instantiate().to(device)
    count_params(model)

    logger.info(header_format("Training", sep='-'))
    trainer = build_trainer(model, device, len(train_loader), args)
    if args.pdb:
        pdb.set_trace()

    torch.save(config, f"{save_path}/{config.name}-config.pth")
    def save_callback(model):
        torch.save(model, f"{save_path}/{config.name}.pth")
    trainer.train_steps(train_loader=train_loader, dev_loader=dev_loader, num_epochs=args.num_epochs,
                        save_callback=save_callback, save_by_loss=False)

    logger.info(header_format("Evaluating", sep='-'))
    model = torch.load(f"{save_path}/{config.name}.pth", map_location=device)
    trainer = Trainer(model, device=device)

    logger.info("Evaluating on dev-set")
    evaluate_text_classification(trainer, dev_set, batch_size=args.batch_size)
    logger.info("Evaluating on test-set")
    evaluate_text_classification(trainer, test_set, batch_size=args.batch_size, save_preds=args.save_preds)
    if args.save_preds:
        torch.save(test_data, f"{save_path}/test-data-with-preds.pth")

    logger.info(" ".join(sys.argv))
    logger.info(pprint.pformat(args.__dict__))
    logger.info(header_format("Ending", sep='='))


import pathlib

import numpy as np

import matplotlib
import matplotlib.pyplot as plt
import matplotlib.ticker
import mpl_toolkits.axes_grid1.axes_divider

import util.io.fs
import util.logging

def generic(file, plot_function, font_size=20, transparent=True, caption=None, use_legend=False,
            tick_power_limit_scientific=None, tick_power_limit_scientific_x=None, tick_power_limit_scientific_y=None,
            tick_power_limit_fix=None, tick_power_limit_fix_x=None, tick_power_limit_fix_y=None,
            tick_number=None, tick_number_x=None, tick_number_y=None,
            tick_interger_only_x=False, tick_interger_only_y=False,
            tick_transform_x=None, tick_transform_y=None,
            x_min=None, x_max=None, y_min=None, y_max=None,
            overwrite=True, make_read_only=True, dpi=800, backend=None,
            invert_x_axis=False, invert_y_axis=False,
            colorbar=False, colorbar_tick_number=None, colorbar_tick_step_size=None,
            colorbar_tick_transform=None, colorbar_tick_power_limit_scientific=None):

    # check if file should be saved
    if check_file(file, overwrite=overwrite):
        # use backend
        if backend is not None:
            plt.switch_backend(backend)

        # font size
        set_global_font_size(font_size=font_size)

        # make fig
        fig = plt.figure()

        # make plot
        plot_function(fig)

        # get axes
        axes = fig.gca()

        # power limits
        set_tick_power_limit_scientific(tick_power_limit_scientific, axis='both')
        set_tick_power_limit_scientific(tick_power_limit_scientific_x, axis='x')
        set_tick_power_limit_scientific(tick_power_limit_scientific_y, axis='y')
        set_tick_power_limit_fix(tick_power_limit_fix, axis='both')
        set_tick_power_limit_fix(tick_power_limit_fix_x, axis='x')
        set_tick_power_limit_fix(tick_power_limit_fix_y, axis='y')

        # set number of ticks
        ticks_set_number(tick_number, axis='both')
        ticks_set_number(tick_number_x, axis='x')
        ticks_set_number(tick_number_y, axis='y')

        # set integer only for ticks
        ticks_set_integer_only(tick_interger_only_x, axis='x')
        ticks_set_integer_only(tick_interger_only_y, axis='y')

        # set caption
        if caption is not None:
            plt.xlabel(caption, fontsize=font_size, fontweight='bold')

        # legend
        add_legend(use_legend=use_legend, transparent=transparent)

        # set axis limits
        set_axis_limits(x_min=x_min, x_max=x_max, y_min=y_min, y_max=y_max)

        # invert axis
        invert_axis(x_axis=invert_x_axis, y_axis=invert_y_axis, axes=axes)

        # transform tick labels
        ticks_transform_labels(tick_transform_x=tick_transform_x, tick_transform_y=tick_transform_y, axes=axes)

        # add colorbar
        if colorbar_tick_number is None:
            colorbar_tick_number = tick_number
        if colorbar_tick_power_limit_scientific is None:
            colorbar_tick_power_limit_scientific = tick_power_limit_scientific
        add_colorbar(axes=axes, colorbar=colorbar,
                     tick_number=colorbar_tick_number, tick_step_size=colorbar_tick_step_size,
                     tick_transform=colorbar_tick_transform, tick_power_limit_scientific=colorbar_tick_power_limit_scientific)

        # save and close
        save_and_close_fig(fig, file, transparent=transparent, make_read_only=make_read_only, overwrite=overwrite, dpi=dpi)

def check_file(file, overwrite=True):
    file_exists = pathlib.Path(file).exists()
    if overwrite and file_exists:
        util.io.fs.make_writable(file)
    save = overwrite or not file_exists
    return save

def save_and_close_fig(fig, file, transparent=True, make_read_only=True, overwrite=False, dpi=800):
    # prepare file
    file = pathlib.Path(file)
    file.parent.mkdir(parents=True, exist_ok=True)
    if overwrite and file.exists():
        file.unlink()
    # plot
    fig.savefig(file, transparent=transparent, dpi=dpi, bbox_inches='tight')
    plt.close(fig)
    # make read only
    if make_read_only:
        util.io.fs.make_read_only(file)
    util.logging.debug('Plot saved to {}.'.format(file))

def set_global_font_size(font_size=None, weight='bold'):
    if font_size is not None:
        util.logging.debug(f'Setting global font size to {font_size}.')
        font_size = int(font_size)
        matplotlib.rcParams.update({'font.size': font_size})
    if weight is not None:
        util.logging.debug(f'Setting global font weight {weight}.')
        matplotlib.rcParams.update({'font.weight': weight})
        if weight == 'bold':
            matplotlib.rcParams['text.latex.preamble'] = ['\\boldmath']

def _get_axes_list(axes=None):
    if axes is None:
        axes = [plt.gca()]
    try:
        len(axes)
    except TypeError:
        axes = [axes]
    return axes

def _parse_scientific_power_limit(power_limit):
    if isinstance(power_limit, str):
        power_limit = int(power_limit)
    try:
        length = len(power_limit)
    except TypeError:
        power_limit = (-power_limit, power_limit)
    else:
        if length != 2:
            raise ValueError(f'power_limit has to be a tuple with two values but it is {power_limit}.')
    return power_limit

def set_tick_power_limit_scientific(power_limit, axis='both', axes=None):
    if power_limit is not None:
        # set axes
        axes = _get_axes_list(axes=axes)
        # set axis
        if axis is None:
            axis = 'both'
        # parse power limits
        power_limit = _parse_scientific_power_limit(power_limit)
        # apply power limit
        util.logging.debug(f'Setting tick power limit scientific for axis {axis} to {power_limit}.')
        for axes_i in axes:
            axes_i.ticklabel_format(style='scientific', axis=axis, scilimits=power_limit)

def set_tick_power_limit_fix(power_limit, axis='both', axes=None):

    class FixedOrderFormatter(matplotlib.ticker.ScalarFormatter):
        """Formats axis ticks using scientific notation with a constant order of
        magnitude"""
        def __init__(self, order_of_magnitude=0, use_offset=True, use_math_text=None):
            self._order_of_magnitude = order_of_magnitude
            matplotlib.ticker.ScalarFormatter.__init__(self, useOffset=use_offset, useMathText=use_math_text)
            self.orderOfMagnitude = order_of_magnitude

        def _set_orderOfMagnitude(self, range):
            """Over-riding this to avoid having orderOfMagnitude reset elsewhere"""
            self.orderOfMagnitude = self._order_of_magnitude

    if power_limit is not None:
        # set axes
        axes = _get_axes_list(axes=axes)
        # set axis
        if axis is None:
            axis = 'both'
        # apply power limit
        util.logging.debug(f'Setting tick power limit fix for axis {axis} to {power_limit}.')
        f = FixedOrderFormatter(power_limit)
        for axes_i in axes:
            if axis == 'y' or axis == 'both':
                axes_i.yaxis.set_major_formatter(f)
            if axis == 'x' or axis == 'both':
                axes_i.xaxis.set_major_formatter(f)

def ticks_set_number(number, axis='both', axes=None):
    if number is not None:
        number = int(number)
        # set axes
        axes = _get_axes_list(axes=axes)
        # set axis
        if axis is None:
            axis = 'both'
        # apply tick number
        for axes_i in axes:
            axes_i.locator_params(axis=axis, tight=True, nbins=number + 1, min_n_ticks=number)

def ticks_set_integer_only(integer_only, axis='both', axes=None):
    integer_only = bool(integer_only)
    if integer_only:
        # set axes
        axes = _get_axes_list(axes=axes)
        # set axis
        if axis is None:
            axis = 'both'
        # apply tick number
        for axes_i in axes:
            axes_i.locator_params(axis=axis, integer=integer_only)

def set_axis_limits(x_min=None, x_max=None, y_min=None, y_max=None):
    if x_min is not None:
        plt.xlim(left=x_min)
    if x_max is not None:
        plt.xlim(right=x_max)
    if y_min is not None:
        plt.ylim(bottom=y_min)
    if y_max is not None:
        plt.ylim(top=y_max)

def get_colors(n, colormap_name='gist_rainbow'):
    colormap = plt.get_cmap(colormap_name)
    colors = [colormap(i / (n - 1)) for i in range(n)]
    return colors

def ticks_set_number_for_locator(locator, tick_number=None):
    if tick_number is not None:
        tick_number = int(tick_number)
        # LinearLocator, LogLocator, SymmetricalLogLocator
        try:
            locator.set_params(numticks=tick_number)
        except TypeError:
            pass
        # MaxNLocator
        try:
            locator.set_params(nbins=tick_number + 1)
            locator.set_params(min_n_ticks=tick_number)
        except TypeError:
            pass

def add_colorbar(axes_image=None, axes=None, colorbar=True,
                 orientation='right', size='3%', pad='1.5%',
                 tick_number=None, tick_step_size=None, tick_transform=None, tick_power_limit_scientific=None):
    # plot colorbar
    if colorbar:
        if axes is None:
            axes = plt.gca()
        if axes_image is None:
            axes_images = axes.get_images()
            axes_image = axes_images[-1]
        # make place for colorbar with same height as plot
        axes_divider = mpl_toolkits.axes_grid1.axes_divider.make_axes_locatable(axes)
        cax = axes_divider.append_axes(orientation, size=size, pad=pad)
        # plot colorbar
        cb = plt.colorbar(axes_image, cax=cax)
        # set ticks
        if tick_number is not None and tick_step_size is not None:
            raise ValueError('Please use only tick_number or tick_step_size, not both.')
        if tick_number is not None:
            ticks_set_number_for_locator(cb.locator, tick_number=tick_number)
            cb.update_ticks()
        if tick_step_size is not None:
            tick_step_size = float(tick_step_size)
            locator = matplotlib.ticker.MultipleLocator(base=tick_step_size)
            cb.locator = locator
            cb.update_ticks()
        if tick_transform is not None and tick_power_limit_scientific is not None:
            raise ValueError('Please use only tick_transform or tick_power_limit_scientific, not both.')
        if tick_transform is not None:
            ticks = cb.ax.get_yticks()
            tick_lables = [tick_transform(tick) for tick in ticks]
            cb.ax.set_yticklabels(tick_lables)
        if tick_power_limit_scientific is not None:
            tick_power_limit_scientific = _parse_scientific_power_limit(tick_power_limit_scientific)
            cb.formatter.set_powerlimits(tick_power_limit_scientific)
            cb.update_ticks()
        return cb
    else:
        return None

def add_legend(labels=None, handles=None, use_legend=True, transparent=True):
    if use_legend:
        legend = plt.legend(labels=labels, handles=handles, loc='best')
        if legend is not None:
            legend.get_frame().set_alpha(float(not transparent))

def _v_min_max(data, percentile, significant_digits=2):
    data = data[np.isfinite(data)]
    v = np.percentile(data, percentile)
    if significant_digits is not None and v != 0:
        exp = np.log10(np.abs(v))
        exp = - np.sign(exp) * np.round(np.abs(exp)) + significant_digits
        v = np.round(v * 10**exp) * 10**-exp
    assert np.isfinite(v)
    return v

def v_min(data, percentile=1, significant_digits=2):
    return _v_min_max(data, percentile, significant_digits=significant_digits)

def v_max(data, percentile=99, significant_digits=2):
    return _v_min_max(data, percentile, significant_digits=significant_digits)

def invert_axis(x_axis=False, y_axis=False, axes=None):
    if x_axis or y_axis:
        if axes is None:
            axes = plt.gca()
        if x_axis:
            axes.invert_xaxis()
        if y_axis:
            axes.invert_yaxis()

def ticks_transform_labels(tick_transform_x=None, tick_transform_y=None, axes=None):
    if tick_transform_x or tick_transform_y:
        if axes is None:
            axes = plt.gca()

        if tick_transform_x:
            x_ticks = axes.get_xticks()
            x_tick_lables = [tick_transform_x(tick) for tick in x_ticks]
            axes.set_xticklabels(x_tick_lables)

        if tick_transform_y:
            y_ticks = axes.get_yticks()
            y_tick_lables = [tick_transform_y(tick) for tick in y_ticks]
            axes.set_yticklabels(y_tick_lables)

def tick_transform_function_exponent_notation(data, v_max=None, decimals=None):
    # calculate factor
    if v_max is not None:
        v_max_for_tick_factor = float(v_max)
    else:
        v_max_for_tick_factor = util.plot.auxiliary.v_max(data)
    tick_exponent = int(np.floor(np.log10(v_max_for_tick_factor)))
    if tick_exponent >= 0:
        tick_exponent_str = f'e\\!\\!{tick_exponent}$'
    else:
        tick_exponent_str = f'e\\!\\!-\\!\\!{-tick_exponent}$'
    tick_factor = 10**tick_exponent

    # choose decimals
    if decimals is None:
        if v_max_for_tick_factor <= 2 * tick_factor:
            decimals = 1
        else:
            decimals = 0
    else:
        decimals = int(decimals)

    # create transform function
    def tick_transform(tick):
        tick /= tick_factor
        tick = np.round(tick, decimals=decimals)
        if decimals == 0:
            tick = int(tick)
        tick_label = f'${tick}{tick_exponent_str}'
        return tick_label

    # return
    return tick_transform


print("""
Q) Write a program to print even numbers in between 10 to 20 by using while loop.
Ans)
""")

i = 10
j = 20
while(i <= j):
    print(i)
    i += 2


from sklearn import datasets, svm, metrics, externals

digits = datasets.load_digits()

n_samples = len(digits.images)
data = digits.images.reshape((n_samples, -1))

classifier = svm.SVC(gamma=0.001)

classifier.fit(data[:n_samples // 2], digits.target[:n_samples // 2])

expected = digits.target[n_samples // 2:]
predicted = classifier.predict(data[n_samples // 2:])

print(metrics.classification_report(expected, predicted))
print(metrics.confusion_matrix(expected, predicted))


# Authors:
#         A01379896 Erick Bautista Pérez
#
#Write a program called generation.py.
#Define in this program a function called generation(y)
#that returns a string indicating the generation to which a person
#belongs given the year y in which she was born. Use the information
#in this table:
# September 23, 2016.

def generation(y):
    if  y <= 1945:
        return "Mature"
    elif 1946 <= y <= 1964:
        return "Baby Boomer"
    elif 1965 <= y <= 1980:
        return "Generation X"
    elif 1981 <= y <= 2000:
        return "Millenium"
    else:
        return "Boomlet"

def main():
    for i in range(1945, 2006, 5):
        print(i, generation(i))

main()


# Daniel Ham
# Data Read v1

# **********************INSTRUCTIONS**********************
# Download professions.txt
# Produce this output:
# ********************************************************

# Open file and read lines
with open('professions.txt', 'r') as f:
    people = f.readlines()

# Create list of people and append
person_list = []
for person in people:
    person_list.append(person.strip().split(", "))

# Print each person in the list
for person in person_list:
    print(person)

## print all the data
print("\nAll the data: ")
print(person_list)


# reading from ds18x20 to obtain temperature
# then map a temp range to a color range and display
# color with neopixel
# Jon Proctor: added LED(13) Heartbeat
# and adding neopixel support

import time
import board
import simpleio
import neopixel

from adafruit_onewire.bus import OneWireBus
from adafruit_ds18x20 import DS18X20

heartbeat = simpleio.DigitalOut(board.D13)
heartbeat.value = True

# Initialize one-wire bus on board pin D5.
ow_bus = OneWireBus(board.D5)

# Scan for sensors and grab the first one found.
ds18_0 = DS18X20(ow_bus, ow_bus.scan()[0]) # pre  radiator
ds18_1 = DS18X20(ow_bus, ow_bus.scan()[1]) # post radiator
ds18_2 = DS18X20(ow_bus, ow_bus.scan()[2]) # GPU vent
ds18_3 = DS18X20(ow_bus, ow_bus.scan()[3]) # inside temp

# devices = ow_bus.scan()
# for device in devices:
#     print("ROM = {} \tFamily = 0x{:02x}".format([hex(i) for i in device.rom], device.family_code))

# SetUp LED ranges for different displays
LEDArrayLength0 = 14
LEDArrayLength1 = 14
LEDArrayLength2 = 14
LEDArrayLength3 = 14

LEDArray0 = LEDArrayLength0
LEDArray1 = LEDArray0 + LEDArrayLength1
LEDArray2 = LEDArray1 + LEDArrayLength2
LEDArray3 = LEDArray2 + LEDArrayLength3

# SetUp NeoPixels
tempLEDPin = board.A1
numLED = LEDArray0 + LEDArray1+ LEDArray2+ LEDArray3
ORDER = neopixel.GRBW
tempLED = neopixel.NeoPixel(tempLEDPin, numLED, brightness=0.2, auto_write=False, pixel_order=ORDER)

# SetUp temp range and color range.  range for computer: 25 - 65 or 70?
minBTemp = 20
maxBTemp = 30

midGTemp = 32
rngGTemp = 8

minRTemp = 36
maxRTemp = 42

minRed = 0
maxRed = 250
minGrn = 0
maxGrn = 200
minBlu = 250
maxBlu = 0

# Main loop to print the temperature every second.
while True:

    celc_0 = (ds18_0.temperature)
    celc_1 = (ds18_1.temperature)
    celc_2 = (ds18_2.temperature)
    celc_3 = (ds18_3.temperature)

    r_0 = int(((celc_0-minRTemp)/(maxRTemp - minRTemp))*(maxRed-minRed))
    g_0 = int((rngGTemp-(abs(midGTemp - celc_0)))/(rngGTemp) * (maxGrn-minGrn))
    b_0 = int(minBlu-((celc_0-minBTemp)/(maxBTemp - minBTemp))*(minBlu-maxBlu))

    r_1 = int(((celc_1-minRTemp)/(maxRTemp - minRTemp))*(maxRed-minRed))
    g_1 = int((rngGTemp-(abs(midGTemp - celc_1)))/(rngGTemp) * (maxGrn-minGrn))
    b_1 = int(minBlu-((celc_1-minBTemp)/(maxBTemp - minBTemp))*(minBlu-maxBlu))

    r_2 = int(((celc_2-minRTemp)/(maxRTemp - minRTemp))*(maxRed-minRed))
    g_2 = int((rngGTemp-(abs(midGTemp - celc_2)))/(rngGTemp) * (maxGrn-minGrn))
    b_2 = int(minBlu-((celc_2-minBTemp)/(maxBTemp - minBTemp))*(minBlu-maxBlu))

    r_3 = int(((celc_3-minRTemp)/(maxRTemp - minRTemp))*(maxRed-minRed))
    g_3 = int((rngGTemp-(abs(midGTemp - celc_3)))/(rngGTemp) * (maxGrn-minGrn))
    b_3 = int(minBlu-((celc_3-minBTemp)/(maxBTemp - minBTemp))*(minBlu-maxBlu))

    if r_0 < minRed:
        r_0 = minRed
    if g_0 < minGrn:
        g_0 = minGrn
    if b_0 < maxBlu:
        b_0 = maxBlu
    if r_0 > maxRed:
        r_0 = maxRed
    if g_0 > maxGrn:
        g_0 = maxGrn
    if b_0 > minBlu:
        b_0 = minBlu

    if r_1 < minRed:
        r_1 = minRed
    if g_1 < minGrn:
        g_1 = minGrn
    if b_1 < maxBlu:
        b_1 = maxBlu
    if r_1 > maxRed:
        r_1 = maxRed
    if g_1 > maxGrn:
        g_1 = maxGrn
    if b_1 > minBlu:
        b_1 = minBlu

    if r_2 < minRed:
        r_2 = minRed
    if g_2 < minGrn:
        g_2 = minGrn
    if b_2 < maxBlu:
        b_2 = maxBlu
    if r_2 > maxRed:
        r_2 = maxRed
    if g_2 > maxGrn:
        g_2 = maxGrn
    if b_2 > minBlu:
        b_2 = minBlu

    if r_3 < minRed:
        r_3 = minRed
    if g_3 < minGrn:
        g_3 = minGrn
    if b_3 < maxBlu:
        b_3 = maxBlu
    if r_3 > maxRed:
        r_3 = maxRed
    if g_3 > maxGrn:
        g_3 = maxGrn
    if b_3 > minBlu:
        b_3 = minBlu

    # print((celc_0, celc_1, celc_2, celc_3))
    print('pre  radiator:  {0:0.3f}C'.format(celc_0))
    print('post radiator:  {0:0.3f}C'.format(celc_1))
    print('rad C increase: {0:0.3f}C'.format(celc_1 - celc_0))
    print('Inside Temp:    {0:0.3f}C'.format(celc_3))
    print('GPU vent:       {0:0.3f}C'.format(celc_2))
    print('GPU C increase:  {0:0.3f}C'.format(celc_2-celc_3))

    print()

    for i in range(0, LEDArray0, 1):          # Pre radiator
        tempLED[i] = (r_0, g_0, b_0)
    for i in range(LEDArray0, LEDArray1, 1):  # Post Radiator
        tempLED[i] = (r_3, g_3, b_3)
    for i in range(LEDArray1, LEDArray2, 1):  # Inside Temp
        tempLED[i] = (r_1, g_1, b_1)
    for i in range(LEDArray2, LEDArray3, 1):  # GPU Vent
        tempLED[i] = (r_2, g_2, b_2)

    tempLED.show()

# using 'not' for heartbeat to pulse LED(13) for heartbeat
    heartbeat.value = not heartbeat.value

#    time.sleep(0.01)


# coding=utf-8
from __future__ import absolute_import, division, print_function

from click import ClickException, argument, command, echo, option, pass_context

_SHORT_HELP = 'Update or view the {} configuration.'

def configuration_options(name, container, use, example_key, example_value, fetch_func):
    """
    Get a decorator for configuration modification options.

    :param name: name of the command
    :param container: the name of the configuration to work on
    :param use: usage string for the configuration options
    :param example_key: example update key
    :param example_value: example update value
    :param fetch_func: function to get container from the context
    :return: the decorator for the CLI function
    """

    def configuration_options_decorator(func):
        def view_configuration(context, _, value):
            """
            View the configuration options for a container. Handles
            the `--view` option.

            :param context: Click context
            :param _: command-line parameter
            :param value: whether or not to view the configuration
            """
            if not value or context.resilient_parsing:
                return

            config_container = fetch_func(context)
            max_length = max([len(key) for key in config_container])
            for key in config_container:
                echo('{:>{width}s}: {}'.format(key, config_container[key], width=max_length))

            context.exit()

        click_options = [
            command(
                name=name, short_help=_SHORT_HELP.format(container), help=_SHORT_HELP.format(container) + '''

Existing configuration options that are used to {use}
can be edited with this command.

\b
Examples:
  Update the option '{key}' option to '{value}'
  $ oct configure {name} '{key}' '{value}'
\b
  View the current {container} options
  $ oct configure {name} --view
'''.format(name=name, container=container, use=use, key=example_key, value=example_value)
            ),
            argument(
                'option',
            ),
            argument(
                'value',
            ),
            option(
                '--view',
                '-v',
                help='Print all configuration options.',
                is_flag=True,
                callback=view_configuration,
            ),
            pass_context,
        ]

        for click_option in reversed(click_options):
            func = click_option(func)

        return func

    return configuration_options_decorator

def update_configuration_option(container, option, value):
    """
    Update an option in a configuration file.

    :param container: configuration file to work on
    :param option: name of the option to update
    :param value: value to update to
    """
    if option not in container:
        raise ClickException(message='Option {} not found in configuration.'.format(option))

    # try to interpret the most common values
    if value.isdigit():
        value = int(value)
    elif value.lower() in ['true', 'yes']:
        value = True
    elif value.lower() in ['false', 'no']:
        value = False
    elif ',' in value:
        value = value.split(',')

    setattr(container, option, value)

    echo('Option {} updated to be {}.'.format(option, value))


import os

data = open("facebook_combined.txt", "r")
jsonFile = open('facebook.json', 'w')

nodesList = []
links = []

for line in data:
    nodes = line.split() # split each line by space
    if (int(nodes[0]) not in nodesList):
        nodesList.append(int(nodes[0]))
    if (int(nodes[1]) not in nodesList):
        nodesList.append(int(nodes[1]))
    links.append({"source": nodes[0], "target": nodes[1]})
nodesList = sorted(nodesList)

jsonFile.write('{\n"nodes": [\n')

# nodes
for node in nodesList[:-1]:
    jsonFile.write('    {"name":' + str(node) + '},\n')
jsonFile.write('    {"name":' + str(nodesList[-1]) + '}\n')
jsonFile.write('],\n"links":[\n')

# links
for link in links[:-1]:
    jsonFile.write('    {"source":' + link["source"] + ',"target":' + link["target"]+ '},\n')
jsonFile.write('    {"source":' + links[-1]["source"] + ',"target":' + links[-1]["target"]+ '}\n')
jsonFile.write(']}\n')

data.close()
jsonFile.close()


from itertools import permutations

with open('input.txt') as f:
    data = f.read()

routes = {}

for line in data.splitlines():
    split = line.split()
    routes[frozenset([split[0], split[2]])] = int(split[-1])

all_destinations = set()
for route in routes:
    all_destinations.update(route)

possible_paths = list(permutations(all_destinations, len(all_destinations)))

costs = []
for path in possible_paths:
    cost = 0
    for i in range(len(path) - 1):
        cost += routes[frozenset([path[i], path[i+1]])]
    costs.append(cost)

print("Part 1:", min(costs))
print("Part 2:", max(costs))


import os
import rospy
import rosbag
from copy import copy
import rostopic

class Recorder(object):
    def __init__(self, path, prefix, topics):
        self.path = path
        os.system('mkdir -p '+path)
        self.prefix = prefix
        self.topics= topics
        self.recorded_topics = {}
        self.publishers = {}
        self.lastMessages = {topic:None for topic in topics}
        self.bag = None

        self._latches = {}
        self._bag_latch = False
        self._not_found_topics = copy(topics)

        self.check_topics()

    def __del__(self):
        self.close_bag()

    def new_bag(self, name):
        if self.bag: raise Excpetion('First close the current bag before creating a new one')
        bag_name = self.path+'/'+name+'.bag'
        rospy.loginfo('Creating new bag : '+bag_name)
        self.bag = rosbag.Bag(bag_name, 'w')

    def close_bag(self):
        if self.bag:
            print('Closing the bag')
            while self._bag_latch:pass
            self.bag.close()
            self.bag = None
        else:
            rospy.loginfo('No bag currently open')

    def new_topic_name(self, topic):
        prefix= self.prefix
        if topic[0]!='/' and prefix[-1]!='/': prefix+='/'
        return prefix+topic

    ''' Callback for recording signals'''
    def make_callback(self, topic):
        written_topic = self.recorded_topics[topic]
        def callback(message):
            while self._latches[topic]: pass
            self._latches[topic] = True
            self.lastMessages[topic] = message
            self._latches[topic] = False
        return callback

    def check_topic(self, topic):
        message_class = rostopic.get_topic_class(topic)[0] # None if topic is not already published
        if message_class:
            self.recorded_topics[topic] = self.new_topic_name(topic)
            self._latches[topic] = False
            rospy.Subscriber(topic, message_class, self.make_callback(topic), queue_size = 10)
            self.publishers[topic] = rospy.Publisher(self.recorded_topics[topic], message_class, queue_size = 1)
            rospy.loginfo('create suscriber for '+topic)
            return True
        return False

    def check_topics(self):
        self._not_found_topics = [topic for topic in self._not_found_topics if not self.check_topic(topic)]

    def all_buffers_full(self, excepts = []):
        for topic, msg in self.lastMessages.iteritems():
            if topic not in excepts and not msg: return False
        return True

    def dump(self, topic):
        if not self.bag:
            raise Exception('Cannot dump '+topic+' : no bag opened')
        if isinstance(topic,list):
            return [self.dump(t) for t in topic]
        if topic not in self.recorded_topics:
            self.check_topic(topic)
            rospy.loginfo('Checking for '+topic+' again')
            return
        if not self.lastMessages[topic]:
            return
        while self._latches[topic]: pass
        self._latches[topic] = True
        self._bag_latch = True
        message = self.lastMessages[topic]
        try:
            self.bag.write(self.recorded_topics[topic], message)
            self.publishers[topic].publish(message)
            self.lastMessages[topic] = None
            return message
        finally:
            self._latches[topic] = False
            self._bag_latch = False

    def dump_all(self):
        return self.dump(self.topics)


# 扩展的表格控件（QTableWidget）
# QTableWidget是QTableView的子类
# 每一个Cell（单元格）是一个QTableWidgetItem

import sys
from PyQt5.QtWidgets import (QWidget, QTableWidget, QHBoxLayout, QApplication, QTableWidgetItem, QAbstractItemView)

class TableWidgetDemo(QWidget):
    def __init__(self):
        super(TableWidgetDemo,self).__init__()
        self.initUI()

    def initUI(self):
        self.setWindowTitle("QTableWidget演示")
        self.resize(430, 230);
        layout = QHBoxLayout()
        tablewidget = QTableWidget()        # 创建QTableWidget对象
        tablewidget.setRowCount(4)          # 设置行数
        tablewidget.setColumnCount(3)       # 设置列数

        layout.addWidget(tablewidget)

        tablewidget.setHorizontalHeaderLabels(['姓名','年龄','籍贯'])     # 设置字段名称
        nameItem = QTableWidgetItem("小明")
        tablewidget.setItem(0,0,nameItem)

        ageItem = QTableWidgetItem("24")
        tablewidget.setItem(0,1,ageItem)

        jgItem = QTableWidgetItem("北京")
        tablewidget.setItem(0,2,jgItem)

        # 禁止编辑
        tablewidget.setEditTriggers(QAbstractItemView.NoEditTriggers)       # 设置禁止编辑

        # 整行选择
        tablewidget.setSelectionBehavior(QAbstractItemView.SelectRows)
        # 调整列和行（即行与列的大小根据内容调整）
        tablewidget.resizeColumnsToContents()
        tablewidget.resizeRowsToContents()

        # 隐藏或显示水平与垂直表格字段名称
        tablewidget.horizontalHeader().setVisible(True)        # 设置水平表头是否可见
        tablewidget.verticalHeader().setVisible(False)         # 设置垂直头是否课件

        tablewidget.setVerticalHeaderLabels(["a","b"])      # 设置垂直的头名称

        # 隐藏表格线
        tablewidget.setShowGrid(True)       # 设置单元格的网格线是否可见

        self.setLayout(layout)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    example = TableWidgetDemo()
    example.show()
    sys.exit(app.exec_())


import tkinter as tk
import tensorflow as tf
from tensorflow import keras
from litemodel import LiteModel
import chess
import chess.svg
import sys
from PIL import Image
import PIL.ImageTk as ImageTk
import cairosvg
import io
import controller

class MainWindow(tk.Frame):
    def __init__(self, parent, *args, **kwargs):
        tk.Frame.__init__(self, parent, *args, **kwargs)
        self.parent = parent

        self.board = chess.Board()
        self.columnconfigure(index=0, weight=1)
        self.rowconfigure(index=0, weight=1)
        self.canvas = tk.Canvas(self, width=400, height=400)
        self.input = tk.Entry(self)
        self.input.bind("<Return>", self.player_move)
        self.canvas.grid(row=0, column=0, sticky="nsew")
        self.input.grid(row=1, column=0, sticky="ew")
        self.imgid = None
        self.redraw()
        self.load_model()

    def load_model(self):
        model = keras.models.load_model("model-10gen.h5")
        self.model = LiteModel.from_keras_model(model)

    def player_move(self, event):
        try:
            move = chess.Move.from_uci(self.input.get())
        except:
            return
        if not self.board.is_legal(move):
            return
        self.input.delete(0, tk.END)
        self.board.push(move)
        self.redraw()
        if self.board.is_game_over():
            self.game_over(True)
            return
        self.model_move()

    def model_move(self):
        move = controller.choose_move(self.board, self.model)
        self.board.push(move)
        self.redraw()
        if self.board.is_game_over():
            self.game_over(False)

    def game_over(self, win):
        self.input.delete(0, tk.END)
        self.input.insert(0, "YOU WIN" if win else "YOU LOSE")
        self.input.configure(state="disabled")

    def redraw(self):
        if self.imgid is not None:
            self.canvas.delete(self.imgid)
        svg = chess.svg.board(self.board).encode("utf-8")
        img_data = cairosvg.svg2png(bytestring=svg)#, parent_width=self.canvas.winfo_width(), parent_height=self.canvas.winfo_height())
        image = Image.open(io.BytesIO(img_data))
        tk_image = ImageTk.PhotoImage(image)
        self.imgid = self.canvas.create_image(0, 0, anchor="nw", image=tk_image)
        self.canvas.image = tk_image

if __name__ == "__main__":
    root = tk.Tk()
    MainWindow(root).pack(side="top", fill="both", expand=True)
    root.mainloop()


import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0,10,100)
y = np.sin(x)

#Contours
def f(x, y):
    return np.sin(x) ** 10 + np.cos(10 + y * x) * np.cos(x)

x = np.linspace(0, 5, 50)
y = np.linspace(0, 5, 40)

X, Y = np.meshgrid(x, y)
Z = f(X, Y)
plt.contourf(X,Y,Z,20,cmap='RdGy')


#!/usr/bin/python

import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk

from view.view_window import ViewWindow

DB_PATH = '/home/wayne/Documents/school/thesis/unicellular-grn/data/dbs/run0.db'

def main():
    win = ViewWindow(DB_PATH)
    win.connect("destroy", Gtk.main_quit)
    Gtk.main()

main()


import sys, pathlib, re, string, pprint

class Bookmark:
    def __init__(self):
        self.source = SourceData()
        self.pageData = PageData()
        self.html = Html()
        self.css = Css()

    def make(self, sourcePath, dest):
        lines = self.source.get(sourcePath)
        pageData = self.pageData.get(lines)
        html = self.html.generate(pageData)
        self.html.write(html, sourcePath, dest)
        self.css.setup(dest)

class SourceData:
    def get(self, sourcePath):
        with open(sourcePath, encoding='utf-8') as f:
            lines = f.readlines()
        cleaned = self.clean(lines)
        return cleaned

    def clean(self, lines):
        striped = [self.strip(l) for l in lines]
        proper = [l for l in striped if not self.is_ignore(l)]
        return proper

    def strip(self, line):
        withoutComment = re.sub(';;.*', '', line)
        striped = withoutComment.strip()
        return striped

    def is_ignore(self, line):
        if line.startswith('title:'):
            return False
        if re.match('>>>.+', line):
            return False
        if '---' in line:
            return False
        return True

class PageData:
    def get(self, lines):
        title = self.getTitle(lines[0])
        groups = self.getGroups(lines[1:]) # タイトルは除く

        return {
            'title': title,
            'groups': groups
        }

    def getTitle(self, text):
        title = 'Bookmark'
        if text.startswith('title:'):
            title = text.replace('title:','').strip()
        return title

    def getGroups(self, lines):
        separated = self.separateByGroup(lines)
        groups = []
        for groupChank in separated:
            groups.append(self.getGroupData(groupChank))
        return groups

    def separateByGroup(self, lines):
        groups = []
        group = []
        for l in lines:
            if l.startswith('>>>'):
                groups.append(group)
                group = []
                group.append(l)
                continue
            group.append(l)
        groups.append(group)

        if not groups[0]:  # 通常、先頭は空リスト（[]）
            groups = groups[1:]
        return groups

    def getGroupData(self, groupChank):
        title = 'No Title'
        if groupChank[0].startswith('>>>'):
            title = groupChank[0].replace('>>>', '').strip()
            groupChank = groupChank[1:]

        return {
            'title': title,
            'links': groupChank
        }

class Html:
    def generate(self, pageData):
        pageTitle = pageData['title']
        groupsHtml = '\n'.join(self.groupsHtml(pageData['groups']))
        d = dict(title=pageTitle, groups=groupsHtml)
        s = string.Template(Template.page)
        html = s.safe_substitute(d)
        return html

    def groupsHtml(self, groups):
        html = []
        for g in groups:
            html.append('{}
'.format(self.indent(2)))
            html.append('{}
{}
'.format(self.indent(3), g['title']))
            html.extend(self.groupHtml(g['links']))
            html.append('{}
'.format(self.indent(2)))
        return html

    def groupHtml(self, links):
        html = []
        html.append('{}
'.format(self.indent(3)))
        for l in links:
            html.append('{}
{}
'.format(self.indent(4), self.linkHtml(l)))
        html.append('{}
'.format(self.indent(3)))
        return html

    def linkHtml(self, link):
        # link: 'title---url'
        title, url = link.split('---')
        html = '{}'.format(url, title)
        return html

    def indent(self, depth):
        return '  ' * depth

    def write(self, html, sourcePath, dest):
        htmlPath = sourcePath.with_suffix('.html')
        htmlPath = dest.joinpath(htmlPath.name)
        if not dest.exists():
            dest.mkdir(parents=True)
        with open(htmlPath, 'w', encoding='utf-8') as f:
            f.write(html)

class Template:
    page = '''<!doctype html>

<title>${title}</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<link href="css/style.css" rel="stylesheet" type="text/css">
<link href="https://use.fontawesome.com/releases/v6.1.1/css/all.css" rel="stylesheet">

${title}

${groups}

'''

class Css:
    code = '''
* {
	margin: 0;
	padding:0;
}

body {
    background: rgb(202, 201, 194);
    color:rgb(129, 129, 129);
}

#contents {
	padding: 1em 1em;
}

h1 {
    color: rgb(105, 42, 105);
    font-weight: normal;
    margin: 0.25em 0em 0.5em 0em;
    font-size: 160%;
    letter-spacing: 0.16em;
}

h2 {
	padding: 0.5em;
    border-top: solid 2px #e000e0;
	background: #535;
    letter-spacing: 0.16em;
	font-size: medium;
	font-width: normal;
	font-weight: normal;
	color: #E1B8ED;
}

.group {
	padding-left: 1px;
	font-size: normal;
	letter-spacing: 0.05em;
}

li {
    position: relative; /* font awsome 用 */
	list-style-type: none;
    border-bottom: dotted 1px #767;
    line-height: 2em;
	color: #4c0e5f;
}

li::before {
    font-family: "Font Awesome 6 Free";
    font-weight: 900;
    content: '\\f138';
    position: absolute;
    left: 0.5em;
    top: 0.5em;
    /*color:#e000e0;*/
}

a {
    display: block;
    background: url("../img/linkmark.png") 1em 1em no-repeat;
    padding: 0.5em 1em 0.5em 2.25em;
    color:rgb(76, 0, 92);
	text-decoration: none;

}

a:hover {
    background-color: rgb(182, 180, 169);
    color:rgb(61, 61, 61)
}
    '''
    def setup(self, dest):
        cssDir = dest.joinpath('css')
        cssFile = dest.joinpath('css', 'style.css')
        if cssFile.exists():
            return
        if not cssDir.exists():
            cssDir.mkdir(parents=True)
        cssFile.write_text(self.code, encoding='utf-8')

Usage = '\nUsage: python bookmark.py source [destination]\n'

def main(args):
    if len(args) < 2:
        print(Usage)
        return
    sourcePath = pathlib.Path(args[1])
    dest = pathlib.Path(args[2]) if len(args) > 2 else sourcePath.parent # 無ければsourcePathと同じディレクトリ
    Bookmark().make(sourcePath, dest)

if __name__ == '__main__':
    main(sys.argv)


class hiddenMarkovTag():
    '''隐马尔科夫模型用于词性标注'''
    def __init__(self):
        '''先对各项参数初始化'''

        #以下为频数矩阵     #注意构造字典类型
        self.meta_vec={}       #原始概率向量，即各个词性作为句子开头的概率
        self.tran_matrix={}     #转移矩阵，从一个词性转移到另一个词性的概率
        self.emit_matrix={}     #发射矩阵，各个词性所对应特定词语的概率
        self.tag_count={}      #用于统计各个词性出现的次数
        self.tag_statis=[]      #用于记录出现过的tag
        self.all_tags=0

        #以下为概率矩阵
        self.pmeta_vec={}
        self.ptran_matrix={}
        self.pemit_matrix={}

    def makeMatrix(self,filename):
        '''统计词频并填充频数矩阵'''

        sentEnd=[',','。']  #标识句子的结束
        #先读出各个词性的个数
        with open(filename,'r',encoding='utf8') as fuckee:  #先读取文件
            lines=fuckee.readlines()
            count=0
            for line in lines:
                line=line.strip()   #去掉换行符
                words=line.split("  ")  #把词语分割出来
                for word in words:
                    for i in range(len(word)):  #读到斜线分隔符时计数，
                        if word[i]=='/':
                            count=i
                    tag=word[count:]        #将分隔符之后的字符计为标签
                    if tag not in self.tag_statis:
                        self.tag_statis.append(tag)     #如果标签不在list里面就加进去

          #  print(self.tag_statis)

            for taige in self.tag_statis:       #在统计频数之前再对每个矩阵的结构进行一下构造
                self.tag_count[taige]=0
                self.meta_vec[taige]=0
                self.tran_matrix[taige]={}
                self.emit_matrix[taige]={}      #发射矩阵再进行处理的时候再具体构造
                for ta in self.tag_statis:
                    self.tran_matrix[taige][ta]=0.0

            for line in lines:
                voca_list=[]    #存储本行单词的list
                voca_tag_list=[]    #存储本行词性的list
                line=line.strip()
                group=line.split('  ')  #将一个词加词性看成一个小组
                for member in group:
                    for i in range(len(member)):
                        if member[i]=='/':
                            count=i
                    voca_tag=member[count:]     #分别记录单词与词性
                    voca=member[:count]
                    voca_list.append(voca)
                    voca_tag_list.append(voca_tag)

                    #之后对矩阵进行填充，对每行的第一个词要进行单独处理
                for i in range(len(voca_list)):
                    try:
                        self.all_tags+=1
                        if i!=0 and voca_list[i-1] in sentEnd:                        #对句号后面的第一个词进行处理
                            self.tag_count[voca_tag_list[i]]+=1
                            self.meta_vec[voca_tag_list[i]]+=1
                            if voca_list[i] in self.emit_matrix[voca_tag]:      #处理发射矩阵
                                self.emit_matrix[voca_tag_list[i]][voca_list[i]]+=1
                            else:
                                self.emit_matrix[voca_tag_list[i]][voca_list[i]]=1
                        else:
                            self.tag_count[voca_tag_list[i]]+=1
                            self.tran_matrix[voca_tag_list[i-1]][voca_tag_list[i]]+=1
                            if voca_list[i] in self.emit_matrix[voca_tag]:
                                self.emit_matrix[voca_tag_list[i]][voca_list[i]]+=1
                            else:
                                self.emit_matrix[voca_tag_list[i]][voca_list[i]]=1
                    except KeyError:
                        pass

    def prob_calc(self):
        '''将频数矩阵转换为概率矩阵'''
        #处理初始向量
        meta_sun=sum(self.meta_vec.values())
        for tag in self.meta_vec:
            self.pmeta_vec[tag]=self.meta_vec[tag]/meta_sun
        #对状态转移矩阵和发射矩阵，采用加1法对二者进行平滑
        for tag in self.tran_matrix:
            self.ptran_matrix[tag]={}
            #状态转移矩阵
            for tage in self.tag_statis:
                self.tran_matrix[tag][tage]+=1
                self.ptran_matrix[tag][tage]=float(self.tran_matrix[tag][tage]/self.tag_count[tag])

        for tag in self.emit_matrix:
            self.pemit_matrix[tag]={}
            #发射矩阵
            for word in self.emit_matrix[tag]:
                self.pemit_matrix[tag][word]=float((self.emit_matrix[tag][word]+1)/self.tag_count[tag])    #进行除法前加1平滑

    def viterbi(self,sequence):
        '''使用维特比算法寻找最大词性序列'''
        self.vito=[{}]
        self.path={}    #存储路径
        self.obj_len=0  #观测序列的长度
        sentence=[]
        self.wordee=[]
        #输入时以两个空格作为分割
        words=sequence.split('  ')
        for word in words:
            sentence.append(word)      #生成观测序列
            self.wordee.append(word)
            self.obj_len+=1
        #根据概率初始向量初始化
        for state in self.tag_statis:
            self.vito[0][state]=self.pmeta_vec[state]*self.pemit_matrix[state].get(sentence[0],0.000001)
            self.path[state]=[state]        #路径上的第一个值设置为

        #进行动态规划
        for t in range(1,len(sentence)):
            self.vito.append({})
            new_path={}
            for statei in self.tag_statis:
                possible_path=[]        #存储各种可能的状态转移的概率
                for statej in self.tag_statis:  #从i状态到j状态
                    if self.vito[t-1][statej]!= 0:
                        cur_prob=self.vito[t-1][statej]*self.ptran_matrix[statej].get(statei,0)*self.pemit_matrix[statei].get(sentence[t],0.000001) #对于此状态时的转移概率
                        possible_path.append((cur_prob,statej)) #当前的转移状态及其所对应的概率
                if(possible_path):
                    best_cur_path=max(possible_path)        #从状态i到状态j的最大可能路径

                self.vito[t][statei]=best_cur_path[0]   #记录从statei 产生观测字t的概率
                new_path[statei]=self.path[best_cur_path[1]]+[statei]
            self.path=new_path          #更新路径状态
        #print(self.path)
        #通过回溯搜索最优路径
        self.prob, state = max([(self.vito[len(sentence) - 1][state], state) for state in self.tag_statis])
       # print(self.vito)
        return state

    def taGGing(self,sequence):
        '''对输入的序列标注结果输出'''
        self.tagOutput=''
        tagState=self.viterbi(sequence)
        # with open('caonima.txt','w',encoding='utf-8') as mmp:
        #     print(self.path,file=mmp)
        #     print(tagState,file=mmp)
        for i in range(self.obj_len):
            tage=self.path[tagState][i]
            self.tagOutput=self.tagOutput+self.wordee[i]+ tage+'  '
        print(self.tagOutput)

if __name__ == "__main__":
    testtt=hiddenMarkovTag()

    testtt.taGGing('我  需要  台灯')


# Import libraries
import openmdao.api as om
import numpy as np
import dymos as dm
import matplotlib.pyplot as plt
from paropt.paropt_sparse_driver import ParOptSparseDriver

class ODESystem1(om.ExplicitComponent):
    def initialize(self):
        # Define obstacles
        self.x0 = 8
        self.y0 = 6
        self.x1 = 5
        self.y1 = 5
        self.x2 = 8
        self.y2 = 8

        # Define penalty
        self.p = 45.0

        # Declare options
        self.options.declare("num_nodes", types=int)

    def setup(self):
        nn = self.options["num_nodes"]
        # Inputs
        self.add_input("x", val=np.zeros(nn), desc="Horizontal Position", units="m")
        self.add_input("y", val=np.zeros(nn), desc="Vertical Position", units="m")
        self.add_input("theta", val=np.zeros(nn), desc="angle of wire", units="rad")

        # outputs
        self.add_output(
            "xdot", val=np.zeros(nn), desc="horizontal velocity", units="m/s"
        )
        self.add_output("ydot", val=np.zeros(nn), desc="vertical velocity", units="m/s")
        self.add_output(
            "cflag", val=np.zeros(nn), desc="collision detection", units="m"
        )

        # Setup partials
        arange = np.arange(self.options["num_nodes"], dtype=int)
        self.declare_partials(of="xdot", wrt="theta", rows=arange, cols=arange)
        self.declare_partials(of="ydot", wrt="theta", rows=arange, cols=arange)
        self.declare_partials(of="xdot", wrt="x", rows=arange, cols=arange)
        self.declare_partials(of="ydot", wrt="x", rows=arange, cols=arange)
        self.declare_partials(of="xdot", wrt="y", rows=arange, cols=arange)
        self.declare_partials(of="ydot", wrt="y", rows=arange, cols=arange)
        self.declare_partials(of="cflag", wrt="x", rows=arange, cols=arange)
        self.declare_partials(of="cflag", wrt="y", rows=arange, cols=arange)

    def compute(self, inputs, outputs):
        theta = inputs["theta"]
        x = inputs["x"]
        y = inputs["y"]
        cos_theta = np.cos(theta)
        sin_theta = np.sin(theta)
        r0 = np.sqrt((x - self.x0) ** 2 + (y - self.y0) ** 2) + 0.01
        r1 = np.sqrt((x - self.x1) ** 2 + (y - self.y1) ** 2) + 0.01
        r2 = np.sqrt((x - self.x2) ** 2 + (y - self.y2) ** 2) + 0.01

        cflag = (
            1.0
            / (1.0 + np.exp(-self.p * (r0 - 1.0)))
            * 1.0
            / (1.0 + np.exp(-self.p * (r1 - 1.0)))
            * 1.0
            / (1.0 + np.exp(-self.p * (r2 - 1.0)))
        )
        outputs["xdot"] = 5.0 * cflag * cos_theta
        outputs["ydot"] = 5.0 * cflag * sin_theta
        outputs["cflag"] = cflag

    def compute_partials(self, inputs, jacobian):
        theta = inputs["theta"]
        x = inputs["x"]
        y = inputs["y"]
        cos_theta = np.cos(theta)
        sin_theta = np.sin(theta)

        r0 = np.sqrt((x - self.x0) ** 2 + (y - self.y0) ** 2) + 0.01
        r1 = np.sqrt((x - self.x1) ** 2 + (y - self.y1) ** 2) + 0.01
        r2 = np.sqrt((x - self.x2) ** 2 + (y - self.y2) ** 2) + 0.01

        cflag = (
            1.0
            / (1.0 + np.exp(-self.p * (r0 - 1.0)))
            * 1.0
            / (1.0 + np.exp(-self.p * (r1 - 1.0)))
            * 1.0
            / (1.0 + np.exp(-self.p * (r2 - 1.0)))
        )

        jacobian["xdot", "theta"] = -5 * cflag * sin_theta
        jacobian["ydot", "theta"] = 5 * cflag * cos_theta

        cflag__r0 = (
            cflag
            / (1.0 + np.exp(-self.p * (r0 - 1.0)))
            * (self.p)
            * np.exp(-self.p * (r0 - 1.0))
        )
        cflag__r1 = (
            cflag
            / (1.0 + np.exp(-self.p * (r1 - 1.0)))
            * (self.p)
            * np.exp(-self.p * (r1 - 1.0))
        )
        cflag__r2 = (
            cflag
            / (1.0 + np.exp(-self.p * (r2 - 1.0)))
            * (self.p)
            * np.exp(-self.p * (r2 - 1.0))
        )
        r0__x = (x - self.x0) / r0
        r0__y = (y - self.y0) / r0
        r1__x = (x - self.x1) / r1
        r1__y = (y - self.y1) / r1
        r2__x = (x - self.x2) / r2
        r2__y = (y - self.y2) / r2

        jacobian["cflag", "x"] = (
            cflag__r0 * r0__x + +cflag__r1 * r1__x + +cflag__r2 * r2__x
        )
        jacobian["cflag", "y"] = (
            cflag__r0 * r0__y + +cflag__r1 * r1__y + +cflag__r2 * r2__y
        )

        xdot__cflag = 5 * cos_theta
        ydot__cflag = 5 * sin_theta

        jacobian["xdot", "x"] = xdot__cflag * jacobian["cflag", "x"]
        jacobian["xdot", "y"] = xdot__cflag * jacobian["cflag", "y"]

        jacobian["ydot", "x"] = ydot__cflag * jacobian["cflag", "x"]
        jacobian["ydot", "y"] = ydot__cflag * jacobian["cflag", "y"]

def pen_f(r0, r1, r2):
    p = 45
    return (
        1
        / (1 + np.exp(-p * (r0 - 1)))
        * 1
        / (1 + np.exp(-p * (r1 - 1)))
        * 1
        / (1 + np.exp(-p * (r2 - 1)))
    )

# Define the OpenMDAO problem
p = om.Problem(model=om.Group())

# Define a Trajectory object
traj = p.model.add_subsystem("traj", subsys=dm.Trajectory())

# Define a Dymos Phase object with GaussLobatto Transcription
n_segments = 20
transcript = dm.GaussLobatto(num_segments=n_segments, order=3)
phase = dm.Phase(ode_class=ODESystem1, transcription=transcript)
traj.add_phase(name="phase0", phase=phase)

# Set the time options
# Time has no targets in our ODE.
# We fix the initial time so that the it is not a design variable in the optimization.
# The duration of the phase is allowed to be optimized, but is bounded on [0.5, 10].
phase.set_time_options(
    initial_bounds=(0, 0), duration_bounds=(0.5, 10.0), units="s"  # fix_initial = True,
)

# Set the time options
# Initial values of positions and velocity are all fixed.
# The final value of position are fixed, but the final velocity is a free variable.
# The equations of motion are not functions of position, so 'x' and 'y' have no targets.
# The rate source points to the output in the ODE which provides the time derivative of the given state.
phase.add_state(
    "x", rate_source="xdot", units="m", fix_initial=True, fix_final=True, targets=["x"]
)

phase.add_state(
    "y", rate_source="ydot", units="m", fix_initial=True, fix_final=True, targets=["y"]
)

# Define theta as a control.
phase.add_control(
    name="theta", targets=["theta"], units="rad", lower=-np.pi / 2, upper=np.pi / 2
)

# Define constraints
phase.add_timeseries_output("cflag", output_name="cflag", units="m")

# Minimize final time.
phase.add_objective("time", loc="final")

# Setup the problem
p.setup(check=True)

p.set_val(
    "traj.phase0.states:x",
    phase.interpolate(xs=[0, 1, 2], ys=[0, 5, 10], kind="linear", nodes="state_input"),
    units="m",
)

# initialize 0: left, 1: middle, 2: right
init = 1
if init == 0:
    p.set_val(
        "traj.phase0.states:y",
        phase.interpolate(
            xs=[0, 1, 2], ys=[0, 8, 10], kind="quadratic", nodes="state_input"
        ),
        units="m",
    )
elif init == 1:
    p.set_val(
        "traj.phase0.states:y",
        phase.interpolate(ys=[0, 10], nodes="state_input"),
        units="m",
    )
elif init == 2:
    p.set_val(
        "traj.phase0.states:y",
        phase.interpolate(
            xs=[0, 1, 2], ys=[0, 2, 10], kind="quadratic", nodes="state_input"
        ),
        units="m",
    )

p.set_val(
    "traj.phase0.controls:theta",
    phase.interpolate(ys=[-5, 5], nodes="control_input"),
    units="deg",
)

p["traj.phase0.t_duration"] = 3.0
p["traj.phase0.t_initial"] = 0.0

# Set up the optimization driver
p.driver = ParOptSparseDriver()

options = {
    "algorithm": "ip",
    "norm_type": "infinity",
    "qn_type": "bfgs",
    "qn_subspace_size": 10,
    "starting_point_strategy": "least_squares_multipliers",
    "qn_update_type": "damped_update",
    "abs_res_tol": 1e-6,
    "barrier_strategy": "monotone",
    "armijo_constant": 1e-5,
    "penalty_gamma": 100.0,
    "max_major_iters": 500,
}

for key in options:
    p.driver.options[key] = options[key]

# Allow OpenMDAO to automatically determine our sparsity pattern.
# Doing so can significantly speed up the execution of Dymos.
p.driver.declare_coloring(show_summary=True, show_sparsity=True)

# Run the driver to solve the problem
p.run_driver()
print(p.get_val("traj.phase0.timeseries.time")[-1])

# Check the validity of our results by using scipy.integrate.solve_ivp to integrate the solution.
sim_out = traj.simulate()

# Plot the results
fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(12, 4.5))
axes[0].plot(
    p.get_val("traj.phase0.timeseries.states:x"),
    p.get_val("traj.phase0.timeseries.states:y"),
    "ro",
    label="Solution",
)
axes[0].plot(
    sim_out.get_val("traj.phase0.timeseries.states:x"),
    sim_out.get_val("traj.phase0.timeseries.states:y"),
    "b-",
    label="Simulation",
)
axes[0].set_xlabel("x (m)")
axes[0].set_ylabel("y (m)")
axes[0].legend()
axes[0].grid()

axes[1].plot(
    p.get_val("traj.phase0.timeseries.time"),
    p.get_val("traj.phase0.timeseries.cflag", units="m"),
    "ro",
    label="Solution",
)
axes[1].plot(
    sim_out.get_val("traj.phase0.timeseries.time"),
    sim_out.get_val("traj.phase0.timeseries.cflag", units="m"),
    "b-",
    label="Simulation",
)
axes[1].set_xlabel("time (s)")
axes[1].set_ylabel("$v$ (m/s)")
axes[1].legend()
axes[1].grid()

ode = ODESystem1()
ode.initialize()

# Add circles
circle0 = plt.Circle((ode.x0, ode.y0), 1, color="k", fill=False, hatch="///")
circle1 = plt.Circle((ode.x1, ode.y1), 1, color="k", fill=False, hatch="///")
circle2 = plt.Circle((ode.x2, ode.y2), 1, color="k", fill=False, hatch="///")
axes[0].add_artist(circle0)
axes[0].add_artist(circle1)
axes[0].add_artist(circle2)

# Additional plots
x_v = np.linspace(0, 10, 50)
y_v = np.linspace(0, 10, 50)
x_m, y_m = np.meshgrid(x_v, y_v)
r0_m = np.sqrt((x_m - ode.x0) ** 2 + (y_m - ode.y0) ** 2)
r1_m = np.sqrt((x_m - ode.x1) ** 2 + (y_m - ode.y1) ** 2)
r2_m = np.sqrt((x_m - ode.x2) ** 2 + (y_m - ode.y2) ** 2)
eta_m = pen_f(r0_m, r1_m, r2_m)
z_m = 5 * eta_m
fig, ax = plt.subplots(1, 1)
cplot = ax.contourf(x_m, y_m, z_m)
cbar = fig.colorbar(cplot)  # Add a colorbar to a plot
cbar.set_label("velocity (m/s)")
ax.set_xlabel("x position (m)")
ax.set_ylabel("y position (m)")
ax.grid()

# Add circles
circle0 = plt.Circle((ode.x0, ode.y0), 1, color="k", fill=False)
circle1 = plt.Circle((ode.x1, ode.y1), 1, color="k", fill=False)
circle2 = plt.Circle((ode.x2, ode.y2), 1, color="k", fill=False)
ax.add_artist(circle0)
ax.add_artist(circle1)
ax.add_artist(circle2)

plt.show()


import subprocess
from InstallerException import InstallerException
from fetcher import fetcher
import shutil, os

##
# The untar fetcher
#
class untar(fetcher):
  fetcher = None
  dirname = None
  compressed = True

  ##
  # Constructor
  # @param fetcher: the fetcher that returns a tar ball
  # @param dirname: the directory name that will be the outcome when extracting the tarball
  # @param compressed: If this tar ball is compressed or not
  #
  def __init__(self, fetcher, dirname, compressed=True):
    super(untar, self).__init__()
    self.fetcher = fetcher
    self.dirname = dirname
    self.compressed = compressed

  ##
  # Fetches and extracts the tar ball
  # @param package: the package to fetch
  # @param env: the build environment
  # @return: the directory that was the result of this tar extraction
  #
  def dofetch(self, package, env=None):
    filename = self.fetcher.fetch(package, env)
    args = ""
    if self.compressed == True:
      args = "-xvzf"
    else:
      args = "-xvf"

    code = subprocess.call("tar %s %s"%(args,filename), shell=True)
    if code != 0:
      raise InstallerException("Failed to extract software %s"%self.name)

    return self.dirname

  ##
  # Removes the tar ball and directory
  #
  def doclean(self, package, env=None):
    self.fetcher.clean(package, env)
    if os.path.exists(self.dirname):
      if self.dirname not in [".", "..", "/", "../", "./"]:
        shutil.rmtree(self.dirname, True)

  ##
  # Executes the fetcher
  # @param package: the package to fetch
  # @param env: the build environment
  #
  def dofetch_offline_content(self, package, env=None):
    self.fetcher.dofetch_offline_content(package, env)
    if os.path.exists(self.dirname):
      if self.dirname not in [".", "..", "/", "../", "./"]:
        shutil.rmtree(self.dirname, True)


"""
Created on Thu Jan 14 13:44:00 2016
Updated Jan 21, 2018

The primary goal of this file is to demonstrate a simple python program to classify triangles

@author: jrr
@author: rk
@author: Yukai Tan
"""

    # require that the input values be >= 0 and <= 200
def classify_triangle(a_side, b_side, c_side):
    """require that the input values be >= 0 and <= 200"""
    if a_side > 200 or b_side > 200 or c_side > 200:
        return 'InvalidInput'

    if a_side <= 0 or b_side <= 0 or c_side <= 0:
        return 'InvalidInput'

    # verify that all 3 inputs are integers
    # Python's "isinstance(object,type) returns True if the object is of the specified type
    if not(isinstance(a_side, int) and isinstance(b_side, int) and isinstance(c_side, int)):
        return 'InvalidInput'

    # This information was not in the requirements spec but
    # is important for correctness
    # the sum of any two sides must be strictly less than the third side
    # of the specified shape is not a triangle
    if (a_side + b_side <= c_side) or (a_side + c_side <= b_side) or (b_side + c_side <= a_side):
        return 'NotATriangle'

    # now we know that we have a valid triangle
    ans = ''
    if a_side == b_side and b_side == c_side:
        ans = 'Equilateral'
    elif ((a_side ** 2) + (b_side ** 2)) == (c_side ** 2) or \
        ((a_side ** 2) + (c_side ** 2)) == (b_side ** 2) or \
            ((b_side ** 2) + (c_side ** 2)) == (a_side ** 2):
        ans = 'Right'
    elif (a_side != b_side) and (b_side != c_side) and (a_side != c_side):
        ans = 'Scalene'
    else:
        ans = 'Isoceles'

    return ans


import numpy as np
import matplotlib.pyplot as plt

def gauss(mu, sigma):
    return np.exp(-(x-mu)**2/sigma**2) / (np.sqrt(2*np.pi)*sigma)

x = np.linspace(-4, 8, 100)
plt.figure(figsize=(4,4))
plt.plot(x, gauss(0, 1), 'black', linewidth=2, label='N(0,1)')
plt.plot(x, gauss(2, 3), 'gray', linewidth=3, label='X(2,3)')
plt.legend()
plt.ylim(-0.1, 0.5)
plt.xlim(-4, 8)
plt.xlabel('x')
plt.ylabel('probability density')
plt.title('Gaussian distribution')
plt.grid(True)
plt.show()


import logging

from telegram.ext import CallbackContext

def delete_message(context: CallbackContext) -> None:
    """
    A job which will delete the given message
    The context (in context.job.context) is a dict that looks like this:
    {
        "chat_id": 1234,
        "message_id": 1234,
    }
    """
    logging.info("Deleting delayed message")

    chat_id = context.job.context["chat_id"]
    message_id = context.job.context["message_id"]
    logging.info(f"Chat ID: {chat_id}")
    logging.info(f"Message ID: {message_id}")

    context.bot.delete_message(chat_id, message_id)


import time
start_time=time.time()
def erasto(n):
	multiples=[]
	prim=[]
	for i in range (2,n+1):
		if i not in multiples:
			#print(i)
			prim.append(i)
			for j in range(i*i,n+1,i):
				multiples.append(j)
	return(prim)

erasto(1000)

print (time.time() - start_time)


import sys
input = sys.stdin.readline

def ccw(x1, y1, x2, y2, x3, y3):
    temp = (x2-x1)*(y3-y1) - (y2-y1)*(x3-x1)
    if temp > 0: return 1
    elif temp < 0: return -1
    else: return 0

x1, y1, x2, y2 = map(int, input().split())
x3, y3, x4, y4 = map(int, input().split())

if ccw(x1, y1, x2, y2, x3, y3) * ccw(x1, y1, x2, y2, x4, y4) <= 0 and ccw(x3, y3, x4, y4, x1, y1) * ccw(x3, y3, x4, y4, x2, y2) <= 0:
    if ccw(x1, y1, x2, y2, x3, y3) * ccw(x1, y1, x2, y2, x4, y4) == 0 and ccw(x3, y3, x4, y4, x1, y1) * ccw(x3, y3, x4, y4, x2, y2) == 0:
        if min(x1, x2) <= max(x3, x4) and min(x3, x4) <= max(x1, x2) and min(y1, y2) <= max(y3, y4) and min(y3, y4) <= max(y1, y2):
            print(1)
        else:
            print(0)
    else:
        print(1)

else: print(0)