import sys
sys.path.append("../../../tm_transport/python_lib")

import TMTransport
import asyncio
from enum import Enum
from typing import Callable
from datetime import datetime
import cbor
import aiofiles

import click

count : int = 0

async def printQueueData(qin : asyncio.Queue, printMode : str = "length"):
    printFunc : Callable[[bytes], str] = lambda x : ""
    if printMode == "length":
        printFunc = lambda x : f"{len(x)} bytes"
    elif printMode == "string":
        printFunc = lambda x : x.decode('utf-8')
    elif printMode == "cbor":
        printFunc = lambda x : repr(cbor.loads(x))
    elif printMode == "bytes":
        printFunc = lambda x : repr(x)

    global count

    #Please note that Python's protobuf module does not support
    #dynamic decoding, therefore the dynamic protobuf printing
    #functionality in node version is not supported here

    while True:
        item : Tuple[string, bytes] = await qin.get()
        count = count+1
        if item:
            now = datetime.now()
            print(f"{now.strftime('%Y-%m-%d %H:%M:%S.%f')}: topic '{item[0]}': {printFunc(item[1])}")

@click.command()
@click.option('--address', help='PROTOCOL://LOCATOR')
@click.option('--topic', help='topic to subscribe', default=None)
@click.option('--printMode', help='length|string|cbor|none|bytes', default='length')
@click.option('--summaryPeriod', help='summary period in seconds', default=0)
@click.option('--captureFile', help='capture file name', default=None)

def run(address : str, topic : str, printmode : str, summaryperiod : int, capturefile : str):
    async def asyncMain() :
        if summaryperiod > 0:
            async def printSummary():
                global count
                while True:
                    await asyncio.sleep(summaryperiod)
                    now = datetime.now()
                    print(f"{now.strftime('%Y-%m-%d %H:%M:%S.%f')}: Received {count} messages so far")
            asyncio.create_task(printSummary())
        printQueue = asyncio.Queue()
        qouts = [printQueue]
        tasks = []
        if capturefile:
            captureQueue = asyncio.Queue()
            async def writeCaptureFile():
                async with aiofiles.open(capturefile, "wb") as o:
                    await o.write(b'\x01\x23\x45\x67')
                    while True:
                        topic, data = await captureQueue.get()
                        now = datetime.now()
                        t : int = int(now.timestamp()*1000000.0)+now.microsecond
                        l : int = len(topic)
                        ld : int = len(data)
                        writeData = b'\x76\x54\x32\x10'\
                                    +t.to_bytes(8, byteorder='little')\
                                    +l.to_bytes(4, byteorder='little')\
                                    +topic.encode()\
                                    +ld.to_bytes(4, byteorder='little')\
                                    +data\
                                    +b'\x00'
                        await o.write(writeData)
            tasks.append(asyncio.create_task(writeCaptureFile()))
            qouts = [printQueue, captureQueue]
        tasks.extend(TMTransport.MultiTransportListener.input(address, qouts, topic = topic))
        tasks.append(asyncio.create_task(printQueueData(printQueue, printMode=printmode)))
        await asyncio.gather(*tasks)
    asyncio.run(asyncMain())

if __name__ == "__main__":
    run()


""" Module for checking data integrity """
import os
import logging

from LNG_AI import utils
from LNG_AI import constants

def record_failure_success(func):
    """decorator for recording failure/success"""
    def wrapper(*args, **kwargs):
        args[0]._total_cnt += 1
        result = func(*args, **kwargs)
        if result:
            args[0]._success_cnt += 1
        else:
            args[0]._failure_cnt += 1
    return wrapper

class DataIntegrityChecker():
    """Class for checking data integrity"""

    def __init__(self) -> None:
        self._init_cnt()

    def _init_cnt(self):
        self._failure_cnt = 0
        self._success_cnt = 0
        self._total_cnt = 0

    @record_failure_success
    def _check_transcript_repetitive_word_occurance(
            self, transcript_path: str) -> None:
        return utils.TranscriptUtils.check_transcript_repetitive_word_occurance(
            transcript_path, 0.1, False)

    @record_failure_success
    def _check_file_exist(self, file_path: str) -> None:
        if not os.path.isfile(file_path):
            logging.error(file_path, "is not exist")
            return False

        return True

    def check_transcripts_creation(self) -> None:
        """Check if transcripts are created successfully"""
        audio_file_dirs = utils.FileUtils.get_audio_file_directories()
        for audio_file_dir in audio_file_dirs:
            # 1-minute transcripit preview
            self._check_file_exist(
                f"{audio_file_dir}/whisper/{constants.AudioFileKeyword.PREVIEW.value}.txt")

            # 5-minutes transcripts
            for five_minutes_transcript_path in utils.FileUtils.get_five_minutes_chuck_transcript_paths(
                    audio_file_dir):
                self._check_file_exist(five_minutes_transcript_path)

        print(f"Transcripts created successfully: {100 * self._success_cnt/self._total_cnt}%",
              f"({self._success_cnt}/{self._total_cnt})")
        self._init_cnt()

    def check_transcripts_repetitive_word_occurance(self) -> None:
        """Check if transcripts have not reptitive word occurance"""
        audio_file_dirs = utils.FileUtils.get_audio_file_directories()
        for audio_file_dir in audio_file_dirs:
            # 5-minutes transcripts
            for five_minutes_transcript_path in utils.FileUtils.get_five_minutes_chuck_transcript_paths(
                    audio_file_dir):
                self._check_transcript_repetitive_word_occurance(
                    five_minutes_transcript_path)

        print(f"Transcripts AI-transcribed successfully: {100 * self._success_cnt/self._total_cnt}%",
              f"({self._success_cnt}/{self._total_cnt})")
        self._init_cnt()

    def check_audio_files_creation(self) -> None:
        """Check if audio files are created successfully"""
        audio_file_dirs = utils.FileUtils.get_audio_file_directories()
        for audio_file_dir in audio_file_dirs:
            self._check_file_exist(
                f"{audio_file_dir}/{constants.AudioFileKeyword.FULL.value}.mp3")
            self._check_file_exist(
                f"{audio_file_dir}/{constants.AudioFileKeyword.PREVIEW.value}.mp3")

            # 1-hour audios
            for one_hour_audio_path in utils.FileUtils.get_one_hour_chuck_audio_paths(
                    audio_file_dir):
                self._check_file_exist(one_hour_audio_path)

            # 5-minutes audios
            for five_minutes_audio_path in utils.FileUtils.get_five_minutes_chuck_audio_paths(
                    audio_file_dir):
                self._check_file_exist(five_minutes_audio_path)

        print(f"Audio files created successfully: {100 * self._success_cnt/self._total_cnt}%",
              f"({self._success_cnt}/{self._total_cnt})")
        self._init_cnt()


""" Write a program to accept 2 strings from user and
swap 1st 2 characters of each of them. """
def mixstr(str1,str2):
    str3 = str2[:2]+str1[2:]
    str4 = str1[:2]+str2[2:]
    print ("Result of String:%s is String:%s \n Result of String:%s is String:%s" %(str1,str3,str2,str4))

str1,str2 = eval(input("Enter two strings: "))
mixstr(str1,str2)


import json
import re

class RuleBase:
	def __init__(self, dict_file='utils/text_correction/rule_base_dict.json'):
		with open(dict_file, 'r') as fp:
			self.data = json.load(fp)
		self.error_words = []
		self.correct_words = []
		for error_word, correct_word in self.data.items():
			self.error_words.append(error_word)
			self.correct_words.append(correct_word)

	def correct(self, string_to_correct):
		string_words = re.findall(r'\S+|\n', string_to_correct)
		for i in range(len(string_words)):
			if string_words[i] == '\n':
				continue
			if string_words[i].lower() in self.error_words:
				string_words[i] = self.data[string_words[i].lower()]
		return " ".join(string_words)


import argparse
import json
import logging
import os
import pickle

from fast_bert.data_cls import BertDataBunch
from fast_bert.learner_cls import BertLearner
from fast_bert.metrics import accuracy, F1
import numpy as np
import pandas as pd
import torch
from tqdm import tqdm

from metric import F1 as myF1
from output_csv import output_csv
from pred_to_output_format import pred_to_output_format

COLS = ['THEORETICAL', 'ENGINEERING', 'EMPIRICAL', 'OTHERS']

def parse_args():
    """ Parse args. """
    parser = argparse.ArgumentParser()

    # output
    parser.add_argument('model_idx', type=int,  help='model index')

    # model
    parser.add_argument('--raw_pred', help='raw output prediction')

    # toggle True / False
    parser.add_argument('--is_large', action='store_true',
                        help='True for is_large (False for is_base)')
    parser.add_argument('--disable_amp', action='store_true',
                        help='True for disabling amp')
    parser.add_argument('--no_tune', action='store_true',
                        help='Don\'t tune the params of BERT.')
    parser.add_argument('--pos_weight', action='store_true',
                        help='True for use pos weight.')

    # numbers
    parser.add_argument('-b', '--batch_size', type=int, default=32,
                        help='batch size')
    parser.add_argument('--lr', '--learning_rate', type=float, default=5e-5,
                        help='The initial learning rate for Adam')
    parser.add_argument("--warmup_steps", default=0, type=int,
                        help="Linear warmup over warmup_steps.")
    parser.add_argument('-s', '--seed', type=int, default=6174,
                        help='random seed')
    parser.add_argument('-e', '--epoch_size', type=int, default=10,
                        help='epoch size')
    parser.add_argument('--valid', type=float, default=0.001,
                        help='Split validation data to observe loss & f1.')
    parser.add_argument("--weight_decay", default=0.0, type=float,
                        help="Weight deay if we apply some.")
    parser.add_argument('-t', '--thres', type=float, default=0.5,
                        help='threshold')

    args = parser.parse_args()
    return args

