"""Snooper is a data processor created for the purpose of downloading JSON data from supported
    WeedMaps APIs to be converted into Pandas DataFrames and stored in multiple different formats.
    1. Objects
        1. data_dir
            os.path data directory used for saving / exporting data from snooper.
        2. save_file
            the primary save file for snooper to export to.
        3. export_file
            an optional test export file for snooper to export to.
    2. Classes
        1. Snooper
            the primary application class for snooper.
"""
import json
import os.path
from datetime import datetime
from pathlib import Path
from lib import actors
from lib import util

# Data directory
data_dir = os.path.dirname(os.path.abspath(__file__))+"/data"
Path(data_dir).mkdir(parents=True, exist_ok=True)

# Primary save file
save_file = data_dir+"/snooper.json"

# debug save file
export_file = data_dir+"/export.json"

class Snooper:
    """
    A class used to represent the primary application of the snooper package.

    Attributes
    ----------
    data_lib : dict
        dictionary representing data stored from converted json received from WeedMaps.

    app : Object/Snooper
        object representing the class executable of Snooper. only accessed if this file is
        ran as main.

    Regions : Object/actors.WMRegions
        Data processor for WeedMaps Regions

    SubRegions : Object/actors.WMSubRegions
        Data processor for WeedMaps SubRegions

    Dispensaries : Object/actors.WMDispensaries
        Data processor for WeedMaps dispensary listings

    Menus : Object/actors.WMMenus
        Data processor for WeedMaps listing menu items

    Deals : Object/actors.WMDeals
        Data processor for WeedMaps deals

    Pandas : Object/util.SnooperToPandas
        addon object that provides additional support via methods for pandas

    selected_region : dict
        dictionary of data extracted using matching method.

    selected_subregion : dict
        dictionary of data extracted using matching method.

    selected_listing : dict
        dictionary of data extracted using matching method.

    selected_menu : dict
        dictionary of data extracted using matching method.

    selected_item : dict
        dictionary of data extracted using matching method.

    Methods
    -------
    select_region(region_slug)
        Stores region data from data_lib in memory using region_slug as key.

    select_subregion(subregion_slug)
        Stores subregion data from data_lib in memory using subregion_slug as key.

    select_listing(listing)
        Stores listing data from data_lib in memory using listing_slug as key.

    select_menu()
        Stores menu data from data_lib in memory using the stored listing data from select_listing.

    load_json(file)
        Loads json from file into data_lib

    save_json(file)
        Saves data from data_lib as json into file

    main()
        Primary standalone executable function of snooper
    """
    data_lib = {}

    def __init__(self):
        """
        Constructs all the necessary attributes for the Snooper object.

        Parameters
        ----------
        None

        """
        self.Regions=actors.WMRegions(self)
        self.SubRegions = actors.WMSubRegions(self)
        self.Dispensaries = actors.WMDispensaries(self)
        self.Menus = actors.WMMenus(self)
        self.Deals = actors.WMDeals(self)
        self.Pandas = util.SnooperToPandas(self)
        self.selected_region = None
        self.selected_subregion = None
        self.selected_listing = None
        self.selected_menu = None
        self.selected_item = None
        print("Creating Snooper App") # DEBUG

    def select_region(self, region_slug):
        """
        Selects a region using region_slug as a key for data_lib

        Parameters
        ----------
        region_slug : str
            A string representing the key of the region to extract from data_lib.

        Returns
        -------
        None
        """
        try:
            self.selected_region = self.data_lib[region_slug]
            print(f"Selected region: {region_slug}")
        except KeyError:
            print("Sorry, but that region doesn't appear to be loaded. \
                Refresh region data and try again.")

    def select_subregion(self, subregion_slug):
        """
        Selects a subregion using subregion_slug as a key for selected_region

        Parameters
        ----------
        subregion_slug : str
            A string representing the key of the subregion to extract from selected_region.

        Returns
        -------
        None
        """
        try:
            self.selected_subregion = self.selected_region[subregion_slug]
            print(f"Selected subregion: {subregion_slug}")
        except KeyError:
            print("Sorry, but that subregion doesn't appear to be loaded. \
                Refresh subregion and try again.")
        except TypeError:
            print("Sorry, but you must select a region first before attempting to select \
                a subregion.")

    def select_listing(self, listing_slug):
        """
        Selects a dispensary listing using listing_slug as a key for selected_subregion

        Parameters
        ----------
        listing_slug : str
            A string representing the key of the listing to extract from selected_subregion.

        Returns
        -------
        None
        """
        try:
            self.selected_listing = self.selected_subregion['listings'][listing_slug]
            print(f"Selected listing: {listing_slug}")
        except KeyError:
            print("Sorry, but that listing doesn't appear to be loaded. \
                Refresh subregion listings and try again.")
        except TypeError:
            print("Sorry, but you must select a subregion first before attempting to \
                select a listing.")

    def select_menu(self):
        """
        Selects the menu listing from selected_listing

        Parameters
        ----------
        None

        Returns
        -------
        None
        """
        try:
            self.selected_menu = self.selected_listing['menu']
            print(f"Selected Menu: {self.selected_listing['slug']}")
        except KeyError:
            print("Sorry, but that listing doesn't appear to have a menu loaded. \
                Refresh menus for listing or subregion and try again.")
        except TypeError:
            print("Sorry, but you must select a listing first before attempting to select a menu.")

    # def select_item(self, item_slug):
    #     pass

    def load_json(self, file):
        """
        Loads json from file and saves into data_lib as dict.

        Parameters
        ----------
        file : str
            path to file that should be used for data export

        loaded : boolean
            boolean representing the load success state of the file

        Returns
        -------
        loaded : boolean
        """
        loaded = False
        try:
            # in_file = open(common.save_file, "r")
            with open(file, encoding="utf8") as in_file:
                print("Loading data from file...")
                self.data_lib = json.load(in_file)
                print("Data loaded!")
                loaded = True
        except FileNotFoundError:
            print("File not found: Starting from scratch!")
            self.data_lib={}
        return loaded

    def save_json(self, file, data):
        """
        Saves data_lib to a file as json.

        Parameters
        ----------
        file : str
            path to file that should be used for data export
        data
            dictionary to write to file as json

        Returns
        -------
        None
        """
        print("Saving JSON file")
        with open(file, "w", encoding="utf8") as out_file:
            out_file.truncate()
            json.dump(data, out_file)

    def main(self):
        """
        Primary executable function of Snooper

        Parameters
        ----------
        None

        Returns
        -------
        None
        """
        start_time = datetime.now()
        print("Running main()")
        # if self.load_json(save_file):
        #     # Define pandas DataFrames
        #     listings_frame = self.Pandas.listings()
        #     subregion_menus_frame = self.Pandas.subregion_menus()
        #     # subregion_deals_frame = self.Pandas.subregion_deals()
        #     region_deals_frame = self.Pandas.region_deals()

        #     # Export to CSV
        #     listings_frame.to_csv(data_dir + "/listings.csv")
        #     subregion_menus_frame.to_csv(data_dir + "/subregion_menus.csv")
        #     region_deals_frame.to_csv(data_dir + "/region_deals.csv")

        # else:
        # Download subregions for region
        self.Regions.get_subregions("oklahoma")

        # Select desired region and subregion
        self.select_region("oklahoma")
        self.select_subregion('oklahoma-city')

        # Download data for export
        self.SubRegions.get_listings(self.selected_subregion)
        self.Regions.get_menus()
        self.Regions.get_deals()

        # Define pandas DataFrames
        listings_frame = self.Pandas.listings()
        subregion_menus_frame = self.Pandas.subregion_menus()
        # subregion_deals_frame = self.Pandas.subregion_deals()
        region_deals_frame = self.Pandas.region_deals()

        # Export to CSV
        listings_frame.to_csv(data_dir + "/listings.csv")
        subregion_menus_frame.to_csv(data_dir + "/subregion_menus.csv")
        region_deals_frame.to_csv(data_dir + "/region_deals.csv")

        # Save to JSON
        self.save_json(export_file, self.data_lib)
        print(f"Time: {datetime.now() - start_time}")

if __name__ == "__main__":
    app = Snooper()
    app.main()


import pandas
import numpy as np
from sklearn.cross_validation import KFold
from sklearn.ensemble import RandomForestRegressor
from sklearn.grid_search import GridSearchCV

def main():
    data = pandas.read_csv('abalone.csv')
    data['Sex'] = data['Sex'].map(lambda x:
                                  1 if x == 'M' else (-1 if x == 'F' else 0))
    features = np.asarray(data.ix[:, :'ShellWeight'])
    markers = np.asarray(data['Rings'])
    grid = {'n_estimators': range(1, 51)}
    cv = KFold(n=len(markers), n_folds=5, shuffle=True, random_state=1)
    reg = RandomForestRegressor(random_state=1)
    gs = GridSearchCV(reg, grid, scoring='r2', cv=cv)
    gs.fit(features, markers)

    means = [score_tuple[1] for score_tuple in gs.grid_scores_]
    n_estimators = np.array(np.where(np.asarray(means) > 0.52)) + 1
    print(n_estimators[0][0])

if __name__ == "__main__":
    main()


import pandas as pd
import glob
import os
import re
import datetime
import matplotlib.pyplot as plt
from tqdm import tqdm
import copy
import numpy as np

os.chdir("D:\\[山口]研究\\YJFX\\2018_USDJPY")

pickle_file = sorted(glob.glob( "*.pickle"))
month = "feb"
if month == "feb":
    file = sorted(glob.glob( "USD_JPY_201802**_data.pickle"))
    month = "february"
elif month == "sep":
    file = sorted(glob.glob( "USD_JPY_201809**_data.pickle"))
    month = "september"

for i in tqdm(file[1:2]):
    print(i)
