"""empty message

Revision ID: 0009_created_by_for_jobs
Revises: 0008_archive_template
Create Date: 2016-04-26 14:54:56.852642

"""

# revision identifiers, used by Alembic.
revision = "0009_created_by_for_jobs"
down_revision = "0008_archive_template"

import sqlalchemy as sa
from alembic import op
from sqlalchemy.dialects import postgresql

def upgrade():
    ### commands auto generated by Alembic - please adjust! ###
    op.add_column("jobs", sa.Column("created_by_id", postgresql.UUID(as_uuid=True), nullable=True))
    op.create_index(op.f("ix_jobs_created_by_id"), "jobs", ["created_by_id"], unique=False)
    op.create_foreign_key(None, "jobs", "users", ["created_by_id"], ["id"])
    op.get_bind()
    op.execute(
        "UPDATE jobs SET created_by_id = \
                (SELECT user_id FROM user_to_service WHERE jobs.service_id = user_to_service.service_id LIMIT 1)"
    )
    op.alter_column("jobs", "created_by_id", nullable=False)
    ### end Alembic commands ###

def downgrade():
    ### commands auto generated by Alembic - please adjust! ###
    op.drop_constraint(None, "jobs", type_="foreignkey")
    op.drop_index(op.f("ix_jobs_created_by_id"), table_name="jobs")
    op.drop_column("jobs", "created_by_id")
    ### end Alembic commands ###


from utilities.readConfig import *

def test_P4_039_inferenceInput_folderStructure(s3_session):
    s3 = s3_session
    client = s3.client('s3')

    paginator = client.get_paginator('list_objects')
    for page in paginator.paginate(Bucket = get_qa_inferenceInputBucket()):
        for obj in page.get('Contents', []):
            object_key = obj['Key']
            if get_testClientId_1() in object_key:
                keyString = object_key.split("/")
                assert keyString[0] == get_testClientId_1()
                assert keyString[1] == get_testLocationId_1()
                assert int(keyString[2]) >= 2022
                assert 1 <= int(keyString[3]) <= 12
                assert 1<= int(keyString[4]) <= 31
                print(object_key)


from odoo import models, fields
import logging

_logger = logging.getLogger(__name__)

class ProductPriceRouteDelivery(models.Model):
    _name = 'product.price.route.delivery'
    _description = 'Product Price Route Delivery'

    sales = fields.Integer(
        string='Ventes'
    )

    create_date_from = fields.Integer(
        string='Create Date'
    )

    create_date_to = fields.Integer(
        string='Create Date'
    )

    multiplier = fields.Char(
        string='Multiplicateur'
    )

    ceiling_id = fields.Many2one(
        string='Product',
        comodel_name='product.ceiling.price'
    )


import sympy
import numpy as np
from numpy.linalg import lstsq
from scipy.optimize import curve_fit

# *****************************************************************************

def linearfitting(X, V, BasisFuncExpr, Var, NonLinearValues=None, Weights=None):
    """ Computes the least-square optimal linear combinations
      of the functions BasisFuncExpr (defined with sympy symbolic expr)
      of the variable Var (also defined with its symbol),
      fitting the points ( X(i), V(i) ) defined in the lists X and V.
      The dictionary NonLinearValues defines the values of the eventual
      non linear parameters as { symbol:value } where symbol is the
      symbolic expression of the parameters and value its fixed value """

    if Weights is None:
        Weights = []
    if NonLinearValues is None:
        NonLinearValues = {}

    # Set the vector of the weights
    if len(Weights) < len(X):
        Weights = [1.0] * len(X)
    else:
        Weights = np.array(Weights) * len(X) / sum(np.array(Weights))

    # Set the numpy functions of the basis set functions
    BasisFunc = []
    for Basis in BasisFuncExpr:

        # substitute the values of the non linear parameters
        LinExpr = Basis
        for NonLinPar in NonLinearValues.keys():
            LinExpr = LinExpr.subs(NonLinPar, NonLinearValues[NonLinPar])
        # Transform the expression in a numpy function
        BasisFunc.append(sympy.lambdify(Var, LinExpr, "numpy"))

    # Define the matrix of the coefficients
    A = []
    for f in BasisFunc:
        if isinstance(Var, list) or isinstance(Var, tuple):
            A.append([w * f(*singleX) for singleX, w in zip(X, Weights)])
        else:
            A.append([f(singleX) for singleX, w in zip(X, Weights)])
    A = np.array(A).transpose()

    # Define the vector of the V values
    B = np.array([v * w for v, w in zip(V, Weights)])

    # Solve the AX = B system with least-squares and return the solution
    Coefficients, ChiSquared, Rank, Singular = lstsq(A, B, rcond=None)

    return Coefficients, ChiSquared[0]

# *****************************************************************************

def nonlinearfitting(X, V, FittingFunction, Var, P0, ConstrainedParameters=None, Weights=None):
    """ Computes the least-square optimal linear combinations
      of the functions BasisFuncExpr (defined with sympy symbolic expr)
      of the variable Var (also defined with its symbol),
      fitting the points ( X(i), V(i) ) defined in the lists X and V.
      The dictionary NonLinearValues defines the values of the eventual
      non linear parameters as { symbol:value } where symbol is the
      symbolic expression of the parameters and value its fixed value """

    if Weights is None:
        Weights = []
    if ConstrainedParameters is None:
        ConstrainedParameters = {}

    # Set the vector of the weights
    if len(Weights) < len(X):
        Weights = [1.0] * len(X)
    else:
        Weights = np.array([1.0 / w ** 2 for w in Weights]) / len(X) * sum(np.array(Weights) ** 2)

    # Substitute linear parameters
    for Param in ConstrainedParameters.keys():
        FittingFunction = FittingFunction.subs(Param, ConstrainedParameters[Param])

    # Transform the expression in a numpy function
    Func = sympy.lambdify(Var, FittingFunction, "numpy")

    # do the fitting with scipy curve_fit
    Coefficients, Covariance = curve_fit(Func, X, V, p0=P0, sigma=Weights)

    return Coefficients, np.sqrt(np.diag(Covariance))

# *****************************************************************************


