import json
import os
import sys
import urllib.error
import urllib.parse
import urllib.request

this_module_path = sys.modules[__name__].__file__

def fetch_remote_files():
    r"""Fetch remote files before any test runs"""
    data_dir = os.path.dirname(this_module_path)
    remote_info_file = os.path.join(data_dir, "remote_files.json")
    remote_info = json.load(open(remote_info_file, "r"))

    remote_address = remote_info["address"]
    remote_files = remote_info["files"]

    for basename, md5 in remote_files.items():
        file_path = os.path.join(data_dir, basename)
        if not os.path.isfile(file_path):
            print("Fetching data file " + basename)
            urllib.request.urlretrieve(os.path.join(remote_address, md5), file_path)

if __name__ == "__main__":
    fetch_remote_files()


#!/usr/bin/env python

def balanced(input_string):
    # Returns -1 if braces are balanced, or the 0-based index of the first
    # unbalanced brace
    openstack = list()
    input_string = str(input_string)

    for idx, char in enumerate(input_string):
        if char == '{':
            openstack.append(idx)
        elif char == '}':
            if not openstack:
                return idx
            openstack.pop()

    if openstack:
        return openstack[0]

    return -1

if __name__ == '__main__':
    import sys

    if len(sys.argv) > 1:
        string = sys.argv[1]
    else:
        print('please provide string as argument')
        sys.exit()

    res = balanced(string)
    if res != -1:
        print('{} : unbalanced brace on {}'.format(string, res))
    else:
        print('{} is balanced'.format(string))


import ray
from ray import tune
from ray.tune.logger import pretty_print

from ray.rllib.agents.ppo import PPOTrainer
from ray.rllib.agents.ppo.ppo_torch_policy import PPOTorchPolicy

from ray.tune.registry import register_env
from wanderer_roborobo import WandererRoborobo

if __name__ == "__main__":

    ray.init(num_cpus=1, num_gpus=1)

    #%%

    n_players = 1
    max_moves = 1000
    agents_id = ['player{:d}'.format(i) for i in range(n_players)]
    actions = {agents_id[i]: 1 for i in range(n_players)}

    register_env("wanderer_roborobo",
                 lambda _: WandererRoborobo(n_players, max_moves))
    act_space = WandererRoborobo.action_space

    obs_space = WandererRoborobo.observation_space

    policies = {agents_id[i]: (None, obs_space, act_space, {}) for i in range(n_players)}

    def select_policy(agent_id):
        return agent_id

    config = {
        "num_gpus": 0,
        'num_workers': 0,
        "multiagent": {
            "policies": policies,
            "policy_mapping_fn": select_policy,
        },
        'model': {
            'fcnet_hiddens': [4, 4]
        },
        "clip_actions": True,
        "framework": "torch",
        "num_sgd_iter": 4,
        "lr": 1e-4,
        "kl_target": 0.03,
        "train_batch_size": 256,
        "rollout_fragment_length": 128
    }

    trainer = PPOTrainer(env="wanderer_roborobo", config=config)
    trainer.restore('model/checkpoint_2000/checkpoint-2000')
    stop_iter = 2000

    #%%
    import numpy as np
    for i in range(stop_iter):
        print("== Iteration", i, "==")
        result_ppo = trainer.train()


import os
import struct
import sys
from io import BytesIO

def insert_gim_files(rssa_file, gim_directory, output_directory):
    original_rssa_name = os.path.basename(rssa_file)
    with open(rssa_file, 'rb') as original_f:
        temp_f = BytesIO(original_f.read())

    temp_f.seek(0)
    header = temp_f.read(0x60)  # read 60 bytes header
    magic = struct.unpack_from('=4s', header, 0)[0]
    fname = struct.unpack_from('=28s', header, 0x4)[0]
    ssad_count = struct.unpack_from('<H', header, 0x2C)[0]
    gim_count = struct.unpack_from('<H', header, 0x2E)[0]
    ssad_pos_foffset = struct.unpack_from('<I', header, 0x30)[0]
    ssad_pos_fsize = struct.unpack_from('<I', header, 0x34)[0]
    gim_pos_foffset = struct.unpack_from('<I', header, 0x38)[0]
    gim_pos_fsize = struct.unpack_from('<I', header, 0x3C)[0]
    print('header=', header.hex())
    print('magic=', magic.decode('utf-8'))
    print('fname=', fname.decode('utf-8'))
    print('ssad_count=', hex(ssad_count))
    print('gim_count=', hex(gim_count))
    print('ssad_pos_foffset=', hex(ssad_pos_foffset))
    print('ssad_pos_fsize=', hex(ssad_pos_fsize))
    print('gim_pos_foffset=', hex(gim_pos_foffset))
    print('gim_pos_fsize=', hex(gim_pos_fsize))

    # Read the structures from the binary file
    structures_pos = []
    temp_f.seek(gim_pos_foffset)
    for _ in range(gim_count):
        structure_pos = struct.unpack('<I', temp_f.read(4))[0]
        structures_pos.append(structure_pos)
        #print('structure_pos=', hex(structure_pos[0]))

    structures_size = []
    temp_f.seek(gim_pos_fsize)
    for _ in range(gim_count):
        structure_size = struct.unpack('<I', temp_f.read(4))[0]
        structures_size.append(structure_size)
        #print('structure_size=', hex(structure_size[0]))

    # insert the gim in the temp_f
    for gim_file in sorted(os.listdir(gim_directory)):
        if gim_file.endswith('.gim'):  # Check if the file has the .gim extension
            with open(os.path.join(gim_directory, gim_file), 'rb') as gim:
                gim_data = gim.read()
                gim_name = os.path.splitext(gim_file)[0]  # Get the gim file name without the .gim extension
                print(gim_name)
                gim_pos = structures_pos[int(gim_name)]  # Retrieve the file offset for this gim file
                print(hex(gim_pos))
                temp_f.seek(gim_pos)  # Move the pointer in temp_f to the specified offset
                temp_f.write(gim_data)  # Write the gim data at the specified position in temp_f
    # Save the modified content to a new file in the output directory

    output_file = os.path.join(output_directory, f"{original_rssa_name}")
    with open(output_file, 'w+b') as new_f:
        new_f.write(temp_f.getbuffer())

if __name__ == '__main__':
    if len(sys.argv) != 4:
        print("Usage: python gim_insertion.py <rssa_file> <gim_directory> <output_directory>")
    else:
        rssa_file = sys.argv[1]
        gim_directory = sys.argv[2]
        output_directory = sys.argv[3]
        insert_gim_files(rssa_file, gim_directory, output_directory)


#coding:utf-8
import sys
import time
import urllib
import urllib.request
import requests
from bs4  import BeautifulSoup
import os

# If we need 500 files, then we need 50 pages in page map
# mymap=['0','1','2','3','4','5','6','7']
# Take only one page to prevent to be put into black list
# page map
mymap=['0']

# access search result page
def baidu_search(key_words,pagenum):
    url='http://www.baidu.com/s?wd='+key_words+'&pn='+mymap[pagenum]
    html=urllib.request.urlopen(url).read()
    return html

# Send 'get' request to w3c validator
def validate(url):
    validaror_url = "https://validator.w3.org/nu/"
    params = { "doc": url, "out": "json"}
    response = requests.get(validaror_url,params=params)
    # Use "type:error" to locate errors
    error_key = "\"type\":\"error\""
    # Use "subType:warning" to locate warnings
    warning_key = "\"subType\":\"warning\""
    # .text contains entire content of checking result
    return str(response.text.count(error_key)), str(response.text.count(warning_key))

# parse html of result page
def deal_key(key_words):
    # create output file
    if os.path.exists('data')==False:
        os.mkdir('data')
    filename='data\\'+key_words+'.txt'
    fp=open(filename,'wb')
    if fp:
        pass
    else:
        print('Failed to create output file：'+filename)
        return

    # parse html of result page one by one
    x=0
    while x<=mymap.__len__()-1:
        htmlpage=baidu_search(key_words,x)
        soup=BeautifulSoup(htmlpage, "html.parser")
        # Find result links
        for item in soup.findAll("div", {"class": "result"}):
            a_click = item.find('a')
            if a_click:
                fp.write(a_click.get("href").encode('utf-8'))
                # collect errors and warnings
                err, war = validate(a_click.get("href").encode('utf-8'))
                fp.write(b' errors: %b, warnings: %b' % (bytes(err, 'utf8'),bytes(war, 'utf8')))
            fp.write(b'\r\n')
        x=x+1
        fp.write(b'\r\n')
    fp.close()

# entrance
print('Start:')
# search key word
Keyword = input("Please input keyword for searching: ")
deal_key(Keyword)
print('End！')


import tflite_runtime.interpreter as tflite
import os
import numpy as np
from io import BytesIO
from urllib import request
from PIL import Image

def download_image(url):
    with request.urlopen(url) as resp:
        buffer = resp.read()
    stream = BytesIO(buffer)
    img = Image.open(stream)
    return img

def prepare_image(img, target_size):
    if img.mode != 'RGB':
        img = img.convert('RGB')
    img = img.resize(target_size, Image.NEAREST)
    return img

def prepare_input(x):
    return x / 255.0

interpreter = tflite.Interpreter('vegetables-model.tflite')
interpreter.allocate_tensors()

input_index = interpreter.get_input_details()[0]['index']
output_index = interpreter.get_output_details()[0]['index']

