from heuristics.Config import Config
from heuristics.InputTW import InputTW
from heuristics.Schedule import Schedule
import numpy as np
import random
import constants as c
import copy
from heuristics.RandomizedCS import RandomizedCS
from heuristics.RandomizedCSbeforeafter import RandomizedCSbeforeafter
from heuristics.RandomizedtiesCS import RandomizedtiesCS
from heuristics.RandomizedSearch import RandomizedSearch
from heuristics.RandomizedtiesCSnomaxduration import RandomizedtiesCSnomaxduration
from heuristics.RandomizedCSnomaxduration import RandomizedCSnomaxduration

class RandomizedSearchAndFixContinuous:

    def __init__(self, input: InputTW, config: Config, input_trucks=None, sorted_shipments_tw=None):
        self.input = input
        self.config = config
        self.input_trucks = input_trucks
        self.shipments_tw = input.shipments_tw
        self.sorted_shipments_tw = sorted_shipments_tw

    def get_solution_old(self, number_of_iterations):
        self.shipments_tw = sorted(self.shipments_tw, key=lambda shipment_tw: shipment_tw.latest_start_time)
        cs = RandomizedCSnomaxduration(input=self.input, config=self.config, input_trucks=self.input_trucks,
                                       sorted_shipments_tw=self.shipments_tw)
        initial_solution: Schedule = cs.get_solution()
        best_solution = initial_solution
        best_score = initial_solution.get_costs_without_feasibility()
        splittable_trucks = best_solution.get_splittable_trucks()
        efficient_trucks = best_solution.get_efficient_trucks()
        fixed_trucks = splittable_trucks + efficient_trucks
        shipments_tbd = exclude_truck_shipments_from_list(fixed_trucks, self.shipments_tw)
        print(len(shipments_tbd))
        for i in range(number_of_iterations):
            number_of_fixed_trucks = len(fixed_trucks)
            new_cs = RandomizedCSnomaxduration(input=self.input, config=self.config, input_trucks=None,
                                               sorted_shipments_tw=shipments_tbd)
            new_solution: Schedule = new_cs.get_solution()
            new_solution.post_improve_depots()
            splittable_trucks = new_solution.get_splittable_trucks()
            efficient_trucks = new_solution.get_efficient_trucks()
            if len(splittable_trucks) + len(efficient_trucks) > 0:
                print(number_of_fixed_trucks, ' fixed trucks: ')
                print([truck.id for truck in splittable_trucks])
                print([truck.id for truck in efficient_trucks])
                print('shipments to plan: ', len(shipments_tbd))
            fixed_trucks += splittable_trucks + efficient_trucks
            shipments_tbd = exclude_truck_shipments_from_list(new_solution.get_splittable_trucks() + new_solution.get_efficient_trucks(),
                                                                        shipments_tbd)
            print(new_solution.get_total_costs())
            if len(new_solution.get_splittable_trucks() + new_solution.get_efficient_trucks()) >= len(fixed_trucks):
                if len(new_solution.get_splittable_trucks() + new_solution.get_efficient_trucks()) > number_of_fixed_trucks:
                    best_solution = new_solution
                    best_score = new_solution.get_costs_without_feasibility()
                    print(best_score)
                elif new_solution.get_costs_without_feasibility() < best_score:
                    best_solution = new_solution
                    best_score = new_solution.get_costs_without_feasibility()
                    print(best_score)

        return best_solution, fixed_trucks

    def get_many_splittable_trucks(self, number_of_iterations):
        self.shipments_tw = sorted(self.shipments_tw, key=lambda shipment_tw: shipment_tw.latest_start_time)
        cs = RandomizedCSnomaxduration(input=self.input, config=self.config, input_trucks=self.input_trucks,
                                       sorted_shipments_tw=self.shipments_tw)
        initial_solution: Schedule = cs.get_solution()
        splittable_trucks = initial_solution.get_splittable_trucks()
        shipments_tbd = exclude_truck_shipments_from_list(splittable_trucks, self.shipments_tw)
        print(len(shipments_tbd))
        for i in range(number_of_iterations):
            new_cs = RandomizedCSnomaxduration(input=self.input, config=self.config, input_trucks=None,
                                               sorted_shipments_tw=shipments_tbd)
            new_solution: Schedule = new_cs.get_solution()
            new_splittable_trucks = new_solution.get_splittable_trucks()
            if len(new_splittable_trucks) > 0:
                splittable_trucks += new_splittable_trucks
                number_of_splittable_trucks = len(splittable_trucks)
                print(number_of_splittable_trucks, ' fixed trucks: ')
                print([truck.id for truck in splittable_trucks])
                shipments_tbd = exclude_truck_shipments_from_list(new_splittable_trucks, shipments_tbd)
                print('shipments to plan: ', len(shipments_tbd))

        return splittable_trucks

    def get_solution(self, max_number_of_iterations):
        self.shipments_tw = sorted(self.shipments_tw, key=lambda shipment_tw: (shipment_tw.latest_start_time, shipment_tw.latest_start_time - shipment_tw.earliest_start_time))
        shipments_tbd = self.shipments_tw
        print(len(shipments_tbd))
        trucks = []
        i = 0
        while len(shipments_tbd) > 0 and i < max_number_of_iterations:
            new_cs = RandomizedtiesCS(input=self.input, config=self.config, input_trucks=None,
                                               sorted_shipments_tw=shipments_tbd)
            new_solution: Schedule = new_cs.get_solution()
            new_trucks = []
            print('\n', 'ROUND ', i+1)
            for truck in new_solution.get_trucks():
                accept_probability = accept_probability_generator(iteration=i+1, cost_truck=truck.get_total_costs())
                rand = random.random()
                if rand < accept_probability:
                    accept = True
                else:
                    accept = False
                if accept:
                    new_trucks.append(truck)
                print('for truck cost ', truck.get_total_costs(), ' we have prob: ', accept_probability, 'is accepted: ', accept)
            if len(new_trucks) > 0:
                trucks += new_trucks
                shipments_tbd = exclude_truck_shipments_from_list(new_trucks, shipments_tbd)
                print('shipments to plan: ', len(shipments_tbd))
            i += 1

        return trucks

def exclude_truck_shipments_from_list(trucks, shipments):
    return list(filter(
        lambda shipment_tw: shipment_tw.id not in flatten(list(
            map(lambda truck: list(map(lambda shipment: shipment.id, truck.shipments)),
                trucks))),
        shipments))

def flatten(list_of_lists):
    if len(list_of_lists) == 0:
        return list_of_lists
    if isinstance(list_of_lists[0], list):
        return flatten(list_of_lists[0]) + flatten(list_of_lists[1:])
    return list_of_lists[:1] + flatten(list_of_lists[1:])

def accept_probability_generator(iteration, cost_truck):
    if cost_truck == c.fixed_cost_new_truck:
        probability = 1
    else:
        probability = np.exp(-(cost_truck-c.fixed_cost_new_truck)/(0.7*iteration))
    return probability


name = "Muditha Hakmana"
age = "20"
new = True

print(f"patient name {name} and the age is {age} years old. And he is a new {new}")

num1 = float(input("enter a number"))
num2 = float(input("enter the second number"))

sum= num1+num2
print(sum)

weight = float(input("what is your weight"))
type = str.upper(input("kg or l"))

if type == "K":
    print(weight*2.2)
elif type == "L":
    print(weight/2.2)

else:
    print("can not convert")

#----------------------------------------------
#while loop
i=1
while i<=5 :
    print(i)
    i= i+1

#------------------------------------
#for loop

number = [1,2,3,4,5]
for item in number:
    print(item)


"""
Translate any word to any language
"""

import tkinter as tk
from googletrans import Translator

win = tk.Tk()
win.title("Translator")
win.geometry("400x100")

# Function to translate

def translation():
    word = entry.get()
    translator = Translator(service_urls =['translate.google.com',])
    translation1 = translator.translate(word, dest="hi")
    label1 = tk.Label(win, text=f"Translated in Hindi: {translation1.text}", bg="yellow")
    label1.grid(row=2, column=0)

label = tk.Label(win, text="Enter Word: ")
label.grid(row=0, column=0, sticky="W")

entry = tk.Entry(win)
entry.grid(row=1, column=0)

button=tk.Button(win, text="Translate", command=translation)
button.grid(row=1, column=2)

win.mainloop()


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

""" A command line utility for The Cannon. """

import argparse
import logging
import os
from collections import OrderedDict
from numpy import ceil, loadtxt, zeros, nan, diag, ones
from subprocess import check_output
from six.moves import cPickle as pickle
from tempfile import mkstemp
from time import sleep

def fit(model_filename, spectrum_filenames, threads, clobber, from_filename,
    **kwargs):
    """
    Fit a series of spectra.
    """

    import AnniesLasso as tc

    model = tc.load_model(model_filename, threads=threads)
    logger = logging.getLogger("AnniesLasso")
    assert model.is_trained

    chunk_size = kwargs.pop("parallel_chunks", 1000) if threads > 1 else 1
    fluxes = []
    ivars = []
    output_filenames = []
    failures = 0

    fit_velocity = kwargs.pop("fit_velocity", False)

    # MAGIC HACK
    delete_meta_keys = ("fjac", ) # To save space...
    initial_labels = loadtxt("initial_labels.txt")

    if from_filename:
        with open(spectrum_filenames[0], "r") as fp:
            _ = list(map(str.strip, fp.readlines()))
        spectrum_filenames = _

    output_suffix = kwargs.get("output_suffix", None)
    output_suffix = "result" if output_suffix is None else str(output_suffix)
    N = len(spectrum_filenames)
    for i, filename in enumerate(spectrum_filenames):
        logger.info("At spectrum {0}/{1}: {2}".format(i + 1, N, filename))

        basename, _ = os.path.splitext(filename)
        output_filename = "-".join([basename, output_suffix]) + ".pkl"

        if os.path.exists(output_filename) and not clobber:
            logger.info("Output filename {} already exists and not clobbering."\
                .format(output_filename))
            continue

        try:
            with open(filename, "rb") as fp:
                flux, ivar = pickle.load(fp)
                fluxes.append(flux)
                ivars.append(ivar)

            output_filenames.append(output_filename)

        except:
            logger.exception("Error occurred loading {}".format(filename))
            failures += 1

        else:
            if len(output_filenames) >= chunk_size:

                results, covs, metas = model.fit(fluxes, ivars,
                    initial_labels=initial_labels, model_redshift=fit_velocity,
                    full_output=True)

                for result, cov, meta, output_filename \
                in zip(results, covs, metas, output_filenames):

                    for key in delete_meta_keys:
                        if key in meta:
                            del meta[key]

                    with open(output_filename, "wb") as fp:
                        pickle.dump((result, cov, meta), fp, 2) # For legacy.
                    logger.info("Saved output to {}".format(output_filename))

                del output_filenames[0:], fluxes[0:], ivars[0:]

    if len(output_filenames) > 0:

        results, covs, metas = model.fit(fluxes, ivars,
            initial_labels=initial_labels, model_redshift=fit_velocity,
            full_output=True)

        for result, cov, meta, output_filename \
        in zip(results, covs, metas, output_filenames):

            for key in delete_meta_keys:
                if key in meta:
                    del meta[key]

            with open(output_filename, "wb") as fp:
                pickle.dump((result, cov, meta), fp, 2) # For legacy.
            logger.info("Saved output to {}".format(output_filename))

        del output_filenames[0:], fluxes[0:], ivars[0:]

    logger.info("Number of failures: {}".format(failures))
    logger.info("Number of successes: {}".format(N - failures))

    return None

