from subprocess import call
from tkinter import filedialog
import subprocess
import requests
import os
import platform

class Application(object):

    app = None
    viewer = None
    smbUser = ('user', 'password')

    serverUrlWidget = None
    versionsWidget = None
    installPathWidget = None
    runWidget = None
    networkStatusWidget = None
    letterListWidget = None
    bootModeWidget = None
    archWidget = None

    winTarget = ''
    archTarget = ''
    bootMode = ''

    jsonConfig = 'netinstall.json'

    availablePaths = {}

    def __init__(self, smbUser, winTarget, createViewHandle, args):

        Application.app = self

        dScaling = 0
        isDBoot = False

        for i in args:

            if "dboot=" in i:
                isDBoot = i.split("=")[1] == "1"
                continue

            if "dscaling=" in i:
                dScaling = float(i.split("=")[1]);
                continue

        self.bootMode = self.getBootType(isDBoot)

        arch = platform.architecture()[0]
        if arch == '64bit':
            self.archTarget = 'x64'
        elif arch == '32bit':
            self.archTarget = 'x86'
        else:
            self.archTarget = 'Desconhecida'

        self.smbUser = smbUser
        self.winTarget = winTarget
        self.viewer = createViewHandle(dScaling)

    def init(self):

        self.serverUrlWidget = self.viewer.getWidgetById('serverUrl')
        self.versionsWidget = self.viewer.getWidgetById('version-list')
        self.installPathWidget = self.viewer.getWidgetById('install-path')
        self.runWidget = self.viewer.getWidgetById('run')
        self.networkStatusWidget = self.viewer.getWidgetById('network-status')
        self.letterListWidget = self.viewer.getWidgetById('letter-list')
        self.bootModeWidget = self.viewer.getWidgetById('boot-mode')
        self.archWidget = self.viewer.getWidgetById('arch')

        self.runWidget['state'] = 'disabled'
        self.viewer.addCLickListener('run', Application.onClick)
        self.viewer.addCLickListener('load-driver', Application.onClick)
        self.viewer.addCLickListener('run-diskpart', Application.onClick)
        self.viewer.addCLickListener('run-cmd', Application.onClick)

        self.versionsWidget.bind('<<ComboboxSelected>>', Application.onSelectVerion);
        self.viewer.addCLickListener('refresh', Application.onClick)

        letters = []
        for l in range(ord('A'), ord('Z') + 1):
            l = chr(l)+':'
            if not self.letterIsUsed(l):
                letters.append(l)

        self.letterListWidget['values'] = letters
        self.letterListWidget.set(self.letterListWidget['values'][0])

        self.bootModeWidget['text'] = self.bootMode
        self.archWidget['text'] = self.archTarget

    def run(self):
        self.refresh()
        self.viewer.loop()

    def onDetectNetWork(self):
        self.networkStatusWidget['text'] = 'Conectado'
        print('* Conexão detectada!')

    def refresh(self):

        self.availablePaths = {}
        self.versionsWidget['values'] = ()
        serverUri = self.serverUrlWidget.get()

        print('* Verificando ping com "'+serverUri+'"...')
        if Application.runProg(['ping', serverUri, '-n', '1' , '-w', '250'], False) != 0 :
            print('* Sem conxeão!')
            return

        print('\n* Baixando arquivo json em "http://'+serverUri+'/'+ self.jsonConfig +'"...')

        response = requests.get('http://' + serverUri + '/' + self.jsonConfig)
        if response.status_code != 200:
            print('* Erro ao baixar o arquivo "'+self.jsonConfig+'".')
            print('* Codigo http: ' + str(response.status_code) + '.')
            return

        cfg = response.json();
        if self.winTarget not in cfg:
            print('* Erro ao buscar a versão alvo para o windows "' + self.winTarget + '".')
            return

        self.onDetectNetWork()
        print('* Versões disponíveis:')

        listValues = ()
        for i in cfg[self.winTarget]:

            item = self.winTarget+'-'+i
            i = cfg[self.winTarget][i]

            if self.archTarget not in i:
                continue

            listValues = listValues + (item,)

            self.availablePaths[item] = {
                'path': i[self.archTarget]['path'],
                'exec': i[self.archTarget]['exec']
            }

            print('\t- ' + item)

        if len(listValues) > 1 :
            self.versionsWidget['values'] = listValues
            self.versionsWidget.set(listValues[0])
            Application.onSelectVerion(None)
        else:
            print('\t - Nenhuma versão disponível')

    def onRunBtnClick(self):

        letter = self.letterListWidget.get();
        serverUri = self.serverUrlWidget.get();
        path = self.installPathWidget.get();
        item = Application.app.versionsWidget.get()
        exe = Application.app.availablePaths[item]['exec']

        if self.letterIsUsed(letter):
            if not os.path.isfile(letter + '\\'+ exe):
                print('* A letra de unidade "' + letter + '" já está em uso. Tente uma outra.')
        else:
            if not self.mountShared(letter, serverUri, path, self.smbUser):
                return

        Application.runProg([letter + '\\' + exe], True)

    def mountShared(self, letter, serverUri, path, user):

        url = '\\\\'+serverUri+'\\'+path

        print('* Tentando montar "'+url+'" em '+letter+'...')
        code = Application.runProg(['net', 'use', letter, url, '/u:'+user[0], user[1]], False)
        if code != 0:
            print('* Erro ao tentar montar unidade de rede.')
            print('* Codigo de erro: ' + str(code) + '.')
            return False

        print('* Unidade montada com sucesso!')
        return True

    def letterIsUsed(self, letter):
        return os.path.isdir(letter)

    def onLoadDriverBtnClick(self):

        driverFile = filedialog.askopenfilename(title = "Selecione o arquivo de driver...", filetypes = (("Driver .inf","*.inf"), ("all files","*.*")))

        if not driverFile:
            return

        print('* Carregando arquivo de driver "'+driverFile+'"...')
        code = Application.runProg(['drvload', driverFile], False)

        if code != 0:
            print('* Erro ao carregar driver com código '+ str(code) +'.')
        else:
            print("* Driver carregado com sucesso!")
            self.refresh()

    @staticmethod
    def onClick(id, viewer, event):

        if id == 'refresh':
            Application.app.refresh()

        if id == 'run':
            Application.app.onRunBtnClick()

        if id == 'load-driver':
            Application.app.onLoadDriverBtnClick()

        if id == 'run-diskpart':
            Application.runProg(['start.bat', 'diskpart'], True)

        if id == 'run-cmd':
            Application.runProg(['start.bat', 'cmd'], True)

    @staticmethod
    def onSelectVerion(event):

        item = Application.app.versionsWidget.get()
        path = Application.app.availablePaths[item]['path']

        Application.app.installPathWidget['state'] = 'normal'
        Application.app.installPathWidget.delete(0, 'end')
        Application.app.installPathWidget.insert(0, path)
        Application.app.installPathWidget['state'] = 'readonly'

        Application.app.runWidget['state'] = 'normal'

    @staticmethod
    def runProg(entry, independent):
        if independent:
            return subprocess.Popen(entry)
        else:
            return call(entry)

    @staticmethod
    def getBootType(isDebug):

        if isDebug :
            return "DEBUG"

        output = subprocess.check_output(['boot-mode.bat'])
        if output == None :
            return 'Desconhecido'

        bootTypeCode = str(output).split(' ')[-1].split('\\r')[0];

        if bootTypeCode == '0x1':
            return 'BIOS'
        elif bootTypeCode == '0x2':
            return 'UEFI'
        else:
            return 'Desconhecido'


import requests, urllib, re, os, json, pyrebase
from bs4 import BeautifulSoup as BS
import txt
# print(txt.user)
session = requests.session()
pageURL = 'https://zenpencils.com/'
page = session.post(pageURL)
# print(page.text)
# Home Page details
# Finding total number of pages
homepage = BS(page.text,"html.parser").find('form',{'class':'comic-list-dropdown-form'})
# print(homepage)
pages = homepage.find_all('option',{'class':'level-0'})
print("\n  Finding Links .... \n ")

for i in pages:
    print(json.dumps({'key':i.get_text(),'value':i['value']}))
    print(" Writing Links into FDB ....  ")
    txt.db.child("zenpencils").push({'key':i.get_text(),'value':i['value']}, txt.user['idToken'])
# print(json.dumps(data))


from .base_dataset import Base, BaseDataset, CenterCrop, RandCrop3D, RandomRotion, RandomIntensityChange, RandomFlip, NumpyType, Pad
from .base_dataset import make_image_label, normalization, label_processing

import torch
import glob
import numpy as np
import nibabel as nib
from torchvision.transforms import Compose

from dataset.base_dataset import RandomRotion

class BraTS20(BaseDataset):
    def __init__(self, cfg):
        BaseDataset.__init__(self, cfg)
        if self.cfg.isTrain:
            self.paths = glob.glob(self.cfg.train_path+'/*')
            self.transforms = Compose([
                # search
                # RandCrop3D((128, 128, 48)),
                # RandomRotion(10),
                # RandomIntensityChange((0.1, 0.1)),
                # RandomFlip(0),
                # NumpyType((np.float32, np.float64)),

                # train
                RandCrop3D((192, 192, 48)), # 64, 64, 64
                RandomRotion(10),
                RandomIntensityChange((0.1, 0.1)),
                RandomFlip(0),
                NumpyType((np.float32, np.float64)),
            ])
        else:
            self.paths = glob.glob(self.cfg.val_path+'/*')
            self.transforms = Compose([
                Pad((0, 0, 0, 5, 0)),
                # CenterCrop((192, 192, 48)),
                NumpyType((np.float32, np.int64)),
            ])

    def __len__(self):
        return len(self.paths)

    def __getitem__(self, idx):
        path = self.paths[idx]
        name = path.split('/')[-1]
        images, labels, affine = make_image_label(path)

        flair, t1, t1ce, t2 = images
        flair = normalization(flair)
        t1 = normalization(t1)
        t1ce = normalization(t1ce)
        t2 = normalization(t2)

        images = []
        images.append(flair)
        images.append(t1)
        images.append(t1ce)
        images.append(t2)
        images = np.asarray(images)
        # print('norm, max, min', images[0, ...].max(), images[0, ...].min(), images.shape)
        images, labels = images[..., np.newaxis], labels[np.newaxis, ...]
        images = np.swapaxes(images, 0, -1)

        images, labels = self.transforms([images, labels])
        labels = label_processing(labels)

        images = np.ascontiguousarray(images.transpose(0, 4, 1, 2, 3)[0])
        labels = np.ascontiguousarray(labels[0])

        images = torch.from_numpy(images)
        labels = torch.from_numpy(labels)

        # print('torch, maxmin, ', images[0].max(), images[0].min(), images.shape)

        return {'img': images, 'label': labels, 'name': name, 'affine': affine}

    def collate(self, batch):
        return [torch.cat(v) for v in zip(*batch)]


import os
import torch

from fairseq.tasks import FairseqTask, register_task

from sightseq.data import CocoDetectionDataset
from sightseq.data.coco_utils import ConvertCocoPolysToMask
import sightseq.data.transforms as T