def predict(url):
    img = download_image(url)
    img = prepare_image(img, target_size=(224, 224))

    x = np.array(img, dtype='float32')
    X = np.array([x])
    X = prepare_input(X)

    interpreter.set_tensor(input_index, X)
    interpreter.invoke()

    preds = interpreter.get_tensor(output_index)

    classes = [
        'Bean',
        'Bitter_Gourd',
        'Bottle_Gourd',
        'Brinjal',
        'Broccoli',
        'Cabbage',
        'Capsicum',
        'Carrot',
        'Cauliflower',
        'Cucumber',
        'Papaya',
        'Potato',
        'Pumpkin',
        'Radish',
        'Tomato'
    ]

    return classes[np.argmax(preds)], preds[0][np.argmax(preds)]

def lambda_handler(event, context):
    url = event['url']
    pred, proba = predict(url)
    result = {
        'prediction': pred,
        'probability':float(proba)
    }

    return result


import requests
from bs4 import BeautifulSoup
header = {
    'User-Agent': 'Mozilla/5.0 (MacintoshIntel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'
}

def get_images(url):
    ret = []
    r = requests.get(url=url, headers=header)
    soup = BeautifulSoup(r.content, features="html.parser")
    gallery = soup.find(
        "div", {"class": "GalleryItems-module__searchContent___DbMmK"})
    link = gallery.find_all("a")
    for i in link:
        ret.append((i['href']))
    return ret

def main():
    images = get_images("https://www.gettyimages.in/photos/aamir-khan-actor")
    head = "https://www.gettyimages.in"
    for i in images:
        print(head+i, "\n")

if __name__ == "__main__":
    main()


import os
import glob
import argparse
import numpy as np

class LabelToKittiConverter:
    """ KITTI FORMAT
    #Values    Name      Description
    ----------------------------------------------------------------------------
       1    type         Describes the type of object: 'Car', 'Van', 'Truck',
                         'Pedestrian', 'Person_sitting', 'Cyclist', 'Tram',
                         'Misc' or 'DontCare'
       1    truncated    Float from 0 (non-truncated) to 1 (truncated), where
                         truncated refers to the object leaving image boundaries
       1    occluded     Integer (0,1,2,3) indicating occlusion state:
                         0 = fully visible, 1 = partly occluded
                         2 = largely occluded, 3 = unknown
       1    alpha        Observation angle of object, ranging [-pi..pi]
       4    bbox         2D bounding box of object in the image (0-based index):
                         contains left, top, right, bottom pixel coordinates
       3    dimensions   3D object dimensions: height, width, length (in meters)
       3    location     3D object location x,y,z in camera coordinates (in meters)
       1    rotation_y   Rotation ry around Y-axis in camera coordinates [-pi..pi]
       1    score        Only for results: Float, indicating confidence in
                         detection, needed for p/r curves, higher is better.
    """
    def __init__(self, conversion, labels_fp, gt_labels_fp, csv):
        conversion_dict = self.get_attribute_idx(conversion)
        self.csv = csv
        if labels_fp is not None:
            print("------ Prediction Labels Conversion -------")
            new_labels_fp = (os.path.join(labels_fp, '..',  'pred_labels_kitti/data/'))
            if new_labels_fp[0] == '/':
                new_labels_fp = new_labels_fp[1:]
            os.makedirs(new_labels_fp, exist_ok=True)
            self.convert_to_kitti(conversion_dict, labels_fp, new_labels_fp, pred_labels=True)
        if gt_labels_fp is not None:
            print("------ Ground Truth Labels Conversion -------")
            new_labels_fp = os.path.join(gt_labels_fp, '..',  '/gt_labels_kitti/')
            if new_labels_fp[0] == '/':
                new_labels_fp = new_labels_fp[1:]
            os.makedirs(new_labels_fp, exist_ok=True)
            self.convert_to_kitti(conversion_dict, gt_labels_fp, new_labels_fp, pred_labels=False)

    def convert_to_kitti(self, conversion_key, fp, new_fp, pred_labels=False):
        labels_list = glob.glob(fp + "*")
        for num, example in enumerate(labels_list):
            print("{}/{}\r".format(num+1, len(labels_list)))
            example_idx = os.path.basename(example)
            new_label = self.new_label_from_txt(example, conversion_key, pred=pred_labels)
            if pred_labels:
                np.savetxt(new_fp + example_idx, new_label, delimiter=' ',
                           fmt='%s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s')
            else:
                np.savetxt(new_fp + example_idx, new_label, delimiter=' ',
                           fmt='%s %s %s %s %s %s %s %s %s %s %s %s %s %s %s')

    def new_label_from_txt(self, label_path, idx_key, pred=True):
        classes = []
        trunc = []
        occ = []
        obs = []
        camera_box = []
        score = []
        x, y, z, r = [], [], [], []
        l, w, h = [], [], []
        with open(label_path, "r") as f:
            labels = f.read().split("\n")
            for label in labels:
                if not label:
                    continue
                if self.csv:
                    label = label.replace(" ", "")
                    label = label.split(",")
                else:
                    label = label.replace(",", "")
                    label = label.split(" ")

                if 'class' in idx_key:
                    classes.append(label[idx_key['class']])
                else:
                    classes.append(['Car']) # assume if no class is specified, its a car
                if 'truncated' in idx_key:
                    trunc.append(label[idx_key['truncated']])
                else:
                    trunc.append(0.00)
                if 'occluded' in idx_key:
                    occ = occ.append(label[idx_key['occluded']])
                else:
                    occ.append(0)
                if 'alpha' in idx_key:
                    obs.append(label[idx_key['alpha']])
                else:
                    obs.append(0)
                if 'x1' in idx_key:
                    start, end = idx_key['x1'], idx_key['x1']+4
                    camera_box.append(label[start:end])
                else:
                    camera_box.append((0, 0, 50, 50))
                if 'x' in idx_key:
                    x.append(label[idx_key['x']])
                else:
                    x.append(0)
                if 'y' in idx_key:
                    y.append(label[idx_key['y']])
                else:
                    y.append(0)
                if 'z' in idx_key:
                    z.append(label[idx_key['z']])
                else:
                    z.append(0)
                if 'r' in idx_key:
                    r.append(label[idx_key['r']])
                else:
                    r.append(0)
                if 'l' in idx_key:
                    l.append(label[idx_key['l']])
                else:
                    l.append(0)
                if 'w' in idx_key:
                    w.append(label[idx_key['w']])
                else:
                    w.append(0)
                if 'h' in idx_key:
                    h.append(label[idx_key['h']])
                else:
                    h.append(0)
                if pred:
                    if 'score' in idx_key:
                        score.append(label[idx_key['score']])
        final_array = np.hstack((
            np.array(classes).reshape(-1, 1),
            np.array(trunc).reshape(-1, 1),
            np.array(occ).reshape(-1,1 ),
            np.array(obs).reshape(-1, 1),
            np.array(camera_box),
            np.array(h).reshape(-1, 1),
            np.array(w).reshape(-1, 1),
            np.array(l).reshape(-1, 1),
            np.array(x).reshape(-1, 1),
            np.array(y).reshape(-1, 1),
            np.array(z).reshape(-1, 1),
            np.array(r).reshape(-1, 1)
        ))
        if pred:
            final_array = np.hstack((final_array, np.array(score).reshape(-1, 1)))
        return final_array

    @staticmethod
    def get_attribute_idx(conversion):
        idx_dict = {}
        conversion = conversion.split(" ")
        print("-- Your conversion key --")
        for i, attribute in enumerate(conversion):
            print(i, attribute)
            if attribute == 'class':
                idx_dict['class'] = i
            elif attribute == 'truncated':
                idx_dict['truncated'] = i
            elif attribute == 'occluded':
                idx_dict['occluded'] = i
            elif attribute == 'alpha':
                idx_dict['alpha'] = i
            elif attribute == 'x1':
                idx_dict['x1'] = i # assumes [x1 y1 x2 y2] follows
            elif attribute == 'x':
                idx_dict['x'] = i
            elif attribute == 'y':
                idx_dict['y'] = i
            elif attribute == 'z':
                idx_dict['z'] = i
            elif attribute == 'l':
                idx_dict['l'] = i
            elif attribute == 'w':
                idx_dict['w'] = i
            elif attribute == 'h':
                idx_dict['h'] = i
            elif attribute == 'r':
                idx_dict['r'] = i
            elif attribute == 'score':
                idx_dict['score'] = i
        return idx_dict

def main():
    parser = argparse.ArgumentParser(description='arg parser')
    parser.add_argument('--pred_labels', type=str, help='file path with your prediction labels')
    parser.add_argument('--gt_labels', type=str, help='file path with your ground truth labels')
    parser.add_argument('--format', type=str, help='your label format e.g. "class, x, y, z, l, w, h"', required=True)
    parser.add_argument('--csv', dest='csv', action='store_true', help='is your file csv or space separated')
    args = parser.parse_args()
    print("------ Converting to KITTI Labels -------")
    LabelToKittiConverter(args.format, args.pred_labels, args.gt_labels, csv=args.csv)

if __name__ == '__main__':
    main()


import cv2
import mediapipe as mp