def join_results(output_filename, result_filenames, model_filename=None,
    from_filename=False, clobber=False, errors=False, cov=False, **kwargs):
    """
    Join the test results from multiple files into a single table file.
    """

    import AnniesLasso as tc
    from astropy.table import Table, TableColumns

    meta_keys = kwargs.pop("meta_keys", {})
    meta_keys.update({
        "chi_sq": nan,
        "r_chi_sq": nan,
        "snr": nan,
    #    "redshift": nan,
    })

    logger = logging.getLogger("AnniesLasso")

    # Does the output filename already exist?
    if os.path.exists(output_filename) and not clobber:
        logger.info("Output filename {} already exists and not clobbering."\
            .format(output_filename))
        return None

    if from_filename:
        with open(result_filenames[0], "r") as fp:
            _ = list(map(str.strip, fp.readlines()))
        result_filenames = _

    # We might need the label names from the model.
    if model_filename is not None:
        model = tc.load_model(model_filename)
        assert model.is_trained
        label_names = model.vectorizer.label_names
        logger.warn(
            "Results produced from newer models do not need a model_filename "\
            "to be specified when joining results.")

    else:
        with open(result_filenames[0], "rb") as fp:
            contents = pickle.load(fp)
            if "label_names" not in contents[-1]:
                raise ValueError(
                    "cannot find label names; please provide the model used "\
                    "to produce these results")
            label_names = contents[-1]["label_names"]

    # Load results from each file.
    failed = []
    N = len(result_filenames)

    # Create an ordered dictionary of lists for all the data.
    data_dict = OrderedDict([("FILENAME", [])])
    for label_name in label_names:
        data_dict[label_name] = []

    if errors:
        for label_name in label_names:
            data_dict["E_{}".format(label_name)] = []

    if cov:
        data_dict["COV"] = []

    for key in meta_keys:
        data_dict[key] = []

    # Iterate over all the result filenames
    for i, filename in enumerate(result_filenames):
        logger.info("{}/{}: {}".format(i + 1, N, filename))

        if not os.path.exists(filename):
            logger.warn("Path {} does not exist. Continuing..".format(filename))
            failed.append(filename)
            continue

        with open(filename, "rb") as fp:
            contents = pickle.load(fp)

        assert len(contents) == 3, "You are using some old school version!"

        labels, Sigma, meta = contents

        if Sigma is None:
            Sigma = nan * ones((labels.size, labels.size))

        result = [filename] + list(labels)
        if errors:
            result.extend(diag(Sigma)**0.5)
        if cov:
            result.append(Sigma)
        result += [meta.get(k, v) for k, v in meta_keys.items()]

        for key, value in zip(data_dict.keys(), result):
            data_dict[key].append(value)

    # Warn of any failures.
    if failed:
        logger.warn(
            "The following {} result file(s) could not be found: \n{}".format(
                len(failed), "\n".join(failed)))

    # Construct the table.
    table = Table(TableColumns(data_dict))
    table.write(output_filename, overwrite=clobber)
    logger.info("Written to {}".format(output_filename))

def main():
    """
    The main command line interpreter. This is the console script entry point.
    """

    # Create the main parser.
    parser = argparse.ArgumentParser(
        description="The Cannon", epilog="http://TheCannon.io")

    # Create parent parser.
    parent_parser = argparse.ArgumentParser(add_help=False)
    parent_parser.add_argument("-v", "--verbose",
        dest="verbose", action="store_true", default=False,
        help="Verbose logging mode.")
    parent_parser.add_argument("-t", "--threads",
        dest="threads", type=int, default=1,
        help="The number of threads to use.")

    # Allow for multiple actions.
    subparsers = parser.add_subparsers(title="action", dest="action",
        description="Specify the action to perform.")

    # Fitting parser.
    fit_parser = subparsers.add_parser("fit", parents=[parent_parser],
        help="Fit stacked spectra using a trained model.")
    fit_parser.add_argument("model_filename", type=str,
        help="The path of a trained Cannon model.")
    fit_parser.add_argument("spectrum_filenames", nargs="+", type=str,
        help="Paths of spectra to fit.")
    fit_parser.add_argument("--parallel-chunks", dest="parallel_chunks",
        type=int, default=1000, help="The number of spectra to fit in a chunk.")
    fit_parser.add_argument("--clobber", dest="clobber", default=False,
        action="store_true", help="Overwrite existing output files.")
    fit_parser.add_argument(
        "--output-suffix", dest="output_suffix", type=str,
        help="A string suffix that will be added to the spectrum filenames "\
             "when creating the result filename")
    fit_parser.add_argument("--from-filename", dest="from_filename",
        action="store_true", default=False, help="Read spectrum filenames from file")
    fit_parser.set_defaults(func=fit)

    # Join results parser.
    join_parser = subparsers.add_parser("join", parents=[parent_parser],
        help="Join results from individual stars into a single table.")
    join_parser.add_argument("output_filename", type=str,
        help="The path to write the output filename.")
    join_parser.add_argument("result_filenames", nargs="+", type=str,
        help="Paths of result files to include.")
    join_parser.add_argument("--from-filename",
        dest="from_filename", action="store_true", default=False,
        help="Read result filenames from a file.")
    join_parser.add_argument(
        "--errors", dest="errors", default=False, action="store_true",
        help="Include formal errors in destination table.")
    join_parser.add_argument(
        "--cov", dest="cov", default=False, action="store_true",
        help="Include covariance matrix in destination table.")
    join_parser.add_argument(
        "--clobber", dest="clobber", default=False, action="store_true",
        help="Ovewrite an existing table file.")

    join_parser.set_defaults(func=join_results)

    # Parse the arguments and take care of any top-level arguments.
    args = parser.parse_args()
    if args.action is None: return

    logger = logging.getLogger("AnniesLasso")
    if args.verbose:
        logger.setLevel(logging.DEBUG)

    # Do things.
    return args.func(**args.__dict__)

if __name__ == "__main__":

    """
    Usage examples:
    # tc train model.pickle --condor --chunks 100
    # tc train model.pickle --threads 8
    # tc join model.pickle --from-filename files

    """
    _ = main()


import pywhatkit as pw
from k2 import speak

def handwritten():

     speak("Ok Sir please give me the text: ")

     txt = input("Enter the text: ")

     pw.text_to_handwriting(txt,"demo.png",[0,0,138])

     print("  END  ")

# handwritten()


import xml.etree.ElementTree as ET

# read all the xml files and store record elements in a list
def get_docs():
    files = ["./cfc-xml/cf74.xml", "./cfc-xml/cf75.xml", "./cfc-xml/cf76.xml", "./cfc-xml/cf77.xml",
             "./cfc-xml/cf78.xml", "./cfc-xml/cf79.xml"]
    res = []
    for file in files:
        with open(file) as f:
            tree = ET.parse(f)
            records = tree.getroot()
            for record in records:
                res.append(record)
    return res

# parse a tree element to json with fields: ["RECORDNUM", 'AUTHORS', 'MAJORSUBJ', "MINORSUBJ", 'ABSTRACT', 'TITLE', 'EXTRACT', 'SOURCE']
def parse_json(elem):
    # get id field information
    record_id = "00000"
    if elem.find('RECORDNUM') != -1 and elem.find('RECORDNUM') is not None and elem.find('RECORDNUM').text is not None:
        record_id = elem.find('RECORDNUM').text

    # get title field information
    title = ""
    if elem.find('TITLE') != -1 and elem.find('TITLE') is not None and elem.find('TITLE').text is not None:
        title = elem.find('TITLE').text

    # get abstract field information
    abstract = ""
    if elem.find('ABSTRACT') != -1 and elem.find('ABSTRACT') is not None and elem.find('ABSTRACT').text is not None:
        abstract = elem.find('ABSTRACT').text

    # get extract field information
    extract = ""
    if elem.find('EXTRACT') != -1 and elem.find('EXTRACT') is not None and elem.find('EXTRACT').text is not None:
        extract = elem.find('EXTRACT').text

    # get source field information
    source = ""
    if elem.find('SOURCE') != -1 and elem.find('SOURCE') is not None and elem.find('SOURCE').text is not None:
        source = elem.find('SOURCE').text

    # get authors field information
    authors = ""
    authors_elem = elem.find('AUTHORS')
    if authors_elem != -1 and authors_elem is not None:
        for author in authors_elem:
            if author is not None and author.text is not None:
                authors = authors + " " + author.text

    # get major_subjs field information
    major_subjs = ""
    major_subj_elem = elem.find('MAJORSUBJ')
    if major_subj_elem != -1 and major_subj_elem is not None:
        for major_subj in major_subj_elem:
            if major_subj is not None and major_subj.text is not None:
                major_subjs = major_subjs + " " + major_subj.text

    # get minor_subjs field information
    minor_subjs = ""
    minor_subj_elem = elem.find('MINORSUBJ')
    if minor_subj_elem != -1 and minor_subj_elem is not None:
        for minor_subj in minor_subj_elem:
            if minor_subj is not None and minor_subj.text is not None:
                minor_subjs = minor_subjs + " " + minor_subj.text

    res = {
        "RECORDNUM": record_id,
        "AUTHORS": authors,
        "TITLE": title,
        "MAJORSUBJ": major_subjs,
        "MINORSUBJ": minor_subjs,
        "ABSTRACT": abstract,
        "EXTRACT": extract,
        "SOURCE": source
    }
    return res


############################################################### 1.3 ###############################################################
# Family name: Amit Shanbhoug
# Student number:  8677407
# Course: IT1 1120
# Assignment Number 3

def longest_run(x):

    ''' The function returns the longest run of identical numbers in the input list.

        (list)-> int
    '''

    previous = x[0]
    a = 0
    for i in range(0, len(x)):
        if x[i] == previous:
            a = a + 1
        else:
            previous = x[i]
        return a

a = input(' Please input a list of numbers seperated by space: ')
a = a.split()
x = [int(i) for i in a]
longest_run(x)


"""change column to BigInteger

Revision ID: 97f2d8b76246
Revises: 18239a3befe0
Create Date: 2016-02-25 20:38:21.952978

"""

# revision identifiers, used by Alembic.
revision = '97f2d8b76246'
down_revision = '18239a3befe0'
branch_labels = None
depends_on = None

from alembic import op
import sqlalchemy as sa

def upgrade():
    ### commands auto generated by Alembic - please adjust! ###
    op.alter_column('user', 'id', type_=sa.BigInteger, existing_type=sa.Integer)
    ### end Alembic commands ###

def downgrade():
    ### commands auto generated by Alembic - please adjust! ###
    op.alter_column('user', 'id', type_=sa.Integer, existing_type=sa.BigInteger)
    ### end Alembic commands ###


import time
import numpy as np
import matplotlib.pyplot as plt
import cv2
import h5py
import os

from tqdm import tqdm
from PIL import Image
from sklearn.preprocessing import StandardScaler

import webdataset as wds
import sys

from nsd_access import NSDAccess
nsda = NSDAccess('/fsx/proj-medarc/fmri/natural-scenes-dataset/s3')

import nibabel as nib

import torch
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
print("device:",device)

sub=int(sys.argv[1])
preset_cnt=int(sys.argv[2])

subject=f'subj0{sub+1}'
subj=subject
print("subject",subject)

print("preset_cnt",preset_cnt)

# CLIP
import clip
from torchvision import transforms
from models import *
clip_extractor = Clipper("ViT-L/14", device=device, hidden_state=True, norm_embs=False)
clip_extractor_last = Clipper("ViT-L/14", device=device, hidden_state=False, norm_embs=False)

# openclip_extractor = OpenClipper('ViT-H-14', device=device, hidden_state=False, norm_embs=False)
# openclip_extractor_last = OpenClipper('ViT-H-14', device=device, hidden_state=True, norm_embs=False)

# ImageBind
import sys
sys.path.insert(0, "/fsx/proj-medarc/fmri/ImageBind")
sys.path.insert(0, "/fsx/proj-medarc/fmri/ImageBind/models")
import data
import imagebind_model
from imagebind_model import ModalityType

imagebind = imagebind_model.imagebind_huge(pretrained=True)
imagebind.eval().requires_grad_(False)
imagebind.to(device)

imagebind_transform = transforms.Compose(
    [transforms.Resize(224, interpolation=transforms.InterpolationMode.BICUBIC),
    transforms.CenterCrop(224),
    transforms.Normalize(
        mean=(0.48145466, 0.4578275, 0.40821073),
        std=(0.26862954, 0.26130258, 0.27577711))])

import copy
imagebind_hidden = copy.deepcopy(imagebind)
imagebind_hidden.modality_heads.vision = nn.Identity()
imagebind_hidden.modality_postprocessors.vision = nn.Identity()
imagebind_hidden.eval().requires_grad_(False)
imagebind_hidden.to(device)

# FCN segmentation model
from torchvision.models.feature_extraction import create_feature_extractor, get_graph_node_names
from torchvision.models.segmentation import fcn_resnet50, FCN_ResNet50_Weights
fcn_weights = FCN_ResNet50_Weights.COCO_WITH_VOC_LABELS_V1
fcn_model = create_feature_extractor(fcn_resnet50(weights=fcn_weights), return_nodes=["backbone.maxpool"]).to(device)
fcn_model.eval().requires_grad_(False)
pass

