import numpy as np
import modules.som as som
from sklearn.metrics import silhouette_score
import modules.dna_encoder
import modules.quadatic_regression as quadres

# factorize is find numbers that could divide the input
def factorize(num: int) -> list():
    return [i for i in range(1,int((num+1)**0.5)+1) if num%i == 0]

# pick the best SOM model with the size of matrix_size
def best_matrix_size(X:list(), matrix_size: int, max_iter = 3000 , epoch = 1, learning_rate = 1, sigma = 1):
    factors = factorize(matrix_size)
    models = list()
    silhouette_scores = list()
    for num in factors:
        clustering_model = som.SOM(m=num, n=int(matrix_size/num), dim=X.shape[1], max_iter=max_iter, lr = learning_rate, sigma=sigma)
        clustering_model.fit(X, epochs= epoch)
        predictions = clustering_model.predict(X)
        models.append(clustering_model)
        silhouette_scores.append(silhouette_score(X, predictions))
    return models[np.array(silhouette_scores).argmax()], max(silhouette_scores)

def som_peak_test(X, som_hist, som_scores, max_iter=3000, epoch = 1, learning_rate = 1, sigma = 1):
    X_quadreg = [(model.m * model.n) for model in som_hist]
    y_quadreg = som_scores
    quad_model = quadres.quadratic_regression(X_quadreg,y_quadreg)
    best_size = int(quad_model.peak_point()[0])
    models_hist = list()
    models_silhouetterScore = list()
    if best_size-2 <= 1:
        min_size = best_size
        if best_size < 2:
            min_size = 2
    else:
        min_size = best_size-2
    if min_size + 3 > X.shape[1]-1:
        max_size = X.shape[1]-1
    else:
        max_size = min_size + 3
    for matrix_size in range(min_size,max_size):
        model, shs = best_matrix_size(X, matrix_size, max_iter=max_iter, epoch= epoch, learning_rate = learning_rate, sigma = sigma)
        models_hist.append(model)
        models_silhouetterScore.append(shs)
    return models_hist[np.array(models_silhouetterScore).argmax()], max(models_silhouetterScore)

def test_som(X, array_n_cluster, max_iter=3000, epoch = 1, learning_rate = 1, sigma = 1):
    models_hist = list()
    models_silhouetterScore = list()
    for n_cluster in array_n_cluster:
        model, silhouette_score = best_matrix_size(X, n_cluster, max_iter=max_iter, epoch= epoch, learning_rate = learning_rate, sigma = sigma)
        predictions = model.predict(X)
        models_hist.append(model)
        models_silhouetterScore.append(silhouette_score)

    # perform quadratic regression based on matrix size and silhouette score
    best_model, shs = som_peak_test(X, models_hist, models_silhouetterScore, max_iter=max_iter, epoch= epoch, learning_rate = learning_rate, sigma = sigma)
    return best_model, models_silhouetterScore
    # return models_hist[np.array(models_silhouetterScore).argmax()], max(models_silhouetterScore)

def find_model(X: np.ndarray, total_rep = 5, random_state = 5, max_iter = 3000, epoch = 1, learning_rate = 1, sigma = 1):
    """
    find_model() is a function to find the best size of matrix within range start from random_state value until random_state*total_rep

    Example:
    find_model(X, total_rep = 5, random_state = 5) would try matrix size of 5, 10, 15, 20, and 25

    Args:
        X (np.ndarray):
            Training data. Must have shape (n, m) where n is the number
            of training samples, and m is the number of the features.
        total_rep (int, optional):
            Maximum iteration of the matrix size.
            Defaults to 5.
        random_state (int, optional):
            Jumping value of the matrix size.
            Defaults to 5.
        max_iter (int, optional):
            Optional parameter to stop training if you reach this many interation.
            Defaults to 3000.
        epoch (int, optional):
            The number of times to loop through the training data when fitting.
            Defaults to 1.
        learning_rate (int, optional):
            The initial step size for updating the SOM weights.
            Defaults to 1.
        sigma (int, optional):
            Optional parameter for magnitude of change to each weight. Does not
            update over training (as does learning rate).
            Defaults to 1.

    Raises:
        ValueError: error if the total sample is less than total_reps*random_state.

    Returns:
        <modules.som.SOM object>: the highest silhouette score among all of the matrix size.
    """
    if X.shape[0] < total_rep*random_state:
        raise ValueError("The sample of the data not enough to iterates, minimum number of data is total_rep * random_state")
    else:
        # generates the list of matrix size
        if random_state == 1:
            array_n_cluster = [random_state*i for i in range(2,total_rep+2)]
        else :
            array_n_cluster = [random_state*i for i in range(1,total_rep+2)]

    models, shs = test_som(X, array_n_cluster, max_iter=max_iter, epoch = epoch, learning_rate = learning_rate, sigma=sigma)
    return models, shs


# 에라토스테네스의 체, 이분탐색
import sys

def prime_list(n):
    prime = [False for _ in range(n + 1)]
    for i in range(2, n + 1):
        if prime[i] == False:
            for j in range(i + i, n + 1, i):
                prime[j] = True

    return [i for i in range(2, n + 1) if prime[i] == False]

n = int(sys.stdin.readline())
answer = 0

prime = prime_list(n)
left = 0
right = 1

while left < right:
    temp = sum(prime[left:right])
    # 오른쪽 포인터가 소수 리스트의 끝까지 도달하면 종료
    if right == len(prime) + 1:
        break
    # 연속된 소수의 합이 N과 같으면
    if temp == n:
        # 경우의 수를 더해주고 왼쪽 포인터 1 증가
        answer += 1
        left += 1
    # 연속된 소수의 합이 N보다 작으면
    elif temp < n:
        # 오른쪽 포인터 1 증가
        right += 1
    # 연속된 소수의 합이 N보다 크면
    elif temp > n:
        # 왼쪽 포인터 1 증가
        left += 1

print(answer)


"""Contains tests for search view."""

import pytest

from django.urls import reverse

from eat_better.models import Product
from my_products.models import Substitution
from core.models import User

@pytest.mark.django_db
class TestSearch:

    def test_status_code(self, client, django_db_populated):
        context = {"product": "Cake aux fruits"}
        response = client.get(reverse("search"), context)
        assert response.status_code == 200

    def test_templates(self, client, django_db_populated):
        """Test search form."""
        context = {"product": "Cake aux fruits"}
        response = client.get(reverse("search"), context)
        templates = [t.name for t in response.templates]
        assert "eat_better/results.html" in templates

    def test_products_name_in_templates(self, client, django_db_populated):
        context = {"product": "Cake aux fruits"}
        response = client.get(reverse("search"), context)
        results = response.context["results"]
        content = response.content
        for product in results:
            byte_mark = bytes(f"{product.name}", 'utf-8')
            assert byte_mark in content

    def test_product_to_search(self, client, django_db_populated):
        context = {"product": "Cake aux fruits"}
        response = client.get(reverse("search"), context)
        product = response.context["product"]
        assert isinstance(product, Product)

    def test_searched_product_not_found(self, client, django_db_populated):
        context = {"product": "steack hachés"}
        response = client.get(reverse("search"), context)
        assert response.context["product"] == context["product"]

    def test_results(self, client, django_db_populated):
        context = {"product": "Cake aux fruits"}
        response = client.get(reverse("search"), context)
        assert len(response.context["results"]) != 0
        for product in response.context["results"]:
            assert isinstance(product, Product)

    def test_searched_product_is_already_healthy(self, client,
                                                 django_db_populated):
        searched_product = Product.objects.filter(nutriscore="a")[0]
        context = {"product": searched_product.name}
        response = client.get(reverse("search"), context)

        assert response.context["is_healthy"] is True

    def test_search_with_product_id(self, client, django_db_populated):
        product_id = 3803
        product = Product.objects.get(id=product_id)
        response = client.get(reverse("search_id",
                              kwargs={"id_product": product_id})
                              )

        assert response.context["product"] == product

    def test_product_saved(self, client, django_db_populated, user_for_test):
        original = Product.objects.get(id=3803)
        substitute = Product.objects.get(id=3781)
        user = User.objects.get(email="test@test.com")
        substitution, created = Substitution.objects.get_or_create(
                    user=user,
                    original=original,
                    substitute=substitute
                            )
        response = client.get(reverse("search_id",
                                      kwargs={"id_product": original.id})
                              )

        assert substitution.substitute in response.context["products_saved"]


"""Collection of auxiliary functions.

The functions are not related to any classes or file/data management.
"""
from typing import Optional, Any, List
import math

def water_density(temp: float) -> float:
    """Calculate water density in kg/m3 as a function of temperature
    in deg C. Eq. A.3 in Praire2021.
    """
    density = 1000 * (1 - (
        (temp + 288.9414) / (508_929.2 * (temp + 68.12963))) *
        (temp - 3.9863) ** 2)
    return density

def air_density(mean_temp: float) -> float:
    """Calculate air density in kg/m3. Eq. A.1 in Praire2021.

    Args:
        mean_temp: mean temperature in degC of the 4 warmest months in
            a year.
    """
    return 101325.0 / (287.05 * (mean_temp + 273.15))

def cd_factor(wind_speed: float) -> float:
    """Calculate CD coefficient, (-). Eq. A.6 in Praire2021.

    Args:
        wind_speed: reservoir mean wind speed, m/s.
    """
    return 1.3E-3 if wind_speed < 5.0 else 1.5E-5

def scale_windspeed(wind_speed: float, wind_height: float,
                    new_height: float) -> float:
    """Calculate wind speed at desired height base on the original wind speed
    at a known height.

    Parameters:
        wind_speed: known wind speed, m/s
        wind_height: known wind heigt, m
        new_height: new height for which wind speed is calculated.

    Note:
        Default wind_height it 50m.

    Returns:
        Wind speed at new_height, in m/s
    """
    return wind_speed / (1 - math.sqrt(cd_factor(wind_speed))/0.4 *
                         math.log10(new_height / wind_height))

def rollout_nested_list(
        nested_list: List[Any],
        out_list: Optional[List] = None) -> List[Any]:
    """
    This function takes a nested list and returns a flattened version of that list.

    Parameters:
        nested_list: A list containing other lists and/or non-list elements.
        out_list (optional): An empty list to store the flattened output.
    Returns:
        A flattened version of the nested_list.

    Example Usage:

    nested_list = [1, [2, 3], 4, [[5, 6], 7]]
    flattened_list = rollout_nested_list(nested_list)
    print(flattened_list) # prints [1, 2, 3, 4, 5, 6, 7]
    """
    if out_list is None:
        out_list = []
    while nested_list:
        item = nested_list.pop(0)
        if not isinstance(item, List):
            out_list.append(item)
        else:
            rollout_nested_list(item, out_list)
    return out_list


import json
import os

from chat_sentiment_analysis.prepare_data.data_object import get_dataset_class_by_name
from chat_sentiment_analysis.common import common_path
from chat_sentiment_analysis.utils import file_utils

if __name__ == '__main__':
    instructions = []
    sentences = []
    responses = []
    dataset_names = ['SemEval-2014-Task-4-REST']
    for dataset_name in dataset_names:
        dataset = get_dataset_class_by_name(dataset_name)()
        training_set = dataset.train_data
        for doc in training_set:
            absa_sentences = doc.absa_sentences
            for absa_sentence in absa_sentences:
                sentence = absa_sentence.text.strip()
                aspect_categories = []
                aspect_sentiment_pairs = []
                for category in absa_sentence.aspect_categories:
                    aspect_categories.append(category.category)
                    aspect_sentiment_pairs.append('(%s, %s)' % (category.category, category.polarity))

                instruction = 'detect aspect categories from the sentence'
                if len(aspect_categories) > 0:
                    response = ','.join(aspect_categories)
                else:
                    response = 'There are no aspect categories in the sentence'
                sentences.append(sentence)
                instructions.append(instruction)
                responses.append(response)

                instruction = 'detect aspect category-sentiment pairs from the sentence'
                if len(aspect_sentiment_pairs) > 0:
                    response = '; '.join(aspect_sentiment_pairs)
                else:
                    response = 'There are no aspect category-sentiment pairs in the sentence'
                sentences.append(sentence)
                instructions.append(instruction)
                responses.append(response)

    output_lines = []
    for i, instruction in enumerate(instructions):
        instance = {
            'instruction': instruction,
            'input': sentences[i],
            'output': responses[i]
        }
        output_lines.append(json.dumps(instance))

    output_dir = os.path.join(common_path.data_dir, 'task_data')
    output_filepath = os.path.join(output_dir, 'acsa.json')
    file_utils.write_lines(output_lines, output_filepath)