@register_task('object_detection')
class ObjectDetectionTask(FairseqTask):
    """
    Train a object detection model.

    Args:
        transforms:
    """

    @staticmethod
    def add_args(parser):
        """Add task-specific arguments to the parser."""
        # fmt: off
        parser.add_argument('data', metavar='FOLDER',
                            help='path to data directory')
        parser.add_argument('--num-classes', type=int, default=-1, metavar='N',
                            help='number of output classes of the model (including the background).'
                                 ' If box_predictor is specified, num_classes should be None')
        parser.add_argument('--max-positions', default=2048, type=int,
                            help='max input length')
        parser.add_argument('--aspect-ratio-group-factor', type=int, default=0, metavar='N',
                            help='data sampler with aspect ratio group')
        # fmt: on

    def __init__(
        self, args, num_classes, transforms=None,
        rpn_anchor_generator=None, rpn_head=None,
        box_roi_pool=None, box_predictor=None, box_head=None,
    ):
        super().__init__(args)
        self.num_classes = num_classes
        self.transforms = transforms
        self.rpn_anchor_generator = rpn_anchor_generator
        self.rpn_head = rpn_head
        self.box_roi_pool = box_roi_pool
        self.box_predictor = box_predictor
        self.box_head = box_head

    @classmethod
    def build_transforms(cls, args):
        transforms = [ConvertCocoPolysToMask()]
        transforms.append(T.ToTensor())

        return transforms

    @classmethod
    def setup_task(cls, args, **kwargs):
        """Setup the task (e.g., load dictionaries).

        Args:
            args (argparse.Namespace): parsed command-line arguments
        """
        # build transforms
        transforms = cls.build_transforms(args)
        return cls(
            args,
            num_classes=args.num_classes,
            transforms=transforms,
        )

    def load_dataset(self, split, **kwargs):
        """Load a given dataset split.

        Args:
            split (str): name of the split (e.g., train, valid, test)
        """
        # Read input images and targets
        image_root = os.path.join(self.args.data, '{}2017'.format(split))
        annotation_file = os.path.join(self.args.data, 'annotations', 'instances_{}2017.json'.format(split))

        t = self.transforms or []
        if split == 'train':
            t.append(T.RandomHorizontalFlip(0.5))
        transforms = T.Compose(t)

        self.datasets[split] = CocoDetectionDataset(image_root, annotation_file, transforms=transforms)

        # if split == 'train':
        #     self.dataset[split].remove_images_without_annotations()

    def build_generator(self, args):
        from sightseq.coco_generator import ObjectDetectionGenerator
        return ObjectDetectionGenerator()

    def valid_step(self, sample, model, criterion):
        model.train()
        with torch.no_grad():
            loss, sample_size, logging_output = criterion(model, sample)
        return loss, sample_size, logging_output

    def max_positions(self):
        """Return the max input length allowed by the task."""
        # The source should be less than *args.max_positions*
        return self.args.max_positions


# Program that asks the user to input any positive integer and outputs the successive values of the following calculation
# At each step calculate the next value by taking the current value and, if it is even, divide it by two, but if it is odd, multiply it by three and add one
# Have the program end if the current value is one
# Author: David Maguire

# Assign input to number
number = int(input("Please enter a positive integer: "))

# Print number
print(number)

# If number is not equal to one, apply correct calculation and assign to new number
while number !=1:
    if number % 2 == 0:
        newNumber = int(number / 2)
    else:
        newNumber = (number * 3) + 1

# Print new number
    print(newNumber)

# Assign number as value of new number so while loop restarts with check for equals one
    number = newNumber


#!/usr/bin/env python3
"""Custom killing of apps."""
import sys

import i3ipc
from i3_helpers import sh

CTRL_Q = ['Slack', 'discord']
CUSTOM = ['Chromium', 'Brave-browser']

def _get_windows(i3, which='all', get_ws=False):
    tree = i3.get_tree()
    focused_win = tree.find_focused()
    if which == 'focused':
        windows = [focused_win]
    elif which == 'all':
        windows = [win for ws in tree.workspaces() for win in ws.leaves()]
    if get_ws:
        return windows, focused_win.workspace().name
    else:
        return windows

def kill_custom(i3, which):
    """Kill apps differently according to their class."""
    windows, focused_ws = _get_windows(i3, which, get_ws=True)
    for win in windows:
        i3.command(f'[con_id={win.id}] focus')
        win_class = win.window_class
        if win_class in CUSTOM:
            sh(f'xdotool key --window {win.window} comma+k+v')
            # If the window was not killed using xdotool then do kill it with i3
            remaining_window_classes = [win.window_class for win in _get_windows(i3)]
            if win_class in remaining_window_classes:
                i3.command('kill')
        elif win_class in CTRL_Q:
            sh(f'xdotool key --window {win.window} ctrl+q')
        else:
            i3.command('kill')
    i3.command(f'workspace {focused_ws}')

if __name__ == '__main__':
    import argparse

    parser = argparse.ArgumentParser()
    parser.add_argument('--which', '-w', default='focused')
    pars_args = parser.parse_args()

    i3_conn = i3ipc.Connection()
    kill_custom(i3_conn, which=pars_args.which)
    sys.exit(0)


# Kivy libs import

# Python libs import

# Personal libs import

#Class of a task
class Code:

    # columns used in the csv, in the right order
    _dtb_columns = [
            "code_id",
            "code_code",
            "code_appdate",
            "code_clodate",
            "codetype_id",
            "project_id",
            "location_id",
            "center_id"
                   ]
    # name of the dtb table for this object
    _dtb_table = "codes"
    # Object(s) which must be included in this object
    _parent_objct = []


import sys
import json
from pathlib import Path
from bisect import bisect
import itertools
import collections

import lingpy
import segments
from pylexirumah import get_dataset

tokenizer = segments.tokenizer.Tokenizer()
model=lingpy.data.model.Model("asjp")
def to_asjp(segments):
    return lingpy.tokens2class(segments, model, cldf=False)
def convert_to_asjp(form):
    tokens = tokenizer(form, ipa=True).split()
    return to_asjp(tokens)
scorer = collections.defaultdict(lambda: -1)
scorer.update({(c, c): 0 for c in set(model.converter.values())})
def relative_edit_distance(x, y):
    a, b, s = lingpy.align.pairwise.pw_align(x, y, scale=1, scorer=scorer)
    return -s / len(a)

try:
    stats = json.load((Path(__file__).parent / "dataset_properties.json").open())
except (FileNotFoundError, json.decoder.JSONDecodeError):
    stats = {}

features = ["min_intersection", "average_intersection", "average_asjp_edit_distance", "mean_word_length", "mean_synonyms", "quantile_for_two_segments", "quantile_for_three_segments", "quantile_for_five_segments", "quantile_for_nine_segments", "n_lects", "mean_segments", "mean_asjp_segments", "mean_asjp_segments_product"]
features.sort()

def mean(x):
    return sum(x) / len(x)

if __name__ == "__main__":
    import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument("--force", action='store_true')
    parser.add_argument("dataset", nargs="+")
    args = parser.parse_args()
    for argument in args.dataset:
        if argument in stats and not args.force:
            continue
        datafile = Path(argument)
        print(datafile)
        basename = datafile.stem

        dataset = get_dataset(datafile)
        c_language = dataset["FormTable", "languageReference"].name
        c_concept = dataset["FormTable", "parameterReference"].name
        c_form = dataset["FormTable", "form"].name
        c_segments = dataset["FormTable", "segments"].name
        lects = list(set(row[c_language] for row in dataset["FormTable"].iterdicts()))

        concepts = []
        wordlengths = []
        synonyms = []
        raw_segments = {}
        for l, language in enumerate(lects):
            print(language)
            c = {}
            concepts.append(c)
            for row in dataset["FormTable"].iterdicts():
                if row[c_language] == language:
                    c.setdefault(row[c_concept], []).append(row[c_form])
                    raw_segments.setdefault(language, set()).update(row[c_segments])
                    wordlengths.append(len(row[c_segments]))
            synonyms.extend([len(f) for f in c.values()])
        wordlengths.sort()
        asjp_segments = {language: set(to_asjp(list(phonemes)))
                         for language, phonemes in raw_segments.items()}

        intersections = []
        relative_edit_distances = []
        for concepts_i, concepts_j in itertools.combinations(concepts, 2):
            intersection = set(concepts_i).intersection(concepts_j)
            intersections.append(len(intersection))
            relative_concept_edit_distances = []
            for concept in intersection:
                for i, j in itertools.product(concepts_i[concept],
                                            concepts_j[concept]):
                    i = convert_to_asjp(i)
                    j = convert_to_asjp(j)
                    relative_concept_edit_distances.append(relative_edit_distance(i, j))
            if intersection:
                relative_edit_distances.append(
                    sum(relative_concept_edit_distances)/
                    len(relative_concept_edit_distances))

        print(basename)
        stats[argument] = {
            "min_intersection": min(intersections),
            "average_intersection": 2 * mean(intersections),
            "average_asjp_edit_distance": mean(relative_edit_distances),
            "mean_word_length": mean(wordlengths),
            "mean_synonyms": mean(synonyms),
            "quantile_for_two_segments": bisect(wordlengths, 2.01) / len(wordlengths),
            "quantile_for_three_segments": bisect(wordlengths, 3.01) / len(wordlengths),
            # In LexiRumah, a morpheme has 5.25 segments in the mean, and 90% of all marked morphemes have 9 segments or fewer.
            "quantile_for_five_segments": bisect(wordlengths, 5.25) / len(wordlengths),
            "quantile_for_nine_segments": bisect(wordlengths, 9.01) / len(wordlengths),
            "n_lects": len(lects),
            "mean_segments": mean([len(x) for x in raw_segments.values()]),
            "mean_asjp_segments": mean([len(x) for x in asjp_segments.values()]),
            "mean_asjp_segments_product": mean([
                len(x) * len(y) for x, y in itertools.combinations(asjp_segments.values(), 2)]),
        }

    json.dump(stats, Path(Path(__file__).parent / "dataset_properties.json").open("w"), indent=2, sort_keys=True)


#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@author: thread.py
@software: vscode
@file: thread.py
@Time: 2021/11/05 18:06:50
@Desc: Cpython Interpreter has GIL,
       but pure python is not thread safe!!