# NOTE: you will want to parallelize this
print(time.strftime("\nCurrent time: %H:%M:%S", time.localtime()))
total_cnt = 100

lh_file = f"/fsx/proj-medarc/fmri/natural-scenes-dataset/algonauts_data/dataset/{subject}/roi_masks/lh.all-vertices_fsaverage_space.npy"
lh_mask = np.load(lh_file)
rh_file = f"/fsx/proj-medarc/fmri/natural-scenes-dataset/algonauts_data/dataset/{subject}/roi_masks/rh.all-vertices_fsaverage_space.npy"
rh_mask = np.load(rh_file)
mask = np.hstack((lh_mask,rh_mask))
mask = np.asarray(mask,bool)

# load coco 73k indices
indices_path = "/fsx/proj-medarc/fmri/natural-scenes-dataset/COCO_73k_subj_indices.hdf5"
hdf5_file = h5py.File(indices_path, "r")
indices = hdf5_file[f"{subj}"][:]

# load orig images
f = h5py.File('/fsx/proj-medarc/fmri/natural-scenes-dataset/s3/nsddata_stimuli/stimuli/nsd/nsd_stimuli.hdf5', 'r')
images = f['imgBrick']

# load shared 73k indices
import scipy.io as sio
nsd_design = sio.loadmat('/fsx/proj-medarc/fmri/natural-scenes-dataset/s3/nsddata/experiments/nsd/nsd_expdesign.mat')
shared_idx = nsd_design['sharedix'][0]-1
order = nsd_design['subjectim'][sub]-1

# for each unique image, get the betas and average
all_betas = None
cnt = 0; abs_cnt = 0;
for uniq_idx in tqdm(np.unique(indices)):
    if abs_cnt==preset_cnt:
        trial_numbers = np.where(indices==uniq_idx)[0]
        for itrial, trial in enumerate(trial_numbers):
            sess = int(np.floor(trial / 750))
            sess_trial = trial - (sess * 750)
            sess += 1

            betas = nsda.read_betas(subject=subject,
                    session_index=int(sess),
                    trial_index=[int(sess_trial)], # empty list as index means get all for this session
                    data_type='betas_fithrf_GLMdenoise_RR',
                    data_format='fsaverage')

            # load mean + scale to get zero mean and unit variance depending on the given session
            betas_nsd_mean = np.load(f"/fsx/proj-medarc/fmri/natural-scenes-dataset/challenge_scalars/challenge_mean_sess{sess}_{subj}.npy")
            betas_nsd_std = np.load(f"/fsx/proj-medarc/fmri/natural-scenes-dataset/challenge_scalars/challenge_std_sess{sess}_{subj}.npy")

            betas_nsd = betas[mask]
            shape = betas_nsd.shape
            betas_nsd = betas_nsd.reshape(-1,betas_nsd.shape[-2]*betas_nsd.shape[-1])
            betas_nsd = (betas_nsd - betas_nsd_mean) / betas_nsd_std
            betas_nsd = betas_nsd.astype('float16') # (1, 15724)

            if itrial==0:
                same_betas_nsd = betas_nsd
            else:
                same_betas_nsd = np.concatenate((same_betas_nsd,betas_nsd),axis=0)

        if same_betas_nsd.shape[0] == 1:
            num_unique = 1
            same_betas_nsd = np.concatenate((same_betas_nsd, same_betas_nsd, same_betas_nsd), axis=0)
        elif same_betas_nsd.shape[0] == 2:
            num_unique = 2
            same_betas_nsd = np.concatenate((same_betas_nsd, np.mean(same_betas_nsd,axis=0)[None]), axis=0)
        else:
            num_unique = 3

        if all_betas is None:
            all_betas = same_betas_nsd[None]
            ordering = uniq_idx
            ordered_imgs = trial_numbers[0]
            num_uniques = num_unique
        else:
            all_betas = np.concatenate((all_betas,same_betas_nsd[None]),axis=0)
            ordering = np.append(ordering,uniq_idx)
            ordered_imgs = np.append(ordered_imgs, trial_numbers[0])
            num_uniques = np.append(num_uniques, num_unique)

    cnt += 1
    if cnt==total_cnt:
        if abs_cnt==preset_cnt:
            sink = wds.TarWriter(f"/fsx/proj-medarc/fmri/natural-scenes-dataset/algonauts_data/wds/{subj}_{abs_cnt}.tar")
            for i,idx in enumerate(range(total_cnt*preset_cnt,total_cnt*preset_cnt+total_cnt)):
                image = Image.fromarray(images[ordering[i]].astype('uint8').clip(0,255))
                with torch.no_grad():
                    cur_imgs_tensor = torch.Tensor(images[ordering[i]]).permute(2,0,1).unsqueeze(0).to(device) / 255
                    ib_inputs = {ModalityType.VISION: imagebind_transform(cur_imgs_tensor)}
                    sink.write({
                        "__key__": "sample%09d" % idx,
                        "num_uniques.npy": np.array([num_uniques[i]]),
                        "coco73k.npy": np.array([ordering[i]]),
                        "vert.npy": all_betas[i],
                        "trial.npy": np.array([ordered_imgs[i]]),
                        "jpg": image,
                        "clip_emb_hidden.npy": clip_extractor.embed_image(cur_imgs_tensor).detach().cpu().numpy(),
                        "clip_emb_final.npy": clip_extractor_last.embed_image(cur_imgs_tensor).detach().cpu().numpy(),
                        "imagebind_hidden.npy": imagebind_hidden(ib_inputs)['vision'].detach().cpu().numpy(),
                        "imagebind_final.npy": imagebind(ib_inputs)['vision'].detach().cpu().numpy(),
                        "fcn_maxpool.npy": fcn_model(cur_imgs_tensor)['backbone.maxpool'].detach().cpu().numpy(),
                    })
            sink.close()

        all_betas = None
        cnt = 0
        abs_cnt += 1

if abs_cnt==preset_cnt: # for the last batch, won't be equal to exactly total_cnt probably
    sink = wds.TarWriter(f"/fsx/proj-medarc/fmri/natural-scenes-dataset/algonauts_data/wds/{subj}_{abs_cnt}.tar")
    for i,idx in enumerate(range(total_cnt*preset_cnt,total_cnt*preset_cnt+total_cnt)):
        image = Image.fromarray(images[ordering[i]].astype('uint8').clip(0,255))
        with torch.no_grad():
            cur_imgs_tensor = torch.Tensor(images[ordering[i]]).permute(2,0,1).unsqueeze(0).to(device) / 255
            ib_inputs = {ModalityType.VISION: imagebind_transform(cur_imgs_tensor)}
            sink.write({
                "__key__": "sample%09d" % idx,
                "num_uniques.npy": np.array([num_uniques[i]]),
                "coco73k.npy": np.array([ordering[i]]),
                "vert.npy": all_betas[i],
                "trial.npy": np.array([ordered_imgs[i]]),
                "jpg": image,
                "clip_emb_hidden.npy": clip_extractor.embed_image(cur_imgs_tensor).detach().cpu().numpy(),
                "clip_emb_final.npy": clip_extractor_last.embed_image(cur_imgs_tensor).detach().cpu().numpy(),
                "imagebind_hidden.npy": imagebind_hidden(ib_inputs)['vision'].detach().cpu().numpy(),
                "imagebind_final.npy": imagebind(ib_inputs)['vision'].detach().cpu().numpy(),
                "fcn_maxpool.npy": fcn_model(cur_imgs_tensor)['backbone.maxpool'].detach().cpu().numpy(),
            })
    sink.close()

print(time.strftime("\nCurrent time: %H:%M:%S", time.localtime()))


from collections import Counter
polymer, insert_data = open('./input.txt').read().split('\n\n')

insert = [l.split(' -> ') for l in insert_data.split('\n') if l]
insert_dict = {i: Counter([i[0]+m, m+i[1]]) for i, m in insert}

def main(steps):
    pol_counts = Counter([c + polymer[i+1] for i, c in enumerate(polymer[:-1])])

    for s in range(steps):
        n_pol_counts = Counter()
        for pair, count in pol_counts.items():
            n_pol_counts += {k: count*v for k,v in insert_dict[pair].items()}
        pol_counts = n_pol_counts

    singular_counter = Counter()
    for pair, count in pol_counts.items():
        for c in pair:
            singular_counter += {c: count}

    singular_counter += Counter([polymer[0], polymer[-1]])
    freq = singular_counter.most_common()
    return (freq[0][1] - freq[-1][1])//2

print(main(10))
print(main(40))


from PyQt5.QtGui import QIcon, QPixmap
from PyQt5.QtDesigner import QPyDesignerCustomWidgetPlugin

from tempswitchbutton import TempSwitchButton

class TempSwitchButtonPlugin(QPyDesignerCustomWidgetPlugin):

    # The __init__() method is only used to set up the plugin and define its
    # initialized variable.
    def __init__(self, parent=None):

        super(TempSwitchButtonPlugin, self).__init__(parent)

        self.initialized = False

    # The initialize() and isInitialized() methods allow the plugin to set up
    # any required resources, ensuring that this can only happen once for each
    # plugin.
    def initialize(self, core):

        if self.initialized:
            return

        self.initialized = True

    def isInitialized(self):

        return self.initialized

    # This factory method creates new instances of our custom widget with the
    # appropriate parent.
    def createWidget(self, parent):
        return TempSwitchButton(parent)

    # This method returns the name of the custom widget class that is provided
    # by this plugin.
    def name(self):
        return "TempSwitchButton"

    # Returns the name of the group in Qt Designer's widget box that this
    # widget belongs to.
    def group(self):
        return "PyQt Examples"

    # Return the icon used to represent the custom widget in Designer's widget
    # box.
    def icon(self):
        return QIcon(_logo_pixmap)

    # Returns a short description of the custom widget for use in a tool tip.
    def toolTip(self):
        return ""

    # Returns a short description of the custom widget for use in a "What's
    # This?" help message for the widget.
    def whatsThis(self):
        return ""

    # Returns True if the custom widget acts as a container for other widgets;
    # otherwise returns False. Note that plugins for custom containers also
    # need to provide an implementation of the QDesignerContainerExtension
    # interface if they need to add custom editing support to Qt Designer.
    def isContainer(self):
        return False

    # Returns the module containing the custom widget class. It may include
    # a module path.
    def includeFile(self):
        return "tempswitchbutton"

# Define the image used for the icon.
_logo_16x16_xpm = [
"16 16 46 1",
". c #a5a5dc",
"l c #a69fd6",
"k c #a7a5da",
"h c #a7a6dc",
"a c #a7a7de",
"Q c #a8a5da",
"s c #a9a7d7",
"R c #a9a9e0",
"z c #abaad4",
"E c #afafda",
"M c #afafdb",
"K c #b0a8e2",
"o c #b1afe4",
"p c #b2b2d7",
"# c #b2b2ed",
"i c #b39eb6",
"F c #b3b3e1",
"e c #b4b4ef",
"t c #b58bab",
"d c #b6b6f2",
"n c #b798b8",
"P c #b798b9",
"c c #b8b6f2",
"D c #b8b89c",
"m c #b9648d",
"J c #ba84b0",
"A c #bdbdfb",
"f c #bfbffe",
"g c #c06996",
"b c #c0c0ff",
"B c #cbb889",
"L c #cbb989",
"O c #cfcf87",
"I c #d09585",
"w c #d0cf86",
"x c #dede81",
"G c #e8e87c",
"q c #edde7b",
"N c #f1e07b",
"v c #f2e07b",
"H c #f6e57c",
"j c #fb917e",
"u c #ffb580",
"r c #ffda80",
"C c #fffe80",
"y c #ffff80",
".##############a",
"#bbbbbbbbcdbbbbe",
"#bbbbbbbfghbbbbe",
"#bbbbbbbijkbbbbe",
"#blmnobpqrsbbbbe",
"#bbtuvwxyyzbbbbe",
"#bbABCyyyyDEfbbe",
"#bbbFGyyyyyHIJKe",
"#bbbFGyyyyyHIJKe",
"#bbALCyyyyDMfbbe",
"#bbtuNOxyyzbbbbe",
"#blmPobpqrsbbbbe",
"#bbbbbbbijQbbbbe",
"#bbbbbbbfghbbbbe",
"#bbbbbbbbcdbbbbe",
"aeeeeeeeeeeeeeeR"]

_logo_pixmap = QPixmap(_logo_16x16_xpm)


