import os

os.environ["CUDA_VISIBLE_DEVICES"]="0"

import numpy as np
import cv2
import io
import requests
from PIL import Image
import pdb
from skimage.transform import resize
import matplotlib.pyplot as plt
import math
import random
import collections
import xml.etree.ElementTree as ET
from sklearn.metrics import precision_score,recall_score, accuracy_score
from utils.helper import calc_accuracy, get_prediction, make_one_hot

import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.init as init
from torch.autograd import Variable
from torch.nn import functional as F
from torch.utils import data
from torch.utils.tensorboard import SummaryWriter
from torch.utils.model_zoo import load_url

import torchvision
import torchvision.datasets as dset
from torchvision import models, transforms
from torch.utils.data import DataLoader, Subset
from torchvision.datasets import ImageFolder
from torchsummary import summary
from torchviz import make_dot
from utils.dataloader import VOC_Dataloader
from utils import helper
from models.vgg import vgg16
from models.resnet import resnet18
from models.squeezenet import squeezenet1_1
from utils.util import normalize_tensor
from utils.util import remove_layer
from utils.util import replace_layer
from utils.util import initialize_weights
from utils.gradcam import *
import random
import argparse
import time
from utils.util import t2n
class FeatureExtractor():
    """ Class for extracting activations and
    registering gradients from targetted intermediate layers """

    def __init__(self, model, pre_features, features, target_layers):
        self.model = model
        self.pre_features = pre_features
        self.features = features
        self.target_layers = target_layers
        self.gradients = []

    def save_gradient(self, grad):
        self.gradients.append(grad)

    def __call__(self, x):
        outputs = []
        self.gradients = []

        for pref in self.pre_features:
            x = getattr(self.model, pref)(x)

        submodel = getattr(self.model, self.features)
        # go through the feature extractor's forward pass
        for name, module in submodel._modules.items():
            # print(name, module)
            x = module(x)
            if name in self.target_layers:
                x.register_hook(self.save_gradient)
                outputs += [x]
        return outputs, x
class ModelOutputs():
    """ Class for making a forward pass, and getting:
    1. The network output.
    2. Activations from intermeddiate targetted layers.
    3. Gradients from intermeddiate targetted layers. """

    def __init__(self, model,
                 pre_feature_block=[],
                 feature_block='features',
                 target_layers='35',
                 classifier_block=['classifier']):
        self.model = model
        self.classifier_block = classifier_block
        # assume the model has a module named `feature`      ⬇⬇⬇⬇⬇⬇⬇⬇
        self.feature_extractor = FeatureExtractor(self.model,
                                                  pre_feature_block,
                                                  feature_block,
                                                  target_layers)

    def get_gradients(self):
        return self.feature_extractor.gradients

    def __call__(self, x):
        # ⬇ target layer    ⬇ final layer's output
        target_activations, output = self.feature_extractor(x)
        print('target_activations[0].size: {}'.format(target_activations[0].size()))# for vgg'35 ([1, 512, 14, 14])
        print('output.size: {}'.format(output.size()))                              # for vgg'36 ([1, 512, 7, 7])

        for i, classifier in enumerate(self.classifier_block):
            if i == len(self.classifier_block) - 2:
                output = output.view(output.size(0), -1)
                print('output.view.size: {}'.format(output.size()))                 # for vgg'36 ([1, 25088])

            output = getattr(self.model, classifier)(output)
            print('output.size: {}'.format(output.size()))                          # for vgg'36 ([1, 1000])

        return target_activations, output

def preprocess_image(img):
    means = [0.485, 0.456, 0.406]
    stds = [0.229, 0.224, 0.225]

    preprocessed_img = img.copy()[:, :, ::-1]
    for i in range(3):
        preprocessed_img[:, :, i] = preprocessed_img[:, :, i] - means[i]
        preprocessed_img[:, :, i] = preprocessed_img[:, :, i] / stds[i]
    preprocessed_img =         np.ascontiguousarray(np.transpose(preprocessed_img, (2, 0, 1)))
    preprocessed_img = torch.from_numpy(preprocessed_img)
    preprocessed_img.unsqueeze_(0)
    input = preprocessed_img.requires_grad_(True)
    return input

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

class GradCam:
    def __init__(self, model, pre_feature_block, feature_block, target_layer_names, classifier_block, use_cuda):
        self.model = model
        self.model.eval()
        self.pre_feature_block = pre_feature_block
        self.feature_block = feature_block
        self.classifier_block = classifier_block
        self.cuda = use_cuda
        if self.cuda:
            self.model = model.cuda()

        self.extractor = ModelOutputs(self.model,
                                      pre_feature_block,
                                      feature_block,
                                      target_layer_names,
                                      classifier_block)

    def forward(self, input):
        return self.model(input)

    def __call__(self, input, index=None):
        if self.cuda:
            features, output = self.extractor(input.cuda())
        else:
            features, output = self.extractor(input)

        if index == None:
            index = np.argmax(output.cpu().data.numpy())

#         with open('imagenet_class_index.json') as f:
#             labels = json.load(f)
#         labels
#         print('prediction[{}]: {}'.format(index, labels[str(index)][1]))
        print('output.size: {}'.format(output.size()))                            # for vgg'36 ([1, 1000])
        one_hot = np.zeros((1, output.size()[-1]), dtype=np.float32)
        one_hot[0][index] = 1
        one_hot = torch.from_numpy(one_hot).requires_grad_(True)
        if self.cuda:
            one_hot = torch.sum(one_hot.cuda() * output)
        else:
            one_hot = torch.sum(one_hot * output)

        #print('output: {}'.format(output))
        #print('one_hot: {}'.format(one_hot))                                      #
        getattr(self.model, self.feature_block).zero_grad()
        for classifier in self.classifier_block:
            getattr(self.model, classifier).zero_grad()
        one_hot.backward(retain_graph=True)

        gradients = self.extractor.get_gradients()
        #print('len(gradients): {}'.format(len(gradients)))
        print('gradients[0].size(): {}'.format(gradients[0].size()))
        grads_val = self.extractor.get_gradients()[-1].cpu().data.numpy()

        target = features[-1]
        print('target.size(): {}'.format(target.size()))
        target = target.cpu().data.numpy()[0, :]
        print('target.shape: {}'.format(target.shape))

        weights = np.mean(grads_val, axis=(2, 3))[0, :]
        print('weights.shape: {}'.format(weights.shape))
        cam = np.zeros(target.shape[1:], dtype=np.float32)
        print('cam.shape: {}'.format(cam.shape))            # (14, 14)

        for i, w in enumerate(weights):
            cam += w * target[i, :, :]

        #print('cam: {}'.format(cam))
        print('cam.shape: {}'.format(cam.shape))
        cam = np.maximum(cam, 0)                            # remove negative numbers
        cam = cv2.resize(cam, (256, 256))
        print('cam.shape: {}'.format(cam.shape))
        #print('cam: {}'.format(cam))
        cam = cam - np.min(cam)
        cam = cam / np.max(cam)
        return cam
def preprocess_image_gradCAM(img):
    means = [0.485, 0.456, 0.406]
    stds = [0.229, 0.224, 0.225]

    preprocessed_img = img.copy()[:, :, ::-1]
    for i in range(3):
        preprocessed_img[:, :, i] = preprocessed_img[:, :, i] - means[i]
        preprocessed_img[:, :, i] = preprocessed_img[:, :, i] / stds[i]
    preprocessed_img =         np.ascontiguousarray(np.transpose(preprocessed_img, (2, 0, 1)))
    preprocessed_img = torch.from_numpy(preprocessed_img)
    preprocessed_img.unsqueeze_(0)
    input_img = preprocessed_img.requires_grad_(True)
    return input_img


import os
import sys
from functools import *
import heapq

os.chdir(os.path.dirname(sys.argv[0]))

print(
"""~~~
""")

with open("input.txt", "r") as file:
    lines = file.read().splitlines()
    width = len(lines[0])
    inputmap = "".join(lines)

    end = inputmap.index("E")
    heightmap = [ord(c) - ord("a") for c in inputmap.replace("S", "a").replace("E", "z")]
    graph = []
    for i in range(len(heightmap)):
        x = i % width
        max_height = heightmap[i] + 1
        edges = set()
        graph.append(edges)
        if x - 1 >= 0 and heightmap[i - 1] <= max_height:
            edges.add(i - 1)
        if x + 1 < width and heightmap[i + 1] <= max_height:
            edges.add(i + 1)
        if i - width >= 0 and heightmap[i - width] <= max_height:
            edges.add(i - width)
        if i + width < len(heightmap) and heightmap[i + width] <= max_height:
            edges.add(i + width)

    length_of_best_path_so_far = 99999

    for start in [pos for pos in range(len(heightmap)) if heightmap[pos] == 0]:
        frontier = []
        heapq.heappush(frontier, (0, start))
        closed_set = set()
        shortest_path_so_far_to = {start: 0}

        end_x = end % width
        end_y = end // width

        while frontier:
            current = heapq.heappop(frontier)[1]

            if current == end:
                break

            for next in graph[current]:
                new_cost = shortest_path_so_far_to[current] + 1
                if next not in shortest_path_so_far_to or new_cost < shortest_path_so_far_to[next]:
                    shortest_path_so_far_to[next] = new_cost

                    heapq.heappush(frontier, (new_cost, next))

        if end in shortest_path_so_far_to and shortest_path_so_far_to[end] < length_of_best_path_so_far:
            length_of_best_path_so_far = shortest_path_so_far_to[end]

    print(f"* Beginning from the most ideal starting position, there will be {length_of_best_path_so_far} steps to walk along the scenic trail to the hilltop.")


from CSP import Constraint, ConstraintSatisfactionProblem, print_sudoku
from typing import Dict, List, Optional
import time
import json

# A map constraint is a two way constraint between two variables
class MapConstraint(Constraint[str, str]):
    def __init__(self, place1: str, place2: str) -> None:
        super().__init__([place1, place2])
        self.place1: str = place1
        self.place2: str = place2

    def is_satisfied(self, assignment: Dict[str, str]) -> bool:
        # If either place is not in the assignment then it is not
        # yet possible for their colors to be conflicting
        if self.place1 not in assignment or self.place2 not in assignment:
            return True
        # check the color assigned to place1 is not the same as the
        # color assigned to place2
        return assignment[self.place1] != assignment[self.place2]

# A sudoku constraint is shared between 9 variables. It is not directional, so all 9 variables actually share this
class SudokuConstraint(Constraint[str, int]):
    def __init__(self, places: List[str]):
        super().__init__(places)

    def is_satisfied(self, assignment: Dict[str, int]) -> bool:
        # For each assigned variable
        for index in range(len(self.variables)):
            variable = self.variables[index]
            if variable in assignment:
                # Every other variable in the row/cell
                # We only check the values forward from the current index since previous
                # indices have already been checked for equality
                for i in range(index + 1, len(self.variables)):
                    variable_2 = self.variables[i]
                    if variable_2 in assignment:
                        # If the domain of the variables are the same
                        if assignment[variable] == assignment[variable_2]:
                            # Constraint is not satisfied
                            return False
        return True

# A method used to parse the json, specify the domains and add the constraints
def createMapCSP() -> ConstraintSatisfactionProblem:
    csp: ConstraintSatisfactionProblem[str, str] = None
    with open('gcp.json', 'r') as f:
        data = json.load(f)
        print(data)
        variables: List[str] = []
        domains: Dict[str, List[str]] = {}
        for key in data['points']:
            variables.append(key)
            domains[key] = ["red", "green", "blue", "purple"]
        csp = ConstraintSatisfactionProblem(variables, domains)
        for edge in data['edges']:
            csp.add_constraint(MapConstraint(str(edge[0]), str(edge[1])))
    return csp