#     i = file[2]#pickle_file[31:59]:#pickle_file[243:273]
    os.chdir("D:\\[山口]研究\\YJFX\\2018_USDJPY")
    name = re.search("(.*)(?=.pickle)",i).group()
    date = re.search("[0-9]+",i).group()
    #残すデータを入れる
    df = pd.read_pickle(i)[["Date","Time","Price","Amount","Event_Type","Distance","Gender_Side"]]
    index =  df.Date +" "+ df.Time
    index = index.apply(lambda x: datetime.datetime.strptime(x,"%Y/%m/%d %H:%M:%S.%f"))
    df.index = index
    #最終的に残すやつ
    tmp = df[["Event_Type","Gender_Side","Distance","Amount","Price"]]
    tmp.Price = tmp.Price.replace("",0)
    tmp.Price = tmp.Price.astype("float")
    tmp.Amount = tmp.Amount.astype("float")

    # データセット読み込み
    # df = pd.read_pickle("C:\\Users\\Owner\\Desktop\\OrderBook\\september\\target4\\data\\min\\20180903_target4_N100_TW1min_F1.pickle")
    features = pd.DataFrame()
    sell_features = pd.DataFrame()
    buy_features = pd.DataFrame()
    timelist = sorted(list(set(tmp.index)))
    # print(len(timelist))
    next_start_time= timelist[0]
    for df_indx in tqdm(timelist):
        _ = copy.deepcopy(tmp[next_start_time:df_indx])
        try:
            dp = _[_.Event_Type=="D"].Price[-1]
            next_start_time = _[_.Event_Type=="D"].Price.index[-1]

        except IndexError:
            dp = np.nan
            stay_pressure = pd.DataFrame([np.nan],columns=["stay_amount"],index=[df_indx])
            move_pressure = pd.DataFrame(np.array([np.nan]*9).reshape(1,9),columns=["Layer"+str(i) for i in range(1,10)],index=[df_indx])
            sell_values = pd.DataFrame(np.array([np.nan]*10).reshape(1,10),columns=["Sell_Side"+str(i) for i in range(1,11)],index=[df_indx])
            buy_values = pd.DataFrame(np.array([np.nan]*10).reshape(1,10),columns=["Buy_Side"+str(i) for i in range(1,11)],index=[df_indx])
            sell_features = pd.concat([sell_features, sell_values])
            buy_features = pd.concat([buy_features, buy_values])
            feature = pd.concat([stay_pressure, move_pressure],axis=1)
            features = pd.concat([features,feature])
            continue

        indx = ((tmp[:df_indx].Event_Type=="Q") & (tmp[:df_indx].Gender_Side=="0"))
        indx = indx[indx==True].index[-1]
        if next_start_time > indx :
            next_start_time = indx

        tmp2 = copy.deepcopy(_.loc[indx:indx,:])
        tmp2 = tmp2[(tmp2.Event_Type=="Q") & (tmp2.Gender_Side=="0") ]
        tmp2 = tmp2[tmp2.Gender_Side=="0"]
        # print(tmp2.index[1])
        tmp2["Price"] = tmp2["Price"] - dp

        stay_amount = 0.0
        values = np.zeros(9)
        #約定価格に注文あるとき
        if len(tmp2[tmp2["Price"]==0.0])!=0:
            #前約定価格の注文量を抽出
            stay_amount += tmp2[tmp2["Price"]==0.0].Amount.item()
            tmp2 = tmp2[tmp2["Price"]!=0.0]

        v = np.round((tmp2.Amount).values,decimals=1)[:9]
        values[:len(v)] = v
        buy_values = values
        buy_feature = pd.DataFrame(buy_values.reshape(1, 9), columns = ["Buy_Side" + str(i) for i in range(1, 10)], index = [df_indx])
        buy_features = pd.concat([buy_features, buy_feature])
    #     buy_price = (tmp2.Price+dp).values[:9]
        # buy_pressure = np.cumsum(values[:9])

        indx = ((tmp[:df_indx].Event_Type=="Q") & (tmp[:df_indx].Gender_Side=="1"))
        indx = indx[indx==True].index[-1]
        if next_start_time > indx :
            next_start_time = indx

        tmp2 = copy.deepcopy(_.loc[indx:indx,:])
        tmp2 = tmp2[tmp2.Event_Type=="Q"]
        tmp2 = tmp2[tmp2.Gender_Side=="1"]

        tmp2["Price"] = tmp2["Price"] - dp

        values = np.zeros(9)
        if len(tmp2[tmp2["Price"]==0.0])!=0:
            #前約定価格に注文なし
            stay_amount += tmp2[tmp2["Price"]==0.0].Amount.item()
            tmp2 = tmp2[tmp2["Price"]!=0.0]

        v = np.round((tmp2.Amount).values,decimals=1)[:9]
        values[:len(v)] = v
        sell_values = values
        sell_feature = pd.DataFrame(sell_values.reshape(1, 9), columns = ["Sell_Side" + str(i) for i in range(1, 10)], index = [df_indx])
        sell_features = pd.concat([sell_features, sell_feature])
        # sell_price = (tmp2.Price+dp).values[:9]
        # sell_pressure = np.cumsum(values[:9])

        stay_pressure = pd.DataFrame([stay_amount],columns=["stay_amount"],index=[df_indx])
        move_pressure = pd.DataFrame((buy_values - sell_values).reshape(1,9),columns=["Layer"+str(i) for i in range(1,10)],index=[df_indx])
        # sell_values = pd.DataFrame(sell_values.reshape(1,9),columns=["Sell_Side"+str(i) for i in range(1,10)],index=[df_indx])
        # buy_values = pd.DataFrame(buy_values.reshape(1,9),columns=["Buy_Side"+str(i) for i in range(1,10)],index=[df_indx])
    #     stay_pressure = pd.DataFrame([stay_amount],columns=["stay_amount"],index=[df.index[df_indx]])
    #     buy_price = pd.DataFrame(buy_price.reshape(1,9),columns=["buy_price"+str(i) for i in range(1,10)],index=[df.index[df_indx]])
    #     sell_price = pd.DataFrame(sell_price.reshape(1,9),columns=["sell_price"+str(i) for i in range(1,10)],index=[df.index[df_indx]])
    #     feature = pd.concat([stay_pressure,move_pressure],axis=1)

        feature = pd.concat([stay_pressure, move_pressure],axis=1)
        features = pd.concat([features,feature])

    os.chdir("D:\\[山口]研究\\YJFX\\new_pbf_d\\move_pressure")
    features.to_pickle(date+"_price_based_features.pickle")

    os.chdir("D:\\[山口]研究\\YJFX\\new_pbf_d\\sell_pressure")
    sell_features.to_pickle(date+"_Sell_Side_features_.pickle")

    os.chdir("D:\\[山口]研究\\YJFX\\new_pbf_d\\buy_pressure")
    buy_features.to_pickle(date+"_Buy_Side_features_.pickle")


from sklearn.datasets import load_boston
from sklearn.ensemble import GradientBoostingRegressor
from sklearn.model_selection import cross_val_score
import numpy as np
import argparse

from hyperspace import hyperdrive

def objective(params):
    """
    Objective function to be minimized.
    """
    param0, param1, param2 = params
    model = Model(param0, param1, param3)

    train_loss = train(model)
    val_loss = validate(model)

    return val_loss

def main():
    hparams = [(2, 10),             # param0
               (10.0**-2, 10.0**0), # param1
               (1, 10)]             # param2

    hyperdrive(objective=objective,
               hyperparameters=hparams,
               results_path='/path/to/save/results',
               model="GP",
               n_iterations=15,
               verbose=True,
               random_state=0,
               sampler="lhs",
               n_samples=5,
               checkpoints=True)

if __name__ == '__main__':
    main()


import logging
from typing import *

import pandas as pd
import yaml

logging.basicConfig(level=logging.INFO)

def load_config(file_name: str) -> dict:
    """
    Load the configuration file and store it as a dictionary.
    :returns: The configuration settings as a dictionary.
    """
    with open(file_name, "r") as file:
        return yaml.safe_load(file)

def yaml_to_df(text: Union[str, bytes]) -> pd.DataFrame:
    """
    Convert the YAML found on the EtherscamDB page to a pandas DataFrame.
    :param text: The YAML to convert.
    :returns: A pandas DataFrame representing the data.
    """
    # Account for malformed document (uris.yml)
    text = text.replace(b"  - name:", b"- name:")

    # Convert YAML to DataFrame
    data = yaml.safe_load(text)
    df = pd.json_normalize(data)

    # Filter and split columns with multiple addresses
    df_address = df[df["addresses"].astype(str).str.contains("-")].copy()
    df = df[~df["addresses"].astype(str).str.contains("-")].copy()

    # Split address column into multiple rows
    df_address = (
        df_address.set_index(["id", "name", "description", "category"])
        .apply(lambda x: x.apply(pd.Series).stack())
        .reset_index()
    )

    df_address.rename(columns={0: "address"}, inplace=True)

    # Concatenate the two dataframes
    df = pd.concat([df, df_address], sort=False)
    return df

def write_to_csv(df: pd.DataFrame, file: str) -> None:
    """
    Write a pandas DataFrame to a CSV file.
    :param df: The pandas DataFrame to use.
    :param file: The file to write to.
    """
    # Add .csv extension if it doesn't already exist
    if not file.endswith(".csv"):
        file = f"{file}.csv"

    df.to_csv(file, index=False)
    logging.info(f"Data was successfully written to {file}")


import scipy.misc
import tensorflow as tf
import numpy as np
import math
import json
import random
from skimage.transform import resize

import RPN

import utils

def load_image_gt(dataset, config, image_id):
    image_id = int(image_id)
    image = dataset.load_image(image_id) #

    old_shape = 416

    print(image)

    image = resize(image,(config.IMAGE_MAX_DIM,config.IMAGE_MAX_DIM))

    shape = image.shape

    image = image * np.full((shape),255.0)

    window = (0,0,shape[0],shape[1])

    #print(window)
    #print(padding)

    bboxes = dataset.load_bboxes(image_id)
    class_ids = np.ones([bboxes.shape[0]], dtype=np.int32)

    for i,bbox in enumerate(bboxes):
        y1,x1,y2,x2 = bbox

        x1 = x1 * 1.0*config.IMAGE_MAX_DIM / old_shape
        x2 = x2 * 1.0*config.IMAGE_MAX_DIM / old_shape
        y1 = y1 * 1.0*config.IMAGE_MAX_DIM / old_shape
        y2 = y2 * 1.0*config.IMAGE_MAX_DIM / old_shape

        bboxes[i] = np.array([y1,x1,y2,x2])

    """
    if random.randint(0,1):
        import imgaug as ia
        import imgaug.augmenters as iaa

        bbs = []
        for bbox in bboxes:
            y1,x1,y2,x2 = bbox
            bbs.append(ia.BoundingBox(x1=x1,y1=y1,x2=x2,y2=y2))

            image_aug, bbs_aug = iaa.Fliplr(1.0)(image=image, bounding_boxes=bbs)

        image = image_aug

        gt_boxes_aug = np.zeros([len(bbs_aug),4], dtype=np.float32)

        for i,bbox in enumerate(bbs_aug):
            #print(bbox.y1,bbox.x1,bbox.y2,bbox.x2)
            y1,x1,y2,x2 = bbox.y1,bbox.x1,bbox.y2,bbox.x2

            gt_boxes_aug[i] = np.array([y1,x1,y2,x2])

        bboxes = gt_boxes_aug
    """

    #print(mask.shape)

    #for image meta

    active_class_ids = np.zeros([dataset.num_classes], dtype=np.int32)
    source_class_ids = dataset.source_class_ids[dataset.image_info[image_id]["source"]]
    active_class_ids[source_class_ids] = 1

    image_meta = utils.compose_image_meta(image_id, shape, window, active_class_ids)

    return image, image_meta, class_ids, bboxes

def view(dataset, config, shuffle=True, augment=True, batch_size=1):
    """
    shuffle: shuffle image every epoch
    return:
    - input_image
    - input_image_meta
    - input_rpn_match
    - input_rpn_bbox
    - input_gt_class_ids
    - input_gt_boxes
    """
    anchors = utils.generate_anchors(config.ANCHOR_SCALES,
                                     config.ANCHOR_RATIOS,
                                     config.ANCHOR_STRIDE,
                                     config.BACKBONE_SHAPES,
                                     config.BACKBONE_STRIDES)

    b = 0 #batch index
    image_ids = np.copy(dataset.image_ids)
    print(len(image_ids))
    error_count = 0

    index=1723

    while True:
        image_id = image_ids[index]

        input_image, input_image_meta, input_gt_class_ids, input_gt_boxes =\
            load_image_gt(dataset, config, image_id)

        print(input_image.shape)
        print(input_image_meta)
        print(input_gt_class_ids)
        print(input_gt_boxes)

        if not np.any(input_gt_class_ids > 0):
            continue

        #RPN targets
        rpn_match, rpn_bbox = RPN.build_targets(input_image.shape, anchors, input_gt_class_ids, input_gt_boxes, config)

        #print(input_gt_boxes)
        for gt_box in input_gt_boxes:
            y1,x1,y2,x2 = gt_box
            print(y1,x1,y2,x2)

            y1 = int(y1)
            x1 = int(x1)
            y2 = int(y2)
            x2 = int(x2)

            for y in range(y1,y2+1):
                input_image[y][x1][0] = 255.0
                input_image[y][x1][1] = 0.0
                input_image[y][x1][2] = 0.0

            for y in range(y1,y2+1):
                input_image[y][x2][0] = 255.0
                input_image[y][x2][1] = 0.0
                input_image[y][x2][2] = 0.0

            for x in range(x1,x2+1):
                input_image[y1][x][0] = 255.0
                input_image[y1][x][1] = 0.0
                input_image[y1][x][2] = 0.0
            for x in range(x1,x2+1):
                input_image[y2][x][0] = 255.0
                input_image[y2][x][1] = 0.0
                input_image[y2][x][2] = 0.0

        for i,anchor in enumerate(anchors):
            #anchor = utils.clip_boxes(anchor, np.array([0,0,832,832]))
            if rpn_match[i]==0:
                continue
            y1,x1,y2,x2 = anchor

            y1 = max(min(y1,512-1), 0)
            x1 = max(min(x1,512-1), 0)
            y2 = max(min(y2,512-1), 0)
            x2 = max(min(x2,512-1), 0)

            y1 = int(y1)
            x1 = int(x1)
            y2 = int(y2)
            x2 = int(x2)
            #print(y1,x1,y2,x2)
            if rpn_match[i]==1:
                for y in range(y1,y2+1):
                    input_image[y][x1][0] = 0.0
                    input_image[y][x1][1] = 255.0
                    input_image[y][x1][2] = 0.0
                    input_image[y][x2][0] = 0.0
                    input_image[y][x2][1] = 255.0
                    input_image[y][x2][2] = 0.0

                for x in range(x1,x2+1):
                    input_image[y1][x][0] = 0.0
                    input_image[y1][x][1] = 255.0
                    input_image[y1][x][2] = 0.0
                    input_image[y2][x][0] = 0.0
                    input_image[y2][x][1] = 255.0
                    input_image[y2][x][2] = 0.0
            else:
                for y in range(y1,y2+1):
                    input_image[y][x1][0] = 0.0
                    input_image[y][x1][1] = 0.0
                    input_image[y][x1][2] = 255.0
                    input_image[y][x2][0] = 0.0
                    input_image[y][x2][1] = 0.0
                    input_image[y][x2][2] = 255.0

                for x in range(x1,x2+1):
                    input_image[y1][x][0] = 0.0
                    input_image[y1][x][1] = 0.0
                    input_image[y1][x][2] = 255.0
                    input_image[y2][x][0] = 0.0
                    input_image[y2][x][1] = 0.0
                    input_image[y2][x][2] = 255.0
        """
        f = open("todo.txt", "w")
        for x in rpn_match:
            f.write(str(x))
        for x in rpn_bbox:
            f.write(str(x))
        f.close()
        """
        from skimage.io import imsave
        imsave('GT_RPN_input_val.png',input_image)

        break