class HandDetector():
    def __init__(self):
        self.hand_detector = mp.solutions.hands.Hands()
        self.drawer = mp.solutions.drawing_utils

    def process(self, img, draw=True):
        img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
        self.hands_data = self.hand_detector.process(img_rgb)
        if draw:
            if self.hands_data.multi_hand_landmarks:
                for handlms in self.hands_data.multi_hand_landmarks:
                    self.drawer.draw_landmarks(img, handlms, mp.solutions.hands.HAND_CONNECTIONS)

    def find_position(self, img):
        h, w, c = img.shape
        self.position = {'Left': {}, 'Right': {}}
        if self.hands_data.multi_hand_landmarks:
            i = 0
            for point in self.hands_data.multi_handedness:
                score = point.classification[0].score
                if score >= 0.8:
                    label = point.classification[0].label
                    hand_lms = self.hands_data.multi_hand_landmarks[i].landmark
                    for id, lm in enumerate(hand_lms):
                        x, y = int(lm.x * w), int(lm.y * h)
                        self.position[label][id] = (x, y)
                i = i + 1
        return self.position

    def fingers_count(self, hand='Left'):
        tips = [4, 8, 12, 16, 20]
        tip_data = {4:0, 8:0, 12:0, 16:0, 20:0}
        for tip in tips:
            ltp1 = self.position[hand].get(tip, None)
            ltp2 = self.position[hand].get(tip-2, None)
            if ltp1 and ltp2:
                if tip == 4:
                    if ltp1[0] > ltp2[0]:
                        if hand == 'Left':
                            tip_data[tip] = 1
                        else:
                            tip_data[tip] = 0
                    else:
                        if hand == 'Left':
                            tip_data[tip] = 0
                        else:
                            tip_data[tip] = 1
                else:
                    if ltp1[1] > ltp2[1]:
                        tip_data[tip] = 0
                    else:
                        tip_data[tip] = 1
        return list(tip_data.values()).count(1)


from django.conf import settings
from django.conf.urls import url, include
from django.conf.urls.static import static
from django.contrib import admin
from django.views.generic import TemplateView
from django.views.static import serve

DEBUG_ID = getattr(settings, 'DEBUG_ID', 'null')
DEBUG_REPORTING_UNIT = getattr(settings, 'DEBUG_REPORTING_UNIT', 'null')

class IndexView(TemplateView):
    template_name = 'index.html'

    def get_context_data(self, **kwargs):
        data = super().get_context_data(**kwargs)
        data['debug_id'] = DEBUG_ID
        data['debug_ru_id'] = DEBUG_REPORTING_UNIT
        return data

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^api/', include('landscapesim.urls')),
    url(r'^maps/', include('ncdjango.urls')),
    url(r'^$', IndexView.as_view()),
    url(r'^downloads/(?P<path>.*)$', serve, {'document_root': settings.DATASET_DOWNLOAD_DIR})
]

if settings.DEBUG:
    # Use Django to serve static files in development
    urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)


"""
Convert the PPMI database to the BIDS format.

We will iterate through each subject, creating a subject directory in the BIDS directory.
The 'anat' and 'func' subdirectories will be created. Then, we will iterate through each
scan type. The name of the scan description, as extracted from the XML metadata file, will
be the acquisition (acq-)label. Within each scan type, we will iterate through the existing
files (using the find utility to acquire a list of files) and construct arrays corresponding
to T1, T2, PD, and Flair scan types. All files containing 'flair' in the file name should be
categorized as Flair; all other files should be categorized according to the weighting as
specified in the metadata file. The arrays only need to consist of the original file paths
since the new files are named according to the BIDS naming scheme. Ensure that the files are
traversed in sorted order. After all files are processed, we will create the new files from
the array. Arrays that contain more than one element will be named with a run index.

There are three types of processed scans: T1-anatomical, T2 in T1-anatomical space, and T2 in
corrected EPI space. The processed scan type can be determined by the 'processedDataLabel'
metadata parameter. For T1-anatomical and T2 in corrected EPI space, the weighting (of the
original image) can be determined by the metadata file. T2 in T1-anatomical scans are derived
from two images, so there will be two weighting parameters in the metadatafile. They should be
labelled as 'inplaneT1' (tentatively).

EDIT: Use file names to determine processed scans, as there are inconsistencies in the metadata files.

There are two types of functional scans: ep2d_bold_rest, ep2d_RESTING_STATE. Using file names, we can
determine if a scan is functional (don't use the metadata file, as there are inconsistencies).
"""

import os, fnmatch, shutil, re, csv

#Open CSV file for writing
csvfile = open('/u/home/e/edwardwa/project-anderson/ppmi/ppmi2bids/scans.csv', 'w')
ppmiwriter = csv.writer(csvfile,quoting=csv.QUOTE_ALL)
ppmiwriter.writerow(['New Scan','Original Scan'])

def copy_files(subj, scan, runs, run_index, scan_list, modality, dest):
    for i in range(len(scan_list)):
        #origfile = re.sub('^.*\/','',scan_list[i]) #Remove full file path
        newfile = 'sub-' + subj + '_acq-' + re.sub('_','-',scan)
        if len(runs) != 1: # More than one run present
            newfile += '_run-' + '{:0>3}'.format(str(run_index+1))

        if len(scan_list) != 1:
            newfile += '_echo-' + '{:0>3}'.format(str(i+1))
        if 'ep2d' in scan:
            ending = '.nii.gz'
        else:
            ending = '.nii'
        newfile += '_' + modality + ending
        os.symlink(scan_list[i], dest + '/' + newfile)
        ppmiwriter.writerow([newfile,scan_list[i]])

def get_xml(subj, scan, filename):
    #Find corresponding XML file
    origfile=re.sub('^.*\/','',filename) #Remove full file path
    match=re.search('_[^_]*_[^_]*$',origfile)
    xml=match.group()
    xml=re.sub('.nii','.xml',xml)
    xml='PPMI_'+ subj + '_' + scan + xml
    return xml

ppmi_dir='/u/home/e/edwardwa/project-anderson/ppmi/PPMI'
bids_dir=ppmi_dir + '_BIDS'

if os.path.isdir(bids_dir):
    print("Removing directory:", bids_dir)
    shutil.rmtree(bids_dir)

print("Making directory:", bids_dir)
os.mkdir(bids_dir)

os.chdir(ppmi_dir)
for subj in os.listdir(os.getcwd()): #Iterate through each directory
    if os.path.isdir(subj):
        #Make subject directory
        subj_dir = bids_dir + '/sub-' + subj
        print("Making directory:", subj_dir)
        os.mkdir(subj_dir)

        #Make 'anat' directory
        anat = subj_dir + '/anat'
        print("Making directory:", anat)
        os.mkdir(anat)

        os.chdir(subj)
        for scan in os.listdir(os.getcwd()): #Iterate through each scan
            os.chdir(scan)
            runs = os.listdir(os.getcwd())
            runs.sort()
            for run_index in range(len(runs)):
                os.chdir(runs[run_index])

                #Get list of NIFTI files
                nifti=[]
                directory = os.getcwd()
                #Correct for functional scans if necessary
                if 'ep2d' in scan:
                    directory = re.sub('PPMI','PPMI_ep2d/PPMI',directory)

                for root,dirs,files in os.walk(directory):
                    for name in files:
                        nifti=nifti+[os.path.join(root,name)]
                if 'ep2d' in scan:
                    nifti=fnmatch.filter(nifti,"*.nii.gz")
                else:
                    nifti=fnmatch.filter(nifti,"*.nii")
                nifti.sort()

                #Check for bad scans
#                for i in nifti:
#                    #print(i)
#                    xml = get_xml(subj, scan, i)
#                    #print(xml)
#                    with open(ppmi_dir+'/'+xml) as f:
#                        catfile = f.readlines()
#                        catfile = fnmatch.filter(catfile, '*subjectIdentifier*')
#                        subj_id = catfile[0]
#                        subj_id = re.sub('^[^>]*>','',subj_id)
#                        subj_id = re.sub('<.*$\n','',subj_id)
#                        if subj_id != subj:
#                            pass
#                            print(xml)

                if 'ep2d' in scan: # Functional scan present
                    #Make 'func' directory
                    func = subj_dir + '/func'
                    if not os.path.isdir(func):
                        print("Making directory:", func)
                        os.mkdir(func)
                        pass

                    copy_files(subj+'_task-rest', scan, runs, run_index, nifti, 'bold', func)

                elif scan in ['T1-anatomical','T2_in_T1-anatomical_space'] or \
                        'corrected' in scan: # Processed scan present
                    if scan == 'T1-anatomical':
                        modality = 'T1w'
                    #elif scan == 'T2_in_T1-anatomical_space':
                    #    modality = 'inplaneT1'
                    else:
                        modality = 'T2w'

                    copy_files(subj, scan, runs, run_index, nifti, modality, anat)

                elif 'flair' in scan.lower():
                    copy_files(subj, scan, runs, run_index, nifti, 'FLAIR', anat)
                    pass

                elif 'mprage' in scan.lower() or 't1' in scan.lower():
                    copy_files(subj, scan, runs, run_index, nifti, 'T1w', anat)
                    pass

                elif 't2' in scan.lower() and not 'pd' in scan.lower():
                    copy_files(subj, scan, runs, run_index, nifti, 'T2w', anat)
                    pass

                else: # Original scan present
                    t1=[]
                    t2=[]
                    pd=[]
                    #Sort scans by type
                    for i in nifti:
                        #Find corresponding XML file
                        xml = get_xml(subj, scan, i)
                        xml_dir = '/u/home/e/edwardwa/project-anderson/ppmi/PPMI_test/PPMI'
                        with open(xml_dir+'/'+xml) as f:
                            catfile=f.readlines()
                            weighting = fnmatch.filter(catfile, '*Weighting*')
                            if len(weighting) != 0:
                                modality = weighting[len(weighting)-1]
                                modality = re.sub('^[^>]*>','',modality)
                                modality = re.sub('<.*$\n','',modality)

                                if modality == 'T1':
                                    t1.append(i)
                                elif modality == 'T2':
                                    t2.append(i)
                                else:
                                    pd.append(i)

                            else:
                                #print(xml)
                                pass

                    copy_files(subj, scan, runs, run_index, t1, 'T1w', anat)
                    copy_files(subj, scan, runs, run_index, t2, 'T2w', anat)
                    copy_files(subj, scan, runs, run_index, pd, 'PD', anat)

                os.chdir('..')
            os.chdir('..')
        os.chdir('..')