#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import LIGGGHTSER
import numpy as np
import matplotlib
import pylab as plt
# import seaborn as sns
read = LIGGGHTSER.read.Read()

plt.figure(figsize=(20,12))
font1={'weight':'normal','size':18,}
fontlabel={'weight':'normal','size':18,}
xlow=2e7
xhigh=10e7
linewidth_set=2.0

os.chdir(r'D:\ETH\origin_speed36\DEM')
top1=read.read_ave('./ave_force_top.txt')
os.chdir(r'D:\ETH\break_120\DEM')
top2=read.read_ave('./ave_force_top.txt')
number2=read.read_log_thermo('./log.liggghts')
os.chdir(r'D:\ETH\break_100\DEM')
top3=read.read_ave('./ave_force_top.txt')
number3=read.read_log_thermo('./log.liggghts')

timestep2=list()
atoms2=list()
for i in number2['data2']:
	timestep2.append(i[0])
	atoms2.append(i[1])

break_atom2=list()
sum_break2=list()
sum_break2.append(0)
for i in range(len(atoms2)-1):
	break_atom2.append(round((atoms2[i+1]-atoms2[i])/13))
	sum_break2.append(break_atom2[i]+sum_break2[i])
break_atom2.append(0)

timestep3=list()
atoms3=list()
for i in number3['data2']:
	timestep3.append(i[0])
	atoms3.append(i[1])

break_atom3=list()
for i in range(len(atoms3)-1):
	break_atom3.append(round((atoms3[i+1]-atoms3[i])/13))
break_atom3.append(0)

# ax211=plt.subplot(211)
# x=top1['v_xForce']
# y=top1['v_yForce']
# x=np.array(x)
# y=np.array(y)
# friction=x/y
# l11=plt.plot(top1['TimeStep'],friction,linewidth=linewidth_set,linestyle='-',label='Unbreakable')
# x=top2['v_xForce']
# y=top2['v_yForce']
# x=np.array(x)
# y=np.array(y)
# friction=x/y
# l12=plt.plot(top2['TimeStep'],friction,linewidth=linewidth_set,linestyle='-',label='breakable s=120MPa')
# for i in range(min(len(break_atom2),len(top1['TimeStep']))):
#     # print(i/len(break_atom3))
#     if(break_atom2[i]==0):
#         continue
#     plt.scatter(timestep2[i],friction[i+26880], s=break_atom2[i]*50,color='blue',edgecolors='black',linewidth=0.5,zorder=3,alpha=0.3)
# plt.tick_params(labelsize=18,direction='in',pad=15)
# plt.xlim((xlow,xhigh))
# plt.ylim((0.2,0.51))
# plt.yticks(np.arange(0.2,0.51,0.1))
# ax=plt.gca()
# ax211.spines['bottom'].set_linewidth(3)
# ax211.spines['top'].set_linewidth(3)
# ax211.spines['left'].set_linewidth(3)
# ax211.spines['right'].set_linewidth(3)
# plt.ylabel('Friction',fontlabel)
# ax211y2=ax211.twinx()
binsize=100
timestep_break2=list()
break_atom_sum2=list()
for i in range(0,len(break_atom2)-binsize,binsize):
    timestep_break2.append(timestep2[i])
    break_atom_sum2.append(sum(break_atom2[i:i+binsize]))
    # print(timestep2[i])
    # print(sum(break_atom2[i:i+binsize]))
# l13=ax211y2.plot(timestep2,break_atom2,linewidth=linewidth_set,color='blue',linestyle='-',alpha=0.3,label='broken particle number')
# l13=ax211y2.bar(timestep2,break_atom2,width = 0.35,facecolor = 'lightskyblue',label='broken particle number')
# l13=ax211y2.bar(timestep_break2,break_atom_sum2,width = 0.35,facecolor = 'lightskyblue',label='broken particle number')
x=np.array(timestep_break2)
y=np.array(break_atom_sum2)
# x=[1,2,3]
# y=[10,0,2]
# plt.bar(x,y)
print(timestep_break2[0:2])
print(break_atom_sum2[0:2])
plt.bar(timestep_break2[0:2],break_atom_sum2[0:2])
# plt.hist(break_atom2,bins=20,color='red',histtype='stepfilled',alpha=0.75)
# plt.ylabel('Particle Number',fontlabel)
# plt.ylim((0.5,3.5))
# plt.yticks(np.arange(1,3.1,1))
# plt.tick_params(labelsize=18,direction='in',pad=15)
# plt.title('Friction & Broken Particles',loc='right',fontsize=24,pad=10)
# ls=l11+l12
# # ls=l11+l12+l13
# labs=[l.get_label() for l in ls]
# ax.legend(ls,labs,loc='lower right',prop=font1)
plt.show()


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

"""
Desc:
File: 25. K 个一组翻转链表.py
Author: fangeng
Date: 2020/5/16 20:16
"""

# Definition for singly-linked list.
class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None

class Solution:
    """
    给你一个链表，每 k 个节点一组进行翻转，请你返回翻转后的链表。
    k 是一个正整数，它的值小于或等于链表的长度。
    如果节点总数不是 k 的整数倍，那么请将最后剩余的节点保持原有顺序。

    给你这个链表：1->2->3->4->5
        当 k = 2 时，应当返回: 2->1->4->3->5
        当 k = 3 时，应当返回: 3->2->1->4->5
    """

    def reverseKGroup(self, head: ListNode, k: int) -> ListNode:
        if not head or k < 2:
            return head

        tail = head
        for i in range(k - 1):
            if tail.next:
                tail = tail.next
            else:
                return head

        # 下一轮的开始
        n_head = tail.next

        pre = head
        cur = head.next
        while cur != n_head:
            nex = cur.next
            cur.next = pre
            pre = cur
            cur = nex
        head.next = self.reverseKGroup(n_head, k)
        return pre

25. K 个一组翻转链表.py

25. K 个一组翻转链表.py


from interp.tools.grad_modify_query_items import (
    NoneConf,
    ReplaceFuncConf,
    StopGradConf,
    MulConf,
    ReplaceFuncConf,
    ItemConf,
)
from interp.tools.log import KeyIdxs

def test_conf_equality_is_id():
    def run(get):
        x = get()
        assert x != get()
        assert x == x
        assert x is x

    run(NoneConf)
    run(lambda: ReplaceFuncConf(ItemConf(KeyIdxs("")), from_key_idxs=KeyIdxs(""), replacement=lambda x: x))
    run(lambda: StopGradConf(ItemConf(KeyIdxs(""))))
    run(lambda: MulConf(ItemConf(KeyIdxs(""))))


from services.StudentService import StudentService

class UI:
  def __init__(self, repo):
    self.__student_service = StudentService(repo)

  def print_ui(self):
    while True:
      print ("1. Add a student")
      print ("2. Disaply all students")
      print ("3. Filter students by group. All the students from that respective group will be deleted")
      print ("4. Undo the last operation you have performed")
      print ("5. Exit the application")
      option = input("Choose your option: ")
      if option == "1":
          id = int(input("What is the ID of the student? "))
          name = input("What is the name of the student? ")
          group = int(input("In which group is the student? "))
          self.__student_service.add_student(id, name, group, True)
      elif option == "2":
          students = self.__student_service.get_all_students()
          for stud in students:
            print(stud)
      elif option == "3":
        group = int(input("Which group would you like to remove? "))
        self.__student_service.filter_students(group)
      elif option == "4":
        self.__student_service.undo_last_operation()
      elif option == "5":
        print("Goodbye")
        return
      else:
        print("Your input is not valid")

1st Semester/Fundamentals of Programming/Lab Assignments/A7/src/ui/ui.py


import os
import json
import yaml
import pickle
import datetime
import numpy as np
from collections import OrderedDict

import torch
from model import TransformerXL

def main():
    # gen config
    modelConfig, trainConfig = get_configs()

    # load dictionary
    event2word, word2event = pickle.load(open(os.path.join(trainConfig['ROOT'],'dictionary.pkl'), 'rb'))

    # load train data
    training_data = np.load(os.path.join(trainConfig['ROOT'],'train_data_XL.npz'))

    device = torch.device("cuda:{}".format(trainConfig['gpuID']) if not trainConfig["no_cuda"] and torch.cuda.is_available() else "cpu")
    os.environ['CUDA_VISIBLE_DEVICES'] = trainConfig['gpuID']

    print('Device to train:', device)

    resume = trainConfig['resume_training_model']

    # declare model
    model = TransformerXL(
            modelConfig,
            device,
            event2word=event2word,
            word2event=word2event,
            is_training=True)

    # train
    model.train(training_data,
                trainConfig,
                device,
                resume)

def get_configs():
    cfg = yaml.full_load(open("config.yml", 'r'))

    modelConfig = cfg['MODEL']
    trainConfig = cfg['TRAIN']

    cur_date = datetime.datetime.now().strftime('%Y%m%d-%H%M%S')
    experiment_Dir = os.path.join(trainConfig['output_dir'],cur_date)
    if not os.path.exists(experiment_Dir):
        print('experiment_Dir:', experiment_Dir)
        os.makedirs(experiment_Dir)
    print('Experiment: ', experiment_Dir)
    trainConfig.update({'experiment_Dir': experiment_Dir})

    with open(os.path.join(experiment_Dir, 'config.yml'), 'w') as f:
        doc = yaml.dump(cfg, f)

    print('='*5, 'Model configs', '='*5)
    print(json.dumps(modelConfig, indent=1, sort_keys=True))
    print('='*2, 'Training configs', '='*5)
    print(json.dumps(trainConfig, indent=1, sort_keys=True))
    return modelConfig, trainConfig

if __name__ == '__main__':
    main()


from django import forms
from .models import YogaClass, Practice
from trainers.models import Trainer

class ClassForm(forms.ModelForm):
    class Meta:
        model = YogaClass
        fields = "__all__"

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        placeholders = {
            'sku': 'Class SKU',
            'name': 'Class Name',
            'description': 'Class description',
            'price': 'Price',
            'category': 'Category',
            'practice': 'Yoga Practice',
            'level': 'Difficulty Level',
            'intensity': 'Class Intensity',
            'session_duration': 'Session duration (minutes)',
            'series_duration': 'No. of sessions',
            'equipment': 'Equipment',
            'trainer': 'Trainer',
            }

        image_label = "Upload image:"

        # Gets the trainer name label from Trainer model
        trainers = Trainer.objects.all()
        trainer_names = [(c.id, c.get_label_name()) for c in trainers]
        self.fields['trainer'].choices = trainer_names

        # Gets the practice name label from Practice model
        practices = Practice.objects.all()
        practice_names = [(c.id, c.get_label_name()) for c in practices]
        self.fields['practice'].choices = practice_names

        # Sets autofocus to name field
        self.fields['name'].widget.attrs['autofocus'] = True

        for field_name, field in self.fields.items():
            field.widget.attrs['class'] = "admin-input"
            if field_name != 'image':
                placeholder = placeholders[field_name]
                self.fields[field_name].widget.attrs[
                        'placeholder'] = placeholder
                self.fields[field_name].label = False
            else:
                self.fields[field_name].label = image_label
            # Hides category field and sets value as "class"
            if field_name == 'category':
                self.fields[field_name].widget.attrs['class'] = "d-none"
                self.fields[field_name].widget.attrs['value'] = 'class'


import argparse
import json

import pandas as pd
from utils import compute_subgroup_auc

def convert_dataframe_to_bool(df):
    bool_df = df.copy()
    for la in LANGS:
        bool_df[la] = df.lang == la
    return bool_df

def compute_lang_metrics_for_model(dataset, subgroups, model, label_col):
    """Computes per-subgroup metrics for all subgroups and one model."""
    records = []
    for subgroup in subgroups:
        record = {
            "subgroup": subgroup,
            "subgroup_size": len(dataset[dataset[subgroup]]),
        }
        record[SUBGROUP_AUC] = compute_subgroup_auc(dataset, subgroup, label_col, model)
        records.append(record)
    return pd.DataFrame(records).sort_values("subgroup_auc", ascending=True)