def inspect(image,rois):

    image,window, scale, padding = utils.resize_image(
        image,
        min_dim = 896,
        max_dim = 896,
        padding = True
    )

    for roi in rois:
        y1,x1,y2,x2 = roi

        y1 = max(min(y1,896-1), 0)
        x1 = max(min(x1,896-1), 0)
        y2 = max(min(y2,896-1), 0)
        x2 = max(min(x2,896-1), 0)

        y1 = int(y1)
        x1 = int(x1)
        y2 = int(y2)
        x2 = int(x2)
        #print(y1,x1,y2,x2)
        for y in range(y1,y2+1):
            image[y][x1][0] = 1.0
            image[y][x1][1] = 0.0
            image[y][x1][2] = 0.0
            image[y][x2][0] = 1.0
            image[y][x2][1] = 0.0
            image[y][x2][2] = 0.0

        for x in range(x1,x2+1):
            image[y1][x][0] = 1.0
            image[y1][x][1] = 0.0
            image[y1][x][2] = 0.0
            image[y2][x][0] = 1.0
            image[y2][x][1] = 0.0
            image[y2][x][2] = 0.0

    from skimage.io import imsave
    imsave('foo.png',image)


inf = float("inf")

totalDist = int(input())
numClubs = int(input())
clubs = []
table = {}

for i in range (numClubs):
    clubs.append(int(input()))

clubs.sort()

#Fill in the table. Need to add going backwards
table[0] = 0

for i in range (1, totalDist+1):
    table[i] = inf

    for x in clubs:
        res = i - x

        if res >= 0:
            table[i] = min(table[res] + 1, table[i])
        else:
            break

if table[totalDist] != inf:
    print ("Roberta wins in", table[totalDist], "strokes.")
else:
    print ("Roberta acknowledges defeat.")


import pandas as pd
import dash
import dash_html_components as html
import dash_core_components as dcc
from dash.dependencies import Input, Output, State
import plotly.graph_objects as go
import plotly.express as px
from dash import no_update

app = dash.Dash(__name__)

# REVIEW1: Clear the layout and do not display exception till callback gets executed
app.config.suppress_callback_exceptions = True

# Read the automobiles data into pandas dataframe
auto_data =  pd.read_csv('automobileEDA.csv', encoding = "ISO-8859-1")
print(auto_data.head(2))

#Layout Section of Dash
app.layout = html.Div(
    children=[
        html.H1('Car Automobile Components', style={'textAlign':'center', 'color':'#503D36', 'font-size':24}),
        # Next Div Level
        html.Div([
            # Inner Division for adding dropdown helper text
            html.Div(
                html.H2('Drive Wheels Type : ', style={'margin-right':'2em'}) # don't see a need for a comma here
            ),
            # Inner Division
            dcc.Dropdown(
                id='demo-dropdown',
                options=[
                    {'label':'Rear Wheel Drive', 'value':'rwd'},
                    {'label':'Front Wheel Drive', 'value':'fwd'},
                    {'label':'Four Wheel Drive', 'value':'4wd'}
                ],
                value='rwd'
            ),
            html.Div([
                html.Div([], id='plot1'),
                html.Div([], id='plot2')
            ], style={'display':'flex'}) # another comma at the eol here in template and unsure if needed
        ])
    ]
)

# Place to add @app.callback Decorator
# The inputs and outputs of our application's interface are described declaratively as the arguments of @app.callback decorator.
# Dash - inputs/outputs of app are properties of a particular components
# In this example, our input is the value property of the component that has the ID demo-dropdown
# Our layout has 2 outputs so we need to create 2 output components.
# Here, the component property will be children as we have created empty division and passing in dcc.Graph (figure) after computation.
# TASK 3E
@app.callback(
    [
        Output(component_id='plot1', component_property='children'),
        Output(component_id='plot2', component_property='children')
    ],
    Input(component_id='demo-dropdown', component_property='value')
)
# Place to define the callback function .
# Whenever an input property changes, the function that the callback decorator wraps will get called automatically.
# TASK 3F
def display_selected_drive_charts(value):
    # Subset dataframe to selected drive wheels value from dropdown
    filtered_df = auto_data[auto_data['drive-wheels'] == value].groupby(['drive-wheels', 'body-style'], as_index=False)['price'].mean()
    filtered_df = filtered_df
    fig1 = px.pie(filtered_df, values='price', names='body-style', title='Pie Chart')
    fig2 = px.bar(filtered_df, x='body-style', y='price', title='Bar Chart')
    return [
        dcc.Graph(figure=fig1),
        dcc.Graph(figure=fig2)
    ]

if __name__ == '__main__':
    app.run_server()


#<---------Solucion a los problemas propuestos en el notebook--------------->
#<------------------01 escalares vectores matrices tensores.ipynb-------------->
import numpy as np
#<--------------Crear un escalar 42-------------->
a=42
print("Esto es un escalar con valor 42\n",a)
#<------------Crear el vector con los elementos 2,3,5,7---------------->
a=np.array([2,3,5,7])
print("Esto es un vector con elementos 2,3,5,7\n",a)
#<Crear una matriz de 2x2 con los elementos 2,3 en la primera fila y 5,7 en la segunda fila>
a=np.array([[2,3],[5,7]])
print("Esto una matriz de 2x2 con los elementos 2,3 en la primera fila y 5,7 en la segunda fila\n",a)
#<Crear un tensor que al graficarlo veamos Blanco, Negro, Gris, desde arriba hacia abajo.>
#<-----------Nota------------>
#<-----La funcion imshow de matplot realiza el "plot" de pixeles, este normalmente tiene valores en rgb--------->
#<-------Blaco en rgb (255,255,255)---------->
#<--------Gris en rgb (128,128,128)----------->
#<----------Negro en rgb (0,0,0)--------------->
#<----------- el tensor que formaremos tendra dimensiones de 3x3------------->
a=np.array([
    [[255,255,255],[255,255,255],[255,255,255]], #Blanco
    [[128,128,128],[128,128,128],[128,128,128]], # Gris
    [[0,0,0],[0,0,0],[0,0,0]] # Negro
]
)
#<--------------Libreria para plotear------------>
import matplotlib.pyplot as plt
#<-------------Deshabilito los ejes---------->
plt.yticks([]);plt.xticks([])
plt.imshow(a)
plt.show()


"""
@File : loss.py
@Author : CodeCat
@Time : 2021/7/28 上午9:57
"""
import torch
import torch.nn as nn
import torch.nn.functional as F

# 二分类
class FocalLoss(nn.Module):

    def __init__(self, gamma=2, alpha=0.5):
        super(FocalLoss, self).__init__()
        self.gamma = gamma
        self.alpha = alpha

    def forward(self, input, target):
        # input:size is M*2. M　is the batch　number
        # target:size is M.
        pt = torch.softmax(input, dim=1)
        p = pt[:, 1]
        loss = -self.alpha * (1 - p) ** self.gamma * (target * torch.log(p)) - (1 - self.alpha) * p ** self.gamma * ((1 - target) * torch.log(1 - p))
        return loss.mean()

class CEWeightLoss(nn.Module):
    def __init__(self, reduction: str = 'mean'):
        super(CEWeightLoss, self).__init__()
        self.reduction = reduction

    def forward(self, input, target):
        # input:size is M*2. M　is the batch　number
        # target:size is M.
        weight = torch.sum(target) / target.numel()
        weights = torch.Tensor([weight, 1-weight]).to(input.device)
        return F.cross_entropy(input, target, weight=weights, reduction=self.reduction)

class DiceLoss(nn.Module):
    def __init__(self, eps=1e-6):
        super(DiceLoss, self).__init__()
        self.eps = eps

    def forward(self, input, target):
        # input:size is M*2. M　is the batch　number
        # target:size is M.
        neg = 1 - target
        pos = target
        target = torch.stack((neg, pos), dim=1)
        intersection = torch.sum(input * target)
        union = torch.sum(input) + torch.sum(target) + self.eps
        loss = 1 - 2.0 * intersection / union
        return loss


"""Module logs for customized logger creation.

Author: Jan Jakub Kubik (xkubik32)
Date: 12.3.2023
"""

import logging
from typing import Callable, Union

import structlog

def _create(
    name: str, get_logger_func: Callable, logging_options=logging
) -> Union[logging.Logger, structlog.BoundLogger]:
    """Create a logger with the given name.

    Args:
        name (str): Name of the logger.
        get_logger_func (Callable): Function for creating logger object.
        logging_options (Optional): Logging options. Default is Python's logging module.

    Returns:
        Union[logging.Logger, structlog.BoundLogger]: Logger object based on get_logger_func.
    """
    logging.setLoggerClass(logging_options.Logger)
    logger = get_logger_func(name)

    return logger

def create_logger(name: str) -> structlog.BoundLogger:
    """Create a logger with the given name.

    Create a structlog logger object with the given name.

    Args:
        name (str): Name of the logger.

    Returns:
        structlog.BoundLogger: Structlog logger object with the given name.
    """
    # Same as default processors, just without timestamps
    structlog.configure(
        processors=[
            structlog.processors.StackInfoRenderer(),
            structlog.processors.format_exc_info,
            # structlog.processors.TimeStamper(fmt="%Y-%m-%d %H:%M:%S", utc=True),
            structlog.dev.set_exc_info,
            structlog.dev.ConsoleRenderer(colors=True),
        ],
        wrapper_class=structlog.BoundLogger,
    )
    return _create(name, structlog.getLogger)


from django.urls import reverse

from core.tests.base import UserBaseTestCase

class SimpleViewsTestCase(UserBaseTestCase):

    def test_renders_main_view_redirect_code(self):
        response = self.client.get(reverse('main'))
        self.assertEqual(302, response.status_code)

    def test_renders_main_view_redirected(self):
        with self.assertTemplateUsed('referrals/index_referrals.html'):
            response = self.client.get(reverse('main'),
                                       follow=True)
            last_url, last_status_code = \
                response.redirect_chain[-1]
            self.assertEquals(last_url, '/en/referrals/')
            self.assertEquals(last_status_code, 302)
            self.assertEqual(200, response.status_code)