csvfile.close()


import torch
from torch import optim
import torch.nn as nn
import torch.nn.functional as F

class SimpleVAE(nn.Module):
    def __init__(self, var_dim):
        super(SimpleVAE, self).__init__()
        assert var_dim in (1,8), 'var_dim must be either 1 or 8'
        self.var_dim = var_dim
        self.fc1 = nn.Linear(2, 32)
        self.enc_mean = nn.Linear(32, 8)
        self.enc_logvar = nn.Linear(32, self.var_dim)
        self.dec_1 = nn.Linear(8, 32)
        self.dec_2 = nn.Linear(32, 2)
        self.mse = nn.MSELoss()

    def encode(self, x):
        h1 = F.relu(self.fc1(x))
        return self.enc_mean(h1), self.enc_logvar(h1)

    def reparameterize(self, mu, logvar):
        std = torch.exp(0.5*logvar)
        eps = torch.randn_like(std)
        return mu + eps*std

    def decode(self, z):
        h3 = F.relu(self.dec_1(z))
        return self.dec_2(h3)

    def forward(self, x):
        mu, logvar = self.encode(x)
        z = self.reparameterize(mu, logvar)
        return self.decode(z), mu, logvar

    def loss_function(self, x_bar, x, mu, logvar):
        '''Calculate the MSE loss and KL loss using input x and the reconscructed output x_bar
        '''
        BATCH_SIZE = len(x_bar)

        if self.training:
            MSE = 0
            for x_bar_sample in x_bar:
                MSE += self.mse(x_bar_sample, x)
            MSE /= len(x_bar)
        else:
            MSE = self.mse(x_bar, x)

        KLD = -0.5 * torch.sum(1 + logvar - mu.pow(2) - logvar.exp())
        KLD /= (BATCH_SIZE * 2)

        return MSE + KLD


import os
import sys
import time
import atexit
from signal import SIGTERM
import subprocess
import pathlib

def init_daemon_env():
    os.chdir('/')
    os.setsid()
    os.umask(0)

def exit_err(msg, status=1):
    print(msg)
    sys.exit(status)

def get_pid(pidfile, default=None):
    try:
        with open(pidfile) as pf:
            return int(pf.read().strip())
    except IOError:
        return default

class Demonio(object):
    #pidfile va a ser el path al programa que se quiere hacer daemon puede ser scrip`t`
    def __init__(self, filename ,pidfile, arg,
                 stdin='/dev/null',
                 stdout='/dev/null',
                 stderr='/dev/null'):
        self.stdin = stdin
        self.stdout = stdout
        self.stderr = stderr
        self.pidfile = pidfile
        self.arg = arg
        self.filename = filename

    def daemonize(self):
        #FORK 1
        try:
            pid = os.fork()
            if pid > 0:
                sys.exit(0)
        except OSError as e:
            exit_err("fork #1 failed: %d (%s)" % (e.errnp, e.strerror))

        #DESACOPLE
        init_daemon_env()

        #FORK2
        try:
            pid = os.fork()
            if pid > 0:
                sys.exit(0)
        except OSError as e:
            exit_err("fork #2 failed: %d (%s)" % (e.errnp, e.strerror))

        #REDIRECCIÓN
        sys.stdout.flush()
        sys.stderr.flush()
        si = open(self.stdin, 'r')
        so = open(self.stdout, 'a+')
        se = open(self.stderr, 'a+')
        os.dup2(si.fileno(), sys.stdin.fileno())
        os.dup2(so.fileno(), sys.stdout.fileno())
        os.dup2(se.fileno(), sys.stderr.fileno())

        #ESCRIBIR EL ARCHIVO PID
        atexit.register(self.delpid)
        pid = str(os.getpid())

        with open("/tmp/calcedaemon/"+self.filename+".pid", 'w+') as f:
            f.write(pid)
        print(pid)

    def delpid(self):
        os.remove("/tmp/calcedaemon/"+self.filename+".pid")

    def start(self):
        #ANTES DE INICIAR CORROBORA SI YA EXISTE EL ARCHIVO PID PARA SABER SI EL DEMONIO YA ESTA CORRIENDO

        if get_pid("/tmp/calcedaemon/"+self.filename+".pid"):
            msg = "El archivo pid %s ya existe. El demonio ya está corriendo"
            exit_err(msg % self.pidfile)

        self.daemonize()
        self.run()

    def stop(self):
        pid = get_pid("/tmp/calcedaemon/"+self.filename+".pid")
        if not pid:
            msg = "El archivo pid %s no existe. El demonio no está corriendo"
            print(msg % self.pidfile)
            return    # not an error in a restart

        try:
            while True:
                os.kill(pid, SIGTERM) #se envia la señal de terminación del proceso
                time.sleep(0.1)
        except OSError as e:
            error = e.strerror
            if 'No such process' in error:                                          #si no se encuentra el archivo pide del proceso activo
                if os.path.exists("/tmp/calcedaemon/"+self.filename+".pid"):   #se verifica si el archivo .pid existe
                    os.remove("/tmp/calcedaemon/"+self.filename+".pid")        #y se elimina
            else:
                exit_err(error)             #log del error

    def restart(self):
        self.stop()
        self.start()

    #función principal del demonio se agrega lo que se desea que el demonio realice
    def run(self):
        raise NotImplementedError

class midemonio(Demonio):
    def run(self):
        try:
            #cmd=[self.pidfile,self.pidfile]
            cmd=[self.pidfile]+self.arg
            os.execvp(cmd[0],cmd)
        except OSError as e:
            print(e)

if __name__ == '__main__':

    #print(sys.argv)
    if len(sys.argv) >= 3:        #calcedaemon.py start path arg1 arg2 arg3
        filepath=os.path.abspath(os.path.expanduser(sys.argv[2]))
        print(filepath)
        filename=pathlib.Path(filepath).name
        print(filename)
        print(sys.argv[3:])
        daemon = midemonio(filename,filepath,sys.argv[3:])
        if 'start' == sys.argv[1]:
            daemon.start()
        elif 'stop' == sys.argv[1]:
            daemon.stop()
        elif 'restart' == sys.argv[1]:
            daemon.restart()
        else:
            print("Comando desconocido")
            sys.exit(2)
        #sys.exit(0)
    else:
        print("modo de uso: %s start|stop|restart nombre_del_demonio" % sys.argv[0])
        #sys.exit(2)


import serial
from NeuroPy import NeuroPy
from time import sleep
import os
import sys

ser = serial.Serial("COM3",9600)
ser1 = serial.Serial("COM5",9600)
#if not ser.isOpen():
#	ser.open()
#print('COM3 is open', ser.isOpen())
#print("hello:"+str(ser.read(1)))

#neuropy = NeuroPy.NeuroPy("COM3",9600)

def attention_callback(attention_value):
    """this function will be called everytime NeuroPy has a new value for attention"""
    print ("Value of attention is: ", attention_value)
    return None

def rawValue_callback(rawValue):
    """this function will be called everytime NeuroPy has a new value for attention"""
    print ("rawValue is: ", rawValue)
    return None

def blink_callback(value):
    print("Blink ", value)

#neuropy.setCallBack("attention", attention_callback)
#neuropy.setCallBack("rawValue", rawValue_callback)
#neuropy.setCallBack("blinkStrength",blink_callback)
#neuropy.start()

try:
    while True:
	    print("i'm running")
	    print("MrESP:"+str(ser.read(1).hex()))
	    print("Mindwave:"+str(ser1.read(1).hex()))
	    sleep(0.2)
finally:
    neuropy.stop()


import sys
from copy import deepcopy
from collections import deque
input = sys.stdin.readline

n, m = map(int, input().split()) # 격자 크기, 명령 개수
board = [list(map(int, input().split())) for _ in range(n)]
cloud = [[n-1, 0], [n-1, 1], [n-2, 0], [n-2, 1]]
cloud = deque(cloud)

dx = [0, 0, -1, -1, -1, 0, 1, 1, 1]
dy = [0, -1, -1, 0, 1, 1, 1, 0, -1]

dx2 = [-1, -1, 1, 1]
dy2 = [-1, 1, -1, 1]

move = [list(map(int, input().split())) for _ in range(m)]

for idx in range(m):
    # 구름 이동
    d, s = move[idx]
    new_cloud = deque()
    for i in range(len(cloud)):
        x, y = cloud[i]
        nx = x + dx[d]*s
        ny = y + dy[d]*s

        nx = nx % n
        ny = ny % n

        new_cloud.append([nx, ny])
    cloud = deepcopy(new_cloud)

    # 비가 내림
    for i in range(len(cloud)):
        board[cloud[i][0]][cloud[i][1]] += 1

    # 물의 양 증가
    for i in range(len(cloud)):
        cnt = 0
        x, y = cloud[i]
        for j in range(4):
            nx = x + dx2[j]
            ny = y + dy2[j]
            if(0<=nx<n and 0<=ny<n and board[nx][ny] > 0):
                cnt += 1
        board[x][y] += cnt

    # 구름 생김 + 물 증발
    new_cloud = deque()
    for i in range(n):
        for j in range(n):
            if(board[i][j] >= 2 and not([i, j] in cloud)):
                new_cloud.append([i, j])
                board[i][j] -= 2
    cloud = deepcopy(new_cloud)

result = 0
for i in range(n):
    result += sum(board[i])

print(result)


from datetime import datetime
import numpy as np
import pandas as pd
from pathlib import Path

OUTPUT_PATH = Path('./output/environmental_determinants/built_environment/house_price')
OUTPUT_PATH.mkdir(exist_ok=True, parents=True)