# A method to parse the json, specify the domains, specify the initial assignment and add the constraints
# There is not 2d array or anything like that that makes up the sudoku board
# The board's structure is dictated simply by the constraints and saved in a list of variables
# with variable values in the format '##' where the first number is the column and the second is the row
def createSudokuCSP() -> ConstraintSatisfactionProblem:
    csp: ConstraintSatisfactionProblem = None
    with open('sudoku.json', 'r') as f:
        table = json.load(f)
        variables = []
        domains: Dict[str, List[int]] = {}
        assignments: Dict[str, int] = {}
        # For each column
        for col in range(0, 9):
            # For each row
            for row in range(0, 9):
                # The key is '##' where 1 <= # <= 9 and it's '[col][row]'
                key = str(col + 1) + str(row + 1)
                # Add this key to the list of all variables
                variables.append(key)
                # The domain of a pre-assigned space is that one value (not necessary, but just for consistency)
                # The domain of a non-assigned space is 1-9
                if table[col][row] != 0:
                    domains[key] = [table[col][row]]
                    assignments[key] = table[col][row]
                else:
                    domains[key] = list(range(1, 10))

        csp = ConstraintSatisfactionProblem(variables, domains, initial_assignments=assignments, sudoku= True)
        # Horizontal Constraints
        for col in range(len(table)):
            row_list: List[str] = []
            for row in range(len(table)):
                row_list.append(str(col + 1) + str(row + 1))
            csp.add_constraint(SudokuConstraint(row_list))

        # Vertical Constraints
        for row in range(len(table)):
            col_list = []
            for col in range(len(table)):
                col_list.append(str(col + 1) + str(row + 1))
            csp.add_constraint(SudokuConstraint(col_list))

        # Cell Constraints
        for cell_row in range(0, 3):
            for cell_col in range(0, 3):
                cell_list = []
                for row in range(0, 3):
                    for col in range(0, 3):
                        cell_list.append(str(3 * cell_row + row + 1) + str(3 * cell_col + col + 1))
                csp.add_constraint(SudokuConstraint(cell_list))
    return csp

if __name__ == "__main__":
    variables: List[str] = []
    csp = createSudokuCSP()
    start = time.time()
    solution: Optional[Dict[str, int]] = csp.solve()
    print("Time: " + str(time.time() - start))
    if solution is None:
        print("No solution found!")
    else:
        print_sudoku(solution)
        print("Solution Found")
        print(solution)

    csp = createMapCSP()
    start = time.time()
    solution: Optional[Dict[str, str]] = csp.solve()
    print("Time: " + str(time.time() - start))
    if solution is None:
        print("No solution found!")
    else:
        print("Solution Found")
        print(solution)


'''
Given an integer array nums where the elements are sorted in ascending order, convert it to a height-balanced binary search tree.

A height-balanced binary tree is a binary tree in which the depth of the two subtrees of every node never differs by more than one.

Example 1:

Input: nums = [-10,-3,0,5,9]
Output: [0,-3,9,-10,null,5]
Explanation: [0,-10,5,null,-3,null,9] is also accepted:

Example 2:

Input: nums = [1,3]
Output: [3,1]
Explanation: [1,3] and [3,1] are both a height-balanced BSTs.

Constraints:

1 <= nums.length <= 104
-104 <= nums[i] <= 104
nums is sorted in a strictly increasing order.
'''

class Solution:
    def sortedArrayToBST(self, nums: List[int]) -> TreeNode:
        def linkSorted(candidates):
            if len(candidates) == 0: return None
            n = len(candidates) // 2
            root = TreeNode(candidates[n])
            root.left = linkSorted(candidates[:n])
            root.right = linkSorted(candidates[n+1:])
            return root
        return linkSorted(nums)


# File names
OTUS = "log10_relative_OTU_all.csv"
LABELS = "class_labels.csv"

# Hyper-parameter grid for training classifiers
svm_hyper_parameters = [{'C': [2 ** s for s in range(-4, 4, 1)], 'kernel': ['linear']},
                        {'C': [2 ** s for s in range(-4, 4, 1)], 'gamma': ['scale', 'auto'], 'kernel': ['rbf']}]
rf_hyper_parameters = [{'n_estimators': [2 ** s for s in range(7, 11, 1)],
                        'max_features': ['sqrt', 'log2'],
                        'criterion': ['gini', 'entropy']
                        }, ]
mlp_hyper_parameters = [{'hidden_layer_sizes': [(128, 64, 32), (128, 64, 32, 16), (128, 64, 32, 16, 8)],
                            'learning_rate': ['constant', 'invscaling', 'adaptive'],
                            'alpha': [10** s for s in range(-4, 0, 1)]
                            }]


import pytest
import logging
import tempfile
from iotile.core.hw.hwmanager import HardwareManager
from iotile.core.hw.transport.adapter.sync_wrapper import SynchronousLegacyWrapper
from iotile.core.hw.transport import VirtualDeviceAdapter
from iotile.core.utilities import BackgroundEventLoop
from iotile_transport_socket_lib.unix_socket.unixsocket_adapter import UnixSocketDeviceAdapter
from iotile_transport_socket_lib.unix_socket.unixsocket_server import UnixSocketDeviceServer

logger = logging.getLogger(__name__)

@pytest.fixture(scope="function")
def loop():
    """Get a fresh BackgroundEventLoop."""

    event_loop = BackgroundEventLoop()
    event_loop.start()

    yield event_loop

    event_loop.stop()

@pytest.fixture(scope="function")
def server(request, loop):
    devices = request.param
    tmpdir = tempfile.TemporaryDirectory(dir="/tmp")
    socketfile = tmpdir.name+"/s"

    if not isinstance(devices, tuple):
        devices = (devices,)

    logger.info("Parametrizing server with devices: %s", devices)

    adapter = VirtualDeviceAdapter(devices=devices, loop=loop)
    loop.run_coroutine(adapter.start())

    args = {
        'path': socketfile
    }
    dev_server = UnixSocketDeviceServer(adapter, args, loop=loop)
    loop.run_coroutine(dev_server.start())

    yield socketfile, adapter

    loop.run_coroutine(dev_server.stop())
    loop.run_coroutine(adapter.stop())

@pytest.fixture(scope="function")
def hw(server):
    path, _ = server

    logger.info("Creating HardwareManager at with socket path %s", path)
    hw = HardwareManager(port="unix:{}".format(path))

    yield hw

    hw.close()

@pytest.fixture(scope="function")
def device_adapter(server, loop):
    path, _ = server

    adapter = UnixSocketDeviceAdapter(port=path, loop=loop)
    wrapper = SynchronousLegacyWrapper(adapter, loop=loop)
    yield wrapper

    wrapper.stop_sync()

@pytest.fixture(scope="function")
def multiple_device_adapter(server, loop):
    path, _ = server

    adapter1 = UnixSocketDeviceAdapter(port=path, loop=loop)
    adapter2 = UnixSocketDeviceAdapter(port=path, loop=loop)

    wrapper1 = SynchronousLegacyWrapper(adapter1, loop=loop)
    wrapper2 = SynchronousLegacyWrapper(adapter2, loop=loop)

    yield wrapper1, wrapper2

    wrapper1.stop_sync()
    wrapper2.stop_sync()


import cv2
import numpy as np

import torch
from Pytorch_model.model_process import create_model
from Pytorch_model.model_process import load_model
from utils.image import get_affine_transform
import time

from torchvision.models.resnet import resnet18
from torch2trt.torch2trt import torch2trt