from mpl_toolkits.axes_grid1 import make_axes_locatable
import numpy as np

from myterial import grey_dark
import matplotlib.patheffects as path_effects
from matplotlib.artist import Artist
from fcutils.plot.elements import plot_mean_and_error

from analysis.ephys.utils import get_frate_per_bin

def raster_histo(ax, X, unit, bins: np.ndarray, n_events: int):
    """
        Makes a histogram visualization to put on top of araster plot
        given a vector of events X
    """
    # get counts per bin
    counts, _ = np.histogram(X, bins=bins)

    # get average count across events
    avg_counts = counts / n_events

    # histogram plot
    divider = make_axes_locatable(ax)
    cax = divider.append_axes("top", size="30%", pad=0.05)

    # cax.hist(
    #     S, bins=np.arange(0, 260 + ds, step=ds), color=unit.color, alpha=1
    # )
    cax.bar(
        bins[0:-1] + bins[1] - bins[0],
        avg_counts,
        width=bins[1] - bins[0],
        color=unit.color,
        alpha=1,
    )
    return cax

def bouts_raster(ax, unit, bouts, tracking=None, ds=5):
    """
        Plot a unit's spikes aligned to bouts. Unlike time_aligned_raster, this function
        plots spikes as a function of track progression, not time!
    """

    S, Y = [], []
    n = len(bouts)
    h = 1 / n

    for i, bout in bouts.iterrows():
        # get spikes during bout (based on frames)
        trial_spikes = unit.spikes[
            (unit.spikes >= bout.start_frame) & (unit.spikes < bout.end_frame)
        ]

        spikes_s = tracking.global_coord[trial_spikes] * 260
        S.extend(spikes_s)
        Y.extend(np.zeros_like(trial_spikes) + (i * h))

        # mark the start/end of the bout
        ax.scatter(
            [
                tracking.global_coord[bout.start_frame] * 260,
                tracking.global_coord[bout.end_frame] * 260,
            ],
            [i * h, i * h],
            s=24,
            color="red",
            alpha=1,
            marker="|",
        )

    ax.scatter(S, Y, s=4, color=grey_dark, alpha=1, marker="|")

    # histogram plot
    bins = np.arange(0, 260 + ds, step=ds)

    # get avg number of spikes per bin
    counts, _ = np.histogram(S, bins=bins)
    avg_counts = counts  # / n

    # get the avg number of frames per bin
    gcoord_values = (
        np.hstack(
            [
                tracking.global_coord[b.start_frame : b.end_frame]
                for i, b in bouts.iterrows()
            ]
        )
        * 260
    )
    frames_count, _ = np.histogram(gcoord_values, bins=bins)
    frames_avg = frames_count  # / n

    # now get the avg number of spikes divided by number of frames
    frate = avg_counts / frames_avg

    # make plot
    divider = make_axes_locatable(ax)
    cax = divider.append_axes("top", size="30%", pad=0.05)
    cax.bar(
        bins[:-1] + (bins[1] - bins[0]) / 2,
        frate,
        width=bins[1] - bins[0],
        color=unit.color,
        alpha=1,
    )

    # style axes
    ax.set(
        yticks=np.arange(0, 1, 10 / n),
        yticklabels=(np.arange(0, 1, 10 / n) * n).astype(int),
        xlim=[0, 260],
        ylabel="trial",
        xlabel="track position (cm)",
    )
    cax.set(ylabel="Firing rate", xticks=[], xlim=[0, 260])

def time_aligned_raster(ax, unit, timestamps, t_before=1, t_after=1, dt=0.1):
    """
        Plot a unit spikes aligned to timestamps (in seconds).
        it also adds a firing rate visualization
    """
    ax.plot([0, 0], [0, 1], lw=3, color="k", alpha=0.3)
    n = len(timestamps)
    if n == 0:
        return
    h = 1 / n

    spikes = unit.spikes_ms / 1000
    perievent_spikes = []
    Y = []
    for i, t in enumerate(timestamps):
        trial_spikes = spikes[(spikes > t - t_before) & (spikes < t + t_after)]
        y = np.zeros_like(trial_spikes) + (i * h)

        Y.extend(y)
        perievent_spikes.extend(trial_spikes - t)
    ax.scatter(perievent_spikes, Y, s=6, color=grey_dark, alpha=1, marker="|")

    # add horizontal cax to axis
    cax = raster_histo(
        ax,
        perievent_spikes,
        unit,
        np.arange(-t_before, t_after + dt, step=dt),
        n,
    )

    # style axes
    ax.set(
        xlabel="time (s)",
        ylabel="trial",
        yticks=np.arange(0, 1, 10 / n),
        yticklabels=(np.arange(0, 1, 10 / n) * n).astype(int),
        xlim=[-t_before, t_after],
    )
    cax.set(ylabel="Spike counts", xticks=[], xlim=[-t_before, t_after])

def plot_frate_binned_by_var(
    ax, unit, in_bin: dict, bin_values, xlabel="", color=None
):
    """
        Plot a unit's firing rate binned by a variable (with bins defined over the variable's range)
    """
    color = color or unit.color
    # get firing rate per bin
    in_bin_frate = get_frate_per_bin(unit, in_bin)

    # plot firing rate
    ax.plot(bin_values, in_bin_frate.values(), "-o", color=color, lw=2)

    ax.set(xlabel=xlabel, xticks=bin_values[::2])

def plot_tuning_curves(ax, tuning_curves: dict, color: str, xlabel: str = ""):
    """
        Given a dictionary of tuning curves where we have
        as keys the values of the independent values and as
        values a list of "tuning curve values" generated by
        repeated random samples (see `get_tuning_curves`).
    """
    x = np.array(list(tuning_curves.keys()))
    y = np.array([np.nanmean(v) for v in tuning_curves.values()])
    e = np.array([np.nanstd(v) for v in tuning_curves.values()])

    x = x[y > 0]
    e = e[y > 0]
    y = y[y > 0]
    plot_mean_and_error(y, e, ax, color=color, x=x)

    # for k, v in tuning_curves.items():
    #     x = np.ones_like(v) * k
    #     ax.scatter(x, v, s=4, color=color, alpha=0.3)

    ax.set(ylabel="Firing rate (Hz)", xlabel=xlabel)

def outline(artist: Artist, lw: float = 1, color: str = "white"):
    artist.set_path_effects(
        [path_effects.withStroke(linewidth=lw, foreground=color,)]
    )


import os
import sys
sys.path.append(os.path.relpath("../../shared/python"))
import utils

# Puzzle description: https://adventofcode.com/2018/day/14

# Part2 is not the fastest solution but it was easy to add to the part1 solution. It
# takes about 20s on i7-6700K CPU.

def solve(recipe, input, extract_count, part1=True):
    elf1 = 0
    elf2 = 1
    first = int(input)
    max_recipes = first + extract_count
    target = input
    target_len = len(target)

    while True:
        r1 = int(recipe[elf1])
        r2 = int(recipe[elf2])
        recipe += str(r1 + r2)
        recipe_len = len(recipe)
        elf1 = (elf1 + (1 + r1)) % recipe_len
        elf2 = (elf2 + (1 + r2)) % recipe_len

        if part1:
            if recipe_len > max_recipes:
                return recipe[first: first + extract_count]
        elif recipe[recipe_len - target_len:recipe_len] == target:
            return recipe_len - target_len

def main():
    input = "430971"
    recipes = "37"

    # assert solve(recipes, "9", 10) == "5158916779"
    # assert solve(recipes, "5", 10) == "0124515891"
    # assert solve(recipes, "18", 10) == "9251071085"
    # assert solve(recipes, "2018", 10) == "5941429882"
    print(f'Part 1 {solve(recipes, input, 10)}')  # 5715102879

    # assert solve(recipes, "51589", 0, False) == 9
    # assert solve(recipes, "01245", 0, False) == 5
    # assert solve(recipes, "92510", 0, False) == 18
    # assert solve(recipes, "59414", 0, False) == 2018
    print(f'Part 2 {solve(recipes, input, 0, False)}')  # 20225706

if __name__ == '__main__':
    main()


# Import the functions we need from flask
from flask import Flask
from flask import render_template
from flask import jsonify
from flask import request

from datetime import datetime

import math

from sklearn.preprocessing import StandardScaler
from tensorflow.keras.models import load_model
import joblib
from joblib import dump, load
import pickle

# Instantiate the Flask application. (Chocolate cake recipe.)
# This statement is required for Flask to do its job.
app = Flask(__name__)
app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 0 # Effectively disables page caching

# Load the model
NN_model = load_model("Trained_Models/chris_best_model.h5")
MLR_model = pickle.load(open("Trained_Models/katrice_MLR_model.h5", 'rb'))

# Load the StandardScaler
X_Scaler = StandardScaler()
X_Scaler = load('Trained_Models/std_scaler.bin')

# Here's where we define the various application routes ...
@app.route("/")
def IndexRoute():
    ''' This function runs when the browser loads the index route.
        Note that the html file must be located in a folder called templates. '''

    webpage = render_template("index.html")
    return webpage

# This order is the current order of the features as listed on the home website
def build_input_row(latitude, longitude, yr_built,
                    sqft_living, floors, sqft_above, sqft_basement, sqft_lot,
                    bedrooms, bathrooms, condition, grade):

    mylist = []

    # Maintain this order of features. This is the order into the NN model
    mylist.append(bedrooms)
    mylist.append(bathrooms)
    mylist.append(sqft_living)
    mylist.append(sqft_lot)
    mylist.append(floors)
    mylist.append(condition)
    mylist.append(grade)
    mylist.append(sqft_above)
    mylist.append(sqft_basement)
    mylist.append(yr_built)
    mylist.append(latitude)
    mylist.append(longitude)

    conds = []
    conds.append(mylist)

    return conds

@app.route("/predict_price")
def predict_price():
    ''' Process the request arguments and feed into the prediction model. '''

    ### REQUIRED ###
    latitude = request.args.get('lat', None)
    longitude = request.args.get('long', None)
    yr_built = request.args.get('yr_built', None)
    sqft_living = request.args.get('sqft_living', None)
    floors = request.args.get('floors', None)
    sqft_above = request.args.get('sqft_above', None)
    sqft_basement = request.args.get('sqft_basement', None)
    sqft_lot = request.args.get('sqft_lot', None)
    bedrooms = request.args.get('bedrooms', None)
    bathrooms = request.args.get('bathrooms', None)
    condition = request.args.get('condition', None)
    grade = request.args.get('grade', None)

    features = []
    features = build_input_row(latitude, longitude, yr_built,
                    sqft_living, floors, sqft_above, sqft_basement, sqft_lot,
                    bedrooms, bathrooms, condition, grade)
    print(features)

    # This is the order expected by the model
    # bedrooms, bathrooms, sqft_living, sqft_lot, floors, condition
    # grade, sqft_above, sqft_basement, yr_built, latitude, longitude
    # features = [3, 2, 2000, 5000, 1, 3, 7, 1600, 400, 1985, 47.1, -122.1]
    # Use this for testing this route's url
    # Real House ie. X_trimmed.head(1)
    # ?lat=47.5112&long=-122.257&yr_built=1955&sqft_living=1180&floors=1&sqft_above=1180&sqft_basement=0&sqft_lot=5650&bedrooms=3&bathrooms=1&condition=3&grade=7
    # Hypothetical House
    # ?lat=47.5112&long=-122.257&yr_built=1985&sqft_living=2000&floors=1&sqft_above=1600&sqft_basement=400&sqft_lot=5000&bedrooms=3&bathrooms=2&condition=3&grade=7

    result = {}

    predicted_value = NN_model.predict(X_Scaler.transform(features))
    result["predicted_value_NN"] = str(predicted_value[0][0])

    predicted_value = MLR_model.predict(X_Scaler.transform(features))
    result["predicted_value_MLR"] = str(predicted_value[0][0])

    print(result)

    return result