from tkinter import Misc
from discord.ext import commands
import discord
import json
import random
import asyncio
class Miscellaneous(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @commands.command()
    async def faq(self,ctx):
      """Get FAQ for the bot ig?"""
      rndclr=random.choice([discord.Colour.red().value,discord.Colour.dark_grey().value])
      """FAQ for the bot"""
      e=discord.Embed(title="Frequently Asked Questions",colour=rndclr)
      e.add_field(name="Is AntiScam a paid service?",value="No. AntiScam is not and never wil be, a paid service.",inline=False)
      e.add_field(name="How does AntiScam work?",value='AntiScam generates a counter and increments it based on how much it "gets scared". ',inline=False)

      e.add_field(name="Will AntiScam randomly delete my messages?",value="Chances are next to none! The algorithm has been tested uncountable number of times and perfected upon, so a false positive is an extremely rare scenario. Nonetheless, if anything of the sort occurs, you will recieve a preview of your message for 10 seconds to review the message for potenitally harmful links that may have set off the trigger.",inline=False)
      e.set_footer(text="For more info, use a!botinfo")
      ed=await ctx.reply(embed=e,mention_author=False)
      await asyncio.sleep(10)
      e.set_footer(text="The questions were asked by no one, mind you")
      await ed.edit(embed=e)
    @commands.command()
    async def vote(self,ctx):
      """Vote the bot on Top.gg!"""
      e=discord.Embed()
      e.add_field(name="Vote for me!",value="Click [**Here**](https://top.gg/bot/886309422526259231/vote)!!")
      await ctx.reply(embed=e)
def setup(bot):
    bot.add_cog(Miscellaneous(bot))


import sys
sys.stdin = open('input.txt')

T = int(input())

for tc in range(1, T+1):
    n, m = map(int, input().split())  # 5, 2
    arr = [list(map(int, input().split())) for i in range(n)]  # [1, 3, 3, 6, 7]

    # n = 5, m = 2일 떄

    '''
    total += arr[0][0] + arr[0][1] + arr[1][0] + arr[1][1]
    total += arr[0][1] + arr[0][2] + arr[1][1] + arr[1][2]
    total += arr[0][2] + arr[0][3] + arr[1][2] + arr[1][3]
    total += arr[0][3] + arr[0][4] + arr[1][3] + arr[1][4]
                                ...
    total += arr[4][0] + arr[4][1] + arr[4][0] + arr[4][1]
    total += arr[4][1] + arr[4][2] + arr[4][1] + arr[4][2]
    '''
    max_sum = []  # 결과값 빈 리스트 생성

    for row in range(n - m + 1):  # 0 ~ 3
        for col in range(n - m + 1):  # 0 ~ 3
            sub_sum = 0
            for r in range(m):  # 0 ~ 1
                for c in range(m):  # 0 ~ 1
                    sub_sum += arr[row + r][col + c]
                    max_sum.append(sub_sum)

    print(max(max_sum))


#!/usr/bin/python3
""" clickup_to_joplin.py

Script to convert a Clickup CSV export file into a Joplin JEX file for import.

Adapted from tiddlywiki_to_joplin: https://github.com/FloatingBoater/tiddlywiki_to_joplin/

Args:
    No external args, only internal constant definitions

Parameters:
    InputFile    (str):  Constant string filename of the CSV export from Clickup.
    OutputDir    (str):  Constant string directory name created to hold exported MD files.
    Author       (str):  Creator name.
    DoNotConvert (list): List of statuses. Tasks with these statuses will not be converted.

Usage:
    Obtain a Clickup CSV export.
    Edit the filename parameters below.
    Run this script.
    Check the directory of individual *.md files, each containing one Clickup task.

    After checking the *.md files, create a tar file of the note files - which is what a JEX file consists of:
      $ cd clickup_notes
      $ tar cvf clickup_export.jex *.md
    You can them import the file 'joplin_conversion.jex' into Joplin.

    After import, inside Joplin, you will find all your Space folders inside a clickup_notes notebook. IF desired, you can drag the Space folders onto the "Notebooks" header to move them to the top level. If there's any tasks left in clickup_notes, they were probably open/etc children of a closed/etc parent task.

Notes/Caveats:
    This script was made for my own use and is not exaustive. Fields from the Clickup CSV export which aren't handled include attachments, priority, assignees, time related fields (sans creation date) and assignee comments.

    This script only handles CSV task export, and therefore does not support doc pages, attachments, exported views, dashboard cards, or alternative export formats.

    Clickup CSV export does not preserve task order, formatting of any sort, checkbox item status, list descriptions, task linking, reminders, or anything fancy like that.

    Since Joplin doesn't have subtasks/subnotes, tasks which have children will be converted to a folder. If the task had any content, that data will be put into its own note as a child to the new folder, with order 1 (meaning it will show at the top of the notebook when sorting by custom order).

Useful references:
    https://joplinapp.org/api/references/rest_api/
    https://help.clickup.com/hc/en-us/articles/6310551109527-Workspace-Task-Data-Export-CSV-
"""

import datetime
import csv
import uuid
import os
import re
import ast
from enum import Enum
from pathlib import Path

###
### change these values as needed
###
InputFile = 'clickupExport.csv'
OutputDir = 'clickup_notes'
Author = ''
DoNotConvert = ['closed', 'complete']

ConvertToFolder = set() # Tasks which have subtasks and therefore need to be converted into folders since Joplin doesn't support subtasks

class Type(Enum):
    TYPE_NOTE = 1
    TYPE_FOLDER = 2
    TYPE_SETTING = 3
    TYPE_RESOURCE = 4
    TYPE_TAG = 5
    TYPE_NOTE_TAG = 6
    TYPE_SEARCH = 7
    TYPE_ALARM = 8
    TYPE_MASTER_KEY = 9
    TYPE_ITEM_CHANGE = 10
    TYPE_NOTE_RESOURCE = 11
    TYPE_RESOURCE_LOCAL_STATE = 12
    TYPE_REVISION = 13
    TYPE_MIGRATION = 14
    TYPE_SMART_FILTER = 15

def format_content( text ):
    return text.replace('\\n', '<br />')

def format_checklist( text ):
    if get_valid_string(False, text):
        text = text.split(':', 1)
        header = text[0][2:-1]
        items = ast.literal_eval(text[1][0:-1])
        text = "### " + header + "\n"
        for item in items:
            text += "- [ ] " + item + "\n"
    return text

def write_note_to_file(note_id, parent_id, name, created_time, updated_time, user_created_time, user_updated_time, type, order=0, content=None, checklists=None):
    ClickupFile = open(OutputDir + '/' + note_id + '.md', 'x')
    ClickupFile.write(name + '\n')
    ClickupFile.write('\n')
    if get_valid_string(False, content):
        ClickupFile.write(content + '\n')
        ClickupFile.write('\n')
    if get_valid_string(False, checklists):
        ClickupFile.write(checklists + '\n')
        ClickupFile.write('\n')
    ClickupFile.write('id: ' + note_id + '\n')
    ClickupFile.write('parent_id: ' + parent_id + '\n')
    ClickupFile.write('created_time: ' + created_time + '\n')
    ClickupFile.write('updated_time: ' + updated_time + '\n')
    ClickupFile.write('is_conflict: 0' + '\n')
    ClickupFile.write('latitude: 55.088' + '\n')
    ClickupFile.write('longitude: -1.5863' + '\n')
    ClickupFile.write('altitude: 0.0000' + '\n')
    ClickupFile.write('author: ' + Author + '\n')
    ClickupFile.write('is_todo: 0' + '\n')
    ClickupFile.write('todo_due: 0' + '\n')
    ClickupFile.write('todo_completed: 0' + '\n')
    ClickupFile.write('source: com.clickup' + '\n')
    ClickupFile.write('source_application: clickup_to_joplin' + '\n')
    ClickupFile.write('application_data: ' + '\n')
    ClickupFile.write('order: ' + str(order) + '\n')
    ClickupFile.write('user_created_time: ' + user_created_time + '\n')
    ClickupFile.write('user_updated_time: ' + user_updated_time + '\n')
    ClickupFile.write('encryption_cipher_text: ' + '\n')
    ClickupFile.write('encryption_applied: 0' + '\n')
    # no '\n' on the last line - it causes Joplin import errors
    ClickupFile.write('type_: ' + str(type))
    ClickupFile.close()

def write_tag_to_file(tag_id, name, created_time, updated_time, user_created_time, user_updated_time):
    path = Path(OutputDir + '/' + tag_id + '.md')
    if not path.is_file():
        ClickupFile = open(path, 'x')
        ClickupFile.write(name + '\n')
        ClickupFile.write('\n')
        ClickupFile.write('id: ' + tag_id + '\n')
        ClickupFile.write('created_time: ' + created_time + '\n')
        ClickupFile.write('updated_time: ' + updated_time + '\n')
        ClickupFile.write('user_created_time: ' + user_created_time + '\n')
        ClickupFile.write('user_updated_time: ' + user_updated_time + '\n')
        ClickupFile.write('encryption_cipher_text: ' + '\n')
        ClickupFile.write('encryption_applied: 0' + '\n')
        ClickupFile.write('is_shared: 0' + '\n')
        # no '\n' on the last line - it causes Joplin import errors
        ClickupFile.write('type_: ' + str(Type.TYPE_TAG.value))
        ClickupFile.close()

def write_tag_association_to_file(id, note_id, tag_id, created_time, updated_time, user_created_time, user_updated_time):
    path = Path(OutputDir + '/' + id + '.md')
    if not path.is_file():
        ClickupFile = open(path, 'x')
        ClickupFile.write('id: ' + id + '\n')
        ClickupFile.write('note_id: ' + note_id + '\n')
        ClickupFile.write('tag_id: ' + tag_id + '\n')
        ClickupFile.write('created_time: ' + created_time + '\n')
        ClickupFile.write('updated_time: ' + updated_time + '\n')
        ClickupFile.write('user_created_time: ' + user_created_time + '\n')
        ClickupFile.write('user_updated_time: ' + user_updated_time + '\n')
        ClickupFile.write('encryption_cipher_text: ' + '\n')
        ClickupFile.write('encryption_applied: 0' + '\n')
        ClickupFile.write('is_shared: 0' + '\n')
        # no '\n' on the last line - it causes Joplin import errors
        ClickupFile.write('type_: ' + str(Type.TYPE_NOTE_TAG.value))
        ClickupFile.close()

# Convert a name to an id by removing non-alphanumerical characters
def as_id(string):
    return ''.join(s for s in string if s.isalnum())

# Return the first string in the list which isn't empty/None or "null"/"hidden"/"{}"/"[]" (Clickup "keywords"). Else return default.
# A "hidden" folder value means the list has no folder.
def get_valid_string(default, *strings):
    for s in strings:
        if s and s != "null" and s != "hidden" and s != "{}" and s != "[]":
            return s
    return default

if not os.path.exists(InputFile):
    print("InputFile does not exist - check script filename <" + InputFile + ">.")
    quit(-1)

with open(InputFile) as csv_file:
    clickup_project = csv.DictReader(csv_file, delimiter=',')

    # Create a directory for tasks as Joplin notes
    if not os.path.exists(OutputDir):
        os.mkdir(OutputDir)
        print("Output directory ", OutputDir,  " created")
    else:
        print("Output directory ", OutputDir,  " already exists")

    top_level_notebook_id = uuid.uuid4().hex
    dt_created  = datetime.datetime.now().isoformat('T','milliseconds')

    # Create the top level Notebook called ClickupImport to contain imported notes
    write_note_to_file(
        note_id = top_level_notebook_id,
        parent_id = "", # blank parent_id as top-level notebook
        name = 'Clickup Import',
        created_time = dt_created,
        updated_time = dt_created,
        user_created_time = dt_created,
        user_updated_time = dt_created,
        type = Type.TYPE_FOLDER.value
    )

    # Do an initial loop to determine which tasks have subtasks
    for task in clickup_project:
        if task['Status'].lower() in DoNotConvert:
            continue
        # If parent id exists, add it to list of tasks which need to be turned into folders
        if (get_valid_string(task['Parent ID'])):
            ConvertToFolder.add(task['Parent ID'])

    # Go back to beginning of CSV file
    csv_file.seek(0)
    next(clickup_project)

    # Create sets of tuples of
    #   1. clickup spaces/folders/lists id (the name in this case)
    #   2. parent id
    #   3. grandparent id (for a List, this is the Space, regardless if the Folder is hidden/nonexistent)
    clickup_spaces = set()
    clickup_folders = set()
    clickup_lists = set()
    for row in clickup_project:
        if row['Status'].lower() in DoNotConvert:
            continue
        clickup_spaces.add((row['Space Name'], top_level_notebook_id, ''))
        if (get_valid_string(False, row['Folder Name'])): # ignore "hidden" folders
            clickup_folders.add((row['Folder Name'], row['Space Name'], top_level_notebook_id))
            clickup_lists.add((row['List Name'], row['Folder Name'], row['Space Name']))
        else:
            clickup_lists.add((row['List Name'], row['Space Name'], top_level_notebook_id))

    # Create a notebook for each Clickup space, folder, and list
    # Using space/folder/list name + parent name as ID isn't really the best, but eh, it's decently unique
    for entry in clickup_spaces | clickup_folders | clickup_lists:
        write_note_to_file(
            note_id = as_id(entry[0] + "IN" + entry[1]), # use name + parent id as unique id (strip the non-alphanumerical chars)
            parent_id = as_id(entry[1] + "IN" + entry[2]), # similarly, parent id + grandparent id
            name = entry[0],
            created_time = dt_created,
            updated_time = dt_created,
            user_created_time = dt_created,
            user_updated_time = dt_created,
            type = Type.TYPE_FOLDER.value
        )

    line_count = 0

    # Go back to beginning of CSV file
    csv_file.seek(0)
    next(clickup_project)

    for task in clickup_project:
        # The Clickup heirarchy looks like: Clickup Project -> Space -> Folder -> List -> Task -> Subtask

        if line_count == 0:
            print(f'Column names are:\t{", ".join(task)}\n')
            print(f'parent_id:\t{top_level_notebook_id}\n')
            line_count += 1
            continue

        if task['Status'].lower() in DoNotConvert:
            continue

        note_id = task['Task ID']
        parent_id = task.get('Parent ID') if get_valid_string(False, task.get('Parent ID')) else as_id(task.get('List Name') + "IN" + get_valid_string(task['Space Name'], task['Folder Name']))

        # Clickup "Date Created" uses epoch time in milliseconds
        # Joplin uses '2017-12-07T12:56:17.000Z' which is basically ISO 8601 format with mS
        dt_created = datetime.datetime.fromtimestamp(float(task['Date Created']) / 1000.0).isoformat( 'T','milliseconds')
        type = Type.TYPE_NOTE.value
        content = format_content(task['Task Content'])
        checklists = format_checklist(task['Checklists'])
        tags = task['Tags'][1:-1]
        tags = tags.split(',') if tags != "" else []

        # If task has subtasks, convert it to a folder instead
        if note_id in ConvertToFolder:
            type = Type.TYPE_FOLDER.value
            # If task contains content, create a new task to house the content
            if get_valid_string(False, content, checklists):
                write_note_to_file(
                    note_id = note_id + "TaskContent",
                    parent_id = note_id,
                    name = "Original content from " + task[' Task Name'],
                    created_time = dt_created,
                    updated_time = dt_created,
                    user_created_time = dt_created,
                    user_updated_time = dt_created, # no modified date in clickup
                    type = Type.TYPE_NOTE.value,
                    content = content,
                    checklists = checklists,
                    order = 1 # Display this task at top of notebook
                )
            content = None
            checklists = None

        write_note_to_file(
            note_id = note_id,
            parent_id = parent_id,
            name = task[' Task Name'],
            created_time = dt_created,
            updated_time = dt_created,
            user_created_time = dt_created,
            user_updated_time = dt_created, # no modified date in clickup
            type = type,
            content = content,
            checklists = checklists
        )

        if tags:
            for tag in tags:
                tag_id = as_id("TAG" + tag)
                write_tag_to_file(
                    tag_id = tag_id,
                    name = tag,
                    created_time = dt_created,
                    updated_time = dt_created,
                    user_created_time = dt_created,
                    user_updated_time = dt_created
                )
                write_tag_association_to_file(
                    id = tag_id + "ASSOCIATEDWITH" + note_id,
                    note_id = note_id,
                    tag_id = tag_id,
                    created_time = dt_created,
                    updated_time = dt_created,
                    user_created_time = dt_created,
                    user_updated_time = dt_created
                )

        line_count += 1

    print('===============')
    print(f'Processed {line_count} lines.')
    print(f'created a new Notebook with id:\t{top_level_notebook_id}\n')


import sys
import os
import time
import re
import functools
import random

from fractions import Fraction

#f = open("C:\\Users\\antoi\\Documents\\GitHub\\hashcode\\prepa\\TD1\\samples-D1_Expression\\2.in",'r')

def get_input():
    return input().strip().split(" ")
    #return f.readline().strip().split(" ")

def is_op(op):

    if(op=='+' or op=='-' or op=='*' or op=='/' ):
        return True

    return False

def op(stack):

    buffer = []
    while(len(stack) >0):

        op = stack.pop()
        if(is_op(op)):
            try:
                opa = Fraction(buffer.pop())
                opb = Fraction(buffer.pop())
            except:
                return None

            if(op=='+'):
                op = opa+opb

            if(op=='-'):
                op = opb-opa

            if(op=='*'):
                op = opa*opb

            if(op=='/'):
                if(opa==0.0):
                    return None
                op = opb/opa

            buffer.append(op)

        else:
            buffer.append(op)

    if(len(buffer)>1):
        return None

    return buffer.pop()

if __name__ == '__main__':

    stack = []
    stack.append(get_input()[::-1])
    stack.append(get_input()[::-1])

    r_1 = op(stack[0])
    r_2 = op(stack[1])
    print(r_1==r_2)


import numpy as np
import seaborn
import pandas
from matplotlib import pyplot
from matplotlib import colors

df = pandas.DataFrame( dict(time=np.arange(500),
                            value=np.random.randn(500).cumsum()))
print(df)
graph = seaborn.relplot(x='time', y='value', kind='line', data=df)
graph.fig.autofmt_xdate()
pyplot.show()

df = pandas.DataFrame( np.random.randn(500, 2).cumsum(axis=0), columns=['x', 'y'])
seaborn.relplot(x='x', y='y', sort=False, kind='line', data=df)
pyplot.show()

# If having multiple set of values
fmri = seaborn.load_dataset('fmri')
print(fmri)
seaborn.relplot(x='timepoint', y='signal', kind='line', data=fmri)
pyplot.show()

# disable UI for aggregate to speed up
seaborn.relplot(x='timepoint', y='signal', ci=None, kind='line', data=fmri)
pyplot.show()

# spread distribution at each timepoint by standard deviation
seaborn.relplot(x='timepoint', y='signal', ci="sd", kind='line', data=fmri)
pyplot.show()

# turn off compute aggragation
seaborn.relplot(x='timepoint', y='signal', estimator=None, kind='line', data=fmri)
pyplot.show()

# 3 variable using color
seaborn.relplot(x='timepoint', y='signal', hue='event', kind='line', data=fmri)
pyplot.show()

# 3 variable using color and dotted lines
seaborn.relplot(x='timepoint', y='signal', hue='event', style='event', kind='line', data=fmri)
pyplot.show()

# 4 variables using color and dotted lines
seaborn.relplot(x='timepoint', y='signal', hue='region', style='event', kind='line', data=fmri)
pyplot.show()

dots = seaborn.load_dataset("dots").query("align == 'dots'")
print(dots)

# separate variable by color
seaborn.relplot(x="time", y="firing_rate",
            hue="coherence", style="choice",
            kind="line", data=dots)
pyplot.show()

# custom color
palette = seaborn.cubehelix_palette(light=0.1, n_colors=6)
seaborn.relplot(x="time", y="firing_rate",
            hue="coherence", style="choice",
            palette=palette,
            kind="line", data=dots)
pyplot.show()

# change the way color shift
seaborn.relplot(x="time", y="firing_rate",
            hue="coherence", style="choice",
                hue_norm=colors.LogNorm(),
            kind="line", data=dots)
pyplot.show()

# separate variable by size of line
seaborn.relplot(x="time", y="firing_rate",
            size='coherence', style='choice',
            kind="line", data=dots)
pyplot.show()

# plot with date
df = pandas.DataFrame( dict(time=pandas.date_range('2017-1-1', periods=500),
                            value=np.random.randn(500).cumsum()))
print(df)
g = seaborn.relplot(x='time', y='value', kind='line', data=df)
# make x label sideway
g.fig.autofmt_xdate()
pyplot.show()


'''
In the Athlete class given below,
make all the attributes private and
add the necessary accessor and mutator methods
Represent Maria, the runner and make her run.
'''

class Athlete:
    def __init__(self,name,gender):
        self.__name=name
        self.__gender=gender

    def running(self):
        if(self.__gender=="girl"):
            print("150mtr running")
        else:
            print("200mtr running")

    def mutator(self, name, gender):
        self.__name=name
        self.__gender=gender

    def accessor(self):
        print("Name is {} and gender is {}".format(self.__name,
        self.__gender))

maria_obj = Athlete("Maria", "boy")
maria_obj.running()
maria_obj.accessor()
maria_obj.mutator("Maria", "girl")
maria_obj.running()
maria_obj.accessor()


import requests
from Jumpscale import j

# html block example
"""

"""
# get images links from enduser
def gallery(doc, **kwargs):
    output = "```gallery\n"
    images_links = []

    for key in kwargs:
        if key.startswith("image"):
            images_links.append(kwargs[key])

    generated_html = render(images_links)
    output += generated_html
    output += "\n```"
    return output

# convert images & thumbs into html code
def render(images):
    blocks = ""
    for image in images:
        temp = """

		""".format(
            image, image, image
        )
        blocks += temp
    return blocks


from django.contrib.auth.models import User
from django.db import models
from django.urls import reverse
from myproject.core.models import TimeStampedModel, Active
from myproject.crm.models import Company, Employee, Provider
# from myproject.storage_backends import PrivateMediaStorage
from .managers import ExpenseManager, ReceiptManager

class Base(TimeStampedModel, Active):
    description = models.CharField('descrição', max_length=500)
    creator = models.ForeignKey(User, on_delete=models.CASCADE)
    payment_date = models.DateField(
        'data de pagto',
        null=True,
        blank=True
    )
    expiration_date = models.DateField(
        'data de vencimento',
        null=True,
        blank=True
    )
    paying_source = models.ForeignKey(
        Employee,
        verbose_name='fonte pagadora',
        related_name='employees',
        on_delete=models.CASCADE
    )
    type_expense = models.ForeignKey(
        'TypeExpense',
        verbose_name='tipo de despesa',
        on_delete=models.CASCADE
    )
    cost_center = models.ForeignKey(
        Company,
        verbose_name='centro de custo',
        related_name='companies',
        help_text='Recebido/Pago ao (cliente)',
        on_delete=models.CASCADE
    )
    provider = models.ForeignKey(
        Provider,
        verbose_name='fornecedor',
        related_name='providers',
        on_delete=models.CASCADE,
        null=True,
        blank=True
    )
    value = models.DecimalField(
        'valor',
        max_digits=9,
        decimal_places=2,
        default=0
    )
    payment = models.BooleanField(
        'Á vista?',
        default=True,
        help_text='Á vista ou Parcelado.'
    )
    paid = models.BooleanField(
        'Pago?',
        default=True,
        help_text='O fornecedor foi pago?'
    )
    cost_center_paid = models.BooleanField(
        'Cliente pagou?',
        default=False,
        help_text='O cliente pagou?'
    )
    payment_cost_center_date = models.DateField(
        'data de pagto do cliente',
        null=True,
        blank=True
    )
    document = models.FileField(
        # storage=PrivateMediaStorage(),
        null=True,
        blank=True
    )
    document_jpg = models.FileField(
        # storage=PrivateMediaStorage(),
        null=True,
        blank=True
    )

    class Meta:
        ordering = ('-payment_date',)

    def __str__(self):
        return self.description

    def to_dict_json_base(self):
        doc_name = ''
        doc_url = ''
        doc_jpg_name = ''
        doc_jpg_url = ''
        if self.document:
            doc_name = self.document.name
            doc_url = self.document.url
        if self.document_jpg:
            doc_jpg_name = self.document_jpg.name
            doc_jpg_url = self.document_jpg.url
        return {
            'pk': self.pk,
            'description': self.description,
            'cost_center': {
                'pk': self.cost_center.pk,
                'name': self.cost_center.social_name,
            },
            'provider': {
                'pk': self.provider.pk if self.provider else '',
                'name': self.provider.social_name if self.provider else '',
            },
            'expiration_date': self.expiration_date,
            'paid': self.paid,
            'cost_center_paid': self.cost_center_paid,
            'paying_source': {
                'pk': self.paying_source.pk,
                'name': self.paying_source.first_name,
            },
            'payment': self.payment,
            'payment_date': self.payment_date,
            'type_expense': {
                'pk': self.type_expense.pk,
                'title': self.type_expense.title,
                'fixed': self.type_expense.fixed,
            },
            'doc': {
                'name': doc_name,
                'url': doc_url,
            },
            'doc_jpg': {
                'name': doc_jpg_name,
                'url': doc_jpg_url,
            },
            'created': self.created,
            'modified': self.modified,
            'active': self.active,
        }

    def _to_dict_json(self):
        data = self.to_dict_json_base()
        return {
            'value': self.value,
            **data
        }

class Expense(Base):
    ''' Despesas '''
    pass

    objects = ExpenseManager()

    '''
    Usage:
    Expense.objects.count()
    Expense.objects.active().count()
    '''

    class Meta:
        proxy = True
        verbose_name = 'Despesa'
        verbose_name_plural = 'Despesas'

    def to_dict_json(self):
        data = self.to_dict_json_base()
        return {
            'value': -1 * self.value,
            **data
        }

    def save(self, *args, **kwargs):
        ''' Despesas é NEGATIVO. '''
        self.value = -1 * abs(self.value)
        super(Expense, self).save(*args, **kwargs)

class Receipt(Base):
    ''' Recebimentos '''
    pass

    objects = ReceiptManager()

    class Meta:
        proxy = True
        verbose_name = 'Recebimento'
        verbose_name_plural = 'Recebimentos'

    def to_dict_json(self):
        data = self.to_dict_json_base()
        return {
            'value': self.value,
            **data
        }

    def save(self, *args, **kwargs):
        ''' Despesas é POSITIVO. '''
        self.value = abs(self.value)
        super(Receipt, self).save(*args, **kwargs)

class TypeExpense(TimeStampedModel, Active):
    ''' Tipo de Despesa '''
    title = models.CharField('título', max_length=70, unique=True)
    fixed = models.BooleanField(
        'fixa',
        default=False,
        help_text='Despesa fixa?'
    )

    class Meta:
        ordering = ('title',)
        verbose_name = 'Tipo de Despesa'
        verbose_name_plural = 'Tipos de Despesas'

    def __str__(self):
        return self.title

    def to_dict_json(self):
        return {
            'pk': self.pk,
            'title': self.title,
        }

class Repayment(TimeStampedModel, Active):
    '''
    Notas de Reembolso do cliente.
    '''
    creator = models.ForeignKey(
        User,
        related_name='creator',
        on_delete=models.CASCADE
    )
    company = models.ForeignKey(
        Company,
        related_name='repayment_companies',
        on_delete=models.CASCADE
    )
    expiration_date = models.DateField(
        'data de vencimento',
        null=True,
        blank=True
    )

    class Meta:
        ordering = ('pk',)
        verbose_name = 'nota de reembolso'
        verbose_name_plural = 'notas de reembolso'

    def __str__(self):
        return '{} - {}'.format(self.pk, self.company)

    def get_code(self):
        return '{}/{}'.format(str(self.pk).zfill(3), self.created.year)

    def get_total(self):
        qs = self.repayments.filter(
            repayment=self.pk,
            expense__type_expense__fixed=False,
        ).values_list('expense__value', flat=True) or 0
        if qs:
            return sum(qs)
        return 0

    def cost_center_is_paid(self):
        '''
        Verifica se o cliente pagou toda a Nota de Reembolso.
        '''
        is_paid = self.repayments.all()\
            .values_list('expense__cost_center_paid', flat=True)
        if is_paid:
            if list(set(is_paid))[0]:
                return True
        return False

    def to_dict_json(self):
        return {
            'pk': self.pk,
            'company': {
                'pk': self.company.pk,
                'name': self.company.social_name,
            },
            'expiration_date': self.expiration_date,
            'code': self.get_code(),
            'total': -1 * self.get_total(),
            'paid': self.cost_center_is_paid(),
            'url': reverse('financial:repayment_items', kwargs={'pk': self.pk})
        }

class RepaymentItems(TimeStampedModel):
    '''
    Itens das Notas de Reembolso.
    '''
    repayment = models.ForeignKey(
        Repayment,
        related_name='repayments',
        on_delete=models.CASCADE
    )
    expense = models.ForeignKey(
        Expense,
        verbose_name='despesa',
        on_delete=models.CASCADE
    )

    class Meta:
        ordering = ('expense__payment_date',)
        verbose_name = 'item da nota de reembolso'
        verbose_name_plural = 'itens das notas de reembolso'

    def __str__(self):
        if self.repayment:
            return '{} - {}'.format(self.repayment.__str__(), self.expense)


# ******************************************************#
#   Random Walk 2 step**********************************#
#   Create Matrix And Selecte Top K                     #
#   Use split File  ************************************#
# ******************************************************#

import re
import split
import numpy as np
from collections import OrderedDict
import operator
import time

class MakeMatrix:
    def __init__(self, TopK):
        self.MusicList = {}
        self.Top_K = TopK
        print("This Is Matrix For Random Walk")

    def LoadFile(self):
        #File Open
        ReadMusicList = open("MusicList.txt", 'r', encoding="utf-8")
        MusicListLine = ReadMusicList.readlines()

        for line in MusicListLine:
            #print(line)
            X = split.LoadMusicList(line)
            #print("%s %s" %(X.MusicID, X.Count))
            self.MusicList["%s"%X.MusicID] = X.Count

        #self.Multiply()

    def Multiply(self):
        print("This Is Multiply")
        b = np.matrix(self.MusicList)
        #np.set_printoptions(threshold=np.nan)  # 매트릭스 전체 출력하기

        # print(b*(b.T*b))
        #b = b * (b.T * b)
        print(b)

    def Selection(self):
        print("This is Selection")
        TopKCount =0
        #임시로 MusicList로 테스트 해보자.
        # operator,itemgetter() 에서 0은 key를 기준으로 정렬, 1은 value를 기준으로 정렬
        # reverse 가 True 이면 작은 값부터 출력됨. #sorted_x = sorted(self.MusicList.items(), key=operator.itemgetter(1), reverse=True)
        sorted_x = sorted(self.MusicList.items(), key=operator.itemgetter(1))

        #print(sorted_x)

        for select in sorted_x:
            if float(select[1]) != 0.0 :
                TopKCount = TopKCount + 1

                print("%s %s" %(select[0], select[1]))

                if TopKCount >= self.Top_K:
                    break

    def Compare(self):
        print("This is Compare Top K and Test Data")

        ReadTestList = open("TestList.txt", 'r', encoding="utf-8")
        TestLine = ReadTestList.readlines()

        ReadTrainingList = open("MusicList.txt", 'r', encoding="utf-8")
        TrainingLine = ReadTrainingList.readlines()

        for Training in TrainingLine:
            B = split.LoadMusicList(Training)
            for Test in TestLine:
                #print(line)
                T = split.LoadMusicList(Test)
                print("%s %s" %(T.MusicID,T.Count))
                if T.MusicID == B.MusicID:
                    print("MID : %s TestCount : %s, Result: %s" %(T.MusicID, T.Count, B.Count))

################################
#   Run Run Run Run Run Run    #
################################
start_time = time.time()

Read = MakeMatrix(10)
#               Top K
Read.LoadFile()
Read.Selection()
#Read.Compare()
print("---------------%s seconds-----------"% (time.time() - start_time))


from typing import Any

from rest_framework import serializers

from apps.guide.serlializers.warehouse import WarehouseSerializer
from apps.shop.models import Product, ProductType
from apps.user.serializers import ReviewSerializer

class ProductTypeSerializer(serializers.Serializer):
    article = serializers.IntegerField()
    categoryId = serializers.IntegerField(source='category_id')
    brand = serializers.CharField()
    images = serializers.SerializerMethodField('_get_image')
    poster = serializers.CharField(source='img_path')
    name = serializers.CharField()
    description = serializers.CharField()
    basePrice = serializers.DecimalField(
        max_digits=10,
        decimal_places=2,
        source='base_price'
    )
    price = serializers.DecimalField(max_digits=10, decimal_places=2)
    discount = serializers.IntegerField()
    attributes = serializers.SerializerMethodField('_get_attributes')
    info = serializers.SerializerMethodField('_get_info')
    reviews = serializers.SerializerMethodField('_get_review')

    def _get_info(self, obj: ProductType) -> dict[str, Any]:
        data = obj.products.select_related('warehouse')
        return ProductSerializer(data, many=True).data

    def _get_attributes(self, obj: ProductType) -> dict[str, Any]:
        data = obj.attributes.select_related('attribute', 'value')
        return ProductAttributeSerializer(data, many=True).data

    def _get_image(self, obj: ProductType) -> list[Any]:
        return [str(im.url_path) for im in obj.images.all()]

    def _get_review(self, obj: ProductType) -> dict[str, Any]:
        return ReviewSerializer(obj.reviews, many=True).data

class ProductTypeListSerializer(serializers.Serializer):
    article = serializers.IntegerField()
    categoryId = serializers.IntegerField(source='category_id')
    poster = serializers.CharField(source='img_path')
    name = serializers.CharField()
    basePrice = serializers.DecimalField(
        max_digits=10,
        decimal_places=2,
        source='base_price'
    )
    price = serializers.DecimalField(max_digits=10, decimal_places=2)
    discount = serializers.IntegerField()
    count = serializers.SerializerMethodField('_get_count_quantity_product')

    def _get_count_quantity_product(self, obj: ProductType) -> int:
        return obj.products.count()

class ProductSerializer(serializers.Serializer):
    id = serializers.IntegerField()
    warehouse = serializers.SerializerMethodField('_get_shop')
    quantity = serializers.IntegerField()

    def _get_shop(self, obj: Product) -> dict[str, Any]:
        return WarehouseSerializer(obj.warehouse).data

class ProductAttributeSerializer(serializers.Serializer):
    name = serializers.CharField(source='attribute.name')
    meaning = serializers.CharField()
    value = serializers.CharField(source='value.name')


from datetime import datetime

import dateutil.parser

from crank.util.logging import logger

DATETIME_FORMAT = '%Y %b %d @ %H%M'

def get_timestamp_header():
    return datetime.now().strftime(DATETIME_FORMAT)

def parse_timestamp(line):
    ts_formats = (
        '%Y %b %d @ %H%M',
        '%d %b %Y @ %H%M',
        '%d %B %Y @ %H%M',
        '%d%b%Y@%H%M',
        '%d%b%Y @ %H%M',
    )

    # Try ISO8601
    try:
        return dateutil.parser.parse(line)
    except:
        pass
    exc = None
    for fmt in ts_formats:
        try:
            return datetime.strptime(line, fmt)
        except Exception as e:
            exc = e
    else:
        logger.warning("Failed to parse: %s", line)
        raise exc


from __future__ import division
import torch
SQRT_CONST = 1e-10

def safe_sqrt(x, lbound=SQRT_CONST):
    return torch.sqrt(torch.clip(x, lbound, 1e+5))

def pdist2sq(X,Y):

    C = -2*torch.matmul(X,torch.transpose(Y, 0, 1))
    nx = torch.sum(torch.square(X), dim=1, keepdim=True)
    ny = torch.sum(torch.square(Y),dim=1, keepdim=True)
    D = (C + torch.transpose(ny,  0, 1)) + nx
    return D

def wasserstein(Xf,Xc,p,lam=10,its=10,sq=False,backpropT=False):
    device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

    nc = Xc.shape[0]
    nf = Xf.shape[0]

    if sq:
        M = pdist2sq(Xf,Xc)
    else:
        M = safe_sqrt(pdist2sq(Xf,Xc))
    M_mean = torch.mean(M)
    # M_drop = torch.nn.Dropout(M,10/(nc*nt))
    delta = torch.max(M).detach()
    eff_lam = (lam/M_mean).detach()

    Mt = M
    num_row = M[:, 0:1].shape[0]
    num_col = M[0:1, :].shape[1]
    row = delta * (torch.ones([1, num_col]).to(device))
    col = torch.cat([delta * (torch.ones([num_row, 1]).to(device)), torch.zeros((1, 1)).to(device)], dim=0)
    Mt = torch.cat([M, row], dim=0)
    Mt = torch.cat([Mt, col], dim=1)

    a = torch.cat([torch.unsqueeze(p * torch.ones(nf) / nf, 1), (1 - p) * torch.ones((1, 1))], dim=0).to(device)
    b = torch.cat([torch.unsqueeze((1 - p) * torch.ones(nc) / nc, 1), p * torch.ones((1, 1))], dim=0).to(device)

    Mlam = eff_lam.to(device)*Mt
    K = torch.exp(-Mlam) + 1e-6 # added constant to avoid nan
    U = K*Mt
    ainvK = K/a

    u = a
    for i in range(0,its):
        u = 1.0/(torch.matmul(ainvK,(b/torch.transpose(torch.matmul(torch.transpose(u, 0, 1),K), 0, 1))))
    v = b/(torch.transpose(torch.matmul(torch.transpose(u, 0, 1),K), 0, 1))

    T = u*(torch.transpose(v, 0, 1)*K)

    E = T*Mt
    D = 2*torch.sum(E)
    return D, Mlam

"""
python implementation of Hilbert Schmidt Independence Criterion
hsic_gam implements the HSIC test using a Gamma approximation
Python 2.7.12

Gretton, A., Fukumizu, K., Teo, C. H., Song, L., Scholkopf, B.,
& Smola, A. J. (2007). A kernel statistical test of independence.
In Advances in neural information processing systems (pp. 585-592).

Shoubo (shoubo.sub AT gmail.com)
09/11/2016

Inputs:
X 		n by dim_x matrix
Y 		n by dim_y matrix
alph 		level of test

Outputs:
testStat	test statistics
thresh		test threshold for level alpha test
"""

def rbf_dot(pattern1, pattern2, deg):
    size1 = pattern1.shape
    size2 = pattern2.shape

    G = torch.sum(pattern1*pattern1, 1).reshape(size1[0],1)
    H = torch.sum(pattern2*pattern2, 1).reshape(size2[0],1)

    Q = torch.tile(G, (1, size2[0]))
    R = torch.tile(H.T, (size1[0], 1))

    H = Q + R - 2* torch.matmul(pattern1, pattern2.T)

    H = torch.exp(-H/2/(deg**2))
    return H

def hsic_gam(X, Y, alph = 0.5):
    device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
    n = X.shape[0]
    Xmed = X

    G = torch.sum(Xmed*Xmed, 1).reshape(n,1)
    Q = torch.tile(G, (1, n) )
    R = torch.tile(G.T, (n, 1) )

    dists = Q + R - 2 * torch.matmul(Xmed, Xmed.T)
    dists = dists - torch.tril(dists)
    dists = dists.reshape(n**2, 1)

    width_x = torch.sqrt(0.5 * torch.median(dists[dists>0]))
    Ymed = Y

    G = torch.sum(Ymed*Ymed, 1).reshape(n,1)
    Q = torch.tile(G, (1, n) )
    R = torch.tile(G.T, (n, 1) )
    dists = Q + R - 2* torch.matmul(Ymed, Ymed.T)
    dists = dists - torch.tril(dists)
    dists = dists.reshape(n**2, 1)
    width_y = torch.sqrt( 0.5 * torch.median(dists[dists>0]))

    bone = torch.ones((n, 1)).to(device)
    H = (torch.eye(n) - torch.ones((n,n)) / n).to(device)

    K = rbf_dot(X, X, width_x)
    L = rbf_dot(Y, Y, width_y)
    Kc = torch.matmul(torch.matmul(H, K), H)
    Lc = torch.matmul(torch.matmul(H, L), H)

    testStat = torch.sum(Kc.T * Lc) / n
    return testStat


from nailgun.db.sqlalchemy.models import NodeBondInterface

from nailgun.openstack.common import jsonutils
from nailgun.test.base import BaseIntegrationTest
from nailgun.test.base import reverse

class TestAssignmentHandlers(BaseIntegrationTest):
    def test_assignment(self):
        self.env.create(
            cluster_kwargs={"api": True},
            nodes_kwargs=[
                {"cluster_id": None}
            ]
        )
        cluster = self.env.clusters[0]
        node = self.env.nodes[0]
        assignment_data = [
            {
                "id": node.id,
                "roles": ['controller']
            }
        ]
        resp = self.app.post(
            reverse(
                'NodeAssignmentHandler',
                kwargs={'cluster_id': cluster.id}
            ),
            jsonutils.dumps(assignment_data),
            headers=self.default_headers
        )
        self.assertEqual(200, resp.status_code)
        self.assertEqual(node.cluster, cluster)
        self.datadiff(
            node.pending_roles,
            assignment_data[0]["roles"]
        )

        resp = self.app.post(
            reverse(
                'NodeAssignmentHandler',
                kwargs={'cluster_id': cluster.id}
            ),
            jsonutils.dumps(assignment_data),
            headers=self.default_headers,
            expect_errors=True
        )
        self.assertEqual(400, resp.status_code)

    def test_unassignment(self):
        cluster = self.env.create(
            cluster_kwargs={"api": True},
            nodes_kwargs=[{}]
        )
        node = self.env.nodes[0]
        # correct unassignment
        resp = self.app.post(
            reverse(
                'NodeUnassignmentHandler',
                kwargs={'cluster_id': cluster['id']}
            ),
            jsonutils.dumps([{'id': node.id}]),
            headers=self.default_headers
        )
        self.assertEqual(200, resp.status_code)
        self.assertEqual(node.cluster, None)
        self.assertEqual(node.pending_roles, [])

        #Test with invalid node ids
        for node_id in (0, node.id + 50):
            resp = self.app.post(
                reverse(
                    'NodeUnassignmentHandler',
                    kwargs={'cluster_id': cluster['id']}
                ),
                jsonutils.dumps([{'id': node_id}]),
                headers=self.default_headers,
                expect_errors=True
            )
            self.assertEqual(400, resp.status_code)
        #Test with invalid cluster id
        resp = self.app.post(
            reverse(
                'NodeUnassignmentHandler',
                kwargs={'cluster_id': cluster['id'] + 5}
            ),
            jsonutils.dumps([{'id': node.id}]),
            headers=self.default_headers,
            expect_errors=True
        )
        self.assertEqual(resp.status_code, 404)

        # Test with wrong cluster id
        self.env.create(
            cluster_kwargs={"api": True},
            nodes_kwargs=[{}]
        )

        resp = self.app.post(
            reverse(
                'NodeUnassignmentHandler',
                kwargs={'cluster_id': cluster['id']}
            ),
            jsonutils.dumps([{'id': self.env.clusters[1].nodes[0].id}]),
            headers=self.default_headers,
            expect_errors=True
        )
        self.assertEqual(resp.status_code, 400)

    def test_unassignment_after_deploy(self):
        cluster = self.env.create(
            nodes_kwargs=[{}]
        )
        node = self.env.nodes[0]
        node.status = 'error'
        self.db.commit()
        resp = self.app.post(
            reverse(
                'NodeUnassignmentHandler',
                kwargs={'cluster_id': cluster['id']}
            ),
            jsonutils.dumps([{'id': node.id}]),
            headers=self.default_headers
        )
        self.assertEqual(resp.status_code, 200)
        self.assertEqual(node.pending_deletion, True)

    def test_assigment_with_invalid_cluster(self):
        node = self.env.create_node(api=False)

        resp = self.app.post(
            reverse(
                'NodeAssignmentHandler',
                kwargs={'cluster_id': '9999'}
            ),
            jsonutils.dumps([{
                'id': node.id,
                'roles': ['controller']
            }]),
            headers=self.default_headers,
            expect_errors=True
        )

        self.assertEquals(404, resp.status_code)

class TestClusterStateUnassigment(BaseIntegrationTest):

    def test_delete_bond_and_networks_state_on_unassigmnet(self):
        """Test verifies that
        1. bond configuration will be deleted
        2. network unassigned from node interfaces
        when node unnasigned from cluster
        """
        cluster = self.env.create(
            nodes_kwargs=[{}]
        )
        node = self.env.nodes[0]
        node.bond_interfaces.append(
            NodeBondInterface(name='ovs-bond0',
                              slaves=node.nic_interfaces))
        self.db.flush()
        resp = self.app.post(
            reverse(
                'NodeUnassignmentHandler',
                kwargs={'cluster_id': cluster['id']}
            ),
            jsonutils.dumps([{'id': node.id}]),
            headers=self.default_headers
        )

        self.assertEqual(resp.status_code, 200)
        self.assertEqual(node.bond_interfaces, [])
        for interface in node.interfaces:
            self.assertEqual(interface.assigned_networks_list, [])


class Solution(object):
    def largestNumber(self, nums):
        """
        :type nums: List[int]
        :rtype: str
        """
        import functools
        def sort_rule(x,y):
            a = x + y
            b = y + x
            if a > b:
                return 1
            elif a < b:
                return -1
            else:
                return 0
        nums = [str(i) for i in nums]
        nums.sort(key=functools.cmp_to_key(sort_rule),reverse=True)
        res = ''.join(nums).lstrip('0')
        return res if res else '0'


from django.urls import path
from . import views

urlpatterns = [
    path('addblog/', views.addblogs, name = 'addblog'),
    path('blogs/', views.blogs, name = 'blogs'),
    path('blogs/<str:pk>/', views.blogscategory, name = 'blogslist'),
    path('doctorsblogs/', views.doctorsblogs, name = 'doctorsblogs'),
    path('doctorsblogs/<str:pk>/', views.doctorblog, name = 'doctorblog'),
]


"""
Author       : noeru_desu
Date         : 2021-11-20 20:43:02
LastEditors  : noeru_desu
LastEditTime : 2023-03-25 20:20:59
"""
from os.path import isfile, splitext, join
from math import ceil
from typing import TYPE_CHECKING, Callable, Union, Type

from PIL import Image
from orjson import loads

from image_obfuscator.constants import SKIP_CUSTOM_SAVE, SKIP_DISPLAY_PREVIEW
from image_obfuscator.modes.lsb_steganography.settings import Settings
from image_obfuscator.modes.lsb_steganography.core import encode, decode
from image_obfuscator.modes.lsb_steganography.utils import gen_lsb_info_json
from image_obfuscator.modules.image import WrappedPillowImage

if TYPE_CHECKING:
    from wx import Gauge
    from image_obfuscator.frame.image_saver import SaveSettings
    from image_obfuscator.frame. file_item import ImageItem
    from image_obfuscator.modes.base import EmptySettings
    from image_obfuscator.modes.lsb_steganography import ModeInterface
    from image_obfuscator.modes.lsb_steganography.settings import Settings
    from image_obfuscator.modules.image import WrappedImage, ImageData, PillowImage

def normal_gen(interface: 'ModeInterface', source: 'Image.Image', original: bool, return_type: Type[Union['PillowImage', 'ImageData']], settings: 'Settings', encryption_parameters: 'EmptySettings', label_text_setter: Callable, gauge: 'Gauge') -> 'WrappedImage':
    gauge.SetValue(0)
    label_text_setter('正在处理')
    if settings.lsb_mode == 0:
        image = encode_mode(interface, source, settings)
    else:
        image = decode_mode(interface, source, settings, True)
    gauge.SetValue(gauge.Range)
    label_text_setter('完成')
    return image

def encode_mode(interface: 'ModeInterface', outside: 'Image.Image', settings: 'Settings'):
    if not isfile(settings.inside_file_path):
        settings.inside_file_path = interface.settings_controller.inside_file = ''
        settings.compression_ratio = interface.settings_controller.compression_ratio = None
        return
    if settings.lsb_ratio is None:
        settings.lsb_ratio = interface.settings_controller._cal_lsb_ratio(outside, settings.lsb_num, settings.use_alpha, settings.inside_file_path)
    if settings.lsb_ratio > 1:
        if settings.auto_zoom_in:
            outside = outside.resize((ceil(outside.size[0] * settings.lsb_ratio), ceil(outside.size[1] * settings.lsb_ratio)))
        else:
            return
    elif settings.lsb_ratio < 1:
        if settings.auto_zoom_out:
            outside = outside.resize((ceil(outside.size[0] * settings.lsb_ratio), ceil(outside.size[1] * settings.lsb_ratio)))
    if not settings.use_alpha:
        alpha = outside.getchannel('A')
        outside = outside.convert('RGB')
    outside_data = interface.compressed_file_manager.open_file(settings.inside_file_path)
    if not isinstance(outside_data, bytes):
        compressor = outside_data.compressor
        outside_data = outside_data.load_compressed_data()
    else:
        compressor = 0
    lsb_info = gen_lsb_info_json(compressor, settings.inside_file_path)
    image = encode(outside, outside_data, settings.lsb_num, lsb_info + b'\xdd\xcc\xbb\xaa', settings.use_alpha)
    if not settings.use_alpha:
        image.putalpha(alpha)
    return WrappedPillowImage(image)

def decode_mode(interface: 'ModeInterface', outside: 'Image.Image', settings: 'Settings', test: bool = False):
    if not settings.use_alpha:
        outside = outside.convert('RGB')
    try:
        file_data, extra_data = decode(outside, settings.lsb_num, settings.use_alpha)
    except Exception as e:
        if test:
            interface.main_frame.dialog.async_warning(
                '尝试提取时出现以下错误: \n(程序运行正常, 这不是Bug)\n'
                '{}\n请检查设置是否正确\n已自动切换到 写入 模式'.format(repr(e).replace("\\n", " ")), '无法提取')
            interface.settings_controller.lsb_mode = 0
            interface.main_frame.sync_setting(interface.settings_panel.lsbMode)
            return SKIP_DISPLAY_PREVIEW
        return None, None
    else:
        if extra_data.endswith(b'\xdd\xcc\xbb\xaa'):
            if test:
                return
            return file_data, extra_data.removesuffix(b'\xdd\xcc\xbb\xaa')
        else:   # 应该不存在此类情况, 不存在分隔符会引发ValueError
            if test:
                interface.main_frame.dialog.async_info('尝试提取时没有出现错误, 但没有检测到LSB标识', '提取测试')
                return
            return file_data, None

def detect(outside: 'Image.Image', lsb_num: int, use_alpha: bool):
    if not use_alpha:
        outside = outside.convert('RGB')
    try:
        _, extra_data = decode(outside, lsb_num, use_alpha)
    except Exception:
        return 0
    else:
        return 2 if extra_data.endswith(b'\xdd\xcc\xbb\xaa') else 1

def save_image(interface: 'ModeInterface', source: 'Image.Image', image_item: 'ImageItem', settings: 'Settings', _, save_settings: 'SaveSettings', relative_save_path: str, quiet: bool):
    if settings.lsb_mode == 0:
        return SKIP_CUSTOM_SAVE
    file_data, info_json = decode_mode(interface, source, settings)
    if file_data is None:
        interface.main_frame.dialog.async_error('无法从所载入的图像中提取文件', '无法提取')
        return
    lsb_info = loads(info_json)
    save_path = join(save_settings.path, relative_save_path, f'{splitext(image_item.path_data.file_name)[0]}-extracted.{lsb_info["FS"]}')
    with open(save_path, 'wb') as f:
        f.write(file_data if lsb_info['CA'] == 0 else interface.compressed_file_manager.decompress_data(file_data, lsb_info['CA']))

def normal_gen_quietly(interface, source: 'Image.Image', original: bool, return_type: Type[Union['PillowImage', 'ImageData']], settings: 'Settings', encryption_parameters: 'EmptySettings') -> 'WrappedImage':
    if settings.lsb_mode == 0:
        image = encode_mode(interface, source, settings)
    else:
        return None
    return image


import sys, os

import unittest
import pandas as pd
import sys
from sklearn import datasets
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler, Imputer, LabelEncoder, LabelBinarizer, MinMaxScaler, MaxAbsScaler, RobustScaler,\
    Binarizer, PolynomialFeatures, OneHotEncoder
from sklearn_pandas import CategoricalImputer
from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer
from sklearn.tree import DecisionTreeRegressor, DecisionTreeClassifier
from sklearn.svm import SVC, SVR, LinearSVC, LinearSVR, OneClassSVM
from sklearn.decomposition import PCA
from sklearn.cluster import KMeans
from sklearn.naive_bayes import GaussianNB
from sklearn_pandas import DataFrameMapper
from sklearn.neighbors import KNeighborsClassifier, KNeighborsRegressor
from sklearn.ensemble import GradientBoostingClassifier, GradientBoostingRegressor, RandomForestClassifier,\
     RandomForestRegressor, IsolationForest
from sklearn.linear_model import LinearRegression, LogisticRegression, RidgeClassifier, SGDClassifier
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis

from nyoka.preprocessing import Lag

from nyoka import skl_to_pmml
from nyoka import PMML44 as pml

class TestMethods(unittest.TestCase):

    def test_sklearn_01(self):

        iris = datasets.load_iris()
        irisd = pd.DataFrame(iris.data,columns=iris.feature_names)
        irisd['Species'] = iris.target

        features = irisd.columns.drop('Species')
        target = 'Species'
        f_name = "svc_pmml.pmml"
        model = SVC()
        pipeline_obj = Pipeline([
            ('svm',model)
        ])

        pipeline_obj.fit(irisd[features],irisd[target])
        skl_to_pmml(pipeline_obj,features,target,f_name)
        pmml_obj = pml.parse(f_name,True)
        ## 1
        svms = pmml_obj.SupportVectorMachineModel[0].SupportVectorMachine
        for mod_val, recon_val in zip(model.intercept_, svms):
            self.assertEqual("{:.16f}".format(mod_val), "{:.16f}".format(recon_val.Coefficients.absoluteValue))

        ## 2
        svm = pmml_obj.SupportVectorMachineModel[0]
        self.assertEqual(svm.RadialBasisKernelType.gamma,model._gamma)

    def test_sklearn_02(self):
        iris = datasets.load_iris()
        irisd = pd.DataFrame(iris.data,columns=iris.feature_names)
        irisd['Species'] = iris.target

        features = irisd.columns.drop('Species')
        target = 'Species'
        f_name = "knn_pmml.pmml"

        pipeline_obj = Pipeline([
            ('scaling',StandardScaler()),
            ('knn',KNeighborsClassifier(n_neighbors = 5))
        ])

        pipeline_obj.fit(irisd[features],irisd[target])

        skl_to_pmml(pipeline_obj,features,target,f_name)

        pmml_obj = pml.parse(f_name,True)
        ##1
        self.assertIsNotNone(pmml_obj.NearestNeighborModel[0].ComparisonMeasure.euclidean)

        ##2
        self.assertEqual(pmml_obj.NearestNeighborModel[0].ComparisonMeasure.kind, "distance")

        ##3
        self.assertEqual(pipeline_obj.steps[-1][-1].n_neighbors, pmml_obj.NearestNeighborModel[0].numberOfNeighbors)

    def test_sklearn_03(self):
        iris = datasets.load_iris()
        irisd = pd.DataFrame(iris.data, columns=iris.feature_names)
        irisd['Species'] = iris.target

        features = irisd.columns.drop('Species')
        target = 'Species'
        f_name = "rf_pmml.pmml"
        model = RandomForestClassifier(n_estimators = 100)

        pipeline_obj = Pipeline([
            ("mapping", DataFrameMapper([
            (['sepal length (cm)', 'sepal width (cm)'], StandardScaler()) ,
            (['petal length (cm)', 'petal width (cm)'], Imputer())
            ])),
            ("rfc", model)
        ])

        pipeline_obj.fit(irisd[features], irisd[target])
        skl_to_pmml(pipeline_obj, features, target, f_name)
        pmml_obj = pml.parse(f_name,True)

        ## 1
        self.assertEqual(model.n_estimators,pmml_obj.MiningModel[0].Segmentation.Segment.__len__())

        ##2
        self.assertEqual(pmml_obj.MiningModel[0].Segmentation.multipleModelMethod, "majorityVote")

    def test_sklearn_04(self):
        titanic = pd.read_csv("nyoka/tests/titanic_train.csv")

        titanic['Embarked'] = titanic['Embarked'].fillna('S')

        features = list(titanic.columns.drop(['PassengerId','Name','Ticket','Cabin','Survived']))
        target = 'Survived'
        f_name = "gb_pmml.pmml"

        pipeline_obj = Pipeline([
            ("mapping", DataFrameMapper([
                (['Sex'], LabelEncoder()),
                (['Embarked'], LabelEncoder())
            ])),
            ("imp", Imputer(strategy="median")),
            ("gbc", GradientBoostingClassifier(n_estimators = 10))
        ])

        pipeline_obj.fit(titanic[features],titanic[target])

        skl_to_pmml(pipeline_obj, features, target, f_name)

        pmml_obj = pml.parse(f_name,True)

        ##1
        self.assertEqual(pmml_obj.MiningModel[0].Segmentation.multipleModelMethod, "modelChain")

        ##2
        self.assertEqual(pmml_obj.MiningModel[0].Segmentation.Segment.__len__(), 2)

        ##3
        self.assertEqual(pmml_obj.MiningModel[0].Segmentation.Segment[1].RegressionModel.normalizationMethod, "logit")

    def test_sklearn_05(self):
        df = pd.read_csv('nyoka/tests/auto-mpg.csv')
        X = df.drop(['mpg'],axis=1)
        y = df['mpg']

        features = [name for name in df.columns if name not in ('mpg')]
        target = 'mpg'

        pipeline_obj = Pipeline([
            ('mapper', DataFrameMapper([
                ('car name', TfidfVectorizer())
            ])),
            ('model',DecisionTreeRegressor())
        ])

        pipeline_obj.fit(X,y)

        skl_to_pmml(pipeline_obj,features,target,"dtr_pmml.pmml")

        self.assertEqual(os.path.isfile("dtr_pmml.pmml"),True)

    def test_sklearn_06(self):
        df = pd.read_csv('nyoka/tests/auto-mpg.csv')
        X = df.drop(['mpg','car name'],axis=1)
        y = df['mpg']

        features = X.columns
        target = 'mpg'
        f_name = "linearregression_pmml.pmml"
        model = LinearRegression()

        pipeline_obj = Pipeline([
            ('model',model)
        ])

        pipeline_obj.fit(X,y)
        skl_to_pmml(pipeline_obj,features,target,f_name)
        pmml_obj = pml.parse(f_name, True)

        ## 1
        reg_tab = pmml_obj.RegressionModel[0].RegressionTable[0]
        self.assertEqual(reg_tab.intercept,model.intercept_)

        ## 2
        for model_val, pmml_val in zip(model.coef_, reg_tab.NumericPredictor):
            self.assertEqual("{:.16f}".format(model_val),"{:.16f}".format(pmml_val.coefficient))

    def test_sklearn_07(self):
        iris = datasets.load_iris()
        irisd = pd.DataFrame(iris.data, columns=iris.feature_names)
        irisd['Species'] = iris.target

        features = irisd.columns.drop('Species')
        target = 'Species'
        f_name = "logisticregression_pmml.pmml"
        model = LogisticRegression()

        pipeline_obj = Pipeline([
            ("mapping", DataFrameMapper([
            (['sepal length (cm)', 'sepal width (cm)'], StandardScaler()) ,
            (['petal length (cm)', 'petal width (cm)'], Imputer())
            ])),
            ("lr", model)
        ])

        pipeline_obj.fit(irisd[features], irisd[target])
        skl_to_pmml(pipeline_obj, features, target, f_name)
        pmml_obj = pml.parse(f_name,True)

        ## 1
        segmentation = pmml_obj.MiningModel[0].Segmentation
        self.assertEqual(segmentation.Segment.__len__(), model.classes_.__len__()+1)

        ## 2
        self.assertEqual(segmentation.multipleModelMethod, "modelChain")

        ##3
        self.assertEqual(segmentation.Segment[-1].RegressionModel.normalizationMethod, "simplemax")

        ##4
        for i in range(model.classes_.__len__()):
            self.assertEqual(segmentation.Segment[i].RegressionModel.normalizationMethod, "logit")
            self.assertEqual("{:.16f}".format(model.intercept_[i]),\
                 "{:.16f}".format(segmentation.Segment[i].RegressionModel.RegressionTable[0].intercept))

    def test_sklearn_08(self):
        iris = datasets.load_iris()
        irisd = pd.DataFrame(iris.data, columns=iris.feature_names)
        irisd['Species'] = [i%2 for i in range(iris.data.shape[0])]

        features = irisd.columns.drop('Species')
        target = 'Species'

        pipeline_obj = Pipeline([
            ('pca',PCA(2)),
            ('mod',LogisticRegression())
        ])
        pipeline_obj.fit(irisd[features], irisd[target])

        skl_to_pmml(pipeline_obj, features, target, "logisticregression_pca_pmml.pmml")

        self.assertEqual(os.path.isfile("logisticregression_pca_pmml.pmml"),True)

    def test_sklearn_09(self):
        iris = datasets.load_iris()
        irisd = pd.DataFrame(iris.data, columns=iris.feature_names)
        irisd['Species'] = iris.target

        features = irisd.columns.drop('Species')
        target = 'Species'

        pipeline_obj = Pipeline([
            ("SGD", SGDClassifier())
        ])

        pipeline_obj.fit(irisd[features], irisd[target])

        skl_to_pmml(pipeline_obj, features, target, "sgdclassifier_pmml.pmml")

        self.assertEqual(os.path.isfile("sgdclassifier_pmml.pmml"),True)

    def test_sklearn_10(self):
        iris = datasets.load_iris()
        irisd = pd.DataFrame(iris.data, columns=iris.feature_names)
        irisd['Species'] = iris.target

        features = irisd.columns.drop('Species')
        target = 'Species'

        pipeline_obj = Pipeline([
            ("lsvc", LinearSVC())
        ])

        pipeline_obj.fit(irisd[features], irisd[target])

        skl_to_pmml(pipeline_obj, features, target, "linearsvc_pmml.pmml")

        self.assertEqual(os.path.isfile("linearsvc_pmml.pmml"),True)

    def test_sklearn_11(self):
        df = pd.read_csv('nyoka/tests/auto-mpg.csv')
        X = df.drop(['mpg','car name'],axis=1)
        y = df['mpg']

        features = X.columns
        target = 'mpg'

        pipeline_obj = Pipeline([
            ('model',LinearSVR())
        ])

        pipeline_obj.fit(X,y)

        skl_to_pmml(pipeline_obj,features,target,"linearsvr_pmml.pmml")

        self.assertEqual(os.path.isfile("linearsvr_pmml.pmml"),True)

    def test_sklearn_12(self):
        df = pd.read_csv('nyoka/tests/auto-mpg.csv')
        X = df.drop(['mpg','car name'],axis=1)
        y = df['mpg']

        features = X.columns
        target = 'mpg'

        pipeline_obj = Pipeline([
            ('model',GradientBoostingRegressor())
        ])

        pipeline_obj.fit(X,y)

        skl_to_pmml(pipeline_obj,features,target,"gbr.pmml")

        self.assertEqual(os.path.isfile("gbr.pmml"),True)

    def test_sklearn_13(self):
        iris = datasets.load_iris()
        irisd = pd.DataFrame(iris.data, columns=iris.feature_names)
        irisd['Species'] = iris.target

        features = irisd.columns.drop('Species')
        target = 'Species'

        pipeline_obj = Pipeline([
            ("SGD", DecisionTreeClassifier())
        ])

        pipeline_obj.fit(irisd[features], irisd[target])

        skl_to_pmml(pipeline_obj, features, target, "dtr_clf.pmml")

        self.assertEqual(os.path.isfile("dtr_clf.pmml"),True)

    def test_sklearn_14(self):
        df = pd.read_csv('nyoka/tests/auto-mpg.csv')
        X = df.drop(['mpg','car name'],axis=1)
        y = df['mpg']

        features = X.columns
        target = 'mpg'

        pipeline_obj = Pipeline([
            ('model',RandomForestRegressor())
        ])

        pipeline_obj.fit(X,y)

        skl_to_pmml(pipeline_obj,features,target,"rfr.pmml")

        self.assertEqual(os.path.isfile("rfr.pmml"),True)

    def test_sklearn_15(self):
        df = pd.read_csv('nyoka/tests/auto-mpg.csv')
        X = df.drop(['mpg','car name'],axis=1)
        y = df['mpg']

        features = X.columns
        target = 'mpg'

        pipeline_obj = Pipeline([
            ('model',KNeighborsRegressor())
        ])

        pipeline_obj.fit(X,y)

        skl_to_pmml(pipeline_obj,features,target,"knnr.pmml")

        self.assertEqual(os.path.isfile("knnr.pmml"),True)

    def test_sklearn_16(self):
        df = pd.read_csv('nyoka/tests/auto-mpg.csv')
        X = df.drop(['mpg','car name'],axis=1)
        y = df['mpg']

        features = X.columns
        target = 'mpg'

        pipeline_obj = Pipeline([
            ('model',SVR())
        ])

        pipeline_obj.fit(X,y)

        skl_to_pmml(pipeline_obj,features,target,"svr.pmml")

        self.assertEqual(os.path.isfile("svr.pmml"),True)

    def test_sklearn_17(self):
        irisdata = datasets.load_iris()
        iris = pd.DataFrame(irisdata.data,columns=irisdata.feature_names)
        iris['Species'] = irisdata.target

        feature_names = iris.columns.drop('Species')

        X = iris[iris.columns.drop(['Species'])]

        pipeline_obj = Pipeline([
            ('standard_scaler',StandardScaler()),
            ('Imputer',Imputer()),
            ('model',OneClassSVM())
        ])

        pipeline_obj.fit(X)
        skl_to_pmml(pipeline_obj, feature_names, pmml_f_name="one_class_svm.pmml")
        self.assertEqual(os.path.isfile("one_class_svm.pmml"),True)

    def test_sklearn_18(self):
        iris = datasets.load_iris()
        irisd = pd.DataFrame(iris.data, columns=iris.feature_names)
        irisd['Species'] = iris.target

        features = irisd.columns.drop('Species')
        target = 'Species'

        pipeline_obj = Pipeline([
            ("model", GaussianNB())
        ])

        pipeline_obj.fit(irisd[features], irisd[target])

        skl_to_pmml(pipeline_obj, features, target, "gnb.pmml")

        self.assertEqual(os.path.isfile("gnb.pmml"),True)

    def test_sklearn_19(self):
        iris = datasets.load_iris()
        irisd = pd.DataFrame(iris.data, columns=iris.feature_names)
        irisd['Species'] = iris.target

        features = irisd.columns.drop('Species')
        target = 'Species'

        pipeline_obj = Pipeline([
            ("model", SGDClassifier())
        ])

        pipeline_obj.fit(irisd[features], irisd[target])

        skl_to_pmml(pipeline_obj, features, target, "sgdc.pmml")

        self.assertEqual(os.path.isfile("sgdc.pmml"),True)

    def test_sklearn_20(self):
        iris = datasets.load_iris()
        irisd = pd.DataFrame(iris.data, columns=iris.feature_names)
        irisd['Species'] = iris.target

        features = irisd.columns.drop('Species')
        target = 'Species'

        pipeline_obj = Pipeline([
            ("model", RidgeClassifier())
        ])

        pipeline_obj.fit(irisd[features], irisd[target])

        skl_to_pmml(pipeline_obj, features, target, "ridge.pmml")

        self.assertEqual(os.path.isfile("ridge.pmml"),True)

    def test_sklearn_21(self):
        iris = datasets.load_iris()
        irisd = pd.DataFrame(iris.data, columns=iris.feature_names)
        irisd['Species'] = iris.target

        features = irisd.columns.drop('Species')
        target = 'Species'

        pipeline_obj = Pipeline([
            ("model", LinearDiscriminantAnalysis())
        ])

        pipeline_obj.fit(irisd[features], irisd[target])

        skl_to_pmml(pipeline_obj, features, target, "lda.pmml")

        self.assertEqual(os.path.isfile("lda.pmml"),True)

    def test_sklearn_22(self):
        iris = datasets.load_iris()
        irisd = pd.DataFrame(iris.data, columns=iris.feature_names)
        irisd['Species'] = iris.target

        features = irisd.columns.drop('Species')
        target = 'Species'
        model = LogisticRegression()
        pipeline_obj = Pipeline([
            ("scaler",Binarizer(threshold=2)),
            ("model", model)
        ])
        pipeline_obj.fit(irisd[features], irisd[target])

        skl_to_pmml(pipeline_obj, features, target, "binarizer.pmml")

        self.assertEqual(os.path.isfile("binarizer.pmml"),True)

    def test_sklearn_23(self):
        iris = datasets.load_iris()
        irisd = pd.DataFrame(iris.data, columns=iris.feature_names)
        irisd['Species'] = iris.target

        features = irisd.columns.drop('Species')
        target = 'Species'
        model = LogisticRegression()
        pipeline_obj = Pipeline([
            ("scaler",MinMaxScaler()),
            ("model", model)
        ])
        pipeline_obj.fit(irisd[features], irisd[target])

        skl_to_pmml(pipeline_obj, features, target, "minmax.pmml")

        self.assertEqual(os.path.isfile("minmax.pmml"),True)

    def test_sklearn_24(self):
        iris = datasets.load_iris()
        irisd = pd.DataFrame(iris.data, columns=iris.feature_names)
        irisd['Species'] = iris.target

        features = irisd.columns.drop('Species')
        target = 'Species'
        model = LogisticRegression()
        pipeline_obj = Pipeline([
            ("scaler",RobustScaler()),
            ("model", model)
        ])
        pipeline_obj.fit(irisd[features], irisd[target])

        skl_to_pmml(pipeline_obj, features, target, "robust.pmml")

        self.assertEqual(os.path.isfile("robust.pmml"),True)

    def test_sklearn_25(self):
        iris = datasets.load_iris()
        irisd = pd.DataFrame(iris.data, columns=iris.feature_names)
        irisd['Species'] = iris.target

        features = irisd.columns.drop('Species')
        target = 'Species'
        model = LogisticRegression()
        pipeline_obj = Pipeline([
            ("scaler",MaxAbsScaler()),
            ("model", model)
        ])
        pipeline_obj.fit(irisd[features], irisd[target])

        skl_to_pmml(pipeline_obj, features, target, "maxabs.pmml")

        self.assertEqual(os.path.isfile("maxabs.pmml"),True)

    def test_sklearn_25(self):
        iris = datasets.load_iris()
        irisd = pd.DataFrame(iris.data, columns=iris.feature_names)
        irisd['Species'] = iris.target
        irisd['new'] = [i%3 for i in range(iris.data.shape[0])]
        irisd.to_csv("test_new.csv",index=False)

        features = irisd.columns.drop('Species')
        target = 'Species'
        model = LogisticRegression()
        pipeline_obj = Pipeline([
            ("mapper", DataFrameMapper([
                (["new"], LabelBinarizer()),
                (iris.feature_names, None)
            ])),
            ('scale', StandardScaler()),
            ("model", model)
        ])
        pipeline_obj.fit(irisd[features], irisd[target])

        skl_to_pmml(pipeline_obj, features, target, "labelbinarizer.pmml")

        self.assertEqual(os.path.isfile("labelbinarizer.pmml"),True)

    def test_sklearn_26(self):
        iris = datasets.load_iris()
        irisd = pd.DataFrame(iris.data, columns=iris.feature_names)
        irisd['Species'] = iris.target
        irisd['new'] = [i%3 for i in range(iris.data.shape[0])]

        features = irisd.columns.drop('Species')
        target = 'Species'
        model = LinearRegression()
        pipeline_obj = Pipeline([
            ("mapper", DataFrameMapper([
                (["new"], OneHotEncoder(categories='auto'))
            ])),
            ("model", model)
        ])
        pipeline_obj.fit(irisd[features], irisd[target])

        skl_to_pmml(pipeline_obj, features, target, "onehot.pmml")

        self.assertEqual(os.path.isfile("onehot.pmml"),True)

    def test_sklearn_27(self):
        df = pd.read_csv('nyoka/tests/auto-mpg.csv')
        X = df.drop(['origin'],axis=1)
        y = df['origin']

        features = [name for name in df.columns if name not in ('origin')]
        target = 'origin'

        pipeline_obj = Pipeline([
            ('mapper', DataFrameMapper([
                ('car name', CountVectorizer())
            ])),
            ('model',LogisticRegression())
        ])

        pipeline_obj.fit(X,y)

        skl_to_pmml(pipeline_obj,features,target,"countvec.pmml")

        self.assertEqual(os.path.isfile("countvec.pmml"),True)

    def test_sklearn_28(self):
        iris = datasets.load_iris()
        irisd = pd.DataFrame(iris.data, columns=iris.feature_names)
        irisd['Species'] = iris.target
        irisd['new'] = [i%3 for i in range(iris.data.shape[0])]

        features = irisd.columns.drop('Species')
        target = 'Species'
        model = LogisticRegression()
        pipeline_obj = Pipeline([
            ("mapper", DataFrameMapper([
                (["new"], PolynomialFeatures())
            ])),
            ("model", model)
        ])
        pipeline_obj.fit(irisd[features], irisd[target])

        skl_to_pmml(pipeline_obj, features, target, "polyfeat.pmml")

        self.assertEqual(os.path.isfile("polyfeat.pmml"),True)

    def test_sklearn_29(self):
        from sklearn.neural_network import MLPClassifier
        iris = datasets.load_iris()
        irisd = pd.DataFrame(iris.data, columns=iris.feature_names)
        irisd['Species'] = iris.target
        target = 'Species'
        features = irisd.columns.drop('Species')
        model = MLPClassifier()
        pipe = Pipeline([
            ('lag', Lag(aggregation="stddev", value=3)),
            ('model',model)
        ])
        pipe.fit(irisd[features], irisd[target])
        file_name = 'mlp_model_numlti_class_classification.pmml'
        skl_to_pmml(pipe, iris.feature_names, target,file_name)
        self.assertEqual(os.path.isfile(file_name),True)

    def test_sklearn_30(self):
        iris = datasets.load_iris()
        model = KMeans()
        pipe = Pipeline([
            ('model',model)
        ])
        pipe.fit(iris.data)
        file_name = 'kmeans_model.pmml'
        skl_to_pmml(pipe, iris.feature_names, 'target',file_name)
        self.assertEqual(os.path.isfile(file_name),True)

    def test_sklearn_31(self):
        iris = datasets.load_iris()
        irisd = pd.DataFrame(iris.data, columns=iris.feature_names)
        irisd['Species'] = iris.target
        target = 'Species'
        features = irisd.columns.drop('Species')
        model = GradientBoostingClassifier()
        pipe = Pipeline([
            ('scaler', MaxAbsScaler()),
            ('model',model)
        ])
        pipe.fit(irisd[features], irisd[target])
        file_name = 'gbc_model_numlti_class_classification.pmml'
        skl_to_pmml(pipe, iris.feature_names, target,file_name)
        self.assertEqual(os.path.isfile(file_name),True)

    def test_sklearn_32(self):
        from sklearn.neural_network import MLPClassifier
        iris = datasets.load_iris()
        irisd = pd.DataFrame(iris.data, columns=iris.feature_names)
        irisd['target'] = [i%2 for i in range(iris.data.shape[0])]
        target = 'target'
        features = irisd.columns.drop('target')
        model = MLPClassifier()
        pipe = Pipeline([
            ('lag', Lag(aggregation="sum", value=3)),
            ('model',model)
        ])
        pipe.fit(irisd[features], irisd[target])
        file_name = 'mlp_model_binary_class_classification.pmml'
        skl_to_pmml(pipe, iris.feature_names, target,file_name)
        self.assertEqual(os.path.isfile(file_name),True)

    def test_sklearn_33(self):
        irisdata = datasets.load_iris()
        iris = pd.DataFrame(irisdata.data,columns=irisdata.feature_names)
        iris['Species'] = irisdata.target

        feature_names = iris.columns.drop('Species')

        X = iris[iris.columns.drop(['Species'])]

        pipeline_obj = Pipeline([
            ('standard_scaler',StandardScaler()),
            ('Imputer',Imputer()),
            ('model',IsolationForest())
        ])

        pipeline_obj.fit(X)
        skl_to_pmml(pipeline_obj, feature_names, pmml_f_name="iforest.pmml")
        self.assertEqual(os.path.isfile("iforest.pmml"),True)

    def test_sklearn_34(self):
        iris = datasets.load_iris()
        irisd = pd.DataFrame(iris.data,columns=iris.feature_names)
        irisd['new'] = [i%2 for i in range(irisd.shape[0])]
        irisd['Species'] = iris.target

        features = irisd.columns.drop('Species')
        target = 'Species'
        model = LogisticRegression()
        pipeline_obj = Pipeline([
            ('mapper', DataFrameMapper([
                ('new', LabelBinarizer())
            ])),
            ('model',model)
        ])
        pipeline_obj.fit(irisd[features],irisd[target])
        skl_to_pmml(pipeline_obj,features,target,"lb_two.pmml")
        self.assertEqual(os.path.isfile("lb_two.pmml"),True)

if __name__=='__main__':
    unittest.main(warnings='ignore')


# 21. 合并两个有序链表
class Solution:
    def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
        # 法1
        if l1 and l2:
            if l1.val > l2.val:
                l1, l2 = l2, l1
            l1.next = self.mergeTwoLists(l2, l1.next)
        return l1 or l2

        # 法2
        prehead = ListNode(-1)
        prev = prehead
        while l1 and l2:
            if l1.val <= l2.val:
                prev.next = l1
                l1 = l1.next
            else:
                prev.next = l2
                l2 = l2.next
            prev = prev.next
        prev.next = l1 if l1 is not None else l2

        return prehead.next


# https://programmers.co.kr/learn/courses/30/lessons/12984
def solution(land, P, Q):
    arr = []
    for i in land:
        arr += i
    arr.sort()
    n = len(arr)
    # 모든 칸을 제거 한 값
    answer = sum(arr) * Q
    # 가장 낮은 칸으로 모든 지형을 맞췄을때 값
    cost = (sum(arr) - arr[0] * n) * Q
    answer = min(answer, cost)
    for i in range(1, len(arr)):
        if arr[i] != arr[i-1]:
            cost += (arr[i] - arr[i-1]) * i * P - (arr[i] - arr[i-1]) * (n-i) * Q
        answer = min(answer, cost)
    return answer

print(solution([[1, 2], [2, 3]], 3, 2))
print(solution([[4, 4, 3], [3, 2, 2], [ 2, 1, 0 ]], 5, 3))


import threading
from networktables import NetworkTables
import logging

# Setup
cond = threading.Condition()
notified = [False]

def connectionListener(connected, info):
    print(info, '; Connected=%s' % connected)

    with cond:
        notified[0] = True
        cond.notify()

NetworkTables.initialize(server='10.1.15.2')
NetworkTables.addConnectionListener(connectionListener, immediateNotify=True)

with cond:
    print("Waiting")
    if not notified[0]:
        cond.wait()

# Processing code
print("Connected!")

sd = NetworkTables.getTable("SmartDashboard")

# fe = fudicial estimated
def updatePose(x, y, theta):
    sd.putNumber("fe x", x)
    sd.putNumber("fe y", y)
    sd.putNumber("fe theta", theta)

def enableLogging(flag):
    logLevel = logging.CRITICAL

    if flag:
        logLevel = logging.DEBUG

    logging.basicConfig(level=logLevel)


#!/usr/bin/python3

def fibonacci(n):
    """Нахождение числа Фибоначчи

    Принимает:
        n - число (номер позиции искомого числа Фибоначчи)
    Возвращает:
        Искомое число Фибоначчи
    """
    # Первые два числа Фибоначчи 0 и 1:
    if (n <= 1):
        return n
    else:
        # Каждое следующее число равно сумме двух предыдущих:
        return (fibonacci(n-1) + fibonacci(n-2))

try:
    n = int(f'{input("Введите число: ")}')
except ValueError:
    print(f'Вы ввели не число')
try:
    print(f'Ваше число Фибоначчи: {fibonacci(n)}')
except NameError:
    print(f'Неправильный ввод, либо на ввод ничего не поступило')


from xml.etree.ElementTree import fromstring, tostring

def normalizeScript(value):
    """
        This analyzes a piece of python script to derive the proper first
        indent (by looking at the first line) and adjusts the rest accordingly.
    """
    value = value.split('\n')

    #find indent
    for line in value:
      if line.strip():
          indent = len(line) - len(line.lstrip())
          break

    #normalize script tab depth to zero, reindenting if wrapped in a defintion
    script = []
    for line in value:
      strippedline = line.strip()
      if not strippedline or strippedline[0] == '#': continue
      script.append(line[indent:])

    return '\n'.join(script)

def castValueFromType(name, typeof="expression", value=None):
    #make an expression from text
    if typeof in ['expression', 'eval']:
        if value == None: value = "None"
        return "%s = %s" % (name, value)

    #make an float from text
    elif typeof in ['number', 'float']:
        if value == None: value = 0
        return "%s = float(%r)" % (name, value)

    #make an string from text
    elif typeof in ['string', 'str']:
        if value == None: value = ""
        return "%s = %r" % (name, value)


import datetime
import secrets

from vims_code.app import ApplicationException
from vims_code.models.game_team_info import GameTeamInfo
from vims_code.models.team import DatabaseTeam
from vims_code.models.team_game_auth import TeamGameAuth
from vims_code.models.team_player_role_list import TeamPlayerRoleList

class TeamAuthClass(object):
    def __init__(self, conn):
        self.conn = conn
        self.tga = TeamGameAuth(conn)
        self.gti = GameTeamInfo(conn)

    async def generate_token(self, game_id, team_id) -> str:
        rows = await self.gti.select(game_id=game_id, team_id=team_id, accepted=1)
        if len(rows) == 0:
            raise ApplicationException(error=44, message="Team not registered to the game")
        await self.tga.deactivate_token(game_id=game_id, team_id=team_id)
        new_token = str(secrets.token_hex(25))
        await self.tga.set(team_id=team_id, game_id=game_id, token=new_token, is_active=1)
        return new_token

    async def get_game_token(self, game_id, team_id):
        try:
            return (await self.tga.select(team_id=team_id, game_id=game_id, is_active=1))[0]['token']
        except IndexError:
            return None
            # raise ApplicationException(error=44, message="Team not registered to the game")

    async def create_team(self, creator_id: int, caption: str):
        t = DatabaseTeam(self.conn)
        if len(await t.select(caption=caption)) > 0:
            raise ApplicationException(43, "Команда с таким названием уже существует!")
        team_id = await t.set(caption=caption, creation_date=datetime.datetime.now())
        tprl = TeamPlayerRoleList(self.conn)
        await tprl.set(player_id=creator_id, team_id=team_id, player_role='OWNER')


f = open("day5.txt",'r')
lines = [x.strip('\n') for x in f.readlines()]
cargo = []

for i,x in enumerate(lines):
    if len(x) == 0:
        lines = lines[i+1:]
        break
    else:
        cargo.append(x)

cargo = cargo[:-1]

stacks = [[] for x in range(9)]
for line in cargo:
    for i,char in enumerate(line):
        if char.isalpha():
            stacks[i//4].append(char)

stacks = [i[::-1] for i in stacks]

for x in lines:
    s = x.split()
    num = int(s[1])
    prvi = int(s[3])
    drugi = int(s[5])
    [stacks[drugi-1].append(x) for x in (stacks[prvi-1][-num:])]
    stacks[prvi-1] = stacks[prvi-1][:-num]
print(*stacks)
print(''.join(x[-1]for x in stacks))


from typing import List, Optional, List

from fastapi.encoders import jsonable_encoder
from sqlalchemy.orm import Session

from app.crud.base import CRUDBase
from app.models import History
from app.schemas import HistoryCreate, HistoryUpdate

from app.utils import get_kst_now

class CRUDHistory(CRUDBase[History, HistoryCreate, HistoryUpdate]):
    def get_multi_with_user(
        self, db: Session, *, user_id: int
    ) -> List[History]:
        return db.query(self.model)\
            .filter(self.model.user_id == user_id)\
            .all()

    def get_with_user_and_episode(
        self,
        db: Session,
        *,
        user_id:int,
        episode_id: int
    ) -> History:
        return db.query(self.model)\
            .filter(self.model.user_id == user_id)\
            .filter(self.model.episode_id == episode_id)\
            .first()

    def create_with_user_and_episode(
        self, db: Session,
        *,
        obj_in: HistoryCreate,
        user_id: int,
        episode_id: int
    ) -> History:
        obj_in_data = jsonable_encoder(obj_in)
        db_obj = self.model(
            **obj_in_data,
            user_id=user_id,
            episode_id=episode_id,
        )
        db.add(db_obj)
        db.commit()
        db.refresh(db_obj)
        return db_obj

    def update(
        self, db: Session,
        *,
        db_obj: History,
        obj_in: HistoryUpdate
    ) -> History:
        obj_data = jsonable_encoder(db_obj)
        if isinstance(obj_in, dict):
            update_data = obj_in
        else:
            update_data = obj_in.dict(exclude_unset=True)

        for field in obj_data:
            if field in update_data:
                setattr(db_obj, field, update_data[field])
        setattr(db_obj, "latest_date", get_kst_now())
        db.add(db_obj)
        db.commit()
        db.refresh(db_obj)
        return db_obj

history = CRUDHistory(History)