city_lut = pd.read_csv('./city_defination_and_LUTs/city_look_up_table.csv')
city_lut = city_lut[['CityName','CityCode','LTLAName','LTLACode']]

mean_price = pd.read_csv('./house_price/city_mean_all_sales_all_house_types.csv')
median_price = pd.read_csv('./house_price/city_median_all_sales_all_house_types.csv')

mean_price = city_lut.merge(mean_price,left_on='LTLACode', right_on='LTLACode',how='left')
median_price = city_lut.merge(median_price,left_on='LTLACode', right_on='LTLACode',how='left')

city_name_list = []
city_code_list = []
LTLA_name_list = []
LTLA_code_list = []
time_list = []
type_list = []
price_list = []
for _, row in mean_price.iterrows():
    for i in range(len(row.index) - 4):
        city_name_list.append(row['CityName'])
        city_code_list.append(row['CityCode'])
        LTLA_name_list.append(row['LTLAName'])
        LTLA_code_list.append(row['LTLACode'])
        type_list.append('Mean')

        time_list.append(row.index[i+4])
        price_list.append(row[row.index[i+4]])

for _, row in median_price.iterrows():
    for i in range(len(row.index) - 4):
        city_name_list.append(row['CityName'])
        city_code_list.append(row['CityCode'])
        LTLA_name_list.append(row['LTLAName'])
        LTLA_code_list.append(row['LTLACode'])
        type_list.append('Median')

        time_list.append(row.index[i+4])
        price_list.append(row[row.index[i+4]])

house_price = pd.DataFrame({'CityName':city_name_list, 'CityCode':city_code_list,'LTLAName':LTLA_name_list, 'LTLACode':LTLA_code_list, 'Time':time_list, 'Aggregation':type_list, 'Price':price_list})
house_price = house_price.sort_values(['CityCode','LTLACode'], ascending=True)
house_price['Price'] = house_price['Price'].map(lambda x:int(''.join(str(x).split(','))))
house_price.to_csv(OUTPUT_PATH.joinpath('house_price_city.csv'),index=False)


from random import randint
computador = randint(0, 10)
print('Sou seu computador...\nAcabei de pensar e um número entre 0 e 10.')
print('Será que você consegue adivinhar qual foi?')
palpite = int(input('Qual é o seu palpite? '))
contador = 1
while palpite != computador:
    contador += 1
    if palpite > computador:
        print('Menos... Tente mais uma vez.')
        palpite = int(input('Qual é o seu palpite? '))
    else:
        print('Mais... Tente mais uma vez.')
        palpite = int(input('Qual é o seu palpite? '))
print(f'Acertou em {contador} tentativa. Parabéns!')


from pyftpdlib.authorizers import DummyAuthorizer
from pyftpdlib.handlers import FTPHandler
from pyftpdlib.servers import FTPServer

def startServer():
    authorizer = DummyAuthorizer()
    authorizer.add_user('root', 'root', '/data/data/com.hifly.chaquopy/cache/chaquopy/tmp', perm='elradfmw')

    handler = FTPHandler
    handler.authorizer = authorizer

    server = FTPServer(('0.0.0.0', 5005), handler)
    server.serve_forever()


def insertionSort(lista):
    for i in range(1, len(lista)):
        daVez = lista[i]
        k = i
        while k > 0 and int(daVez['dificuldade']) > int(lista[k-1]['dificuldade']):
            lista[k] = lista[k - 1]
            k = k - 1
            lista[k] = daVez
    return lista

num_problemas = int(input())
solucoes = []
problema = {}
for _ in range(num_problemas):
    problema['nome'], problema['solucao'], problema['dificuldade'] = input().split()
    solucoes.append(problema.copy())
    insertionSort(solucoes)

for s in solucoes:
    print(s['solucao'], end='')


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

import os
import uuid
import argparse
import logging
import configparser

import xml.etree.ElementTree as ET
from xml.dom import minidom

from enum import Enum

import codecs
import urllib.parse

# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# Cue
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
class Cue:
    class Type(Enum):
        """
        Most cue types can be inferred:
          MemCue  -> num < 0
          Cue     -> num >=0
          + Loop  -> len > 0.0
        'Type' will be used to annotate extra info when needed.

        Values of Cue, FadeIn, FadeOut and Load identical in RB and TK.
        No Grid cue is available in RB.
        """
        Cue = 0
        FadeIn = 1
        FadeOut = 2
        Load = 3
        Grid = 5

    def __init__(self):
        self.name = ""
        self.start = 0.0
        self.len = 0.0
        self.num = -1
        self.type = Cue.Type.Cue

    def __str__(self):
        return "{} @{} [{}]".format(repr(self.type), self.start, self.num)

# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# Track
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
class Track:
    def __init__(self):
        self.id = ""
        self.name = ""
        self.artist = ""
        self.album = ""
        self.bpm = 120.0
        self.tonality = ""
        self.fileurl = ""
        self.cues = []

    def __str__(self):
        return "{}:\t{} ({}) [{}, {}, {} cues]" \
            .format(self.id, self.name, self.artist,
                    self.tonality, self.bpm, len(self.cues))

# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# Playlist
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
class Playlist:
    class Type(Enum):
        Folder = 0
        List = 1

    def __init__(self):
        self.name = ""
        self.type = Playlist.Type.Folder
        self.children = []

    def __str__(self):
        return self.__str_recursive(0)

    def __str_recursive(self, level):
        s = ""
        if self.type == Playlist.Type.Folder:
            s = "{}[{}]".format(' '*2*level, self.name)
            for c in self.children:
                s = s + "\n" + c.__str_recursive(level + 1)
        elif self.type == Playlist.Type.List:
            s = "{}{} ({} tracks)".format(' '*2*level, self.name, len(self.children))
            # for c in self.children:
            #     s = s + "\n{}- {}".format(' '*2*level, c)
        return s

# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# Library
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
class Library:
    def __init__(self):
        self.track_dict = {}
        self.playl_tree = None

# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# RekordboxReader
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
class RekordboxReader:
    def __init__(self):
        pass

    def read(self, path_xml : str) -> Library:
        l = Library()
        if not os.path.exists(path_xml):
            logging.error("File doesn't exist: {}".format(path_xml))
        else:
            logging.debug("Reading: {}".format(path_xml))
            l.track_dict = self.__parse_tracks(path_xml)
            l.playl_tree = self.__parse_playlists(path_xml)
        return l

    def __parse_tracks(self, path_xml):
        tree = ET.parse(path_xml)
        root = tree.getroot()
        tracks = {}

        coll_elem = root.find('COLLECTION')
        for track_elem in coll_elem.iter('TRACK'):
            a = track_elem.attrib
            t = Track()
            t.id = a['TrackID']
            t.name = a['Name']
            t.artist = a['Artist']
            t.bpm = float(a['AverageBpm'])
            t.tonality = a['Tonality']
            t.fileurl = a['Location']
            t.album = a['Album']

            for mark_elem in track_elem.iter('POSITION_MARK'):
                t.cues.append(self.__make_cue(mark_elem.attrib))

            t.cues.sort(key=lambda c: c.start)
            tracks[t.id] = t

        logging.debug("{} tracks found.".format(len(tracks)))
        return tracks

    def __make_cue(self, cue_dict) -> Cue:
        c = Cue()
        c.start = float(cue_dict['Start'])
        c.len = float(cue_dict['End']) - c.start if 'End' in cue_dict else 0.0
        c.num = int(cue_dict['Num'])
        c.name = cue_dict['Name']
        c.type = Cue.Type.Cue
        return c

    def __parse_playlists(self, path_xml) -> Playlist:
        tree = ET.parse(path_xml)
        root = tree.getroot()
        playl_root = None

        playl_elem = root.find('PLAYLISTS')
        for child in playl_elem:
            playl_root = self.__make_node_recursive(child)

        return playl_root

    def __make_node_recursive(self, node_elem) -> Playlist:
        a = node_elem.attrib
        p = Playlist()
        p.name = a['Name']
        p.type = Playlist.Type.Folder if a['Type'] == "0" else Playlist.Type.List

        for t_e in node_elem: # iterate over children
            if p.type == Playlist.Type.List and t_e.tag == "TRACK":
                p.children.append(t_e.attrib['Key'])
            elif p.type == Playlist.Type.Folder and t_e.tag == "NODE":
                p.children.append(self.__make_node_recursive(t_e))

        return p

# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# TraktorWriter
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
class TraktorWriter:
    def __init__(self):
        self.__sep = "/:"
        pass

    def write(self, lib : Library, path_xml : str):
        root = self.__init_dom()
        root = self.__render_tracks(root, lib)
        root = self.__render_playlists(root, lib)
        self.__write_to_output(path_xml, root)

    def __init_dom(self):
        root = ET.Element("NML", {"VERSION": "19"})
        for e in ["MUSICNODES", "COLLECTION", "PLAYLISTS", "SETS"]:
            ET.SubElement(root, e)
        return root

    def __generate_location(self, fileurl : str) -> dict:
        """
        Generates attribute dictionary for a LOCATION element from a file URL.
        {"DIR": ..., "FILE", ..., "VOLUME": ...}
        """
        url = urllib.parse.urlparse(fileurl)
        path = os.path.normpath(url.path)
        path = urllib.parse.unquote_plus(path)
        tokens = path.split(os.sep)

        locdict = {}
        locdict["VOLUME"] = tokens.pop(1)
        locdict["FILE"] = tokens.pop(-1)
        locdict["DIR"] = self.__sep.join(tokens)
        return locdict

    def __generate_cue(self, cue : Cue) -> dict:
        """
        Generates attribute dictionary for a CUE_V2 element from a file URL.
        {"NAME": ..., "TYPE", ..., "START": ...}
        """
        is_loop = cue.len > 0.0
        is_hot = cue.num > -1

        cuedict = {}
        cuedict["NAME"] = cue.name if cue.name != "" else \
                            "Loop" if is_loop else \
                            "Cue"  if is_hot else "Mem"
        cuedict["DISPL_ORDER"] = "0"
        cuedict["TYPE"] = str("5" if is_loop else cue.type.value)
        cuedict["START"] = str(cue.start*1000.0)
        cuedict["LEN"] = str(cue.len*1000.0)
        cuedict["REPEATS"] = "-1"
        cuedict["HOTCUE"] = str(cue.num)
        return cuedict

    def __generate_info(self, track : Track) -> dict:
        infodict = {}
        infodict["BITRATE"] = "320" # TODO
        infodict["KEY"] = track.tonality
        return infodict

    def __render_tracks(self, root, lib : Library):
        tracks = lib.track_dict.values()
        coll_elem = root.find('COLLECTION')
        coll_elem.attrib["ENTRIES"] = str(len(tracks))

        for t in tracks:
            t_e = ET.SubElement(coll_elem, "ENTRY")
            t_e.attrib['TITLE'] = t.name
            t_e.attrib['ARTIST'] = t.artist

            ET.SubElement(t_e, "LOCATION", self.__generate_location(t.fileurl))
            ET.SubElement(t_e, "ALBUM", {"TITLE": t.album})
            ET.SubElement(t_e, "INFO", self.__generate_info(t))
            ET.SubElement(t_e, "MODIFICATION_INFO", {"AUTHOR_TYPE": "user"})
            ET.SubElement(t_e, "TEMPO", {"BPM_QUALITY": "100",
                                         "BPM": str(t.bpm)})
            for c in t.cues:
                ET.SubElement(t_e, "CUE_V2", self.__generate_cue(c))

        return root

    def __generate_playl_track(self, track_id : str, track_dict : dict) -> dict:
        """
        Generates attribute dictionary for a PRIMARYKEY ENTRY of a PLAYLIST NODE.
        """
        track = track_dict[track_id]
        locdict = self.__generate_location(track.fileurl)
        attrib = {}
        attrib["KEY"] = locdict["VOLUME"] + locdict["DIR"] + self.__sep + locdict["FILE"]
        attrib["TYPE"] = "TRACK"
        return attrib

    def __generate_node_recursive(self, parent, playl : Playlist, track_dict : dict):
        """
        @param parent       Parent DOM node.
        @param playl        Current Playlist node.
        @param track_dict   Track dictionary to render track info.
        @return Modified parent DOM
        """
        node = ET.SubElement(parent, "NODE")
        node.attrib["NAME"] = "$ROOT" if playl.name == "ROOT" else playl.name

        if playl.type == Playlist.Type.Folder:
            node.attrib["TYPE"] = "FOLDER"
            subnode = ET.SubElement(node, "SUBNODES", {"COUNT": str(len(playl.children))})
            for c in playl.children:
                self.__generate_node_recursive(subnode, c, track_dict)
        elif playl.type == Playlist.Type.List:
            node.attrib["TYPE"] = "PLAYLIST"
            playlist = ET.SubElement(node, "PLAYLIST",
                                     {"ENTRIES": str(len(playl.children)),
                                      "TYPE": "LIST",
                                      "UUID": "/db/Playlist/" + str(uuid.uuid4())})
            for c in playl.children:
                entry = ET.SubElement(playlist, "ENTRY")
                ET.SubElement(entry, "PRIMARYKEY", self.__generate_playl_track(c, track_dict))

        return node

    def __render_playlists(self, root, lib : Library):
        if lib.playl_tree is not None:
            playl_elem = root.find('PLAYLISTS')
            self.__generate_node_recursive(playl_elem, lib.playl_tree, lib.track_dict)
        return root

    def __write_to_output(self, xml_path, root):
        xmlstr = minidom.parseString(ET.tostring(root)).toprettyxml(indent="  ")
        with codecs.open(xml_path, "w", "utf-8") as f:
            if f.write(xmlstr) is None:
                logging.info("Wrote output to file: {}".format(xml_path))
            else:
                logging.error("Failed to write to location: {}".format(xml_path))

# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
#
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #

class OptionalOperations:
    def __init__(self, config):
        self.config = config
        pass

    def apply(self, lib : Library) -> Library:
        lib.track_dict = self.__tk_add_grid_marker(lib.track_dict)
        lib.track_dict = self.__tk_assign_all_cues(lib.track_dict)
        return lib

    def __tk_add_grid_marker(self, tracks : dict) -> dict:
        if self.config.getboolean("Options", "GridMakerFromCue", fallback=False):
            for tid in tracks:
                t = tracks[tid]
                if len(t.cues) > 0:
                    gridcue = Cue()
                    gridcue.start = t.cues[0].start
                    gridcue.type = Cue.Type.Grid
                    gridcue.name = "Grid"
                    t.cues.insert(0, gridcue)
                    tracks[tid] = t
        return tracks

    def __tk_assign_all_cues(self, tracks : dict) -> dict:
        num = self.config.getint("Options", "AssignMemCueToPad", fallback=-1)
        if num > -1:
            for tid in tracks:
                t = tracks[tid]
                for i in range(0, len(t.cues)):
                    if t.cues[i].num < 0 and t.cues[i].type != Cue.Type.Grid:
                        t.cues[i].num = num
        return tracks

# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# main
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
if __name__ == "__main__":

    ''' Args '''
    parser = argparse.ArgumentParser(
                    prog='rb2tk.py',
                    description='Convert a rekordbox XML library into a '
                                'Traktor Pro 3 NML collection.',
                    epilog='For more info: github.com/martinbloedorn')

    parser.add_argument('RekordboxXmlInput', nargs='?', default=None,
                        help="Path to rekordbox XML library export.")
    parser.add_argument('TraktorNmlOutput', nargs='?', default=None,
                        help="Output path of generated Traktor NML collection.")
    parser.add_argument('-c', '--conf', action='store', default="rb2tk.ini")
    parser.add_argument('-v', '--verbose', action='count', default=0)

    args = parser.parse_args()

    ''' Logging '''
    logging.basicConfig(format='%(levelname)s @ %(funcName)s: %(message)s')
    levels = [logging.WARNING, logging.INFO, logging.DEBUG]
    logging.getLogger().setLevel(levels[min(args.verbose, len(levels)-1)])

    ''' Config '''
    config = configparser.ConfigParser()
    config.read(args.conf)

    if args.RekordboxXmlInput is not None:
        config["Library"]["RekordboxXmlInput"] = args.RekordboxXmlInput
    elif not config.has_option("Library", "RekordboxXmlInput"):
        config["Library"]["RekordboxXmlInput"] = "rekordbox.xml"

    if args.TraktorNmlOutput is not None:
        config["Library"]["TraktorNmlOutput"] = args.TraktorNmlOutput
    elif not config.has_option("Library", "TraktorNmlOutput"):
        config["Library"]["TraktorNmlOutput"] = "collection.nml"

    ''' Main '''
    rr = RekordboxReader()
    tw = TraktorWriter()
    oo = OptionalOperations(config)

    lib = rr.read(config["Library"]["RekordboxXmlInput"])
    lib = oo.apply(lib)
    tw.write(lib, config["Library"]["TraktorNmlOutput"])


import numpy as np
from torchvision import datasets, transforms
from .imagenetcls import ImageNetClsDataset
from PIL import Image

from io import BytesIO
import cv2

def disk(radius, alias_blur=0.1, dtype=np.float32):
    if radius <= 8:
        L = np.arange(-8, 8 + 1)
        ksize = (3, 3)
    else:
        L = np.arange(-radius, radius + 1)
        ksize = (5, 5)
    X, Y = np.meshgrid(L, L)
    aliased_disk = np.array((X ** 2 + Y ** 2) <= radius ** 2, dtype=dtype)
    aliased_disk /= np.sum(aliased_disk)

    # supersample disk to antialias
    return cv2.GaussianBlur(aliased_disk, ksize=ksize, sigmaX=alias_blur)

def shotnoise(x, severity=1):
    c = [500, 250, 100, 75, 50][severity - 1]

    x = np.array(x) / 255.
    return np.clip(np.random.poisson(x * c) / c, 0, 1) * 255

def defocusblur(x, severity=1):
    c = [(0.3, 0.4), (0.4, 0.5), (0.5, 0.6), (1, 0.2), (1.5, 0.1)][severity - 1]

    x = np.array(x) / 255.
    kernel = disk(radius=c[0], alias_blur=c[1])

    channels = []
    for d in range(3):
        channels.append(cv2.filter2D(x[:, :, d], -1, kernel))
    channels = np.array(channels).transpose((1, 2, 0))  # 3x32x32 -> 32x32x3

    return np.clip(channels, 0, 1) * 255

def jpeg(x, severity=1):
    c = [80, 65, 58, 50, 40][severity - 1]

    output = BytesIO()
    x.save(output, 'JPEG', quality=c)
    x = Image.open(output)

    return x