def main():
    with open(TEST) as f:
        results = json.load(f)

    test_private_path = "jigsaw_data/jigsaw-multilingual-toxic-comment-classification/updated_test.csv"
    test_private = pd.read_csv(test_private_path)
    test_private = convert_dataframe_to_bool(test_private)

    test_private[MODEL_NAME] = [s[0] for s in results["scores"]]

    lang_metrics_df = compute_lang_metrics_for_model(test_private, LANGS, MODEL_NAME, TOXICITY_COLUMN)
    print(lang_metrics_df)
    lang_metrics_df.to_csv(TEST[:-9] + "_lang_breakdown.csv")

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "--res_path",
        type=str,
        help="path to the saved results file",
    )
    args = parser.parse_args()
    TEST = args.res_path

    LANGS = ["es", "fr", "pt", "ru", "it", "tr"]

    TOXICITY_COLUMN = "toxic"
    MODEL_NAME = "XLM-R"
    SUBGROUP_AUC = "subgroup_auc"

    main()


def handleWebhook(request):

    import json
    from random import choice

    f = open('meals.json')
    meals_dict = json.load(f)

    req = request.get_json()

    responseText = ""
    intent = req["queryResult"]["intent"]["displayName"]

    if intent == "Default Welcome Intent":
        responseText = "來自Cloud Function的誠摯歡迎"
    elif intent == "Default Fallback Intent":
        fallbacks = ["再講一次可以嗎?","對不起，我不清楚你所表達的意思","試著換個方式問看看吧","我剛剛恍神了，再說一次好嗎?"]
        responseText = choice(fallbacks)
    elif intent == "輸出想到的美食":
        types = req["queryResult"]["parameters"]["input"]
        if types in ["午餐","晚餐"]:
            types = "午晚餐"

        if types in list(meals_dict.keys()):
            results = choice(meals_dict[types])
            responseText = f" 「{results}」如何呢? "
        else:
            fallbacks = ["我當機了，讓我再想一下","再幫我撐十秒","等待靈感降落中..."]
            responseText = choice(fallbacks)

    # You can also use the google.cloud.dialogflowcx_v3.types.WebhookRequest protos instead of manually writing the json object
    res = {"fulfillmentMessages": [{"text": {"text": [responseText]}}]}

    return res


from Products.ZenRelations.RelSchema import ToManyCont, ToOne

from .RabbitMQComponent import RabbitMQComponent

class RabbitMQVHost(RabbitMQComponent):
    meta_type = portal_type = "RabbitMQVHost"

    _relations = RabbitMQComponent._relations + (
        ('rabbitmq_node', ToOne(ToManyCont,
            'ZenPacks.zenoss.RabbitMQ.RabbitMQNode.RabbitMQNode',
            'rabbitmq_vhosts',
            ),),
        ('rabbitmq_exchanges', ToManyCont(ToOne,
            'ZenPacks.zenoss.RabbitMQ.RabbitMQExchange.RabbitMQExchange',
            'rabbitmq_vhost',
            ),),
        ('rabbitmq_queues', ToManyCont(ToOne,
            'ZenPacks.zenoss.RabbitMQ.RabbitMQQueue.RabbitMQQueue',
            'rabbitmq_vhost',
            ),),
        )

    def device(self):
        return self.rabbitmq_node().device()


import pprint
import sys
import random

with open(f"{sys.argv[1]}.txt", "r") as f:
    lines = f.readlines()

family = 0
people = {}
choices = {}
for line in lines:
    if line == "\n":
        family += 1
    else:
        people[line.strip("\n")] = family
        choices[line.strip("\n")] = ""

i = 0

while True:
    invalid = False
    unchosenPeople = list(people.keys())

    for person in people.keys():
        random.shuffle(unchosenPeople)
        for choice in unchosenPeople:
            if people[choice] != people[person]:
                break
        else:
            invalid = True
        unchosenPeople.remove(choice)
        choices[person] = choice

    if not invalid:
        break

    i+=1

print(i)
# pprint.pprint(choices)

with open (f"{sys.argv[2] if len(sys.argv) > 2 else sys.argv[1]+'-out'}.txt", "w") as f:
    for person in choices:
        f.write(f"{person} -> {choices[person]}\n")


import com.datastax.spark.connector._
import com.datastax.spark.connector.cql._
import com.datastax.spark.connector.cql.CassandraConnector
from pyspark.sql import SQLContext

import ast

# TSV separated file
delimiter = '\t'

# Input file
filepath = 'hdfs://ec2-54-219-144-56.us-west-1.compute.amazonaws.com:9000/examples/data/pubmed_publication.tsv'

def filter_line(line):
	tokens = line.split(delimiter)
	if len(tokens) < 9:
		return False
	if tokens[0] == "":
		return False
	if not tokens[4] == "":
		try:
			authors = ast.literal_eval(tokens[4].replace('"',''))
		except:
			return False
		authors = ast.literal_eval(tokens[4].replace('"',''))
		if len(authors) == 0:
			return False
	if not tokens[6] == "":
		date = ast.literal_eval(tokens[6].replace('"',''))
		if date[0] == None or date[1] == None or date[2] == None:
			return False
	return True

def keep_values(line):
	tokens = line.split(delimiter)
	doi = tokens[0]
	journal = tokens[1]
	title = tokens[3]
	authors = ast.literal_eval(tokens[4].replace('"',''))
	date = ast.literal_eval(tokens[6].replace('"',''))
	for a in authors:
		yield (a[0], doi, journal, title, date[2], date[1], date[0])

publications = sc.textFile(filepath).filter(lambda line: filter_line(line))\
	.flatMap(lambda line: keep_values(line))

publications.take(1)

#sql = SQLContext(sc)
#sql.read.format("org.apache.spark.sql.cassandra").load(table="author_publication_table", keyspace="harary")
#srdd = sqlCtx.inferSchema(publications)
#srdd.insertInto("author_publication_table", True)
#publications.saveToCassandra("harary", "author_publication_table", SomeColumns("author", "doi", "journal", "title", "year_accepted", "month_accepted", "day_accepted"));

#outputfile = 'hdfs://ec2-54-219-144-56.us-west-1.compute.amazonaws.com:9000/output/coauthorship_count.txt'
#coauthorship_count.saveAsTextFile(outputfile)


import pytest
from flask.testing import FlaskClient
from flask_sqlalchemy import SQLAlchemy

from tests.functional.settings import get_settings
from tests.functional.testdata.users_registration import (test_data_for_registration_successfull,
                              test_data_for_registration_fail)

conf = get_settings()
pytestmark = pytest.mark.asyncio

@pytest.mark.parametrize(
    'request_body, expected_body, expected_answer', test_data_for_registration_successfull
)
async def test_registration_successfull(
        auth_api_client: FlaskClient, sqlalchemy_postgres: SQLAlchemy,
        request_body: dict, expected_body: dict, expected_answer: dict
):
    """
    Тест для проверки успешных запросов на регистрацию.

    Проверяет:
    - наличие пользователя после регистрации в бд
    - успешный ответ от серивиса
    """
    from models.db_models import User

    response = auth_api_client.post(f'/registration', json=request_body)
    response_body = response.json
    user = User.query.filter_by(username=request_body['username']).first()

    assert user.username == request_body['username']
    assert response.status_code == expected_answer['status']
    assert response_body == expected_body

@pytest.mark.parametrize(
    'request_body, expected_body, expected_answer', test_data_for_registration_fail
)
async def test_registration_fail(
        auth_api_client: FlaskClient, sqlalchemy_postgres: SQLAlchemy,
        request_body: dict, expected_body: dict, expected_answer: dict
):
    """
    Тест для проверки ошибки регистрации при существовании пользователя с таким логином.

    Проверяет:
    - неудачный ответ от серивиса
    """
    auth_api_client.post(f'/registration', json=request_body)

    response = auth_api_client.post(f'/registration', json=request_body)
    response_body = response.json

    assert response.status_code == expected_answer['status']
    assert response_body == expected_body


"""素因数分解
[素因数1,素因数2, ・・・]　で出力
"""

def prime_factorization(n):
    a = []
    while n % 2 == 0:
        a.append(2)
        n //= 2
    f = 3
    while f * f <= n:
        if n % f == 0:
            a.append(f)
            n //= f
        else:
            f += 2
    if n != 1:
        a.append(n)
    return a


# Databricks notebook source
# MAGIC %md
# MAGIC
# MAGIC Let us go through ranking using Spark SQL and Pyspark.
# MAGIC * Create Data Frame for Daily Product Revenue
# MAGIC * Create Temporary View for Daily Product Revenue
# MAGIC * Ranking using Spark SQL (using `OVER (PARTITION BY grouping_column ORDER BY sorting_column)`)
# MAGIC * Ranking using Pyspark Data Frame APIs (using functions from `pyspark.sql.window`)

# COMMAND ----------

daily_product_revenue = spark. \
    read. \
    format('delta'). \
    load('dbfs:/public/retail_db/daily_product_revenue')

# COMMAND ----------

daily_product_revenue.createOrReplaceTempView('daily_product_revenue')

# COMMAND ----------

# MAGIC %sql
# MAGIC
# MAGIC SHOW tables

# COMMAND ----------

# MAGIC %sql
# MAGIC
# MAGIC SELECT count(*) FROM daily_product_revenue

# COMMAND ----------

# MAGIC %sql
# MAGIC
# MAGIC SELECT dpr.*,
# MAGIC   dense_rank() OVER (PARTITION BY order_date ORDER BY revenue DESC) AS drnk
# MAGIC FROM daily_product_revenue AS dpr
# MAGIC ORDER BY dpr.order_date, dpr.revenue DESC

# COMMAND ----------

# MAGIC %sql
# MAGIC
# MAGIC WITH dpr_ranked AS (
# MAGIC   SELECT dpr.*,
# MAGIC     dense_rank() OVER (PARTITION BY order_date ORDER BY revenue DESC) AS drnk
# MAGIC   FROM daily_product_revenue AS dpr
# MAGIC ) SELECT * FROM dpr_ranked
# MAGIC WHERE drnk <= 5
# MAGIC ORDER BY order_date, revenue DESC

# COMMAND ----------

from pyspark.sql.functions import col

# COMMAND ----------

from pyspark.sql.window import Window

# COMMAND ----------

spec = Window. \
    partitionBy('order_date'). \
    orderBy(col('revenue').desc())

# COMMAND ----------

from pyspark.sql.functions import dense_rank

# COMMAND ----------

daily_product_revenue. \
    withColumn('drnk', dense_rank().over(spec)). \
    filter('drnk <= 5'). \
    orderBy('order_date', col('revenue').desc()). \
    show()

# COMMAND ----------

045 Data Processing using Spark SQL/115 Ranking using Spark SQL Windowing Functions/11 Ranking using Spark SQL and Pyspark.py


import time
from collections import defaultdict

start = None

def print_with_time(string, restart=False):
    global start
    if not start or restart:
        start = time.time()
    elapsed = time.time() - start
    print('{} (+{:.2f}s) {}'.format(time.strftime('%a %H:%M:%S'), elapsed, string))

def read_dfs(file_name):
    dfs = defaultdict(int)
    with open(file_name, 'r') as file:
        num_docs, vocab_size = map(int, file.readline().strip().split())
        for line in file:
            token, count = line.strip().split()
            dfs[token] = int(count)
    assert vocab_size == len(dfs)
    return dfs, num_docs


# -*- coding: utf-8 -*-
"""
Created on Wed Dec 14 22:09:47 2022

@author: Shahir
"""

import os
import pickle
from typing import Any, Optional

import torch
import torch.nn as nn
import torch.optim as optim

from cloudsift.utils import get_timestamp_str

class ModelTracker:
    def __init__(
            self,
            root_dir: str) -> None:

        experiment_dir = "Experiment {}".format(get_timestamp_str())
        self.save_dir = os.path.join(root_dir, experiment_dir)
        self.best_model_metric = float('-inf')
        self.record_per_epoch = {}

    def update_info_history(
            self,
            epoch: int,
            info: Any) -> None:

        os.makedirs(self.save_dir, exist_ok=True)
        self.record_per_epoch[epoch] = info
        fname = "Experiment Epoch Info History.pckl"
        with open(os.path.join(self.save_dir, fname), 'wb') as f:
            pickle.dump(self.record_per_epoch, f)

    def update_model_weights(
            self,
            epoch: int,
            model_state_dict: dict,
            metric: Optional[float] = None,
            save_best: bool = True,
            save_latest: bool = True,
            save_current: bool = False) -> None:

        os.makedirs(self.save_dir, exist_ok=True)
        update_best = metric is None or metric > self.best_model_metric
        if update_best and metric is not None:
            self.best_model_metric = metric

        if save_best and update_best:
            torch.save(model_state_dict, os.path.join(self.save_dir,
                                                      "Weights Best.pckl"))
        if save_latest:
            torch.save(model_state_dict, os.path.join(self.save_dir,
                                                      "Weights Latest.pckl"))
        if save_current:
            torch.save(model_state_dict, os.path.join(self.save_dir,
                                                      "Weights Epoch {} {}.pckl".format(epoch, get_timestamp_str())))