# This file will take the input and write to a new file the formatted country codes
import pandas as pd
import requests

def extract_country_codes():
	x = requests.get('https://www.att.com/support_media/images/pdf/Country_Code_List.pdf')
	with open("./wiki_country_codes.txt", 'w') as f:
		print(x.text)

#phone_code_dict = {'USA':, 'UK', 'FRANCE', 'SPAIN'}
def strip_number():
	df = pd.read_csv("./input.csv")
	for country, num in zip(df['country'], df['phone_number']):
		print (f'{country}  {num}')

if __name__ == "__main__":
	extract_country_codes()
	strip_number()


import numpy as np
from numpy.linalg.linalg import lstsq
import random

def GetTx(t):
    '''
        A:3 dim vector
        B:3 dim vector
        A x B = Ax @ B
        return Ax
    '''
    return np.array([
        [0,-t[2],t[1]],
        [t[2],0,-t[0]],
        [-t[1],t[0],0]
    ])

class LinearSolver:

    def __init__(self,n):
        self.n=n
        self.A=np.zeros((0,n))
        self.b=np.zeros(0)
    def Add(self,A,b):
        self.A=np.vstack((self.A,A))
        self.b=np.append(self.b,b)
    def AddByIndex(self,i_v,b):
        A=np.zeros(self.n)
        for i,v in i_v:
            A[i]=v
        self.Add(A,b)
    def Solve(self):
        return np.linalg.lstsq(self.A, self.b,rcond=-1)[0]

if __name__=='__main__':
    ls = LinearSolver(2)
    for i in range(10):
        for j in range(10):
            x=i
            y=2*j
            z=x+y+random.random()*0.01
            ls.Add(np.array([i,j],dtype=np.float32),z)
    print(ls.Solve())


## @file CircleADT.py
#  @title CircleT
#  @author Melissa Gonzales
#  @date 16/01/2017

import math
## @brief This class represents a circle
#  @details This class represents a circle as (x,y,r) values representing the
#  centre of the cirlce with x and y coordinates and r representing the radius
class CircleT:
## @brief constructor that initialises value of object
#  @param x is the x coordinate of the circle
#  @param y is the y coordinate of the circle
#  @param r is the radius of the circle
    def __init__ (self, x, y, r):
        self.r = r;
        self.x = x;
        self.y = y;
## @brief accessor that returns the x coordinate
#  @return the x coordinate of the circle object
    def xcoord(self):
        return self.x;
## @brief accessor that returns the y coordinate
#  @return the y coordinate of the circle object
    def ycoord(self):
        return self.y;
## @brief accessor that returns the radius
#  @return the radius of the circle object
    def radius(self):
        return self.r;
## @brief function that calculates the area of given circle
#  @details the Pi constant is used from the math library. This function will only return 2 decimal places
#  @return the area of the circle object
    def area(self):
        return round(math.pi*(self.r**2), 2);
## @brief function that calculates the circumference of given circle
#  @details the Pi constant is used from the math library. This function will only return 2 decimal places
#  @return the circumference of the circle object
    def circumference(self):
        return round(2*math.pi*(self.r), 2) ;
## @brief this function determines whether the circle is inside the box or not
#  @details assume that if the circle is enscribed in the box, returns true.
#  @param xNot top left x coordinate of box
#  @param yNot top left y coordinate of box
#  @param w width of box
#  @param h height of box
#  @return true or false depending if it is in the box
    def insideBox(self, xNot, yNot, w, h):
        x1 = self.x + self.r; #right side of circle, x coordinate
        x2 = self.x - self.r; #left side of circle, x coordinate
        y1 = self.y + self.r; #top side of circle, y coordinate
        y2 = self.y - self.r; #bottom side of circle, y coordinate

        boxX = xNot + w; #outer x coordinate of box
        boxY = yNot - h; #outer y coordinate of box

        areaC = math.pi*(self.r**2);
        areaB = math.fabs(w * h);
        if (areaC < areaB):
            if (xNot <= x2 <= boxX):
                if (xNot <= x1 <= boxX):
                    if (boxY <= y1 <= yNot ):
                        if (boxY <= y2 <= yNot):
                            return True;
                        else:
                            return False;
                    else:
                        return False;
                else:
                    return False;
            else:
                return False;
        else:
            return False;

## @brief This function checks if two circles intersect
#  @details assume that if a circle is a subset of another (i.e. overlaps) they intersect
#  @return true or false depending if the circles interesect
    def intersect(self,c):
        if (math.sqrt(((c.x - self.x)**2)+ (c.y - self.y)**2) <= (self.r + c.r)):
            return True;
        else:
            return False;
## @brief This function scales the radius
#  @param k number to scale radius by
    def scale(self,k):
        self.r = self.r * k;
## @brief This function translates the circle
#  @param dx amount to move x coordinate by
#  @param dy amount to move y coordinate by
    def translate(self,dx, dy):
        self.x = self.x + dx;
        self.y = self.y + dy;


"""
module for RINEX 3.0x processing
"""

import numpy as np
from cssrlib.gnss import uGNSS, uTYP, rSigRnx
from cssrlib.gnss import bdt2gpst, time2bdt
from cssrlib.gnss import gpst2time, bdt2time, epoch2time, timediff, gtime_t
from cssrlib.gnss import prn2sat, char2sys, timeget, utc2gpst, time2epoch
from cssrlib.gnss import Eph, Obs, sat2id, sat2prn, gpst2bdt, time2gpst

class pclk_t:
    def __init__(self, time=None):
        if time is not None:
            self.time = time
        else:
            self.time = gtime_t()
        self.clk = np.zeros(uGNSS.MAXSAT)
        self.std = np.zeros(uGNSS.MAXSAT)