def learner_pred(learner, test_texts, thres=0.5, batch_num=100):
    pred = []
    for batch_idx in range(len(test_texts) // batch_num):
        text = test_texts[batch_idx * batch_num: (batch_idx + 1) * batch_num]
        pred += learner.predict_batch(text)

    output_df = pd.DataFrame(columns=COLS)
    for row in tqdm(pred, desc='transfer pred to output format'):
        output_df = output_df.append({
            elm[0]: elm[1]
            for elm in row
        }, ignore_index=True)
    output_df = 0 + (output_df > thres)
    return output_df.values

def run():
    args = parse_args()

    with open('fast_bert_val.csv') as infile:
        val_df = pd.read_csv(infile)
        val_text = val_df['text'].tolist()
        val_label = torch.Tensor(val_df[COLS].values).float()

    DATA_PATH = './'
    LABEL_PATH = './'
    OUTPUT_DIR = './'
    logging.basicConfig(level=logging.NOTSET)
    logger = logging.getLogger()
    databunch = BertDataBunch(DATA_PATH,
                              LABEL_PATH,
                              tokenizer='xlnet-base-cased',
                              train_file='fast_bert_train.csv',
                              val_file='fast_bert_val.csv',
                              label_file='labels.csv',
                              text_col='text',
                              label_col=['THEORETICAL', 'ENGINEERING', 'EMPIRICAL', 'OTHERS'],
                              batch_size_per_gpu=8,
                              max_seq_length=512,
                              multi_gpu=True,
                              multi_label=True,
                              model_type='xlnet')

    device_cuda = torch.device('cuda')
    metrics = [{'name': 'f1', 'function': F1}]
    learner = BertLearner.from_pretrained_model(databunch,
                                                pretrained_path='xlnet-base-cased',
                                                metrics=metrics,
                                                device=device_cuda,
                                                logger=logger,
                                                output_dir=OUTPUT_DIR,
                                                finetuned_wgts_path=None,
                                                warmup_steps=500,
                                                multi_gpu=True,
                                                is_fp16=False,
                                                multi_label=True,
                                                logging_steps=50)

    # train
    learner.fit(epochs=args.epoch_size,
                lr=args.lr,
                validate=True,
                schedule_type='warmup_cosine',
                optimizer_type='lamb')
    learner.save_model()

    os.rename('./model_out', 'model_out_{}'.format(args.model_idx))

    # test
    with open('./test_abstract.json') as infile:
        test_texts = json.load(infile)
    test_pred = learner_pred(learner, test_texts)

    pred_pad = np.zeros((40000, test_pred.shape[1]), int)
    pred_pad[:20000] = test_pred
    pred_fn = './{}.csv'.format(args.model_idx)
    output_csv(test_pred, pred_fn)
    print('Outputed to ', pred_fn)

    # get f1
    val_pred = learner_pred(learner, val_text)
    f1_score = myF1()
    f1_score.update(torch.Tensor(val_pred), val_label)
    print('valid f1_score =', f1_score.get_score())

if __name__ == '__main__':
    run()


import trimesh
import meshio
import numpy as np
from tqdm import tqdm

vtk_mesh = meshio.vtk.read('/home/SENSETIME/xulixin2/RJ_demo/mesh/all.vtk')

points = vtk_mesh.points
cells = vtk_mesh.cells[0].data
label_data = vtk_mesh.cell_data['MeshDomain'][0]

label_value = set(label_data)
color_data = list(range(len(label_value)))
color_dict = dict(zip(label_value, color_data))

with open('/home/SENSETIME/xulixin2/RJ_demo/mesh/all.face', 'r') as f:
    lines = f.readlines()
    surface_faces = []
    for line in lines[1:]:
        # skip the first line
        surface_faces.append([int(x) for x in line.split()[1:4]])
    surface_faces = np.array(surface_faces)

face_dict = {}
for i, cell in enumerate(cells):
    cell_faces = []
    for j in range(4):
        for k in range(j + 1, 4):
            for l in range(k + 1, 4):
                face = tuple(sorted([cell[j], cell[k], cell[l]]))
                cell_faces.append(face)
                for face in cell_faces:
                    if face in face_dict: face_dict[face].append(i)
                    else: face_dict[face] = [i]

face_label = []
for each_face in tqdm(surface_faces, total=len(surface_faces)):
    face = tuple(sorted(each_face))
    if face not in face_dict.keys():
        print(f'face:{face} not in face_dict.keys()')
        continue
    tetra_index = face_dict[face]
    label = label_data[tetra_index]
    face_label.append(color_dict[min(label)])

with open('/home/SENSETIME/xulixin2/RJ_demo/mesh/fine_liver_labeled.face', 'a') as f:
    f.write(f'{len(surface_faces)} 0\n')
    for i, each_face in enumerate(surface_faces):
        f.write(f'{i} {each_face[0]} {each_face[1]} {each_face[2]} {int(face_label[i])}\n')


#!/usr/bin/env python
import json
import os
import sys
import babelfish
import pycountry

output_directory = "output"

def append_to_file(path, string):
    with open(path, 'a') as output:
        output.write(string)

def get_path(alpha3t_code):
    language = babelfish.Language.fromalpha3t(alpha3t_code)
    output_path = output_directory
    directory = 'values-' + language.alpha2
    if language == babelfish.Language('eng'):
        directory = 'values'
    path = output_path + os.path.sep + directory + os.path.sep
    if not os.path.exists(path):
        os.makedirs(path)
    return path + 'strings.xml'

def format_string(prefix, suffix, text):
    pattern = '<string name=\"{0}_{1}\">{2}</string>\n'
    return pattern.format(str(prefix.encode('utf-8')), str(suffix.encode('utf-8')), str(text.encode('utf-8')))

def export_country_names(country):
    translations = country["translations"]
    for translation in translations.keys():
        append_to_file(get_path(translation),
                       format_string(country['cca2'].lower(), 'name_common', translations[translation]['common']) +
                       format_string(country['cca2'].lower(), 'name_official', translations[translation]['official']))
    append_to_file(get_path('eng'),
                   format_string(country['cca2'].lower(), 'name_common', country["name"]['common']) +
                   format_string(country['cca2'].lower(), 'name_official', country["name"]['official']))

def export_currencies_names(currencies):
    for currency in currencies:
        append_to_file(get_path('eng'),
                       format_string(currency.lower(), 'currency_name', pycountry.currencies.get(letter=currency).name))

def export_languages_names(languages):
    for key in languages.keys():
        append_to_file(get_path('eng'),
                       format_string(key.lower(), 'language_name', languages[key]))

def export_capital_names(country):
    capital = country["capital"]
    append_to_file(get_path('eng'),
                   format_string(country['cca2'].lower(), "capital", capital))

def main(source_path):
    countries = []

    values_to_exclude = ["translations", "landlocked", "demonym"]

    with open(source_path, 'r') as data_file:
        data = json.load(data_file)

    currencies = []
    languages = {}
    for country in data:
        new_country = {}
        if country["region"] == "Europe":
            currencies += country["currency"]
            languages.update(country["languages"])
            for value in country:
                if value not in values_to_exclude:
                    new_country[value] = country[value]
            countries.append(new_country)
            export_country_names(country)
            export_capital_names(country)

    export_currencies_names(set(currencies))
    export_languages_names(languages)

    with open('filtered_countries.json', 'w') as file:
        file.write(json.dumps(countries))

if __name__ == "__main__":
    if len(sys.argv) < 2:
        print("Usage: filter.py source_file.json")
    else:
        main(source_path=sys.argv[1])


import tkinter as tk
from tkinter.filedialog import askopenfilename, asksaveasfilename
import platform,socket,re,uuid,psutil,configparser

config = configparser.ConfigParser()

# Class for the about page
class about():
  def __init__(self) -> None:
      self = tk.Toplevel()
      label = tk.Label(self, text='Version: 0.1')
      platformlabel = tk.Label(self, text=f'Platform: {platform.system()}')
      releaselabel = tk.Label(self, text=f'Release: {platform.release()}')
      versionlabel = tk.Label(self, text=f'Version: {platform.version()}')
      architlabel = tk.Label(self, text=f'Proccessor Architecture: {platform.machine()}')
      hostnamelabel = tk.Label(self, text=f'Hostname: {socket.gethostname()}')
      nodelabel = tk.Label(self, text=f'Node Name: {platform.node()}')
      ipaddlabel = tk.Label(self, text=f'IP Address: {socket.gethostbyname(socket.gethostname())}')
      macaddlabel = tk.Label(self, text="Mac Address: "+':'.join(re.findall('..', '%012x' % uuid.getnode())))
      processorlabel = tk.Label(self, text=f'Processor: {platform.processor()}')
      ramlabel = tk.Label(self, text=str(round(psutil.virtual_memory().total / (1024.0 **3)))+" GB")
      self.title('About')
      label.pack()
      platformlabel.pack()
      releaselabel.pack()
      versionlabel.pack()
      architlabel.pack()
      hostnamelabel.pack()
      nodelabel.pack()
      ipaddlabel.pack()
      macaddlabel.pack()
      processorlabel.pack()
      ramlabel.pack()
      self.mainloop()

class configeditor():
  def __init__(self) -> None:
      editor = tk.Toplevel()
      editor.title("Simple Text Editor")

      editor.rowconfigure(0, minsize=800, weight=1)
      editor.columnconfigure(1, minsize=800, weight=1)

      txt_edit = tk.Text(editor)
      fr_buttons = tk.Frame(editor)
      btn_open = tk.Button(fr_buttons, text="Open", command=self.open_file(txt_edit))
      btn_save = tk.Button(fr_buttons, text="Save As...", command=self.save_file(txt_edit))
      btn_open.grid(row=0, column=0, sticky="ew", padx=5, pady=5)
      btn_save.grid(row=1, column=0, sticky="ew", padx=5)

      fr_buttons.grid(row=0, column=0, sticky="ns")
      txt_edit.grid(row=0, column=1, sticky="nsew")

  def open_file(wtf,txt_edit):
    """Open a file for editing."""
    '''filepath = askopenfilename(
        filetypes=[("Text Files", "*.txt"), ("All Files", "*.*")]
    )
    print(filepath)
    print(type(filepath))'''
    filepath = 'config.ini'
    if not filepath:
        return
    txt_edit.delete("1.0", tk.END)
    with open(filepath, "r") as input_file:
        text = input_file.read()
        txt_edit.insert(tk.END, text)
    window.title(f"Simple Text Editor - {filepath}")

  def save_file(wtf,txt_edit):
    """Save the current file as a new file."""
    '''filepath = asksaveasfilename(
        defaultextension="txt",
        filetypes=[("Text Files", "*.txt"), ("All Files", "*.*")],
    )'''
    filepath = 'config.ini'
    if not filepath:
        return
    with open(filepath, "w") as output_file:
        text = txt_edit.get("1.0", tk.END)
        output_file.write(text)
    window.title(f"Simple Text Editor - {filepath}")

def CreateConfig():
    config['Steam'] = {'WebAPIkey': '',
                        'SteamID': '',
                        'UseAuthToken': 'False'}
    config['MongoDBinfo'] = {'UseMongo': 'True',
                        'ClientAddress': '',
                        'ClientPort': '27017',
                        'DBName': ''}
    config['MySQLDBinfo'] = {'UseMySQL': 'False',
                        'ClientAddress': '',
                        'ClientPort': '',
                        'DBName': ''}
    config['AWSDBinfo'] = {'UseAWS': 'False',
                        'ClientAddress': '',
                        'ClientPort': '',
                        'DBName': ''}
    config['OracleDBinfo'] = {'UseOracle': 'False',
                        'ClientAddress': '',
                        'ClientPort': '',
                        'DBName': ''}
    config['PostgreDBinfo'] = {'UsePostgre': 'False',
                        'ClientAddress': '',
                        'ClientPort': '',
                        'DBName': ''}
    with open('config.ini', 'w') as configfile:
        config.write(configfile)

window = tk.Tk()
buttonconfigedit = tk.Button(text='Config Editor', command=lambda: configeditor())
buttoncreatconfig = tk.Button(text='Make Config', command=lambda: CreateConfig())
buttonabout = tk.Button(text='About', command=lambda: about())
buttonexit = tk.Button(text='Exit', command=lambda: exit(1))
buttonconfigedit.pack()
buttoncreatconfig.pack()
buttonabout.pack()
buttonexit.pack()
window.title('GUI Testing')
window.mainloop()


# coding: utf-8
import sqlite3
import networkx as nx
import cProfile

conn = sqlite3.connect('xqfriends_0504.db')
cur = conn.cursor()

def save_graph_nets(fans_level):
    # cur.execute('select from_id, to_id from Follows where from_id in (select id from People where fo_num > ?) and to_id in (select id from People where fo_num > ?)', (fans_level, fans_level))
    cur.execute(
        'select from_id, to_id from Follows where from_id in (select id from People where fo_num > ?)', (fans_level,))

    name = 'net' + str(int(fans_level / 1000)) + 'k'
    g = nx.DiGraph(name=name)

    for i in cur.fetchall():
        g.add_edge(*i)

    nx.write_pajek(g, name + '.net')

def ego_graph(user_name):
    cur.execute(
        'select from_id, to_id from Follows where from_id in (select to_id from Follows where from_id in (select id from People where name = ?))', (user_name,))
    g = nx.DiGraph(name='ego_graph')

    for i in cur.fetchall():
        g.add_edge(*i)

    in_degree = g.in_degree()
    sorted_in_degree = sorted(
        in_degree.items(), key=lambda item: item[1], reverse=True)

    print('\ntop 50 likes of ego_graph:\n')
    # for i in range(100):
    for i in range(len(sorted_in_degree)):
        id, likes_num = sorted_in_degree[i]
        cur.execute('select name, fo_num from People where id = ?', (id,))
        name, fo_num = cur.fetchone()
        print(i + 1, name, fo_num, likes_num)

def likes_top_50(fans_level):
    name = 'net' + str(int(fans_level / 1000)) + 'k'
    g = nx.read_pajek(name + '.net')

    print(nx.info(g))

    in_degree = g.in_degree()
    sorted_in_degree = sorted(
        in_degree.items(), key=lambda item: item[1], reverse=True)

    print('\ntop 50', 'likes of', name, 'graph:\n')
    for i in range(200):
        id, likes_num = sorted_in_degree[i]
        cur.execute('select name, fo_num from People where id = ?', (id,))
        name, fo_num = cur.fetchone()
        print(i + 1, name, fo_num, likes_num)

    # with open(name + 'like_top50.txt', 'a', encoding='utf-8') as f:
        # f.write(nx.info(g))
        # f.write('\ntop 50 in_degree of graph:\n')
        # for i in range(50):
        # id, likes_num = sorted_in_degree[i]
        # cur.execute('select name, fo_num from People where id = ?', (id,))
        # name, fo_num = cur.fetchone()
        # f.write(str(i+1) + name + str(fo_num) + str(likes_num))

if __name__ == '__main__':
    print('---------starting----------')
    net_list = [100000, 50000, 10000, 5000]

    # for i in net_list:
    #     save_graph_nets(i)
    #     likes_top_50(i)
    # save_graph_nets(1000)
    cProfile.run('likes_top_50(50000)')
    # ego_graph('不明真相的群众')
    print('---------ending---------')


from collections import Counter

mod = 1000000007

def get_total(array, index):
    total = 0
    while index > 0:
        total += array[index]
        index -= index & -index
    return total

def update(array, length, index, value):
    while index < length:
        array[index] += value
        index += index & -index

n = int(input())
a = list(map(int, input().strip().split()))
b = list(map(int, input().strip().split()))
facts = [1] * (n + 1)
x = 1
for i in range(2, n + 1):
    x = x * i % mod
    facts[i] = x
freq = Counter(a)
size = max(*a, *b)
tree = [0] * (size + 1)
comb = facts[n]
ans = 0
for x in freq.keys():
    comb = comb * pow(facts[freq[x]], mod - 2, mod) % mod
    update(tree, size, x, freq[x])
for i in range(n):
    comb = comb * pow(n - i, mod - 2, mod) % mod
    ans = (ans + comb * get_total(tree, b[i] - 1)) % mod
    comb = comb * freq[b[i]] % mod
    freq[b[i]] -= 1
    if freq[b[i]] < 0:
        break
    update(tree, size, b[i], -1)
print(ans)

hackerearth/Data Structures/Advanced Data Structures/Fenwick (Binary Indexed) Trees/Count the permutations/solution.py


# -*- coding: utf-8 -*-

import re
import stanfordnlp

from solvers.utils import AbstractSolver

def _iterate_subsets(elements):
    if not elements:
        yield []
        return
    for subset in _iterate_subsets(elements[1:]):
        element = elements[0]
        yield [] + subset
        yield [element] + subset

class Solver(AbstractSolver):
    def __init__(self, models_dir='data/stanfordnlp_resources/'):
        self._pipeline = stanfordnlp.Pipeline(lang='ru', models_dir=models_dir)

    @staticmethod
    def _convert_sentence(sentence):
        result_sent, positions = '', []
        prev_match_end = 0
        for match in re.finditer('\(\d+\)', sentence):
            result_sent += sentence[prev_match_end: match.start()].strip() + ' '
            positions.append(len(result_sent) - 1)
            prev_match_end = match.end()

        result_sent += sentence[prev_match_end:].strip()
        return result_sent, positions

    @staticmethod
    def _get_sentence(task):
        task_text = ''
        for sent in task['text'].split('.'):
            sent = sent.strip() + '. '
            if re.search('\(\d+\)', sent):
                task_text += sent
        print(task_text.strip())
        return task_text.strip()

    def _find_best_positions(self, sentence, positions):
        best_positions, best_score = ["1"], -100
        for subset in _iterate_subsets(positions):
            sent_with_punct = ''
            prev_position = 0
            for position in subset:
                sent_with_punct += sentence[prev_position: position] + ','
                prev_position = position
            sent_with_punct += sentence[prev_position:]

            doc = self._pipeline(sent_with_punct)
            score = doc.conll_file.sents[0][0][-1]

            if score > best_score:
                best_positions = subset
                best_score = score

        return [str(positions.index(position) + 1) for position in best_positions]

    def predict_from_model(self, task):
        sentence, positions = self._convert_sentence(self._get_sentence(task))

        assert task['question']['type'] == 'multiple_choice'
        assert len(task['question']['choices']) == len(positions)
        assert [int(choice['id']) == i + 1 for i, choice in enumerate(task['question']['choices'])]

        return self._find_best_positions(sentence, positions)

    @classmethod
    def load(cls, path):
        return cls()

    def save(self, path):
        pass


# -*- coding: utf-8 -*-
from tkinter import *
from tkinter import ttk
from tkinter import messagebox

root = Tk()
root.title("Hello World")

# Full Name

ttk.Label(root, text="full Name:").grid(row=0, column=0, padx=10, pady=10)
EntryFullName = ttk.Entry(root, width=25, font=('Arial', 16))
EntryFullName.grid(row=0, column=1, columnspan=2, pady=10)

#gender
ttk.Label(root, text="Gender:").grid(row=1, column=0)
SpanGender=StringVar()
ttk.Radiobutton(root,text="MALE",variable=SpanGender,value="Male").grid(row=1, column=1)
ttk.Radiobutton(root,text="FEMALE",variable=SpanGender,value="Female").grid(row=1, column=2)

#radio buttom

#Comment

ttk.Label(root,text="comments:").grid(row=2,column=0)
xtComments=Text(root,width=30,height=14,font=('Arial',16))
xtComments.grid(row=2,column=1,columnspan=2)

#buttom

#bottom

root.mainloop()


from __future__ import absolute_import
from __future__ import division
# from __future__ import google_type_annotations
from __future__ import print_function
from albert import fine_tuning_utils
from albert import modeling
from albert import optimization
from albert import tokenization
import tensorflow.compat.v1 as tf
from tensorflow.contrib import data as contrib_data
import json
import collections

class InputExample(object):
  """A single training/test example for crf based models."""

  def __init__(self, guid, text, token_labels=None):
    """Constructs a InputExample.

    Args:
      guid: Unique id for the example.
      text_a: string. The untokenized text of the first sequence.
      token_labels: (Optional) string. for each token in text.
    """
    self.guid = guid
    self.text = text
    self.token_labels=token_labels
    #if self.token_labels is None:
    #    self.token_labels = ["O"]* 20

class PaddingInputExample(object):
  """Fake example so the num input examples is a multiple of the batch size.

  When running eval/predict on the TPU, we need to pad the number of examples
  to be a multiple of the batch size, because the TPU requires a fixed batch
  size. The alternative is to drop the last batch, which is bad because it means
  the entire output data won't be generated.

  We use this class instead of `None` because treating `None` as padding
  battches could cause silent errors.
  """

class InputFeatures(object):
  """A single set of features of data."""

  def __init__(self,
               input_ids,
               input_mask,
               segment_ids,
               label_ids,
               guid=None,
               example_id=None,
               is_real_example=True):
    self.input_ids = input_ids
    self.input_mask = input_mask
    self.segment_ids = segment_ids
    self.label_ids = label_ids
    self.example_id = example_id
    self.guid = guid
    self.is_real_example = is_real_example

def load_labels(label_list_file):
    label_list=[]
    with open(label_list_file, "r", encoding="utf-8") as f:
        for line in f:
            if line and line.strip():
                label_list.append(line.strip())
    return label_list

def convert_single_example(ex_index, example, max_seq_length,
                           processor):
    """Converts a single `InputExample` into a single `InputFeatures`."""
    tokenizer=processor.tokenizer
    label_map=processor.label_map

    if isinstance(example, PaddingInputExample):
        return InputFeatures(
            input_ids=[0] * max_seq_length,
            input_mask=[0] * max_seq_length,
            segment_ids=[0] * max_seq_length,
            label_ids=[0] * max_seq_length,
            is_real_example=False)

    # The convention in ALBERT is:
    # (a) For sequence pairs:
    #  tokens:   [CLS] is this jack ##son ##ville ? [SEP] no it is not . [SEP]
    #  type_ids: 0     0  0    0    0     0       0 0     1  1  1  1   1 1
    # (b) For single sequences:
    #  tokens:   [CLS] the dog is hairy . [SEP]
    #  type_ids: 0     0   0   0  0     0 0
    #
    # Where "type_ids" are used to indicate whether this is the first
    # sequence or the second sequence. The embedding vectors for `type=0` and
    # `type=1` were learned during pre-training and are added to the
    # embedding vector (and position vector). This is not *strictly* necessary
    # since the [SEP] token unambiguously separates the sequences, but it makes
    # it easier for the model to learn the concept of sequences.
    #
    # For classification tasks, the first vector (corresponding to [CLS]) is
    # used as the "sentence vector". Note that this only makes sense because
    # the entire model is fine-tuned.

    #tokens = tokenizer.tokenize(example.text)
    tokens=[]
    segment_ids = []
    label_ids=[]

    '''
    a severe bug exits using the following snippets as the original text are labeled
    character by charater ...
    we need to modify it
    it=iter(example.token_labels)

    for token in tokens[1:]:
        segment_ids.append(0)
        if not token.startswith(piece_prefix): # a new token rather than pieces
            label_id=label_map[next(it)]
        label_ids.append(label_id)
    '''

    '''
    a severe error also occured as pieces like cm, etc. take 2 positions chars
    offset=0
    for token in tokenizer.basic_tokenizer.tokenize(example.text):
        if example.token_labels is None:
            label_str="O"
        else:
            label_str=example.token_labels[offset]

        for sub_token in  tokenizer.wordpiece_tokenizer.tokenize(token):
            tokens.append(sub_token)
            label_ids.append(label_map[label_str])
            segment_ids.append(0)

        offset+=len(token.replace(piece_prefix,""))
    '''

    '''
    tokstr="".join(map(lambda tok: tok.replace(piece_prefix, ""),tokens[1:]))
    print("-------", tokstr)
    print("_______", example.text)
    print("******", example.token_labels)
    print(len(tokstr),len(example.token_labels),len(example.text))
    '''

    text=example.text
    for offset, word in enumerate(text):
        if example.token_labels is None:
            label_str="O"
        else:
            label_str=example.token_labels[offset]

        label=label_map[label_str]
        if word not in tokenizer.vocab:
            word="[UNK]"

        tokens.append(word )
        segment_ids.append(0)
        label_ids.append(label)

    # Account for [CLS] and [SEP] with "- 2"
    if len(tokens) > max_seq_length - 2:
        tokens = tokens[0:(max_seq_length - 2)]
        segment_ids=segment_ids[0:(max_seq_length-2)]
        label_ids=label_ids[0:(max_seq_length-2)]

    # inser [CLS]
    tokens.insert(0,"[CLS]")
    segment_ids.insert(0,0)
    label_ids.insert(0,label_map["O"])
    #add [SEP]
    tokens.append("[SEP]")
    segment_ids.append(0)
    label_ids.append(label_map["O"])

    input_ids = tokenizer.convert_tokens_to_ids(tokens)

    # The mask has 1 for real tokens and 0 for padding tokens. Only real
    # tokens are attended to.
    input_mask = [1] * len(input_ids)

    #print(len(input_ids), len(input_mask), len(segment_ids), len(label_ids))
    # Zero-pad up to the sequence length.
    while len(input_ids) < max_seq_length:
        input_ids.append(0)
        input_mask.append(0)
        segment_ids.append(0)
        label_ids.append(label_map["O"])
    #print(len(input_ids), len(input_mask), len(segment_ids), len(label_ids))
    assert len(input_ids) == max_seq_length
    assert len(input_mask) == max_seq_length
    assert len(segment_ids) == max_seq_length
    assert len(label_ids) == max_seq_length

    if ex_index < 5:
        tf.logging.info("*** Example ***")
        tf.logging.info("guid: %s" % (example.guid))
        tf.logging.info("tokens: %s" % " ".join(
            [tokenization.printable_text(x) for x in tokens]))
        tf.logging.info("input_ids: %s" % " ".join([str(x) for x in input_ids]))
        tf.logging.info("input_mask: %s" % " ".join([str(x) for x in input_mask]))
        tf.logging.info("segment_ids: %s" % " ".join([str(x) for x in segment_ids]))
        if example.token_labels is not None:
            tf.logging.info("label_ids: %s \n   (ids = %s)" % (" ".join(example.token_labels),
            " ".join([str(label_id) for label_id in label_ids]) ) )

    feature = InputFeatures(
        input_ids=input_ids,
        input_mask=input_mask,
        segment_ids=segment_ids,
        label_ids=label_ids,
        guid=example.guid,
        example_id=ex_index,
        is_real_example=True)
    return feature

def data_based_input_fn_builder(features, seq_length, is_training, drop_remainder):
    """Creates an `input_fn` closure to be passed to TPUEstimator."""

    all_input_ids = []
    all_input_mask = []
    all_segment_ids = []
    all_label_ids = []

    for feature in features:
        all_input_ids.append(feature.input_ids)
        all_input_mask.append(feature.input_mask)
        all_segment_ids.append(feature.segment_ids)
        all_label_ids.append(feature.label_ids)

    def input_fn(params):
        """The actual input function."""
        batch_size = params["batch_size"]

        num_examples = len(features)

        # This is for demo purposes and does NOT scale to large data sets. We do
        # not use Dataset.from_generator() because that uses tf.py_func which is
        # not TPU compatible. The right way to load data is with TFRecordReader.
        d = tf.data.Dataset.from_tensor_slices({
            "input_ids":
                tf.constant(
                    all_input_ids, shape=[num_examples, seq_length],
                    dtype=tf.int32),
            "input_mask":
                tf.constant(
                    all_input_mask,
                    shape=[num_examples, seq_length],
                    dtype=tf.int32),
            "segment_ids":
                tf.constant(
                    all_segment_ids,
                    shape=[num_examples, seq_length],
                    dtype=tf.int32),
            "label_ids":
                tf.constant(all_label_ids, shape=[num_examples, seq_length], dtype=tf.int32),
        })

        if is_training:
            d = d.repeat()
            d = d.shuffle(buffer_size=100)

        d = d.batch(batch_size=batch_size, drop_remainder=drop_remainder)
        return d

    return input_fn

def file_based_convert_examples_to_features(
    examples, max_seq_length, seq_processor, output_file):
  """Convert a set of `InputExample`s to a TFRecord file."""

  writer = tf.python_io.TFRecordWriter(output_file)

  for (ex_index, example) in enumerate(examples):
    if ex_index % 10000 == 0:
      tf.logging.info("Writing example %d of %d" % (ex_index, len(examples)))
    #print("-----examples-------\n{}".format(example.token_labels))
    feature = convert_single_example(ex_index, example,
                                     max_seq_length, seq_processor)

    def create_int_feature(values):
      f = tf.train.Feature(int64_list=tf.train.Int64List(value=list(values)))
      return f

    def create_float_feature(values):
      f = tf.train.Feature(float_list=tf.train.FloatList(value=list(values)))
      return f

    features = collections.OrderedDict()
    features["input_ids"] = create_int_feature(feature.input_ids)
    features["input_mask"] = create_int_feature(feature.input_mask)
    features["segment_ids"] = create_int_feature(feature.segment_ids)
    features["label_ids"] =  create_int_feature(feature.label_ids)
    features["is_real_example"] = create_int_feature(
        [int(feature.is_real_example)])

    tf_example = tf.train.Example(features=tf.train.Features(feature=features))
    writer.write(tf_example.SerializeToString())
  writer.close()

def file_based_input_fn_builder(input_file, seq_length, is_training,
                                drop_remainder, bsz,
                                multiple=1):
  """Creates an `input_fn` closure to be passed to TPUEstimator."""
  labeltype = tf.int64

  name_to_features = {
      "input_ids": tf.FixedLenFeature([seq_length * multiple], tf.int64),
      "input_mask": tf.FixedLenFeature([seq_length * multiple], tf.int64),
      "segment_ids": tf.FixedLenFeature([seq_length * multiple], tf.int64),
      "label_ids": tf.FixedLenFeature([seq_length * multiple], labeltype),
      "is_real_example": tf.FixedLenFeature([], tf.int64),
  }

  def _decode_record(record, name_to_features):
    """Decodes a record to a TensorFlow example."""
    example = tf.parse_single_example(record, name_to_features)

    # tf.Example only supports tf.int64, but the TPU only supports tf.int32.
    # So cast all int64 to int32.
    for name in list(example.keys()):
      t = example[name]
      if t.dtype == tf.int64:
        t = tf.to_int32(t)
      example[name] = t

    return example

  def input_fn(params):
    """The actual input function."""
    batch_size = bsz

    # For training, we want a lot of parallel reading and shuffling.
    # For eval, we want no shuffling and parallel reading doesn't matter.
    d = tf.data.TFRecordDataset(input_file)
    if is_training:
      d = d.repeat()
      d = d.shuffle(buffer_size=100)

    d = d.apply(
        contrib_data.map_and_batch(
            lambda record: _decode_record(record, name_to_features),
            batch_size=batch_size,
            drop_remainder=drop_remainder))

    return d

  return input_fn


'''
NAME:
    PorcentajeAT-GC.py

VERSION:
    4

AUTOR:
    Diana Delgado Gutierrez

DESCRIPTION:
    Programa que calcula el porcentaje de AT y GC con nombre y ruta del archivo input de secuencia.

USAGE:
    python porcentajeAT-GC.py [-h] -i path/to/file [-o OUTPUT] [-r ROUND]

ARGUMENTS:
    -h, --help            show this help message and exit
    -i path/to/file, --input path/to/file
                            File with gene sequences
    -o OUTPUT, --output OUTPUT
                            Path for the output file
    -r ROUND, --round ROUND
                            number of digits to rouond

SOFTWARE REQUIREMENTS:
    python 3.10

INPUT:
    data/archivo.txt

OUTPUT:
    en pantalla: porcentaje de AT, GC
    results/archivo.txt
'''

import argparse

parser = argparse.ArgumentParser(
    description="Script que calcula el porcentaje de AT-GC en una secuencia.")

parser.add_argument("-i", "--input",
                    metavar="path/to/file",
                    help="File with gene sequences",
                    required=True)

parser.add_argument("-o", "--output",
                    help="Path for the output file",
                    required=False)

parser.add_argument("-r", "--round",
                    help="number of digits to rouond",
                    type=int,
                    required=False)

args = parser.parse_args()

# Definir cálculo de porcentajes

def get_AT_content(dna, decimales):
    '''
    Obtiene el porcentaje de AT en una secuencia.

    Parámetros:
        dna(string): Secuencia de adn.
        decimales(int): Número de decimales a redondear.

    Returns:
        Porcentaje de AT(string)
    '''
    length = len(dna)
    a_count = dna.upper().count('A')
    t_count = dna.upper().count('T')
    at_content = ((a_count + t_count) / length) * 100
    at_content = round(at_content, decimales)
    return str(at_content)

def get_GC_content(dna, decimales):
    '''
    Obtiene el porcentaje de GC en una secuencia.

    Parámetros:
        dna(string): Secuencia de adn.
        decimales(int): Número de decimales a redondear.

    Returns:
        Porcentaje de GC(string)
    '''
    length = len(dna)
    g_count = dna.count('G')
    c_count = dna.count('C')
    gc_content = ((c_count + g_count) / length) * 100
    gc_content = round(gc_content, decimales)
    return str(gc_content)

# Checar que la ruta sea viable.
try:
    secuencia = open(args.input, "r")
    dna = secuencia.read().upper()

    try:
        # Comprobar que la secuencia es una secuencia.
        if (dna.isdigit() == True):
            raise ValueError('No hay una secuencia de ADN')

        # Obtener los porcentajes
        porcentajeAT = (get_AT_content(dna, decimales=2))
        porcentajeGC = (get_GC_content(dna, decimales=2))

        # Si quiere que guarde los resultados
        if args.output:
            outputFile = open(args.output, "w")
            print(
                f"Porcentaje de AT: {porcentajeAT}%\n Porcentaje de CG: {porcentajeGC}%",
                file=outputFile)
            outputFile.close()

        print(f"Archivo de la secuencia: {args.input}")
        print(
            f"Porcentaje de AT: {porcentajeAT}%\n Porcentaje de CG: {porcentajeGC}%")

    finally:
        # Cerrar archivo
        secuencia.close()

except IOError as exception:
    print('No se pudo encontrar el archivo: ' + exception.strerror)


import sys

input = sys.stdin.readline
T = int(input())
for _ in range(T):
    N = int(input())
    board = []
    for _ in range(2):
        board.append(list(map(int, input().split())))
    dp = [[0] * N for _ in range(2)]
    for i in range(N):
        if i == 0:
            dp[0][i] = board[0][i]
            dp[1][i] = board[1][i]
        elif i == 1:
            dp[0][i] = board[0][i] + board[1][0]
            dp[1][i] = board[1][i] + board[0][0]
        else:
            dp[0][i] = max(dp[1][i - 1], dp[1][i - 2]) + board[0][i]
            dp[1][i] = max(dp[0][i - 1], dp[0][i - 2]) + board[1][i]
    print(max(dp[0][N - 1], dp[1][N - 1], dp[0][N - 2], dp[1][N - 2]))


import threading
from time import sleep
from rqse import EventClient, EventListener, message

class CountListener(EventListener):

   def __init__(self,key,group,max):
      super().__init__(key,group)
      self._count = 0
      self._max = max

   def process(self,id, event):
      self._count += 1
      print(f'Received message, count={self._count}')
      if self._count==self._max:
         self.stop()
      return True

   @property
   def count(self):
      return self._count

def test_simple_listen():
   key = 'test_simple_listen'
   client = EventClient(key)
   client.delete_stream()

   listener = CountListener(key,'mygroup',3)

   thread = threading.Thread(target=lambda : listener.listen())
   thread.start()

   sleep(1)

   client.append({'fruit':'apple'})
   client.append({'fruit':'orange'})
   client.append({'fruit':'banana'})

   max_wait = 10
   while listener.listening and max_wait>0:
      sleep(1)
      max_wait -= 1

   listener.stop()

   client.delete_stream()
   assert listener.count==3

def test_messages():
   key = 'test_messages'
   client = EventClient(key)
   client.delete_stream()

   listener = CountListener(key,'mygroup',3)

   thread = threading.Thread(target=lambda : listener.listen())
   thread.start()

   # guarantee the consumer groups have been created first so we don't lose messages
   max_wait = 3
   while not listener.established and max_wait>0:
      sleep(1)
      max_wait -= 1

   assert listener.established

   client.append(message({'name':'apple'},kind='food'))
   client.append(message({'name':'orange'},kind='food'))
   client.append(message({'name':'banana'},kind='food'))

   max_wait = 10
   while listener.listening and max_wait>0:
      sleep(1)
      max_wait -= 1

   listener.stop()

   client.delete_stream()
   assert listener.count==3


from datetime import datetime, timedelta

from pydantic import BaseModel

from pol.permission import Role, UserGroup

__all__ = ["PublicUser", "User"]

class PublicUser(BaseModel):
    id: int
    username: str
    nickname: str

class User(Role, BaseModel):
    id: int
    username: str
    nickname: str
    group_id: UserGroup
    registration_date: datetime
    sign: str
    avatar: str

    def allow_nsfw(self) -> bool:
        allow_date = self.registration_date + timedelta(days=60)
        return datetime.utcnow().astimezone() > allow_date

    def get_user_id(self) -> int:
        return self.id


# 1 - https://www.qwant.com/?client=brz-moz&t=videos&q=pygame&o=0%3AWxEmflz009U
# 2 - https://www.youtube.com/watch?v=W4cbtcyONag

import sys
import pygame

pygame.init()

# Creating colors
BLUE = (0, 0, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)

screen = pygame.display.set_mode((400, 400))
screen.fill(WHITE)

image = pygame.image.load("ball.png")
image = pygame.transform.rotozoom(image, 0, 0.2)

x = 0
y = 0

clock = pygame.time.Clock()

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()

    pressed = pygame.key.get_pressed()
    if pressed[pygame.K_LEFT]:
        x -= 1
    if pressed[pygame.K_RIGHT]:
        x += 1
    if pressed[pygame.K_UP]:
        y -= 1
    if pressed[pygame.K_DOWN]:
        y += 1

    """
    On repeint en blanc le fond afin d'effacer les traces laisser par le deplacement du ballon.
    """
    screen.fill(WHITE)
    screen.blit(image, (x, y))
    pygame.display.flip()
    clock.tick(60)

"""
pygame.display.update()
Les deux fonctions font la meme action elles mettent à jour les informations de l'écran en appliquant les
changements faits. Cependant pygame.display.update() a une particularité, à l'aide d'un tuple de 4 valeurs
(x, y. width, height) ou d'un objet rect: pygame.Rect(x, y, width, height) nous pouvons définir la zone que nous
souhaitons mettre à jour. Ainsi si nous utilisons la méthode sous cette forme pygame.display.update((0, 0, 150, 150))
nous mettons à jour qu'un carré de 150 pixels par 150 pixels qui se trouve aux coordonnées 0, 0.
pygame.display.flip() quand à lui ne prend aucun paramètre et permet de mettre à jour l'écran entier. Cependant
flip a été codé avec certaine optimisations qui permettent de mettre à jour l'écran plus rapidement.
"""

"""
pygame en oriente objet
"""


import sys
import random
import pygame
from pygame.locals import *
from Player import Player
from card_data import card_deck

DEFAULT_CARD_SIZE = (100,145)
PLAYER_IMAGE_POS = (100,180)
ENEMY_IMAGE_POS = (485,180)
PLAYER_NUMBER_POS = (50,330)
ENEMY_NUMBER_POS = (430,330)
RESULT_POS = (250,200)
WAR_POS = (300,200)
START_POSE = (0,420)
PLAYER_NAME = (100,110)
ENEMY_NAME = (485,110)
BATTLE_NUMBER_POS = (230,30)
IMAGE_SIZE = (700,500)
WAR_PHASE_POS = (150,430)

class WarCardGame:

    def __init__(self):
        self.screen = pygame.display.set_mode((700,500))
        self.screen.fill((0, 102, 0))
        pygame.display.set_caption("Card War Game")
        pygame_icon = pygame.image.load("cards/ace_of_spades.png")
        pygame.display.set_icon(pygame_icon)

    def run_game(self):
        pygame.init()
        global player, enemy, war_award, war_phase
        war_phase = False
        war_award = []
        player = Player()
        enemy = Player()
        self.start_screen()
        self.shuffle_cards()

        '''Game Loop'''
        is_result = False

        number_of_battles = 1
        clock = pygame.time.Clock()

        while True:
            for event in pygame.event.get():

                if event.type ==  pygame.QUIT:
                    sys.exit()

                if event.type == pygame.KEYDOWN:

                    if event.key == K_ESCAPE:
                        sys.exit()

                    elif event.key != K_SPACE :
                        continue

                    else:
                        if event.key == K_SPACE:
                            self.screen.fill((0, 102, 0))
                            self.draw_info(number_of_battles)
                            if not is_result:
                                number_of_battles+=1
                                result = self.draw_cards()
                                self.draw_result(result)
                                is_result = True
                            else:
                                self.draw_cards_backwards()
                                self.draw_number_of_cards()
                                is_result = False

                        if self.end_of_game(result):
                            break

            pygame.display.flip()
            clock.tick(30)

    def shuffle_cards(self):
        '''Shuffle cards at the beginning of the game'''
        full_deck = random.sample(card_deck.keys(),52)
        player.deck = full_deck[:26]
        enemy.deck = full_deck[26:]

    def change_decks(self,player_card,enemy_card,result):
        '''Adding cards to winner's deck'''
        global war_phase,war_award

        if war_phase:
            self.draw_cards_backwards()
            font = pygame.font.SysFont("comicsansms", 42)
            player_number_text = font.render(f"BLIND WAR PHASE",False,(255, 204, 102))
            self.screen.blit(player_number_text,WAR_PHASE_POS)

        if result == "war":
            if not war_award:
                self.war(player_card,enemy_card)
                war_phase = True

        elif result == "win" and war_phase == False:
            card = enemy.deck.pop(enemy_card)
            player.deck.append(card)
            if war_award:
                enemy.deck.extend(war_award)
                war_award.clear()

        elif result == "lose" and war_phase == False:
            card = player.deck.pop(player_card)
            enemy.deck.append(card)
            if war_award:
                enemy.deck.extend(war_award)
                war_award.clear()

        elif war_phase == True:
            self.war(player_card,enemy_card)
            war_phase = False

        player.number_of_cards = len(player.deck)
        enemy.number_of_cards = len(enemy.deck)

    def war(self,player_card,enemy_card):
            '''Adding cards to the war reward array'''
            card = enemy.deck.pop(enemy_card)
            war_award.append(card)
            card = player.deck.pop(player_card)
            war_award.append(card)

    def compare_cards(self,player_choice,enemy_choice):
        '''Compare value of each chosen card'''
        player_value = card_deck[player.deck[player_choice]]["value"]
        enemy_value = card_deck[enemy.deck[enemy_choice]]["value"]
        if player_value > enemy_value:
            return "win"
        elif player_value == enemy_value:
            return "war"
        else:
            return "lose"

    def end_of_game(self,result):
        '''Drawing the result of the game'''
        if player.number_of_cards == 0 or (result == "war" and player.number_of_cards < 2):
            self.screen.fill((0, 102, 0))
            game_result = pygame.image.load("cards\you_lost.png")
            game_result = pygame.transform.scale(game_result,IMAGE_SIZE)
            self.screen.blit(game_result,(0,0))
            return True
        elif enemy.number_of_cards == 0 or (result == "war" and enemy.number_of_cards < 2):
            self.screen.fill((0, 102, 0))
            game_result = pygame.image.load("cards\game_won.png")
            game_result = pygame.transform.scale(game_result,IMAGE_SIZE)
            self.screen.blit(game_result,(0,0))
        else:
            return False

    def start_screen(self):
        '''Drawing screen at the beginning'''
        font = pygame.font.SysFont("comicsansms", 42)
        player_number_text = font.render(f"To start press SPACEBAR",False,(0,0,0))
        self.screen.blit(player_number_text,START_POSE)

    def draw_cards(self):
        '''Get number of cards in each deck, pick a random card from the deck and draw the card on the surface. Getting result of the battle and modify decks'''

        player.number_of_cards = len(player.deck)
        player_choice = random.randint(0,player.number_of_cards-1)
        image_path = card_deck[player.deck[player_choice]]["image"]
        card = pygame.image.load(image_path)
        card = pygame.transform.scale(card,DEFAULT_CARD_SIZE)
        self.screen.blit(card,PLAYER_IMAGE_POS)

        enemy.number_of_cards = len(enemy.deck)
        enemy_choice = random.randint(0,enemy.number_of_cards-1)

        image_path = card_deck[enemy.deck[enemy_choice]]["image"]
        card = pygame.image.load(image_path)
        card = pygame.transform.scale(card,DEFAULT_CARD_SIZE)
        self.screen.blit(card,ENEMY_IMAGE_POS)

        result = self.compare_cards(player_choice,enemy_choice)
        self.change_decks(player_choice,enemy_choice,result)

        return result

    def draw_number_of_cards(self):
        '''Drawing number of cards which remain in each deck'''
        font = pygame.font.SysFont("comicsansms", 32)
        player_number_text = font.render(f"Cards left: {player.number_of_cards}",False,(0,0,0))
        self.screen.blit(player_number_text,PLAYER_NUMBER_POS)
        enemy_number_text = font.render(f"Cards left: {enemy.number_of_cards}",False,(0,0,0))
        self.screen.blit(enemy_number_text,ENEMY_NUMBER_POS)

    def draw_result(self,result):
        '''Drawing result of the battle'''
        font = pygame.font.SysFont("comicsansms", 32)
        if result == "win":
            result_text = font.render(f"YOU WON",False,(153, 255, 153))
            self.screen.blit(result_text,RESULT_POS)
        elif result == "war":
            result_text = font.render(f"WAR",False,(255, 204, 102))
            self.screen.blit(result_text,WAR_POS)
        else:
            result_text = font.render(f"YOU LOST",False,(255, 51, 0))
            self.screen.blit(result_text,RESULT_POS)

    def draw_info(self,number_of_battles):
        '''Drawing names and number of battles which were made'''

        font = pygame.font.SysFont("comicsansms", 32)
        text = font.render(f"Player",False,(0,0,0))
        self.screen.blit(text,PLAYER_NAME)
        text = font.render(f"Enemy",False,(0,0,0))
        self.screen.blit(text,ENEMY_NAME)
        text = font.render(f"Battle nr. {number_of_battles}",False,(0,0,0))
        self.screen.blit(text,BATTLE_NUMBER_POS)

    def draw_cards_backwards(self):
        '''Drawing back of the card before battle'''
        card = pygame.image.load("cards/card_back.png")
        card = pygame.transform.scale(card,DEFAULT_CARD_SIZE)
        self.screen.blit(card,ENEMY_IMAGE_POS)
        self.screen.blit(card,PLAYER_IMAGE_POS)

if __name__ == "__main__":
    game = WarCardGame()
    game.run_game()


import codecs
import hashlib
import logging
import re
import time
from datetime import datetime
from typing import List, Union

import requests

from .constants import (CLEVERBOT_API_URL, CLEVERBOT_COOKIE_URL, CLEVERBOT_URL,
                        DEBOUNCE_TIME, MAX_ATTEPTS, MAX_CONTEXT_LENGTH,
                        MAX_DEBOUNCE_ATTEMPS)

class Cleverbot:
    """
    Cleverbot api wrapper

    Attributes
    ----------
    cookies : dict
        Cookies to be used in the requests.
    context : list
        List of messages representing the context of the conversation.
    proxies :
        Proxy to be used or proxies to rotate through.
    debounce: bool
        Whether to try to debounce the requests or not. If set to False it will try to use proxies immediately upon failure.
    :param use_tor_fallback:
        If set to True, whenever a request fail will try to use a new tor session as a proxy. This will override the proxy options. Even when this is set to true it will still try to make a connection without using tor at first.
    Methods
    ----------
    send(message)
        Sends a message to Cleverbot and returns the response as a string.
    """

    def __init__(
        self,
        context: List[str] = [],
        proxies: Union[dict, List[dict], List[str]] = None,
        debounce: bool = True,
        use_tor_fallback: bool = False,
    ):
        """
        Cleverbot Constructor

        :param context List[str]:List of strings to be used as the initial chat messages with the bot.
        :param proxies dict: Must have keys "http" and "https" and values of the proxies address:port to be used on the requests library format. You can also pass a list of proxies to rotate through. If an element of the list is None, it means not to use any proxy.
        :param debounce bool: Whether to try to debounce the requests or not. If set to False it will try to use proxies immediately upon failure.
        :param use_tor_fallback: If set to True, whenever a request fail will try to use a new tor session as a proxy. This will override the proxy options. Even when this is set to true it will still try to make a connection without using tor at first.
        """
        self.cookies = None
        self.context = context
        self.proxies = proxies
        self.debounce = debounce
        self.use_tor = use_tor_fallback

        if not isinstance(self.use_tor, bool):
            raise ValueError("use_tor_fallback must be a boolean")

        if proxies is None:
            self.proxies = [None]
        elif isinstance(proxies, dict):
            self.proxies = [proxies]
        elif isinstance(proxies, list):
            self.proxies = []
            for proxy in proxies:
                if isinstance(proxy, dict):
                    self.proxies.append(proxy)
                elif isinstance(proxy, str):
                    self.proxies.append({"http": proxy, "https": proxy})
                elif proxy is None:
                    self.proxies.append(None)
                else:
                    raise ValueError(
                        "Invalid proxy format. Must be a dict or a list of dicts."
                    )
        else:
            raise ValueError(
                "Invalid proxy format. Must be a dict, a list of dicts or a list of strings."
            )

        self._proxy_index = 0
        self._debounce_attempts = 0
        self._proxy = self.proxies[0]
        self._attempts = 0
        self.session = None
        self._tor_context = None
        self._start_session()

    def _start_session(self, tor=False):
        """Starts a new session refreshing the cookies"""
        logging.debug("Starting new session")
        if tor:
            try:
                from torpy.http.requests import tor_requests_session
            except ModuleNotFoundError:
                raise ModuleNotFoundError("You have to install torpy to use the tor fallback. Run: pip3 install torpy[requests]")
            logging.info("Starting tor session")
            if self._tor_context:
                self._tor_context.__exit__()
            self._tor_context = tor_requests_session()
            self.session = self._tor_context.__enter__()
            logging.info("tor session created!")
        else:
            self.session = requests.Session()
            self.session.proxies = self._proxy

        date = datetime.now().strftime("%Y%m%d")
        response = self.session.get(CLEVERBOT_COOKIE_URL + date)
        if "Set-cookie" not in response.headers:
            if not tor and self.use_tor:
                return self._start_session(self.use_tor)
            raise requests.exceptions.HTTPError(f"Api returned '{response.status_code}' for request. Try to use a proxy or use_tor_fallback")
        self.cookies = {
            "XVIS": re.search(r"\w+(?=;)", response.headers["Set-cookie"]).group()
        }

    def send(self, message: str) -> str:
        """
        Sends a message to Cleverbot and returns the response as a string.

        :param message str: The message to send to Cleverbot.
        :rtype str: Message received from Cleverbot.
        """
        payload = f"stimulus={requests.utils.requote_uri(message)}&"
        _context = self.context[:]
        reverse_context = list(reversed(_context))

        # Clear context list to keep things short and fast
        self._clear_context()
        for i in range(len(_context)):
            payload += f"vText{i + 2}={requests.utils.requote_uri(reverse_context[i])}&"

        # Append message to the context for future messages
        self.context.append(message)

        payload += "cb_settings_scripting=no&islearning=1&icognoid=wsf&icognocheck="

        # Checksum
        payload += hashlib.md5(payload[7:33].encode()).hexdigest()

        response = self.session.post(
            CLEVERBOT_API_URL,
            cookies=self.cookies,
            data=payload,
        )

        # If the request is not succesful, refresh cookies, debounce, try a new proxy
        if response.status_code != 200:
            if self._attempts > len(self.proxies) + MAX_ATTEPTS:
                logging.error(
                    f"Cleverbot failed to respond after {self._attempts} attempts. Giving up."
                )
                self._attempts = 0
                # TODO: Raise exception? Return None? idk
                return ""

            self._start_session(self.use_tor)
            if self._debounce_attempts >= MAX_DEBOUNCE_ATTEMPS or not self.debounce:
                self._debounce_attempts = 0
                self._proxy_index += 1
                if self._proxy_index >= len(self.proxies):
                    self._proxy_index = 0
                logging.info(
                    f"Cleverbot failed to respond. Trying proxy {self.proxies[self._proxy_index]}"
                )
                self._proxy = self.proxies[self._proxy_index]

            elif self.debounce:
                self._debounce_attempts += 1
                logging.info(
                    f"Cleverbot failed to respond. Trying again in {DEBOUNCE_TIME * self._debounce_attempts} seconds."
                )
                time.sleep(DEBOUNCE_TIME * self._debounce_attempts)

            self.context.pop()
            self._attempts += 1
            return self.send(message)

        response = re.split(r"\r", response.content.decode("utf-8"))[0]
        self._attempts = 0

        # Append bot's response to the context
        self.context.append(response)
        return codecs.escape_decode(bytes(response, "utf-8"))[0].decode("utf-8")

    def _clear_context(self):
        """_clear_context."""
        if len(self.context) >= MAX_CONTEXT_LENGTH:
            self.context.pop(0)


from dps.config.xsection import XSectionConfig
from dps.utils.ROOT_utils import set_root_defaults
from dps.utils.latex import setup_matplotlib
from rootpy.io import File
from rootpy import asrootpy
from ROOT import TCanvas, kRed
# latex, font, etc
setup_matplotlib()

if __name__ == '__main__':
    set_root_defaults()

    measurement_config = XSectionConfig( 13 )
    # # caching of variables for shorter access
    files_for_pdfs = { 'PDFWeights_%d' % (index - 9) : File( measurement_config.unfolding_pdfweights[index] ) for index in range( 9, 109 ) }
    files_central = File( measurement_config.unfolding_powheg_pythia8)

    path_to_unfolding = 'abs_lepton_eta_combined'
    i=0
    canvas = TCanvas("CanvasRef", "CanvasTitle", 800,600)

    folder = files_central.Get(path_to_unfolding)
    h_truth = asrootpy( folder.truthVis.Clone() )
    h_measured = asrootpy( folder.measuredVis_without_fakes.Clone() )
    h_measured.Draw()

    for k,f in files_for_pdfs.iteritems():
        folder = f.Get(path_to_unfolding)

        # folder = inputfile.Get( '%s_%s' % ( variable, channel ) )
        h_truth = asrootpy( folder.truthVis.Clone() )
        h_measured = asrootpy( folder.measuredVis_without_fakes.Clone() )
        h_measured.SetMarkerSize( 0 )
        h_measured.Draw("same")

    folder = files_central.Get(path_to_unfolding)
    h_truth = asrootpy( folder.truthVis.Clone() )
    h_measured = asrootpy( folder.measuredVis_without_fakes.Clone() )
    h_measured.SetMarkerColor( kRed )
    h_measured.Draw("same")

    canvas.Update()
    canvas.SaveAs('PDFvsCentral.pdf')
    canvas.Close()


"""
VUnit testbench for the High Speed ADC AXIS Adapter
"""

from pathlib import Path

import vunit_util

WORKSPACE = Path(__file__).parent / "workspace"
RTL_ROOT = Path(__file__).parent / ".."

# Create source list
sources = [
    RTL_ROOT / "testbenches" / "hsadc_axis_wrapper_tb.sv",
    RTL_ROOT / "hsadc" / "*.sv",
    RTL_ROOT / "axis" / "*.sv"
]

# Create VUnit instance and add sources to library
vu, lib = vunit_util.init(WORKSPACE)
lib.add_source_files(sources)

# Create testbench
tb = lib.test_bench("hsadc_axis_wrapper_tb")

# Suppress vopt deprecation error
vu.add_compile_option('modelsim.vlog_flags', ['-suppress', '12110'])

# Run
vu.main()


'''
Created on 4 de dez. de 2020

@author: michel
'''

import csv
from datetime import datetime
import get_date

## Getting the Dates
get_date.get_dp_date()

with open('./input_data/included-datapoints-date.csv', newline='') as csvfile:
    with open('./output_data/energy-datapoints.csv',  mode='w') as csvfileout:
        writer = csv.writer(csvfileout, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
        reader = csv.DictReader(csvfile)
        # Headers
        line = []
        line.append('ID')
        line.append('URL')
        line.append('Collection')
        line.append('Title')
        line.append('Contents')
        line.append('DateTime')
        line.append('Timestamp')
        writer.writerow(line)
        for row in reader:
            line = []
            line.append(row['ID'])
            line.append(row['URL'])
            line.append(row['Collection'])
            line.append(row['Title'])
            line.append(row['Contents'])
            line.append(row['DateTime'])
            date = row['DateTime']
            dtime = '0000-00-00 00:00:00'
            timestamp = '0'
            collection = row['Collection']
            if collection == 'Commits':
                if date != '0000-00-00 00:00:00' and date != '0000-00-00 00:00':
                    dtime = datetime.strptime(date, '%Y-%m-%d %H:%M:%S')
                    #print('Commits', dtime)
                    timestamp = datetime.timestamp(dtime)
            elif collection in ['GitHubIssues', 'GitHubPRs', 'Repositories']:
                if date != 'NA':
                    dtime = datetime.strptime(date, '%b %d, %Y')
                    #print(collection, dtime)
                    timestamp = datetime.timestamp(dtime)
            elif collection in ['ROSAnswers','ROSDiscourse','StackOverflow']:
                date_parts = date.split()
                if collection == 'ROSAnswers':
                    date = str(date_parts[0])+' '+str(date_parts[1])
                else:
                    date = str(date_parts[0])+' '+str(date_parts[1])+':00'
                #print(collection,date)
                dtime = datetime.strptime(date, '%Y-%m-%d %H:%M:%S')
                timestamp = datetime.timestamp(dtime)
            line.append(timestamp)
            print(timestamp)
            writer.writerow(line)


import torch
import numpy as np

'''
Train the model on the given train set for one epoch
Args
model:       the model we want to train
train_loader:a dataloader object for the train set
optimizer:   the optimizer to use
loss_fn:     the loss function to use
device:      the device to use (CPU or cuda)
print_every: a boolean telling when to print infos
status:      a boolean indicating debug mode
Return
np.mean(np.array(losses)):  the average loss
accuracy:                   the average accuracy
'''
def train(model, train_loader, optimizer, loss_fn, device, print_every=10, status = False):
    model.train()
    losses = []
    n_correct = 0
    n_sample = 0
    n_sample_0 = 0
    n_sample_1 = 0
    iteration = 0
    print("length of dataset :",len(train_loader.dataset))
    for iter, (images, labels) in enumerate(train_loader):
        images = images.to(device)
        labels = labels.to(device)
        output = model(images)
        optimizer.zero_grad()
        loss = loss_fn(output, labels)
        loss.backward()
        optimizer.step()

        losses.append(loss.item())
        n_correct += torch.sum(output.argmax(1) == labels).item()

        # DEBUG
        if status is True:
            n_sample_0 += torch.sum(output.argmax(1) == 0).item()
            n_sample_1 += torch.sum(output.argmax(1) == 1).item()
            n_sample = n_sample_0+n_sample_1
            if(n_sample>0):
                accuracy = 100.0 * n_correct / n_sample
            else:
                accuracy = np.inf

            print('Training iteration {}: loss {:.4f}, accuracy {:.4f}'.format(iteration, loss.item(), accuracy))
            print('# 0 output: {}, # 1 output: {}'.format(n_sample_0,n_sample_1))

        iteration += 1

    accuracy = 100.0 * n_correct / len(train_loader.dataset)

    return np.mean(np.array(losses)), accuracy


##levou algumas horas e um stackoverflow para fazer esse kkkk

def __mdc_(x,y):
    while(y):
        x,y=y,x%y
    return x

def mdc(nums):

    if len(nums) == 2:
        return __mdc_(nums[0], nums[1])
    else:
        mdc_val = __mdc_(nums[0], nums[1])
        nums[0] = mdc_val
        del nums[1]
        return mdc(nums)

mdc([30, 54, 72])


'''
    CountSlaves.py - An example of how to find the number of Slaves which have worked on a job
'''

from Deadline.Plugins import *
from Deadline.Scripting import *

from sets import Set

def __main__():
    '''
        Try both methods for counting Slaves on a particular job
    '''
    job_id = "5851875be9faf18185fa9334"
    slave_count = reports_way(job_id)
    print("Number of slaves: {}".format(slave_count))
    slave_count = tasks_way(job_id)
    print("Number of slaves: {}".format(slave_count))

def tasks_way(string_job_id):
    '''
    	Return the number of Slaves which worked on this job by using the task objects.
        This will not count Slaves which tried to render a task if it was completed by
        a different machine at a later date.
    '''
    job = RepositoryUtils.GetJob(string_job_id, True)
    tasks = RepositoryUtils.GetJobTasks(job, True)
    tasks = list(tasks.TaskCollectionAllTasks)

    print("Found {} tasks.".format(len(tasks)))

    slaves = Set()
    for task in tasks:
        slaves.add(task.TaskSlaveName)

    return len(slaves)

def reports_way(string_job_id):
    '''
    	Return the number of Slaves which worked on this job. Note that this
    	will include *all* Slaves, including those which may have thrown errors
        or for tasks that have been re-tried since.
    '''
    report_collection = RepositoryUtils.GetJobReports(string_job_id)
    reports = list(report_collection.GetAllReports())

    print("Found {} reports.".format(len(reports)))

    slaves = Set()
    # This could be done with a Python one-liner. I'm just a noob :D
    for report in reports:
        slaves.add(report.ReportSlaveName)

    return len(slaves)


"""
Advent of Code 2020 :: Day 17: Conway Cubes
"""
import sys
from collections import defaultdict
from itertools import product
import pyperclip

def add_v(left, right):
    """Add two vectors (tuples) together."""
    return tuple(a + b for a, b in zip(left, right))

def neighborhood(posn):
    """Return all the neighbors of the given position."""
    offsets = [tuple(p) for p in product([-1, 0, 1], repeat=len(posn))]
    for off in offsets:
        posn0 = add_v(posn, off)
        if posn0 == posn:
            continue
        yield posn0

def tick(live_cells):
    """Return the active cells after the given tick."""
    # Compute number of living neighbor cells for all neighbors
    # that will have a living neighbor.
    live_neighbors = defaultdict(int)
    for posn in live_cells:
        for neighbor in neighborhood(posn):
            live_neighbors[neighbor] += 1

    next_live_cells = set()
    for cell in live_neighbors:
        # If a cube is active and exactly 2 or 3 of its neighbors are also
        # active, the cube remains active. Otherwise, the cube becomes
        # inactive.
        living_neighbors = live_neighbors[cell]
        cell_is_alive = (cell in live_cells)
        if cell_is_alive and (living_neighbors == 2 or living_neighbors == 3):
            next_live_cells.add(cell)
        # If a cube is inactive but exactly 3 of its neighbors are active, the
        # cube becomes active. Otherwise, the cube remains inactive.
        if not cell_is_alive and living_neighbors == 3:
            next_live_cells.add(cell)

    return next_live_cells

def main():
    """Main program."""
    live_cells3 = set()
    live_cells4 = set()
    for y, line in enumerate(sys.stdin):
        for x, char in enumerate(line.strip()):
            if char == '#':
                live_cells3.add((x, -y, 0))
                live_cells4.add((x, -y, 0, 0))

    for _ in range(6):
        live_cells3 = tick(live_cells3)
        live_cells4 = tick(live_cells4)

    soln1 = len(live_cells3)
    print(f"The solution to part 1 is {soln1}")
    # assert soln1 == 362

    soln2 = len(live_cells4)
    print(f"The solution to part 2 is {soln2}")
    # assert soln2 == 362
    pyperclip.copy(soln2)

if __name__ == '__main__':
    main()


#Not activate until the system is integrated to RasPi
#import RPi.GPIO as GPIO

class SonicSensor():
    '''
    This class consist relevant function for acquiring distance between any obstacle and the car.
    '''
    #Initializer
    def __init__(self):
        #--------------------------------------------------------------------------------------------------
        #Set ultrasonic sensor configuraiton.These will be unactive until the system is integrated to RasPi
        #--------------------------------------------------------------------------------------------------
        #Set GPIO Mode
        #GPIO.setmode(GPIO.BCM)
        #Set GPIO Pins
        #self.GPIO_TRIGGER = 18
        #self.GPIO_ECHO = 24
        i=0

    def measureDistance(self):
        #==========================================================================================================
        #Measures distance from ultrasoin sensor using ultrasonic sensor class. Return the distance as double value
        #==========================================================================================================
        # set Trigger to HIGH
        GPIO.output(self.GPIO_TRIGGER, True)

        # set Trigger after 0.01ms to LOW
        time.sleep(0.00001)
        GPIO.output(self.GPIO_TRIGGER, False)

        StartTime = time.time()
        StopTime = time.time()

        #Save StartTime
        while GPIO.input(self.GPIO_ECHO) == 0:
            startTime = time.time()

        #Save time of arrival
        while GPIO.input(self.GPIO_ECHO) == 1:
            stopTime = time.time()

        #Time difference between start and arrival
        timeElapsed = stopTime - startTime
        #Multiply with the sonic speed (34300 cm/s) and divide by 2, because there and back
        measuredDistance = (timeElapsed * 34300) / 2

        return measuredDistance


import random as r

class Kik:
    """Klasa kółko i krzyżyk"""

    def __init__(self, player1 = "", player2 = ""):
        self.player1 = self.playerName()
        self.player2 = self.playerName()
        self.plansza = self.initPlansza()
        self.znak1 = 'x'
        self.znak2 = 'o'

    def __str__(self):
        return """Klasa kółko i krzyżyk"""

    def initPlansza(self):
        l = [[[],[],[]],[[],[],[]],[[],[],[]]]
        return l

    def playerName(self):
        name = ""
        return name

    def pokaz(self):
        for i in range(0, 3):
            print(self.plansza[i])
        print("")

    def isEmpty(self):
        k = True
        for i in range(0,3):
            for j in range(0,3):
                if self.plansza[i][j] != []:
                    k = False
                    break
        return k

    def czyWygrana(self):
        p = self.isEmpty()
        if p == True: return False
        for i in self.plansza:
            if i[0] != [] and i[0] == i[1] == i[2]:
                return True
        for i in range(0, 3):
            if self.plansza[0][i] != [] and self.plansza[0][i] == self.plansza[1][i] == self.plansza[2][i]:
                return True
        if self.plansza[1][1] != []:
            if self.plansza[0][0] == self.plansza[1][1] == self.plansza[2][2]:
                return True
            if self.plansza[2][0] == self.plansza[1][1] == self.plansza[0][2]:
                return True
        return False

    def znak(self, z):
        x = self.x()
        y = self.y()
        if self.plansza[x][y] != []: return False
        self.plansza[x][y] = z
        return True

    def x(self):
        x = r.randint(0, 2)
        return x

    def y(self):
        y = r.randint(0, 2)
        return y

    def gra(self):
        p = self.czyWygrana()
        while p == False:
            while True:
                if self.znak(self.znak1): break
            p = self.czyWygrana()
            self.pokaz()
            while True:
                if self.znak(self.znak2): break
            p = self.czyWygrana()
            self.pokaz()