'''

import threading

n = 0

def add():
    global n
    for _ in range(1000000):
        n = n + 1

def sub():
    global n
    for _ in range(1000000):
        n = n - 1

if __name__ == "__main__":
    t1 = threading.Thread(target=add)
    t2 = threading.Thread(target=sub)

    t1.start()
    t2.start()

    t1.join()
    t2.join()

    print("n的值为:", n)


import PySimpleGUI as Sg  # PySimpleGUI Call Reference: https://www.pysimplegui.org/en/latest/call%20reference/

# ----- Theme Variables -----

# Colour Generator: http://colormind.io/bootstrap/
colours = {"light": "#A6A4A6",
           "light_accent": "#ADA88D",
           "main": "#E46F1C",
           "dark_accent": "#A37B5B",
           "dark": "#31615B",
           "text field grey": "#4f4d4d"}

# --- frames ---
frame_header_font_large = ("Arial Bold", 18)
frame_header_font_small = ("Arial Bold", 16)
frame_font_colour = colours["dark"]

# --- text labels ---
text_font = ("Arial", 15)
text_font_emphasis = ("Arial Italic", 12)
text_box_size_small = (20, 2)
text_box_padding = (5,5)
text_box_background = colours["light"]
text_sub_header_colour = colours["dark"]
text_sub_header_font = ("Arial", 17)

# --- buttons ---
button_font = ("Arial", 13)
button_size = (20, 1)
button_padding = (10, 20)
button_colour = colours["main"]

# --- radio boxes ---
radio_font = ("Arial", 13)
radio_size_small = (25, 1)
radio_size_large = (35, 1)
radio_padding = (5,5)
radio_background_colour = colours["light"]

# --- checkboxes ---
checkbox_font = ("Arial", 13)
checkbox_size = (25,1)
checkbox_padding = (5,5)
checkbox_background_colour = colours["light"]

# --- input field ---
input_field_background_colour = colours["light_accent"]
input_filed_text_colour = colours["text field grey"]
input_field_font = ("Arial", 15)

# --- LAYOUT ELEMENTS -------------------------------------------------------------------------------------------------

def working_with_class_data():
    # ----- ZONE 2.1 (working with classes - left column: select select) -----
    courses = ["AVI1O0B", "AVI2O0A", "AVI3M0B", "AVI1O0A"]  # TODO: to be sourced from file system
    class_list_layout = [[Sg.Text(text="Choose Class...", text_color=text_sub_header_colour, font=text_sub_header_font,
                                  background_color=text_box_background)],
        *[[Sg.Radio(text=course, group_id="courses", size=radio_size_small,
                    key=f"-{course.upper()} KEY-",
                    font=radio_font, pad=radio_padding,
                    background_color=radio_background_colour), ] for course in courses]
    ]

    # ----- ZONE 2.2 (working with classes - middle column: report options) -----
    work_with_classes_layout = [
        [Sg.Text(text="Select Report Options...", text_color=text_sub_header_colour, font=text_sub_header_font,
                 background_color=text_box_background)],
        [Sg.Text(text="Sort Student Data:", font=text_font, background_color=text_box_background,
                 size=(25, 1), justification="left")],
        [Sg.Radio(text="Alpha by Last Name", group_id="sort_type", size=radio_size_large,
                  key="-ALPHA-",
                  font=radio_font, pad=radio_padding,
                  background_color=radio_background_colour)],
        [Sg.Radio(text="By Google ID", group_id="sort_type", size=radio_size_large,
                  key="-GOOGLE_ID-",
                  font=radio_font, pad=radio_padding,
                  background_color=radio_background_colour),
         ],  # end section 1
        [Sg.HorizontalSeparator()],
        [Sg.Text(text="Reporting Cycle:", font=text_font, background_color=text_box_background,
                 size=(25, 1), justification="left")],
        [Sg.Radio(text="Progress Report", group_id="reporting_cycle", size=radio_size_small,
                  key="-PROGRESS_REPORT-",
                  font=radio_font, pad=radio_padding,
                  background_color=radio_background_colour)],
        [Sg.Radio(text="Mid-Term", group_id="reporting_cycle", size=radio_size_small,
                  key="-MID_TERM_REPORT-",
                  font=radio_font, pad=radio_padding,
                  background_color=radio_background_colour)],
         [Sg.Radio(text="Final Term", group_id="reporting_cycle", size=radio_size_small,
                  key="-FINAL_TERM_REPORT-",
                  font=radio_font, pad=radio_padding,
                  background_color=radio_background_colour)],
        [Sg.HorizontalSeparator()],
        [Sg.Text(text="Filter Achievement Data by:", font=text_font, background_color=text_box_background,
                 size=(25, 1), justification="left")],
        [Sg.Radio(text="OLG", group_id="filter_type", size=radio_size_small,
                  key="-OLG_FILTER-",
                  font=radio_font, pad=radio_padding,
                  background_color=radio_background_colour)],
         [Sg.Radio(text="SC (Success Criteria)", group_id="filter_type", size=radio_size_small,
                  key="-SC_FILTER-",
                  font=radio_font, pad=radio_padding,
                  background_color=radio_background_colour)],
         [Sg.Radio(text="KTCA (Achievement Chart Categories)", group_id="filter_type", size=radio_size_small,
                  key="-KTCA_FILTER-",
                  font=radio_font, pad=radio_padding,
                  background_color=radio_background_colour)],
        [Sg.HorizontalSeparator()],
        [Sg.Text(text="Include Elements in Report:", font=text_font, background_color=text_box_background,
                 size=(25, 1), justification="left")],
        [Sg.Checkbox(text="Include Graph ", size=checkbox_size,
                     key="-INCLUDE_GRAPH-",
                     font=checkbox_font, pad=checkbox_padding,
                     background_color=checkbox_background_colour)]
    ]
    # TODO: add secondary column here for frequency of criteria in grade determination
    frequency_categories = ["Knowledge", "Thinking", "Communication", "Application"]
    achievement_explanation = "Achievement Frequency refers to the number of times that the student must demonstrate " \
                              "PROFICIENCY in a given category in order to fully demonstrate that they have mastered the " \
                              "criteria. The value in a given category should be proportionate to the number of " \
                              "opportunities that the students have to demonstrate their learning."
    frequency_layout = [
        [Sg.Text(text="Set Frequency Requirements...", text_color=text_sub_header_colour, font=text_sub_header_font,
                 background_color=text_box_background)],
        [Sg.Text(text=achievement_explanation, size=(55,6), font=text_font_emphasis, text_color="black",
         background_color=text_box_background)],
        *[[Sg.Input(key=f"-{cat} Frequency Key-",
                    default_text=1,
                    font=input_field_font, text_color=input_filed_text_colour,
                    justification="center", size=(5, 1),
                    background_color=input_field_background_colour, visible=True),
           Sg.Text(text=cat, font=text_font, background_color=text_box_background)] for cat in frequency_categories]
    ]
    # ---- ZONE 3.3 (working with classes - right column: actions to be taken

    # ----- ZONE 2.3 (working with classes - right column: user actions) -----
    user_actions_layout = [
        [Sg.Button(button_text="Sort Student Data",
                   key="-GOOGLE_ID-",
                   tooltip=" sort selected class MS Excel data by Google Id ",
                   size=button_size, font=button_font, pad=button_padding, button_color=button_colour)],
        [Sg.Button(button_text="Missing Work Summary",
                   key="-MISSING_WORK-",
                   tooltip="print missing work summaries for selected class",
                   size=button_size, font=button_font, pad=button_padding, button_color=button_colour)],
        [Sg.Button(button_text="Achievement Summary",
                   key="-ACHIEVEMENT_SUMMARIES-",
                   tooltip="create achievement summary based on selected class and parameters",
                   size=button_size, font=button_font, pad=button_padding, button_color=button_colour)],
        [Sg.Button(button_text="Achievement Graphs",
                   key="-ACHIEVEMENT_GRAPHS-",
                   tooltip="view achievement graphs",
                   size=button_size, font=button_font, pad=button_padding, button_color=button_colour)],
        [Sg.Button(button_text="FE Prompts",
                   key="-FE_PROMPTS-",
                   tooltip="create final evaluation documents for students in selected class",
                   size=button_size, font=button_font, pad=button_padding, button_color=button_colour)]
    ]

    # ----- ZONE 2 COLUMNS -----
    options_background_colour=colours["light"]

    options_layout=[[Sg.Column(layout=class_list_layout, size=(250, 550), pad=(5,5),
                               background_color=options_background_colour,
                               scrollable=False, visible=True, vertical_alignment="top"),
                    Sg.VerticalSeparator(),
                    Sg.Column(layout=work_with_classes_layout, size=(400, 550), pad=(5,5),
                              background_color=options_background_colour,
                              scrollable=False, visible=True, vertical_alignment="top"),
                    Sg.Column(layout=frequency_layout, size=(400, 550), pad=(5,5),
                              background_color=options_background_colour,
                              scrollable=False, visible=True, vertical_alignment="top"),
                    Sg.VerticalSeparator(),
                    Sg.Column(layout=user_actions_layout, size=(250, 550), pad=(5,5),
                              background_color=options_background_colour,
                              scrollable=False, visible=True, vertical_alignment="top")]]

    return options_layout


import torch
import torch.nn as nn
from mover.utils.camera import (
    get_pitch_roll_euler_rotation_matrix,
)

### ground plane nformation
def set_ground_plane(self, ground_plane):
    self.ground_plane.data.copy_(ground_plane)

# def get_ground_plane(self):
#     verts = self.get_verts_object_parallel_ground()
#     return torch.max(verts[:, :, 1])

def get_ground_plane_mesh(self):
    gp_y = self.ground_plane
    vertices = torch.Tensor([[[-3, 0, 0], [3, 0, 0], [3, 0, 7], [-3, 0, 7]]]).type_as(gp_y)
    vertices[:, :, 1] = gp_y
    faces = torch.Tensor([[[0, 1, 2], [0, 2, 3]]]).type_as(self.faces)
    green = [0.19607843, 0.80392157, 0.19607843]
    textures = torch.Tensor([green, green]).reshape(1, 2, 1, 1, 1, 3).type_as(self.textures)
    return vertices, faces, textures

def get_ground_plane_np(self):
    vertices, faces, textures = self.get_ground_plane_mesh()
    return vertices.detach().cpu().numpy(), faces.detach().cpu().numpy(), textures.detach().cpu().numpy()

## camera -> image
def apply_projection_to_image(self, verts):
    proj_v = torch.matmul(self.K_intrin, verts.transpose(2,1)).transpose(2,1)
    xy = proj_v[:, :, :2] / proj_v[:, :, 2:]
    z = proj_v[:, :, 2:]
    return xy, z

def apply_projection_to_local_image(self, verts, obj_cam=None, resize=None):
    assert obj_cam is not None
    proj_v = torch.matmul(self.K_rois[obj_cam].float(), verts.float().transpose(2,1)).transpose(2,1)
    xy = proj_v[:, :, :2] / proj_v[:, :, 2:]
    z = proj_v[:, :, 2:]

    return xy, z

def get_relative_extrin_new(self):
    return get_pitch_roll_euler_rotation_matrix(self.rotate_cam_pitch, self.rotate_cam_roll) # need in forward

# camera
def get_cam_extrin(self):
    extra_extrin_mat = self.get_relative_extrin_new()
    cam_extrin = torch.transpose(torch.matmul(extra_extrin_mat, torch.transpose(self.K_extrin, 2, 1)), 2, 1)
    return cam_extrin


from django.dispatch import receiver
from django.db.models.signals import post_save
from users.models import Profile
from users.models import CustomUser

@receiver(post_save, sender=CustomUser)
def create_profile(sender, instance, created, **kwargs):
    if created:
        print('email'+instance.email)
        Profile.objects.create(id=instance.id,
                               email=instance.email,
                               user=instance,
                               first_name=instance.first_name,
                               last_name=instance.last_name)

@receiver(post_save, sender=CustomUser)
def save_profile(sender, instance, created, **kwargs):
    instance.profile.save()


class potion:
    def __init__(self, name, duration, item_id, quantity, effect, effect_readable):
        self.name = name
        self.duration = duration
        self.item_id = item_id
        self.quantity = quantity
        self.effect = effect
        self.effect_readable = effect_readable

class melee_weapon: #swords, clubs, tridents, ~~MournBlade~~,
    def __init__(self, name, type, damage, ):
        self.name = name
        self.type = type
        self.damage = damage
    damage_radius = 1 # for all melee weapons. Might add another class for spears, lances, etc


import os
import shutil
acmdir = '/Users/M/Documents/Xcode Projects/ACM'
targetdir = '/Users/M/Desktop/Algorithm/ACM'
dirlist = os.listdir(acmdir)
for i in dirlist:
	if i[0]=='.' or i == 'test' or os.path.isdir(acmdir + '/'+ i)!=True:
		continue
	if i[0:8] == 'BJTU-ACM':
		targetname = 'BOJ'+i[8:]
	elif i[0:7] == 'BJT-ACM':
		targetname = 'BOJ' + i[7:];
	else:
		targetname = i;
	tmppath = acmdir+'/'+i
	tmplist = os.listdir(tmppath)
	if tmplist.count('main.cpp') == 1:
		shutil.copy(tmppath+'/main.cpp', targetdir+'/'+targetname+'.cpp')
	elif tmplist.count('main.c')==1:
		shutil.copy(tmppath+'/main.c', targetdir+'/'+targetname+'.cpp')
	elif tmplist.count(i)==1:
		shutil.copy(tmppath+'/'+i+'/main.cpp', targetdir+'/'+targetname+'.cpp')


class Solution(object):
    def partitionLabels(self, S):
        """
        :type S: str
        :rtype: List[int]
        """
        range_dic={}
        for i in range(len(S)):
            range_dic.setdefault(S[i],i)
            range_dic[S[i]]=i
        res=[]
        furthest=0
        count=0
        for i in range(len(S)):
            furthest= max(furthest,range_dic[S[i]])
            count+=1

            if i==furthest:
                res.append(count)
                furthest=0
                count=0
        return res


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

import numpy as np
import pybullet as p
import tf.transformations as tt
import matplotlib.pyplot as plt
from scipy.stats import norm
import time

def addDebugFrame(pos, quat, length=0.2, lw=2, duration=0.2, pcid=0):
    rot_mat = np.array(p.getMatrixFromQuaternion(quat)).reshape(3, 3).transpose()
    toX = pos + length * rot_mat[0, :]
    toY = pos + length * rot_mat[1, :]
    toZ = pos + length * rot_mat[2, :]
    item_id = [0, 0, 0]
    item_id[0] = p.addUserDebugLine(pos, toX, [1, 0, 0], lw, duration, physicsClientId=pcid)
    item_id[1] = p.addUserDebugLine(pos, toY, [0, 1, 0], lw, duration, physicsClientId=pcid)
    item_id[2] = p.addUserDebugLine(pos, toZ, [0, 0, 1], lw, duration, physicsClientId=pcid)
    return item_id

class CameraPose(object):

    def __init__(self, position, rpy, distance):
        self.position = position
        self.rpy = rpy
        self.distance = distance

def normal_random_integer(samples = 1, mean = 0, std = 1):

    return norm.ppf(np.random.random(samples), loc=mean, scale=std).astype(int)

class ImageGetter(object):
    def __init__(self, pcid):
        self._id = pcid

        self.camera_poses = []
        self.camera_poses.append(CameraPose([0.3, 0.0, 0.5],[0.0, -30.0, 90.0],1.5))
        self.camera_poses.append(CameraPose([0.50,0.35,0.20],[0.0, 4.60, 168.0],1.5))
        self.camera_poses.append(CameraPose([1.0,-0.02,-1.31],[0.0, -46.6, 214.0],1.9))
        self.camera_poses.append(CameraPose([0.6,0.62,-0.55],[0.0, -39.0, 320.0],1.5))

        self.camera_idx = 0

        camera_pose = self.camera_poses[self.camera_idx]

        self.camTargetPos = camera_pose.position#[0.3, 0.0, 0.5]
        self.roll = camera_pose.rpy[0]
        self.pitch = camera_pose.rpy[1]
        self.yaw = camera_pose.rpy[2]

        self.camDistance = camera_pose.distance

        self.pixelWidth = 640
        self.pixelHeight = 640
        self.aspect = self.pixelWidth / self.pixelHeight

        self.nearPlane = 0.01
        self.farPlane = 5.0
        self.fov = 57.0
        # Primesense carmine 1.09 field of view
        #horizontal FOV of 57.5 degrees and vertical FOV of 45 degrees.

        self.xyz_rgb = np.zeros((self.pixelWidth * self.pixelHeight, 6))

        self.projectionMatrix = p.computeProjectionMatrixFOV(self.fov, self.aspect,
                                                             self.nearPlane, self.farPlane,
                                                             physicsClientId=self._id)
        self.viewMatrix = None

        self.setCameraPose()

    def setCameraPose(self, idx = 0):
        assert idx < len(self.camera_poses)

        self.camera_idx = idx

        camera_pose = self.camera_poses[self.camera_idx]

        self.camTargetPos = camera_pose.position
        self.roll = camera_pose.rpy[0]
        self.pitch = camera_pose.rpy[1]
        self.yaw = camera_pose.rpy[2]
        self.camDistance = camera_pose.distance

        self.viewMatrix = p.computeViewMatrixFromYawPitchRoll(self.camTargetPos, self.camDistance,
                                                              yaw=self.yaw, pitch=self.pitch, roll=self.roll,
                                                              upAxisIndex=2, physicsClientId=self._id)

        p.resetDebugVisualizerCamera(cameraDistance=self.camDistance,
                                    cameraYaw=self.yaw, cameraPitch=self.pitch,
                                    cameraTargetPosition = self.camTargetPos
                                    )

        self.setCameraParams()

    def nextCameraPose(self):
        idx = (self.camera_idx+1)%len(self.camera_poses)

        self.setCameraPose(idx)

    def previousCameraPose(self):
        idx = (self.camera_idx-1)
        idx = (len(self.camera_poses)-1) if idx < 0 else idx

        self.setCameraPose(idx)

    def setCameraParams(self):
        # https://blog.noctua-software.com/opencv-opengl-projection-matrix.html
        opengl_proj_mat = np.array(self.projectionMatrix).reshape([4,4])
        opengl_view_mat = np.array(self.viewMatrix).reshape([4,4])

        self.fx = opengl_proj_mat[0,0] / 2.0 * self.pixelWidth
        self.fy = -opengl_proj_mat[1,1] / 2.0 * self.pixelHeight
        self.cx = (1.0 - opengl_proj_mat[2,0])/2.0*self.pixelWidth
        self.cy = (1.0 + opengl_proj_mat[2,1])/2.0*self.pixelHeight

        self.extrinsic_params = np.linalg.inv(opengl_view_mat).T
        self.camera_pos = self.extrinsic_params[0:3, 3]
        self.camera_quat = tt.quaternion_from_matrix(self.extrinsic_params)

        addDebugFrame(self.camera_pos, self.camera_quat, 0.2, 2, 10.0, self._id)

    def getImage(self):
        p.configureDebugVisualizer(p.COV_ENABLE_RENDERING,0)
        Renderer = p.ER_BULLET_HARDWARE_OPENGL #p.ER_TINY_RENDERER
        img_arr = p.getCameraImage(self.pixelWidth, self.pixelHeight,
                                   self.viewMatrix, self.projectionMatrix,
                                   renderer=Renderer, shadow=-1, physicsClientId=self._id)

        self.rgb = img_arr[2] # RGBA data
        self.dep = img_arr[3] # depth data
        p.configureDebugVisualizer(p.COV_ENABLE_RENDERING, 1)

    def corruptImage(self, depth_image):
        # zˆ(u, v) = z(u + N (0, σ2p), v + N (0, σ2p)) + N (0, σ2d)
        # Ed John's paper
        # Corrupt image with noise
        rows, cols = depth_image.shape

        std_dev = 0.001
        std_p = 1
        std_v = 1
        rintc = normal_random_integer(rows*cols,0,std_p).reshape(rows,cols)
        rintr = normal_random_integer(rows*cols,0,std_p).reshape(rows,cols)

        c, r = np.meshgrid(np.arange(cols), np.arange(rows), sparse=False)
        c_new = np.minimum(np.maximum(rintc + c,0),rows-1)
        r_new = np.minimum(np.maximum(rintr + r,0),cols-1)

        depth_image[c,r] = depth_image[c_new,r_new] # zˆ(u, v) = z(u + N (0, σ2p), v + N (0, σ2p))

        noise = np.random.randn(rows, cols)*std_dev
        noise_cutoff = 0.005
        noise[ noise < -noise_cutoff ] = -noise_cutoff
        noise[ noise > noise_cutoff ] = noise_cutoff
        depth_image = depth_image + noise # zˆ(u, v) = zˆ(u, v) + N (0, σ2d)

        # mask = (np.random.uniform(0,1,size=depth_image.shape) > 0.95).astype(np.bool)
        # # Randomly set 5% of the depth pixels to 0
        # depth_image[mask] = 0

        return depth_image

    def createPointCloud(self):
        xyz_rgb = self.xyz_rgb

        depth_image = np.array(self.dep).T
        depth_image = self.farPlane* self.nearPlane / (self.farPlane - (self.farPlane - self.nearPlane) * depth_image)
        # i = 0

        rows, cols = depth_image.shape

        t0 = time.time()

        depth_image = self.corruptImage(depth_image)

        # plt.imshow(depth_image)
        # plt.show()

        c, r = np.meshgrid(np.arange(cols), np.arange(rows), sparse=True)
        valid = (depth_image > 0) #
        z = np.where(valid, -depth_image , np.nan)
        x = np.where(valid, -z * (r - self.cx) / self.fx, 0)
        y = np.where(valid, -z * (c - self.cy) / self.fy, 0)
        # rgb = np.flipud(np.rot90(self.rgb))#[:, :,:3] #np.where(valid, self.rgb[r, c,:], [0,0,0])
        #
        # points = np.dstack((x, y, z,rgb))
        points = np.dstack((x, y, z))
        point_list = points.reshape(-1,3)
        # point_list = points.reshape(-1,7)
        # print "RGB shape: ", rgb.shape
        # points = np.vstack([x,y,z])
        # print "Point shape: ", points.shape
        # points = np.vstack([x,y,z,rgb])#np.dstack((x, y, z, rgb))
        # print points.shape

        # colors = np.where(valid, rgb[col, row, :3], 0)
        # points = np.dstack((x, y, z))
        # for row in range(self.pixelWidth):
        #     for col in range(self.pixelHeight):
        #         z = depth_image[row, col]
        #         xyz_rgb[i, 0] = (row - self.cx) / self.fx * z
        #         xyz_rgb[i, 1] = (col - self.cy) / self.fy * z
        #         xyz_rgb[i, 2] = -z
        #         xyz_rgb[i, 3:6] = self.rgb[col, row, :3]
        #         i = i + 1
        # print "Got it!"
        print("Time elapsed %.3f"%(time.time()-t0,))
        return point_list


h = eval(input())
M = eval(input())
t = 1
A = -6 * t * t * t * t + h * t * t * t + 2 * t * t + t
print("time=" + str(t) + " Altitude=" + str(A))
while t < M and A > 0:
    t = t + 1
    A = -6 * pow(t, 4) + h * pow(t, 3) + 2 * t * t + t
    print("time=" + str(t) + " Altitude=" + str(A))
if A > 0:
    print("The balloon does not touch ground in the given time.")
else:
    print("The balloon touches ground at time:", t)


from scipy.ndimage import zoom
from torchvision import transforms
from PIL import Image
from cv2 import cv2
import cv2
import numpy as np
import torch

def gaussian_filter(img, K_size=7, sigma=0.4):
    if len(img.shape) == 3:
        H, W, C = img.shape
    else:
        img = np.expand_dims(img, axis=-1)
        H, W, C = img.shape
    ## Zero padding
    pad = K_size // 2
    out = np.zeros((H + pad * 2, W + pad * 2, C), dtype=np.float)
    out[pad: pad + H, pad: pad + W] = img.copy()
    ## prepare Kernel
    K = np.zeros((K_size, K_size), dtype=np.float)
    for x in range(-pad, -pad + K_size):
        for y in range(-pad, -pad + K_size):
            K[y + pad, x + pad] = np.exp(-(x ** 2 + y ** 2) / (2 * (sigma ** 2)))
    K /= (2 * np.pi * sigma * sigma)
    K /= K.sum()
    tmp = out.copy()
    # filtering
    for y in range(H):
        for x in range(W):
            for c in range(C):
                out[pad + y, pad + x, c] = np.sum(K * tmp[y: y + K_size, x: x + K_size, c])
    out = np.clip(out, 0, 255)
    out = out[pad: pad + H, pad: pad + W]
    return out

def show_cam_on_image(img, mask):
    heatmap = cv2.applyColorMap(np.uint8(255 * mask), cv2.COLORMAP_JET)
    heatmap = np.float32(heatmap) / 255
    cam = heatmap + np.float32(img)
    cam = cam / np.max(cam)
    cv2.imwrite("cam.jpg", np.uint8(255 * cam))

if __name__ == '__main__':

    trans = transforms.ToTensor()
    pp = np.loadtxt('model2_img1.txt')
    ct_img = cv2.imread('1.png', 1)

    img1 = cv2.resize(pp, (224, 224))
    img2 = np.float32(cv2.resize(ct_img, (224, 224))) / 255
    ct = img2
    img1 = gaussian_filter(img1).transpose(2,0,1)[0]

    means = [0.5]
    stds = [1]
    preprocessed_img = img1.copy()[:, :]
    preprocessed_img[:,:] = preprocessed_img[:, :] - means
    preprocessed_img[:,:] = preprocessed_img[:, :] / stds
    preprocessed_img = np.ascontiguousarray(preprocessed_img)
    preprocessed_img = torch.from_numpy(preprocessed_img)
    input1 = preprocessed_img
    heatmap = cv2.applyColorMap(np.uint8(255 * input1), cv2.COLORMAP_JET)
    heatmap = np.float32(heatmap) / 255

    heatmap = torch.where(torch.from_numpy(heatmap) < 0.6, torch.tensor([0.0]), torch.from_numpy(heatmap))
    cam = heatmap + np.float32(img2)
    cam = cam / cam.max()

    cv2.imwrite("cam.jpg", np.uint8(255 * cam))

    cam = torch.where(torch.from_numpy(heatmap) < 0.005, torch.from_numppy(img2), torch.from_numpy(heatmap+np.float32(img2)))


import asyncio
import logging
from typing import Mapping, Optional
from opentrons.drivers.mag_deck import (
    SimulatingDriver,
    MagDeckDriver,
    AbstractMagDeckDriver,
)
from opentrons.drivers.rpi_drivers.types import USBPort
from ..execution_manager import ExecutionManager
from . import update, mod_abc, types

log = logging.getLogger(__name__)

MAX_ENGAGE_HEIGHT = {
    # Distance from home position.
    # Measured in model-specific units (half-mm for GEN1, mm for GEN2).
    "magneticModuleV1": 45,
    "magneticModuleV2": 25,
}

# Measured in model-specific units (half-mm for GEN1, mm for GEN2).
# TODO(mc, 2022-06-13): the value for gen1 is off by ~1.5 mm
# The correct value is ~8.0 half-mm (4.0 mm)
# https://opentrons.atlassian.net/browse/RET-1242
OFFSET_TO_LABWARE_BOTTOM = {"magneticModuleV1": 5, "magneticModuleV2": 2.5}

def engage_height_is_in_range(model: str, height: float) -> bool:
    """Return whether or not a height would be valid to pass to `MagDeck.engage()`.

    Args:
        model: The model of Magnetic Module for which you want to check
            the engage height.
        height: A height that you would provide to `MagDeck.engage()`.
    """
    return 0 <= height <= MAX_ENGAGE_HEIGHT[model]

class MagDeck(mod_abc.AbstractModule):
    """Hardware control interface for an attached Temperature Module."""

    MODULE_TYPE = types.ModuleType.MAGNETIC
    FIRST_GEN2_REVISION = 20

    @classmethod
    async def build(
        cls,
        port: str,
        usb_port: USBPort,
        execution_manager: ExecutionManager,
        hw_control_loop: asyncio.AbstractEventLoop,
        poll_interval_seconds: Optional[float] = None,
        simulating: bool = False,
        sim_model: Optional[str] = None,
    ) -> "MagDeck":
        """Factory function."""
        driver: AbstractMagDeckDriver
        if not simulating:
            driver = await MagDeckDriver.create(port=port, loop=hw_control_loop)
        else:
            driver = SimulatingDriver(sim_model=sim_model)

        mod = cls(
            port=port,
            usb_port=usb_port,
            execution_manager=execution_manager,
            hw_control_loop=hw_control_loop,
            device_info=await driver.get_device_info(),
            driver=driver,
        )
        return mod

    def __init__(
        self,
        port: str,
        usb_port: USBPort,
        execution_manager: ExecutionManager,
        hw_control_loop: asyncio.AbstractEventLoop,
        driver: AbstractMagDeckDriver,
        device_info: Mapping[str, str],
    ) -> None:
        """Constructor"""
        super().__init__(
            port=port,
            usb_port=usb_port,
            hw_control_loop=hw_control_loop,
            execution_manager=execution_manager,
        )
        self._device_info = device_info
        self._driver = driver
        self._current_height = 0.0

    async def cleanup(self) -> None:
        await self._driver.disconnect()

    @classmethod
    def name(cls) -> str:
        """Get the module name."""
        return "magdeck"

    def firmware_prefix(self) -> str:
        """The prefix used for looking up firmware"""
        return "magnetic-module"

    def model(self) -> str:
        """Get the model."""
        return self._model_from_revision(self._device_info.get("model"))

    def bootloader(self) -> types.UploadFunction:
        """Get the bootloating method."""
        return update.upload_via_avrdude

    async def calibrate(self) -> None:
        """Calibration involves probing for top plate to get the plate height."""
        await self.wait_for_is_running()
        await self._driver.probe_plate()
        # return if successful or not?

    # TODO(mc, 2022-09-23): refactor this method to take real mm,
    # hardware API should abstract away the idea of "short millimeters"
    # https://opentrons.atlassian.net/browse/RET-1242
    async def engage(
        self,
        height: Optional[float] = None,
        height_from_base: Optional[float] = None,
        must_be_running: bool = True,
    ) -> None:
        """Move the magnet to a specific height, measured from home position.

        The units of position depend on the module model.
        For GEN1, it's half millimeters ("short millimeters").
        For GEN2, it's millimeters.
        """
        if height is None:
            assert height_from_base is not None, "An engage height must be specified"
            height = height_from_base + OFFSET_TO_LABWARE_BOTTOM[self.model()]

        if must_be_running:
            await self.wait_for_is_running()
        if not engage_height_is_in_range(self.model(), height):
            raise ValueError(
                f"Invalid engage height for {self.model()}: {height}. "
                f"Must be 0 - {MAX_ENGAGE_HEIGHT[self.model()]}."
            )
        await self._driver.move(height)
        self._current_height = await self._driver.get_mag_position()

    async def deactivate(self, must_be_running: bool = True) -> None:
        """Home the magnet."""
        if must_be_running:
            await self.wait_for_is_running()
        await self._driver.home()
        await self.engage(0.0, must_be_running=must_be_running)

    @property
    def current_height(self) -> float:
        """Get the current height."""
        return self._current_height

    @property
    def device_info(self) -> Mapping[str, str]:
        """

        Returns: a dict
            { 'serial': 'abc123', 'model': '8675309', 'version': '9001' }

        """
        return self._device_info

    @property
    def status(self) -> types.MagneticStatus:
        if self.current_height > 0:
            return types.MagneticStatus.ENGAGED
        else:
            return types.MagneticStatus.DISENGAGED

    @property
    def engaged(self) -> bool:
        if self.current_height > 0:
            return True
        else:
            return False

    @property
    def live_data(self) -> types.LiveData:
        return {
            "status": self.status,
            "data": {"engaged": self.engaged, "height": self.current_height},
        }

    @property
    def is_simulated(self) -> bool:
        return isinstance(self._driver, SimulatingDriver)

    # Internal Methods

    async def prep_for_update(self) -> str:
        await self._driver.enter_programming_mode()
        new_port = await update.find_bootloader_port()
        return new_port or self.port

    @staticmethod
    def _model_from_revision(revision: Optional[str]) -> str:
        """Defines the revision -> model mapping"""
        if not revision or "v" not in revision:
            log.error(f"bad revision: {revision}")
            return "magneticModuleV1"
        try:
            revision_num = float(revision.split("v")[-1])
        except (ValueError, TypeError):
            log.exception("bad revision: {revision}")
            return "magneticModuleV1"
        if revision_num < MagDeck.FIRST_GEN2_REVISION:
            return "magneticModuleV1"
        else:
            return "magneticModuleV2"


# -*- coding:utf-8 -*-
"""
author:Bonnieliuliu
email:fangyuanliu@pku.edu.cn

file: 4.py
time: 2018/8/25 11:15
"""

def LongestSubSeq(n, m, arr):
    """
    :type nums: List[int]
    :rtype: int
    """
    nums = []
    for i in range(m):
        nums.extend(arr)
    N = len(nums)
    dp = [0] * N
    for i in range(N):
        for j in range(i):
            if nums[j] < nums[i] and dp[j] > dp[i]:
                dp[i] = dp[j]
        dp[i] += 1
    return max(dp)

import sys
if __name__ == "__main__":
    # 读取第一行的n
    line = sys.stdin.readline().strip()
    num = list(map(int, line.split()))
    n = num[0]
    m = num[1]
    line = sys.stdin.readline().strip()
    # 把每一行的数字分隔后转化成int列表
    arr = list(map(int, line.split()))
    res = LongestSubSeq(n, m, arr)
    print(res)


from loader import dp
from aiogram.types import Message
import game
import random

@dp.message_handler()
async def mes_help(message: Message):
    if game.new_game:
        for duel in game.total:
            if message.from_user.id == duel[0]:
                count = message.text
                name = message.from_user.first_name
                if count.isdigit() and 0 < int(count) <29:
                    duel[2] -= int(count)
                    await check_win(message, 'Ты', duel)
                    if game.new_game:
                        await message.answer(f'{duel[1]} взял {count} конфет и на столе осталось {duel[2]}\n Теперь ход бота...')

                    bot_take = random.randint(1,28) if duel[2] >28 else duel[2]
                    duel[2] -= bot_take

                    await check_win(message, 'Бот', duel)
                    if game.new_game:
                        await message.answer(f'Бот взял {bot_take} конфет и на столе осталось {duel[2]}\n Теперь твой ход...')

            else:
                await message.answer(f'Введите число от 1 до 28')

async def check_win(message: Message, win: str, total: list):
    if total[2] <= 0:
        await message.answer(f'{win} Победил!')
        game.new_game = False
        game.total.remove(total)


import librosa
import numpy as np
import pandas as pd
from IPython.display import Audio
import os
import shutil
import skimage
import skimage.io
from PIL import Image

class Preprocess:
    def __init__(self, hop_length=256, n_mels=80, win_size=128):
        self.hop_length = hop_length
        self.n_mels = n_mels
        self.n_fft = hop_length * 4
        self.frame_length = hop_length * 4
        self.win_size= win_size

    def scale_minmax(self, X, min=0, max=255):
        '''
        Scales and converts the spectrogram to a PNG
        Called by spectrogram_image()
        '''
        X_std = (X - X.min()) / (X.max() - X.min())
        X_scaled = X_std * (max - min) + min
        return X_scaled

    def loudest_window(self, spectrogram):
        '''
        Identifies the loudest window of a specified size within a spectrogram
        '''
        # Convert the array to a spectrogram
        array = np.asarray(spectrogram)
        # get the width of the array
        width = array.shape[1]
        # set the starting and ending of the window
        start = 0
        end = self.win_size
        arrays = []
        # move the window across the image advancing by 1 pixel.
        # append the array in the window to the list of arrays
        while end <= width:
            window = array[0:self.n_mels,start:end]
            arrays.append(window)
            start += 1
            end += 1
        # get the sum of each window in the array
        sums = [np.sum(window) for window in arrays]
        # get the index of the smallest window. This will be the loudest section
        index = sums.index(max(sums))
        # pull the loudest window from the list and return it.
        loudest = arrays[index]
        return loudest

    def add_silence(self, spectrogram):
        '''
        Adds silence to the end of a spectrogram if the spectrogram is shorter than
        the minimum window size
        '''
        # get the width of the spectrogram
        width = spectrogram.shape[1]
        # subtract the width from the minimum width to determine number of silent columns to add
        n_col = self.win_size-width
        # create silent columns
        silence = np.full((self.n_mels, n_col), 0)
        # convert the spectrogram to an array
        spect_ar = np.asarray(spectrogram)
        # add the silence to the spectrogram array
        spect_ar = np.concatenate((spect_ar, silence), axis = 1).astype(np.uint8)
        return spect_ar

    def standardize(self, spectrogram):
        '''
        Standardizes an image using the loudest_window() and add_silence() functions
        Pass spectrogram as an array
        '''
        width = spectrogram.shape[1]
        # if the width of the spectrogram is less than the minimum, add silence
        if width < self.win_size:
            spect = self.add_silence(spectrogram)
        # otherwise get the loudest window
        else:
            spect = self.loudest_window(spectrogram)
        # scale and return
        return scale_minmax(spect).astype(np.uint8)

    def spectrogram_image(self, wav_file, out_file = '', save = True):
        '''
        Converts a WAV file to a spectrogram and sames the image

        wav_file: The path to a WAV file as a string
        '''
        # load the audio data
        y, sr = librosa.load(wav_file)
        # trim the silence at edges
        #sample, _ = librosa.effects.trim(y, top_db=30, ref = np.max, hop_length = 128, frame_length=512)
        # use log-melspectrogram
        mels = librosa.feature.melspectrogram(y=y, sr=sr, n_mels=self.n_mels,
                                                n_fft=self.hop_length*4, hop_length=self.hop_length)
        # convert mel to decibles
        DB = librosa.power_to_db(mels, ref=np.max)
        # Standardize by finding the loudest window or adding silence
        # and rescaling
        DB = self.standardize(DB)

        # save the image
        if save == True:
            skimage.io.imsave(out_file, DB)
        else:
            return Image.fromarray(DB, mode = 'P')

    def play_spectrogram(self, spectrogram, sr = 22050, n_fft = 1024, hop_length = 256):
        array = np.asarray(spectrogram)
        mels = librosa.db_to_power(array, ref=1)
        return Audio(librosa.feature.inverse.mel_to_audio(mels, sr = sr, n_fft = self.hop_length*4, hop_length = self.hop_length), rate = sr)


from asyncpg.connection import Connection

class DBWorker:
    def __init__(self, conn: Connection):
        self.conn = conn

    async def get_all_tokens_output(self):
        sql = """select tot."id", u."id" as user_id, tot.tokens, u."bep_address",tot.created_date_time from "tokens_output" tot join "user" u on tot.user_id = u."id" """
        return await self.conn.fetch(sql)

    async def delete_tokens_output(self, id):
        sql = "delete from \"tokens_output\" where \"id\" = $1"
        return await self.conn.fetch(sql, id)


import cv2
import numpy as np
import matplotlib.pyplot as plt
def region_of_interest(img, vertices):
    mask = np.zeros_like(img)
    # channel_count = img.shape[2]
    match_mask_color = 255
    cv2.fillPoly(mask, vertices, match_mask_color)
    masked_image = cv2.bitwise_and(img, mask)
    return masked_image
def draw_lines(img,lines):
    for line in lines:
        (x1,y1,x2,y2)=line[0]
        cv2.line(img,(x1,y1),(x2,y2),(255,0,255),6)
    return img
# img=cv2.imread('../test_road.jpg')
# img=cv2.cvtColor(img,cv2.COLOR_BGR2RGB)
def process(img):
    print(img.shape)
    height=img.shape[0]
    width=img.shape[1]
    ROI=[(0,height),(width/2,height/2),(width,height)]

    gray_image=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
    edge=cv2.Canny(gray_image,70,200)
    crop_image=region_of_interest(edge,np.array([ROI],np.int32))
    lines=cv2.HoughLinesP(crop_image,6,np.pi/60,160,np.array([]),minLineLength=40,maxLineGap=25)
    f_image=draw_lines(img,lines)
    return  f_image
cap=cv2.VideoCapture('../test1.mp4')

while (cap.isOpened()):
    _,frame=cap.read()
    frame=process(frame)
    cv2.imshow('test_road',frame)
    if cv2.waitKey(1) &0xFF ==ord('q'):
        break


dirs = "ENWS"

d = {
    "N": (0, +1),
    "W": (-1, 0),
    "E": (+1, 0),
    "S": (0, -1)
}

a, b = map(int, input().split())
n, m = map(int, input().split())

board = [[0] * a for _ in range(b)]

# print(*board, sep='\n')
robots = {}

for i in range(n):
    x, y, z = input().split()
    x, y = int(x)-1, int(y)-1
    board[y][x] = z
    robots[i+1] = [x, y, z]

def find_robot_num_by_pos(robots, x, y):
    for k, v in robots.items():
        xx, yy, _ = v
        if xx == x and yy == y:
            return k

# print(*board, sep='\n')

result = 'OK'

for _ in range(m):
    num, order, it = input().split()
    num, it = map(int, (num, it))
    if order == 'L' or order == 'R':
        x, y, z = robots[num]
        idx = dirs.index(z)
        idx = idx + it if order =='L' else idx - it
        idx = idx % len(dirs)
        robots[num][2] = dirs[idx]
        board[y][x] = dirs[idx]
        # print('-'*20, *board, sep='\n')
    else: # order == 'F'
        _, _, z = robots[num]
        dx, dy = d[z]
        for _ in range(it):
            x, y, _ = robots[num]
            prev_x, prev_y = x, y
            new_x, new_y = x + dx, y + dy
            if not (0 <= new_x < a and 0 <= new_y < b):
                result = f'Robot {num} crashes into the wall'
                break
            if board[new_y][new_x] != 0:
                crashed_robot = find_robot_num_by_pos(robots, new_x, new_y)
                result = f'Robot {num} crashes into robot {crashed_robot}'
                break
            board[new_y][new_x] = z
            board[prev_y][prev_x] = 0
            robots[num] = [new_x, new_y, z]
            # print('-'*20, *board, sep='\n')
        if result != 'OK':
            break

print(result)


from skimage.transform import hough_line, hough_line_peaks
from skimage.feature import canny
import matplotlib.pyplot as plt
from skimage.draw import line
from PIL import Image as im
from matplotlib import cm
from skimage import data
import numpy as np
import imageio
import sys
import os

class edgedetector:
  ''' A class implementation for line detection and blurring image if line is detected '''

  def open_image(self,imgpath) -> np.array:
    ''' a function that takes the image path,load the raw image and returns a numpy array '''
    assert os.path.exists(imgpath),'please enter a valid path'
    img   = np.array(im.open(imgpath))
    return img

  def image_shape(self,imgpath) -> tuple:
    ''' A function to return the iamge shape'''
    assert os.path.exists(imgpath),'please enter a valid path'
    return imageio.imread(imgpath).shape

  def display_img(self,img) -> None:
    imgdata = im.fromarray(img)
    plt.imshow(imgdata, cmap=plt.cm.gray)

  #Blurring an image by applying a gaussian filter
  def gaussian_filter(self,img) -> np.array:
    ken = np.array([[1.0,2.0,1.0], [2.0,4.0,2.0], [1.0,2.0,1.0]])
    ken = ken / np.sum(ken)
    arraylist = []
    for y in range(3):
        temparray = np.copy(img)
        temparray = np.roll(temparray, y - 1, axis=0)
        for x in range(3):
            temparray_X = np.copy(temparray)
            temparray_X = np.roll(temparray_X, x - 1, axis=1)*ken[y,x]
            arraylist.append(temparray_X)

    arraylist   = np.array(arraylist)
    img         = np.sum(arraylist, axis=0)
    return img/255.0

  def rgb2gray(self,gray_img) -> np.array:
    gray_img = np.zeros(img.shape)
    R = np.array(img[:, :, 0])
    G = np.array(img[:, :, 1])
    B = np.array(img[:, :, 2])

    R = (R *.299)
    G = (G *.587)
    B = (B *.114)

    Avg = (R+G+B)
    gray_img = img

    for i in range(3):
        gray_img[:,:,i] = Avg

    return gray_img[:,:,0]

  def binarize_img(self,grey_img,threshold=128,maxval=255) -> np.array:
    img   = (grey_img>threshold)*maxval
    return img.astype(np.uint8)

  def hough_line(self,img):
    # Rho and Theta ranges
    thetas = np.deg2rad(np.arange(-90.0, 90.0))
    width, height = img.shape
    diag_len = int(np.ceil(np.sqrt(width * width + height * height)))   # max_dist
    rhos = np.linspace(-diag_len, diag_len, diag_len * 2)

    # Cache some resuable values
    cos_t = np.cos(thetas)
    sin_t = np.sin(thetas)
    num_thetas = len(thetas)

    # Hough accumulator array of theta vs rho
    accumulator = np.zeros((2 * diag_len, num_thetas), dtype=np.uint64)
    y_idxs, x_idxs = np.nonzero(img)  # (row, col) indexes to edges

    # Vote in the hough accumulator
    for i in range(len(x_idxs)):
      x = x_idxs[i]
      y = y_idxs[i]

      for t_idx in range(num_thetas):
        # Calculate rho. diag_len is added for a positive index
        rho = round(x * cos_t[t_idx] + y * sin_t[t_idx]) + diag_len
        accumulator[rho, t_idx] += 1

    return accumulator, thetas, rhos

if __name__ == '__main__':
  img_path = sys.argv[1]
  ed  = edgedetector()
  img = ed.open_image(img_path)
  img = ed.rgb2gray(img)
  img = ed.binarize_img(img,threshold=200)
  ed.display_img(img)
  h, theta, d = ed.hough_line(img)

  fig, axes = plt.subplots(1, 3, figsize=(15, 6))
  ax = axes.ravel()

  ax[0].imshow(img, cmap=cm.gray)
  ax[0].set_title('Input image')
  ax[0].set_axis_off()

  angle_step = 0.5 * np.diff(theta).mean()
  d_step = 0.5 * np.diff(d).mean()
  bounds = [np.rad2deg(theta[0] - angle_step),
            np.rad2deg(theta[-1] + angle_step),
            d[-1] + d_step, d[0] - d_step]
  ax[1].imshow(np.log(1 + h), extent=bounds, cmap=cm.gray, aspect=1 / 1.5)
  ax[1].set_title('Hough transform')
  ax[1].set_xlabel('Angles (degrees)')
  ax[1].set_ylabel('Distance (pixels)')
  ax[1].axis('image')

  ax[2].imshow(img, cmap=cm.gray)
  ax[2].set_ylim((img.shape[0], 0))
  ax[2].set_axis_off()
  ax[2].set_title('Detected lines')

  plt.tight_layout()
  plt.show()


import os
from datetime import datetime

import numpy as np
from visualization import make_movie,make_movie_eval
from episode import SimpleEpisode
from environment_abstract import AbstractEnvironment
from extract_tensor import objects_in_range, extract_tensor, objects_in_range_map
#from reconstruct3D.reconstruct3D import reconstruct3D
from colmap.reconstruct import reconstruct3D_ply, camera_to_cityscapes_coord
from commonUtils.ReconstructionUtils import CreateDefaultDatasetOptions_Cityscapes
import time, scipy
from settings import USE_LOCAL_PATHS

class Environment(AbstractEnvironment):

    def work(self, cachePrefix, file_name, agent, poses_db, epoch,saved_files_counter, training=True, road_width=5, conv_once=False,time_file=None, act=True):
        # Setup some options for the episode
        file_agent = self.get_file_agent_path(file_name)
        pos_x, pos_y = self.default_camera_pos()
        seq_len, seq_len_pfnn = self.default_seq_lengths(training, evaluate=False)

        # Create the desired dataset options structure
        options = CreateDefaultDatasetOptions_Cityscapes(None)
        options.LIMIT_FRAME_NUMBER = max(seq_len, seq_len_pfnn)
        options.envSettings = self.settings

        # Setup the episode
        start_setup = time.time()
        episode = self.set_up_episode(cachePrefix, file_name, pos_x, pos_y, training, useCaching=True, time_file=time_file, seq_len_pfnn=seq_len_pfnn, datasetOptions=options)
        setup_time = time.time() - start_setup
        print(("Setup time in s {:0.2f}s".format(setup_time)))

        # Initialize the agent
        run_episode = True
        test_init, succedeed, validRun = self.default_initialize_agent(training, agent, episode, None)
        if not succedeed:
            return self.counter, saved_files_counter

        # Act and learn for a repeated number of times
        number_of_runs_per_scene = 1
        if training:
            number_of_runs_per_scene = 1

        if act and (not test_init or run_episode):
            saved_files_counter,initializer_stats = self.default_doActAndGetStats(training, number_of_runs_per_scene, agent, episode, poses_db, file_agent, file_name, saved_files_counter)
        else:
            print("Not valid initialization")
            return self.counter, saved_files_counter

        return self.counter, saved_files_counter,initializer_stats

    def visualizeFromScript(self):

        with open("stats.pkl", "rb") as testFile:
            Objects_serialized = pickle.load(testFile, encoding="latin1", fix_imports=True)

        episode=Objects_serialized['episode']
        statistics_list = Objects_serialized['statistics']
        poses = Objects_serialized['poses']
        file_name = Objects_serialized['filename']
        seq_len = Objects_serialized['seq_len']
        episode = Objects_serialized['episode' ]
        training = Objects_serialized['training']
        jointsParents = Objects_serialized['jointParents']
        initialization_map=Objects_serialized['initialization_map']
        initialization_map=Objects_serialized['initialization_map']

        self.frame_counter = make_movie(episode.people,
                                        episode.reconstruction,
                                        statistics_list,
                                        self.settings.width,
                                        self.settings.depth,
                                        seq_len,
                                        self.frame_counter,
                                        self.settings.agent_shape,
                                        self.settings.agent_shape_s, episode,
                                        poses,
                                        initialization_map,
                                        initialization_car,
                                        training=training,
                                        name_movie=self.settings.name_movie,
                                        path_results=self.settings.statistics_dir + "/agent/",
                                        episode_name=os.path.basename(file_name),
                                        action_reorder=self.settings.reorder_actions,
                                        velocity_show=self.settings.velocity,
                                        velocity_sigma=self.settings.velocity_sigmoid,
                                        jointsParents=jointsParents,
                                        continous=self.settings.continous)

    def visualize(self, episode, file_name, statistics, training, poses, initialization_map,initialization_car,agent):
        seq_len=self.settings.seq_len_train
        if not training:
            seq_len =self.settings.seq_len_test
        jointsParents = None
        if self.settings.pfnn:
            jointsParents = agent.PFNN.getJointParents()

        HACK_ENABLED_SAVE = False
        if HACK_ENABLED_SAVE:
            # 'people' : episode.people, 'recontruction' : episode.reconstruction,
            Objects = {'statistics' : [statistics], 'poses' : poses, 'filename' : file_name
                       , 'seq_len' : seq_len, 'episode':episode, 'training' : training, 'jointParents' : jointsParents}

            with open("stats.pkl", "wb") as statsFile:
                Objects_serialized = pickle.dump(Objects, statsFile, protocol=pickle.HIGHEST_PROTOCOL)

            # Sanity check
            self.visualizeFromScript()
            exit(0)

        self.frame_counter = make_movie(episode.people,
                                        episode.reconstruction,
                                        [statistics],
                                        self.settings.width,
                                        self.settings.depth,
                                        seq_len,
                                        self.frame_counter,
                                        self.settings.agent_shape,
                                        self.settings.agent_shape_s, episode,
                                        poses,
                                        initialization_map,
                                        initialization_car,
                                        training=training,
                                        name_movie=self.settings.name_movie,
                                        path_results=self.settings.statistics_dir + "/agent/",
                                        episode_name=os.path.basename(file_name),
                                        action_reorder=self.settings.reorder_actions,
                                        velocity_show=self.settings.velocity,
                                        velocity_sigma=self.settings.velocity_sigmoid,
                                        jointsParents=jointsParents,
                                        continous=self.settings.continous)

    def evaluate(self, cachePrefix, file_name, agent, file_agent,saved_files_counter, viz=False, folder=""):
        training = False

        # Setup some options for the episode
        file_agent = self.get_file_agent_path(file_name)
        pos_x, pos_y = self.default_camera_pos()
        seq_len, seq_len_pfnn = self.default_seq_lengths(training=training, evaluate=True)
        self.settings.seq_len_test= seq_len # Override the test seq length because this is the one actually used, there is no different variable for evaluate in the core code

        options = CreateDefaultDatasetOptions_Cityscapes(None)
        options.LIMIT_FRAME_NUMBER = max(seq_len, seq_len_pfnn)
        options.envSettings = self.settings

        # Setup the episode
        start_setup = time.time()
        episode = self.set_up_episode(cachePrefix, file_name, pos_x, pos_y, training, useCaching=True,evaluate=True, seq_len_pfnn=seq_len_pfnn, datasetOptions=options)
        setup_time = time.time() - start_setup
        print(("Setup time in s {:0.2f}s".format(setup_time)))

        run_episode=True
        test_init, succedeed, validRun = self.default_initialize_agent(training, agent, episode, None)
        if not succedeed:
            return self.counter, saved_files_counter
        run_episode |= validRun

        # Act and get stats
        stats = []
        number_of_runs_per_scene = 1

        if (not test_init or run_episode):
            saved_files_counter,initializer_stats = self.default_doActAndGetStats(training,number_of_runs_per_scene, agent, episode, None, file_agent, file_name, saved_files_counter, outStatsGather=stats, evaluate=True)
        else:
            print ("Not valid initialization")
            return self.counter, saved_files_counter, None

        return stats, saved_files_counter,initializer_stats

    def visualize_aachen(self, camera_pos, middle, pos_x, pos_y, scale_vector, seq_len_pfnn, tensor):
        people_list = []
        cars_list = []
        cars_list_colmap = []
        for f in range(30):
            people_list.append([])
            cars_list.append([])
            p = camera_pos[f, :].copy()
            p = camera_to_cityscapes_coord(p, middle, scale_vector[0]).astype(int)
            p = p[[2, 1, 0]]
            p[1] = p[1] + (128 // 2)
            cars_list[-1].append(np.array([p[0] - 4, p[0] + 4, p[1] - 4, p[1] + 4, p[2] - 4, p[2] + 4]))
        cars_list[0] = cars_list[1]
        people_list[5] = [np.array([[1, 9], [75, 83], [95, 103]])]
        people_list[6] = [np.array([[1, 9], [75, 83], [95, 103]]), np.array([[1, 9], [73, 81], [91, 99]])]
        people_list[7] = [np.array([[1, 9], [75, 83], [95, 103]]), np.array([[1, 9], [73, 81], [91, 99]])]
        people_list[8] = [np.array([[1, 9], [74, 82], [94, 102]]), np.array([[1, 9], [72, 80], [90, 98]])]
        people_list[9] = [np.array([[1, 9], [74, 82], [93, 101]]), np.array([[1, 9], [72, 80], [90, 98]])]
        people_list[10] = [np.array([[1, 9], [74, 82], [93, 101]]), np.array([[1, 9], [72, 80], [90, 98]])]
        people_list[11] = [np.array([[1, 9], [74, 82], [93, 101]]), np.array([[1, 9], [72, 80], [90, 98]])]
        people_list[12] = [np.array([[1, 9], [74, 82], [93, 101]]), np.array([[1, 9], [72, 80], [90, 98]])]
        people_list[13] = [np.array([[1, 9], [74, 82], [92, 100]]), np.array([[1, 9], [72, 80], [90, 98]])]
        people_list[14] = [np.array([[1, 9], [73, 81], [90, 98]]), np.array([[1, 9], [71, 79], [86, 94]])]
        people_list[15] = [np.array([[1, 9], [72, 80], [89, 97]]), np.array([[1, 9], [70, 78], [85, 93]])]
        people_list[16] = [np.array([[1, 9], [72, 80], [86, 94]]), np.array([[1, 9], [70, 78], [82, 90]])]
        people_list[17] = [np.array([[1, 9], [72, 80], [86, 94]]), np.array([[1, 9], [70, 78], [82, 90]])]
        people_list[18] = [np.array([[1, 9], [72, 80], [86, 94]]), np.array([[1, 9], [70, 78], [82, 90]])]
        people_list[19] = [np.array([[1, 9], [71, 79], [86, 94]]), np.array([[1, 9], [69, 77], [82, 90]])]
        people_list[20] = [np.array([[1, 9], [71, 79], [86, 94]]), np.array([[1, 9], [69, 77], [82, 90]])]
        people_list[21] = [np.array([[1, 9], [70, 78], [86, 94]]), np.array([[1, 9], [68, 76], [82, 90]])]
        people_list[22] = [np.array([[1, 9], [70, 78], [86, 94]]), np.array([[1, 9], [68, 76], [82, 90]])]
        people_list[23] = [np.array([[1, 9], [70, 78], [86, 94]]), np.array([[1, 9], [68, 76], [82, 90]])]
        people_list[24] = [np.array([[1, 9], [70, 78], [82, 90]]), np.array([[0, 8], [68, 76], [79, 87]])]
        people_list[25] = [np.array([[1, 9], [70, 78], [82, 90]]), np.array([[0, 8], [68, 76], [79, 87]])]
        people_list[26] = [np.array([[1, 9], [69, 77], [82, 90]]), np.array([[0, 8], [67, 75], [79, 87]])]
        people_list[27] = [np.array([[1, 9], [68, 76], [82, 90]]), np.array([[0, 8], [66, 74], [79, 87]])]
        people_list[28] = [np.array([[1, 9], [68, 76], [82, 90]]), np.array([[0, 8], [66, 74], [79, 87]])]
        people_list[29] = [np.array([[1, 9], [67, 75], [82, 90]]), np.array([[0, 8], [65, 73], [79, 87]])]
        print("People list--- frame 5")
        print((people_list[5]))
        print("People list--- frame 10")
        print((people_list[10]))
        episode = self.set_up_episode(cars_list, people_list, pos_x, pos_y, tensor, False, evaluate=True, seq_len_pfnn=seq_len_pfnn)
        print("After episode set up ")
        print("People list--- frame 5")
        print((episode.people[5]))
        print("People list--- frame 10")
        print((episode.people[10]))
        return episode

    def agent_initialization(self, agent, episode, itr,  poses_db, training, init_m=-1, set_goal=""):
        init_key=itr
        # 1,6,2,4
        init_names = {1:"on ped", 6:"near ped", 2:"by car", 4:"random", -1 : "train"}
        #aachen_000024
        init_pairs={}
        init_pairs["aachen_000042"]=[([103, 68],[213,38]), ([103, 68],[254,45]), ([103, 68],[72,70]),
                    ([132, 42],[248,46]), ([132, 42],[60,23]), ([132, 42],[64, 32]), ([132, 42],[42,38]),
                    ([60, 25],[123,29]), ([60, 25],[121,2]), ([60, 25],[72,73]), ([60, 25],[141,70]),
                    ([60, 25],[252,49]) ]
        init_pairs["tubingen_000136"] = [([76, 16], [113, 62]), ([76, 16], [100, 83]), ([76, 16], [16, 62]), ([76, 16], [107,4]), ([76, 16], [169, 78]), ([76, 16], [150, 112])]
        #init_pairs["tubingen_000112"] = [([131, 2], [7, 78]), ([131, 2], [69, 104]),([131, 2], [100, 78]), ([131, 2], [74, 123]), ([131, 2], [152, 64])]
        init_pairs["tubingen_000112"] = [(np.array([ 5,  79,  99]), [85, 123]), (np.array([ 5,  79,  99]), [21, 2]), (np.array([ 5,  79,  99]), [6, 124])]

        init_pairs["bremen_000028"] = [([40, 71], [145, 40]), ([40, 71], [166, 54]),  ([12, 71], [157, 95]),  ([12, 71], [169, 47]),  ([12, 71], [86, 40])]
        init_pairs["bremen_000160"] = [([18, 42], [145, 82]), ([18, 42], [251, 57]),([18, 42], [144, 83]), ([18, 42], [79, 84]),
                                       ([58, 54], [145, 82]), ([58, 54], [251, 57]), ([58, 54], [144, 83]),
                                       ([58, 54], [79, 84])]
        init_pairs["munster_000039"] = [([23, 57], [118, 97]), ([23, 57], [190, 10]),([23, 57], [140, 42]),([23, 57], [127, 94])]
        init_pairs["darmstadt_000019"] = [([27, 52], [191, 18]),([27, 52], [80, 95]),([27, 52], [243, 89]),([27, 52], [59, 101]), ([59, 101], [191, 18]), ([59, 101], [243, 89])]

        if len(set_goal)>0:
            goal = init_pairs[set_goal][itr % len(init_pairs[set_goal])][1]

            if "tubingen_000112" in set_goal:
                episode.agent[0]=init_pairs[set_goal][itr%len(init_pairs[set_goal])][0]
                episode.goal = np.array([episode.agent[0][0], 128 - goal[1], goal[0]])
            else:
                pos_x=init_pairs[set_goal][itr%len(init_pairs[set_goal])][0]
                h = episode.get_height_init()
                episode.agent[0]=np.array([h, 128-pos_x[1], pos_x[0]])
                episode.goal=np.array([h, 128-goal[1], goal[0]])
            print(("Set pos "+str(episode.agent[0])+" "+str(goal)+" "+str(episode.goal)))
            return episode.agent[0], -1, episode.vel_init
        if itr >= len(episode.valid_keys) and len(episode.valid_keys)>0 :
            init_key=itr%len(episode.valid_keys)

        if init_m>0:
            print(("init_m- initialization method "+str(init_m)+" "+str(init_key)+" "+str(training)))
            pos, indx, vel_init = episode.initial_position(poses_db, training=training, init_key=init_key, initialization=init_m)
        elif len(episode.valid_keys) > 0:
            print(("valid_keys"+" "+str(init_key)+" "+str(training)))
            pos, indx, vel_init = episode.initial_position(poses_db, training=training, init_key=init_key)
        else:
            print(("training "+str(training)))
            pos, indx, vel_init = episode.initial_position(poses_db, training=training)
        return pos, indx, vel_init

    def __init__(self, path, sess, writer, gradBuffer, log,settings, net=None):
        super(Environment, self).__init__( path, sess, writer, gradBuffer, log,settings, net=None)
        self.init_methods = [ 8,  2, 4]  # [1,5]#[1, 3, 5, 9]#, 8, 6, 2, 4]#[1, 8, 6, 2, 4, 9,3,5, 10]#[1, 8, 6, 2, 4, 5, 9]#[8, 6, 2, 4] #<--- regular![1, 8, 6, 2, 4] [1]
        self.init_methods_train = [ 8,  2, 4]#9


import gevent
from gevent import getcurrent
from gevent.pool import Group

group = Group()

def hello_from(n):
    print('Size of group', len(group))
    print('Hello from Greenlet %s' % id(getcurrent()))

group.map(hello_from, xrange(3))

def intensive(n):
    gevent.sleep(3 - n)
    return 'task', n

print('Ordered')

ogroup = Group()

'''
think of it this way:
def imap(function, *iterables):
    # imap(pow, (2,3,10), (5,2,3)) --> 32 9 1000
    iterables = map(iter, iterables)
    while True:
        args = [next(it) for it in iterables]
        if function is None:
            yield tuple(args)
        else:
            yield function(*args)