def make_optimizer(
        params_to_update: list[torch.Tensor],
        lr: float = 0.001,
        weight_decay: float = 1e-9,
        clip_grad_norm: bool = False) -> optim.Optimizer:

    optimizer = optim.AdamW(
        params_to_update,
        lr=lr,
        betas=(0.9, 0.999),
        eps=1e-08,
        weight_decay=weight_decay,
        amsgrad=True)

    if clip_grad_norm:
        nn.utils.clip_grad_norm_(params_to_update, 3.0)

    return optimizer

def get_lr(
        optimizer: optim.Optimizer) -> None:

    for param_group in optimizer.param_groups:
        return param_group['lr']

def set_optimizer_lr(
        optimizer: optim.Optimizer,
        lr: float) -> None:

    for param_group in optimizer.param_groups:
        param_group['lr'] = lr

def make_scheduler(
        optimizer: optim.Optimizer) -> optim.lr_scheduler.ReduceLROnPlateau:

    scheduler = optim.lr_scheduler.ReduceLROnPlateau(
        optimizer, factor=0.5, threshold=0.025, patience=10, cooldown=5, min_lr=1e-6, verbose=True)

    return scheduler

def shrink_and_preturb(
        base_net: nn.Module,
        new_net: nn.Module,
        shrink: float = 0.5,
        perturb: float = 0.1) -> nn.Module:

    params1 = base_net.parameters()
    params2 = new_net.parameters()
    with torch.set_grad_enabled(False):
        for p1, p2 in zip(params1, params2):
            p1.mul_(shrink).add_(p2, alpha=perturb)

    return base_net

def load_weights(
        model: nn.Module,
        weights_fname,
        map_location=None) -> nn.Module:

    model.load_state_dict(torch.load(weights_fname, map_location=map_location))

    return model

def save_training_session(
        model: nn.Module,
        optimizer: optim.Optimizer,
        sessions_save_dir: str) -> str:

    sub_dir = "Session {}".format(get_timestamp_str())
    sessions_save_dir = os.path.join(sessions_save_dir, sub_dir)
    os.makedirs(sessions_save_dir, exist_ok=True)

    torch.save(model.state_dict(), os.path.join(
        sessions_save_dir, "Model State.pckl"))
    torch.save(optimizer.state_dict(), os.path.join(
        sessions_save_dir, "Optimizer State.pckl"))
    print("Saved session to", sessions_save_dir)

    return sessions_save_dir

def load_training_session(
        model: nn.Module,
        optimizer: optim.Optimizer,
        session_dir: str,
        update_models: bool = True,
        map_location: Optional[torch.device] = None) -> dict[str, Any]:

    if update_models:
        model.load_state_dict(torch.load(os.path.join(
            session_dir, "Model State.pckl"), map_location=map_location))
        optimizer.load_state_dict(
            torch.load(os.path.join(session_dir, "Optimizer State.pckl"), map_location=map_location))

    print("Loaded session from", session_dir)

    out_data = {
        'model': model,
        'optimizer': optimizer
    }

    return out_data


from dacite import from_dict
from elasticsearch import Elasticsearch, NotFoundError

from service.models import FinancialBusinessOffer

class ElasticSearchService:
    def __init__(self, host, port, index, secrets):
        self.es_client = Elasticsearch(
            [{'host': host, 'port': int(port), 'scheme': 'https'}],
            basic_auth=(secrets.ES_USER, secrets.ES_PASSWORD),
        )
        self.index = index

    def get_document_by_id(self, document_id) -> FinancialBusinessOffer:
        try:
            document = dict(
                self.es_client.get(index=self.index, id=document_id)['_source']
            )
            return from_dict(data=document, data_class=FinancialBusinessOffer)
        except NotFoundError:
            print(f'Elastic document Not found for {document_id}')

    def get_batch(self, batch_size):
        return self.es_client.search(index=self.index, size=batch_size)

    def get_all_documents(self):
        return self.es_client.search(index=self.index, size=10000)


from django.shortcuts import render, redirect
from .credentials import REDIRECT_URI, CLIENT_SECRET, CLIENT_ID
from rest_framework.views import APIView
from requests import Request, post
from rest_framework import status
from rest_framework.response import Response
from .util import *

class AuthURL(APIView):
    def get(self, request, fornat=None):
        scopes = 'user-read-playback-state user-modify-playback-state user-read-currently-playing playlist-modify-public playlist-modify-private'

        url = Request('GET', 'https://accounts.spotify.com/authorize', params={
            'scope': scopes,
            'response_type': 'code',
            'redirect_uri': REDIRECT_URI,
            'client_id': CLIENT_ID
        }).prepare().url

        return Response({'url': url}, status=status.HTTP_200_OK)

def spotify_callback(request, format=None):
    code = request.GET.get('code')
    error = request.GET.get('error')

    response = post('https://accounts.spotify.com/api/token', data={
        'grant_type': 'authorization_code',
        'code': code,
        'redirect_uri': REDIRECT_URI,
        'client_id': CLIENT_ID,
        'client_secret': CLIENT_SECRET
    }).json()

    access_token = response.get('access_token')
    token_type = response.get('token_type')
    refresh_token = response.get('refresh_token')
    expires_in = response.get('expires_in')
    error = response.get('error')

    if not request.session.exists(request.session.session_key):
        request.session.create()

    update_or_create_user_tokens(
        request.session.session_key, access_token, token_type, expires_in, refresh_token)

    return redirect('/user')

class IsAuthenticated(APIView):
    def get(self, request, format=None):
        is_authenticated = is_spotify_authenticated(
            self.request.session.session_key)
        return Response({'status': is_authenticated}, status=status.HTTP_200_OK)

class GetPlaylists(APIView):
    def get(self, request, format=None):
        # Send request to Spotify for user's playlists.
        host = self.request.session.session_key
        endpoint = "playlists"
        response = execute_user_spotify_api_request(host, endpoint)

        # Return 204 if error.
        if 'error' in response or 'items' not in response:
            return Response({}, status=status.HTTP_204_NO_CONTENT)

        # Get list of playlists.
        items = response.get('items')

        # Return 204 if user has no playlists.
        if not items:
            return Response({}, status=status.HTTP_204_NO_CONTENT)

        # Collect playlist information into a list.
        playlists = []
        for item in items:
            playlist = {
                'playlist_id': item.get('id'),
                'name': item.get('name'),
                'tracks_total': item.get('tracks').get('total'),
            }
            playlists.append(playlist)

        return Response(playlists, status=status.HTTP_200_OK)

class GetPlaylistInfo(APIView):
    def get(self, request, playlist_id, format=None):
        playlist_info = get_playlist_info(self, playlist_id)

        if playlist_info is None:
            return Response({}, status=status.HTTP_204_NO_CONTENT)
        else:
            return Response(playlist_info, status=status.HTTP_200_OK)

class PutPlaylistInfo(APIView):
    def put(self, request, playlist_id, insert_before, range_length, range_start, format=None):
        print(playlist_id, insert_before, range_length, range_start)
        print("------------------------------------------------------------")
        response = put_playlist_info(self, playlist_id, insert_before,
                                     range_length, range_start)
        return Response({}, status=response.status_code)


from odoo import api, fields, models, _

CONST_SETTING_EXPENSE_PRODUCT_ID = 'weladee-expense_product_id'
CONST_SETTING_EXPENSE_PERIOD = 'weladee-expense_period'
CONST_SETTING_EXPENSE_PERIOD_UNIT = 'weladee-expense_period_unit'
CONST_SETTING_EXPENSE_JOURNAL_ID = 'weladee-expense_journal_id'

CONST_SETTING_SYNC_EXPENSE = 'weladee-sync-expense'

class weladee_settings_expense(models.TransientModel):
    _inherit="weladee_attendance.synchronous.setting"
    _description="Weladee settings"

    @api.model
    def get_sync_expense(self):
        return self._get_params_value(CONST_SETTING_SYNC_EXPENSE) == 'Y'

    @api.model
    def get_expense_period_unit(self):
        return self._get_params_value(CONST_SETTING_EXPENSE_PERIOD_UNIT, number=True, default=1)

    @api.model
    def get_expense_period(self):
        return self._get_params_value(CONST_SETTING_EXPENSE_PERIOD, number=False, default='w')

    @api.model
    def get_expense_product(self):
        return self._get_params_value(CONST_SETTING_EXPENSE_PRODUCT_ID, number=True)

    @api.model
    def get_expense_journal(self):
        return self._get_params_value(CONST_SETTING_EXPENSE_JOURNAL_ID, number=True)

    expense_product_id = fields.Many2one("product.product", String="Expense product",default=get_expense_product )
    expense_period_unit = fields.Integer('Period Unit', default=get_expense_period_unit)
    expense_period = fields.Selection([('w','week(s) ago'),
                                        ('m','month(s) ago'),
                                        ('y','year(s) ago'),
                                        ('all', 'All')], string='Since', default=get_expense_period)
    expense_journal_id = fields.Many2one("account.journal", String="Expense journal",domain=[('type','=','purchase')],default=get_expense_journal )

    sync_expense = fields.Boolean('Sync Expense', default=get_sync_expense)

    @api.model
    def get_settings(self):
        r = super(weladee_settings_expense, self).get_settings()
        r.sync_expense = self.get_sync_expense()

        r.expense_period_unit = self.get_expense_period_unit()
        r.expense_period = self.get_expense_period()
        r.expense_product_id = self.get_expense_product()
        r.expense_journal_id = self.get_expense_journal()

        return r

    def saveBtn(self):
        ret = super(weladee_settings_expense, self).saveBtn()

        config_pool = self.env['ir.config_parameter']
        if self.sync_expense:
           self._save_setting(config_pool, CONST_SETTING_EXPENSE_PRODUCT_ID, self.expense_product_id.id)
           self._save_setting(config_pool, CONST_SETTING_EXPENSE_PERIOD_UNIT, self.expense_period_unit)
           self._save_setting(config_pool, CONST_SETTING_EXPENSE_PERIOD, self.expense_period)
           self._save_setting(config_pool, CONST_SETTING_EXPENSE_JOURNAL_ID, self.expense_journal_id.id)

        self._save_setting(config_pool, CONST_SETTING_SYNC_EXPENSE, "Y" if self.sync_expense else "")
        return ret


# https://www.testdome.com/d/python-interview-questions/9
"""A palindrome is a word that reads the same backward or forward.

Write a function that checks if a given word is a palindrome. Character case should be ignored.

For example, is_palindrome("Deleveled") should return True as character case should be ignored, resulting in "deleveled", which is a palindrome since it reads the same backward and forward."""

class Palindrome:

    @staticmethod
    def is_palindrome(word):
        reversed_word = word[::-1]
        if word.lower() == reversed_word.lower():
            return True
        else:
            return False

print(Palindrome.is_palindrome('Deleveled'))


'''
방문체크는 왔던 곳 한 번 더 안 오려고!!
벽을 한 번도 안 부셨을 때, 벽을 이미 부수고 지나왔을 때
나눠서 방문 체크 두 번 하기
벽을 한 번 부수고 왔을 때는 갈 수 없는 길이어도(-1 return)
한 번도 부수지 않았을 때는 가능한 길이 될 수 있음
'''
import sys
input = sys.stdin.readline
from collections import deque

N, M = map(int, input().split())
graph = [list(map(int, input().rstrip())) for _ in range(N)]

def bfs(N, M):
    visited = [[[0] * M for _ in range(N)] for _ in range(2)]       # 3차원 배열 (벽을 부시지 않았을 때, 부셨을 때 방문 체크)
    deq = deque([(0, 0, 1, 0)])
    visited[0][0][0] = 1

    di = [-1, 1, 0, 0]
    dj = [0, 0, -1, 1]

    while deq:
        i, j, cnt, broken = deq.popleft()

        if i == N-1 and j == M-1:
            return cnt

        for k in range(4):
            ni = i + di[k]
            nj = j + dj[k]
            if ni in range(N) and nj in range(M):
                if graph[ni][nj] == 0 and not visited[broken][ni][nj]:
                    deq.append((ni, nj, cnt+1, broken))
                    visited[broken][ni][nj] = 1

                elif graph[ni][nj] == 1 and not visited[1][ni][nj]:    # 벽이면 한 번 부수기
                    if broken == 0:
                        deq.append((ni, nj, cnt+1, 1))
                        visited[1][ni][nj] = 1

    return -1