class rnxdec:
    """ class for RINEX decoder """

    def __init__(self):

        self.ver = -1.0
        self.fobs = None

        # signal code mapping from RINEX header to columns in data section
        self.sig_map = {}
        # signal selection for internal data structure
        self.sig_tab = {}
        self.nsig = {uTYP.C: 0, uTYP.L: 0, uTYP.D: 0, uTYP.S: 0}

        self.pos = np.array([0, 0, 0])
        self.ecc = np.array([0, 0, 0])
        self.rcv = None
        self.ant = None
        self.ts = None
        self.te = None
        # 0:LNAV,INAV,D1/D2, 1:CNAV/CNAV1/FNAV, 2: CNAV2, 3: CNAV3,
        # 4:FDMA, 5:SBAS
        self.mode_nav = 0

    def setSignals(self, sigList):
        """ define the signal list for each constellation """

        for sig in sigList:
            if sig.sys not in self.sig_tab:
                self.sig_tab.update({sig.sys: {}})
            if sig.typ not in self.sig_tab[sig.sys]:
                self.sig_tab[sig.sys].update({sig.typ: []})
            if sig not in self.sig_tab[sig.sys][sig.typ]:
                self.sig_tab[sig.sys][sig.typ].append(sig)
            else:
                raise ValueError("duplicate signal {} specified!".format(sig))

        for _, sigs in self.sig_tab.items():
            for typ, sig in sigs.items():
                self.nsig[typ] = max((self.nsig[typ], len(sig)))

    def getSignals(self, sys, typ):
        """ retrieve signal list for constellation and obs type """
        if sys in self.sig_tab.keys() and typ in self.sig_tab[sys].keys():
            return self.sig_tab[sys][typ]
        else:
            return []

    def autoSubstituteSignals(self):
        """
        Automatically substitute signal tracking attribute based on
        available signals
        """
        for sys, tmp in self.sig_tab.items():
            for typ, sigs in tmp.items():
                for i, sig in enumerate(sigs):

                    # Skip unavailable systems or available signals
                    #
                    if sys not in self.sig_map.keys():
                        continue
                    if sig in self.sig_map[sys].values():
                        continue

                    # Not found try to replace
                    #
                    if sys == uGNSS.GPS and sig.str()[1] in '12':
                        atts = 'CW' if sig.str()[2] in 'CW' else 'SLX'
                    elif sys == uGNSS.GPS and sig.str()[1] in '5':
                        atts = 'IQX'
                    elif sys == uGNSS.GAL and sig.str()[1] in '578':
                        atts = 'IQX'
                    elif sys == uGNSS.GAL and sig.str()[1] in '16':
                        atts = 'BCX'
                    elif sys == uGNSS.QZS and sig.str()[1] in '126':
                        atts = 'SLX'
                    elif sys == uGNSS.QZS and sig.str()[1] in '5':
                        atts = 'IQX'
                    elif sys == uGNSS.BDS and sig.str()[1] in '157':
                        atts = 'PX'
                    else:
                        atts = []

                    for a in atts:
                        if sig.toAtt(a) in self.sig_map[sys].values():
                            self.sig_tab[sys][typ][i] = sig.toAtt(a)

    def flt(self, u, c=-1):
        if c >= 0:
            u = u[19*c+4:19*(c+1)+4]
        if u.isspace():
            return 0.0
        return float(u.replace("D", "E"))

    def decode_time(self, s, ofst=0, slen=2):
        year = int(s[ofst+0:ofst+4])
        month = int(s[ofst+5:ofst+7])
        day = int(s[ofst+8:ofst+10])
        hour = int(s[ofst+11:ofst+13])
        minute = int(s[ofst+14:ofst+16])
        sec = float(s[ofst+17:ofst+slen+17])
        t = epoch2time([year, month, day, hour, minute, sec])
        return t

    def decode_nav(self, navfile, nav):
        """
        Decode RINEX Navigation message from file

        NOTE: system time epochs are converted into GPST on reading!

        """

        nav.eph = []
        with open(navfile, 'rt') as fnav:
            for line in fnav:
                if line[60:73] == 'END OF HEADER':
                    break
                elif line[60:80] == 'RINEX VERSION / TYPE':
                    self.ver = float(line[4:10])
                    if self.ver < 3.02:
                        return -1
                elif line[60:76] == 'IONOSPHERIC CORR':
                    if line[0:4] == 'GPSA' or line[0:4] == 'QZSA':
                        for k in range(4):
                            nav.ion[0, k] = self.flt(line[5+k*12:5+(k+1)*12])
                    if line[0:4] == 'GPSB' or line[0:4] == 'QZSB':
                        for k in range(4):
                            nav.ion[1, k] = self.flt(line[5+k*12:5+(k+1)*12])

            for line in fnav:

                if self.ver >= 4.0:

                    if line[0:5] == '> STO':  # system time offset (TBD)
                        ofst_src = {'GP': uGNSS.GPS, 'GL': uGNSS.GLO,
                                    'GA': uGNSS.GAL, 'BD': uGNSS.BDS,
                                    'QZ': uGNSS.QZS, 'IR': uGNSS.IRN,
                                    'SB': uGNSS.SBS, 'UT': uGNSS.NONE}
                        sys = char2sys(line[6])
                        itype = line[10:14]
                        line = fnav.readline()
                        ttm = self.decode_time(line, 4)
                        mode = line[24:28]
                        if mode[0:2] in ofst_src and mode[2:4] in ofst_src:
                            nav.sto_prm[0] = ofst_src[mode[0:2]]
                            nav.sto_prm[1] = ofst_src[mode[2:4]]

                        line = fnav.readline()
                        ttm = self.flt(line, 0)
                        for k in range(3):
                            nav.sto[k] = self.flt(line, k+1)
                        continue

                    elif line[0:5] == '> EOP':  # earth orientation param
                        sys = char2sys(line[6])
                        itype = line[10:14]
                        line = fnav.readline()
                        ttm = self.decode_time(line, 4)
                        for k in range(3):
                            nav.eop[k] = self.flt(line, k+1)
                        line = fnav.readline()
                        for k in range(3):
                            nav.eop[k+3] = self.flt(line, k+1)
                        line = fnav.readline()
                        ttm = self.flt(line, 0)
                        for k in range(3):
                            nav.eop[k+6] = self.flt(line, k+1)
                        continue

                    elif line[0:5] == '> ION':  # iono (TBD)
                        sys = char2sys(line[6])
                        itype = line[10:14]
                        line = fnav.readline()
                        ttm = self.decode_time(line, 4)
                        if sys == uGNSS.GAL and itype == 'IFNV':  # Nequick-G
                            for k in range(3):
                                nav.ion[0, k] = self.flt(line, k+1)
                            line = fnav.readline()
                            nav.ion[0, 3] = int(self.flt(line, 0))
                        elif sys == uGNSS.BDS and itype == 'CNVX':  # BDGIM
                            ttm = self.decode_time(line, 4)
                            self.ion_gim = np.zeros(9)
                            for k in range(3):
                                nav.ion_gim[k] = self.flt(line, k+1)
                            line = fnav.readline()
                            for k in range(4):
                                nav.ion_gim[k+3] = self.flt(line, k)
                            line = fnav.readline()
                            for k in range(2):
                                nav.ion_gim[k+7] = self.flt(line, k)
                        else:  # Klobucher (LNAV, D1D2, CNVX)
                            self.ion_gim = np.zeros(9)
                            for k in range(3):
                                nav.ion[0, k] = self.flt(line, k+1)
                            line = fnav.readline()
                            nav.ion[0, 3] = self.flt(line, 0)
                            for k in range(3):
                                nav.ion[1, k] = self.flt(line, k+1)
                            line = fnav.readline()
                            nav.ion[1, 3] = self.flt(line, 0)
                            if len(line) >= 42:
                                nav.ion_region = int(self.flt(line, 1))
                        continue

                    elif line[0:5] == '> EPH':
                        sys = char2sys(line[6])
                        self.mode_nav = 0  # LNAV, D1/D2, INAV
                        m = line[10:14]
                        if m == 'CNAV' or m == 'CNV1' or m == 'FNAV':
                            self.mode_nav = 1
                        elif m == 'CNV2':
                            self.mode_nav = 2
                        elif m == 'CNV3':
                            self.mode_nav = 3
                        elif m == 'FDMA':
                            self.mode_nav = 4
                        elif m == 'SBAS':
                            self.mode_nav = 5
                        line = fnav.readline()

                # Process ephemeris information
                #
                sys = char2sys(line[0])

                # Skip undesired constellations
                #
                if sys not in (uGNSS.GPS, uGNSS.GAL, uGNSS.QZS, uGNSS.BDS):
                    continue

                prn = int(line[1:3])
                if sys == uGNSS.QZS:
                    prn += 192
                sat = prn2sat(sys, prn)
                eph = Eph(sat)

                eph.mode = self.mode_nav

                eph.toc = self.decode_time(line, 4)
                eph.af0 = self.flt(line, 1)
                eph.af1 = self.flt(line, 2)
                eph.af2 = self.flt(line, 3)

                line = fnav.readline()  # line #1

                if self.mode_nav > 0:
                    eph.Adot = self.flt(line, 0)
                else:
                    eph.iode = int(self.flt(line, 0))
                eph.crs = self.flt(line, 1)
                eph.deln = self.flt(line, 2)
                eph.M0 = self.flt(line, 3)

                line = fnav.readline()  # line #2
                eph.cuc = self.flt(line, 0)
                eph.e = self.flt(line, 1)
                eph.cus = self.flt(line, 2)
                sqrtA = self.flt(line, 3)
                eph.A = sqrtA**2

                line = fnav.readline()  # line #3
                eph.toes = int(self.flt(line, 0))
                eph.cic = self.flt(line, 1)
                eph.OMG0 = self.flt(line, 2)
                eph.cis = self.flt(line, 3)

                line = fnav.readline()  # line #4
                eph.i0 = self.flt(line, 0)
                eph.crc = self.flt(line, 1)
                eph.omg = self.flt(line, 2)
                eph.OMGd = self.flt(line, 3)

                line = fnav.readline()  # line #5
                eph.idot = self.flt(line, 0)
                if self.mode_nav > 0:
                    eph.delnd = self.flt(line, 1)
                    if sys == uGNSS.BDS:
                        eph.sattype = int(self.flt(line, 2))
                        eph.tops = int(self.flt(line, 3))
                    else:
                        eph.urai[0] = int(self.flt(line, 2))
                        eph.urai[1] = int(self.flt(line, 3))
                else:
                    eph.code = int(self.flt(line, 1))  # source for GAL
                    eph.week = int(self.flt(line, 2))

                line = fnav.readline()  # line #6
                if sys == uGNSS.BDS and self.mode_nav > 0:
                    eph.sisai[0] = int(self.flt(line, 0))  # oe
                    eph.sisai[1] = int(self.flt(line, 1))  # ocb
                    eph.sisai[2] = int(self.flt(line, 2))  # oc1
                    eph.sisai[3] = int(self.flt(line, 3))  # oc2
                else:
                    eph.sva = int(self.flt(line, 0))
                    eph.svh = int(self.flt(line, 1))
                    eph.tgd = float(self.flt(line, 2))
                    if sys == uGNSS.GPS or sys == uGNSS.QZS:
                        if self.mode_nav == 0:
                            eph.iodc = int(self.flt(line, 3))
                        else:
                            eph.urai[2] = int(self.flt(line, 3))
                    elif sys == uGNSS.GAL:
                        tgd_b = float(self.flt(line, 3))
                        if (eph.code >> 9) & 1:
                            eph.tgd = tgd_b
                        else:
                            eph.iodc = int(self.flt(line, 3))
                    elif sys == uGNSS.BDS:
                        eph.tgd_b = float(self.flt(line, 3))  # tgd2 B2/B3

                if self.mode_nav < 3:
                    line = fnav.readline()  # line #7
                    if sys == uGNSS.BDS:
                        if self.mode_nav == 0:
                            tot = self.flt(line, 0)
                            eph.iodc = int(self.flt(line, 1))
                        else:
                            if self.mode_nav == 1:
                                eph.isc[0] = float(self.flt(line, 0))  # B1Cd
                            elif self.mode_nav == 2:
                                eph.isc[1] = float(self.flt(line, 1))  # B2ad

                            eph.tgd = float(self.flt(line, 2))    # tgd_B1Cp
                            eph.tgd_b = float(self.flt(line, 3))  # tgd_B2ap

                    else:
                        if self.mode_nav > 0 and sys != uGNSS.GAL:
                            eph.isc[0] = self.flt(line, 0)
                            eph.isc[1] = self.flt(line, 1)
                            eph.isc[2] = self.flt(line, 2)
                            eph.isc[3] = self.flt(line, 3)
                            line = fnav.readline()

                        if self.mode_nav == 2:
                            eph.isc[4] = self.flt(line, 0)
                            eph.isc[5] = self.flt(line, 1)
                            line = fnav.readline()

                        tot = int(self.flt(line, 0))
                        if self.mode_nav > 0:
                            eph.week = int(self.flt(line, 1))
                        elif len(line) >= 42:
                            eph.fit = int(self.flt(line, 1))

                if sys == uGNSS.BDS and self.mode_nav > 0:
                    line = fnav.readline()  # line #8
                    eph.sismai = int(self.flt(line, 0))
                    eph.svh = int(self.flt(line, 1))
                    eph.integ = int(self.flt(line, 2))
                    if self.mode_nav < 3:
                        eph.iodc = int(self.flt(line, 3))
                    else:
                        eph.tgd_b = float(self.flt(line, 3))

                    line = fnav.readline()  # line #9
                    tot = int(self.flt(line, 0))
                    if self.mode_nav < 3:
                        eph.iode = int(self.flt(line, 3))

                if sys == uGNSS.BDS:
                    if self.mode_nav > 0:
                        eph.week, _ = time2bdt(eph.toc)
                    eph.toc = bdt2gpst(eph.toc)
                    eph.toe = bdt2gpst(bdt2time(eph.week, eph.toes))
                    eph.tot = bdt2gpst(bdt2time(eph.week, tot))
                else:
                    eph.toe = gpst2time(eph.week, eph.toes)
                    eph.tot = gpst2time(eph.week, tot)

                nav.eph.append(eph)

        return nav

    def decode_clk(self, clkfile, nav):
        """decode Clock-RINEX data from file """

        # Offset for Clock-RINEX v3.x data section
        #
        offs = None

        nav.pclk = []
        fnav = open(clkfile, 'rt')

        # Read header section
        #
        for line in fnav:

            if 'RINEX VERSION / TYPE' in line:
                ver = float(line[0:20])
                offs = 0 if ver < 3.04 else 5

            if 'END OF HEADER' in line:
                break

        # Read data section
        #
        for line in fnav:

            if line[0:2] != 'AS':
                continue

            sys = char2sys(line[3])
            prn = int(line[4:7])
            if sys == uGNSS.QZS:
                prn += 192
            sat = prn2sat(sys, prn)

            t = self.decode_time(line, offs+8, 9)

            if nav.nc <= 0 or abs(timediff(nav.pclk[-1].time, t)) > 1e-9:
                nav.nc += 1
                pclk = pclk_t()
                pclk.time = t
                nav.pclk.append(pclk)

            nrec = int(line[offs+35:offs+37])
            clk = float(line[offs+40:offs+59])
            std = float(line[offs+61:offs+80]) if nrec >= 2 else 0.0

            nav.pclk[nav.nc-1].clk[sat-1] = clk
            nav.pclk[nav.nc-1].std[sat-1] = std

        return nav

    # TODO: decode GLONASS FCN lines
    def decode_obsh(self, obsfile):
        self.fobs = open(obsfile, 'rt')
        for line in self.fobs:
            if line[60:73] == 'END OF HEADER':
                break
            if line[60:80] == 'RINEX VERSION / TYPE':
                self.ver = float(line[4:10])
                if self.ver < 3.02:
                    return -1
            elif 'REC # / TYPE / VERS' in line:
                self.rcv = line[20:40].upper()
            elif 'ANT # / TYPE' in line:
                self.ant = line[20:40].upper()
            elif line[60:79] == 'APPROX POSITION XYZ':
                self.pos = np.array([float(line[0:14]),
                                     float(line[14:28]),
                                     float(line[28:42])])
            elif 'ANTENNA: DELTA H/E/N' in line[60:]:
                self.ecc = np.array([float(line[14:28]),  # East
                                     float(line[28:42]),  # North
                                     float(line[0:14])])  # Up
            elif line[60:79] == 'SYS / # / OBS TYPES':

                gns = char2sys(line[0])
                nsig = int(line[3:6])

                # Extract string list of signal codes
                #
                sigs = line[7:60].split()
                for _ in range(int(nsig/14)):
                    line2 = self.fobs.readline()
                    sigs += line2[7:60].split()

                # Convert to RINEX signal code and store in map
                #
                for i, sig in enumerate(sigs):
                    rnxSig = rSigRnx(gns, sig)
                    if gns not in self.sig_map:
                        self.sig_map.update({gns: {}})
                    self.sig_map[gns].update({i: rnxSig})
            elif 'TIME OF FIRST OBS' in line[60:]:
                self.ts = epoch2time([float(v) for v in line[0:44].split()])
            elif 'TIME OF LAST OBS' in line[60:]:
                self.te = epoch2time([float(v) for v in line[0:44].split()])

        return 0

    def decode_obs(self):
        """ decode RINEX Observation message from file """

        obs = Obs()

        for line in self.fobs:

            if line[0] != '>':
                continue

            nsat = int(line[32:35])

            year = int(line[2:6])
            month = int(line[7:9])
            day = int(line[10:12])
            hour = int(line[13:15])
            minute = int(line[16:18])
            sec = float(line[19:29])
            obs.t = epoch2time([year, month, day, hour, minute, sec])

            # Initialize data structures
            #
            obs.P = np.empty((0, self.nsig[uTYP.C]), dtype=np.float64)
            obs.L = np.empty((0, self.nsig[uTYP.L]), dtype=np.float64)
            obs.S = np.empty((0, self.nsig[uTYP.S]), dtype=np.float64)
            obs.lli = np.empty((0, self.nsig[uTYP.L]), dtype=np.int32)
            obs.sat = np.empty(0, dtype=np.int32)
            obs.sig = self.sig_tab

            for _ in range(nsat):

                line = self.fobs.readline()
                sys = char2sys(line[0])

                # Skip constellation not contained in RINEX header
                #
                if sys not in self.sig_map.keys():
                    continue

                # Skip undesired constellations
                #
                if sys not in self.sig_tab:
                    continue

                # Convert to satellite ID
                #
                prn = int(line[1:3])
                if sys == uGNSS.QZS:
                    prn += 192
                elif sys == uGNSS.SBS:
                    prn += 100
                sat = prn2sat(sys, prn)

                pr = np.zeros(len(self.getSignals(sys, uTYP.C)),
                              dtype=np.float64)
                cp = np.zeros(len(self.getSignals(sys, uTYP.L)),
                              dtype=np.float64)
                ll = np.zeros(len(self.getSignals(sys, uTYP.L)),
                              dtype=np.int32)
                cn = np.zeros(len(self.getSignals(sys, uTYP.S)),
                              dtype=np.float64)

                for i, sig in self.sig_map[sys].items():

                    # Skip undesired signals
                    #
                    if sig.typ not in self.sig_tab[sys] or \
                            sig not in self.sig_tab[sys][sig.typ]:
                        continue

                    # Get string representation of measurement value
                    #
                    sval = line[16*i+3:16*i+17].strip()
                    slli = line[16*i+17] if len(line) > 16*i+17 else ''

                    # Convert from string to numerical value
                    #
                    val = 0.0 if not sval else float(sval)
                    lli = 1 if slli == '1' else 0

                    # Signal index in data structure
                    #
                    j = self.sig_tab[sys][sig.typ].index(sig)

                    if sig.typ == uTYP.C:
                        pr[j] = val
                    elif sig.typ == uTYP.L:
                        cp[j] = val
                        ll[j] = lli
                    elif sig.typ == uTYP.S:
                        cn[j] = val
                    else:
                        continue

                # Store prn and data
                #
                obs.P = np.append(obs.P, pr)
                obs.L = np.append(obs.L, cp)
                obs.S = np.append(obs.S, cn)
                obs.lli = np.append(obs.lli, ll)
                obs.sat = np.append(obs.sat, sat)

            obs.P = obs.P.reshape(len(obs.sat), self.nsig[uTYP.C])
            obs.L = obs.L.reshape(len(obs.sat), self.nsig[uTYP.L])
            obs.S = obs.S.reshape(len(obs.sat), self.nsig[uTYP.S])
            obs.lli = obs.lli.reshape(len(obs.sat), self.nsig[uTYP.L])

            break

        return obs