'''
# why is this executing all at once?
for i in ogroup.imap(intensive, xrange(3)):
    print(i)

print('Unordered')

group = Group()

'''
imap_unordered
The same as imap() except that the ordering of the results from the returned iterator should be considered in arbitrary order.
'''
# why is this iterating one at a time?
# gevent is deterministic.  hence each greenlet is processed in order in deterministed way
for i in igroup.imap_unordered(intensive, xrange(3)):
    print(i)


import itertools

filepath = '/home/bigdata/PycharmProjects/LDA/PyLDA/pubmed_bioontology/data/PreLresults.txt'

# convert the data into list
def read_words(words_file):
    with open(words_file, 'r') as f:
        return list(itertools.chain.from_iterable(line.split("\n") for line in f))

mylist = read_words(filepath)

# covert all list of elements to lower case
lowercaselist = []
for x in mylist:
    y = x.lower()
    lowercaselist.append(y)

# get only unique values from above list
uniqueoutput = []
for x in lowercaselist:
    if x not in uniqueoutput:
        uniqueoutput.append(x)

# sort the unique output

# convert the sorted output to string
output = '\n'.join(uniqueoutput)

# write the output to file
f = open("data/unique.txt", "a+")
f.write("%s" % output)
f.close()


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

"""技能摸牌期望计算：关羽【忠义】

【忠义】：出牌阶段限一次，你可以将一张♥手牌交给一名其他角色，然后摸一张牌。本局游戏中，你只能对同一名角色发动【忠义】。

假定所有的♥牌都用来发动【忠义】，且一直能发动【忠义】。

计算前15回合的摸牌数期望。

结果：
    0.827  0.7538 0.7152 0.6946 0.6908
    0.6743 0.6754 0.6711 0.6727 0.6796
    0.6785 0.6758 0.6689 0.666  0.6633

    收敛于2/3；前五回合平均收益为0.7363。
"""

from random import random

import numpy as np

INIT_HAND = 4
EACH_TURN_DRAW = 2
N_TURNS = 15
P_CARD = 0.25
N_EXPERIMENTS = 10000

def get():
    return True if random() < P_CARD else False

def experiment():
    hand = [get() for _ in range(INIT_HAND)]

    result = []

    for _ in range(N_TURNS):
        hand.extend(get() for _ in range(EACH_TURN_DRAW))

        try:
            hand.remove(True)
        except ValueError:
            # target card is not present.
            result.append(0)
        else:
            # Remove one target card, add a new card.
            result.append(1)
            hand.append(get())

    return result

def main():
    experiments = [experiment() for _ in range(N_EXPERIMENTS)]
    experiments = np.array(experiments)

    print(experiments.shape)
    print(experiments.mean(axis=0))

if __name__ == '__main__':
    main()


# Первая задача

print('Введите число камней')
stones = int(input())
while stones > 0:
    take = int(input())
    stones -= take
    print('Осталось', stones)

# Вторая  задача

print('Введите число камней')
stones = int(input())
while stones > 0:
    take = int(input())
    if take <= stones and take <= 3:
        stones = stones - take
        print('Осталось', stones)
    else:
        print('Осталось', stones)

# Третья  задача

print('Введите число')
num = int(input())
(x, y) = (0, 1)
while x <= num:
    print(x)
    (x, y) = (y, x+y)

# Четвертая задача

print('Введите день')
d = int(input())
print('Введите месяц')
m = int(input()) - 2
print('Введите год')
e = int(input())

c = int(e / 100)
y = ((e-c) % 100)

r = d + ((13*m - 1) // 5) + y + (y // 4 + c // 4 - 2*c + 777)
r %= 7
print(r)

# Пятая  задача

print('Введите число')
num = int(input())
count = 0

while num != 1:
    if num % 2 == 0:
        num = num // 2
    else:
        num = num - 1
    count += 1
print(count)

# Шестая задача

print('Введите кол-во камней')
one = int(input(' - 1-ой кучи: '))
two = int(input(' - 2-ой кучи: '))

bunch = 0
taken = 0

# Седьмая  адача

while True:
    bunch = int(input('Введите номер кучи - из которой беруться камни: '))
    taken = int(input('Введите количество забираемых камней: '))

    if bunch == 1:
        if one - taken >= 0:
            one -= taken
    else:
        if two - taken >= 0:
            two -= taken
    print(one, two)
    if one == 0 or two == 0:
        break


def getIndex(c):
    hm = {}
    k = 'a'
    v = 0
    hm[k] = v
    while v < 26:
        k = chr(ord(k)+1)
        v += 1
        hm[k] = v
    return hm[c]

class Trie:
    def __init__(self):
        self.char = ['']*26
        self.ptr = [None]*26
        self.flag = False

    def insert(self, word):
        res = 0
        curr = None
        for w in word:
            i = getIndex(w)
            if curr is not None:
                if curr.char[i] == w:
                    curr = curr.ptr[i]
                else:
                    curr.char[i] = w
                    curr.ptr[i] = Trie()
                    curr = curr.ptr[i]
                    res += 1

            elif self.char[i] == w:
                curr = self.ptr[i]
            else:
                self.char[i] = w
                self.ptr[i] = Trie()
                curr = self.ptr[i]
                res += 1
        curr.flag = True
        return res

def distinctSubstring(word):
    res = 0
    root = Trie()
    n = len(word)
    for i in range(n):
        res += root.insert(word[i:])

    return res + 1

print(distinctSubstring("abab"))


### basic
def tensor_to_img(image_t):
    """
    image_t:torch.Tensor
    display one image
    tensor -> display image
    """
    image = image_t.cpu().detach().numpy().transpose((1,2,0)) # CHW -> HWC
    image = np.clip(image, 0, 1) # 0~1clip
    plt.imshow(image)
    plt.show()

def tensor2image_np(image_t, mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]):
    """
    Normalize tensor -> inverse_transform -> np.array
    Args:
        image_t: A pytorch Tensor
    Return:
        image_np
    """
    image_np = image_t.cpu().detach().numpy().transpose((1,2,0))
    mean = np.array(mean)
    std = np.array(std)
    image_np = std * image_np + mean # inverse_transform
    image_np = np.clip(image_np, 0, 1)
    return image_np

### for img pathlist
def filelist_to_imgs(file_list, rows=5, columns=10, scale=4, order=True):
    """
    display rows*columns images
    file_list:path_list
    scale:display scaling value
    order:path_order True/False
    """
    plt.figure(figsize=(scale*columns, scale*rows))
    if order == True:
        for i, img_path in enumerate(file_list[0:rows*columns]):
            img = Image.open(img_path).convert('RGB')
            plt.subplot(rows, columns, i+1)
            plt.imshow(img)
        plt.show()

    if order == False:
        for i, img_path in enumerate(random.sample(file_list, rows*columns)):
            img = Image.open(img_path).convert('RGB')
            plt.subplot(rows, columns, i+1)
            plt.imshow(img)
        plt.show()

### for simple classification
def dataset_to_imgs(dataset, rows=3, columns=5, scale=3, order=True):
    """
    display rows*columns images
    file_list:path_list
    scale:display scaling value
    order:dataset_order True/False
    """
    # index を作る。0番目からdatasetの長さ。
    dataset_index = list(range(len(dataset)))

    plt.figure(figsize=(scale*columns, scale*rows))
    if order == True:
        for i, dataset_index in enumerate(dataset_index[0: rows*columns]):
            img = dataset[dataset_index][0]
            img = img.cpu().detach().numpy().transpose(1,2,0)
            img = np.clip(img, 0, 1) # 0~1clip
            ax = plt.subplot(rows, columns, i+1)
            plt.imshow(img)
        plt.show()

    if order == False:
        for i, dataset_index in enumerate(random.sample(dataset_index, rows*columns)):
            img = dataset[dataset_index][0]
            img = img.cpu().detach().numpy().transpose(1,2,0)
            img = np.clip(img, 0, 1) # 0~1clip
            ax = plt.subplot(rows, columns, i+1)
            plt.imshow(img)
        plt.show()

### for simple classification
def dataloader_to_imgs(dataloader, net=None, device=None):
    """
    display dataloader_imags(max:50）
    net:classification_model
    title:true_label / predict
    """
    images, labels = next(iter(dataloader))
    n_size = min(len(images), 50) # n_size: len(images) or 50

    # has classification_model
    if net is not None:
        inputs, labels = images.to(device), labels.to(device)
        # predict
        outputs = net(inputs)
        predicted = torch.max(outputs, 1)[1]
        images, labels, predicted = images.to("cpu"), labels.to("cpu"), predicted.to("cpu")

    plt.figure(figsize=(20,15))
    for i in range(n_size):
        ax = plt.subplot(5,10, i+1)
        if net is not None:
            if labels[i].item() == predicted[i].item():
                c = "k"
            else:
                c="b"
            ax.set_title(str(labels[i].item()) + "/" + str(predicted[i].item()) , c=c, fontsize=20)
            # ax.set_title(str(labels[i].item()) + "/" , c=c, fontsize=20)
        else:
            ax.set_title(labels[i].item(), fontsize=20) # .item -> delete tensor
        image_np = images[i].numpy().copy()
        img = np.transpose(image_np, (1,2,0))
        img = np.clip(img, 0,1)
        ax.set_axis_off()
        plt.imshow(img)
    plt.show()