print(bfs(N, M))


from wx import PySimpleApp, DirDialog, DD_DEFAULT_STYLE, DD_NEW_DIR_BUTTON, ID_OK

def choose_dir():
    """图形方式选择路径"""
    app = PySimpleApp()
    dialog = DirDialog(None, "选择安装目录", style=DD_DEFAULT_STYLE | DD_NEW_DIR_BUTTON)
    if dialog.ShowModal() == ID_OK:
        return dialog.GetPath()

if __name__ == '__main__':
    choose_dir()


"""
=====
Shape
=====

``Shape`` is used to calculate shape properties using 3D capsule geometry.
Outputs `length and `surface_area` are determined from inputs `volume` and `width`.
These variables are required to plug into a `Lattice Environment`
"""

import math

from scipy.constants import N_A
from vivarium.core.process import Step
from vivarium.library.units import units, Quantity

PI = math.pi
AVOGADRO = N_A / units.mol

def length_from_volume(volume, width):
    """
    get cell length from volume, using the following equation for capsule volume, with V=volume, r=radius,
    a=length of cylinder without rounded caps, l=total length:

    :math:`V = (4/3)*PI*r^3 + PI*r^2*a`
    :math:`l = a + 2*r`
    """
    radius = width / 2
    cylinder_length = (volume - (4/3) * PI * radius**3) / (PI * radius**2)
    total_length = cylinder_length + 2 * radius
    return total_length

def volume_from_length(length, width):
    """
    get volume from length and width, using 3D capsule geometry
    """
    radius = width / 2
    cylinder_length = length - width
    volume = cylinder_length * (PI * radius**2) + (4 / 3) * PI * radius**3
    return volume

def surface_area_from_length(length, width):
    """
    get surface area from length and width, using 3D capsule geometry

    :math:`SA = 4*PI*r^2 + 2*PI*r*a`
    """
    radius = width / 2
    cylinder_length = length - width
    surface_area = 4 * PI * radius**2 + 2 * PI * radius * cylinder_length
    return surface_area

def mmol_to_counts_from_volume(volume):
    '''mmol_to_counts has units L/mmol'''
    return (volume * AVOGADRO).to(units.L/units.mmol)

class Shape(Step):
    """Shape Step

    Derives cell length and surface area from width and volume.

    Ports:

    * **cell_global**: Should be given the agent's boundary store.
      Contains variables: **volume**, **width**, **length**, and
      **surface_area**.
    * **periplasm_global**: Contains the **volume** variable for the
      volume of the periplasm.

    Arguments:
        parameters (dict): A dictionary that can contain the
            following configuration options:

            * **width** (:py:class:`float`): Initial width of the cell in
              microns
    """

    name = 'ecoli-shape'
    defaults = {
        'width': 1.0 * units.um,
        'periplasm_fraction': 0.2,
        'cytoplasm_fraction': 0.8,
        'initial_cell_volume': 1.2 * units.fL,
        'initial_mass': 1339 * units.fg,
    }

    def __init__(self, parameters=None):
        super().__init__(parameters)
        self.outer_to_inner_area = math.pow(self.parameters[
            'cytoplasm_fraction'], 1/3)**2

    def ports_schema(self):

        schema = {
            'cell_global': {
                'volume': {
                    '_default': 0 * units.fL,
                    '_updater': 'set',
                    '_emit': True,
                    '_divider': 'split',
                },
                'width': {
                    '_default': 0 * units.um,
                    '_updater': 'set',
                    '_emit': True,
                    '_divider': 'set',
                },
                'length': {
                    '_default': 0 * units.um,
                    '_updater': 'set',
                    '_emit': True,
                    '_divider': 'split',
                },
                'outer_surface_area': {
                    '_default': 0 * units.um**2,
                    '_updater': 'set',
                    '_emit': True,
                    '_divider': 'split',
                },
                'inner_surface_area': {
                    '_default': 0 * units.um**2,
                    '_updater': 'set',
                    '_emit': True,
                    '_divider': 'split',
                },
                'mmol_to_counts': {
                    '_default': 0 / units.millimolar,
                    '_emit': True,
                    '_divider': 'split',
                    '_updater': 'set',
                },
                'mass': {
                    '_default': 0 * units.fg,
                    '_updater': 'set',
                    '_emit': True,
                    '_divider': 'split',
                },
            },
            'listener_cell_mass': {
                '_default': self.parameters['initial_mass'].magnitude,  # fg
            },
            'listener_cell_volume': {
                '_default': self.parameters['initial_cell_volume'].magnitude,  # fL
            },
            'periplasm_global': {
                'volume': {
                    '_default': self.parameters['initial_cell_volume'] * self.parameters['periplasm_fraction'],  # fL
                    '_emit': True,
                    '_divider': 'split',
                    '_updater': 'set',
                },
                'mmol_to_counts': {
                    '_default': 0 / units.millimolar,
                    '_emit': True,
                    '_divider': 'split',
                    '_updater': 'set',
                },
            },
            'cytoplasm_global': {
                'volume': {
                    '_default': self.parameters['initial_cell_volume'] * self.parameters['cytoplasm_fraction'],  # fL
                    '_emit': True,
                    '_divider': 'split',
                    '_updater': 'set',
                },
                'mmol_to_counts': {
                    '_default': 0 / units.millimolar,
                    '_emit': True,
                    '_divider': 'split',
                    '_updater': 'set',
                },
            },
        }
        return schema

    def initial_state(self, config=None):
        cell_volume = self.parameters['initial_cell_volume']
        assert isinstance(cell_volume, Quantity)
        width = self.parameters['width']
        assert isinstance(width, Quantity)
        length = length_from_volume(cell_volume, width)
        outer_surface_area = surface_area_from_length(length, width)
        inner_surface_area = self.outer_to_inner_area * outer_surface_area

        assert self.parameters['periplasm_fraction'] + self.parameters['cytoplasm_fraction'] == 1
        periplasm_volume = cell_volume * self.parameters['periplasm_fraction']
        cytoplasm_volume = cell_volume * self.parameters['cytoplasm_fraction']

        mass = self.parameters['initial_mass']
        assert isinstance(mass, Quantity)
        return {
            'cell_global': {
                'volume': cell_volume,
                'width': width,
                'length': length,
                'outer_surface_area': outer_surface_area,
                'inner_surface_area': inner_surface_area,
                'mmol_to_counts': mmol_to_counts_from_volume(
                    cell_volume),
                'mass': mass,
            },
            'listener_cell_mass': mass.magnitude,
            'listener_cell_volume': cell_volume.magnitude,
            'periplasm_global': {
                'volume': periplasm_volume,
                'mmol_to_counts': mmol_to_counts_from_volume(
                    periplasm_volume),
            },
            'cytoplasm_global': {
                'volume': cytoplasm_volume,
                'mmol_to_counts': mmol_to_counts_from_volume(
                    cytoplasm_volume),
            },
        }

    def next_update(self, timestep, states):
        for port in (
                'cell_global', 'periplasm_global', 'cytoplasm_global'):
            for variable, value in states[port].items():
                assert isinstance(value, Quantity), f"{variable}={value} is not a Quantity"

        width = states['cell_global']['width']
        cell_volume = states['listener_cell_volume'] * units.fL

        assert self.parameters['periplasm_fraction'] + self.parameters['cytoplasm_fraction'] == 1
        periplasm_volume = cell_volume * self.parameters['periplasm_fraction']
        cytoplasm_volume = cell_volume * self.parameters['cytoplasm_fraction']

        # calculate length and surface area
        length = length_from_volume(cell_volume, width)
        outer_surface_area = surface_area_from_length(length, width)
        inner_surface_area = self.outer_to_inner_area * outer_surface_area

        update = {
            'cell_global': {
                'length': length,
                'outer_surface_area': outer_surface_area,
                'inner_surface_area': inner_surface_area,
                'mmol_to_counts': mmol_to_counts_from_volume(
                    cell_volume),
                'mass': states['listener_cell_mass'] * units.fg,
                'volume': cell_volume,
            },
            'periplasm_global': {
                'volume': periplasm_volume,
                'mmol_to_counts': mmol_to_counts_from_volume(
                    periplasm_volume),
            },
            'cytoplasm_global': {
                'volume': cytoplasm_volume,
                'mmol_to_counts': mmol_to_counts_from_volume(
                    cytoplasm_volume),
            }
        }
        return update


from django.conf import settings
ugettext = lambda s: s

Jenis_Material = getattr(settings, 'Jenis_Material',((1, ugettext('Major')),
														(2, ugettext('Minor')),
														(3, ugettext('Colour Material')),
														(4, ugettext('Uncolour')),
														(5, ugettext('Stabilitator')),
														(6, ugettext('Cat Label')),
														(7, ugettext('Case'))))

Warna_Produk = getattr(settings, 'Warna_Produk',((1, ugettext('Flint')),
													(2, ugettext('Amber')),
													(3, ugettext('Green'))))

Label_Produk = getattr(settings, 'Label_Produk',((1, ugettext('Polos')),
													(2, ugettext('Dekorasi'))))

Dapur = getattr(settings, 'Dapur',(('G.1.1 D.G', ugettext('G.1.1 D.G')),
									('G.1.2 D.G', ugettext('G.1.2 D.G')),
									('G.1.3 D.G', ugettext('G.1.3 D.G')),
									('G.2.1 D.G', ugettext('G.2.1 D.G')),
									('G.2.2 D.G', ugettext('G.2.2 D.G')),
									('G.2.3 D.G', ugettext('G.2.3 D.G'))))

Status_Dapur = getattr(settings, 'Status_Dapur',((1, ugettext('PRODUKSI')),
												(2, ugettext('STOP PRODUKSI'))))

ACL = getattr(settings, 'ACL',(('ACL-1', ugettext('ACL-1')),
									('ACL-2', ugettext('ACL-2')),
									('ACL-3', ugettext('ACL-3')),
									('ACL-4', ugettext('ACL-4'))))

Status_ACL = getattr(settings, 'Status_ACL',((1, ugettext('PRODUKSI')),
												(2, ugettext('STOP PRODUKSI'))))

TIM = getattr(settings, 'TIM',(('PRODUKSI', ugettext('PRODUKSI')),
											('ACL', ugettext('ACL')),
											('PENGEMASAN', ugettext('PENGEMASAN'))))

Initial = getattr(settings, 'Initial',(('A', ugettext('A')),
										('B', ugettext('B')),
										('C', ugettext('C')),
										('D', ugettext('D')),
										('E', ugettext('E')),
										('F', ugettext('F'))))

Inspect = getattr(settings, 'Inspect',((1, ugettext('Target')),
												(2, ugettext('Pencapaian'))))

LEVEL_AKSES_CHOICES =  getattr(settings, 'LEVEL_AKSES_CHOICES', (('Seksi', ugettext('Seksi')),
																	('Kadep', ugettext('Kadep')),
																	('Direktur', ugettext('Direktur')))) #nanti Direktur rubah ke kasi

STACHOLDER =  getattr(settings, 'STACHOLDER', (('Departemen Inventori', ugettext('Departemen Inventori')),
																	('Departemen Sales', ugettext('Departemen Sales')),
																	('Departemen Assest', ugettext('Departemen Assest'))))

Kategori_Produk = getattr(settings, 'Kategori_Produk', ((1, ugettext('Generic')),
										(2, ugettext('Patent'))))


from django.contrib.auth.decorators import login_required
from django.views.decorators.csrf import csrf_exempt
from django.shortcuts import render, redirect, get_object_or_404
from question_box.models import Question, Answer, Favorite, Category
from users.models import User
from question_box.forms import QuestionForm, AnswerForm
from django.utils.text import slugify
from django.http import JsonResponse
import json
from django.contrib import messages

@login_required
def question_list(request):
    questions = Question.objects.all()
    # favorite_questions = get_user_favorite(request)
    return render(request, 'core/question_list.html', {'questions': questions})

def question_details(request, pk):
    question = get_object_or_404(Question, pk=pk)
    answers = Answer.objects.filter(response=question.pk)
    if request.method == "POST":
        form = AnswerForm(request.POST)
        if form.is_valid():
            answer = form.save(commit=False)
            answer.response = question
            answer.save()
            return redirect('question-details', pk=pk)
    else:
        form = AnswerForm()
        return render(request, 'core/question_details.html', {'question': question, 'answers':answers, 'form': form, 'user':request.user})