@app.route("/predict_NN_price")
def predict_NN_price():
    ''' Process the request arguments and feed into the prediction model. '''

    ### REQUIRED ###
    latitude = request.args.get('lat', None)
    longitude = request.args.get('long', None)
    yr_built = request.args.get('yr_built', None)
    sqft_living = request.args.get('sqft_living', None)
    floors = request.args.get('floors', None)
    sqft_above = request.args.get('sqft_above', None)
    sqft_basement = request.args.get('sqft_basement', None)
    sqft_lot = request.args.get('sqft_lot', None)
    bedrooms = request.args.get('bedrooms', None)
    bathrooms = request.args.get('bathrooms', None)
    condition = request.args.get('condition', None)
    grade = request.args.get('grade', None)

    features = []
    features = build_input_row(latitude, longitude, yr_built,
                    sqft_living, floors, sqft_above, sqft_basement, sqft_lot,
                    bedrooms, bathrooms, condition, grade)
    print(features)

    predicted_value = NN_model.predict(X_Scaler.transform(features))

    result = {"predicted_value_NN": str(predicted_value[0][0])}

    print(result)

    return result

@app.route("/predict_MLR_price")
def predict_MLR_price():
    ''' Process the request arguments and feed into the prediction model. '''

    ### REQUIRED ###
    latitude = request.args.get('lat', None)
    longitude = request.args.get('long', None)
    yr_built = request.args.get('yr_built', None)
    sqft_living = request.args.get('sqft_living', None)
    floors = request.args.get('floors', None)
    sqft_above = request.args.get('sqft_above', None)
    sqft_basement = request.args.get('sqft_basement', None)
    sqft_lot = request.args.get('sqft_lot', None)
    bedrooms = request.args.get('bedrooms', None)
    bathrooms = request.args.get('bathrooms', None)
    condition = request.args.get('condition', None)
    grade = request.args.get('grade', None)

    features = []
    features = build_input_row(latitude, longitude, yr_built,
                    sqft_living, floors, sqft_above, sqft_basement, sqft_lot,
                    bedrooms, bathrooms, condition, grade)
    print(features)

    predicted_value = MLR_model.predict(X_Scaler.transform(features))

    result = {"predicted_value_MLR": str(predicted_value[0][0])}

    print(result)

    return result

# This statement is required for Flask to do its job.
# Think of it as chocolate cake recipe.
if __name__ == '__main__':
    app.run(debug=True)


import random
from random_word import RandomWords

class Hangman:
    def fill10(word1,word2):
        for i in range(len(word1)):
            rand = random.randint(1,2)
            if rand == 1:
                word2 = word2[:i] + word1[i] + word2[i+1:]
        return word2
    def __init__(self,word:str):
        flag = 5
        word = word.upper()
        empty = "_"*len(word)
        doneindices = []
        empty = Hangman.fill10(word,empty)
        print(empty)
        while '_' in empty and flag>0:
            letter = (input('Letter: ')).upper()
            if len(letter)>1:print("Enter a letter not a word.");continue
            if letter not in word or (word.count(letter)==empty.count(letter)) : flag-=1
            for index,value in enumerate(word):
                if str(index) not in doneindices:
                    if letter==value:
                        doneindices.append(index)
                        empty = empty[:index]+letter+empty[index+1:]
            print(empty+" Tries: "+str(flag))
            if flag==0:
                print("The word was "+word+" lmaoo couldnt even get that.")
            if empty==word:
                print("Congrats, the word was "+word+".")

generator = RandomWords()
Hangman(generator.get_random_word())


import numpy as np
from chainer import serializers

FLAG_GPU = False
if FLAG_GPU:
    xp = cuda.cupy
    cuda.get_device_from_id(0).use()
else:
    xp = np

class Decoder(object):
    def __init__(self, model, data_converter, decode_max_size, npz):
        self.model = model
        self.data_converter = data_converter
        self.decode_max_size = decode_max_size
        serializers.load_npz(npz, self.model)

    def __call__(self, query):
        # モデルの勾配などをリセット
        self.model.reset()
        # userからの入力文をIDに変換
        enc_query = self.data_converter.sentence2ids(query)
        enc_query = enc_query.T
        # エンコード時のバッチサイズ
        encode_batch_size = len(enc_query[0])
        # エンコードの計算
        self.model.encode(enc_query, encode_batch_size)
        # <eos>をデコーダーに読み込ませる
        t = xp.array([0] * encode_batch_size, dtype="int32")
        # デコーダーが生成する単語IDリスト
        ys = []
        for i in range(self.decode_max_size):
            y = self.model.decode(t)
            y = xp.argmax(y.data)  # 確率で出力されたままなので、確率が高い予測単語を取得する
            ys.append(y)
            t = xp.array([y], dtype="int32")
            if y == 0:  # <EOS>を出力したならばデコードを終了する
                break
        # IDから，文字列に変換する
        response = self.data_converter.ids2words(ys)

        if "<eos>" in response:  # 最後の<eos>を回避
            res = "".join(response[0:-1])
        else:  # 含んでない時もある．(出力wordサイズが，15を超えた時？？？)
            res = "".join(response)
        return res


#
import json

import openpyxl
import re

################################################################
# INPUT
YEAR = 2023
filename = "../CERT-Officer-Dienstplan_{}.xlsx".format(YEAR)
################################################################

sheetname_regex = '{}-0[1-9]|1[012]'.format(YEAR)

vacations = {}

if __name__ == '__main__':
    excel_workbook = openpyxl.load_workbook(filename=filename)

    for sheetname in excel_workbook.sheetnames:
        if not re.match(sheetname_regex, sheetname):
            continue

        sheet = excel_workbook[sheetname]

        if not sheet.cell(row=1, column=1).value == YEAR:
            print(sheet.cell(row=1, column=1).value)
            raise Exception

        officers = {}
        lastname = 'notNone'
        current_row = 3
        while lastname:
            lastname = sheet.cell(row=current_row, column=1).value
            if lastname:
                officers[lastname] = current_row
                if not vacations.get(lastname):
                    vacations[lastname] = []
            current_row += 1

        for officer, row in officers.items():
            for column in range(1, 31 + 1):
                if not sheet.cell(row=1, column=column + 2).value == column:
                    continue

                if sheet.cell(row=row, column=column + 2).fill.start_color.index in [8, 'FF92D050']:
                    vacations[officer].append('{}-{:02}'.format(sheetname, column))

    with open('../data/officer_vacation.json', 'w') as f:
        f.write(json.dumps(vacations, indent=4))


import cv2
import numpy as np

from utils.object_detection import ObjectDetection
from utils.video_recorder import VideoRecorder
from utils.frame_rate import FrameRate

fish_name = 'flowerhorn'
objectDetection = ObjectDetection(model='rfcn_resnet101_{}'.format(fish_name),
                                  labels='{}_label_map.pbtxt'.format(fish_name),
                                  num_classes=1)
videoRec = VideoRecorder(fileName='{}'.format(fish_name),
                         width=1280,
                         height=720)

if __name__ == '__main__':

    # input_cam = 2
    input_video = '{}.mp4'.format(fish_name)
    cap = cv2.VideoCapture(input_video)
    rec = videoRec.recording()

    frameRate = FrameRate()

    while True:
        _, frame = cap.read()

        objectDetection.run(image_np=frame, display=True)

        frameRate.putText(frame=frame, text=frameRate.fps())

        cv2.imshow('Detector [{}]'.format(fish_name), frame)

        videoRec.output(frame=frame, recording=rec)

        if cv2.waitKey(1) & 0xFF == ord('q'):
            break

    cap.release()
    cv2.destroyAllWindows()


import sys

#최소 스패닝 트리는,
#주어진 그래프의 모든 정점들을 연결하는 부분 그래프 중에서
#그 가중치의 합이 최소인 트리를 말한다.

vertex, edge = map(int ,sys.stdin.readline().strip().split())
tree = {}
for _ in range(edge):
    v1, v2, g = map(int, sys.stdin.readline().strip().split())
    if g in tree:
        tree[g].append((v1, v2))
    else:
        tree[g] = [(v1,v2)]

# union-find
# cycle이 존재하는지 확인 방법
# make-set
union_set = [i for i in range(vertex+1)]

def find(vt):
    global union_set
    if union_set[vt] != vt:
        union_set[vt] = find(union_set[vt])
    return union_set[vt]

def union(vt1, vt2):
    global union_set
    root1 = find(vt1)
    root2 = find(vt2)

    # 루트 노드가 같지 않은 경우 합쳐
    if root1 != root2:
        union_set[root1] = root2

def kruskalMST(tree):
    # 가중치 오름차순으로 Loop
    gAry = sorted(tree)
    result = 0
    for i in gAry:
        for edges in tree[i]:
            # 사이클이 없는 경우에만
            if find(edges[0]) != find(edges[1]):
                union(edges[0], edges[1])
                result += i
    print(result)

kruskalMST(tree)

[2019년 10월 시작]/[8주차]그리디 알고리즘/[강필규][8주차][백준_1197번_최소_스패닝_트리].py


import numpy as np
import torch
import torch.nn as nn
from torch.distributions import Normal, Categorical
import torch.nn.functional as F

torch.autograd.set_detect_anomaly(True)

class MLP(nn.Module):
    def __init__(self, sizes, activation_func=nn.Tanh):
        super(MLP, self).__init__()
        layers = []
        for i in range(len(sizes) - 1):
            act_func = activation_func if i < (len(sizes) - 2) else nn.Identity
            layers += [
                nn.Linear(sizes[i], sizes[i+1]), act_func()
            ]
        self.sequential = nn.Sequential(*layers)

    def forward(self, x):
        output = self.sequential(x)
        return output

class CategoricalMLP(nn.Module):
    def __init__(self, sizes, activation_func=nn.ReLU):
        super(CategoricalMLP, self).__init__()
        layers = []
        for i in range(len(sizes) - 1):
            act_func = activation_func if i < (len(sizes) - 2) else nn.Identity
            layers += [
                nn.Linear(sizes[i], sizes[i+1]), act_func()
            ]
        self.sequential = nn.Sequential(*layers)

    def forward(self, x):
        output = self.sequential(x)
        dist = Categorical(logits=output)

        sample = dist.sample()
        log_proba = dist.log_prob(sample)

        return sample, log_proba

class GaussianMLP(nn.Module):
    def __init__(self, sizes, action_limit, activation_func=nn.Tanh):
        super(GaussianMLP, self).__init__()
        self.action_limit = action_limit

        layers = []
        for i in range(len(sizes) - 2):
            layers += [nn.Linear(sizes[i], sizes[i+1]), nn.ReLU()]
        self.core_net = nn.Sequential(*layers)
        self.mean_net = nn.Linear(sizes[-2], sizes[-1])
        self.log_std_net = nn.Linear(sizes[-2], sizes[-1])

    def forward(self, x):
        core_out = self.core_net(x)
        mean = self.mean_net(core_out)
        log_std = self.log_std_net(core_out)
        log_std = torch.clamp(log_std, -20, 2)
        std = torch.exp(log_std)

        norm_dist = Normal(mean, std)
        # sample = norm_dist.sample()

        # log_proba = norm_dist.log_prob(sample).sum()
        # tanh_sample = (torch.tanh(sample)
        #                * torch.tensor(self.action_limit, dtype=torch.float32))

        return norm_dist


"""
File: 04.py
Author: Jin Lexuan
E-mail: jlx321@126.com
Time: 2020-02-04 16:14:56
Function:

"""

Fahrenheit = float(input("Input Fahrenheit: "))
Celsius = (Fahrenheit-32)/1.8
print("Celsius:%.2f" % Celsius)
input()


from datetime import datetime
from pathlib import Path
import requests as req
import locale
import logging

locale.setlocale(locale.LC_ALL, 'es_ES.utf8')
logger = logging.getLogger(__name__)