def sync_obs(dec, decb, dt_th=0.1):
    """ sync observation between rover and base """
    obs = dec.decode_obs()
    obsb = decb.decode_obs()
    while True:
        dt = timediff(obs.t, obsb.t)
        if np.abs(dt) <= dt_th:
            break
        if dt > dt_th:
            obsb = decb.decode_obs()
        elif dt < dt_th:
            obs = dec.decode_obs()
    return obs, obsb

class rnxenc:
    """ class for RINEX encoder """

    def __init__(self, sig_tab=None):
        self.ver = -1.0
        self.fobs = None
        self.fnav = None
        self.rnx_obs_header_sent = False
        self.sig_tab = sig_tab

        self.prog = "cssrlib"
        self.runby = "Unknown"
        self.agency = "Unknown"
        self.observer = "Unknown"
        self.rec = "Unknown"
        self.rectype = "Unkown"
        self.recver = ""
        self.ant = "Unknown"
        self.anttype = "Unknown"
        self.pos = np.zeros(3)
        self.dant = np.zeros(3)

        self.rec_eph = {}

    def rnx_nav_header(self, fh=None, ver=4.00):
        tutc = timeget()
        tgps = utc2gpst(tutc)
        leaps = timediff(tgps, tutc)

        ep = time2epoch(tutc)
        s = "{:4d}{:02d}{:02d} {:02d}{:02d}{:02d} {:3s}". \
            format(ep[0], ep[1], ep[2], ep[3], ep[4], ep[5], "UTC")

        fh.write("{:9.2f}           {:19s} {:19s} {:20s}\n".
                 format(ver, "NAVIGATION DATA", "M", "RINEX VERSION / TYPE"))
        fh.write("{:20s}{:20s}{:20s}{:20s}\n".
                 format(self.prog, self.runby, s, "PGM / RUN BY / DATE"))
        fh.write("{:6d}{:6s}{:6s}{:6s}{:3s}{:33s}{:20s}\n".
                 format(leaps, "", "", "", "", "", "LEAP SECONDS"))
        fh.write("{:60s}{:20s}\n".
                 format("", "END OF HEADER"))

    def rnx_obs_header(self, ts: gtime_t, fh=None, ver=4.00):

        if self.rnx_obs_header_sent:
            return
        self.rnx_obs_header_sent = True

        sys_t = {uGNSS.GPS: 'G', uGNSS.GLO: 'R', uGNSS.GAL: 'E',
                 uGNSS.QZS: 'J', uGNSS.BDS: 'C', uGNSS.IRN: 'I',
                 uGNSS.SBS: 'S'}

        tutc = timeget()
        tgps = utc2gpst(tutc)
        leaps = timediff(tgps, tutc)

        ep = time2epoch(tutc)
        s = "{:4d}{:02d}{:02d} {:02d}{:02d}{:02d} {:3s}". \
            format(ep[0], ep[1], ep[2], ep[3], ep[4], ep[5], "UTC")

        fh.write("{:9.2f}           {:19s} {:19s} {:20s}\n".
                 format(ver, "OBSERVATION DATA", "M", "RINEX VERSION / TYPE"))
        fh.write("{:20s}{:20s}{:20s}{:20s}\n".
                 format(self.prog, self.runby, s, "PGM / RUN BY / DATE"))

        fh.write("{:60s}{:20s}\n".format("Unknown", "MARKER NAME"))
        fh.write("{:20s}{:40s}{:20s}\n".format(
            self.observer, self.agency, "OBSERVER / AGENCY"))
        fh.write("{:20s}{:20s}{:20s}{:20s}\n".format(
            self.rec, self.rectype, self.recver, "REC # / TYPE / VERS"))
        fh.write("{:20s}{:20s}{:20s}{:20s}\n".format(
            self.ant, self.anttype, "", "ANT # / TYPE"))
        fh.write("{:14.4f}{:14.4f}{:14.4f}{:18s}{:20s}\n".format(
            self.pos[0], self.pos[1], self.pos[2], "", "APPROX POSITION XYZ"))
        fh.write("{:14.4f}{:14.4f}{:14.4f}{:18s}{:20s}\n".format(
            self.dant[0], self.dant[1], self.dant[2], "",
            "ANTENNA: DELTA H/E/N"))

        for sys in self.sig_tab:
            pr = self.sig_tab[sys][uTYP.C]
            cp = self.sig_tab[sys][uTYP.L]
            dp = self.sig_tab[sys][uTYP.D]
            cn = self.sig_tab[sys][uTYP.S]

            nsig = len(pr)+len(cp)+len(dp)+len(cn)

            fh.write("{:1s}  {:3d}".format(sys_t[sys], nsig))

            n = 0
            for k, _ in enumerate(pr):
                fh.write(" {:3s}".format(pr[k].str()))
                n += 1
                if n == 13:
                    fh.write("  {:20s}\n{:6s}".format(
                        "SYS / # / OBS TYPES", ""))

                fh.write(" {:3s}".format(cp[k].str()))
                n += 1
                if n == 13:
                    fh.write("  {:20s}\n{:6s}".format(
                        "SYS / # / OBS TYPES", ""))

                fh.write(" {:3s}".format(dp[k].str()))
                n += 1
                if n == 13:
                    fh.write("  {:20s}\n{:6s}".format(
                        "SYS / # / OBS TYPES", ""))

                fh.write(" {:3s}".format(cn[k].str()))
                n += 1

                if n == 13:
                    fh.write("  {:20s}\n{:6s}".format(
                        "SYS / # / OBS TYPES", ""))
                elif n >= nsig-1:
                    fh.write("  {:s}".format("    "*(13-(nsig % 13))))
                    fh.write("{:20s}".format("SYS / # / OBS TYPES \n"))

        # TBD
        ep = time2epoch(ts)
        fh.write(" {:5d} {:5d} {:5d} {:5d} {:5d}{:13.7f}".
                 format(int(ep[0]), int(ep[1]), int(ep[2]), int(ep[3]),
                        int(ep[4]), ep[5]))
        fh.write("{:5s}{:3s}{:9s}{:20s}\n".
                 format("", "GPS", "", "TIME OF FIRST OBS"))

        fh.write("{:6d}{:6s}{:6s}{:6s}{:3s}{:33s}{:20s}\n".
                 format(leaps, "", "", "", "", "", "LEAP SECONDS"))
        fh.write("{:60s}{:20s}\n".
                 format("", "END OF HEADER"))
        fh.flush()

    def sval(self, v: float):
        if v == 0.0:
            s = "{:14s}".format("")
        else:
            s = "{:14.3f}".format(v)
        return s

    def rnx_obs_body(self, obs=None, fh=None):

        ep = time2epoch(obs.time)
        nsat = len(obs.sat)
        nsig = obs.P.shape[1]
        fh.write("> {:4d} {:02d} {:02d} {:02d} {:02d} {:010.7f}".
                 format(int(ep[0]), int(ep[1]), int(ep[2]),
                        int(ep[3]), int(ep[4]), ep[5]))
        fh.write("  {:1d}{:3d}\n".format(0, nsat))

        for k in range(nsat):
            fh.write("{:3s}".format(sat2id(obs.sat[k])))
            sys, _ = sat2prn(obs.sat[k])
            for i in range(nsig):
                ssi = min(max(int(obs.S[k][i]/6), 1), 9)
                lli = obs.lli[k][i]
                fh.write("{:14s}{:2s}".format(
                    self.sval(obs.P[k][i]), ""))
                fh.write("{:14s}".format(self.sval(obs.L[k][i])))
                if obs.L[k][i] == 0.0:
                    fh.write("{:2s}".format(""))
                else:
                    fh.write("{:1d}{:1d}".format(lli, ssi))

                fh.write("{:14s}{:2s}".format(
                    self.sval(obs.D[k][i]), ""))
                fh.write("{:14s}{:2s}".format(self.sval(obs.S[k][i]), ""))
            fh.write("\n")

    def rnx_nav_body(self, eph=None, fh=None):
        if eph.sat in self.rec_eph.keys():
            if eph.iode in self.rec_eph[eph.sat].keys():
                return
        else:
            self.rec_eph[eph.sat] = {}
        self.rec_eph[eph.sat][eph.iode] = eph.toes

        id_ = sat2id(eph.sat)
        sys, prn = sat2prn(eph.sat)

        if sys == uGNSS.BDS and (eph.iodc & 0xff) != eph.iode:
            return

        if sys == uGNSS.BDS:
            ep = time2epoch(gpst2bdt(eph.toc))
            week, tot_ = time2bdt(eph.tot)
        else:
            ep = time2epoch(eph.toc)
            week, tot_ = time2gpst(eph.tot)

        if sys == uGNSS.BDS and eph.mode == 1:  # B-CNAV1
            lbl = "CNV1"
            v1 = eph.Adot
        elif (sys == uGNSS.GPS or sys == uGNSS.QZS) and eph.mode == 0:  # LNAV
            lbl = "LNAV"
            v1 = float(eph.iode)
        elif sys == uGNSS.GAL and eph.mode == 0:  # INAV
            lbl = "INAV"
            v1 = float(eph.iode)
        else:
            return

        fh.write("> {:2s} {:3s} {:2s}\n".format("EPH", id_, lbl))
        fh.write("{:3s} {:4d} {:02d} {:02d} {:02d} {:02d} {:02d}".
                 format(id_, int(ep[0]), int(ep[1]), int(ep[2]),
                        int(ep[3]), int(ep[4]), int(ep[5])))
        fh.write("{:19.12E}{:19.12E}{:19.12E}\n".
                 format(eph.af0, eph.af1, eph.af2))
        fh.write("    {:19.12E}{:19.12E}{:19.12E}{:19.12E}\n".
                 format(v1, eph.crs, eph.deln, eph.M0))
        fh.write("    {:19.12E}{:19.12E}{:19.12E}{:19.12E}\n".
                 format(eph.cuc, eph.e, eph.cus, np.sqrt(eph.A)))
        fh.write("    {:19.12E}{:19.12E}{:19.12E}{:19.12E}\n".
                 format(eph.toes, eph.cic, eph.OMG0, eph.cis))
        fh.write("    {:19.12E}{:19.12E}{:19.12E}{:19.12E}\n".
                 format(eph.i0, eph.crc, eph.omg, eph.OMGd))

        if sys == uGNSS.BDS and eph.mode == 1:  # B-CNAV1
            fh.write("    {:19.12E}{:19.12E}{:19.12E}{:19.12E}\n".
                     format(eph.idot, eph.delnd, eph.sattype, eph.top))
            fh.write("    {:19.12E}{:19.12E}{:19.12E}{:19.12E}\n".
                     format(eph.sisai[0], eph.sisai[1], eph.sisai[2],
                            eph.sisai[3]))
            fh.write("    {:19.12E}{:19s}{:19.12E}{:19.12E}\n".
                     format(eph.isc[0], "", eph.tgd, eph.tgd_b))
            fh.write("    {:19.12E}{:19.12E}{:19.12E}{:19.12E}\n".
                     format(float(eph.sismai), float(eph.svh),
                            float(eph.integ), float(eph.iodc)))
            fh.write("    {:19.12E}{:19s}{:19s}{:19.12E}\n".
                     format(tot_, "", "", float(eph.iode)))

        if (sys == uGNSS.GPS or sys == uGNSS.QZS) and eph.mode == 0:  # LNAV
            fh.write("    {:19.12E}{:19.12E}{:19.12E}{:19.12E}\n".
                     format(eph.idot, float(eph.code), float(eph.week),
                            float(eph.l2p)))
            fh.write("    {:19.12E}{:19.12E}{:19.12E}{:19.12E}\n".
                     format(float(eph.sva), float(eph.svh), eph.tgd,
                            float(eph.iodc)))
            fh.write("    {:19.12E}{:19.12E}{:19s}{:19s}\n".
                     format(tot_, float(eph.fit), "", ""))

        if sys == uGNSS.GAL and eph.mode == 0:  # INAV
            fh.write("    {:19.12E}{:19.12E}{:19.12E}{:19s}\n".
                     format(eph.idot, float(eph.code), float(eph.week), ""))
            fh.write("    {:19.12E}{:19.12E}{:19.12E}{:19.12E}\n".
                     format(float(eph.sva), float(eph.svh), eph.tgd,
                            float(eph.tgd_b)))
            fh.write("    {:19.12E}{:19s}{:19s}{:19s}\n".
                     format(tot_, "", "", ""))