class ImageShuffler:
    # set seed=None to use default random state
    def __init__(self, mode, ny, nx, h=32, w=32, seed=42):
        assert h % ny == 0, 'h should be divisible by ny'
        assert w % nx == 0, 'w should be divisible by nx'
        self.mode = mode
        self.ny, self.nx = ny, nx
        self.h, self.w = h, w
        dy, dx = h // ny, w // nx
        p = np.empty([h, w], dtype=np.int32)
        r = np.arange(h * w).reshape(h, w)
        if mode == 'glo':
            q = np.random.RandomState(seed).permutation(ny * nx).reshape(ny, nx)
            for y in range(ny):
                for x in range(nx):
                    z = q[y, x]
                    v, u = z // nx, z % nx
                    p[y*dy:(y+1)*dy, x*dx:(x+1)*dx] = r[v*dy:(v+1)*dy, u*dx:(u+1)*dx]
        elif mode == 'loc':
            q = np.random.RandomState(seed).permutation(dy * dx)
            for y in range(ny):
                for x in range(nx):
                    v, u = y, x
                    p[y*dy:(y+1)*dy, x*dx:(x+1)*dx] = r[v*dy:(v+1)*dy, u*dx:(u+1)*dx].reshape(-1)[q].reshape(dy,dx)
        self.p = p.reshape(-1)
        self.p_inv = np.empty(h*w, dtype=np.int32)
        self.p_inv[self.p] = r.reshape(-1)

    # img: shape (h,w,c)
    def apply_one(self, img):
        s = img.shape
        assert len(s) == 3 and s[0] == self.h and s[1] == self.w
        return img.reshape(-1, s[-1])[self.p].reshape(s)

    # imgs: shape (n,h,w,c)
    def apply_batch(self, imgs):
        s = imgs.shape
        assert len(s) == 4
        if s[1] == self.h and s[2] == self.w:
            return imgs.reshape(s[0], -1, s[-1])[:, self.p].reshape(s)
        elif s[2] == self.h and s[3] == self.w:
            return imgs.reshape(s[0], s[1], -1)[:, :, self.p].reshape(s)

    def invert_one(self, img):
        s = img.shape
        return img.reshape(-1, s[-1])[self.p_inv].reshape(s)

    def invert_batch(self, imgs):
        s = imgs.shape
        return imgs.reshape(s[0], -1, s[-1])[:, self.p_inv].reshape(s)

def gamma_distortion_uint8(x, gamma):
    # print(x.dtype, x.shape, x.min(), x.max())  # uint8, (50000, 32, 32, 3) 0 255
    assert x.dtype == np.uint8
    return (255.*((x/255.)**gamma)).astype(np.uint8)

def corrupt_dataset(DatasetClass, corrupt):
    corrupt = corrupt.split('_')

    # if not corrupt or (corrupt.startswith('ori') and not resize):
    #     return DatasetClass
    # if not resize:
    if DatasetClass is datasets.CIFAR10 or DatasetClass is datasets.CIFAR100:
        image_size = 32

        class CorruptedDataset(DatasetClass):
            def __init__(self, *args, transform=None, **kwargs):
                super().__init__(*args, **kwargs)
                resize = transforms.Resize((image_size, image_size))
                # transform = transforms.Compose([transforms.ToTensor(),
                #                                 transforms.Normalize(mean=(0.4914, 0.4822, 0.4465), std=(0.247, 0.2435, 0.2616))])
                if corrupt[0] == 'glo' or corrupt[0] == 'loc':
                    shuf = ImageShuffler(corrupt[0], ny=int(corrupt[1]), nx=int(corrupt[1]), h=image_size, w=image_size)
                    def aug_func(x):
                        x = resize(x)
                        x = np.asarray(x)
                        x = shuf.apply_one(x)
                        x = Image.fromarray(x)
                        if transform is not None: x = transform(x)
                        return x
                elif corrupt[0] == 'randglo' or corrupt[0] == 'randloc':
                    def aug_func(x):
                        shuf = ImageShuffler(corrupt[0][-3:], ny=int(corrupt[1][-3:]), nx=int(corrupt[1][-3:]), h=image_size, w=image_size, seed=None)
                        x = resize(x)
                        x = np.asarray(x)
                        x = shuf.apply_one(x)
                        x = Image.fromarray(x)
                        if transform is not None: x = transform(x)
                        return x
                elif corrupt[0] == 'gam':
                    def aug_func(x):
                        x = resize(x)
                        x = np.asarray(x)
                        x = gamma_distortion_uint8(x, gamma=float(corrupt[1]))
                        x = Image.fromarray(x)
                        if transform is not None: x = transform(x)
                        return x
                elif corrupt[0] == 'ori':
                    def aug_func(x):
                        x = resize(x)
                        if transform is not None: x = transform(x)
                        return x
                else:
                    def aug_func(x):
                        x = resize(x)
                        x = eval(corrupt[0])(x, 3)
                        x = Image.fromarray(np.uint8(x))
                        if transform is not None: x = transform(x)
                        return x
                self.transform = aug_func

        return CorruptedDataset

    elif DatasetClass is datasets.STL10:
        image_size = 96
    elif DatasetClass is ImageNetClsDataset:
        image_size = 256

        class CorruptedDataset(DatasetClass):
            def __init__(self, *args, transform=None, **kwargs):
                super().__init__(*args, **kwargs)
                resize = transforms.Resize((image_size, image_size))
                if corrupt[0] == 'glo' or corrupt[0] == 'loc':
                    shuf = ImageShuffler(corrupt[0], ny=int(corrupt[1]), nx=int(corrupt[1]), h=image_size, w=image_size)
                    def aug_func(x):
                        x = resize(x)
                        x = np.asarray(x)
                        x = shuf.apply_one(x)
                        x = Image.fromarray(x)
                        if transform is not None: x = transform(x)
                        return x
                elif corrupt[0] == 'gam':
                    def aug_func(x):
                        x = resize(x)
                        x = np.asarray(x)
                        x = gamma_distortion_uint8(x, gamma=float(corrupt[1]))
                        x = Image.fromarray(x)
                        if transform is not None: x = transform(x)
                        return x
                else:
                    def aug_func(x):
                        x = resize(x)
                        x = eval(corrupt[0])(x, 3)
                        x = Image.fromarray(np.uint8(x))
                        if transform is not None: x = transform(x)
                        return x
                self.transform = aug_func

        return CorruptedDataset

    else:
        raise ValueError(f'unsupported {DatasetClass}')
    # else:
    #    image_size = resize

    class CorruptedDataset(DatasetClass):
        def __init__(self, *args, **kwargs):
            super().__init__(*args, **kwargs)
            # if resize:
            #     self.data = torch.nn.functional.interpolate(
            #         torch.as_tensor(self.data, dtype=torch.float32), [image_size, image_size], mode='bicubic').numpy()
            if corrupt[0] == 'glo' or corrupt[0] == 'loc':
                shuf = ImageShuffler(corrupt[0], ny=int(corrupt[1]), nx=int(corrupt[1]), h=image_size, w=image_size)
                self.data = shuf.apply_batch(self.data)
            elif corrupt[0] == 'gam':
                self.data = gamma_distortion_uint8(self.data, gamma=float(corrupt[1]))

    return CorruptedDataset


import os
import time
import bzrlib

from bzrlib.tests import TestCaseWithTransport
from bzrlib.xml_serializer import elementtree as elementtree
fromstring = elementtree.fromstring