class csv_download:
    def __init__(self, url, file_name):
        """Inicializador de la clase
        Args:
            url: url del archivo csv en string
            file_name: nombre del archivo csv en string
        ambos guardados en atributos
        """

        self.url = url
        self.file_name = file_name.lower().replace(" ", "_")

    def download_explicit_date(self):
        """Descarga el archivo csv con la fecha actual en una
           direccion especifica
        Returns:
            direccion del archivo csv en string
        """

        date = datetime.now()
        path_raw = "/".join([self.file_name, date.strftime('%Y') +
                            "-" + date.strftime('%B').lower()])
        full_name = self.file_name + "-" + date.strftime('%d-%m-%Y') + ".csv"
        try:
            path = Path(path_raw).mkdir(parents=True, exist_ok=True)
            file = req.get(self.url)
            file.raise_for_status()
            full_name = path_raw + "/" + full_name
            logger.info(f"Se abrio/creo el archivo: \n {full_name}, como wb")
            with open(full_name, "wb") as f:
                f.write(file.content)
        except req.exceptions.ConnectionError as e:
            logger.exception(f"Error de conexion: {self.url}")
            raise SystemExit(f"Error de conexion: {self.url} \n" +
                             str(e))
        except req.exceptions.Timeout as e:
            logger.exception(f"Error de tiempo de espera: {self.url}")
            raise SystemExit(f"Error de tiempo de espera: {self.url} \n" +
                             str(e))
        except req.exceptions.HTTPError as e:
            logger.exception(f"Error de HTTP: {self.url},\n HTTP: {e.code}")
            raise SystemExit("Error HTTP \n" + str(e))
        except req.exceptions.RequestException as e:
            logger.exception(f"Error de request: {self.url},\n request: {e}")
            raise SystemExit(str(e))
        except OSError as e:
            logger.exception(f"Error al abrir/crear:\n {full_name},\n OS: {e}")
            raise SystemExit("Error al crear el directorio \n" + str(e))

        logger.debug(f"Archivo {full_name} descargado en {path_raw}")
        return full_name


import numpy as np
from sklearn.decomposition import PCA

def main():
    features = np.loadtxt('close_prices.csv', delimiter=',',
                          usecols=range(1, 31), skiprows=1)
    pca = PCA(n_components=10)
    pca_features = pca.fit_transform(features)

    sum = 0
    cnt = 0
    while sum < 0.9:
        sum += pca.explained_variance_ratio_[cnt]
        cnt += 1
    print(cnt)

    djia_idx = np.loadtxt('djia_index.csv', delimiter=',',
                          usecols=[1], skiprows=1)
    first_component_vals = pca_features[:, 0]
    corr_matrix = np.corrcoef(djia_idx, first_component_vals)
    print(corr_matrix[0, 1])

    i = np.identity(features.shape[1])
    coef = pca.transform(i)
    print(np.argmax(coef[:, 0]) + 1)

if __name__ == "__main__":
    main()


import sys
import YDR_aux as aux
import YDR_gene as drv
import YDR_land as lnd
from datetime import datetime
import MoNeT_MGDrivE as monet
from joblib import Parallel, delayed

if monet.isNotebook():
    (USR, SET, DRV, AOI) = ('dsk', 'homing', 'CRS', 'HLT')
    (OVW, JOB) = (True, aux.JOB_DSK)
else:
    (USR, SET, DRV, AOI) = (sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4])
    (OVW, JOB) = (True, aux.JOB_SRV)
###############################################################################
MF = (True, True)
if (AOI=='HLT') or (AOI=='TRS'):
    MF = (False, True)
###############################################################################
EXPS = aux.EXPS
for exp in EXPS:
    ###########################################################################
    # Setting up paths and style
    ###########################################################################
    (drive, land) = (
        drv.driveSelector(DRV, AOI, popSize=aux.POP_SIZE),
        lnd.landSelector('SPA')
    )
    (gene, fldr) = (drive.get('gDict'), drive.get('folder'))
    (PT_ROT, PT_IMG, PT_DTA, PT_PRE, PT_OUT, PT_MTR) = aux.selectPath(
        USR, SET, fldr, exp
    )
    # Time and head -----------------------------------------------------------
    tS = datetime.now()
    monet.printExperimentHead(
        PT_DTA, PT_PRE, tS,
        aux.XP_ID+' PreProcess [{}:{}:{}]'.format(DRV, exp, AOI)
    )
    ###########################################################################
    # Load folders
    ###########################################################################
    (expDirsMean, expDirsTrac) = monet.getExpPaths(
        PT_DTA, mean='ANALYZED/', reps='TRACE/'
    )
    (expNum, nodeDigits) = (len(expDirsMean), len(str(len(land)))+1)
    outNames = aux.splitExpNames(PT_PRE)
    outExpNames = set(outNames)
    ###########################################################################
    # Analyze data
    ###########################################################################
    Parallel(n_jobs=JOB)(
        delayed(monet.preProcess)(
                exIx, expNum, expDirsMean, expDirsTrac, gene,
                analysisOI=AOI, prePath=PT_PRE, nodesAggLst=land,
                outExpNames=outExpNames, fNameFmt='{}/{}-{}_', OVW=OVW,
                MF=MF, cmpr='bz2', nodeDigits=nodeDigits
        ) for exIx in range(0, expNum)
    )


from typing import List, Optional

from . import bootloader
from .base import Nitrokey3Base
from .device import Nitrokey3Device

VID_NITROKEY = 0x20A0
PID_NITROKEY3_DEVICE = 0x42B2
PID_NITROKEY3_LPC55_BOOTLOADER = 0x42DD
PID_NITROKEY3_NRF52_BOOTLOADER = 0x42E8

def list() -> List[Nitrokey3Base]:
    devices: List[Nitrokey3Base] = []
    devices.extend(bootloader.list())
    devices.extend(Nitrokey3Device.list())
    return devices

def open(path: str) -> Optional[Nitrokey3Base]:
    device = Nitrokey3Device.open(path)
    bootloader_device = bootloader.open(path)
    if device and bootloader_device:
        raise Exception(f"Found multiple devices at path {path}")
    if device:
        return device
    if bootloader_device:
        return bootloader_device
    return None


from decimal import Decimal
import datetime
from dateutil.relativedelta import relativedelta

from django.contrib.auth.models import User
from django.core import validators
from django.core.exceptions import ValidationError
from django.db import models
from django.db.models import F, Q, Sum, Max, Min
from django.utils import timezone
from django.utils.encoding import python_2_unicode_compatible

from timepiece import utils
from timepiece.manager.models import Project

class EntryQuerySet(models.query.QuerySet):
    """QuerySet extension to provide filtering by billable status"""

    def date_trunc(self, key='month', extra_values=None):
        select = {
            "day": {"date": """DATE_TRUNC('day', end_time)"""},
            "week": {"date": """DATE_TRUNC('week', end_time)"""},
            "month": {"date": """DATE_TRUNC('month', end_time)"""},
            "year": {"date": """DATE_TRUNC('year', end_time)"""},
        }
        basic_values = (
            'user', 'date', 'user__first_name', 'user__last_name')

        extra_values = extra_values or ()
        qs = self.extra(select=select[key])
        qs = qs.values(*basic_values + extra_values)
        qs = qs.annotate(hours=Sum('hours')).order_by(
            'user__last_name',
            'user__first_name',
            'user__pk',
            'date')
        return qs

    def timespan(self, from_date, to_date=None, span=None, current=False):
        """
        Takes a beginning date and filters entries. An optional to_date can be
        specified, or a span, which is one of ('month', 'week', 'day').
        N.B. - If given a to_date, it does not include that date, only before.
        """
        if span and not to_date:
            diff = None
            if span == 'month':
                diff = relativedelta(months=1)
            elif span == 'week':
                diff = relativedelta(days=7)
            elif span == 'day':
                diff = relativedelta(days=1)
            if diff is not None:
                to_date = from_date + diff
        datesQ = Q(end_time__gte=from_date)
        datesQ &= Q(end_time__lt=to_date) if to_date else Q()
        datesQ |= Q(end_time__isnull=True) if current else Q()
        return self.filter(datesQ)

class EntryManager(models.Manager):

    def get_queryset(self):
        qs = EntryQuerySet(self.model)

        # ensure our select_related are added.  Without this line later calls
        # to select_related will void ours (not sure why - probably a bug
        # in Django)
        # in other words: do not remove!
        str(qs.query)
        return qs

    def date_trunc(self, key='month', extra_values=()):
        return self.get_queryset().date_trunc(key, extra_values)

    def timespan(self, from_date, to_date=None, span='month'):
        return self.get_queryset().timespan(from_date, to_date, span)

@python_2_unicode_compatible
class Entry(models.Model):
    """
    This class is where all of the time logs are taken care of
    """
    user = models.ForeignKey(User, related_name='timepiece_entries', on_delete=models.CASCADE,)
    project = models.ForeignKey('manager.Project', related_name='entries', on_delete=models.CASCADE,)
    start_time = models.DateTimeField()
    end_time = models.DateTimeField(blank=True, null=True, db_index=True)
    end = models.TimeField(blank=True, null=True)
    activities = models.CharField(max_length=50, blank=False)
    date_updated = models.DateTimeField(auto_now=True)
    hours = models.DecimalField(max_digits=11, decimal_places=5, default=0)

    #uses EntryManager for querysets
    objects = EntryManager()
    no_join = models.Manager()

    class Meta:
        db_table = 'timepiece_entry'  # Using legacy table name
        ordering = ('-start_time',)
        verbose_name_plural = 'entries'
        permissions = (
            ('can_clock_in', 'Can use Pendulum to clock in'),
            ('can_clock_out', 'Can use Pendulum to clock out'),
        )

    def __str__(self):
        return '%s on %s' % (self.user, self.project)

    def check_overlap(self, entry_b, **kwargs):
        """Return True if the two entries overlap."""
        #used to be a pause feature that was taken out but now requires this
        consider_pause = False
        entry_a = self
        # if entries are open, consider them to be closed right now
        if not entry_a.end_time or not entry_b.end_time:
            return False
        # Check the two entries against each other
        start_inside = entry_a.start_time > entry_b.start_time \
            and entry_a.start_time < entry_b.end_time
        a_is_inside = entry_a.start_time > entry_b.start_time \
            and entry_a.end_time < entry_b.end_time
        b_is_inside = entry_a.start_time < entry_b.start_time \
            and entry_a.end_time > entry_b.end_time
        overlap = start_inside or a_is_inside or b_is_inside
        return overlap

    def is_overlapping(self):
        if self.start_time and self.end_time:
            entries = self.user.timepiece_entries.filter(
                Q(end_time__range=(self.start_time, self.end_time)) |
                Q(start_time__range=(self.start_time, self.end_time)) |
                Q(start_time__lte=self.start_time, end_time__gte=self.end_time)
            )

            totals = entries.aggregate(max=Max('end_time'), min=Min('start_time'))

            totals['total'] = 0
            for entry in entries:
                totals['total'] = totals['total'] + entry.get_total_seconds()

            totals['diff'] = totals['max'] - totals['min']
            totals['diff'] = totals['diff'].seconds + \
                totals['diff'].days * 86400

            if totals['total'] > totals['diff']:
                return False
            else:
                return False
        else:
            return None

    def clean(self):
        if not self.user_id:
            raise ValidationError('An unexpected error has occured')
        if not self.start_time:
            raise ValidationError('Please enter a valid start time')
        start = self.start_time

        #if regular end time (clock out and add entry)
        if self.end_time:
            end = self.end_time - relativedelta(seconds=1)
        #this end time is used on homescreen, must grab date from start
        elif self.end:
            end = datetime.datetime.combine(self.start_time.date(), self.end)
        #if no end time at all
        else:
            end = start + relativedelta(seconds=1)

        entries = self.user.timepiece_entries.filter(
            end_time__gt=start, start_time__lte=end)

        # An entry can not conflict with itself so remove it from the list
        if self.id:
            entries = entries.exclude(pk=self.id)
        for entry in entries:
            entry_data = {
                'project': entry.project,
                'start_time': entry.start_time,
                'end_time': entry.end_time,
                'endTime': entry.end,
            }
            # Conflicting saved entries
            if entry.end_time:
                if entry.start_time.date() == start.date() and entry.end_time.date() == end.date():
                    entry_data['start_time'] = entry.start_time.strftime(
                        '%H:%M:%S')
                    entry_data['end_time'] = entry.end_time.strftime(
                        '%H:%M:%S')
                    raise ValidationError('Start time overlaps with '
                                          '{project} from {start_time} to '
                                          '{end_time}.'.format(**entry_data))
                else:
                    entry_data['start_time'] = entry.start_time.strftime(
                        '%H:%M:%S on %m\%d\%Y')
                    entry_data['end_time'] = entry.end_time.strftime(
                        '%H:%M:%S on %m\%d\%Y')
                    raise ValidationError(
                        'Start time overlaps with {project} '
                        'from {start_time} to {end_time}.'.format(**entry_data))

        if end <= start:
            raise ValidationError('Ending time must exceed the starting time')
        return True

    def save(self, *args, **kwargs):
        self.hours = Decimal('%.5f' % round(self.total_hours, 5))
        super(Entry, self).save(*args, **kwargs)

    def get_total_seconds(self):
        """
        Determines the total number of seconds between the starting and
        ending times of this entry.
        """
        start = self.start_time
        end = self.end_time
        if not end:
            end = timezone.now()
        delta = end - start
        seconds = delta.seconds
        return seconds + (delta.days * 86400)

    @property
    def total_hours(self):
        """
        Determined the total number of hours worked in this entry
        """
        total = self.get_total_seconds() / 3600.0
        if total < 0:
            total = 0
        return total