def question_add(request):
    if request.method == "POST":
        form = QuestionForm(request.POST)
        if form.is_valid():
            question = form.save(commit=False)
            question.save()
            return redirect('question-list')
    else:
        form = QuestionForm()
        return render(request, 'core/question_add.html', {'form': form})

# @csrf_exempt
# def question_add(request):
#     data = json.loads(request.body.decode('utf-8'))
#     question_body = data.get("questionBody")
#     question_title = data.get("questionTitle")
#     new_question = Question.objects.create(title=question_title, body=question_body,)
#     if question_body and question_title:
#         return JsonResponse(
#             {
#         "status":"ok",
#         "data": {
#             "pk": new_question.pk,
#             "title": new_question.title,
#             "body": new_question.body,
#         },
#     })

def question_delete(request, pk):
    question = get_object_or_404(Question, pk=pk)
    if question.creator.pk == request.user.pk:
        question.delete()
        return redirect('question-list')
    else:
        messages.add_message(request, messages.INFO, 'You do not have the authority to delete this question.')

# def answer_add(request, pk):
#     question = get_object_or_404(Question, pk=pk)
#     answers = Answer.objects.filter(response=question.pk)
#     if request.method == "POST":
#         form = AnswerForm(request.POST)
#         if form.is_valid():
#             answer = form.save(commit=False)
#             answer.save()
#             return redirect('question-details')
#     else:
#         form = AnswerForm()
#     return render(request, 'core/answer_add.html', {'form': form})

def tagged(request, slug):
    # Filter books by tag name
    tag = Category.objects.get(slug=slug)
    questions = Question.objects.filter(tag=tag)
    return render(request, 'core/question_list.html', {'tag': tag, 'questions': questions})

# ********trying to make favorites work************

def favorite(request, question_pk):
    # for favorite in books:
    question = get_object_or_404(Question, pk=question_pk)
    favorite = Favorite.objects.create(owner=request.user, question=question)
    print(favorite)
    return render(request, 'core/question_details.html', {'question': question})

# def get_user_favorite(request):
#     user = User.objects.get(username=request.user.username)
#     favorite_questions = [favorite.questions for favorite in user.favorites.all()]
#     return favorite_questions


from typing import Tuple, Optional

import aiohttp
import orjson

from polyschedule.exceptions import GettingScheduleError

async def _request_schedule_json(group_id, date) -> dict:
    async with aiohttp.ClientSession() as session:
        async with session.get(f'https://ruz.spbstu.ru/api/v1/ruz/scheduler/{group_id}?date={date}') as response:
            return orjson.loads(await response.text())

async def get_week(group_id, date) -> Tuple[dict, Optional[list]]:
    week_json = await _request_schedule_json(group_id, date)

    if week_json.get('error'):
        raise GettingScheduleError(week_json['text'])

    week_info = week_json['week']
    week_schedule = week_json['days']

    return week_info, week_schedule or None

async def get_day(group_id, date) -> Optional[dict]:
    _, week_schedule = await get_week(group_id, date)

    if not week_schedule:
        return None

    matched_day = [i for i in week_schedule if i['date'] == date]

    return matched_day[0] if matched_day else None


import sys
import gc
import time
import os
import logging
from multiprocessing import Pool, current_process
from multiprocessing import log_to_stderr, get_logger
from tqdm import tqdm
from numba import jit

import pyarrow.parquet as pq
import pandas as pd
import numpy as np

import keras
import keras.backend as K
from keras.layers import LSTM,Dropout,Dense,TimeDistributed,Conv1D,MaxPooling1D,Flatten
from keras.models import Sequential
import tensorflow as tf

from IPython.display import display, clear_output

import matplotlib.pyplot as plt
import seaborn as sns

sns.set_style("whitegrid")
import pyarrow.parquet as pq
import pandas as pd
import numpy as np
train_set = pq.read_pandas('../input/train.parquet').to_pandas()
meta_train = pd.read_csv('../input/metadata_train.csv')
@jit('float32(float32[:,:], int32)')
def feature_extractor(x, n_part=1000):
    lenght = len(x)
    pool = np.int32(np.ceil(lenght/n_part))
    output = np.zeros((n_part,))
    for j, i in enumerate(range(0,lenght, pool)):
        if i+pool < lenght:
            k = x[i:i+pool]
        else:
            k = x[i:]
        output[j] = np.max(k, axis=0) - np.min(k, axis=0)
    return output
x_train = []
y_train = []
for i in tqdm(meta_train.signal_id):
    idx = meta_train.loc[meta_train.signal_id==i, 'signal_id'].values.tolist()
    y_train.append(meta_train.loc[meta_train.signal_id==i, 'target'].values)
    x_train.append(abs(feature_extractor(train_set.iloc[:, idx].values, n_part=400)))
del train_set; gc.collect()
y_train = np.array(y_train).reshape(-1,)
X_train = np.array(x_train).reshape(-1,x_train[0].shape[0])
def keras_auc(y_true, y_pred):
    auc = tf.metrics.auc(y_true, y_pred)[1]
    K.get_session().run(tf.local_variables_initializer())
    return auc
n_signals = 1 #So far each instance is one signal. We will diversify them in next step
n_outputs = 1 #Binary Classification
#Build the model
verbose, epochs, batch_size = True, 15, 16
n_steps, n_length = 40, 10
X_train = X_train.reshape((X_train.shape[0], n_steps, n_length, n_signals))
# define model
model = Sequential()
model.add(TimeDistributed(Conv1D(filters=64, kernel_size=3, activation='relu'), input_shape=(None,n_length,n_signals)))
model.add(TimeDistributed(Conv1D(filters=64, kernel_size=3, activation='relu')))
model.add(TimeDistributed(Dropout(0.5)))
model.add(TimeDistributed(MaxPooling1D(pool_size=2)))
model.add(TimeDistributed(Flatten()))
model.add(LSTM(100))
model.add(Dropout(0.5))
model.add(Dense(100, activation='relu'))
model.add(Dense(n_outputs, activation='sigmoid'))
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=[keras_auc])
model.fit(X_train, y_train, epochs=epochs, batch_size=batch_size, verbose=verbose)
model.save_weights('model1.hdf5')
#%%time
meta_test = pd.read_csv('../input/metadata_test.csv')
def process_chunk(arg):
    start_index = arg['start_index']
    chunk_size = arg['chunk_size']

    # Test set indices start at 8712
    test_set_start = 8712
    offset_index = (test_set_start + start_index)

    # Column name must be a string
    subset_test = pq.read_pandas('../input/test.parquet', columns=[str(offset_index + j) for j in range(chunk_size)]).to_pandas()
    x_test = []
    for j in range(chunk_size):
        subset_test_row = subset_test[str(offset_index + j)]
        x_test.append(abs(feature_extractor(subset_test_row.values, n_part=400)))
    return x_test
# Define 21 chunks for processing the test set
# on multiple cpus. I have choosen to process in chunks of 1000 (plus the remainder)
# so as to keep within the kernels memory limit
args = []
for i in range(0, 20000, 1000):
    args.append({
        'start_index': i,
        'chunk_size': 1000
    })

# Add a chunk for the remainder
args.append({
    'start_index': 20000,
    'chunk_size': 337
})

n_cpu = processes=os.cpu_count()
print('n_cpu: ', n_cpu)

p = Pool(processes=n_cpu)

# Map the chunk args to the the process_chunk function
x_test_chunks = p.map(process_chunk, args)
print(f"multi processing complete. len: {len(x_test_chunks)}")

p.close()
p.join()
x_test = [item for sublist in x_test_chunks for item in sublist]
x_test = np.array(x_test)
print('x_test.shape: ', x_test.shape)
X_test = x_test.reshape((x_test.shape[0], n_steps, n_length, n_signals))
del x_test_chunks
preds = model.predict(X_test)
preds.shape
threshpreds = (preds>0.5)*1
sub = pd.read_csv('../input/sample_submission.csv')
sub.target = threshpreds

# Gave me an LB score of ~0.450
sub.to_csv('submission.csv',index=False)
check_sub = pd.read_csv('submission.csv')
check_sub.head(20)


#!/usr/bin/env python
# -*- coding: utf-8 -*-
import urllib.request as urllib
import json
from datetime import datetime,timedelta
import re

output="/tmp/muell.ics"
idx="termins"
city_id="71186"
area_id="71186"
#alert_lead_time_sec=21600
alert_length_time_sec=3600
url = "https://mymuell.jumomind.com/webservice.php?idx="+idx+"&city_id="+city_id+"&area_id="+area_id
#import_garbage_type=["EICH_BIO", "LK_EICH_PAP", "LK_EICH_REST", "LK_EICH_GELB3","LK_EICH_GELB2","LK_EICH_GELB1"]
import_garbage_type=["EICH_BIO", "LK_EICH_PAP", "LK_EICH_REST", "LK_EICH_GELB2"]
import_translation = {
'EICH_BIO': 'Grünzeug',
'LK_EICH_PAP': 'Pappzeug',
'LK_EICH_REST': 'Restzeug',
'LK_EICH_GELB3': 'Plastikzeug'}

def create_ical(cal_id, cal_garbage_type, cal_date_start, cal_date_end, cal_date_created):
    return  "PRODID:peppisLittleHelper\r\n" \
            "METHOD:PUBLISH\r\n" \
            "BEGIN:VEVENT\r\n" \
            "UID:"+cal_id + "\r\n"\
            "LOCATION:Strasse\r\n" \
            "SUMMARY:"+cal_garbage_type + "\r\n" \
            "DESCRIPTION:"+cal_garbage_type + "\r\n" \
            "CLASS:PUBLIC\r\n" \
            "DTSTART;VALUE=DATE:" + datetime.strftime(cal_date_start,"%Y%m%d") + "\r\n" \
            "DTEND;VALUE=DATE:" + datetime.strftime(cal_date_end,"%Y%m%d") + "\r\n" \
            "DTSTAMP:" + datetime.strftime(cal_date_created,"%Y%m%dT%H%M%SZ") + "\r\n" \
            "END:VEVENT\r\n\r\n"  \

def multipleReplace(text, wordDict):
    """
    take a text and replace words that match the key in a dictionary
    with the associated value, return the changed text
    """
    for key in wordDict:
        text = text.replace(key, wordDict[key])
    return text

json_object = urllib.urlopen(url)
data = json.loads(json_object.read().decode())
f = open(output, "a")
f.write("BEGIN:VCALENDAR\r\n" \
"VERSION:2.0\r\n" )

for item in data:
    _data=(item["_data"])
    for _item in _data:
        if _item["cal_garbage_type"] in import_garbage_type:
            cal_id=_item["cal_id"]
            cal_date=_item["cal_date"]
            cal_date_normal=_item["cal_date_normal"]
            cal_garbage_type=_item["cal_garbage_type"]
            cal_comment=_item["cal_comment"]

            #convert string to datetime
            cal_date = datetime.strptime(cal_date, "%Y-%m-%d")

            #calc the cal_date_start & cal_date_end
            #cal_date_start=cal_date - timedelta(seconds=alert_lead_time_sec)
            #cal_date_end=cal_date - timedelta(seconds=alert_lead_time_sec) + timedelta(seconds=alert_length_time_sec)
            cal_date_start=cal_date
            cal_date_end=cal_date + timedelta(seconds=alert_length_time_sec)

            cal_date_created = datetime.now()
            #replace the strings
            cal_garbage_type = multipleReplace(cal_garbage_type,import_translation)

            ical= create_ical(_item["cal_id"], cal_garbage_type, cal_date_start, cal_date_end, cal_date_created)

            f.write(ical)
f.write("END:VCALENDAR")
f.close()


import sys

def solution(str):
    stack = []
    for i in range(len(str)):
        char = str[i]
        if char == '(' or char == '[':
            stack.append(char)

        elif char == ')':
            if len(stack) > 0 and stack[-1] == '(':
                stack.pop()
            else:
                stack.append(char)
        elif char == ']':
            if len(stack) > 0 and stack[-1] == '[':
                stack.pop()
            else:
                stack.append(char)

    print('yes') if len(stack) == 0 else print('no')

if __name__ == '__main__':
    arr = []
    while True:
        str = sys.stdin.readline()[:-1]
        if str == '.':
            print(str)
            break
        solution(str)