class TestXmlAnnotate(TestCaseWithTransport):

    def setUp(self):
        super(TestXmlAnnotate, self).setUp()
        self.wt = self.make_branch_and_tree('.')
        b = self.wt.branch
        self.build_tree_contents([('hello.txt', 'my helicopter\n'),
                                  ('nomail.txt', 'nomail\n')])
        self.wt.add(['hello.txt'])
        self.revision_id_1 = self.wt.commit('add hello',
                              committer='test@user',
                              timestamp=1165960000.00, timezone=0)
        self.wt.add(['nomail.txt'])
        self.revision_id_2 = self.wt.commit('add nomail',
                              committer='no mail',
                              timestamp=1165970000.00, timezone=0)
        self.build_tree_contents([('hello.txt', 'my helicopter\n'
                                                'your helicopter\n')])
        self.revision_id_3 = self.wt.commit('mod hello',
                              committer='user@test',
                              timestamp=1166040000.00, timezone=0)
        self.build_tree_contents([('hello.txt', 'my helicopter\n'
                                                'your helicopter\n'
                                                'all of\n'
                                                'our helicopters\n'
                                  )])
        self.revision_id_4 = self.wt.commit('mod hello',
                              committer='user@test',
                              timestamp=1166050000.00, timezone=0)
        self.time_revision_id_1 = date_str = time.strftime('%Y%m%d',
                                     time.gmtime(1165960000.00))
        self.time_revision_id_2 = date_str = time.strftime('%Y%m%d',
                                     time.gmtime(1165970000.00))
        self.time_revision_id_3 = date_str = time.strftime('%Y%m%d',
                                     time.gmtime(1166040000.00))
        self.time_revision_id_4 = date_str = time.strftime('%Y%m%d',
                                     time.gmtime(1166050000.00))

    def test_help_xmlannotate(self):
        """XmlAnnotate command exists"""
        out, err = self.run_bzr('xmlannotate --help')

    def test_xmlannotate_cmd(self):
        out, err = self.run_bzr('xmlannotate hello.txt')
        wt_root_path = self.wt.id2abspath(self.wt.get_root_id())
        expected_xml = (''.join(['<?xml version="1.0"?>',
                        '<annotation workingtree-root="%s" file="hello.txt">',
                        '<entry revno="1" author="test@user" date="%s">my helicopter</entry>',
                        '<entry revno="3" author="user@test" date="%s">your helicopter</entry>',
                        '<entry revno="4" author="user@test" date="%s">all of</entry>',
                        '<entry revno="4" author="user@test" date="%s">our helicopters</entry>',
                        '</annotation>\n',]) %
                        (wt_root_path, self.time_revision_id_1, self.time_revision_id_3,
                         self.time_revision_id_4, self.time_revision_id_4))
        #TODO: assert xml and elementree (including attributes)
        self.assertEqual('', err)
        self.assertEqualDiff(expected_xml, out)
        expected_elementtree = fromstring(expected_xml)
        current_elementtree = fromstring(out)
        self.assertEquals(elementtree.tostring(expected_elementtree),
                elementtree.tostring(current_elementtree))

    def test_xmlannotate_cmd_show_ids(self):
        out, err = self.run_bzr('xmlannotate hello.txt --show-ids')
        wt_root_path = self.wt.id2abspath(self.wt.get_root_id())

        expected_xml = (''.join(['<?xml version="1.0"?>',
                                '<annotation workingtree-root="%s" file="hello.txt">',
                                '<entry revno="1" author="test@user" date="%s"',
                                ' fid="%s">my helicopter</entry>',
                                '<entry revno="3" author="user@test" date="%s"',
                                ' fid="%s">your helicopter</entry>',
                                '<entry revno="4" author="user@test" date="%s"',
                                ' fid="%s">all of</entry>',
                                '<entry revno="4" author="user@test" date="%s"',
                                ' fid="%s">our helicopters</entry>',
                                '</annotation>\n',]) %
                                (wt_root_path,
                                self.time_revision_id_1, self.revision_id_1,
                                self.time_revision_id_3, self.revision_id_3,
                                self.time_revision_id_4, self.revision_id_4,
                                self.time_revision_id_4, self.revision_id_4))
        #TODO: assert xml and elementree (including attributes)
        max_len = max([len(self.revision_id_1),
                       len(self.revision_id_3),
                       len(self.revision_id_4)])
        self.assertEqual('', err)
        self.assertEqualDiff(expected_xml, out)
        #        self.assertEqualDiff('''\
        #%*s | my helicopter
        #%*s | your helicopter
        #%*s | all of
        #%*s | our helicopters
        #''' % (max_len, self.revision_id_1,
        #max_len, self.revision_id_3,
        #max_len, self.revision_id_4,
        #max_len, '',
        #)
        #, out)

    def test_no_mail(self):
        out, err = self.run_bzr('xmlannotate nomail.txt')
        wt_root_path = self.wt.id2abspath(self.wt.get_root_id())
        expected_xml = (''.join(['<?xml version="1.0"?>',
                        '<annotation workingtree-root="%s" file="nomail.txt">',
                        '<entry revno="2" author="no mail" date="%s">nomail</entry>',
                        '</annotation>\n']) % (wt_root_path, self.time_revision_id_2))
        #TODO: assert xml and elementree (including attributes)
        self.assertEqual('', err)
        self.assertEqualDiff(expected_xml, out)
        #        self.assertEqualDiff('''\
        #2   no mail | nomail
        #''', out)

    def test_xmlannotate_cmd_revision(self):
        out, err = self.run_bzr('xmlannotate hello.txt -r1')
        wt_root_path = self.wt.id2abspath(self.wt.get_root_id())
        expected_xml = (''.join(['<?xml version="1.0"?>',
                                '<annotation workingtree-root="%s" file="hello.txt">',
                                '<entry revno="1" author="test@user" date="%s">my helicopter</entry>',
                                '</annotation>\n']) % (wt_root_path,
                                                    self.time_revision_id_1))
        #TODO: assert xml and elementree (including attributes)
        self.assertEqual('', err)
        self.assertEqualDiff(expected_xml, out)
        #self.assertEqualDiff('''\
        #1   test@us | my helicopter
        #''', out)

    def test_xmlannotate_cmd_revision3(self):
        out, err = self.run_bzr('xmlannotate hello.txt -r3')
        wt_root_path = self.wt.id2abspath(self.wt.get_root_id())
        expected_xml = (''.join(['<?xml version="1.0"?>',
                                '<annotation workingtree-root="%s" file="hello.txt">',
                                '<entry revno="1" author="test@user" date="%s">my helicopter</entry>',
                                '<entry revno="3" author="user@test" date="%s">your helicopter</entry>',
                                '</annotation>\n'])  % (wt_root_path,
                                                     self.time_revision_id_1,
                                                     self.time_revision_id_3))
        #TODO: assert xml and elementree (including attributes)
        self.assertEqual('', err)
        self.assertEqualDiff(expected_xml, out)
        #        self.assertEqualDiff('''\
        #1   test@us | my helicopter
        #3   user@te | your helicopter
        #''', out)

    def test_xmlannotate_cmd_unknown_revision(self):
        out, err = self.run_bzr('xmlannotate hello.txt -r 10',
                                retcode=3)
        self.assertEqual('', out)
        self.assertContainsRe(err, 'Requested revision: \'10\' does not exist')

    def test_xmlannotate_cmd_two_revisions(self):
        out, err = self.run_bzr('xmlannotate hello.txt -r1..2',
                                retcode=3)
        self.assertEqual('', out)
        self.assertEqual('<?xml version="1.0" encoding="%s"?><error><class>'
                'BzrCommandError</class><dict><key>_preformatted_string</key><value>xmlannotate'
                ' --revision takes exactly 1 argument</value></dict><message>'
                'xmlannotate --revision takes exactly 1 argument</message>'
                '</error>' % bzrlib.osutils.get_user_encoding(), err)

    def test_xmlannotate_empty_file(self):
        tree = self.make_branch_and_tree('tree')
        self.build_tree_contents([('tree/empty', '')])
        tree.add('empty')
        tree.commit('add empty file')

        os.chdir('tree')
        out, err = self.run_bzr('xmlannotate empty')
        wt_root_path = self.wt.id2abspath(self.wt.get_root_id())
        #TODO: assert xml and elementree (including attributes)'
        expected_xml = (''.join(['<?xml version="1.0"?>',
                                '<annotation workingtree-root="%s" file="empty">',
                                '</annotation>\n']) % (wt_root_path+'tree/',))
        self.assertEqual(expected_xml, out)

    def test_xmlannotate_nonexistant_file(self):
        tree = self.make_branch_and_tree('tree')
        self.build_tree(['tree/file'])
        tree.add(['file'])
        tree.commit('add a file')

        os.chdir('tree')
        out, err = self.run_bzr("xmlannotate doesnotexist", retcode=3)
        self.assertEqual('', out)
        self.assertContainsRe(err, '<error><class>NotVersionedError.*'
                '<dict><key>path.*<value>doesnotexist'
                '.*<message>doesnotexist is not versioned.</message></error>')


from mock import Mock, patch, ANY, sentinel
from nose.tools import ok_, eq_, raises

from operant.base import Registry

class RegObject(object):
    def __init__(self, name):
        self.name = name

class TestRegistry(object):

    @property
    def _reg(self):
        return Registry("testing", "name")

    @raises(RuntimeError)
    def test_register_existing(self):
        a = RegObject("foo")
        b = RegObject("foo")
        reg = self._reg
        reg.register(a)
        # This line should raise
        reg.register(b)

    def test_register(self):
        reg = self._reg
        a = RegObject("bar")
        reg.register(a)
        eq_(reg.get("bar"), a)

    def test_get_none(self):
        eq_(self._reg.get("__not__valid__"), None)

    def _handler_res(self):
        m = Mock()
        m.name = "handler_res"
        return m

    def test_str_handler(self):
        reg = self._reg

        res = self._handler_res()
        handler = Mock(return_value=res)

        reg.set_str_handler(handler)

        reg.register("whatever")
        handler.assert_called_once_with("whatever")
        eq_(reg.get("handler_res"), res)

    def test_cust_handler(self):
        reg = self._reg

        res = self._handler_res()
        handler = Mock(return_value=res)

        class Foo(object):
            name = "Foo"
        reg.set_handler(Foo, handler)

        foo = Foo()
        reg.register(foo)

        handler.assert_called_once_with(foo)
        eq_(reg.get("handler_res"), res)


import streamlit as st

from front.model_controller import get_event_push

def rest_alert(default_current_time):
    st.header("기사님 휴식 푸시 메세지")

    # st.image('resources/weather_alert_flow.png')

    current_time = st.text_input("시간 설정", default_current_time)

    # 버튼 클릭 여부 확인
    if st.button("모델 예측", key="rest_alert"):
        with st.spinner("Loading..."):
            recommend_result = get_event_push(event_type="장시간 근무 알람", current_time=current_time)
            st.write(recommend_result)


TESTES,NOTAS,REPO,FINAL,ALT = int(input()),[],[],[],0
for x in range(TESTES):
    NOTAS.append(float(input()))
for i in range(TESTES):
    REPO.append(float(input()))
for j in range(TESTES):
    if NOTAS[j] == REPO[j] or REPO[j] == 0 or REPO[j] < 10: FINAL.append(NOTAS[j])
    if NOTAS[j] < REPO[j] and REPO[j] == 10:
        FINAL.append(NOTAS[j]+2)
        ALT += 1
for m in range(TESTES):
    if FINAL[m] > 10: FINAL[m] = 10
print("NOTAS ALTERADAS: {}".format(ALT))
for F in range(TESTES):
    if NOTAS[F] == FINAL[F]:print("-(00{}) original: {:05.2f} | final: {:05.2f}".format(F+1,NOTAS[F],FINAL[F]))
    else:print("*(00{}) original: {:05.2f} | final: {:05.2f}".format(F+1,NOTAS[F],FINAL[F]))


from skimage.transform import rescale
import matplotlib.pyplot as plt

# Loading the image using Matplotlib
image = plt.imread('garden.jpg')

#Rescale the image to be 1/4
image_rescaled = rescale(image, 1/4, anti_aliasing=True, multichannel=True)

def show_image(image, title):
    plt.imshow(image)
    plt.title(title)
    plt.axis('off')
    plt.show()

show_image(image, 'orginal')
show_image(image_rescaled, 'Rescale image')