##    @property
##    def is_paused(self):
##        """
##        Determine whether or not this entry is paused
##        """
##        return False

    @property
    def is_closed(self):
        """
        Determine whether this entry has been closed or not
        """
        return bool(self.end_time)

    @property
    def is_editable(self):
        return True

    @property
    def delete_key(self):
        """
        Make it a little more interesting for deleting logs
        """
        salt = '%i-apple-%s-sauce' \
            % (self.id, self.is_closed)
        try:
            import hashlib
        except ImportError:
            import sha
            key = sha.new(salt.encode('utf-8')).hexdigest()
        else:
            key = hashlib.sha1(salt.encode('utf-8')).hexdigest()
        return key

    @staticmethod
    def summary(user, date, end_date):
        """
        Returns a summary of hours worked in the given time frame, for this
        user.
        """
        entries = user.timepiece_entries.filter(
            end_time__gt=date, end_time__lt=end_date)
        data = {
           'total': Decimal('0'),
           }
        total = entries.aggregate(s=Sum('hours'))['s']
        if total:
            data['total'] = total
        return data

@python_2_unicode_compatible
class ProjectHours(models.Model):
    week_start = models.DateField(verbose_name='start of week')
    project = models.ForeignKey('manager.Project', on_delete=models.CASCADE,)
    user = models.ForeignKey(User, on_delete=models.CASCADE,)
    hours = models.DecimalField(
        max_digits=11, decimal_places=5, default=0,
        validators=[validators.MinValueValidator(Decimal("0.00001"))])
    published = models.BooleanField(default=False)

    def __str__(self):
        return "{0} on {1} for Week of {2}".format(
            self.user.get_name_or_username(),
            self.project, self.week_start.strftime('%B %d, %Y'))

    def save(self, *args, **kwargs):
        # Ensure that week_start is the Sunday of a given week.
        self.week_start = utils.get_week_start(self.week_start)
        return super(ProjectHours, self).save(*args, **kwargs)

    class Meta:
        db_table = 'timepiece_projecthours'  # Using legacy table name
        verbose_name = 'project hours entry'
        verbose_name_plural = 'project hours entries'
        unique_together = ('week_start', 'project', 'user')

class ToDo(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE,)
    priority = models.IntegerField()
    description = models.CharField(max_length=500, blank=False)
    completed = models.BooleanField(blank=False, default=False)

    class Meta:
        ordering = ["user", "priority"]

    def __str__(self):
        return self.description


import sys
import math
import matplotlib.pyplot as plt

def get_histogram(filename):
    histro=[0]*256
    file=open(filename,'rb')
    data=bytearray(file.read())
    for d in data:
        histro[d]+=1
    return histro

def entrophy_cal(histro):
    entropy=0
    prob=sum(histro)
    for h in histro:
        if h!=0:
            entropy-=(h/prob)*math.log2(h/prob)
    return entropy

def plot(histro, name='temp'):
    x=[]
    for i in range(256):
        x.append(i)
    plt.clf()
    plt.bar(x,histro)
    plt.xlabel("byte value")
    plt.ylabel("quant.")
    plt.savefig("img/"+(name.replace('.','')).replace(' ','')+".png")
    print("saved img/"+(name.replace('.','')).replace(' ','')+".png")
def main():
    file_offset=1
    MODE_COMPARE    = False
    MODE_HISTOGRAM  = False
    MODE_ENTROPHY   = False
    if "-h" in sys.argv:
        MODE_HISTOGRAM=True
        file_offset+=1
    if "-e" in sys.argv:
        MODE_ENTROPHY=True
        file_offset+=1
    if "-c" in sys.argv:
        MODE_COMPARE=True
        file_offset+=1

    if file_offset==1 or len(sys.argv)==1:
        print('''usage:\tFileHistogram.py {options} [file name list]
        \n\t\t-h\tcreate histogram plot of binary(created in ./img/.)
        \n\t\t-e\tprint entrophy of binary
        \n\t\t-c\tcompare mode(read files from ./original/. and ./packed/.)''')

    program=sys.argv[file_offset:]
    if MODE_COMPARE:
        if MODE_ENTROPHY:
            print("============================================================")
            print("             file               origin -> packed (increment)")
            print("------------------------------------------------------------")
            for p in program:
                histro_p=get_histogram('packed/'+p)
                histro_o=get_histogram('original/'+p)
                entrophy_o=entrophy_cal(histro_o)
                entrophy_p=entrophy_cal(histro_p)
                print("{:>30}: {:.4f} -> {:.4f} ({:.4f}%)".format(p,entrophy_o,entrophy_p,entrophy_p/entrophy_o*100-100))
        if MODE_HISTOGRAM:
            print("============================================================")
            print("creating histogram")
            print("------------------------------------------------------------")
            for p in program:
                histro_p=get_histogram('packed/'+p)
                histro_o=get_histogram('original/'+p)
                plot(histro_p,"p_"+p)
                plot(histro_o,"o_"+p)
    else:
        if MODE_ENTROPHY:
            print("========================================")
            print("             file               Entrophy")
            print("----------------------------------------")
            for p in program:
                histro=get_histogram(p)
                entrophy=entrophy_cal(histro)
                print("{:>30}: {:.4f}".format(p,entrophy))
        if MODE_HISTOGRAM:
            print("========================================")
            print("creating histogram")
            print("----------------------------------------")
            for p in program:
                histro_p=get_histogram(p)
                plot(histro_p,p)

if __name__=="__main__":
    main()


import streamlit as st
from streamlit_option_menu import option_menu
from streamlit_extras.app_logo import add_logo
from streamlit_extras.add_vertical_space import add_vertical_space
from streamlit_extras.colored_header import colored_header

st.set_page_config(
    page_title="AI Buddy Guard",
    layout= "wide",
    # page_icon="ðŸ¤–"
)

add_logo("ai_buddy_guard/web_app/logo.png", height=180)

colored_header(
    label=":green[AI Buddy GuardðŸ¦¾]",
    description=None,
    color_name="green-90",
)

st.markdown("##### Settings")

hide_streamlit_style = """
            <style>
            #MainMenu {visibility: visible;}
            footer {visibility: hidden;}
                            footer:before {
                    content:'Â© 2023 Gurpartap Sandhu';
                    visibility:visible;
                    display: block;
                    }
            </style>
            """
st.markdown(hide_streamlit_style, unsafe_allow_html=True)

add_vertical_space(2)
# Template ends here

col1, col2, col3 = st.columns(3)

with col1:
   st.header("AI Mode")
   ai_mode = st.selectbox(
    'What tone do you want to the model to use?',
    ('Professional Helpful Assistant', 'Silicon Valley Developer', 'Marvel Superfan', 'Soccer Fanatic', 'Pretentious Pirate'))

with col2:
   st.header("Model")
   model_used = st.selectbox(
    'Which AI Model would you like to use?',
    ('gpt-4', 'gpt-3.5-turbo-16k', 'gpt-3.5-turbo'))

with col3:
   st.header("Self hosted model")
   self_hosted_model_url = st.text_input('What is the url for your self hosted model', placeholder="Acme Corp Special LLM", disabled=True)

st.session_state['ai_mode'] = ai_mode
st.session_state['model'] = model_used
st.session_state['self_hosted_model_url'] = self_hosted_model_url
# st.session_state

add_vertical_space(2)

col4, col5, col6 = st.columns(3)

with col4:
   st.header("Authentication System")
   auth_system_name = st.text_input('What is the name of your authentication system', placeholder="Acme Corp Identity System")

with col5:
   st.header("Secret Storage Solution")
   secret_storage_solution = st.text_input('What is the name of your recommended secret storage solution', placeholder="Acme Corp Special Secret Store")

with col6:
   st.header("Patch Management")
   patch_management_solution = st.text_input('What is the name of your recommended patch management solution', placeholder="Acme Corp Special Patch Management Solution")

st.session_state['auth_system'] = auth_system_name
st.session_state['secrets_solution'] = secret_storage_solution
st.session_state['patching_solution'] = patch_management_solution
# st.session_state


#! usr/bin/env python

'''
hw3.py
Makes a list of household items and their prices on a separate file.
By David Baylor on 7/16/19
using python 3

How do I get rid of the extra line that prints inbetween the items?
'''

with open(r".\HomeInventory.txt", "a+") as fh:  #opens HomeInventory.txt
    item = input("Name a household item. ")  #asks for the items name and price
    price = input("how much does that cost. $")

    outlines = [item, " $", price, "\n"]

    fh.writelines(outlines)  #adds the new item to the list
    fh.seek(0)  #goes to the top of HomeInventory.txt

    line = fh.readline()
    while line:  #prints each line and stops after all the lines have been printed.
        print(line)
        line = fh.readline()


def _minmax(mat,col,get,ismax,obj,dFrame):
    from ..customs.objects import Label

    feats = mat.features.labels
    if mat.features.level == 1:
        feats = [row[0] for row in feats]

    col = feats.index(col)+1 if isinstance(col,(tuple,str)) else col

    if col==None:
        ranges = mat.ranged(get=0)
        if not isinstance(ranges[0],list):
            ranges = [ranges]
        m = {feats[i]:ranges[i][ismax] for i in range(len(ranges))}
    else:
        if col != None:
            if col<=0 or col>mat.d1:
                raise IndexError(f"Column index is out of range, expected range: [1,{mat.d1}]")
        name = feats[col-1]
        m = {name:mat.ranged(name,get=0)[ismax]}

    #Return a matrix
    if get==2:
        cols = list(m.keys())
        return obj((len(cols),1),[i for i in m.values()],features=[["Minimum","Maximum"][ismax]],dtype=dFrame,coldtypes=[float],index=Label(cols,mat.features.names[:]))
    #Return a dictionary
    elif get==1:
        return m
    #Return a list
    else:
        if col != None:
            return list(m.values())[0]
        return list(m.values())


import random

def prime_checker(number):
    is_prime = True
    for i in range(2,number):
        if number % i == 0:
            is_prime = False
    if is_prime:
        print("Prime Number")
    else:
        print("Not prime number")

num = int(input("Type a number "))
prime_checker(num)