import contextlib
from typing import Optional
import torch
from torch import Tensor
from mGPT.utils.joints import smplh_to_mmm_scaling_factor, smplh2mmm_indexes, get_root_idx
from mGPT.utils.easyconvert import rep_to_rep
from .base import Rots2Joints

def slice_or_none(data, cslice):
    if data is None:
        return data
    else:
        return data[cslice]

class SMPLX(Rots2Joints):
    def __init__(self,
                 path: str,
                 jointstype: str = "mmm",
                 input_pose_rep: str = "matrix",
                 batch_size: int = 512,
                 gender="neutral",
                 **kwargs) -> None:
        super().__init__(path=None, normalization=False)
        self.batch_size = batch_size
        self.input_pose_rep = input_pose_rep
        self.jointstype = jointstype
        self.training = False

        from smplx.body_models import SMPLXLayer
        import os
        # rel_p = path.split('/')
        # rel_p = rel_p[rel_p.index('data'):]
        # rel_p = '/'.join(rel_p)

        # Remove annoying print
        with contextlib.redirect_stdout(None):
            self.smplx = SMPLXLayer(path,
                                    ext="npz",
                                    gender=gender,
                                    batch_size=batch_size).eval()

        self.faces = self.smplx.faces
        for p in self.parameters():
            p.requires_grad = False

    def train(self, *args, **kwargs):
        return self

    def forward(self,
                smpl_data: dict,
                jointstype: Optional[str] = None,
                input_pose_rep: Optional[str] = None,
                batch_size: Optional[int] = None) -> Tensor:

        # Take values from init if not specified there
        jointstype = self.jointstype if jointstype is None else jointstype
        batch_size = self.batch_size if batch_size is None else batch_size
        input_pose_rep = self.input_pose_rep if input_pose_rep is None else input_pose_rep

        poses = smpl_data.rots
        trans = smpl_data.trans

        from functools import reduce
        import operator
        save_shape_bs_len = poses.shape[:-3]
        nposes = reduce(operator.mul, save_shape_bs_len, 1)

        matrix_poses = rep_to_rep(self.input_pose_rep, input_pose_rep, poses)

        # Reshaping
        matrix_poses = matrix_poses.reshape((nposes, *matrix_poses.shape[-3:]))

        global_orient = matrix_poses[:, 0]

        if trans is None:
            trans = torch.zeros((*save_shape_bs_len, 3),
                                dtype=poses.dtype,
                                device=poses.device)

        trans_all = trans.reshape((nposes, *trans.shape[-1:]))

        body_pose = matrix_poses[:, 1:22]

        if poses.shape[-3] == 55:
            nohands = False
            nofaces = False
        elif poses.shape[-3] == 52:
            nohands = False
            nofaces = True
        elif poses.shape[-3] == 22:
            nohands = True
            nofaces = True
        else:
            raise NotImplementedError("Could not parse the poses.")

        if nohands:
            left_hand_pose = None
            right_hand_pose = None
        else:
            left_hand_pose = matrix_poses[:, 25:40]
            right_hand_pose = matrix_poses[:, 40:55]

        if nofaces:
            jaw_pose = None
            leye_pose = None
            reye_pose = None
        else:
            jaw_pose = matrix_poses[:, 22:23]
            leye_pose = matrix_poses[:, 23:24]
            reye_pose = matrix_poses[:, 24:25]

        n = len(body_pose)
        outputs = []
        for chunk in range(int((n - 1) / batch_size) + 1):
            chunk_slice = slice(chunk * batch_size, (chunk + 1) * batch_size)
            smpl_output = self.smplx(
                global_orient=slice_or_none(global_orient, chunk_slice),
                body_pose=slice_or_none(body_pose, chunk_slice),
                left_hand_pose=slice_or_none(left_hand_pose, chunk_slice),
                right_hand_pose=slice_or_none(right_hand_pose, chunk_slice),
                jaw_pose=slice_or_none(jaw_pose, chunk_slice),
                leye_pose=slice_or_none(leye_pose, chunk_slice),
                reye_pose=slice_or_none(reye_pose, chunk_slice),
                transl=slice_or_none(trans_all, chunk_slice))

            if jointstype == "vertices":
                output_chunk = smpl_output.vertices
            else:
                joints = smpl_output.joints
                output_chunk = joints

            outputs.append(output_chunk)

        outputs = torch.cat(outputs)
        outputs = outputs.reshape((*save_shape_bs_len, *outputs.shape[1:]))

        # Change topology if needed
        outputs = smplx_to(jointstype, outputs, trans)

        return outputs

    def inverse(self, joints: Tensor) -> Tensor:
        raise NotImplementedError("Cannot inverse SMPLX layer.")

def smplx_to(jointstype, data, trans):

    if "mmm" in jointstype:
        indexes = smplh2mmm_indexes
        data = data[..., indexes, :]

        # make it compatible with mmm
        if jointstype == "mmm":
            data *= smplh_to_mmm_scaling_factor

        if jointstype == "smplmmm":
            pass
        elif jointstype in ["mmm", "mmmns"]:
            # swap axis
            data = data[..., [1, 2, 0]]
            # revert left and right
            data[..., 2] = -data[..., 2]

    elif jointstype == "smplnh":
        from mGPT.utils.joints import smplh2smplnh_indexes
        indexes = smplh2smplnh_indexes
        data = data[..., indexes, :]
    elif jointstype == "smplh":
        pass
    elif jointstype == "vertices":
        pass
    else:
        raise NotImplementedError(f"SMPLX to {jointstype} is not implemented.")

    if jointstype != "vertices":
        # shift the output in each batch
        # such that it is centered on the pelvis/root on the first frame
        root_joint_idx = get_root_idx(jointstype)
        shift = trans[..., 0, :] - data[..., 0, root_joint_idx, :]
        data += shift[..., None, None, :]

    return data


__author__ = 'Netšajev'

from PIL import Image, ImageDraw
import BigPig

def get_wave_lenght_from_data_point(value, min_value, max_value):
    """
    Normalize values to wavelength value so we
    can use it for wave_length_to_rgb function
    """
    #visible wave lengths
    min_wave = 380.0
    max_wave = 780.0

    #   Data normalization: Convert data value in the
    #   range of min_values..max_values to the range 380..780
    result = (value - min_value) / (max_value+0.1-min_value) * (max_wave - min_wave) + min_wave
    return result