class BaseDetector(object):
    def __init__(self, opt):
        opt.device = torch.device('cuda')
        print('Creating model...')
        self.model_trt = create_model(opt.backbone, opt.heads, opt.head_conv, True)
        self.model = create_model(opt.backbone, opt.heads, opt.head_conv, False)
        #because tensorrt not support mutioutpu and ConvTranspose2d, so neeed splite

        self.model_trt = load_model(self.model_trt, opt.load_model)
        self.model = load_model(self.model, opt.load_model)

        self.model_trt = self.model_trt.to(opt.device)
        self.model_trt.eval()

        self.model = self.model.to(opt.device)
        self.model.eval()
        #Transform model from torch to tensorrt
        if opt.tensorrt:
            x = torch.ones((1, 3, 512, 512)).cuda()

            self.model_trt = torch2trt(self.model_trt, [x])
            torch.save(self.model_trt.state_dict(), 'temp.pth')
            from torch2trt import TRTModule
            self.model_trt = TRTModule()
            self.model_trt.load_state_dict(torch.load('temp.pth'))

        self.mean = np.array(opt.mean, dtype=np.float32).reshape(1, 1, 3)
        self.std = np.array(opt.std, dtype=np.float32).reshape(1, 1, 3)
        self.max_per_image = 100
        self.num_classes = opt.num_classes
        self.scales = opt.test_scales
        self.opt = opt
        self.pause = True

    def pre_process(self, image, scale, meta=None):
        height, width = image.shape[0:2]
        new_height = int(height * scale)
        new_width = int(width * scale)

        if self.opt.fix_res:
            inp_height, inp_width = self.opt.input_h, self.opt.input_w
            c = np.array([new_width / 2., new_height / 2.], dtype=np.float32)
            s = max(height, width) * 1.0
        else:
            inp_height = (new_height | self.opt.pad) + 1
            inp_width = (new_width | self.opt.pad) + 1
            c = np.array([new_width // 2, new_height // 2], dtype=np.float32)
            s = np.array([inp_width, inp_height], dtype=np.float32)

        trans_input = get_affine_transform(c, s, 0, [inp_width, inp_height])
        resized_image = cv2.resize(image, (new_width, new_height))
        inp_image = cv2.warpAffine(
            resized_image, trans_input, (inp_width, inp_height),
            flags=cv2.INTER_LINEAR)
        inp_image = ((inp_image / 255. - self.mean) / self.std).astype(np.float32)
        images = inp_image.transpose(2, 0, 1).reshape(1, 3, inp_height, inp_width)

        images = torch.from_numpy(images)
        meta = {'c': c, 's': s,
                'out_height': inp_height // self.opt.down_ratio,
                'out_width': inp_width // self.opt.down_ratio}
        return images, meta

    def process(self, images, return_time=False):
        raise NotImplementedError

    def post_process(self, dets, meta, scale=1):
        raise NotImplementedError

    def merge_outputs(self, detections):
        raise NotImplementedError

    def debug(self, debugger, images, dets, output, scale=1):
        raise NotImplementedError

    def show_results(self, debugger, image, results):
        raise NotImplementedError

    def run(self, image_or_path_or_tensor, meta=None):
        start_time = time.time()

        load_time, pre_time, net_time, dec_time, post_time = 0, 0, 0, 0, 0
        merge_time, tot_time = 0, 0
        pre_processed = False

        if isinstance(image_or_path_or_tensor, np.ndarray):
            image = image_or_path_or_tensor
        elif type(image_or_path_or_tensor) == type(''):
            image = cv2.imread(image_or_path_or_tensor)
        else:
            image = image_or_path_or_tensor['image'][0].numpy()
            pre_processed_images = image_or_path_or_tensor

        detections = []
        for scale in self.scales:
            scale_start_time = time.time()
            images, meta = self.pre_process(image, scale, meta)
            images = images.to(self.opt.device)
            torch.cuda.synchronize()
            pre_process_time = time.time()
            pre_time += pre_process_time - scale_start_time

            output, dets, forward_time = self.process(images, return_time=True)

            torch.cuda.synchronize()
            net_time += forward_time - pre_process_time
            decode_time = time.time()
            dec_time += decode_time - forward_time

            dets = self.post_process(dets, meta, scale)
            torch.cuda.synchronize()
            post_process_time = time.time()
            post_time += post_process_time - decode_time

            detections.append(dets)

        results = self.merge_outputs(detections)
        torch.cuda.synchronize()
        end_time = time.time()
        merge_time += end_time - post_process_time
        tot_time += end_time - start_time

        return {'results': results, 'tot': tot_time, 'load': load_time,
                'pre': pre_time, 'net': net_time, 'dec': dec_time,
                'post': post_time, 'merge': merge_time}


import torch
import torch.nn as nn
import torch.nn.functional as F
from modeling.sync_batchnorm.batchnorm import SynchronizedBatchNorm2d
from modeling.aspp import build_aspp
from modeling.decoder import build_decoder
from modeling.backbone import build_backbone
from operations import ABN, NaiveBN

class DeepLab(nn.Module):
    def __init__(self, backbone='resnet', output_stride=16, num_classes=19,
                 use_ABN=True, freeze_bn=False, args=None, separate=False):
        super(DeepLab, self).__init__()
        if backbone == 'drn':
            output_stride = 8

        if use_ABN:
            BatchNorm = ABN
        else:
            BatchNorm = NaiveBN

        self.backbone = build_backbone(backbone, output_stride, BatchNorm, args)
        self.aspp = build_aspp(backbone, output_stride, BatchNorm, args, separate)
        self.decoder = build_decoder(
            num_classes, backbone, BatchNorm, args, separate)

        if freeze_bn:
            self.freeze_bn()

    def forward(self, input_feature):
        x, low_level_feat = self.backbone(input_feature)
        x = self.aspp(x)
        x = self.decoder(x, low_level_feat)
        x = F.interpolate(x, size=input_feature.shape[2:], mode='bilinear', align_corners=True)

        return x

    def freeze_bn(self):
        for m in self.modules():
            if isinstance(m, ABN):
                m.eval()
            elif isinstance(m, nn.BatchNorm2d):
                m.eval()

    def get_1x_lr_params(self):
        modules = [self.backbone]
        for i in range(len(modules)):
            for m in modules[i].named_modules():
                if isinstance(m[1], nn.Conv2d) or isinstance(m[1], SynchronizedBatchNorm2d) \
                        or isinstance(m[1], nn.BatchNorm2d):
                    for p in m[1].parameters():
                        if p.requires_grad:
                            yield p

    def get_10x_lr_params(self):
        modules = [self.aspp, self.decoder]
        for i in range(len(modules)):
            for m in modules[i].named_modules():
                if isinstance(m[1], nn.Conv2d) or isinstance(m[1], SynchronizedBatchNorm2d) \
                        or isinstance(m[1], nn.BatchNorm2d):
                    for p in m[1].parameters():
                        if p.requires_grad:
                            yield p

if __name__ == "__main__":
    model = DeepLab(backbone='mobilenet', output_stride=16)
    model.eval()
    input = torch.rand(1, 3, 513, 513)
    output = model(input)
    print(output.size())


# -*- coding: utf-8 -*-

import base64

from odoo import models, fields, api, tools
from odoo.modules.module import get_resource_path

#这个要去掉，直接利用odoo的，在设置中设置
class AnodooProduct(models.Model):
    _name = 'anodoo.product'
    _description = '产品描述和配置,单例实体'
    _rec_name = 'product_name'
    _order = 'id'

    def _get_default_favicon(self):
        image_path = get_resource_path('anodoo_base', 'static/src/img/favicon.ico')
        with tools.file_open(image_path, 'rb') as f:
            return base64.b64encode(f.read())

    def _default_logo(self):
        image_path = get_resource_path('anodoo_base', 'static/src/img', 'anodoo-logo.png')
        with tools.file_open(image_path, 'rb') as f:
            return base64.b64encode(f.read())

    def _default_icon(self):
        image_path = get_resource_path('anodoo_base', 'static/description', 'icon.png')
        with tools.file_open(image_path, 'rb') as f:
            return base64.b64encode(f.read())

    product_name = fields.Char('名称名称', default="Anodoo", required=True, help="产品名称,可以将Odoo,Anodoo改为自己的产品名称")

    product_website = fields.Char('产品官网', default="http://www.anodoo.com", help="产品官网,系统很多地方链接到产品官网")

    product_logo = fields.Binary('产品Logo', default=_default_logo, help="产品Logo,图片形式,在一些地方可以替换Odoo,Anodoo的图片")

    product_icon = fields.Binary('产品Icon', default=_default_icon, help="产品图标,图片形式,在一些地方可以替换Odoo,Anodoo的图标")

    product_description = fields.Text('产品描述')

class UserMenuLink(models.Model):
    _name = 'anodoo.usermenu.link'
    _description = '系统右上角的用户菜单额外扩展的链接'
    _rec_name = 'name'
    _order = 'id'

    name = fields.Char('名称', required=True)

    sequence = fields.Integer('序号', default=10)

    description = fields.Text('描述')

    active = fields.Boolean('激活', default=True)

    isblank = fields.Boolean('是否新窗口', default=True)

    url = fields.Char('链接URL')

    groups = fields.Char('角色组')

    onclick = fields.Text('onclick方法内容', help="设置了url后onclick方法不会被调用")

class DataClean(models.Model):
    _name = 'anodoo.data.clean'
    _description = '数据清理功能,不同的数据清理定义一个'
    _rec_name = 'name'
    _order = 'id'

    name = fields.Char('名称', required=True)

    table_name = fields.Char('数据库表', help="多个数据库表用,号隔开, 提供了表名后按照顺序删除表内的数据")

    class_name = fields.Char('调用类名', default="anodoo_base.model.UserMenuLinkTools", help="清理功能所在类,默认为anodoo_base.model.UserMenuLinkTools")

    method_name = fields.Char('调用方法名', help="清理功能所在类的方法,可以继承UserMenuLinkTools定义一个新方法")

    method_define = fields.Text('调用方法过程', help="清理功能的方法过程")

    description = fields.Text('描述')

    active = fields.Boolean('激活', default=True)

    def action_data_clean(self, **additional_values):
        raise NotImplementedError("请实现anodoo_base.models.base_models.py的action_data_clean方法")

#参考res.user 的 'res.users.log' 登陆人和登陆时间使用 create_uid, create_date, 但是会被清空
class LoginRecord(models.Model):
    _name = 'anodoo.login.record'
    _rec_name = 'user_id'
    _order = 'id desc'
    _description = '用户登陆记录'

    user_id = fields.Many2one('res.users', string='登陆用户')

    login_time = fields.Datetime('登陆时间', default=lambda self: fields.datetime.now())

    login_ip = fields.Char(string="登陆IP")


# take 3 inputs from User and find the max

num_1, num_2, num_3 = input('Enter the 3 numbers : ').split()
num_1 = int(num_1)
num_2 = int(num_2)
num_3 = int(num_3)

# if num_1 > (num_2 and num_3):
#     print(f'{num_1} is greater')
# elif num_2 > (num_3 and num_1):
#     print(f'{num_2} is greater')
# else:
#     print(f'{num_3} is greater')

if num_1 > num_2 and num_1 > num_3:
    print(f'{num_1} is greater')
elif num_2 > num_3 and num_2 > num_1:
    print(f'{num_2} is greater')
else:
    print(f'{num_3} is greater')


import torch
import torch.nn as nn
import torch.optim as optim
import torchvision
import torchvision.transforms as transforms
import os
import argparse
from resnet import ResNet, BasicBlock
from utils import progress_bar

# Set up argument parser
parser = argparse.ArgumentParser(description='PyTorch CIFAR10 Training')
parser.add_argument('--lr', default=0.1, type=float, help='learning rate')
parser.add_argument('--data', default='./data', type=str, help='Path to CIFAR10 dataset')
parser.add_argument('--workers', default=2, type=int, help='Number of dataloader workers')
parser.add_argument('--optimizer', default='sgd', type=str, help='Optimizer type (e.g., "sgd")')
parser.add_argument('--device', default='cuda' if torch.cuda.is_available() else 'cpu', type=str, help='Device to run on ("cuda" or "cpu")')
args = parser.parse_args()

device = args.device

# Prepare data with transformations
transform_train = transforms.Compose([
    transforms.RandomCrop(32, padding=4),
    transforms.RandomHorizontalFlip(),
    transforms.ToTensor(),
    transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)),
])

trainset = torchvision.datasets.CIFAR10(
    root=args.data, train=True, download=True, transform=transform_train)
trainloader = torch.utils.data.DataLoader(
    trainset, batch_size=128, shuffle=True, num_workers=args.workers)

# Build ResNet-18 model
model = ResNet(BasicBlock, [2, 2, 2, 2])
model = model.to(device)

if device == 'cuda':
    model = torch.nn.DataParallel(model)

criterion = nn.CrossEntropyLoss()
if args.optimizer == 'sgd':
    optimizer = optim.SGD(model.parameters(), lr=args.lr, momentum=0.9, weight_decay=5e-4)
else:
    raise ValueError(f"Unsupported optimizer: {args.optimizer}")

# Training function
def train(epoch):
    print('\nEpoch: %d' % epoch)
    model.train()
    train_loss = 0
    correct = 0
    total = 0
    for batch_idx, (inputs, targets) in enumerate(trainloader):
        inputs, targets = inputs.to(device), targets.to(device)
        optimizer.zero_grad()
        outputs = model(inputs)
        loss = criterion(outputs, targets)
        loss.backward()
        optimizer.step()

        train_loss += loss.item()
        _, predicted = outputs.max(1)
        total += targets.size(0)
        correct += predicted.eq(targets).sum().item()

        progress_bar(batch_idx, len(trainloader), 'Loss: %.3f | Acc: %.3f%% (%d/%d)'
                     % (train_loss/(batch_idx+1), 100.*correct/total, correct, total))

# Train for 5 epochs
for epoch in range(5):
    print("Starting Training\n")
    train(epoch)


from lib.model.Analysis import Analysis

import base64

import jinja2
import os

dirname = os.path.realpath(os.path.dirname(os.path.realpath(__file__))+'/../../')

class ReportGenerator:

    @staticmethod
    def b64encode(text):
        return base64.b64encode(text).decode('utf8')

    def generate(self, path, param):
        '''
        Generate the report by rendering with jinja2 template
        :param param:
        :param searchpath:
        :return:
        '''
        templateLoader = jinja2.FileSystemLoader(searchpath=dirname+'/templates/report')
        templateEnv = jinja2.Environment(loader=templateLoader,autoescape=jinja2.select_autoescape(
                                        enabled_extensions=('html', 'xml'),
                                        default_for_string=True),
                                        extensions=['jinja2.ext.do'])

        templateEnv.filters['b64encode'] = ReportGenerator.b64encode

        TEMPLATE_FILE = f"index.jinja"
        template = templateEnv.get_template(TEMPLATE_FILE)

        outputText = template.render(param=param)

        path = f"{path}/{param.analysis.date}_{param.analysis.application[0].package}_{param.analysis.application[0].sha256}.html"
        f = open(path,"w")
        f.write(outputText)
        f.close()
        return path


# Imported Libraries
import numpy as np
import matplotlib.pyplot as plt

'''
I want to compute the sum over time of the mass density for radiation form black hole accretion and from HMXB emission. This is a replica of
figure 10 from Jeon et al. 2014.
'''

'''
Importing data files of the highest lines from the top and bottom panels of figure 9.
'''

accretion_timeHMXB_dashed, accretion_rateHMXB_dashed = np.loadtxt('/Users/laurenhiggins/Desktop/Research Projects/CIB_Research/analysis/HMXB/tables/line_tables/Dashed_w_Gray_Peak.txt').T
time_Jeon_fig10, rate_Jeon_fig10 = np.loadtxt('/Users/laurenhiggins/Desktop/Research Projects/CIB_Research/analysis/HMXB/tables/Jeon_fig10_og.txt').T

fig = plt.figure(figsize=[14,8])
fig, ax1 = plt.subplots()
ax1.plot( accretion_timeHMXB_dashed, accretion_rateHMXB_dashed, 'r', label='accretion rate')
ax1.set_yscale('log')
ax1.set_xlabel('Time [Myr]')
ax1.set_ylabel('Accretion Rate $\\dot{\\rho}$ [M$\\odot$ yr$^{-1}$]')
#fig.savefig('/Users/laurenhiggins/Desktop/CIB_Research/analysis/HMXB/plots/accretion_rate_dashed.pdf', bbox_inches = "tight")
ax1.legend()
plt.show()

'''
density over cosmic time = the integration of the sum of the accretion rate densities from HMXB. This rate is from dashed lines of the top
panel of Figure 9.
'''
def rho_acc(file_sum, small_time):
    accretion_density = np.zeros(len(file_sum))

    def rho_help(rho, t2, t1):
        return rho * (t2 - t1) * 1e6 * (0.7)**3 / 0.3**3

    for i in range(0, len(file_sum)-1):
        accretion_density[i] = rho_help(file_sum[i], small_time[i], small_time[i-1])
        if i == 0:
            accretion_density[i] = rho_help(file_sum[i], small_time[i], small_time[i-1])
        if i > 0:
            accretion_density[i] = accretion_density[i-1] + accretion_density[i]
    return accretion_density

#dashed_density = rho_acc(interp_sum, accretion_timeHMXB_dashed)
dashed_density = rho_acc(accretion_rateHMXB_dashed, accretion_timeHMXB_dashed)

'''
Replicated plot. Note, that my input accretion rate values range from ~105 Myr to 200 Mry. This accounts for the offset in starting and ending points
in the plot.
'''

fig, ax1 = plt.subplots(figsize=[8,4])
ax1.plot( time_Jeon_fig10, np.log10(rate_Jeon_fig10), 'r-', label='Jeon fig10 w/ HMXBs')
ax1.plot( accretion_timeHMXB_dashed, np.log10(dashed_density), 'g--', label='Higgins w/ HMXB Dashed')
ax1.set_xlim([100, 207])
ax1.set_xticks([100, 120, 140, 160, 180, 200])
#ax1.set_ylim([-4, 3])
#ax1.set_yticks([-4, -2, 0, 2, 4])
#ax1.set_yscale('log')
ax1.yaxis.get_ticklocs(minor=True)
ax1.minorticks_on()
ax1.yaxis.set_ticks_position('both')
ax1.set_xlabel('t$_{H}$(z) [Myr]')
#ax1.set_ylabel('log$_{10}(\\rho_{acc})$ [M$\\odot$ yr$^{-1}$]')
ax1.set_ylabel('$\\rho_{acc}$ [M$\\odot$ yr$^{-1}$]')
ax1.legend(loc=4, fontsize=10)
#fig.savefig('/Users/laurenhiggins/Desktop/Research Projects/CIB_Research/analysis/HMXB/plots/Jeon_fig10_compairson_V5.pdf', bbox_inches = "tight")
plt.show()


# Data Extraction packages
import os
import requests
from bs4 import BeautifulSoup

# stats per champion
def extract_stats():
  filename = "data/stats.txt"
  if os.path.isfile(filename):
    return

  stats_per_champion_url = 'https://www.op.gg/statistics/ajax2/champion/'
  stats_response = requests.post(stats_per_champion_url, data = {'type': 'win','league':'', 'period': 'month','mapId': 1, 'queue': 'ranked'})
  stats_per_champion_soup = BeautifulSoup(stats_response.text, 'html.parser')
  stats_rows = stats_per_champion_soup.find_all('tr', {'class':'Row'})

  print(f"stats: {len(stats_rows[1:])} champions found.")

  def extract_stats(row):
    name = row.find('td', {'class', 'ChampionName'}).text.replace('\'','').strip()
    victory_rate = row.find('span', {'class', 'Value'}).text.replace('%', '').strip()
    games = row.find_all('td', {'class', 'Cell'})[4].text.replace(',','').strip()
    kda = row.find('td', {'class', 'KDARatio'}).text.split(":")[0].strip()
    cs = row.find('span', {'class', 'Value Green'}).text.strip()
    gold = row.find('span', {'class', 'Value Orange'}).text.replace(',','').strip()
    stats_attributes = [name,victory_rate,games,kda,cs,gold]
    return ','.join(stats_attributes) + "\n"

  champions_stats = [extract_stats(row) for row in stats_rows[1:]]
  champions_stats.sort()
  stats_file_content = ''.join(champions_stats)

  outfile = open(filename, "w")
  outfile.write(stats_file_content)
  outfile.close()


#!/usr/bin/env python3
import json
import os
import codecs

from werkzeug.utils import secure_filename
from flask import Flask, render_template, request, flash, redirect, send_from_directory, make_response, Markup

app = Flask(__name__)
app.secret_key = "super secret key"
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024

ROOT = os.getcwd()

ALLOWED_EXTENSIONS = {'txt', 'pdf', 'csv', "json"}

@app.route("/application_ran", methods=['GET', 'POST'])
def complete_app():

    DOWNLOAD_FOLDER = "C:\\Users\\wirksc\\NTC Tools\\NLP_Project\\data\\e2b9a4a429008824c88bb99f5a843a193047c3c7e173b14216f7b1690e45b581\\downloaded"
    userItems = codecs.open(os.path.join(DOWNLOAD_FOLDER, "data.html"), 'r')
    html_in_browser = userItems.read()
    html_in_browser = Markup(html_in_browser)
    if not True:
        html_in_browser = None

    if True:
        plotly_chart=True

    return render_template("app_finish.html", html_in_browser=html_in_browser, plotly_chart=plotly_chart)

@app.route('/out/<filename>')
def downloaded_file(filename):
    DOWNLOAD_FOLDER = "C:\\Users\\wirksc\\NTC Tools\\NLP_Project\\data\\e2b9a4a429008824c88bb99f5a843a193047c3c7e173b14216f7b1690e45b581\\downloaded"
    return send_from_directory(os.path.join(DOWNLOAD_FOLDER), filename)

if __name__=='__main__':
    app.run(host='0.0.0.0', port=8000, debug=True, use_reloader=False)


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

class myRNN(nn.Module):
    def __init__(self,input_size,hidden_size,num_layers):
        super(RNN, self).__init__()

        self.rnn = nn.RNN(
            input_size=input_size,
            hidden_size=hidden_size,  # RNN隐藏神经元个数
            num_layers=len(num_layers),  # RNN隐藏层个数
            batch_first=True
        )
        self.out = nn.Linear(hidden_size, input_size)

    def forward(self, x, hidden):
        batch_size = x.shape[0]
        r_out, hidden = self.rnn(x, hidden)
        r_out = r_out.view(-1, self.rnn.hidden_size)
        output = self.fc(r_out)

        return output, hidden


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

# In[1]:

#Output

# In[2]:

import cv2
import os
from glob import *

# In[3]:

list_of_dirs = glob('./data/*/**.mp4')
list_of_dirs

# In[4]:

list_of_dirs[0].split('\\')

# In[5]:

# alp_name = list_of_dirs[0].split('\\')[1]

# d_name = 'frame/'+str(alp_name)

# try:
#     os.mkdir(d_name)

# except:
#     pass

# ['./data', 'E', 'zoom_0.mp4']

# In[ ]:

# In[6]:

# Importing all necessary libraries
import cv2
import os

currentframe = 0

for files in list_of_dirs:

    print('.'*25)
    print(f'...... file name is {files} ................')
    print('.'*25)
    flg_d =1

    if flg_d:
        alp_name = files.split('\\')[1]

        d_name = 'frame/'+str(alp_name)

        try:
            os.mkdir(d_name)

        except:

#             flg_d = 0
            pass

    cam = cv2.VideoCapture(files)

    while(True):

        ret,frame = cam.read()

        if ret:
            # if video is still left continue creating images
            name = f'./frame/{alp_name}/frame' + str(currentframe) + '.jpg'
            print ('Creating...' + name)

            # writing the extracted images
            cv2.imwrite(name, frame)

            # increasing counter so that it will
            # show how many frames are created
            currentframe += 1
        else:
            break

#         if currentframe ==5:
#             break

    # Release all space and windows once done
    cam.release()
    cv2.destroyAllWindows()

# In[7]:

# # Importing all necessary libraries
# import cv2
# import os

# # Read the video from specified path
# cam = cv2.VideoCapture("data/L/zoom_0.mp4")

# currentframe = 0

# while(True):

#     ret,frame = cam.read()

#     if ret:
#         # if video is still left continue creating images
#         name = './data/frame/frame' + str(currentframe) + '.jpg'
#         print ('Creating...' + name)

#         # writing the extracted images
#         cv2.imwrite(name, frame)

#         # increasing counter so that it will
#         # show how many frames are created
#         currentframe += 1
#     else:
#         break

#     if currentframe ==20:
#         break

# # Release all space and windows once done
# cam.release()
# cv2.destroyAllWindows()

# In[8]:

currentframe #976

# In[ ]:


from example.example_data import documents
from vectorizer.dictionary_builder import load_dictionary
from vectorizer.tfidf_vectorizer import build_TfIdfModel_from_list_of_texts, save_tfidf_model, convert_text_to_tfidf

file_dictionary = '/tmp/example.dict'
output_tfidf_model_filename = '/tmp/example.tfidf'
dict=load_dictionary(file_dictionary)
tfidf_model=build_TfIdfModel_from_list_of_texts(documents, dict)
save_tfidf_model(tfidf_model, output_tfidf_model_filename)

sample="Graph for Human machine interface"
tfidf=convert_text_to_tfidf(sample, dict, tfidf_model)
print(sample, tfidf)


import asyncio
import os
import shutil
from typing import Dict, FrozenSet, List
from uuid import UUID

from ai.backend.common.types import BinarySize
from ai.backend.storage.abc import CAP_QUOTA, CAP_VFOLDER

from ..exception import ExecutionError
from ..types import FSUsage, Optional, VFolderCreationOptions
from ..vfs import BaseVolume

async def run(cmd: str) -> str:
    proc = await asyncio.create_subprocess_shell(
        cmd, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE
    )
    out, err = await proc.communicate()
    if err:
        raise ExecutionError(err.decode())
    return out.decode()

class CephFSVolume(BaseVolume):
    loop: asyncio.AbstractEventLoop
    registry: Dict[str, int]
    project_id_pool: List[int]

    async def init(self) -> None:
        available = True
        try:
            await asyncio.create_subprocess_exec(
                b"ceph",
                b"--version",
                stdout=asyncio.subprocess.PIPE,
                stderr=asyncio.subprocess.STDOUT,
            )
        except FileNotFoundError:
            available = False

        if not available:
            raise RuntimeError("Ceph is not installed. ")

    async def get_capabilities(self) -> FrozenSet[str]:
        return frozenset([CAP_VFOLDER, CAP_QUOTA])

    # ----- volume operations -----
    async def create_vfolder(
        self,
        vfid: UUID,
        options: Optional[VFolderCreationOptions] = None,
        *,
        exist_ok: bool = False
    ) -> None:
        vfpath = self.mangle_vfpath(vfid)
        loop = asyncio.get_running_loop()
        await loop.run_in_executor(
            None,
            lambda: vfpath.mkdir(0o755, parents=True, exist_ok=exist_ok),
        )
        if not (options is None or options.quota is None or options.quota == 0):
            quota = options.quota
            await self.set_quota(vfpath, quota)

    async def get_fs_usage(self) -> FSUsage:
        (total, used, _) = await asyncio.get_running_loop().run_in_executor(
            None,
            shutil.disk_usage,
            self.mount_path,
        )
        return FSUsage(
            capacity_bytes=BinarySize(total),
            used_bytes=BinarySize(used),
        )

    async def get_quota(self, vfpath) -> BinarySize:
        loop = asyncio.get_running_loop()
        raw_report = await loop.run_in_executor(
            None,
            # without type: ignore mypy will raise error when trying to run on macOS
            # because os.getxattr() is only for linux
            lambda: os.getxattr(vfpath, "ceph.quota.max_bytes"),  # type: ignore[attr-defined]
        )
        report = str(raw_report)
        if len(report.split()) != 6:
            raise ExecutionError("ceph quota report output is in unexpected format")
        _, quota = report.split("=")
        quota = quota.replace('"', "")
        return BinarySize(quota)

    async def set_quota(self, vfpath, size_bytes: BinarySize) -> None:
        loop = asyncio.get_running_loop()
        await loop.run_in_executor(
            None,
            # without type: ignore mypy will raise error when trying to run on macOS
            # because os.setxattr() is only for linux
            lambda: os.setxattr(vfpath, "ceph.quota.max_bytes", str(int(size_bytes)).encode()),  # type: ignore[attr-defined]
        )


import sys
input = sys.stdin.readline

N, M, R = map(int, input().split())
arr = [[0] * M for _ in range(N)]
for i in range(N):
     arr[i] = list(map(int, input().split()))

half = min(N, M) // 2

for _ in range(R):
     for i in range(half):
        x, y = i, i
        tmp = arr[i][i]

        for j in range(i+1, N-i):
            x = j
            prev_value = arr[x][y]
            arr[x][y] = tmp
            tmp = prev_value

        for j in range(i+1, M-i):
            y = j
            prev_value = arr[x][y]
            arr[x][y] = tmp
            tmp = prev_value

        for j in range(i+1, N-i):
            x = N - j - 1
            prev_value = arr[x][y]
            arr[x][y] = tmp
            tmp = prev_value

        for j in range(i+1, M-i):
            y = M - j - 1
            prev_value = arr[x][y]
            arr[x][y] = tmp
            tmp = prev_value

for i in range(N):
    for j in range(M):
        print(arr[i][j], end=' ')
    print()


import sys
import subprocess
import time
from datetime import timedelta

def run_blastx(dna_reads_path, protein_db_path, output_path, time_log_path):
    """
    Run BLASTx to align DNA reads to a protein database and record the execution time.

    Parameters:
    dna_reads_path (str): Path to the DNA reads file.
    protein_db_path (str): Path to the protein database file.
    output_path (str): Path to save the output file.
    time_log_path (str): Path to save the execution time log.
    """
    try:
        start_time = time.monotonic()

        # Construct the BLASTx command
        command = [
            'blastx',
            '-query', dna_reads_path,
            '-db', protein_db_path,
            '-out', output_path,
            '-outfmt', '6'  # Change this number for different output formats
        ]

        # Run the BLASTx command
        subprocess.run(command, check=True)

        end_time = time.monotonic()
        elapsed_time = timedelta(seconds=end_time - start_time)

        # Print and save the execution time
        with open(time_log_path, 'w') as f:
            f.write(f"Time taken to run the script: {elapsed_time}\n")

        print(f"BLASTx completed successfully. Output saved to {output_path}")
        print(f"Time taken to run the script: {elapsed_time}")

    except subprocess.CalledProcessError as e:
        print(f"An error occurred while running BLASTx: {e}")

dna_reads_path = sys.argv[1]
protein_db_path = sys.argv[2]
output_path = sys.argv[3]
time_log_path = sys.argv[4]

run_blastx(dna_reads_path, protein_db_path, output_path, time_log_path)


# [백준]11047번-그리디-동전0-S4
# https://github.com/irishNoah/Algorithm-Study
# https://www.acmicpc.net/problem/11047

n, k = map(int, input().split())

money = []

for _ in range(n):
    value = int(input())

    money.append(value)

money.reverse()

cnt = 0 # 동전 개수

while True:

    for i in range(0, n):
        if k == 0:
            break

        if k // money[i] > 0:
            cnt += k // money[i]

            k = k - (money[i] * (k // money[i]))

    break

print(cnt)

알고리즘/파이썬(Python)/001-그리디/001-[백준]11047번-그리디-동전0-S4.py


from tkinter import*
from tkinter import ttk
from PIL import Image, ImageTk
from attendance import Attendance
from student import Student
import os
from face_recognition import Face_Recognition
from train import Train

class Face_Recognition_System_Student:
    def __init__(self,root):
        self.root=root
        self.root.geometry("1530x790+0+0")
        self.root.title("Face Recognition System")

        # first image
        img=Image.open(r"college_images\smart-attendance.jpg")
        img=img.resize((500,150),Image.ANTIALIAS)
        self.photoimg=ImageTk.PhotoImage(img)

        f_lbl=Label(self.root,image=self.photoimg)
        f_lbl.place(x=0,y=0,width=500,height=150)

        # second image
        img1=Image.open(r"college_images\facialrecognition.png")
        img1=img1.resize((500,150),Image.ANTIALIAS)
        self.photoimg1=ImageTk.PhotoImage(img1)

        f_lbl=Label(self.root,image=self.photoimg1)
        f_lbl.place(x=500,y=0,width=500,height=150)

        # third image
        img2=Image.open(r"college_images\facial-recognition_0.jpg")
        img2=img2.resize((500,150),Image.ANTIALIAS)
        self.photoimg2=ImageTk.PhotoImage(img2)

        f_lbl=Label(self.root,image=self.photoimg2)
        f_lbl.place(x=1000,y=0,width=550,height=150)

        # bg image
        img3=Image.open(r"college_images\bg_face.jpg")
        img3=img3.resize((1300,780),Image.ANTIALIAS)
        self.photoimg3=ImageTk.PhotoImage(img3)

        bg_img=Label(self.root,image=self.photoimg3)
        bg_img.place(x=0,y=100,width=1300,height=780)

        title_lbl=Label(bg_img,text="STUDENT PANEL", font=("times new roman",35,"bold"),bg="white", fg="red")
        title_lbl.place(x=0,y=1,width=1300,height=45)

        # -------------Functions buttons-----------------
        def student_details():
            self.new_window=Toplevel(self.root)
            self.app=Student(self.new_window)

        def face_data():
            self.new_window=Toplevel(self.root)
            self.app=Face_Recognition(self.new_window)

        # # 1. student button
        img4=Image.open(r"college_images\gettyimages-1022573162.jpg")
        img4=img4.resize((280,260),Image.ANTIALIAS)
        self.photoimg4=ImageTk.PhotoImage(img4)

        # command=self.student_details
        b1=Button(bg_img,command=student_details,image=self.photoimg4,cursor="hand2")
        b1.place(x=300,y=150,width=260,height=230)

        b1_1=Button(bg_img,text="Student Details",command=student_details,cursor="hand2", font=("times new roman",15,"bold"),bg="darkblue", fg="white")
        b1_1.place(x=300,y=380,width=260,height=60)

        # detect face button
        img5=Image.open(r"college_images\face_detector1.jpg")
        img5=img5.resize((280,260),Image.ANTIALIAS)
        self.photoimg5=ImageTk.PhotoImage(img5)

        b1=Button(bg_img, image=self.photoimg5,cursor="hand2",command=face_data)
        b1.place(x=700,y=150,width=260,height=230)

        b1_1=Button(bg_img,text="Mark Your Attendance",cursor="hand2",command=face_data, font=("times new roman",15,"bold"),bg="darkblue", fg="white")
        b1_1.place(x=700,y=380,width=260,height=60)

if __name__ == "__main__":
    root=Tk()
    obj=Face_Recognition_System_Student(root)
    root.mainloop()


hours=int(input("Please Enter no. of hours you have worked in a week (HOURS): "))
if hours<=40:
    c=hours*12
if hours>40:
    c=40*12+(hours-40)*1.5*12

if c<=300:
    tax=c*0.15
elif c>300 and c<=450:
    tax=300*0.15+(c-300)*0.20
else:
    tax=300*0.15+150*0.20+(c-450)*0.25
net=c-tax
print("Your gross salary after tax deduction is : ",net,"$")


N,P,limit = map(int,input().split())

if N == 0:
    print(1)
else:
    num_list = list(map(int,input().split()))

    num_list.sort(reverse=True)

    rank_list = []

    for i in num_list:
        if len(rank_list) == limit:
            break
        else:
            rank_list.append(i)

    rank_length = len(rank_list)

    if rank_length == limit:
        if rank_list[-1] >= P:
            print(-1)
        else:
            for i,v in enumerate(rank_list):
                if v == P:
                    print(i+1)
                    break
                elif v < P:
                    print(i+1)
                    break
    elif rank_length < limit:
        if rank_list[-1] > P:
            print(rank_length+1)
        else:
            for i,v in enumerate(rank_list):
                if v == P:
                    print(i+1)
                    break
                elif v < P:
                    print(i+1)
                    break


import tensorflow as tf
import numpy as np
from mnist import MNIST
from feature_forcing import FFGAN
slim = tf.contrib.slim

class MnistGanTrainer:
  def __init__(self, batch_size, save_dest):
    mndata =  MNIST('./')
    images, labels = mndata.load_training()
    images = np.array(images, dtype=np.float32)
    labels = np.array(labels, dtype=np.float32)
    dataset = tf.data.Dataset.from_tensor_slices((images, labels))
    dataset.shuffle(1000)
    dataset.repeat()
    dataset.batch(batch_size)
    itr = dataset.make_one_shot_iterator()
    (self.img, self.lbl) = itr.get_next()
    self.img = tf.reshape(self.img, [-1, 28, 28, 1])
    self.z_noise = tf.random_uniform([batch_size, 128], minval=-1, maxval=1)
    self.model = FFGAN(self.img, self.z_noise)
    self.save_dest = save_dest

  def train(self, training_steps=100000):
    self.init_op = tf.global_variables_initializer()
    if self.save_dest is not None:
      saver = tf.train.Saver(
        keep_checkpoint_every_n_hours=0.01)  # every 12 minutes.
    else:
      saver = None
    sess = tf.Session()
    sess.run(self.init_op)
    merged = tf.summary.merge_all()
    slim.learning.train(
      self.model.train_descrim, #gan_train_op,
      self.save_dest,
      number_of_steps=training_steps,
      init_op=self.init_op,
      saver=saver,
      save_summaries_secs=60,
      save_interval_secs=360)

if __name__ == '__main__':
  model = MnistGanTrainer(1, "./mnist_events")
  model.train(100000)


import os
import glob
from bs4 import BeautifulSoup,Comment
import urllib.request
import requests
import json

uri = "https://www.carcomplaints.com/"

#read the webpage and store it as a string
webpage = urllib.request.urlopen(uri).read()

soup = BeautifulSoup(webpage,'html.parser')

#find all the <a> tags which consist of all car name
section = soup.section.find_all('a')

data_dir = os.getcwd()
data_dir = os.path.join(data_dir,"Ford Explorer")

#list of all complaints
ans = []
count_data = 0

#list of all cars
car_dict = {}
cars = []

#extract the name and url for each car and stored it in dictionary car_dict
for i in section:
    car_dict[i.text] = i["href"]
    cars.append(i.text)
print("level1 completed")
print(cars)

#now loop through the cars list.
for i in range(8,9):
    new_uri = uri+cars[i]
    print(new_uri)

    #"new_uri" will be url for the webpage which consist of all models of a  specific car.
    page = urllib.request.urlopen(new_uri).read()
    soup2 = BeautifulSoup(page,'html.parser')

    #extract all the model names and urls present in <ul> tag and store it in model_dict dictionary.
    models_div = soup2.div.find_all("ul",class_="column bar")
    model = []
    model_dict = {}

    #get list of all models
    for j in range(len(models_div)):
        for li in models_div[j].find_all("a"):
            print(li.text,"=>",li["href"])
            model.append(li.text)
            model_dict[li.text] = li["href"]
    print(model_dict)

    print("level2 completed")

    #loop through each model.
    for models in model:
        new_uri2 = uri+model_dict[models]
        print(new_uri2)
        #this new_uri2 will be new uri for webpage contains all model years. extract and save it in model_year_div
        page2 = urllib.request.urlopen(new_uri2).read()
        soup3 = BeautifulSoup(page2,'html.parser')

        model_year = []
        model_year_div = soup3.div.find("ul",class_="timeline")

        count_p = []

        #list of model year
        for li_year in model_year_div.find_all("span",class_="label"):
            print(li_year.text)
            model_year.append(li_year.text)

        for c in model_year_div.find_all("span",class_="count"):
            print(c.text)
            count_p.append(c.text)

        new_model_year = []

        #remove all the model year where cars complaint count is "0".
        for count_ele in range(len(model_year)):
            co = count_p[count_ele].replace(",","")
            if int(co) != 0:
                new_model_year.append(model_year[count_ele])
        print(new_model_year)
        print("level3 completed")

        #loop through model years
        for year in new_model_year:
            new_uri3 = new_uri2+year+"/"
            print(new_uri3)
            #new_uri3 will be new uri of webpage for problems extract it and store it in problem_dict.
            page3 = urllib.request.urlopen(new_uri3).read()
            soup4 = BeautifulSoup(page3,'html.parser')
            problem_div = soup4.find("div",id="graph").find_all("li")
            problem_dict = {}

            #list of problems
            for li_problem in range(len(problem_div)):
                a_tag = problem_div[li_problem].find("a")
                strong = problem_div[li_problem].find("strong")
                print(a_tag["href"],"=>",strong.text)
                problem_dict[strong.text] = a_tag["href"]

            print("level4 completed")
            prob_arr = list(problem_dict.keys())

            #loop through each problem.
            for prob in prob_arr:
                print(problem_dict[prob])
                new_uri4 = new_uri3+problem_dict[prob]
                #new_uri4 will be new uri of webpage for sub-problems extract it and store it in sub_problem_dict.
                print(new_uri4)
                page4 = urllib.request.urlopen(new_uri4).read()
                soup5 = BeautifulSoup(page4,'html.parser')

                sub_problems = soup5.find("div",id="graph").find_all("li")
                sub_problem_dict = {}
                #list of sub problems
                for li_subproblem in range(len(sub_problems)):
                    a_tag_sub = sub_problems[li_subproblem].find("a")
                    strong_sub = sub_problems[li_subproblem].find("strong")
                    print(a_tag_sub["href"],"=>",strong_sub.text)
                    sub_problem_dict[strong_sub.text] = a_tag_sub["href"]
                print("level5 completed")

                #loop through each sub problem.
                for sub_prob in list(sub_problem_dict.keys()):
                    new_uri5 = "https://www.carcomplaints.com"+sub_problem_dict[sub_prob]
                    print(new_uri5,"------------")
                    #new_uri5 will be new uri of webpage for complaints for a subproblem extract it and store it in problem_desc_dict.
                    page5 = urllib.request.urlopen(new_uri5).read()
                    soup6 = BeautifulSoup(page5,'html.parser')

                    problem_desc_dict = {}

                    problem_desc_div = soup6.find_all("div",class_="complaint")
                    #print(problem_desc_div)
                    #loop throght each complaint create a dictionary ans_new and add all info of car make,model,year,problem,.... and append in ans array.
                    for ele in range(len(problem_desc_div)):
                        title = problem_desc_div[ele].find("h3",class_="ptitle").text
                        problem_distance = problem_desc_div[ele].find("div",class_="cheader").find_all("li")

                        if len(problem_distance) == 1:
                            if "miles" in problem_distance[0]:
                                distance = problem_distance[0].text
                                problem = ""
                            else:
                                problem = problem_distance[0].text
                                distance = ""
                        else:
                            problem = problem_distance[0].text
                            distance = problem_distance[1].text

                        problem_distance = [ele.text for ele in problem_distance]
                        description = problem_desc_div[ele].find("div",class_="comments").text
                        description = description.replace("\n","")
                        description = description.replace("A D V E R T I S E M E N T S","")

                        ans_new = {}
                        ans_new["Vehicle"] = cars[i]
                        ans_new["Model"] = models
                        ans_new["Model Year"] = year
                        ans_new["Problem"] = prob
                        ans_new["Sub Problem"] = sub_prob
                        ans_new["Model Title"] = title
                        ans_new["Model Problem"] = problem
                        ans_new["distance covered"] = distance
                        ans_new["description"] = description

                        ans.append(ans_new)
                        #print(ans_new)

                        print("--------------------------------------------------------------")

                    #append the object in json file after each iteration so that if the program chrashes we won't lose and scraped information.
                    name = "Ford__new_"+str(models)+"_"+str(year)+".json"
                    file = os.path.join(data_dir,name)
                    with open(file, "w") as final:
                        json.dump(ans, final)
                        print("Data Saved")

            ans = []


from code import Code
from js_util import JsUtil
from model import *
from schema_util import *

import os
import sys
import re

NOTE = """// NOTE: The format of types has changed. 'FooType' is now
//   'chrome.%s.FooType'.
// Please run the closure compiler before committing changes.
// See https://chromium.googlesource.com/chromium/src/+/master/docs/closure_compilation.md
"""

class JsExternsGenerator(object):
  def Generate(self, namespace):
    return _Generator(namespace).Generate()

class _Generator(object):
  def __init__(self, namespace):
    self._namespace = namespace
    self._js_util = JsUtil()

  def Generate(self):
    """Generates a Code object with the schema for the entire namespace.
    """
    c = Code()
    (c.Append(self._GetHeader(sys.argv[0], self._namespace.name))
      .Append())

    self._AppendNamespaceObject(c)

    for js_type in self._namespace.types.values():
      self._AppendType(c, js_type)

    for function in self._namespace.functions.values():
      self._AppendFunction(c, function)

    for event in self._namespace.events.values():
      self._AppendEvent(c, event)

    c.TrimTrailingNewlines()

    return c

  def _GetHeader(self, tool, namespace):
    """Returns the file header text.
    """
    return (self._js_util.GetLicense() + '\n' +
            self._js_util.GetInfo(tool) + (NOTE % namespace) + '\n' +
            ('/** @fileoverview Externs generated from namespace: %s */' %
             namespace))

  def _AppendType(self, c, js_type):
    """Given a Type object, generates the Code for this type's definition.
    """
    if js_type.property_type is PropertyType.ENUM:
      self._AppendEnumJsDoc(c, js_type)
    else:
      self._AppendTypeJsDoc(c, js_type)
    c.Append()

  def _AppendEnumJsDoc(self, c, js_type):
    """ Given an Enum Type object, generates the Code for the enum's definition.
    """
    (c.Sblock(line='/**', line_prefix=' * ')
      .Append('@enum {string}')
      .Append(self._js_util.GetSeeLink(self._namespace.name, 'type',
                                       js_type.simple_name))
      .Eblock(' */'))
    c.Append('chrome.%s.%s = {' % (self._namespace.name, js_type.name))

    def get_property_name(e):
      # Enum properties are normified to be in ALL_CAPS_STYLE.
      # Assume enum '1ring-rulesThemAll'.
      # Transform to '1ring-rules_Them_All'.
      e = re.sub(r'([a-z])([A-Z])', r'\1_\2', e)
      # Transform to '1ring_rules_Them_All'.
      e = re.sub(r'\W', '_', e)
      # Transform to '_1ring_rules_Them_All'.
      e = re.sub(r'^(\d)', r'_\1', e)
      # Transform to '_1RING_RULES_THEM_ALL'.
      return e.upper()

    c.Append('\n'.join(
        ["  %s: '%s'," % (get_property_name(v.name), v.name)
            for v in js_type.enum_values]))
    c.Append('};')

  def _IsTypeConstructor(self, js_type):
    """Returns true if the given type should be a @constructor. If this returns
       false, the type is a typedef.
    """
    return any(prop.type_.property_type is PropertyType.FUNCTION
               for prop in js_type.properties.values())

  def _AppendTypeJsDoc(self, c, js_type):
    """Appends the documentation for a type as a Code.
    """
    c.Sblock(line='/**', line_prefix=' * ')

    if js_type.description:
      for line in js_type.description.splitlines():
        c.Append(line)

    is_constructor = self._IsTypeConstructor(js_type)
    if is_constructor:
      c.Comment('@constructor', comment_prefix = ' * ', wrap_indent=4)
    else:
      self._AppendTypedef(c, js_type.properties)

    c.Append(self._js_util.GetSeeLink(self._namespace.name, 'type',
                                      js_type.simple_name))
    c.Eblock(' */')

    var = 'chrome.%s.%s' % (js_type.namespace.name, js_type.simple_name)
    if is_constructor: var += ' = function() {}'
    var += ';'
    c.Append(var)

  def _AppendTypedef(self, c, properties):
    """Given an OrderedDict of properties, Appends code containing a @typedef.
    """
    if not properties: return

    c.Append('@typedef {')
    self._js_util.AppendObjectDefinition(c, self._namespace.name, properties,
                                         new_line=False)
    c.Append('}', new_line=False)

  def _AppendFunction(self, c, function):
    """Appends the code representing a function, including its documentation.
       For example:

       /**
        * @param {string} title The new title.
        */
       chrome.window.setTitle = function(title) {};
    """
    self._js_util.AppendFunctionJsDoc(c, self._namespace.name, function)
    params = self._GetFunctionParams(function)
    c.Append('chrome.%s.%s = function(%s) {};' % (self._namespace.name,
                                                  function.name, params))
    c.Append()

  def _AppendEvent(self, c, event):
    """Appends the code representing an event.
       For example:

       /** @type {!ChromeEvent} */
       chrome.bookmarks.onChildrenReordered;
    """
    c.Sblock(line='/**', line_prefix=' * ')
    if (event.description):
      c.Comment(event.description, comment_prefix='')
    c.Append('@type {!ChromeEvent}')
    c.Append(self._js_util.GetSeeLink(self._namespace.name, 'event',
                                      event.name))
    c.Eblock(' */')
    c.Append('chrome.%s.%s;' % (self._namespace.name, event.name))
    c.Append()

  def _AppendNamespaceObject(self, c):
    """Appends the code creating namespace object.
       For example:

       /**
        * @const
        */
       chrome.bookmarks = {};
    """
    c.Append("""/**
 * @const
 */""")
    c.Append('chrome.%s = {};' % self._namespace.name)
    c.Append()

  def _GetFunctionParams(self, function):
    """Returns the function params string for function.
    """
    params = function.params[:]
    if function.callback:
      params.append(function.callback)
    return ', '.join(param.name for param in params)


from typing import Optional
from decimal import Decimal

from validator_collection import validators

from highcharts_core.metaclasses import HighchartsMeta

class LinkOptions(HighchartsMeta):
    """Link style options."""

    def __init__(self, **kwargs):
        self._color = None
        self._dash_style = None
        self._width = None

        self.color = kwargs.get('color', None)
        self.dash_style = kwargs.get('dash_style', None)
        self.width = kwargs.get('width', None)

    @property
    def color(self) -> Optional[str]:
        """Color of the link between two nodes. Defaults to ``rgba(100, 100, 100, 0.5)``.

        :rtype: :class:`str <python:str>` or :obj:`None <python:None>`
        """
        return self._color

    @color.setter
    def color(self, value):
        self._color = validators.string(value, allow_empty = True)

    @property
    def dash_style(self) -> Optional[str]:
        """A name for the dash style to use for links. Defaults to
        :obj:`None <python:None>`.

        :rtype: :class:`str <python:str>` or :obj:`None <python:None>`
        """
        return self._dash_style

    @dash_style.setter
    def dash_style(self, value):
        self._dash_style = validators.string(value, allow_empty = True)

    @property
    def width(self) -> Optional[int | float | Decimal]:
        """Width (px) of the link between two nodes. Defaults to ``1``.

        :rtype: numeric or :obj:`None <python:None>`
        """
        return self._width

    @width.setter
    def width(self, value):
        self._width = validators.numeric(value, allow_empty = True)

    @classmethod
    def _get_kwargs_from_dict(cls, as_dict):
        kwargs = {
            'color': as_dict.get('color', None),
            'dash_style': as_dict.get('dashStyle', None),
            'width': as_dict.get('width', None)
        }

        return kwargs

    def _to_untrimmed_dict(self, in_cls = None) -> dict:
        untrimmed = {
            'color': self.color,
            'dashStyle': self.dash_style,
            'width': self.width
        }

        return untrimmed


import numpy as np
from pymer4.models import Lm, Lmer
from pymer4.simulate import simulate_lm, simulate_lmm

def test_simulate_lm():

    # Simulate some data
    num_obs = 500
    num_coef = 3
    coef_vals = [10, 2.2, -4.1, 3]
    mus = [10.0, 3.0, 2.0]
    corrs = 0.1
    data, b = simulate_lm(num_obs, num_coef, coef_vals, mus=mus, corrs=corrs, seed=4)

    # Check predictors are correlated
    # True - Generated < .1
    corr = data.iloc[:, 1:].corr().values
    corr = corr[np.triu_indices(corr.shape[0], k=1)]
    assert (np.abs(corrs - corrs) < 0.1).all()

    # Check column means are correct
    # True - Generated < .1
    means = data.iloc[:, 1:].mean(axis=0)
    assert np.allclose(means, mus, atol=0.1)

    # Check coefficients are as specified
    assert np.allclose(b, coef_vals)

    # Model simulated data
    m = Lm("DV ~ IV1+IV2+IV3", data=data)
    m.fit(summarize=False)

    # Check parameter recovery
    # True - Recovered < .15 for params and < 1 for intercept
    assert (np.abs(m.coefs.iloc[1:, 0] - coef_vals[1:]) < 0.15).all()
    assert (np.abs(m.coefs.iloc[0, 0] - coef_vals[0]) < 1).all()

def test_simulate_lmm():

    # Simulate some data
    num_obs = 50
    num_coef = 3
    num_grps = 100
    mus = [10.0, 30.0, 2.0]
    coef_vals = [4.0, 1.8, -2, 10]
    corrs = 0.15
    data, blups, b = simulate_lmm(
        num_obs,
        num_coef,
        num_grps,
        coef_vals=coef_vals,
        mus=mus,
        corrs=corrs,
        noise_params=(0, 0.25),
        seed=4,
    )

    # Check data shape (add 2 for DV and group columns)
    assert data.shape == (num_obs * num_grps, num_coef + 2)

    # Check group shapes
    group_data = data.groupby("Group")
    assert group_data.ngroups == num_grps
    assert (group_data.apply(lambda grp: grp.shape == (num_obs, num_coef + 2))).all()

    # Check coefficients are as specified
    assert np.allclose(b, coef_vals)

    # Check blups are close to population values
    # True - Generated < .25
    np.allclose(coef_vals, blups.mean(axis=0), atol=0.25)

    # Check column means within groups, i.e. random intercepts
    # True - Generated < 1.1
    assert (
        group_data.apply(
            lambda grp: np.allclose(grp.iloc[:, 1:-1].mean(axis=0), mus, atol=1.1)
        )
    ).all()

    # Check correlations within group
    # True - Generated < .5
    def grp_corr(grp):
        corr = grp.iloc[:, 1:-1].corr().values
        corr = corr[np.triu_indices(corr.shape[0], k=1)]
        return corr

    assert (
        group_data.apply(lambda grp: (np.abs(grp_corr(grp) - corrs) < 0.5).all())
    ).all()

    # Model simulated data
    m = Lmer("DV ~ IV1+IV2+IV3 + (IV1+IV2+IV3|Group)", data=data)
    m.fit(summarize=False)

    # Check random effects variance
    # True - Generated < .25
    assert np.allclose(m.ranef_var.iloc[1:-1, -1], corrs, atol=0.25)

    # Check parameter recovery
    # True - Recovered < .15 for params and < 1 for intercept
    assert (np.abs(m.coefs.iloc[1:, 0] - b[1:]) < 0.15).all()
    assert (np.abs(m.coefs.iloc[0, 0] - b[0]) < 1).all()

    # Check BLUP recovery
    # mean(True - Generated) < .5 (sigma)
    assert np.abs((m.fixef.values - blups.values).ravel()).mean() < 0.5


# -*- coding: utf-8 -*-
import azureml.core
from azureml.core import Experiment, Workspace

def main():
    print('Testing Azure ML with a standalone Python script')

    # Load the workspace from the saved config file
    ws = Workspace.from_config()
    print('Ready to use Azure ML {} to work with {}'.format(azureml.core.VERSION, ws.name))

    # Display compute resources in workspace
    print("Compute resources in the workspace:")
    for compute_name in ws.compute_targets:
        compute = ws.compute_targets[compute_name]
        print("\t", compute.name, ':', compute.type)

    # Create an Azure ML experiment in the workspace
    experiment = Experiment(workspace=ws,
                            name="Test-Experiment-Standalone-Scripts")

    # Start logging data from the experiment, obtaining
    # a reference to the experiment run
    run = experiment.start_logging()
    print("Starting experiment:", experiment.name)

    # Just test logging 1
    run.log('TEST', 1)
    print('Testing logging 1 in the experiment run')

    # Complete the run
    run.complete()
    print('Completed running the expriment')

if __name__ == '__main__':
    main()


import sys
import re
import numpy as np

#####
#Read data
#####

text_file = open("input.txt", "r")
lines = text_file.readlines()

#####
# get my ticket
#####

myticket=[]
seen=False
for i in range(len(lines)):
	if lines[i].strip("\n")=="your ticket:": #stop when this is observed
		seen=True
	else:
		if lines[i].strip("\n") != "" and seen==True:
			myticket = list(map(int,lines[i].strip("\n").split(",")))
	if len(myticket)>0:
		break
print("My ticket: ", myticket)

#####
#get valid numbers
#####

combinedRegex = re.compile("[0-9]+-[0-9]+")#regular expression for range of numbers
myranges0=[]
rowids=[]
for i in range(len(lines)):
	if lines[i].strip("\n")=="your ticket:": #stop when this is observed
		break
	else:
		if lines[i].strip("\n") != "":
			myranges0.append(combinedRegex.findall(lines[i].strip("\n"))) #get the ranges
			rowids.append(lines[i].strip("\n").split(": ")[0]) #get the rownames

###
#combined all valid numbers into a single list
###

validnums = []
for therange in myranges0:
	l1start=int(therange[0].split("-")[0])
	l1end=int(therange[0].split("-")[1])+1
	l2start=int(therange[1].split("-")[0])
	l2end=int(therange[1].split("-")[1])+1
	validnums.append(list(range(l1start,l1end))+list(range(l2start,l2end)))
myranges=validnums #save this for later
validnums=list(set([inner for outer in validnums for inner in outer])) #get unique values
validnums.sort()

###
#get nearby tickets
###

seen=False
nearbytix=[]
for i in range(len(lines)):
	if lines[i].strip("\n")=="nearby tickets:": #only start appending after you see this
		seen=True
	elif seen==True:
		nearbytix.append(lines[i].strip("\n").split(","))

nearbytix=[list(map(int, x)) for x in nearbytix]

###
# Find invalid numbers and remove those tickets
###

notthere=[]#find rows with invalid numbers
for i in range(len(nearbytix)): #iterate rows in nearbytix (distinct tickets)
	therow=nearbytix[i]
	for j in therow: #iterate over values in that row
		if j not in validnums: #compare each value to the valid numbers
			notthere.append(i)#find rows with invalid numbers
#print("rows with invalid numbers: ",notthere)

for index in sorted(notthere, reverse=True):
    del nearbytix[index]

########
# Get a matrix of 0s and 1s
# checking if all the numbers in a given column of nearby tickets are in ranges specified
# output matrix will be square
########

nearbytix=np.array(nearbytix)

outlist=[]
for i in range(len(nearbytix[0,:])):#iterate over columns
	rowlist=[]
	for j in myranges:#iterate over the ranges for each type
		if(len(set(nearbytix[:,i]).intersection(j))==len(set(nearbytix[:,i]))):
			rowlist.append(1)
		else:
			rowlist.append(0)
	outlist.append(rowlist)

print(rowids)
mymat=np.array(outlist).T######ugggggh it took me forever to figure out I needed to transpose here

######
# RREF the matrix by hand because I couldn't find an RREF function that keeps track of column names
######

cnt=0
seen = []
mydict=dict()
while cnt<=mymat.shape[1]:
	for col in range(mymat.shape[1]):#iterate over columns
		if(list(mymat[:,col]).count(1)==1 and list(mymat[:,col]).count(0)==mymat.shape[1]-1) and col not in seen:#if you find a reduced column you haven't seen before
			seen.append(col)
			theindex=list(mymat[:,col]).index(1)
			#print("column:",col,"is",rowids[theindex])
			mydict[rowids[theindex]]=col
			for col2 in range(mymat.shape[1]):
				if(list(mymat[:,col2]).count(1)==1 and list(mymat[:,col2]).count(0)==mymat.shape[1]-1):#if you find a reduced row skip it
					continue
				else:
					mymat[:,col2]-=mymat[:,col] #subtract out column
	cnt+=1

print(mydict)
print(myticket[mydict['departure station']]*myticket[mydict['departure track']]*myticket[mydict['departure location']]*myticket[mydict['departure date']]*myticket[mydict['departure platform']]*myticket[mydict['departure time']])


from typing import List
from fastapi import APIRouter, HTTPException

from ..models.user import User
from ..models.review import UserReview, Movie
from ..schemas.review import (
    MovieResponseModel, MovieRequestModel, ReviewRequestModel, ReviewRequestPutModel, ReviewResponseModel
)

router = APIRouter(prefix='/reviews')

@router.post('/movies/create', response_model=MovieResponseModel)
async def create_movie(movie: MovieRequestModel):
    return Movie.create(
        title=movie.title
    )

@router.post('/create', response_model=ReviewResponseModel)
async def create_review(user_review: ReviewRequestModel):
    if User.select().where(User.id == user_review.user).first() is None:
        raise HTTPException(
            status_code=404,
            detail='User not found'
        )

    if Movie.select().where(Movie.id == user_review.movie).first() is None:
        raise HTTPException(
            status_code=404,
            detail='Movie not found'
        )

    return UserReview.create(
        user=user_review.user,
        movie=user_review.movie,
        review=user_review.review,
        score=user_review.score
    )

@router.get('/list', response_model=List[ReviewResponseModel])
async def get_reviews(page: int = 1, limit: int = 10):
    reviews = UserReview.select().paginate(page, limit)
    return [review for review in reviews]

@router.get('/{review_id}', response_model=ReviewResponseModel)
async def get_review(review_id: int):
    user_review = UserReview.select().where(
        UserReview.id == review_id
    ).first()

    if user_review is None:
        raise HTTPException(
            status_code=404,
            detail='Review not found'
        )
    return user_review

@router.put('/{review_id}/edit', response_model=ReviewResponseModel)
async def edit_review(review_id: int, review_request: ReviewRequestPutModel):
    user_review = UserReview.select().where(
        UserReview.id == review_id
    ).first()

    if user_review is None:
        raise HTTPException(
            status_code=404,
            detail='Review not found'
        )

    user_review.review = review_request.review
    user_review.score = review_request.score
    user_review.save()

    return user_review

@router.delete('/{review_id}/delete')
async def delete_review(review_id: int):
    user_review = UserReview.select().where(
        UserReview.id == review_id
    ).first()

    if user_review is None:
        raise HTTPException(
            status_code=404,
            detail='Review not found'
        )
    user_review.delete_instance()
    return user_review


from re import compile

short_name = "WatchSeries"
full_name = "WatchSeries.to"

class host_scraper(object):

	def __init__(self, possible_hostsites):
		possible_hostsites.append([full_name,short_name])

	def program_search_vars(self):
		self.search_url = "http://thewatchseries.to/search/"
		self.search_name = "div"
		self.search_attrs = {"valign": "top","style": "padding-left: 10px;"}
		self.server_url = "http://thewatchseries.to"

	def tv_or_movie(self,program_url):
		return "tv"

	def episode_search_vars(self):
		self.search_name = "li"
		self.search_attrs = {"itemprop": "episode", "itemscope": "", "itemtype": "http://schema.org/TVEpisode"}
		#self.server_url = "http://thewatchseries.to"
		self.commands = [
			"episode_number = int( episode.find('meta', {'itemprop':'episodenumber'}).get('content') )",
			"episode_url = '"+self.server_url+"' + episode.find('a').get('href')",
			"episode_season = int( re.search(r'_s(.\d?)_e', episode_url).group(1) )",
		]

	def source_search_vars(self):
		self.search_name = "tr"
		self.search_attrs = {"class": compile('download_link_.*'), "id": compile('link_.*')}
		self.link_name = "a"
		self.link_attrs = {"target":"_blank","class":"buttonlink","style":"cursor:pointer;"}
		#self.server_url = "http://thewatchseries.to"

	def final_step(self,url):
		return [
			"url = scrape_site('"+url+"', javascript='yes').find('a',{'class': 'push_button blue'}).get('href')"
		]


# https://www.acmicpc.net/problem/1018
# Solved Date: 20.04.30.

import sys
read = sys.stdin.readline

def check_board(board, y, x):
    black_start = 0
    # y가 짝수이면 black과 다를 때 / 홀수이면 black과 같을 때 증가
    black = "BWBWBWBW"
    for dy in range(8):
        if dy % 2 == 0:
            for dx in range(8):
                new_y, new_x = y + dy, x + dx
                if board[new_y][new_x] != black[dx]:
                    black_start += 1
        else:
            for dx in range(8):
                new_y, new_x = y + dy, x + dx
                if board[new_y][new_x] == black[dx]:
                    black_start += 1
    return min(black_start, 64 - black_start)

def brute_force(board):
    # 완전히 하나의 색에서 하나라도 다른 색이 칠해지면 가지수 1이 감소한다.
    min_count = 32
    for y in range(len(board) - 7):
        for x in range(len(board[0]) - 7):
            min_count = min(min_count, check_board(board, y, x))
    return min_count

def main():
    row, column = (int(x) for x in read().split())
    board = []
    for _ in range(row):
        board.append(read().strip())
    print(brute_force(board))

if __name__ == '__main__':
    main()


import json
from starter.objects import Starter, default_workflow_params
from starter.starter_helper import NullRequiredDataException

"""
Amazon SWF PostPerfectPublication starter, for API and Lens publishing etc.
"""

class starter_PostPerfectPublication(Starter):
    def __init__(self, settings=None, logger=None):
        super(starter_PostPerfectPublication, self).__init__(
            settings, logger, "PostPerfectPublication"
        )

    def get_workflow_params(self, info):
        workflow_params = default_workflow_params(self.settings)

        if info.get("article_id") is None:
            raise NullRequiredDataException(
                "article id is Null. Possible error: "
                "Lax did not send back valid data from ingest."
            )

        publication_from = "lax" if "requested_action" in info else "website"

        workflow_params["workflow_id"] = "%s_%s.%s.%s" % (
            self.name,
            info.get("article_id"),
            info.get("version"),
            publication_from,
        )
        workflow_params["workflow_name"] = self.name
        workflow_params["workflow_version"] = "1"
        workflow_params["execution_start_to_close_timeout"] = str(60 * 10)

        workflow_params["input"] = json.dumps(info, default=lambda ob: None)

        return workflow_params

    def start(self, info, settings):
        """method for backwards compatibility"""
        self.settings = settings
        self.instantiate_logger()
        self.start_workflow(info)

    def start_workflow(self, info):

        workflow_params = self.get_workflow_params(info)

        self.start_workflow_execution(workflow_params)


from odoo import fields, models, api
from odoo.addons import decimal_precision as dp

class MrpBom(models.Model):
    _inherit = 'mrp.bom'

    cost_price = fields.Float(
        compute='_compute_cost_price',
        digits=dp.get_precision('Purchase Price'),
    )

    @api.multi
    @api.depends('bom_line_ids.cost_price')
    def _compute_cost_price(self):
        for bom in self:
            prices = bom.bom_line_ids.mapped('cost_price')
            bom.cost_price = sum(prices)


from django.db import models
#import datetime

# Create your models here.

BLACKLISTED_SHORTCUT_NAMES = ("admin","api")

class shortcut(models.Model):
    shortcut_key = models.CharField(max_length=20,help_text="Key of the shortcut")
    shortcut_value = models.URLField(help_text="The target of the shortcut") # URL of the shortcut target
    shortcut_accesses = models.PositiveIntegerField(default=0) # Times the shortcut being accessed
    def __str__(self):
        return "{} -> {}, used {} time(s)".format(self.shortcut_key,self.shortcut_value,self.shortcut_accesses)
    def save(self, *args, **kwargs):
        if self.shortcut_key in BLACKLISTED_SHORTCUT_NAMES:
            return
        else:
            super().save(*args, **kwargs)
    shortcut_key.short_description = "Key"
    shortcut_value.short_description = "Target"
    shortcut_accesses.short_description = "Access Count"

class log(models.Model):
    log_ip = models.TextField() # IP
    log_ua = models.TextField() # User Agent
    log_shortcut = models.TextField() # Requested shortcut
    log_time = models.DateTimeField(auto_now_add = True) # request time
    def __str__(self):
        return "{}: {} (UA {}) <- {}".format(str(self.log_time),self.log_ip,self.log_ua,self.log_shortcut)
    log_time.short_description = "Access Time"
    log_ip.short_description = "IP Address"
    log_ua.short_description = "User Agent"
    log_shortcut.short_description = "Shortcut"


import requests
from bs4 import BeautifulSoup
import json
link=requests.get("https://www.rottentomatoes.com/top/bestofrt/top_100_animation_movies/")
data=BeautifulSoup(link.text,"html.parser")
def movieData():
    list=[]
    x=0
    mainDiv=data.find("div",class_="body_main container")
    subDiv=mainDiv.find("table",class_="table")
    tr=subDiv.find_all("tr")
    for i in tr :
        dict={}
        td=i.find_all("td")
        for j in td:
            title=i.find("a",class_="unstyled articleLink")["href"][3:]
            dict["tital"]=title
            rating=i.find("span",class_="tMeterScore").get_text()[:-1]
            dict["rating"]=float(rating)
            review=i.find("td",class_="right hidden-xs").get_text()
            year=i.find("a",class_="unstyled articleLink").get_text()[-5:-1]
            dict["year"]=int(year)
            rank=i.find("td",class_="bold").get_text()[:-1]
            dict["rank"]=int(rank)
            url="https://www.rottentomatoes.com/m/"+title
            dict["url"]=url
            if dict not in list:
                x+=1
                list.append(dict)
                dict["position"]=x
            with open ("task1.json","w+") as f:
                file=json.dump(list,f,indent=4)
    return list
movieData()


## 3행 4열 2차원 배열 만드는 방법!!
if 0:
    a = [ [0] * 4 for x in range(3) ]
    print(a)

    print('========================================')

## 문제 A4: [TST]지능형 기차
if 0:
##    a = [0] * 4
    people = [0] * 5
    for i in range(4):
##        a[i] = list(map(int ,input().split()))
        a = list(map(int ,input().split()))
        people[i+1] = (a[1] - a[0]) + people[i]
##        print(a)
    print(max(people))

if 0:
    people = []
    for i in range(4):
        a = list(map(int ,input().split()))
        people.append(a[1] - a[0])
    for i in range(1, 4):
        people[i] += people[i-1]
    print(max(people))

    print('========================================')

## 문제 B0: [TST]가장 많은 알파벳은?
if 0:
    getInput = input()
    cnt = []
    for i in range(26): cnt.append(getInput.count(chr(ord('a')+i)))
##    print(cnt)
    print(chr(cnt.index(max(cnt))+ord('a')))

if 0:
    getLower = [ i for i in input() if i > 'Z']
    print(min(i for i in getLower if getLower.count(i) >= max([getLower.count(i) for i in getLower])))

    print('========================================')

## 문제 A9: [LAB]행과 열의 큰 값 찾기
if 0:
    n = int(input())
    row = []
    col = [0] * n
    for i in range(n):
        a = list(map(int, input().split()))
        row.append(sum(a))
        for j in range(n):
##            print(j)
##            print(a[j])
            col[j] += a[j]

##    print(row)
##    print(col)
    print( row.index(max(row))+1, col.index(max(col))+1 )

##    for i in range(n):
##        for j in range(n):
##            arr[i][j] = int(input())
##    print(arr)

    print('========================================')

## 문제 A8: [LAB]숫자맞추기
if 0:
    x, y = input().split()
    a = b = 0

    for i in range(4):
        if x[i] == y[i] : a = a + 1
        for j in range(4):
             if x[i] == y[j] and i != j: b = b + 1

    print(f'{a}A{b}B')

    print('========================================')

## 문제 A7: [Bash] 숫자 범위 맞추기
if 0:
    result = ( 0 <= int(input()) <= 100) and "OK" or "X"
    print(result)

print('========================================')

## 문제 A6: [MLAB] 점수로 학점구하기 - if~else 활용
if 0:
    chg = "FFFFFFDCBAA"
    score = int(input())
    result = (0 <= score <= 100) and chg[score//10] or 'Error'
    print(result)

    print('========================================')

## 아래의 두 코드는 같은 기능을 함!!
if 0:
    r, c = map(int, input().split())
    a = [ [0] * c for i in range(r) ]
    a[0][2] = 1
    print(a)

if 0:
    r, c = map(int, input().split())
    a = []

    for i in range(r):
        b = [0] * c
        a.append(b)

    a[0][2] = 1
    print(a)

    print('위에서 re...')
    print('========================================')

## r, c를 입력 받아, r행 c열 2차원 배열 안에 다 0으로 채우기!
if 0:
    r, c = map(int, input().split())

    a = [ [0]  * c ] * r
##    print(a)

    a[0][0] = 30
    print(a)

    print('========================================')

if 0:
    a = [1, 2, 3]
    b = [4, 5, 6]
    c = a + b   ## [ [1, 2, 3], [4, 5, 6] ]이 아니라 [1, 2, 3, 4, 5, 6]이 됨!!!
    print(c)
    print('------------------')

    a = [[1, 2]]
    b = [[3, 4, 5]]
    c = a + b   ## [1, 2, 3, 4, 5,]이 아니라 [ [1, 2], [3, 4, 5] ]이 됨!!
    print(c)
    print('------------------')

    a = [10, 20]
    a *= 5
    print(a)
    a[3] = 50
    print(a) ## 1, 3, 5, 7, 9, ... 자리에 있는 공간은 다 달라! 그래서 4번째 요소만 바뀜!!
    print('------------------')

    a = [ [1, 2, 3] ]
    b = a * 3
    print(b)
    b[0][0] = 50
    b[1] = 100
    print(b)            ## 하아아아아아아 헷갈령
    print('------------------')

    print('========================================')

if 0:
    a = [1, 2, 3, 4, 5, 6, 7, 8]
    print(a)

    b = ' '.join(map(str, a))
    print(b)

    c = str(a[1:-1]).replace(', ', '' )
    print(c)

    print('========================================')

## 문제 A5: [실무C 3-4] 비교 연산자의 사용, 2,3,5의 배수 판단하기

if 0:

    def compare(num):
        if not (num % 2) : return 2
        if not (num % 3): return 3
        if not (num % 5): return 5
        return 0

    print('3 =>', compare(3))
    print('62 =>', compare(62))
    print('25 =>', compare(25))
    print('157 =>', compare(157))

if 0:

    def compare(num):
        return 2 if not (num % 2) else 3 if not (num % 3) else 5 if not (num % 5) else 0

    print('3 =>', compare(3))
    print('62 =>', compare(62))
    print('25 =>', compare(25))
    print('157 =>', compare(157))

if 0:

    def compare(num):
        return not (num%2) and 2 or not (num%3) and 3 or not (num%5) and 5 or 0

    print('3 =>', compare(3))
    print('62 =>', compare(62))
    print('25 =>', compare(25))
    print('157 =>', compare(157))

    print('========================================')

if 0:
    import dis

    def func1(a):
        if a == 0:
            print("a == 0")

    def func2(a):
        if not a:
            print("a == 0")

    dis.dis(func1)
    dis.dis(func1)

    print('========================================')

if 0:
    a = 1
    b = 2
    c = 3
    d = 4
    e = 5
    if a<b<c<d<e:
        print(True)

    print('========================================')

if 0:
    ## Python 수행 흐름의 분기점!?!?!? - 이것으로 scope 구분됨!! (블럭 { } 이 없잖아!)

    a = 10
    if a < 20 :
        b = 1
    else :
        b = 2
    ## a는 전역변수이다 당연히. 그럼 b는??? => b 또한 전역변수이다!!!!

    for x in range(10):
        print(x)
    ## 그렇다면 x는? => x 또한 전역변수이다!!

    print(globals()) ## => 확인해보면 b와 x 모두 전역 namespace에 들어가있다는 것을 알 수 있음!!

    def func(a, b):
        ret = a + b
        print('나는 locals() : ')
        print(locals())
        return ret
    ## a, b, ret 모두 지역변수!

    func(1, 2)
    print('나는 globals() : ')
    print(globals())

    print('--------------------')

    globals()['yongnam'] = 'good'
    print(globals())
    del globals()['yongnam']
    print(globals())
    ## 추가적으로 추가, 삭제도 가능하넹!

    print('========================================')

if 0:

    print(chr(97))
    print(ord('a'))

    print('========================================')

if 0:

    ucmd = input()
    eval(ucmd)

    ## 1. dir()
    ## 2. 10
    ## 3. a = 10
    ## 4. 10+20
    ## 이 중에서 입력으로 불가능한 것은?
    ## ans : 3번!!
    ##         ㄴ  Why?: a = 10. 즉, 대입"문"이므로!!
    ##                          eval에는 expression(식)만 가능하고, statement(문)을 받을 수는 없다!
    ##                          ( dir()은 "식 (expression)"임!! )

    print('========================================')

if 0:
    import sys

    ## range와 list의 차이점!

    a = range(1, 99)
    print(a, sys.getsizeof(a))

    print(len(a))
    print(a[2])
    print(a[2:5])

    b = range(6, 66, 6)
    print(b, sys.getsizeof(b))
    ## a와 b는 다른데 크기가 똑같다!!! 오오

    aa = list(range(1, 99))
    print(aa, sys.getsizeof(aa))

    print(len(aa))
    print(aa[2])
    print(aa[2:5])  ## 여기에서 차이가 남!!

    bb = list(range(6, 66, 6))
    print(bb, sys.getsizeof(bb))
    ## a와 b는 list 컨테이너가 아닌 range이지만,
    ## 이렇게 list처럼 만들어 준다면 결과는 달라진다!!|\

    print('========================================')

if 0:
    ## 10번 반복!
    for i in range(10):
        print(i)
        if i == 4 : break

    for i in [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]:
        print(i)
        if i == 4 : break
    ## 이 둘의 차이점은?? : 메모리!! (interning이 안 되었다면 ㅎ)
    ## 하지만 range의 경우에는 for문을 추가적으로 더 도는 것이기 때문에 좀 더 오래 걸린다고 함!


from django import template
from selia_templates.custom_tags.components.base import ComplexNode

def tab(parser, token):
    content = parser.parse(('endtab',))
    parser.delete_first_token()

    try:
        _, url = token.split_contents()
    except ValueError:
        raise template.TemplateSyntaxError(
            "%r tag requires a single argument" % token.contents.split()[0]
        )

    return ComplexNode(
        template_name='selia_templates/navbars/tab.html',
        content=content,
        url=url)