import time
starttime=time.time()
from threading import Thread
import os
import json
import sys
from traceback import print_exc
dirname, filename = os.path.split(os.path.abspath(__file__))
sys.path.append(dirname)
import threading,win32gui
from tts.windowstts import tts
from PyQt5.QtCore import QCoreApplication ,Qt
from PyQt5.QtWidgets import  QApplication ,QGraphicsScene,QGraphicsView,QDesktopWidget
import utils.screen_rate
from utils.wrapper import timer,threader
import gui.rangeselect
import gui.settin
import gui.selecthook
from utils.getpidlist import getwindowlist
import gui.translatorUI
from utils.config import globalconfig
import importlib
from functools import partial
#print(time.time()-starttime)
import win32api,win32con,win32process
class MAINUI() :

    def __init__(self) -> None:
        self.screen_scale_rate = utils.screen_rate.getScreenRate()
        self.translators={}
        self.reader=None
        self.rect=None
        self.textsource=None
        self.savetextractor=None
    def textgetmethod(self,paste_str,shortlongskip=True):
        if paste_str=='':
            return
        if len(paste_str)>500 or   len(paste_str.split('\n'))>20:
            return

        postsolve=importlib.import_module('postprocess.post').POSTSOLVE
        try:
            paste_str=postsolve(paste_str)
        except:
            print_exc()

        self.translation_ui.original=paste_str
        if globalconfig['isshowhira'] and globalconfig['isshowrawtext']:
            if 'hira_' in dir(self):
                hiratext2,hiratext1,rawtext,guiuse=self.hira_.fy(paste_str)
                self.translation_ui.displayraw1.emit(guiuse,globalconfig['rawtextcolor'],1)
        elif globalconfig['isshowrawtext']:
            self.translation_ui.displayraw1.emit(paste_str,globalconfig['rawtextcolor'],1)
        else:
            self.translation_ui.displayraw1.emit(paste_str,globalconfig['rawtextcolor'],0)
        try:
            if globalconfig['autoread']:
                self.reader.read(paste_str)
        except:
            pass
        if shortlongskip and  (len(paste_str)<globalconfig['minlength'] or len(paste_str)>globalconfig['maxlength'] ):
            skip=True
        else:
            skip=False
        for engine in self.translators:
            #print(engine)
            self.translators[engine].gettask((paste_str,skip))
    @threader
    def startreader(self):
        if globalconfig['reader']:

            use=None
            if globalconfig['reader']['windows']:
                    self.reader=tts( self.settin_ui.voicelistsignal)
    @threader
    def starttextsource(self):

        if hasattr(self,'textsource') and self.textsource and self.textsource.ending==False :
            self.textsource.end()
        if True:#try:
            #classes={'ocr':ocrtext,'copy':copyboard,'textractor':textractor}#,'textractor_pipe':namepipe}
            classes=['ocr','copy','textractor']
            use=None
            for k in classes:
                if globalconfig['sourcestatus'][k]:
                    use=k
            if use is None:
                self.textsource=None
            elif use=='textractor':
                #from textsource.textractor import textractor

                pass
            elif use=='ocr':
                from textsource.ocrtext import ocrtext
                self.textsource=ocrtext(self.textgetmethod,self)
            # elif use=='textractor_pipe':
                    #from textsource.namepipe import namepipe
            #     self.textsource=classes[use](self.textgetmethod)
            #     return True

            elif use=='copy':
                from textsource.copyboard import copyboard
                self.textsource=copyboard(self.textgetmethod)

            return True
    @threader
    def starthira(self):

        from utils.hira import hira
        self.hira_=hira()

    @threader
    def prepare(self,now=None):

        import requests
        if now:
            Thread(target=self.fanyiloader,args=(now,)).start()
        else:
            for source in globalconfig['fanyi']:
                if globalconfig['fanyi'][source]['use']:
                    Thread(target=self.fanyiloader,args=(source,)).start()

    def fanyiloader(self,classname):

                    aclass=importlib.import_module('translator.'+classname).TS
                    aclass.settypename(classname)
                    _=aclass()
                    _.show=partial(self.translation_ui.displayres.emit,classname)
                    self.translators[classname]=_
    # 主函数
    def setontopthread(self):
        while True:
            #self.translation_ui.keeptopsignal.emit()

            win32gui.BringWindowToTop(int(self.translation_ui.winId()))

            time.sleep(0.5)

    def onwindowloadautohook(self):
        if not(globalconfig['autostarthook'] and globalconfig['sourcestatus']['textractor']):
            return False
        else:
            if 'textsource' not in dir(self) or self.textsource is None:
                if os.path.exists('./files/savehook_new.json'):
                                with open('./files/savehook_new.json', 'r', encoding='utf8') as ff:
                                        js = json.load(ff)
                else:
                    return False
                plist = getwindowlist()
                for pid in plist:
                    #print(pid)
                    try:
                            hwnd = win32api.OpenProcess(
                                win32con.PROCESS_ALL_ACCESS, False, (pid))
                            name_ = win32process.GetModuleFileNameEx(
                                hwnd, None)
                    except:
                        continue

                    if name_ in js:
                        self.settin_ui.autostarthooksignal.emit(pid, name_,(js[name_]))
                        return True
        return False
    def autohookmonitorthread(self):
        while True:
            if(self.onwindowloadautohook()):
                #break
                pass
            time.sleep(0.5)
    def aa(self):
        t1=time.time()

        self.translation_ui =gui.translatorUI.QUnFrameWindow(self)
        if globalconfig['rotation']==0:
            self.translation_ui.show()
        else:
            self.scene = QGraphicsScene()

            self.oneTestWidget = self.scene.addWidget(self.translation_ui)
            self.oneTestWidget.setRotation(globalconfig['rotation']*90)
            self.view = QGraphicsView(self.scene)
            self.view.setWindowFlags(Qt.FramelessWindowHint|Qt.WindowStaysOnTopHint|Qt.Tool)
            self.view.setAttribute(Qt.WA_TranslucentBackground)
            self.view.setStyleSheet('background-color: rgba(255, 255, 255, 0);')
            self.view.setGeometry(QDesktopWidget().screenGeometry())
            self.view.show()

        threading.Thread(target=self.setontopthread).start()

        self.prepare()
        self.starthira()
        self.starttextsource()

        self.settin_ui =gui.settin.Settin(self)

        self.startreader()
        self.range_ui =gui.rangeselect.rangeadjust(self)
        self.hookselectdialog=gui.selecthook.hookselect(self )
        threading.Thread(target=self.autohookmonitorthread).start()
        #self.translation_ui.displayraw.emit('欢迎','#0000ff')
        #print(time.time()-t1)
    def main(self) :
        # 自适应高分辨率
        t1=time.time()
        QCoreApplication.setAttribute(Qt.AA_UseHighDpiPixmaps, True)
        app = QApplication(sys.argv)
        app.setQuitOnLastWindowClosed(False)

        self.aa()
        #print(time.time()-t1)
        #print(time.time()-starttime)
        app.exit(app.exec_())

if __name__ == "__main__" :

    app = MAINUI()

    app.main()


from django.urls import path

from . import views

urlpatterns = [
    path('', views.index, name='index'),
    path('tasks/', views.get_tasks, name='get_tasks'),
    path('tasks/add/', views.add_task, name='add_task'),
    path('about/', views.about, name='about'),
    path('tasks/<int:id>/edit', views.edit_task, name='edit_task'),
    path('tasks/<int:id>/delete', views.delete_task, name='delete_task')
]


#! /usr/bin/env python

import openturns as ot

ot.TESTPREAMBLE()

distribution = ot.ClaytonCopula(1.5)
size = 1000
sample = distribution.getSample(size)
factory = ot.ClaytonCopulaFactory()
estimatedDistribution = factory.build(sample)
print("distribution=", repr(distribution))
print("Estimated distribution=", repr(estimatedDistribution))
estimatedDistribution = factory.build()
print("Default distribution=", estimatedDistribution)
estimatedDistribution = factory.build(distribution.getParameter())
print("Distribution from parameters=", estimatedDistribution)
estimatedClaytonCopula = factory.buildAsClaytonCopula(sample)
print("ClaytonCopula          =", distribution)
print("Estimated claytonCopula=", estimatedClaytonCopula)
estimatedClaytonCopula = factory.buildAsClaytonCopula()
print("Default claytonCopula=", estimatedClaytonCopula)
estimatedClaytonCopula = factory.buildAsClaytonCopula(distribution.getParameter())
print("ClaytonCopula from parameters=", estimatedClaytonCopula)


import numpy as np
import time

def read_matrix(path):
    with open(path) as f:
        lines = f.readlines()

    n = int(lines[0])
    lines = lines[2:]

    mp = [{} for _ in range(n)]

    for line in lines:
        val, i, j = line.split(',')
        val = float(val.strip())
        i = int(i.strip())
        j = int(j.strip())

        if mp[i].get(j) is not None:
            mp[i][j] += val
            continue

        mp[i][j] = val

    return n, mp

def to_matrix(a: list[dict], sym=False):
    n = len(a)

    matrix = np.zeros((n, n), dtype='float32')

    for i in range(n):
        for k, value in a[i].items():
            if sym:
                matrix[i, k] = matrix[k, i] = value
                continue

            matrix[i, k] = value

    return matrix

def sum_matrix(a, b):
    start_time = time.time()

    n = len(a)
    r = [{} for _ in range(n)]

    for i in range(n):
        for j, value in a[i].items():
            r[i][j] = value

    for i in range(n):
        for j, value in b[i].items():
            if r[i].get(j) is not None:
                r[i][j] += value
                continue

            r[i][j] = value
    print("---Timp adunare %s seconds ---" % (time.time() - start_time))
    return r

def square_matrix(a: list[dict]):
    start_time = time.time()

    n = len(a)

    prod = [{} for _ in range(n)]

    for i in range(n):
        for j, value in a[i].items():
            a[j][i] = value

    for i in range(n):
        line_a = a[i]
        for j in range(n):
            # numai valorile nenule de pe linia i a se vor inmulti
            # cu valorile nenule de pe linia j
            s = 0
            for k, lin in line_a.items():
                col = a[k].get(j)

                if col is None:
                    col = a[j].get(k)

                if col is not None:
                    s += lin * col

            if s != 0:
                prod[i][j] = s
    print("---Timp inmultire %s seconds ---" % (time.time() - start_time))
    return prod

# sym means the values are only below diagonal, but it's symmetric
def check(a: list[dict], b: list[dict], a_sym=True, b_sym=True):
    n = len(a)

    a_m = to_matrix(a, a_sym)
    b_m = to_matrix(b, b_sym)

    for i in range(n):
        for j in range(n):
            if a_m[i, j] != b_m[i, j]:
                print(f'{a_m[i, j]} vs {b_m[i, j]}')
                return False

    return True

def main():
    n, a = read_matrix('a.txt')
    _, b = read_matrix('b.txt')

    _, a_p_b = read_matrix('a_plus_b.txt')
    _, a_m_a = read_matrix('a_ori_a.txt')

    _sum = sum_matrix(a, b)
    print("Sum is correct?", check(_sum, a_p_b))

    _square = square_matrix(a)
    print("Squared is correct?", check(_square, a_m_a, False, True))

if __name__ == "__main__":
    main()


import sys
from io import StringIO
from typing import Optional, List

class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

class Solution:
    def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:
        stack = []
        while(root) or (len(stack)):
            while(root):
                stack.append((root, targetSum - root.val))
                targetSum -= root.val
                root = root.left

            curr = stack.pop()
            root = curr[0]
            if (curr[1] == 0) and (root.left == root.right == None):
                return True
            root = curr[0].right
            targetSum = curr[1]
        return False

    def hasPathSum_slow(self, root: Optional[TreeNode], targetSum: int) -> bool:
        if root == None:
            return False
        def dfs(root, rest):
            rest = rest - root.val

            # Only True if rest == 0 at a leaf
            if (root.left == root.right == None):
                return (rest == 0)

            # If we are not at a leaf, just continue
            if (root.left) and (dfs(root.left, rest)):
                return True
            if (root.right) and (dfs(root.right, rest)):
                return True
            return False

        return dfs(root, targetSum)