def wave_length_to_rgb(wave_length):
    gamma = 0.950
    intensity_max = 255

    """ Taken from Earl F. Glynn's web page Spectra Lab Report:
    http://www.efg2.com/Lab/ScienceAndEngineering/Spectra.htm
    """

    if 380 <= wave_length < 781:
        if wave_length < 460:
            red = -(wave_length - 460) / (460 - 380)
            green = 0.0
            blue = 1.0
        elif wave_length < 580:
            red = 0.0
            green = (wave_length - 460) / (580 - 460)
            blue = 1.0
        elif wave_length < 620:
            red = 0.0
            green = 1.0
            blue = -(wave_length - 620) / (620 - 560)
        elif wave_length < 690:
            red = (wave_length - 570) / (690 - 570)
            green = 1.0
            blue = 0.0
        elif wave_length < 755:
            red = 1.0
            green = -(wave_length - 755) / (755 - 580)
            blue = 0.0
        else:
            red = 1.0
            green = 0.0
            blue = 0.0
    else:
        red = 0.0
        green = 0.0
        blue = 0.0

    # Let the intensity fall off near the vision limits
    if 380 <= wave_length:
        if wave_length < 500:
            factor = 0.3 + 0.7*(wave_length - 380) / (500 - 380)
        elif wave_length < 751:
            factor = 1.0
        elif wave_length < 781:
            factor = 0.3 + 0.7*(780 - wave_length) / (780 - 750)
    else:
        factor = 0.0

    # Don't want 0^x = 1 for x <> 0
    rgb = (0 if red == 0 else int((intensity_max * ((red * factor) ** gamma)) // 1),
           0 if green == 0 else int((intensity_max * ((green * factor) ** gamma)) // 1),
           0 if blue == 0 else int((intensity_max * ((blue * factor) ** gamma)) // 1))

    return rgb

# real tries number = tries squared
tries = 1

def create_matrix(game_count=10):
    size = 100 * tries
    matrix = [[_ for _ in range(size)] for _ in range(size)]

    for i in range(size):
        for j in range(size):
           #matrix[i][j] = BigPig.get_winrate(10000, 10000, game_count, i/tries, 15-j/tries)
           # points vs. points
           # matrix[i][j] = BigPig.get_winrate(i/tries, 100-j/tries, game_count)
            matrix[i][j] = i
        if i % 10 == 0:
            print("done {} out of {}".format(i, size))
    return matrix

def generate_heatmap(data_matrix):

    size = 100 * tries
    min_freq = 1
    max_freq = 0

    def draw_heatmap_rgb(dataset):
        tile_size = 1
        im = Image.new("RGB", (size*tile_size, size*tile_size))
        draw = ImageDraw.Draw(im)
        for d in dataset:
            draw.rectangle([(d[0]*tile_size, d[1]*tile_size), ((d[0]+1)*tile_size, (d[1]+1)*tile_size)],
                           wave_length_to_rgb(get_wave_lenght_from_data_point(d[2], min_freq, max_freq)))
        # write file
        im.save("winrateGuideFromZeroToHundred.jpg", "PNG")

    data = []

    for i in range(size):
        for j in range(size):
            value = data_matrix[i][j]
            if value > max_freq:
                max_freq = value
            if value < min_freq:
                min_freq = value

    for i in range(size):
        for j in range(size):
            data.append((i, j, data_matrix[i][j]))

    draw_heatmap_rgb(data)

def main():
    generate_heatmap(create_matrix(1000))

if __name__ == "__main__":
    main()


from PyQt5.QtWidgets import *
from PyQt5.uic import loadUi
import sys
from databaseinfo.dbconnection import DbConnection as db
class ModelDetails(QFrame):
    def __init__(self):
        super().__init__()
        loadUi("modelDetails.ui", self)
        self.con = db.createconnection()
        self.cursor = self.con.cursor()
        self.btnsubmit.clicked.connect(self.fetchdata)
    def fetchdata(self):
        self.modelNumber = self.txtmodel.text()
        self.brandId = self.txtid.text()
        self.modelName = self.txtname.text()
        self.price = self.txtprice.text()
        self.Features = self.txtfeatures.text()
        self.Quantity = self.txtquan.text()
        no = len(self.modelNumber.strip())
        id = len(self.brandId.strip())
        nm = len(self.modelName.strip())
        pr = len(self.price.strip())
        fe = len(self.Features.strip())
        qu = len(self.Quantity.strip())

        if no == 0 or id == 0 or nm == 0 or pr == 0 or fe == 0 or qu == 0:
            self.showDialog("You are in wrong way")
        else:
            strinsert = " insert into modeldetails(modelNumber,brandId,modelName,price,Features,Quantity)values(%s,%s,%s,%s,%s,%s) "
            self.cursor.execute(strinsert, (self.modelNumber, self.brandId, self.modelName, float(self.price), self.Features, int(self.Quantity)))
            self.con.commit()
            self.txtmodel.setText("")
            self.txtid.setText("")
            self.txtname.setText("")
            self.txtprice.setText("")
            self.txtfeatures.setText("")
            self.txtquan.setText("")
            self.showDialog("data inserted successfully")
    def showDialog(self, msg):  # show inserted data dialog box insertion successfully
        msgbox = QMessageBox()  # msg variable is used for insertion and not inserted dialoge box alert massage
        msgbox.setIcon(QMessageBox.Information)
        msgbox.setWindowTitle("Model Details")
        msgbox.setText(msg)
        msgbox.setStandardButtons(QMessageBox.Ok)
        msgbox.exec_()
def main():
    app = QApplication(sys.argv)
    md = ModelDetails()
    md.show()
    app.exec_()

if __name__ == '__main__':
    main()


def merge_sort(data):
    """归并算法"""
    # 使用递归
    length = len(data)
    if length <= 1:
        return data
    mid = length//2
    # 利用left,right进行递归，形成有序的列表
    left = merge_sort(data[:mid])
    right = merge_sort(data[mid:])

    # 将left, right进行合并排序
    left_pointer, right_pointer = 0, 0
    result = []
    while left_pointer < len(left) and right_pointer < len(right):
        if left[left_pointer] <= right[right_pointer]:
            result.append(left[left_pointer])
            left_pointer += 1
        else:
            result.append(right[right_pointer])
            right_pointer += 1
    result += left[left_pointer:]
    result += right[right_pointer:]
    return result

if __name__ == '__main__':
    data = [100, 1, 2, 3, 4, 50, 5, 6, 7, 8, 9]
    sorted_result = merge_sort(data)
    print(sorted_result)
    # 最坏时间复杂度O(n*logn)


# Fit an SED to given multifrequency data
#
# Version history:
# IDL batch script for running haperflux on several maps
# and plotting/fitting spectra for Planck and ancillary data
#
#
# 28-Aug-2010  C. Dickinson  Added model fitting
# 02-Sep-2010  C. Dickinson  Added inputs
# 20-Oct-2010  M. Peel		 Add different input map unit options (via filename),
#							 write out data file of results
# 09-Sep-2011  M. Peel/C. Dickinson Updated from Mike's version.
#
#                         Differences are
# 1. Commented out new parameters to haperflux
# 2. Added noise model to haperflux (not as input yet)
# 3. Added /nocmb option
# 4. Changed range of LFI frequencies (28.5 to 28.4 so it works with
# this frequency!)
# 5. Increased error bar thickness and plotsymbol size
# 6. Added extra oplot so plotsymbol can be seen
# 7. Addded extra IF statements to WMAP colour corrections in case no
# good data there.
#
# 22-Sep-2011 M. Peel  Output grep-able summary of fitted parameters; epstopdf call; input for noisemodel
# 10-Nov-2011 M. Peel  Adding code to deal with halpha and RRL maps
# 22-Dec-2011 C. Dickinson  Added minfreq and maxfreq options
# 04-Jan-2012 C. Dickinson  Added amemodels option. Residual plots now
#                           include modelling errors
# 08-Jan-2012 C. Dickinson  Added modelling errors when fitting for Te
# 12-Jan-2012 C. Dickinson  Added dust_optical_depth_freq for thermal dust
# 22-Jan-2012 C. Dickinson  Added usecochannels option
# 24-Jan-2012 M. Peel       Add option to read in flux densities from a text file.
# 01-Mar-2012 M. Peel       Also output the flux densities prior to colour correction.
# 18-Mar-2012 C. Dickinson  Added extra columns to .dat file
# 19-Mar-2012 M. Peel       Additional formatting in .dat file
# 16-Apr-2012 C. Dickinson  Added /shiftspdust option
# 18-Jul-2012 C. Dickinson  Added /nothermaldust option + minor bugs
# 04-Dec-2012 M. Peel		Added /nosyserr option + set s25000,s12000 to 0 when no map at that freq exists
# 05-Dec-2012 M. Peel       Fixed bug with increasing the uncertainty on CO-affected 100 and 217GHz channels
# 06-Dec-2012 M. Peel       Added /nocoerr option, change default noise_model to 1
# 11-Jan-2013 M. Peel       New wmap colour correction code, and updated LFI colour correction coefficients
# 14-Jan-2013 M. Peel       Updating HFI colour correction code
# 18-Jan-2013 M. Peel       Updated LFI frequency ranges
# 23-Jan-2013 M. Peel       Updated LFI colour corrections, creating planckcc function
# 19-Apr-2013 M. Peel       Update to published colour correction code ('LFI_fastcc' and 'hfi_colour_correction')
#
# Mike Peel   02-Feb-2016   v1.0 Migrating from IDL runaperflux.pro
# Mike Peel   07-Apr-2016   v1.0.1 Expanding, adding emcee

import numpy as np
import scipy.optimize as op
from mpfit import mpfit
from spectra import *
from astroutils import *
import copy
import matplotlib.pyplot as plt
import emcee
import corner

def calc_beam_area(beam1,beam2):
	return (np.pi * (beam1*np.pi/180.0)*(beam2*np.pi/180.0))/(4.0*np.log(2.0))

# Define some constants, used later in the SED functions
const = get_spectrum_constants()
solid_angle = calc_beam_area(100.0/60.0,0.7*100.0/60.0)#1.0e-5 # For now
spd_freq = []
spd_amp = []

def spectrum(p, fjac=None, x=None):
	model = synchrotron(const, x, 1.0, p[7], p[8]) + freefree(const, x, p[0], p[1], solid_angle) + spinningdust(spd_freq, spd_amp, solid_angle, x, p[5], p[9]) + cmb(const, x, p[6]*1e-6, solid_angle) + thermaldust(const, x, p[2]*1e-5, p[3], p[4], const['dust_optical_depth_freq'], solid_angle)# + thermaldust(const, x, p[10]*1e-5, p[11], p[12], const['dust_optical_depth_freq'], solid_angle)

	return model

def mpfitfunction(p, fjac=None, x=None, y=None, err=None):

	model = spectrum(p, fjac, x)

	status = 0
	return [status, (y-model)/err]

def lnlike(p, x, y, yerr):
	model = spectrum(p, x=x)
	inv_sigma2 = 1.0/(yerr**2) # + model**2*np.exp(2*lnf))
	value = -0.5*(np.sum((y-model)**2*inv_sigma2 - np.log(inv_sigma2)))
	return value

def lnprior(p, bounds):
	for i in range (0,len(p)):
		if p[i] < bounds[i][0] or p[i] > bounds[i][1]:
			return -np.inf
	# If we've got to here, we're within the bounds.
	return 0.0

def lnprob(p, bounds, x, y, yerr):
    lp = lnprior(p, bounds)
    if not np.isfinite(lp):
        return -np.inf
    return lp + lnlike(p, x, y, yerr)

def plot_results(outfile,srcname,minfreq,maxfreq,params,const,solid_angle,spd_freq,spd_amp,freqs,fd,fd_err,goodvals,minflux,maxflux):

	x = np.arange(minfreq,maxfreq,(maxfreq-minfreq)/1000.0)

	# Generate the model and plot it
	# if nosync == False:
	model_sync = synchrotron(const, x, 1.0, params[7], params[8])
	plt.plot(x, model_sync, 'r')
	# if nofreefree == False:
	model_freefree = freefree(const, x, params[0], params[1], solid_angle)
	plt.plot(x, model_freefree, 'b')
	# if noame == False:
	model_spd = spinningdust(spd_freq, spd_amp, solid_angle, x, params[5], params[9])
	plt.plot(x, model_spd, 'black')
	# if nodust == False:
	model_dust1 = thermaldust(const, x, params[2]*1e-5, params[3], params[4], const['dust_optical_depth_freq'], solid_angle)
	plt.plot(x, model_dust1, 'g')
	# if nodust2 == False:
	# model_dust2 = thermaldust(const, x, params[10]*1e-5, params[11], params[12], const['dust_optical_depth_freq'], solid_angle)
	# plt.plot(x, model_dust2, 'y')

	model_overall = spectrum(params, x=x)
	# plt.style.use('classic')
	plt.plot(x, model_overall, 'orange')
	# Add the data to the plot
	plt.errorbar(freqs[goodvals == 1], fd[goodvals == 1], fd_err[goodvals == 1],fmt='+')
	plt.errorbar(freqs[goodvals == 0], fd[goodvals == 0], fd_err[goodvals == 0])
	# plt.errorbar(7.0, spectrum(params,x=7.0),fmt='r.',markersize=10.0)
	# plt.errorbar(18.6, spectrum(params,x=18.6),fmt='r.',markersize=10.0)
	# plt.errorbar(24.6, spectrum(params,x=24.6),fmt='r.',markersize=10.0)

	model_spd = spinningdust(spd_freq, spd_amp, solid_angle, 30.0, 1.0, 0.0)
	model_spd_norm = 0.5*spectrum(params,x=30.0)/model_spd
	model_spd_25 = spinningdust(spd_freq, spd_amp, solid_angle, 24.6, 1.0, 0.0)*model_spd_norm
	model_spd_19 = spinningdust(spd_freq, spd_amp, solid_angle, 18.6, 1.0, 0.0)*model_spd_norm

	# plt.errorbar(18.6, spectrum(params,x=18.6)+model_spd_19,fmt='rx',markersize=5.0)
	# plt.errorbar(24.6, spectrum(params,x=24.6)+model_spd_25,fmt='rx',markersize=5.0)

	# print(spectrum(params,x=30.0))
	# print(spectrum(params,x=24.6))
	# print(spectrum(params,x=18.6))
	# print(model_spd_25)
	# print(model_spd_19)
	# exit()

	# Formatting, and output
	plt.title(srcname, fontsize=15)
	plt.rcParams["font.family"] = "serif"
	plt.rc('xtick',labelsize=14)
	plt.rc('ytick',labelsize=14)
	plt.xscale('log')
	plt.yscale('log')
	plt.xlabel('Frequency (GHz)', fontsize=15)
	plt.ylabel('Flux density (Jy)', fontsize=15)
	plt.ylim(ymin=minflux*0.1,ymax=maxflux*2)
	plt.tight_layout()
	plt.savefig(outfile)
	plt.clf()
	plt.close()
	return

def get_percentage(outfile,srcname,freq,params,const,solid_angle,spd_freq,spd_amp,freqs,fd,fd_err,goodvals,minflux,maxflux):

	x = freq

	model_sync = synchrotron(const, x, 1.0, params[7], params[8])
	model_freefree = freefree(const, x, params[0], params[1], solid_angle)
	model_spd = spinningdust(spd_freq, spd_amp, solid_angle, x, params[5], params[9])
	model_dust1 = thermaldust(const, x, params[2]*1e-5, params[3], params[4], const['dust_optical_depth_freq'], solid_angle)

	model_overall = spectrum(params, x=x)

	print(model_overall)
	print(model_sync)
	print(model_freefree)
	print(model_spd)
	print(model_dust1)

	return

def write_results(outfile,srcname,freqs,fd,fd_err,params,perror, const, solid_angle):
	outputfile = open(outfile, "w")
	outputfile.write("# " + srcname + "\n")
	for i in range(0,len(freqs)):
		outputfile.write(str(freqs[i]) + "	" + str(fd[i]) + "	" + str(fd_err[i]) + "\n")

	outputfile.write('# Sync amplitude: ' + str(params[7]) + " +- " + str(perror[7]) + '\n')
	outputfile.write('# Sync index: ' + str(params[8]) + " +- " + str(perror[8]) + '\n')
	outputfile.write('# Freefree amplitude: ' + str(params[0]) + " +- " + str(perror[0]) + '\n')
	outputfile.write('# Freefree temp: ' + str(params[1]) + " +- " + str(perror[1]) + '\n')
	ff1 = freefree(const, 1.0, params[0], params[1], solid_angle)
	ff1_err = ff1*perror[0]/params[0]
	outputfile.write('# Free-free at 1GHz ' + str(ff1) + ' +- ' + str(ff1_err) +'\n')
	outputfile.write('# AME amplitude: ' + str(params[5]) + " +- " + str(perror[5]) + '\n')
	outputfile.write('# AME significance: ' + str(params[5]/perror[5]) + '\n')

	outputfile.write('# AME shift: ' + str(params[9]) + " +- " + str(perror[9]) + '\n')
	outputfile.write('# CMB amplitude: ' + str(params[6]*1e-6) + " +- " + str(perror[6]*1e-6) + '\n')
	# outputfile.write('# AME at 25GHz: ' + str(spinningdust(spd_freq, spd_amp, solid_angle, 25.0, m.params[5], m.params[9])) + '\n')
	# outputfile.write('# AME at 30GHz: ' + str(spinningdust(spd_freq, spd_amp, solid_angle, 30.0, m.params[5], m.params[9])) + '\n')
	outputfile.write('# Dust amplitude: ' + str(params[2]*1e-5) + " +- " + str(perror[2]*1e-5) + '\n')
	outputfile.write('# Dust index: ' + str(params[3]) + " +- " + str(perror[3]) + '\n')
	outputfile.write('# Dust temperature: ' + str(params[4]) + " +- " + str(perror[4]) + '\n')
	# outputfile.write('# Dust2 amplitude: ' + str(params[10]) + " +- " + str(perror[10]) + '\n')
	# outputfile.write('# Dust2 index: ' + str(params[11]) + " +- " + str(perror[11]) + '\n')
	# outputfile.write('# Dust2 temperature: ' + str(params[12]) + " +- " + str(perror[12]) + '\n')
	outputfile.write('# At 7GHz, model says ' + str(spectrum(params, x=7.0))+'\n')
	outputfile.write('# At 18.6GHz, model says ' + str(spectrum(params, x=18.6))+'\n')
	outputfile.write('# At 24.6GHz, model says ' + str(spectrum(params, x=24.6))+'\n')

	model_spd = spinningdust(spd_freq, spd_amp, solid_angle, 30.0, 1.0, 0.0)
	model_spd_norm = 0.5*spectrum(params,x=30.0)/model_spd
	model_spd_25 = spinningdust(spd_freq, spd_amp, solid_angle, 24.6, 1.0, 0.0)*model_spd_norm
	model_spd_19 = spinningdust(spd_freq, spd_amp, solid_angle, 18.6, 1.0, 0.0)*model_spd_norm

	outputfile.write('# At 30GHz, model says ' + str(spectrum(params,x=30.0))+'\n')
	outputfile.write('# At 18.6GHz, AME might be ' + str(model_spd_19)+'\n')
	outputfile.write('# At 24.6GHz, AME might be ' + str(model_spd_25)+'\n')
	flux = spectrum(params, x=7.0)
	outputfile.write('# 7.0	'+str(flux)+'	'+str(flux*0.05)+'\n')
	flux = spectrum(params, x=18.6)+model_spd_19
	outputfile.write('# 18.6	'+str(flux)+'	'+str(flux*0.05)+'\n')
	flux = spectrum(params, x=24.6)+model_spd_25
	outputfile.write('# 24.6	'+str(flux)+'	'+str(flux*0.05)+'\n')
	outputfile.close()
	return

def fitspectrum(filename, srcname='',indir='', outdir='', spd_file='amemodels/spdust2_wim.dat',
	format=1, inunits='Jy',fitunits='Jy',minfitfreq=0,maxfitfreq=0,
	nosync=False,nofreefree=False,noame=False,nocmb=False,nodust=False,
	startparams=0,mcmc=True,quiet=False,nosyncbeta=False):#,nodust2=True, fixdust2temp=0

	print(outdir)
	ensure_dir(outdir)

	# Read in the spinning dust curve
	global spd_freq
	global spd_amp
	spd_freq, spd_amp = np.loadtxt(spd_file, dtype=float,usecols=(0,1),comments=';',unpack=True)

	# solid_angle = calc_beam_area(100.0/60.0,0.7*100.0/60.0)
	# print(solid_angle)

	###
	# Read in the file containing the SED data
	# Different formats are supported, namely:
	# 1: freq [GHz] flux [Jy] err [Jy]'
	# 2: freq [Hz] flux [Jy] err [Jy]'
	# 3: wavelength [um]  flux [W/m^2/um] err [W/m^2/um]
	# Use # to mark comments in the input file, and these will be ignored.
	# For the actual fitting, we'll use freq [GHz], flux [Jy], err [Jy] - other formats will be converted to this.
	###
	inputspectrum = np.loadtxt(filename)
	if format == 1:
		freqs = inputspectrum[:,0]
		fd = inputspectrum[:,1]
		fd_err = inputspectrum[:,2]
	elif format == 2:
		freqs = inputspectrum[:,0] / 1e9
		fd = inputspectrum[:,1]
		fd_err = inputspectrum[:,2]
	elif format == 3:
		wavelength = inputspectrum[:,0]
		freqs = const['c'] / (wavelength*1e3)
		fd = inputspectrum[:,1] / ((1e-26 * (const['c']*1e6) / (wavelength**2))) # Convert from W/m^2/um to W/m^2/Hz then to Jy
		fd_err = inputspectrum[:,2] / ((1e-26 * (const['c']*1e6) / (wavelength**2)))

	num_datapoints = len(freqs)
	print('Fitting ' + str(num_datapoints) + ' data points')

	minfreq = min(freqs)
	maxfreq = max(freqs)
	minflux = min(fd)
	maxflux = max(fd)
	# Assume 10% uncertainties across the board for now
	fd_err = np.sqrt((0.1*fd)**2+fd_err**2)

	# Define which values we want to use in the fit
	goodvals = np.ones(num_datapoints)
	if maxfitfreq != 0:
		goodvals[freqs > maxfitfreq] = 0
	if minfitfreq != 0:
		goodvals[freqs < minfitfreq] = 0
	num_goodvals = np.sum(goodvals)
	badvals = True
	if (num_goodvals == num_datapoints):
		badvals = False

	###
	# Use MPFit
	###

	# Set up the initial parameters
	num_params = 10
	parbase={'value':0., 'fixed':0, 'limited':[0,0], 'limits':[0.,0.]}
	parinfo=[]
	for i in range(0,num_params):
		parinfo.append(copy.deepcopy(parbase))

	# Starting parameters
	p0 = [10.0,8000.,1.0,1.7,20.,1.,0.,10.0,-1.0, 0]#, 1.0,1.7,1000.]  # standard starting values
	if startparams != 0:
		p0 = startparams

	# Free-free, EM then Te
	parinfo[0]['limited'] = [1,1]
	parinfo[0]['limits'] = [0,1e10]
	parinfo[1]['limited'] = [1,1]
	parinfo[1]['limits'] = [1000.,30000.]
	parinfo[1]['fixed'] = 1  # fix Te
	if nofreefree == True:
		p0[0] = 0
		parinfo[0]['fixed'] = 1
		# parinfo[0]['limits'] = [p0[0],p0[0]]
		parinfo[1]['fixed'] = 1
		# parinfo[1]['limits'] = [p0[1],p0[1]]

	# Thermal dust: optical depth, then index, then temperature
	parinfo[2]['limited'] = [1,1]
	parinfo[2]['limits'] = [0.0,100.]
	parinfo[3]['limited'] = [1,1]
	parinfo[3]['limits'] = [0.5,3.5]
	parinfo[3]['fixed'] = 0  # fix dust emissivity index
	parinfo[4]['limited'] = [1,1]
	parinfo[4]['limits'] = [5.,600.]
	if nodust == True:
		p0[2] = 0
		parinfo[2]['fixed'] = 1
		parinfo[3]['fixed'] = 1
		parinfo[4]['fixed'] = 1

	# Spinning dust amplitude
	parinfo[5]['limited'] = [1,1]
	parinfo[5]['limits'] = [0.,1e25]
	parinfo[9]['fixed'] = 1  # spdust shift
	parinfo[9]['limited'] = [1,1]
	parinfo[9]['limits'] = [0.0,1e10]
	if noame == True:
		p0[5] = 0
		parinfo[5]['fixed'] = 1
		parinfo[9]['fixed'] = 1

	# CMB delta T (CMB) in K
	parinfo[6]['limited'] = [1,1]
	parinfo[6]['limits'] = [-150.0,150.0]#*1e-6
	if nocmb == True:
		p0[6] = 0
		parinfo[6]['fixed'] = 1

	# Synchrotron, amplitude then index
	parinfo[7]['limited'] = [1,1]
	parinfo[7]['limits'] = [0.0,1e10]
	parinfo[8]['limited'] = [1,1]
	parinfo[8]['limits'] = [-3.0,1.0]
	if nosync == True:
		p0[7] = 0
		parinfo[7]['fixed'] = 1
		parinfo[8]['fixed'] = 1
	if nosyncbeta == True:
		parinfo[8]['fixed'] = 1
	p0[8] = -1.0
	# parinfo[8]['fixed'] = 1

	# Second thermal dust component: optical depth, then index, then temperature. Disabled by default.
	# parinfo[10]['limited'] = [1,1]
	# parinfo[10]['limits'] = [0.0,100.]
	# parinfo[11]['limited'] = [1,1]
	# parinfo[11]['limits'] = [0.0,3.5]
	# parinfo[12]['limited'] = [1,1]
	# parinfo[12]['limits'] = [5.,10000.]
	# if nodust2 == True:
	# 	p0[10] = 0
	# 	parinfo[10]['fixed'] = 1
	# 	parinfo[11]['fixed'] = 1
	# 	parinfo[12]['fixed'] = 1
	# if fixdust2temp != 0:
	# 	p0[12] = fixdust2temp
	# 	parinfo[12]['fixed'] = 1

	print('Full info:')
	print(parinfo)

	# Do the fit
	fa = {'x':freqs[goodvals == 1], 'y':fd[goodvals == 1], 'err':fd_err[goodvals == 1]}
	m = mpfit(mpfitfunction, p0, parinfo=parinfo,functkw=fa,xtol=1e-30,quiet=True)

	print('status = ', m.status)
	if (m.status <= 0):
		print('error message = ', m.errmsg)

	print('Number of iterations: ', m.niter)
	dof = len(freqs[goodvals == 1]) - len(m.params)
	print('Degrees of freedom: ', dof)
	print('Chisq: ', m.fnorm / dof)
	print('Parameters: ', m.params)

	plot_results(outdir+srcname+'.pdf',srcname,minfreq,maxfreq,m.params,const,solid_angle,spd_freq,spd_amp,freqs,fd,fd_err,goodvals,minflux,maxflux)

	get_percentage(outdir+srcname+'.pdf',srcname,30.0,m.params,const,solid_angle,spd_freq,spd_amp,freqs,fd,fd_err,goodvals,minflux,maxflux)
	write_results(outdir+srcname+".txt",srcname,freqs,fd,fd_err,m.params,m.perror, const, solid_angle)
	# exit()

	###
	# MCMC fitting
	###
	if mcmc == True:

		nll = lambda *args: -lnlike(*args)
		p = p0
		# p = m.params
		# x = freqs[goodvals == 1]
		# y = fd[goodvals == 1]
		# yerr = fd_err[goodvals == 1]
		bounds = np.zeros((num_params,2))
		for i in range(0,num_params):
			if parinfo[i]['fixed'] == 1:
				if p0[i] == 0:
					bounds[i][0] = -1e-5
				else:
					bounds[i][0] = p0[i]*0.999
			elif parinfo[i]['limited'][0] == 1:
				bounds[i][0] = parinfo[i]['limits'][0]
			else:
				bounds[i][0] = None
			if parinfo[i]['fixed'] == 1:
				if p0[i] == 0:
					bounds[i][1] = 1e-5
				else:
					bounds[i][1] = p0[i]*1.0001
			elif parinfo[i]['limited'][1] == 1:
				bounds[i][1] = parinfo[i]['limits'][1]
			else:
				bounds[i][1] = None
		print(bounds)
		result = op.minimize(nll, p, args=(freqs[goodvals == 1], fd[goodvals == 1], fd_err[goodvals == 1]), bounds=bounds, method='L-BFGS-B')#, options={'gtol': 1e-30, 'disp': False, 'maxiter': 4000})
		maxlikelihood = result["x"]
		print("Done")
		print(m.params)
		print(maxlikelihood)
		print(result['success'])
		print(result['message'])

		plot_results(outdir+srcname+'_likelihood.pdf',srcname,minfreq,maxfreq,maxlikelihood,const,solid_angle,spd_freq,spd_amp,freqs,fd,fd_err,goodvals,minflux,maxflux)
		write_results(outdir+srcname+"_likelihood.txt",srcname,freqs,fd,fd_err,maxlikelihood,np.zeros(len(maxlikelihood)), const, solid_angle)

		# Let's do some MCMC fitting!
		ndim = num_params
		nwalkers = 100
		# not_fixed *= 1e-4 # Use a random distribution only for values that aren't fixed.
		pos = [result["x"] + 1e-4*result["x"]*np.random.randn(ndim) for i in range(nwalkers)]
		sampler = emcee.EnsembleSampler(nwalkers, ndim, lnprob, threads=8,args=(bounds, freqs[goodvals == 1], fd[goodvals == 1], fd_err[goodvals == 1]))
		sampler.run_mcmc(pos, 5000)

		samples = sampler.chain[:, 50:, :].reshape((-1, ndim))
		plt.plot(samples[:,0])
		plt.savefig(outdir+srcname+'_test.png')
		plt.close()
		plt.plot(samples[:,1])
		plt.savefig(outdir+srcname+'_test1.png')
		plt.close()
		plt.plot(samples[:,2])
		plt.savefig(outdir+srcname+'_test2.png')
		plt.close()
		plt.plot(samples[:,3])
		plt.savefig(outdir+srcname+'_test3.png')
		plt.close()

		# samples[:, 2] = np.exp(samples[:, 2])
		p1,p2,p3,p4,p5,p6,p7,p8,p9,p10 = map(lambda v: (v[1], v[2]-v[1], v[1]-v[0]),
                             zip(*np.percentile(samples, [16, 50, 84],
                                                axis=0)))
		vals = np.zeros(num_params)
		vals[0] = p1[0]
		vals[1] = p2[0]
		vals[2] = p3[0]
		vals[3] = p4[0]
		vals[4] = p5[0]
		vals[5] = p6[0]
		vals[6] = p7[0]
		vals[7] = p8[0]
		vals[8] = p9[0]
		vals[9] = p10[0]
		# vals[10] = p11[0]
		# vals[11] = p12[0]
		# vals[12] = p13[0]
		errs = np.zeros(num_params)
		errs[0] = p1[1]
		errs[1] = p2[1]
		errs[2] = p3[1]
		errs[3] = p4[1]
		errs[4] = p5[1]
		errs[5] = p6[1]
		errs[6] = p7[1]
		errs[7] = p8[1]
		errs[8] = p9[1]
		errs[9] = p10[1]
		# errs[10] = p11[1]
		# errs[11] = p12[1]
		# errs[12] = p13[1]
		print(errs)
		# print(m_mcmc)
		# print(b_mcmc)
		# print(f_mcmc)
		# print(vals)
		# print(np.shape(vals))
		# exit()
		plot_range = []
		for i in range(0,num_params):
			if parinfo[i]['fixed'] == 1:
				if vals[i] == 0.0:
					plot_range.append((-0.01, 0.01))
				else:
					plot_range.append((0.99*vals[i], 1.01*vals[i]))
			elif vals[i] == 0.0:
				plot_range.append((-0.01, 0.01))
			else:
				plot_range.append((np.min(samples[:,i]),np.max(samples[:,i])))
				# plot_range.append((vals[i]-3.0*errs[i],vals[i]+3.0*errs[i]))
				# plot_range[i][1] = max(samples[:,i])
		print(plot_range)
		fig = corner.corner(samples, labels=['EM', 'Te', 'Damp', 'Dalph', 'Dtemp', 'SDamp', 'dTCMB','Samp','Salph','SDshift'],range=plot_range,show_titles=True)#,'Damp', 'Dalph', 'Dtemp'
                      # truths=[m_true, b_true, np.log(f_true)])
		fig.savefig(outdir+srcname+"_triangle.png")
		plt.close()

		plot_results(outdir+srcname+'_mcmc.pdf',srcname,minfreq,maxfreq,vals,const,solid_angle,spd_freq,spd_amp,freqs,fd,fd_err,goodvals,minflux,maxflux)
		write_results(outdir+srcname+"_mcmc.txt",srcname,freqs,fd,fd_err,vals,errs, const, solid_angle)

# That's all, folks!


from art import logo, vs
from game_data import data
import random

play = True

while play:
    print(logo)
    questions = data
    winning = True
    A = random.choice(questions)
    questions.remove(A)
    score = 0
    while winning:
        B = random.choice(questions)
        questions.remove(B)
        x = A['follower_count']
        y = B['follower_count']
        if x > y:
            answer_letter = 'A'
            answer = A
        else:
            answer_letter = 'B'
            answer = B
        print(f"Compare A : {A['name']}, a {A['description']}, from {A['country']} ")
        print(vs)
        print(f"Compare B : {B['name']}, a {B['description']}, from {B['country']} ")
        choice = input("Who has more followers ? Type 'A' or 'B' : ")
        if choice.upper() == answer_letter:
            score += 1
            print(f"You are correct !! Your Score = {score}")
            A = answer
        else:
            print(f"You lose. Your score is : {score}")
            print(
                f"{A['name']} has {A['follower_count']} million followers and {B['name']} has {B['follower_count']} million followers")
            winning = False
            temp = input("Do you want to play the game again? Press 'y' or 'n' :")
            if temp.lower() == 'y':
                play = True
            else:
                play = False


import torch
import torch.backends.cudnn as cudnn
from tqdm import tqdm

import configuration
import numpy as np
from utils import utils, create_model, prepare_dataset
from models import projector, ResNet
import copy

def experiment(args):
    device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
    # device = "cpu"
    cudnn.benchmark = True

    '''--------------------Loading Model-----------------------------'''
    print('Loading model')
    model = ResNet.resnet50(10).cuda()
    #checkpoint = torch.load(args.root + 'weights/' + 'cifar10_resnet50_12_together' + '.pth') #cifar10_resnet50_all_together.pth')
    checkpoint = torch.load('../../Summer2022/TTTFlow/ttt/ttt_together_350_4CLASSES.pth')
    ckpt = checkpoint['net']
    #for key in list(ckpt.keys()):
    #    ckpt[key.replace('module.', '')] = ckpt[key]
    #    ckpt.pop(key)
    model.load_state_dict(ckpt, strict=False) #, strict=False)
    state = copy.deepcopy(model.state_dict())

    '''--------------------Test-Time Adaptation----------------------'''
    print('Test-Time Adaptation')
    common_corruptions = ['original', 'cifar_new', 'gaussian_noise', 'shot_noise', 'impulse_noise', 'defocus_blur', 'glass_blur',
                          'motion_blur', 'zoom_blur', 'snow', 'frost', 'fog',
                          'brightness', 'contrast', 'elastic_transform', 'pixelate', 'jpeg_compression']
    for corruption in common_corruptions:
        args.corruption = corruption
        teloader, _ = prepare_dataset.prepare_test_data(args)
        correct = 0
        for batch_idx, (inputs, labels) in tqdm(enumerate(teloader)):
            inputs, labels = inputs.to(device, non_blocking=True), labels.to(device, non_blocking=True)
            model.load_state_dict(state)
            correctness, _ = utils.test_batch(model, inputs, labels)
            correct += correctness.sum().item()

        accuracy = correct/len(teloader.dataset)
        print('--------------------RESULTS----------------------')
        print('Perturbation: ', args.corruption)
        print('Accuracy: ', accuracy)

if __name__ == '__main__':
    args = configuration.argparser()
    experiment(args)


import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import numpy as np
import cv2

image = mpimg.imread('./road.png')

def grayscale(img):
    return cv2.cvtColor(img,cv2.COLOR_RGB2GRAY)

def canny(img,low_threshold=100,high_threshold=200):
    return cv2.Canny(img,low_threshold,high_threshold)

def region_of_interest(img):
        """
        分割出ROI，并填充，再对图像掩膜处理，将其他object遮挡
        """
        #draw the polygon with three vertices
        height=img.shape[0]
        width=img.shape[1]
        region_of_interest_vertices = [
        (0, height),
        (width / 2, height / 2),
        (width, height)]
        # Define a blank matrix that matches the image height/width.
        mask = np.zeros_like(img)
        # Retrieve the number of color channels of the image.
        #channel_count = img.shape[2]
        # Create a match color with the same color channel counts.
        #match_mask_color = (255,) * channel_count #彩色图像时的color
        match_mask_color = 255
        # Fill inside the polygon
        #cv2.fillPoly(mask, np.array([region_of_interest_vertices],np.int32)，match_mask_color)#多边形填充
        cv2.fillPoly(mask, np.array([region_of_interest_vertices],np.int32), match_mask_color)
        #按位与操作，对图片进行mask淹膜操作，ROI区域正常显示，其他区域置零
        masked_image = cv2.bitwise_and(img, mask)
        return masked_image

def hough_lines(img,rho=6,theta=np.pi/180,threshold=160,
                    min_line_len=40,max_line_gap=25):

        lines=cv2.HoughLinesP(img,rho,theta,threshold, np.array([]),
                              minLineLength=min_line_len, maxLineGap=max_line_gap)
        return lines

def draw_lines(img,lines,color=[255,0,0],thickness=3):
        imm=img

        if lines is None:
            return
        img=np.copy(img)
        #生成待划线的图,zeros，addweighted混合的时候，0值不会显示
        img_channels=img.shape[2]
        line_img=np.zeros((img.shape[0],img.shape[1],img_channels),dtype=np.uint8)
        for line in lines:
            for x1,y1,x2,y2 in line:
                cv2.line(line_img,(x1,y1),(x2,y2),color,thickness)
        img=cv2.addWeighted(img, 0.8, line_img, 1.0, 0.0, imm, cv2.CV_32F)
        return img

def group_lines_and_draw(img,lines):
    """
    根据斜率，将所有的线分为左右两组,斜率绝对值小于0.5的舍去（影响不显著）
    （因为图像的原点在左上角，slope<0是left lines，slope>0是right lines)
    设定min_y作为left和right的top线,max_y为bottom线，求出四个x值即可确定直线：
    将left和right的点分别线性拟合，拟合方程根据y值，求出x值，画出lane
    """
    left_x,left_y,right_x,right_y=[],[],[],[]
    for line in lines:
        for x1,y1,x2,y2 in line:
            slope=(y2-y1)/(x2-x1)
            #if abs(slope)<0.5: continue
            if slope<0:
                left_x.extend([x1,x2])
                left_y.extend([y1,y2])
            if slope>0:
                right_x.extend([x1,x2])
                right_y.extend([y1,y2])
    #设定top 和 bottom的y值，left和right的y值都一样
    min_y=int(img.shape[0]*(3/5))
    max_y=int(img.shape[0])

    #对left的所有点进行线性拟合
    poly_left = np.poly1d(np.polyfit(left_y,left_x,deg=1))
    left_x_start = int(poly_left(max_y))
    left_x_end = int(poly_left(min_y))
    #对right的所有点进行线性拟合
    poly_right = np.poly1d(np.polyfit(right_y,right_x,deg=1))
    right_x_start = int(poly_right(max_y))
    right_x_end = int(poly_right(min_y))

    line_image=draw_lines(img,[[
            [left_x_start,max_y,left_x_end,min_y],
            [right_x_start,max_y,right_x_end,min_y],
            ]],thickness=5)
    return line_image

#plt.imshow(image)
#plt.show()

gray_image=grayscale(image)
#plt.imshow(gray_image, cmap='gray')
gray_image = (gray_image * 255).astype(np.uint8)

canny_img=canny(gray_image)
#canny_img = (canny_img * 255).astype(np.uint8)
#plt.imshow(canny_img)
#plt.show()

ROI_img=region_of_interest(canny_img)
#ROI_img = (ROI_img * 255).astype(np.uint8)
#plt.imshow(ROI_img)
#plt.show()

lines=hough_lines(ROI_img)
line_img=draw_lines(image,lines)
#final_image=group_lines_and_draw(image,lines)

#line_img = (line_img * 255).astype(np.uint8)
plt.imshow(line_img)

plt.show()


import numpy as np
import matplotlib.pyplot as plt

Nlights = 1000
results = np.zeros(Nlights)
prob_evolution = np.zeros(Nlights)

for light in range(1, Nlights):
  #cada semaforo rojo se reinicia
  red_light = np.random.choice([0, 1, 2, 3, 4, 5], p=[0.1, 0.13, 0.21, 0.23, 0.2, 0.13])
  results[light] = red_light

print('Mean: ', np.mean(results))

plt.hist(results, 5)
plt.show()


import pandas as pd

link = pd.read_csv("../data/link_lt_gn.tab", sep="\t", names=["genename", "locustag"])

old_fasta_file = open("../data/reference_sequences/oligos_cds.fasta", "r")
new_fasta_file = open("../data/reference_sequences/oligos_cds_with_name.fasta", "w")

for line in old_fasta_file:
    if line[0] != ">":
        new_fasta_file.write(line)
    else:
        splitted_line = line.split("_")
        lt = splitted_line[0][1:]
        gname = link.loc[link["locustag"] == lt]
        if len(gname) > 0:
            line = line[:-1] + "_" + gname.iloc[0, 0] + "\n"
        new_fasta_file.write(line)

old_fasta_file.close()
new_fasta_file.close()


from aiogram import Bot, Dispatcher, executor, types

bot = Bot('5836660462:AAGe1SzEod0F4KBRm4HQLBUz5KwkYB7SXto')
dp = Dispatcher(bot)

async def on_start(_):
    print('Бот запущен')

@dp.message_handler(commands=['start'])
async def mes_start(message: types.Message):
    await message.answer('Привет' )

@dp.message_handler(commands=['help'])
async def mes_help(message: types.Message):
    await message.answer('Пока ничего не умею')

@dp.message_handler()
async def mes_all(message: types.Message):
    await message.answer('Ловлю всё')

executor.start_polling(dp, skip_updates=True, on_startup=on_start)