## AlexNet tensorflow

import tensorflow as tf
import numpy as np

def init_weights(shape):
    return tf.Variable(tf.random_normal(shape,stddev=0.01),dtype = tf.float32)

def init_bias_zero(shape):
    return tf.Variable(tf.zeros(shape,dtype=tf.float32))

def init_bias_ones(shape):
    return tf.Variable(tf.ones(shape,dtype=tf.float32))

"""
input = [None , 224, 224, 3]   -
conv2d 11*11 - 4 - 96 - Relu   -  max_pool - 3*3 - 2 - LRN (local_response_normalization)
conv2d 5*5 - 1 - 256 - Relu    -  max_pool - 3*3 - 2 - LRN

conv2d - 3*3 - 1 - 384 - Relu
conv2d - 3*3 - 1 - 384 - Relu
conv2d - 3*3 - 1 - 256 - Relu  - max_pool - 3*3 - 2  - LRN

reshape
FC4096 - tanh - dropout 0.5
FC4096 - tanh - dropout 0.5
FC8 - softmax
"""

weights ={
"w1":init_weights([11,11,3,96]),
"w2":init_weights([5,5,96,256]),
"w3":init_weights([3,3,256,384]),
"w4":init_weights([3,3,384,384]),
"w5":init_weights([3,3,384,256]),
"w6":init_weights([4096,4096]),
"w7":init_weights([4096,4096]),
"w8":init_weights([4096,8])
}

bias ={
"b1":init_bias_zero([96]),
"b2":init_bias_ones([256]),
"b3":init_bias_zero([384]),
"b4":init_bias_ones([384]),
"b5":init_bias_ones([256]),
"b6":init_bias_ones([4096]),
"b7":init_bias_ones([4096])
}

def alexnet(X,weights,bias):
    network = tf.nn.conv2d(X,weights["w1"],strides=[1,4,4,1], padding = "SAME",name="conv1")
    network = tf.nn.relu(tf.nn.bias_add(network,bias["b1"]))
    network = tf.nn.max_pool(network,ksize=[1,3,3,1],strides=[1,2,2,1], padding = "SAME",name="max1")
    network = tf.nn.local_response_normalization(network, depth_radius=5, bias=1.0, alpha=0.0001, beta=0.75, name="lrn1")
    network = tf.nn.conv2d(network,weights["w2"],strides=[1,2,2,1],padding="SAME",name="conv2")
    network =tf.nn.relu(tf.nn.bias_add(network,bias["b2"]))
    network = tf.nn.max_pool(network,ksize=[1,3,3,1],strides=[1,2,2,1],padding="SAME",name="max2")
    network = tf.nn.local_response_normalization(network, depth_radius=5, bias=1.0, alpha=0.0001, beta=0.75, name="lrn2")
    network = tf.nn.conv2d(network,weights["w3"],strides=[1,1,1,1],padding="SAME",name="conv3")
    network = tf.nn.relu(tf.nn.bias_add(network,bias["b3"]))
    network = tf.nn.conv2d(network,weights["w4"],strides=[1,1,1,1],padding="SAME",name="conv4")
    network = tf.nn.relu(tf.nn.bias_add(network,bias["b4"]))
    network = tf.nn.conv2d(network,weights["w5"],strides=[1,1,1,1],padding="SAME",name="conv5")
    network = tf.nn.relu(tf.nn.bias_add(network,bias["b5"]))
    network = tf.nn.max_pool(network,ksize=[1,3,3,1],strides=[1,2,2,1],padding="SAME",name="max3")
    network = tf.nn.local_response_normalization(network, depth_radius=5, bias=1.0, alpha=0.0001, beta=0.75, name="lrn2")
    pool6Shape = network.get_shape().as_list()
    network = tf.reshape(network, [-1, pool6Shape[1] * pool6Shape[2] * pool6Shape[3]])
    network = tf.tanh(tf.add(tf.matmul(network, weights["w6"]), bias["b6"]))
    network = tf.nn.dropout(network,0.5)
    network = tf.tanh(tf.add(tf.matmul(network, weights["w7"]), bias["b7"]))
    network = tf.nn.dropout(network,0.5)
    network = tf.matmul(network,weights["w8"])
    return network # add a softmax logit layer when computing the cost


import unittest

class MakingChange(object):

    def __init__(self, coins):
        self.coins = coins

    def greedy_making_change(self, c):
        """
        Greedy algorithm. Take the largest coin possible each time. Doesn't work
        for all coin systems. We also assume that the coins are in descending
        order
        """
        total_coins = 0
        # Remove the largest coin from c that doesn't make c negative
        for coin in self.coins:
            while c - coin >= 0:
                total_coins += 1
                c -= coin
        return total_coins

    def optimal_greedy_making_change(self, c):
        """
        Optimized greedy algorithm. By using mods, we can solve this in constant
        time but this solution has the same limitations
        """
        total_coins = 0
        # Find how many of each coin can go into the remaining total
        for coin in self.coins:
            total_coins += c // coin
            c %= coin
        return total_coins

    def naive_making_change(self, c):
        """
        Brute force solution. Go through every possible combination of coins that
        sum up to c to find the minimum number
        """
        if c == 0:
            return 0

        min_coins = float('inf')

        # Try removing each coin from the total and see how many more coins
        # are required
        for coin in self.coins:
            # Skip a coin if it's value is greater than the amount remaining
            if c - coin >= 0:
                cur_min_coins = self.naive_making_change(c - coin)
                min_coins = min(min_coins, cur_min_coins)

        # Our recursive call removes one coin from the amount, so add it back
        return min_coins + 1

    def top_down_making_change_optimized(self, c):
        """
        Top down dynamic solution. Cache the values as we compute them
        """

        cache = [-1]*(c+1)
        cache[0] = 0

        return self.__top_down_making_change_optimized(c, cache)

    def __top_down_making_change_optimized(self, c, cache):
        # Return the value if it's in the cache
        if cache[c] >= 0:
            return cache[c]

        min_coins = float('inf')

        # Try removing each coin from the total and see how many more coins
        # are required
        for coin in self.coins:
            # Skip a coin if it's value is greater than the amount remaining
            if c - coin >= 0:
                cur_min_coins = self.__top_down_making_change_optimized(
                    c - coin, cache)
                min_coins = min(min_coins, cur_min_coins)

        # Save the value into the cache
        cache[c] = min_coins + 1
        return cache[c]

    def bottom_up_making_change(self, c):
        cache = [0]*(c+1)
        for i in range(1, c+1):
            min_coins = float('inf')

            # Try removing each coin from the total and see which requires
            # the fewest additional coins

            for coin in self.coins:
                if i - coin >= 0:
                    cur_min_coins = cache[i-coin] + 1
                    min_coins = min(min_coins, cur_min_coins)

            cache[i] = min_coins
        return cache[c]

class TestMakingChange(unittest.TestCase):

    def setUp(self):
        self.american_coins = [25, 10, 5, 1]
        self.random_coins = [10, 6, 1]

        self.testcases = [(self.american_coins, 1, 1), (self.american_coins, 6, 2), (self.american_coins, 47, 5), (
            self.random_coins, 1, 1), (self.random_coins, 8, 3), (self.random_coins, 11, 2), (self.random_coins, 12, 2)]

    def test_naive_making_change(self):
        for coins, value, expected in self.testcases:
            making_change = MakingChange(coins)
            with self.subTest(value=(coins, value)):
                self.assertEqual(
                    making_change.naive_making_change(value), expected)

    def test_top_down_making_change_optimized(self):
        for coins, value, expected in self.testcases:
            making_change = MakingChange(coins)
            with self.subTest(value=(coins, value)):
                self.assertEqual(
                    making_change.top_down_making_change_optimized(value), expected)

    def test_bottom_up_making_change(self):
        for coins, value, expected in self.testcases:
            making_change = MakingChange(coins)
            with self.subTest(value=(coins, value)):
                self.assertEqual(
                    making_change.bottom_up_making_change(value), expected)

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


class Solution(object):
    def lengthLongestPath(self, input):
        """
        :type input: str
        :rtype: int
        """
        stack = []
        paths = input.split("\n")
        res = 0
        for path in paths:
            p = path.replace("\t", "")
            cur_level = (len(path) - len(p))
            while len(stack) > cur_level:
                stack.pop()
            stack.append(p)
            if "." in p: # found file
                cur_len = 0
                for ele in stack:
                    cur_len += len(ele)
                    cur_len += 1
                res = max(res, cur_len-1)
                print(stack)
        return res


#Validate a given date. Input date in the format dd/mm/yyyy. Check also for leap year.
# Validate a given date. Check also for leap year.

maxdays = [None, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
line = input("enter the date as dd/mm/yyyy : ")
(dd, mm, yy) = line.split('/')
dd = int(dd)
mm = int(mm)
yy = int(yy)
if (yy % 4 == 0 and yy % 100 != 0) or (yy % 400 == 0) :
	maxdays[2] = 29
if mm < 1 or mm > 12 :
	print ("invalid month")
elif dd < 1 or dd > maxdays[mm] :
	print ("invalid date")
else:
	print ("date ok")


#!/usr/bin/env python3
"""this is a pagination module
"""

from typing import Tuple

def index_range(page: int, page_size: int) -> Tuple[int, int]:
    """return a start index and an end index as tuple
    """

    if page <= 0 or page_size <= 0:
        raise ValueError("Page and page_size must be positive integers")

    start_index = (page - 1) * page_size
    end_index = page * page_size

    return (start_index, end_index)


# -*- coding: utf-8 -*-
import sys
import cv2
import numpy as np

# 主函数
if __name__ == "__main__":
    # 输入图像矩阵，转换为array
    if len(sys.argv) > 1:
        image = cv2.imread(sys.argv[1], cv2.IMREAD_COLOR)
    else:
        print("Usage: python RGB.py imageFile")
        sys.exit(1)

    # 显示彩色图像
    cv2.imshow("bgr", image)

    # 得到三个颜色通道
    b = image[:,:,0]
    g = image[:,:,1]
    r = image[:,:,2]

    # 显示三个颜色通道
    cv2.imshow("b", b)
    cv2.imshow("g", g)
    cv2.imshow("r", r)

    cv2.waitKey(0)
    cv2.destroyAllWindows()


"""
Script to convert angular units
"""

import argparse as ap
from datetime import datetime
from astropy import units as u
from astropy.coordinates import (
    Angle,
    EarthLocation,
    )
from astropy.time import Time

SITE_LATITUDE = 28.761935*u.deg
SITE_LONGITUDE = -17.877591*u.deg
SITE_ELEVATION = 2348*u.m

SITE_LOCATION = EarthLocation(lat = SITE_LATITUDE,
                              lon = SITE_LONGITUDE,
                              height = SITE_ELEVATION)

def argParse():
    """
    Argument parser settings

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

    Returns
    -------
    args : array-like
        Array of command line arguments

    Raises
    ------
    None
    """

    parser = ap.ArgumentParser()

    parser.add_argument('angle',
                        help='angle to be converted',
                        type=str)

    parser.add_argument('--rad2deg',
                        help='radians to degrees',
                        action='store_true')

    parser.add_argument('--deg2rad',
                        help='degrees to radians',
                        action='store_true')

    parser.add_argument('--dec2sexagesimal',
                        help='declination in degrees to sexagesimal',
                        action='store_true')

    parser.add_argument('--dec2deg',
                        help='declination in sexagesimal to degrees',
                        action='store_true')

    parser.add_argument('--ra2sexagesimal',
                        help='right ascension in degrees to sexagesimal',
                        action='store_true')

    parser.add_argument('--ra2deg',
                        help='right ascension in sexagesimal to degrees',
                        action='store_true')

    parser.add_argument('--ra2ha',
                        help='right ascension to current hour angle',
                        action='store_true')

    parser.add_argument('--ha2ra',
                        help='hour angle to current right ascension',
                        action='store_true')

    return parser.parse_args()

def rad2deg(angle):
    """
    convert radians to degrees
    """
    angle_rad = Angle(angle, u.rad)

    return angle_rad.deg

def deg2rad(angle):
    """
    convert degrees to radians
    """
    angle_deg = Angle(angle, u.deg)

    return angle_deg.rad

def dec2sexagesimal(angle):
    """
    convert declination in degrees to sexagesimal format
    """
    angle_deg = Angle(angle, u.deg)

    return angle_deg.to_string()

def dec2deg(angle):
    """
    convert declination in sexagesimal format to degrees
    """
    angle_deg = Angle(angle, u.deg)

    return angle_deg

def ra2sexagesimal(angle):
    """
    convert a right ascension in degrees to sexagesimal format
    """
    angle_deg = Angle(angle, u.deg)
    angle_hourangle = Angle(angle.hourangle, u.hourangle)

    return angle_hourangle.to_string(), angle_hourangle

def ra2deg(angle):
    """
    convert a right ascension in sexagesimal format to degrees
    """
    angle_sexagesimal = Angle(angle, u.hourangle)

    return angle_sexagesimal.deg

def ra2ha(ra):
    """
    convert right ascension to hour angle at the current time
    """
    ra = Angle(ra, u.hourangle)

    utc_now = Time(datetime.utcnow(), scale='utc', location=SITE_LOCATION)
    lst = utc_now.sidereal_time('apparent')

    return (lst - ra).wrap_at(12*u.hourangle)

def ha2ra(ha):
    """
    convert hour angle to right ascension at the current time
    """
    ha = Angle(ha, u.hourangle)

    utc_now = Time(datetime.utcnow(), scale='utc', location=SITE_LOCATION)
    lst = utc_now.sidereal_time('apparent')

    return (lst - ha).wrap_at(24*u.hourangle)

def main(args):
    """
    Carry out requested conversion
    """

    if args.rad2deg:
        print('Angle in degrees: ', rad2deg(args.angle))

    elif args.deg2rad:
        print('Angle in radians: ', deg2rad(args.angle))

    elif args.dec2sexagesimal:
        print('Declination in sexagesimal format: ', dec2sexagesimal(args.angle))

    elif args.dec2deg:
        print('Declination in degrees: ', dec2deg(args.angle))

    elif args.ra2sexagesimal:
        print('Right ascension in sexagesimal format: ', ra2sexagesimal(args.angle))

    elif args.ra2deg:
        print('Right ascension in degrees: ', ra2deg(args.angle))

    elif args.ra2ha:
        print('Hour angle: ', ra2ha(args.angle))

    elif args.ha2ra:
        print('Right ascension: ', ha2ra(args.angle))

    return None

if __name__ == "__main__":

    args = argParse()

    main(args)


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

# In[ ]:

# This Python 3 environment comes with many helpful analytics libraries installed
# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python
# For example, here's several helpful packages to load

import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)

# Input data files are available in the read-only "../../../input/imnikhilanand_heart-attack-prediction/" directory
# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory

import os
for dirname, _, filenames in os.walk("../../../input/imnikhilanand_heart-attack-prediction"):
    for filename in filenames:
        print(os.path.join(dirname, filename))

# You can write up to 5GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using "Save & Run All"
# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session

# In[ ]:

d=pd.read_csv("../../../input/imnikhilanand_heart-attack-prediction/data.csv")

# In[ ]:

d.columns

# In[ ]:

d.columns=['age', 'sex', 'cp', 'bp', 'chol', 'fbs', 'restecg', 'thalach', 'exang', 'oldpeak', 'slope', 'ca', 'thal','num']

# In[ ]:

import matplotlib.pyplot as plt
d.head()

# In[ ]:

# In[ ]:

import seaborn as sns
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn import metrics

# In[ ]:

# In[ ]:

d["chol"].replace({'?': 0},inplace=True)
#d["age"].replace({'?': 0},inplace=True)
d["bp"].replace({'?': 0},inplace=True)
#d["sex"].replace({'?': 0},inplace=True)
#d["cp"].replace({'?': 0},inplace=True)
#d["num"].replace({'?': 0},inplace=True)

# In[ ]:

x=np.array(d.iloc[:,1:5])
y=np.array(d[['num']])
X_train, X_test, y_train, y_test = train_test_split( x, y, test_size=0.2, random_state=4)
LR = LogisticRegression().fit(X_train,y_train)

# In[ ]:

yhat = LR.predict(X_test)
yhat

# In[ ]:

yhat_prob = LR.predict_proba(x)
yhat_prob

# In[ ]:

accuracy = metrics.accuracy_score(y_test, yhat)
accuracy_percentage = 100 * accuracy
accuracy_percentage

# In[ ]:

from sklearn.metrics import jaccard_similarity_score
jaccard_similarity_score(y_test, yhat)

# In[ ]:

from sklearn.metrics import classification_report, confusion_matrix
import itertools
def plot_confusion_matrix(cm, classes,
                          normalize=False,
                          title='Confusion matrix',
                          cmap=plt.cm.Blues):
    """ This function prints and plots the confusion matrix. Normalization can be applied by setting `normalize=True`. """
    if normalize:
        cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
        print("Normalized confusion matrix")
    else:
        print('Confusion matrix, without normalization')

    print(cm)

    plt.imshow(cm, interpolation='nearest', cmap=cmap)
    plt.title(title)
    print()
    tick_marks = np.arange(len(classes))
    plt.xticks(tick_marks, classes, rotation=45)
    plt.yticks(tick_marks, classes)

    fmt = '.2f' if normalize else 'd'
    thresh = cm.max() / 2.
    for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
        plt.text(j, i, format(cm[i, j], fmt), horizontalalignment="center", color="white" if cm[i, j] > thresh else "black")

    plt.tight_layout()
    plt.ylabel('True label')
    plt.xlabel('Predicted label')
print(confusion_matrix(y_test, yhat, labels=[1,0]))

# In[ ]:

# Compute confusion matrix
cnf_matrix = confusion_matrix(y_test, yhat, labels=[1,0])
np.set_printoptions(precision=2)

# Plot non-normalized confusion matrix
plt.figure()
plot_confusion_matrix(cnf_matrix, classes=['num=1','num=0'],normalize= False,  title='Confusion matrix')

# In[ ]:

print (classification_report(y_test, yhat))

# In[ ]:

print(len(d['chol']),len(yhat_prob[:,0]))

# In[ ]:

plt.scatter(d['age'],yhat_prob[:,0], s=10)
print()

# In[ ]:


from time import sleep
from typing import Set, Tuple, Union
from dotenv import load_dotenv
import os
import tweepy
import re
from tqdm import tqdm

class CurrentUser:
    def __init__(
        self, client: tweepy.Client, api: tweepy.API, id: str
    ) -> None:
        self.client: tweepy.Client = client
        self.api: tweepy.API = api
        self.id: str = id

class PyTweeBlockError(Exception):
    pass

def main() -> None:
    curr_user = generate_current_user()
    keep_going = True
    while keep_going:
        keep_going = main_menu(curr_user)

def main_menu(curr: CurrentUser) -> bool:
    print("Please enter with the @ you want to block, or a tweet link.")
    user_input = input().strip()
    if re.match(r"https:\/\/twitter.com\/\w+\/status\/\w+", user_input):
        blocklist = generate_tweet_blocklist(curr, user_input)
        block_users(curr, blocklist)
    elif re.match(r"(@\w+)|(\w+)", user_input):
        blocklist = generate_account_blocklist(curr, user_input)
        block_users(curr, blocklist)
    answer = ""
    while answer not in ("y", "n"):
        answer = (
            input("Do you want to mass block another account? (y\\n)")
            .strip()
            .lower()
        )
    return True if answer == "y" else False

def block_users(curr: CurrentUser, blocklist: Set[str]) -> None:
    curr.client.wait_on_rate_limit = False
    use_api_2 = True
    for id in tqdm(blocklist):
        if use_api_2:
            try:
                curr.client.block(id)
            except tweepy.errors.TooManyRequests:
                curr.api.create_block(user_id=id)
                use_api_2 = False
        else:
            curr.api.create_block(user_id=id)

def generate_account_blocklist(curr: CurrentUser, account: str) -> Set[str]:
    account = account.removeprefix("@")
    account: tweepy.User = curr.client.get_user(
        username=account, user_auth=True
    ).data
    users_following = collect_set_paginator(
        curr.client.get_users_followers,
        account.id,
        max_results=1000,
    )
    users_to_not_block = collect_set_paginator(
        curr.client.get_users_followers,
        curr.id,
        user_auth=True,
        max_results=1000,
    ) | collect_set_paginator(
        curr.client.get_users_following,
        curr.id,
        user_auth=True,
        max_results=1000,
    )
    block_list = (users_following | set([account.id])) - users_to_not_block
    return block_list

def generate_tweet_blocklist(curr: CurrentUser, tweet_link: str) -> Set[str]:
    account = ""
    tweet_id = ""
    try:
        account = re.findall(r"(?<=twitter\.com\/)\w+", tweet_link)[0]
        tweet_id = re.findall(r"(?<=status\/)\d+", tweet_link)[0]
    except IndexError:
        raise PyTweeBlockError(
            "Error extracting account name and tweet id from link"
        )
    account: tweepy.User = curr.client.get_user(
        username=account, user_auth=True
    ).data
    liking_users = collect_set(
        curr.client.get_liking_users,
        tweet_id,
    )
    retweeting_users = collect_set(
        curr.client.get_retweeters,
        tweet_id,
    )
    users_following = collect_set_paginator(
        curr.client.get_users_followers,
        account.id,
        user_auth=True,
        max_results=1000,
    )
    users_to_not_block = collect_set_paginator(
        curr.client.get_users_followers,
        curr.id,
        user_auth=True,
        max_results=1000,
    ) | collect_set_paginator(
        curr.client.get_users_following,
        curr.id,
        user_auth=True,
        max_results=1000,
    )
    block_list = (
        liking_users | users_following | retweeting_users | set([account.id])
    ) - users_to_not_block
    return block_list

def collect_set(method, *args, **kwargs) -> Set[str]:
    return set(map(lambda user: user.id, method(*args, **kwargs).data))

def collect_set_paginator(method, *args, **kwargs) -> Set[str]:
    to_return = set()
    for response in tweepy.Paginator(method, *args, **kwargs):
        to_return |= set(
            map(
                lambda user: user.id,
                response.data,
            )
        )
    #        print("Able to get Paginator once!")
    return to_return

def get_pin_input(url: str) -> str:
    """
    Basic while loop to get the pin from the user
    Returns the identifier stripped and only if it's only digits
    """
    while True:
        print(url)
        verifier = input("Please enter the PIN code: ")
        verifier = verifier.strip()
        if verifier.isdigit():
            return verifier
        else:
            print("Please input only the PIN code")

def generate_current_user() -> CurrentUser:
    load_dotenv()
    consumer_key = os.getenv("TWITTER_API_KEY")
    consumer_secret = os.getenv("TWITTER_API_SECRET")
    bearer_token = os.getenv("TWITTER_BEARER_TOKEN")
    auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
    verifier = get_pin_input(auth.get_authorization_url())
    user_key, user_secret = auth.get_access_token(verifier)
    client = tweepy.Client(
        consumer_key=consumer_key,
        consumer_secret=consumer_secret,
        access_token=user_key,
        access_token_secret=user_secret,
        wait_on_rate_limit=True,
        bearer_token=bearer_token,
    )
    api = tweepy.API(auth)
    user_id = api.verify_credentials().id_str
    print("Login successful!")
    return CurrentUser(client, api, user_id)

if __name__ == "__main__":
    main()


def input_int(a, b):
    while True:
        x = input("put a number >")
        if x.isdigit() and a <= int(x) <= b:
            break
        elif not x.isdigit() or a >= int(x) >= b :
            print ("put a number from " + str(a) +" to " + str(b))
        else:
            print ("error")

input_int(1,100)


import asyncio
import json
import os

from slack_sdk.web.async_client import AsyncWebClient

if os.path.exists("claude.json"):
    with open("claude.json") as f:
        try:
            claude_config = json.load(f)
        except json.JSONDecodeError:
            claude_config = {}
else:
    claude_config = {}

class Chatbot:
    def __init__(
            self,
            slack_user_token=claude_config.get("slackUserToken"),
            slack_channel_id=claude_config.get("slackChannelId"),
            claude_member_id=claude_config.get("claudeMemberId"),
            proxy=None,
    ):
        self.client = AsyncWebClient(token=slack_user_token, proxy=proxy)
        self.slack_channel_id = slack_channel_id
        self.claude_member_id = claude_member_id

    async def ask_stream(self, message):
        if len(message) < 3000:  # Slack truncates message at ~3000 characters
            response = await self.client.chat_postMessage(channel=self.slack_channel_id, text=message)
            thread_ts = response["ts"]
        else:
            response = await self.client.chat_postMessage(channel=self.slack_channel_id, text=message[:3000])
            thread_ts = response["ts"]
            await self.client.chat_postMessage(
                channel=self.slack_channel_id,
                text=message[3000:],
                thread_ts=thread_ts,
            )

        await self.client.chat_postMessage(
            channel=self.slack_channel_id,
            text=f'<@{self.claude_member_id}> [assistant](#message)',
            thread_ts=thread_ts,
        )

        while True:
            await asyncio.sleep(1)
            replies_response = await self.client.conversations_replies(channel=self.slack_channel_id, ts=thread_ts)
            all_replies = replies_response["messages"]
            for reply in all_replies:
                if reply["user"] == self.claude_member_id:
                    break
            else:
                continue

            if reply["text"].endswith("_Typing…_"):
                yield reply["text"][:-11]
            else:
                yield reply["text"]
                break


import random
from nas_lib.nas_201_api.genotypes import Structure as CellStructure
from copy import deepcopy
import numpy as np
from nas_lib.data.cell_nasbench201 import Cell
import torch
import pickle
from nas_lib.configs import nas_bench_201_converted_base_path

NUM_VERTICES = 8
OPS = ['input', 'none', 'skip_connect', 'nor_conv_1x1', 'nor_conv_3x3', 'avg_pool_3x3', 'isolate', 'output']
OPS_GRAPH = ['input', 'skip_connect', 'nor_conv_1x1', 'nor_conv_3x3', 'avg_pool_3x3', 'isolate', 'output']
OPS_LIST = ['avg_pool_3x3', 'nor_conv_1x1', 'nor_conv_3x3', 'none', 'skip_connect']
OP_SPOTS = 6

class NASBench201:
    def __init__(self, dataset):
        self.nas_bench = None
        self.max_nodes = 4
        self.op_names = ['none', 'skip_connect', 'nor_conv_1x1', 'nor_conv_3x3', 'avg_pool_3x3']
        self.op_names_alphaX = ['none', 'skip_connect', 'nor_conv_1x1', 'nor_conv_3x3', 'avg_pool_3x3', 'term']
        del self.nas_bench
        pkl_path = nas_bench_201_converted_base_path % dataset
        with open(pkl_path, 'rb') as f:
            self.total_archs = pickle.load(f)
            self.total_keys = pickle.load(f)

    def random_arch(self):
        genotypes = []
        for i in range(1, self.max_nodes):
            xlist = []
            for j in range(i):
                node_str = '{:}<-{:}'.format(i, j)
                op_name = random.choice(self.op_names)
                xlist.append((op_name, j))
            genotypes.append(tuple(xlist))
        return CellStructure(genotypes)

    def mutate(self, parent_arch):
        while True:
            child_arch = deepcopy(parent_arch)
            node_id = random.randint(0, len(child_arch.nodes) - 1)
            node_info = list(child_arch.nodes[node_id])
            snode_id = random.randint(0, len(node_info) - 1)
            xop = random.choice(self.op_names)
            while xop == node_info[snode_id][0]:
                xop = random.choice(self.op_names)
            node_info[snode_id] = (xop, node_info[snode_id][1])
            child_arch.nodes[node_id] = tuple(node_info)
            str_arch = child_arch.tostr()
            if str_arch in self.total_keys:
                break
        return child_arch, self.total_archs[str_arch]

    def get_candidates(self,
                       data,
                       num=100,
                       allow_isomorphisms=False,
                       patience_factor=5,
                       num_best_arches=10,
                       return_dist=False):
        """
        Creates a set of candidate architectures with mutated and/or random architectures
        """
        # test for isomorphisms using a hash map of path indices
        candidates = []
        dic = {}
        dist_list = []
        nums_list = []
        mutated_archs_list = []
        for d in data:
            arch = {'matrix': d[0][0], 'ops': d[0][1]}
            path_indices = Cell(**arch).get_path_indices()
            dic[path_indices] = 1

        best_arches = [CellStructure.str2structure(arch[6])
                       for arch in sorted(data, key=lambda i: i[4])[:num_best_arches * patience_factor]]
        best_arches_full = [arch for arch in sorted(data, key=lambda i: i[4])[:num_best_arches * patience_factor]]
        # stop when candidates is size num
        # use patience_factor instead of a while loop to avoid long or infinite runtime
        for idx, arch in enumerate(best_arches):
            if len(candidates) >= num:
                break
            nums = 0
            for i in range(num):
                _, mutated = self.mutate(arch)
                path_indices = Cell(matrix=mutated[0][0], ops=mutated[0][1]).get_path_indices()

                if allow_isomorphisms or path_indices not in dic:
                    dic[path_indices] = 1
                    candidates.append(mutated)
                    dist = adj_distance(arch.tostr(), mutated[6])
                    dist_list.append(dist)
                    nums += 1
            nums_list.append(nums)
            mutated_archs_list.append(best_arches_full[idx])
        if return_dist:
            return candidates[:num], dist_list[:num], 0, nums_list, mutated_archs_list
        else:
            return candidates[:num]

    def generate_random_dataset(self, num=10,
                                allow_isomorphisms=False,
                                deterministic_loss=False):
        data = []
        dic = {}
        key_list = []
        while True:
            k = random.sample(self.total_keys, 1)
            key_list.append(k[0])
            arch = self.total_archs[k[0]]
            cell_arch = Cell(matrix=arch[0][0], ops=arch[0][1], isolate_node_idxs=[])
            path_encoding1 = cell_arch.encode_paths()
            path_encoding2 = cell_arch.encode_cell2()
            path_indices = cell_arch.get_path_indices()
            if allow_isomorphisms or path_indices not in dic:
                dic[path_indices] = 1
                data.append(
                    (
                        arch[0],
                        arch[1],
                        arch[2],
                        path_encoding1,
                        arch[4],
                        arch[5],
                        arch[6],
                        path_encoding2
                    )
                )
            if len(data) == num:
                break
        return data

    def nasbench2graph2(self, data):
        matrix, ops = data[0], data[1]
        node_feature = torch.zeros(NUM_VERTICES, 8)
        edges = int(np.sum(matrix))
        edge_idx = torch.zeros(2, edges)
        counter = 0
        for i in range(NUM_VERTICES):
            idx = OPS.index(ops[i])
            node_feature[i, idx] = 1
            for j in range(NUM_VERTICES):
                if matrix[i, j] == 1:
                    edge_idx[0, counter] = i
                    edge_idx[1, counter] = j
                    counter += 1
        return edge_idx, node_feature

    def get_arch_list(self,
                      aux_file_path,
                      distance=None,
                      iteridx=0,
                      num_top_arches=5,
                      max_edits=20,
                      num_repeats=5,
                      random_encoding='adj',
                      verbose=0):
        # Method used for gp_bayesopt

        # load the list of architectures chosen by bayesopt so far
        base_arch_list = pickle.load(open(aux_file_path, 'rb'))
        top_arches = [archtuple[0] for archtuple in base_arch_list[:num_top_arches]]
        if verbose:
            top_5_loss = [archtuple[1][0] for archtuple in base_arch_list[:min(5, len(base_arch_list))]]
            print('top 5 val losses {}'.format(top_5_loss))

        # perturb the best k architectures
        dic = {}
        for archtuple in base_arch_list:
            arch = {'matrix': self.total_archs[archtuple[0]['string']][0][0],
                    'ops': self.total_archs[archtuple[0]['string']][0][1]}
            path_indices = Cell(**arch).get_path_indices()
            dic[path_indices] = 1

        new_arch_list = []
        for arch in top_arches:
            for edits in range(1, max_edits):
                for _ in range(num_repeats):
                    #perturbation = Cell(**arch).perturb(self.nasbench, edits)
                    perturbation = self.mutate_edit(arch['string'], mutation_rate=edits)
                    perturbation_arch = self.total_archs[perturbation][0]
                    path_indices = Cell(matrix=perturbation_arch[0], ops=perturbation_arch[1]).get_path_indices()
                    if path_indices not in dic:
                        dic[path_indices] = 1
                        new_arch_list.append({'string': perturbation})

        # make sure new_arch_list is not empty
        while len(new_arch_list) == 0:
            for _ in range(100):
                random_arch_str = self.random_arch().tostr()
                random_arch = self.total_archs[random_arch_str][0]
                path_indices = Cell(matrix=random_arch[0], ops=random_arch[1]).get_path_indices()
                if path_indices not in dic:
                    dic[path_indices] = 1
                    new_arch_list.append({'string': random_arch_str})

        return new_arch_list

    def mutate_edit(self, arch, mutation_rate=1.0):
        """
        code modified from project https://github.com/naszilla/naszilla
        """
        ops = get_op_list(arch)
        new_ops = []
        # keeping mutation_prob consistent with nasbench_101
        mutation_prob = mutation_rate / (OP_SPOTS - 2)

        for i, op in enumerate(ops):
            if random.random() < mutation_prob:
                available = [o for o in OPS_LIST if o != op]
                new_ops.append(random.choice(available))
            else:
                new_ops.append(op)
        return get_string_from_ops(new_ops)

    @classmethod
    def generate_distance_matrix(cls, arches_1, arches_2, distance):
        matrix = np.zeros([len(arches_1), len(arches_2)])
        for i, arch_1 in enumerate(arches_1):
            for j, arch_2 in enumerate(arches_2):
                if distance == 'adj':
                    matrix[i][j] = adj_distance(arch_1['string'], arch_2['string'])
                elif distance == 'nasbot':
                    matrix[i][j] = nasbot_distance(arch_1['string'], arch_2['string'])
                else:
                    raise ValueError(f'Distance {distance} does not support at present!')
        return matrix

def get_op_list(arch):
    """
    code modified from project https://github.com/naszilla/naszilla
    """
    # given a string, get the list of operations
    tokens = arch.split('|')
    ops = [t.split('~')[0] for i,t in enumerate(tokens) if i not in [0,2,5,9]]
    return ops

def get_string_from_ops(ops):
    """
    code modified from project https://github.com/naszilla/naszilla
    """
    # given a list of operations, get the string
    strings = ['|']
    nodes = [0, 0, 1, 0, 1, 2]
    for i, op in enumerate(ops):
        strings.append(op+'~{}|'.format(nodes[i]))
        if i < len(nodes) - 1 and nodes[i+1] == 0:
            strings.append('+|')
    return ''.join(strings)

def adj_distance(cell_1, cell_2):
    cell_1_ops = get_op_list(cell_1)
    cell_2_ops = get_op_list(cell_2)
    return np.sum([1 for i in range(len(cell_1_ops)) if cell_1_ops[i] != cell_2_ops[i]])

def nasbot_distance(cell_1, cell_2):
    # distance based on optimal transport between row sums, column sums, and ops

    cell_1_ops = get_op_list(cell_1)
    cell_2_ops = get_op_list(cell_2)

    cell_1_counts = [cell_1_ops.count(op) for op in OPS]
    cell_2_counts = [cell_2_ops.count(op) for op in OPS]
    ops_dist = np.sum(np.abs(np.subtract(cell_1_counts, cell_2_counts)))

    return ops_dist + adj_distance(cell_1, cell_2)

if __name__ == '__main__':
    search_space = NASBench201(dataset='cifar10-valid')
    # search_space = NASBench201(dataset='cifar100')
    # search_space = NASBench201(dataset='ImageNet16-120')
    total_val_list = []
    total_test_list = []
    for key in search_space.total_keys:
        total_val_list.append(search_space.total_archs[key][4])
        total_test_list.append(search_space.total_archs[key][5])
    total_val = np.array(total_val_list)
    total_test = np.array(total_test_list)
    idx = np.argmin(total_val)
    print(total_val[idx], total_test[idx], min(total_test_list))


"""
Tests for the ODE Solver ODEint_solver.py module
"""

import sys
import numpy as np
from chemkin import pckg_xml_path
from chemkin.preprocessing.parse_xml import XmlParser
from chemkin.solver.ODEint_solver import ODE_int_solver
from chemkin.reaction.elementary_rxn import ElementaryRxn

def test_ODE_solver_functionality():

    """
    Test basic ODE solver functionality.
    """

    Ti = [1500]
    xi = [2., 1., .5, 1., 1., 1., .5, 1.] # specie concentrations 'rxns_reversible.xml'
    xml_parser = XmlParser(pckg_xml_path('rxns_reversible'))
    parsed_data_list = xml_parser.parsed_data_list(Ti)
    #print(parsed_data_list)
    for parsed_data in parsed_data_list:

        species = parsed_data['species']
        #print(species)
        ki = parsed_data['ki']
        sys_vi_p = parsed_data['sys_vi_p']
        sys_vi_dp = parsed_data['sys_vi_dp']
        T= parsed_data['T']
        b_ki=parsed_data['b_ki']

        rxn = ElementaryRxn(ki, b_ki, xi, sys_vi_p, sys_vi_dp)
        my_solver = ODE_int_solver(T, rxn)

        error_msg = "Solver is not initiating properly"
        assert my_solver != None and isinstance(my_solver,ODE_int_solver),error_msg

def test_ODE_solver_solve():

    """
    Tests ODE solver solve() method.
    """

    Ti = [1500]
    xi = [2., 1., .5, 1., 1., 1., .5, 1.] # specie concentrations 'rxns_reversible.xml'
    xml_parser = XmlParser(pckg_xml_path('rxns_reversible'))
    parsed_data_list = xml_parser.parsed_data_list(Ti)

    for parsed_data in parsed_data_list:

        species = parsed_data['species']
        ki = parsed_data['ki']
        sys_vi_p = parsed_data['sys_vi_p']
        sys_vi_dp = parsed_data['sys_vi_dp']
        T= parsed_data['T']
        b_ki=parsed_data['b_ki']

        rxn = ElementaryRxn(ki, b_ki, xi, sys_vi_p, sys_vi_dp)
        my_solver = ODE_int_solver(T, rxn)

        time_int = time_steps = np.linspace(0, 100, 101)

        s , t_c , t_o =my_solver.solve(time_int)

        error_msg1 = "The dimensions of input do not match output"

        assert s.shape == (len(s),len(xi)),error_msg1

        assert len(t_c)==len(ki) and len(t_c)==len(b_ki),error_msg1

        #error_msg2 = "Reaction has not reached an equilibrium"
        #assert all(i>0 for i in t_c) and t_o >0, error_msg2


# 문제 링크: https://level.goorm.io/exam/88520/%EB%86%80%EC%9D%B4%EA%B3%B5%EC%9B%90/quiz/1

def get_count(area, y, x, k):
    return sum(
        area[i][j] == 1
        for i in range(y, y + k)
        for j in range(x, x + k)
    )

t = int(input())

for _ in range(t):
    n, k = map(int, input().split())
    area = [list(map(int, input().split())) for _ in range(n)]

    counts = [
        get_count(area, i, j, k)
        for i in range(n - k + 1)
        for j in range(n - k + 1)
    ]

    print(min(counts))


import pprint

import click

from . import constants, iapi, utils

@click.group()
@click.option("--verbose/--quiet", "-v/-q", default=False)
def main(verbose: bool):
    """main entry point.
    """
    if verbose:
        iapi.set_verbose_mode()

# ref.
# https://click.palletsprojects.com/en/8.1.x/options/#multi-value-options
# https://click.palletsprojects.com/en/8.1.x/utils/#pager-support
@main.command()
@click.option("--datadir", "-d", default='.')
@click.option("--output", "-o", default=constants.DATABASE_FILEPATH)
@click.option(
    "--zip-filenames", "-Z", nargs=2,
    default=constants.ZIPCODE_ZIP_FILENAMES
)
@click.option(
    "--csv-filenames", "-C", nargs=2,
    default=constants.ZIPCODE_CSV_FILENAMES
)
def initdb(
    datadir: str, output: str,
    zip_filenames: tuple[str, str],
    csv_filenames: tuple[str, str],
):
    """
    Prase csv files extracted from zip files, save resutl data as a db file.
    """
    iapi.initdb(
        datadir, output,
        zip_filenames=zip_filenames, csv_filenames=csv_filenames
    )

@main.command()
@click.option("--db-path", "-d", default=constants.DATABASE_FILEPATH)
@click.argument("zipcode")
def search(db_path: str, zipcode: str):
    """
    Search address info from rhe database file by given zip code.
    """
    res = iapi.search_by_zipcode(zipcode, db_path, limit=0)
    fmt = pprint.pformat

    if len(res) > utils.get_term_lines():
        click.echo_via_pager(fmt(r) for r in res)
    else:
        for zipd in res:
            click.echo(fmt(zipd))


from datetime import datetime
import datetime as dt

from activity.models import EatRainbowActivity
from master.models import EatRainbowMaster

def get_previous_date(date_str):
    """

    :param date_str: date in yyyy-mm-dd formate
    :return:  date in yyyy-mm-dd formate
    """
    date_object = datetime.strptime(date_str, "%Y-%m-%d")
    day = dt.timedelta(days=1)
    reduce_date = date_object - day
    return reduce_date.strftime("%Y-%m-%d")

def get_difference_from_current_date(date_str):
    date_object = datetime.strptime(date_str, "%Y-%m-%d")
    date = datetime.now() - date_object
    return date.days

def user_first_login(user, eat_date):
    """

    this methods takes user and date object
    return eat_activity object matched with master first sequence

    """
    master = EatRainbowMaster.objects.get(sequence=1)
    eat_rainbow_object = EatRainbowActivity.objects.create(user=user, date=eat_date, master=master,
                                                               red_serving=master.red_serving,
                                                               cream_serving=master.cream_serving,
                                                               yellow_serving=master.yellow_serving,
                                                               kiwi_serving=master.kiwi_serving,
                                                               blue_serving=master.blue_serving,
                                                               green_serving=master.green_serving)
    eat_rainbow_object.enjoy_regular.set(master.enjoy_regular.all(), clear=True)
    eat_rainbow_object.eat_more.set(master.eat_more.all(), clear=True)
    eat_rainbow_object.eat_less.set(master.eat_less.all(), clear=True)
    eat_rainbow_object.eat_avoid.set(master.eat_avoid.all(), clear=True)
    eat_rainbow_object.tag.set(master.tag.all(), clear=True)
    eat_rainbow_object.save()
    return eat_rainbow_object


number = int(input())
texts = [] # 문자열 모음
text_dic={} # 문자를 (단어:단어의 개수) 의 딕셔러니로 받음
count =0 # 그룹 단어의 개수

for i in range(number) :
    texts.append(input())
    text = texts[i] # 문자열 모음 중 하나의 문자열

    for j in range(len(text)) :
        if text[j] not in text_dic.keys():
            text_dic[text[j]] = 1
        elif text[j] in text_dic.keys() and text[j] == (text[j-1]) and text_dic[text[j]] != 0 :
            text_dic[text[j]] += 1
        else :
            text_dic[(texts[i])[j]] = 0 # 그룹단어가 아니라면 개수를 0으로 만듬

    if 0 not in text_dic.values() :
        count += 1
    text_dic.clear() # 다음 문자열 체크를 위해 사전 비우기

print(count)


import logging
import os

from aiohttp import ClientError, ClientResponseError
from asyncpg import exceptions
from discord import File, Embed
from discord.ext import commands
from discord.ext.commands import (
    BadArgument,
    NoPrivateMessage,
    CommandError,
    Context,
)
from django.conf import settings

import validators

from dangobot.core.bot import command_handler, DangoBot
from dangobot.core.plugin import Cog
from dangobot.core.helpers import download_file, FileTooLarge

from .models import file_path
from .data import ParsedCommand
from .repository import CommandRepository

logger = logging.getLogger(__name__)

class Commands(Cog):
    """A plugin for configuring custom user-made bot commands."""

    @command_handler
    async def handle_command(self, ctx: Context) -> bool:
        """
        The command handler.

        Handles all incoming command invocations, and checks if there's
        a custom command defined with the given name. If it exists, its
        contents are pulled from the database, and sent to the target channel.

        Arguments:
            message (string): the incoming message
        """
        if not ctx.guild:  # we don't want commands to work in DMs
            return False

        if not ctx.invoked_with:
            return False

        command = await CommandRepository().find_by_trigger(
            ctx.invoked_with, ctx.guild
        )

        if command:
            await self.send_response(ctx, command)
            return True

        return False

    async def send_response(self, ctx: Context, command) -> None:
        """Sends a response for a given custom command database record."""
        params = {"content": command["response"]}

        if command["file"] == "":
            await ctx.send(**params)
        else:
            # TODO: actual asynchronous file read
            with open(
                os.path.join(settings.MEDIA_ROOT, command["file"]), "rb"
            ) as file:
                params["file"] = File(file, command["original_file_name"])
                await ctx.send(**params)

    async def parse_command(self, ctx: Context, *args) -> ParsedCommand:
        """
        Parse the command syntax used for the :func:`add` and :func:`edit`
        functions.

        The format of the command is as follows:
        * the first word is the command trigger,
        * rest of the string is treated as the command response, until the last
          word starts with ``attachment=``,
        * if so, then the last word specifies a file attachment that will be a
          part of the command.

        The attachment is provided as an ``attachment=<url>`` parameter at the
        end of the command. The file under the URL is then downloaded and saved
        in the media location.

        This means that the command response can have a length of zero if you
        only specify the trigger and the attachment.

        Keep in mind that if there is an attachment provided as a part of the
        message (as in: uploaded in Discord, not as as an URL posted in the
        message body), then it will take precedence over the attachment posted
        in the command.

        Returns a four-element tuple where:
        * the first element is a command trigger,
        * the second element is the command response,
        * the third element is a path to an eventual attachment (relative to
          the media directory), if there's no attachment then it is an empty
          string,
        * the fourth element is the orignal file name of the attachment, or
          an empty string if there's no attachment.
        """
        if len(args) < 2 and len(ctx.message.attachments) < 1:
            raise BadArgument("No message content specified!")

        url = ""
        path_relative = ""
        filename = ""

        if args[-1].startswith("attachment="):
            url = args[-1].replace("attachment=", "", 1)

            if not validators.url(url):
                raise commands.BadArgument(
                    message="The provided URL is incorrect!"
                )

            args = args[:-1]

        if len(ctx.message.attachments) > 0:
            url = ctx.message.attachments[0].url

        if url != "":
            filename = url.split("/")[-1]
            # relative path is being saved to the database
            path_relative = file_path(ctx, filename)
            path_absolute = f"{settings.MEDIA_ROOT}/{path_relative}"

            try:
                await download_file(self.bot.http_session, url, path_absolute)
            except ClientError as exc:
                if isinstance(exc, ClientResponseError) and exc.status == 404:
                    raise CommandError(
                        "The requested file was not found!"
                    ) from exc

                logger.error(
                    "An error occured while downloading file %s to %s.",
                    url,
                    path_absolute,
                    exc_info=True,
                )

                raise exc
            except FileTooLarge as exc:
                raise CommandError(str(exc)) from exc

        trigger = args[0]
        response = " ".join(args[1:])

        return ParsedCommand(trigger, response, path_relative, filename)

    @commands.group(name="commands", invoke_without_command=True)
    async def cmds(self, ctx):
        """
        Management of user-defined commands.
        """
        await ctx.send_help("commands")

    @cmds.command(usage="<trigger> (<response>) (attachment=url)")
    @commands.has_permissions(administrator=True)
    async def add(self, ctx: Context, *args):
        """
        Add a new command.

        Parameters:

          * trigger: the string that will trigger executing this command.
          * response: the string that will be sent by this command.\
            Can be empty.
          * url: URL to a file that will be sent by this command.\
            Can be omitted.

        Executing the command without specifying either RESPONSE or ATTACHMENT
        will result in an error. You can also upload an attachment to Discord
        instead of specifying the URL.
        """
        if ctx.guild is None:
            raise NoPrivateMessage("This command cannot be used in a DM")

        command = await self.parse_command(ctx, *args)

        try:
            await CommandRepository().add_to_guild(ctx.guild, command)
        except exceptions.UniqueViolationError as exc:
            raise BadArgument(
                f"Command `{ctx.args[-1]}` already exists!"
            ) from exc

        await ctx.send(f"Command `{command.trigger}` added successfully!")

    @cmds.command()
    async def list(self, ctx: Context):
        """
        List all commands defined in the server.
        """
        if ctx.guild is None:
            raise NoPrivateMessage("This command cannot be used in a DM")

        command_list = await CommandRepository().find_all_from_guild(ctx.guild)

        embed = Embed()
        embed.title = "Available custom commands:"
        embed.description = "\n".join(
            map(
                lambda c: f"{ctx.prefix}{c['trigger']}",
                command_list,
            )
        )

        await ctx.send(embed=embed)

    @cmds.command()
    @commands.has_permissions(administrator=True)
    async def delete(self, ctx: Context, trigger: str):
        """
        Deletes a command from the server.
        """
        if ctx.guild is None:
            raise NoPrivateMessage("This command cannot be used in a DM")

        deleted = await CommandRepository().delete_from_guild(
            trigger, ctx.guild
        )

        if deleted:
            message = "Command `{}` deleted successfully!"
        else:
            message = "Command `{}` does not exist!"

        await ctx.send(content=message.format(trigger))

    @cmds.command(usage="<trigger> (<response>) (attachment=url)")
    @commands.has_permissions(administrator=True)
    async def edit(self, ctx: Context, *args):
        """
        Edit an existing command.

        Has the same parameters as the add command.
        """
        if ctx.guild is None:
            raise NoPrivateMessage("This command cannot be used in a DM")

        command = await self.parse_command(ctx, *args)

        updated = await CommandRepository().update_in_guild(ctx.guild, command)

        if updated:
            message = "Command `{}` updated successfully!"
        else:
            message = "Command `{}` does not exist!"

        await ctx.send(content=message.format(command.trigger))

async def setup(bot: DangoBot):  # pylint: disable=missing-function-docstring
    await bot.add_cog(Commands(bot))


#!/bin/bash python
import argparse
import os
import json
import time
import logging
import fitz

st = time.time()

def process_text(filename, filepath):
    # time.sleep(180)

    output_folder = "/home/flask/app/output_files"
    all_paths = []

    file_at = f"{output_folder}/{filename}"
    if not os.path.exists(file_at):
        return []

    doc = fitz.open(file_at)
    for i in range(len(doc)):
        for img in doc.getPageImageList(i):
            xref = img[0]
            pix = fitz.Pixmap(doc, xref)

            file_out = f"{output_folder}/{filename}_p%s-%s.png" % (i, xref)
            all_paths.append(f"output_files/{filename}_p%s-%s.png" % (i, xref))

            if pix.n < 5:       # this is GRAY or RGB
                pix.writePNG(file_out)
            else:               # CMYK: convert to RGB first
                pix1 = fitz.Pixmap(fitz.csRGB, pix)
                pix1.writePNG(file_out)
                pix1 = None
            pix = None

    return all_paths

def main(id="", uuid="", filename="", filepath=""):
    processed_body = process_text(filename, filepath)
    ajson = {}
    return processed_body

usage = """
    Minimal app

	Usage:

    # Use text buffer
    python3 main.py -i id_of_item -t "text buffer" -l
	"""

if __name__ == "__main__":
    # Handle arguments
    parser = argparse.ArgumentParser(
        description="Minimal app",
        epilog=usage,
        formatter_class=argparse.RawDescriptionHelpFormatter)
    parser.add_argument("-i", help="Item id", type=str, default="1")
    parser.add_argument("-t", help="Text to be processed", type=str, default="")
    args = parser.parse_args()

    uuid = args.i
    body = args.t

    result = main(
        id="", uuid=uuid, filename=body, filepath=""
    )

    print(result)
    print("~~ finished in {0:.3f} sec ~~".format(time.time() - st))


from datetime import datetime
import time
now = datetime.now()

i = 0
while i < 10:
    i+=1
    time.sleep(1)
    stampTime = datetime.now()
    print(datetime.now())

# returns (minutes, seconds)
diff = stampTime - now
print(now)
print(stampTime)
print(diff)
print(diff.total_seconds())
minutes = divmod(diff.total_seconds(), 60)
print('Total difference in minutes: ', minutes[0], 'minutes', minutes[1], 'seconds')


from functools import wraps
import operator

def err(f):
    @wraps(f)
    def wrapper(*a,**kw):
        try:
            return f(*a,**kw)
        except Exception as e:
            return DotDict()
    return wrapper

class DotDict(dict):
    __getattr__ = dict.__getitem__
    __setattr__ = dict.__setitem__
    __delattr__ = dict.__delitem__
    def __init__(self, dct={}):
        for key, value in dct.items():
            if hasattr(value, 'keys'):
                value = DotDict(value)
            self[key] = value
    def __missing__(self, key):
        self[key] = DotDict()
        return self[key]

def dotset(obj, keys, value):
    attrs = keys.split('.')
    target = obj
    if '.' in keys:
        target = dotget(obj, '.'.join(attrs[:-1]))
    setattr(target, attrs[-1], value)

def dotget(obj, attr):
    return reduce(getattr, attr.split('.'), obj)

def compare_object_values(a, b, attrs, cmp=lambda x,y: x==y, cmp_value=lambda x: x, flat=True, allow_empty_values=False):
    ac = DotDict()
    bc = DotDict()
    changes = DotDict()
    for key in attrs:
        setattr(ac, key, dotget(a, key))
        setattr(bc, key, dotget(b, key))
    for key in attrs:
        if not cmp(dotget(ac, key), dotget(bc, key)):
            value = dotget(ac, cmp_value(key))
            if not allow_empty_values and not value:
                continue
            if flat:
                setattr(changes, key, dotget(ac, key))
            else:
                dotset(changes, key, dotget(ac, key))
    return changes


import time
import numpy as np
import pybullet as pb
import pybullet_data

class my_robot:
    def __init__(self,base_position_global,final_pos,final_vel,final_acc,c_m,c_d,c_k):
        #all configuration and loading here
        pb.connect(pb.GUI)
        pb.setAdditionalSearchPath(pybullet_data.getDataPath())
        pb.setGravity(0, 0, -9.8)
        pb.loadURDF("plane.urdf")
        path = r"D:\Ivlabs\Manipulator-robotics\urdfs of manipulators\git-repo-cloned\urdf\ur5.urdf"
        self.robotID = pb.loadURDF(path,base_position_global,useFixedBase=True)
        self.endPostition=final_pos #orientation and position both
        self.endVelocity=final_vel
        self.endAcceleration=final_acc
        self.desired_M = c_m*np.eye(6)
        self.desired_D = c_d*np.eye(6)
        self.desired_K = c_k*np.eye(6)
        self.num_joints = pb.getNumJoints(self.robotID)
        self.revolutes=[]
        for i in range(self.num_joints):
            temp = pb.getJointInfo(self.robotID,i)
            if(temp[2]==0):
                self.revolutes.append(i)
    def robotJointstates(self):
        #returns the positions,velocities and forces on all joints as lists
        jointState_temp = pb.getJointStates(self.robotID,self.revolutes)
        jointPositions = [i[0] for i in jointState_temp]
        jointVelocities = [i[1] for i in jointState_temp]
        jointForces = [i[2] for i in jointState_temp]
        return np.array(jointPositions),np.array(jointVelocities),np.array(jointForces)
    def dynamicMatrices(self,joint_pos,joint_vel):
        #returns M,C and G of the dynamic torque equation
        gravity_matrix = np.array(pb.calculateInverseDynamics(self.robotID,joint_pos,[0]*len(self.revolutes),[0]*len(self.revolutes)))
        coriolis_matrix = np.array(pb.calculateInverseDynamics(self.robotID,joint_pos,joint_vel,[0]*len(self.revolutes)))-gravity_matrix
        mass_matrix = np.array(pb.calculateMassMatrix(self.robotID,joint_pos))
        return mass_matrix,coriolis_matrix,gravity_matrix
    def jacobian_and_inverse(self):
        #returns jv and jomega concatenated and their inverse
        jointState_temp = pb.getJointStates(self.robotID,self.revolutes)
        jointPositions = [i[0] for i in jointState_temp]
        jointVelocities = [i[1] for i in jointState_temp]
        pos,vel = jointPositions,jointVelocities
        jv,jo = pb.calculateJacobian(self.robotID,7,[0,0,0],pos,vel,[0,0,0,0,0,0])
        jacobian = np.concatenate((jo,jv),axis=0)
        return jacobian,np.linalg.pinv(jacobian)
    def initialse_robot_joints(self):
        #removes all forces from joints
        zeroVect = np.zeros(6)
        pb.setJointMotorControlArray(self.robotID,self.revolutes,pb.VELOCITY_CONTROL,forces=zeroVect)
#class definition done

arm = my_robot(base_position_global=[0,0,0],final_pos=np.array([0,0,0,0.35,0.6,1.25]),final_vel=[0,0,0,0,0,0],final_acc=[0,0,0],c_m=0.001,c_d=0.02,c_k=0.05)
arm.initialse_robot_joints()

end_pos_e=0
end_vel_e=0
forcex = pb.addUserDebugParameter("force x",0,0.1,0)
forcey = pb.addUserDebugParameter("force y",0,0.1,0)
forcez = pb.addUserDebugParameter("force z",0,0.1,0)

to_run = int(input("Enter 1 to start the simulation: "))
if(to_run):
    while True:
        fx = pb.readUserDebugParameter(forcex)
        fy = pb.readUserDebugParameter(forcey)
        fz = pb.readUserDebugParameter(forcez)
        F_external = np.array([[0],[0],[0],[-fx],[-fy],[-fz]])
        pb.applyExternalForce(arm.robotID, 7, [fx, fy, fz], [0, 0, 0], pb.LINK_FRAME)
        J_g,J_inv = arm.jacobian_and_inverse()
        pos_current,vel_current,_ = arm.robotJointstates()
        end_pos = np.array(pb.getLinkState(arm.robotID,7)[0])
        end_pos = np.pad(end_pos,(3,0),'constant',constant_values=(0,0))
        end_vel = np.dot(J_g,vel_current)
        end_vel_e = arm.endVelocity-end_vel
        end_pos_e=arm.endPostition-end_pos
        m_matrix,c_matrix,g_matrix = arm.dynamicMatrices(list(pos_current),list(vel_current))
        M_x = np.dot(np.dot(np.transpose(J_inv),m_matrix),J_inv)
        temp = np.dot((np.dot(np.linalg.inv(arm.desired_M),M_x)-np.eye(6)),F_external)
        F = np.dot(np.dot(np.linalg.inv(arm.desired_M),M_x),(np.dot(arm.desired_D,end_vel_e)+np.dot(arm.desired_K,end_pos_e))) + np.squeeze(temp)
        torque = g_matrix+np.dot(np.transpose(J_g),F)
        pb.setJointMotorControlArray(arm.robotID, arm.revolutes, pb.TORQUE_CONTROL, forces=list(torque))
        pb.stepSimulation()
        time.sleep(1 / 100)


from time import sleep
from kafka import KafkaProducer
from json import dumps

producer = KafkaProducer(
    value_serializer=lambda m: dumps(m).encode(),
    bootstrap_servers=['localhost']
)

for i in range(3):
    producer.send('quickstart-events', value='009')
    sleep(0.001)


import matplotlib.pyplot as plt
x1 = [1,2,3,4,5,6]
y1 = [2,4,6,18,12,12]

x2 = [2,6,8]
y2 = [6,4,9]

plt.plot(x2,y2,linestyle=":")
plt.plot(x1,y1)
plt.title("test",fontsize=20, color="red")
plt.xlabel("x-axis")

plt.show()


## 字符串的排列
# 滑动窗口依次比较排序后的s1和s2中相同位数排序后的值，若相等则返回T（超时）

class Solution(object):
    def checkInclusion(self, s1, s2):
        """
        :type s1: str
        :type s2: str
        :rtype: bool
        """
        tem = sorted(s1)
        lll = len(tem)
        for i in range(len(s2)):
            if s2[i] in tem:
                if sorted(s2[i:i+lll]) == tem:
                    return True
        return False

# 建立dict存储s1中数字出现次数， dict2存储s1长度内数字出现次数，若二者相等，则T；
# 否则dict2中第一个记录的出现次数-1；更新dict2

class Solution(object):
    def checkInclusion(self, s1, s2):
        """
        :type s1: str
        :type s2: str
        :rtype: bool
        """
        tmp = set(list(s1))
        lll = len(s1)
        if lll >= len(s2):
            return sorted(s1) == sorted(s2)
        dict = {}
        for i in tmp:
            dict[i] = dict.get(i, 0) + s1.count(i)

        dict2 = {}
        for i in range(0, lll):
            dict2[s2[i]] = dict2.get(s2[i], 0) + 1
        for i in range(lll, len(s2)+1):

            if dict == dict2:
                return True
            elif i == len(s2):
                return False
            else:
                if dict2[s2[i - lll]] != 1:
                    dict2[s2[i - lll]] -= 1
                else:
                    del dict2[s2[i - lll]]
                dict2[s2[i]] = dict2.get(s2[i], 0) + 1
        return False


from .models import Article, Comment
from slugify import slugify
from django import forms
from djrichtextfield.widgets import RichTextWidget

class ArticleForm(forms.ModelForm):
    """ Form to create an article """
    title = forms.CharField(max_length=200)

    def save(self, commit=True):
        instance = super().save(commit=False)
        # Set the slug value from the title
        instance.slug = slugify(instance.title)
        if commit:
            instance.save()
        return instance

    class Meta:
        model = Article
        fields = ['title', 'featured_image', 'image_alt', 'excerpt', 'content']

        contents = forms.CharField(widget=RichTextWidget())

        widget = {
            "excerpt": forms.Textarea(attrs={"rows": 5}),
        }

        labels = {
            "title": "Article Title",
            "featured_image": "Article Image",
            "image_alt": "Describe Image",
            "excerpt": "Excerpt",
            "content": "Content",
        }

class CommentForm(forms.ModelForm):
    class Meta:
        model = Comment
        fields = ('body',)


#%%
# ─── Challenge 1 ──────────────────────────────────────────────────────────────

import numpy as np

with open('input08') as file:
    lines = file.read().splitlines()

matrix_tree_heights = np.zeros((len(lines), len(lines[0])), dtype=int)
for i, line in enumerate(lines):
    for j, num in enumerate(line):
        matrix_tree_heights[i,j] = int(num)

matrix_visible_trees = np.ones(matrix_tree_heights.shape, dtype=int)
matrix_visible_trees[1:-1, 1:-1] = 0

def c1_check_vis_top_to_down():
    for x in range(1, matrix_tree_heights.shape[1]-1):
        level = matrix_tree_heights[0, x]
        for y in range(1, matrix_tree_heights.shape[0]):
            if matrix_tree_heights[y, x] > level:
                matrix_visible_trees[y, x] = 1
            level = max(matrix_tree_heights[y, x], level)

c1_check_vis_top_to_down()
matrix_tree_heights = np.flip(matrix_tree_heights, axis=0)
matrix_visible_trees = np.flip(matrix_visible_trees, axis=0)
c1_check_vis_top_to_down()
matrix_tree_heights = matrix_tree_heights.transpose()
matrix_visible_trees = matrix_visible_trees.transpose()
c1_check_vis_top_to_down()
matrix_tree_heights = np.flip(matrix_tree_heights, axis=0)
matrix_visible_trees = np.flip(matrix_visible_trees, axis=0)
c1_check_vis_top_to_down()

print(np.count_nonzero(matrix_visible_trees))

# ─── Challenge 2 ──────────────────────────────────────────────────────────────

def c2_count_trees_for_y_x(y, x, matrix):
    def find_trees_top_down(y, x, matrix):
        level = 0
        tree_counter = 0
        for y_i in range(y+1, matrix.shape[1]):
            height = matrix[y_i,x]
            if height >= matrix[y,x]:
                tree_counter += 1
                break
            else:
                tree_counter += 1
                if height >= level:
                    level = height
        return tree_counter

    score = 1
    score *= find_trees_top_down(y, x, matrix)
    matrix = np.flip(matrix, axis=0)
    score *= find_trees_top_down(matrix.shape[0]-y-1, x, matrix)
    matrix = matrix.transpose()
    score *= find_trees_top_down(x, matrix.shape[0]-y-1, matrix)
    matrix = np.flip(matrix, axis=0)
    score *= find_trees_top_down(matrix.shape[1]-x-1, matrix.shape[0]-y-1, matrix)
    return score

max_score = 0
for y, x in np.ndindex(matrix_tree_heights.shape):
    score = c2_count_trees_for_y_x(y, x, matrix_tree_heights)
    if score > max_score:
        max_score = score
print(max_score)


"""
https://leetcode.cn/problems/count-symmetric-integers/
2843. 统计对称整数的数目
提示
简单
7
相关企业
给你两个正整数 low 和 high 。

对于一个由 2 * n 位数字组成的整数 x ，如果其前 n 位数字之和与后 n 位数字之和相等，则认为这个数字是一个对称整数。

返回在 [low, high] 范围内的 对称整数的数目 。

示例 1：

输入：low = 1, high = 100
输出：9
解释：在 1 到 100 范围内共有 9 个对称整数：11、22、33、44、55、66、77、88 和 99 。
示例 2：

输入：low = 1200, high = 1230
输出：4
解释：在 1200 到 1230 范围内共有 4 个对称整数：1203、1212、1221 和 1230 。

提示：

1 <= low <= high <= 10**4
"""
"""
思路：直接枚举+模拟
数据量很小，枚举没问题
"""
class Solution:
    def countSymmetricIntegers(self, low: int, high: int) -> int:
        ans = 0
        for num in range(low, high + 1):    # 遍历数组
            if self.is_half(num):
                ans += 1
        return ans

    def is_half(self, num):
        num_str = str(num)
        num_len = len(num_str)
        if num_len % 2 != 0:   # 非偶数个数组成的数
            return False
        left_sum = 0
        for idx in range(num_len // 2):
            left_sum += int(num_str[idx])
        right_sum = 0
        for idx in range(num_len//2, num_len):
            right_sum += int(num_str[idx])
        return left_sum == right_sum

if __name__ == '__main__':
    oSolute = Solution()
    assert oSolute.countSymmetricIntegers(1, 100) == 9
    assert oSolute.countSymmetricIntegers(1200, 1230) == 4


from turtle import Turtle, shapesize
import random

COLORS = ["red", "orange", "yellow", "white", "blue", "purple","coral","pink","grey"]

class CarManager:
    def __init__(self):

        self.STARTING_MOVE_DISTANCE = 5
        self.MOVE_INCREMENT = 5
        self.all_cars=[]
        self.car_speed=self.MOVE_INCREMENT

    def car_maker(self):
        chance=random.randint(1,6)
        if chance==6:
            car = Turtle("square")
            car.penup()
            car.shapesize(stretch_len=2, stretch_wid=1)
            car.speed(0.1)
            car.color(random.choice(COLORS))
            car.goto(280, random.randint(-250, 250))
            self.all_cars.append(car)

    def car_mover(self):
        for car in self.all_cars:
            car.backward(self.car_speed)
    def level_up(self):
        self.car_speed+=self.MOVE_INCREMENT


import numpy as np
import sys,os
import cv2
caffe_root = '/home/wxx/develop/caffe-ssd/'
sys.path.insert(0, caffe_root + 'python')
import caffe
import shutil
import time

caffe.set_mode_gpu()

net_file= '../example/MobileNetSSD_deploy.prototxt'
caffe_model='../snapshot/r/mobilenet_iter_28000.caffemodel'
test_dir = "images"

if not os.path.exists(caffe_model):
    print(caffe_model + " does not exist")
    exit()
if not os.path.exists(net_file):
    print(net_file + " does not exist")
    exit()
net = caffe.Net(net_file,caffe_model,caffe.TEST)

CLASSES = ('background','person','test')

def preprocess(src):
    img = cv2.resize(src, (300,300))
    img = img - 127.5
    img = img * 0.007843
    return img

def postprocess(img, out):
    h = img.shape[0]
    w = img.shape[1]
    box = out['detection_out'][0,0,:,3:7] * np.array([w, h, w, h])

    cls = out['detection_out'][0,0,:,1]
    conf = out['detection_out'][0,0,:,2]
    return (box.astype(np.int32), conf, cls)

def detect(origimg):
    result = 0
    img = preprocess(origimg)

    img = img.astype(np.float32)
    img = img.transpose((2, 0, 1))

    net.blobs['data'].data[...] = img
    out = net.forward()
    start_time = time.time()
    box, conf, cls = postprocess(origimg, out)
    # if len(box) <= 0:
    #     return -5
    for i in range(len(box)):
        p1 = (box[i][0], box[i][1])
        p2 = (box[i][2], box[i][3])
        print (p1)
        print (p2)
        # if box[i][0] <=0 or box[i][1] <= 0 or box[i][2] <= 0 or box[i][3] <= 0:
        #     return -4
        # site =
        if int(cls[i]) == 1:
            cv2.rectangle(origimg, p1, p2, (0,255,255))
        elif int(cls[i]) > 1:
            break
        else:
            cv2.rectangle(origimg, p1, p2, (255,0,0))
        p3 = (max(p1[0], 15), max(p1[1], 15))
        title = "%s:%.2f:%d" % (CLASSES[int(cls[i])], conf[i],i)
        cv2.putText(origimg, title, p3, cv2.FONT_ITALIC, 0.6, (255, 0, 0), 1)
        if int(cls[i]) == 1:
            result = 1

    cv2.imshow("SSD", origimg)
    k = cv2.waitKey(1) & 0xff

    # k = cv2.waitKey(0) & 0xff
        #Exit if ESC pressed
    if k == 27 : result = -1
    return result

######## video  ##############
if __name__ == '__main__':
    cap = cv2.VideoCapture('/home/wxx/develop/demo4/video/walk2/test39.mp4')
    while(1):
        ret, img = cap.read()
        detect(img)

######## img  ##############
# if __name__ == '__main__':
#     img = cv2.imread("/home/wxx/testimg/02563.jpg")
#     witch = detect(img)

######## photo_test ##############
# if __name__ == '__main__':
#     imgpath = '/home/wxx/testimg/'
#     witch = 0
#     for i1 in range(0,9):
#         if witch == -1:
#             break
#         for i2 in range(0,9):
#             if witch == -1:
#                 break
#             for i3 in range(0,9):
#                 if witch == -1:
#                     break
#                 for i4 in range(0,9):
#                     imgname = '0' + str(i1) + str(i2) + str(i3) + str(i4) + '.jpg'
#                     imgfile = imgpath + imgname
#                     img = cv2.imread(imgfile)
#                     try:
#                         img.shape
#                         witch = detect(img)
#                     except:
#                         print('fail to read '+imgfile)
#                         continue

######## photo_result  ##############
# if __name__ == '__main__':
#     imgpath = '/home/wxx/img/person_data/JPEGImages/'
#     witch = 0
#     width = 1080
#     height = 720
#     sz = (width, height)
#     fps = 1
#     fourcc = cv2.VideoWriter_fourcc(*'XVID')
#     vout = cv2.VideoWriter('output.avi', fourcc, 20.0, sz, True)
#     back_img = np.zeros((720, 1080, 3), dtype=np.uint8)
#     # vout.open()
#     for i1 in range(0,9):
#         if witch == -1:
#             break
#         for i2 in range(0,9):
#             if witch == -1:
#                 break
#             for i3 in range(0,9):
#                 if witch == -1:
#                     break
#                 for i4 in range(0,9):
#                     imgname = '0' + str(i1) + str(i2) + str(i3) + str(i4) + '.jpg'
#                     imgfile = imgpath + imgname
#                     img = cv2.imread(imgfile)
#                     try:
#                         img.shape
#                         witch = detect(img)
#                         # back_img.fill(0)
#                         # for w in range(img.shape[1]):
#                         #     for h in range(img.shape[0]):
#                         #         back_img[h, w] = img[h, w]
#                         # vout.write(back_img)
#                         # pirnt('running')
#                         cv2.imwrite('result/'+imgname, img)
#                     except:
#                         print('fail to read '+imgfile)
#                         continue
#     vout.release()

######## copy  ##############
# if __name__ == '__main__':
#     imgpath = '/media/wxx/系统公用/add_data/'
#     witch = 0
#     print ('ok')
#     for i1 in range(0,9):
#         if witch == -1:
#             break
#         for i2 in range(0,9):
#             if witch == -1:
#                 break
#             for i3 in range(0,9):
#                 if witch == -1:
#                     break
#                 for i4 in range(0,9):
#                     imgname = '0' + str(i1) + str(i2) + str(i3) + str(i4) + '.jpg'

#                     imgfile = imgpath + imgname
#                     img = cv2.imread(imgfile)
#                     try:
#                         img.shape
#                         witch = detect(img)
#                         if witch == -4 or witch == -5:
#                             newname = '/home/wxx/testimg/' + imgname
#                             shutil.copyfile(imgfile,newname)
#                         elif witch == -1:
#                             break
#                     except:
#                         print('fail to read '+imgfile)
#                         continue


"""
Write an algorithm to determine if a number is "happy".

A happy number is a number defined by the following process: Starting with any positive
integer, replace the number by the sum of the squares of its digits, and repeat the process
until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does
not include 1. Those numbers for which this process ends in 1 are happy numbers.

Example:
    Input: 19
    Output: true
    Explanation:
    1^2 + 9^2 = 82
    8^2 + 2^2 = 68
    6^2 + 8^2 = 100
    1^2 + 0^2 + 0^2 = 1
"""

class Solution:
    def isHappy(self, n: int) -> bool:
        """
            tortoise and hare for detecting loop
        """
        def get_next(num: int) -> int:
            total_sum = 0
            while num > 0:
                num, digit = divmod(num, 10)
                total_sum += digit * digit

            return total_sum

        tortoise = n
        hare = get_next(n)
        while hare != 1 and hare != tortoise:
            tortoise = get_next(tortoise)
            hare = get_next(get_next(hare))

        return hare == 1

    def isHappy1(self, n):    # 28ms
        def helper(n):
            res = 0
            n = str(n)
            for s in n:
                res += int(s) * int(s)
            return res

        while n >= 10:
            n = helper(n)

        return n in [1, 7]

    def isHappy2(self, n):    # 28ms
        def helper(n):
            res = 0
            while n > 0:
                res += (n % 10) * (n % 10)
                n //= 10
            return res

        while n >= 10:
            n = helper(n)

        return n in [1, 7]

    def isHappy3(self, n):    # 24ms
        used_nums = {}
        while (n != 1) and (n not in used_nums):
            used_nums[n] = 1
            n = sum(int(s) * int(s) for s in str(n))
        return n == 1


from urllib import parse
from markupsafe import Markup

def varencode(s):
    """
    URL encode string after first replacing spaces with underscores.
    :param s: String to url encode.
    :type s: basestring
    :return: URL-encoded string.
    """
    if type(s) == 'Markup':
        s = s.unescape()
    s = s.replace(' ', '_')
    s = s.encode('utf8')
    s = parse.quote_plus(s)
    return Markup(s)

def varunencode(s):
    """
    Unencode string url-encoded with varencode() to return it to its original readable state.
    :param s: String to unencode.
    :type s: basestring
    :return: Unencoded string.
    """
    s = s.replace('_', ' ')
    return parse.unquote(s)


#!/usr/bin/env python3

import redis
import json
from collections import defaultdict
from datetime import datetime
import re
from uuid import uuid4

def nano_valid_address(string):
    p = re.compile('^(nano|xrb)_[13]{1}[13456789abcdefghijkmnopqrstuwxyz]{59}$')
    return p.match(string)

def dpow_address(string):
    return string == "nano_1dpowzkw9u6annz4z48aixw6oegeqicpozaajtcnjom3tqa3nwrkgsk6twj7" or string == "xrb_1dpowzkw9u6annz4z48aixw6oegeqicpozaajtcnjom3tqa3nwrkgsk6twj7"

r = redis.StrictRedis(host="localhost", port=6379)

clients = r.smembers("clients")
clients = {c.decode("utf-8") for c in clients}

snapshot = defaultdict(lambda: {"precache": 0, "ondemand": 0, "id": str(uuid4())})
payouts = defaultdict(lambda: {"precache": 0, "ondemand": 0, "id": str(uuid4())})

for client in clients:
    if not nano_valid_address(client):
        print("!Skipping client '{}' as it is an invalid Nano account!\n\n".format(client))
        continue
    if dpow_address(client):
        print("!Skipping '{}' as it is the dpow account!\n\n".format(client))
        continue
    client_info = r.hgetall(f"client:{client}")
    if not client_info:
        continue
    print(client, client_info)

    for work in ('precache', 'ondemand'):
        work_enc = str.encode(work, "utf-8")
        if work_enc in client_info:
            amount = int(client_info[work_enc])
            snapshot_enc = str.encode("snapshot_"+work, "utf-8")
            snapshot_amount = int(client_info.get(snapshot_enc, 0))
            payout_amount = amount - snapshot_amount
            if payout_amount < 50:
                print(f"Skipping {work}, only did {payout_amount} since last snapshot.")
                continue
            snapshot[client][work] += snapshot_amount
            payouts[client][work] += payout_amount
            r.hset(f"client:{client}", snapshot_enc.decode("utf-8"), amount)
    print("\n")

now = f"{datetime.now():%Y-%m-%d_%H-%M-%S}"

payouts = dict(payouts)
with open(f"payouts_{now}.json", "w") as f:
    json.dump(payouts, f, indent=4)

snapshot = dict(snapshot)
with open(f"snapshot_{now}.json", "w") as f:
    json.dump(snapshot, f, indent=4)

print(f"Updated DB and wrote to files with timestamp {now}")


from django.shortcuts import render, redirect
from django.http import HttpResponse
from .forms import RecipeForm, IngredientForm
from django.views.generic import DetailView
from .models import Recipe, Ingredient, Association_Ingredient_Recipes
import re

def index(request):
    recipes = Recipe.objects.all()
    return render(request, 'books/index.html', {'recipes':recipes})

class RecipesDetailView(DetailView):
    model = Recipe
    template_name = 'books/details_view.html'
    context_object_name = 'recipes'

def create(request):
    error = ''
    if request.method == 'POST':
        form = RecipeForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('recipe_list')
        else:
            error = 'Incorrect form'

    form = RecipeForm()
    data = {
        'form': form,
        'error': error,
    }
    return render(request, 'books/create.html', data)
# Create your views here.

def all_recipes(request):
    if request.method == "POST":
        searched_dishes = request.POST['recipe_or_name'].lower()
        searched_ingredients = re.split("[\s,\\+]*[\\+,\s,\\,]",request.POST['ingredients'].lower())
        searched_objects = Recipe.objects.all()
        searched = 0
        if searched_dishes:
            searched_objects = Recipe.objects.filter(name__contains= searched_dishes)
        searched = len(searched_ingredients)

        for word in searched_ingredients:
            if word == '':
                continue
            searched_objects = searched_objects.filter(ingredients__name__contains=word)
    else:
        searched_dishes = ""
        searched_ingredients = [""]
        searched_objects = Recipe.objects.all()
        searched = 1

    return render(request, 'books/recipes.html', {'recipe_list':searched_objects,
                                                  'searched_dishes':searched_dishes,
                                                  'searched_ingredients': searched_ingredients,
                                                  'searched':searched,
                                                  })


#! /usr/bin/env python

import numpy
import sys

fileName = 'test_pairs.txt';
tests = numpy.loadtxt(fileName, dtype=int)
bytes = int(sys.argv[1])

initcode = ''
initcode = initcode + '    pattern.resize(' + str(bytes*8) + ');';
initcode = initcode + '\n'

for i in range(bytes*8):
    x1, y1, x2, y2 = tests[i, :]
    initcode = initcode + '    pattern[' + str(i) + '].first.first = ' + str(x1) + '; pattern[' + str(i) + '].first.second = ' + str(y1) + '; '
    initcode = initcode + 'pattern[' + str(i) + '].second.first = ' + str(x2) + '; pattern[' + str(i) + '].second.second = ' + str(y2) + ';'
    initcode = initcode + '\n'

output = 'initcode_' + str(bytes) + '.i'
file = open(output, 'w')
file.write(initcode)
file.close()

code = ''
code = code + '    for (int i = 0; i < (int)keypoints.size(); ++i)'
code = code + '\n'
code = code + '    {'
code = code + '\n'
code = code + '        uchar* desc = descriptors.ptr(i);'
code = code + '\n'
code = code + '        const KeyPoint& pt = keypoints[i];'
code = code + '\n\n'

for byte in range(bytes):
    code = code + '        desc[' + str(byte) + '] ='
    for i in range(8):

        index = byte*8 + i;

        code = code + '((smoothedSum(sum, pt, pattern[' + str(index) + '].first.second, pattern[' + str(index) + '].first.first) < '
        code = code + 'smoothedSum(sum, pt, pattern[' + str(index) + '].second.second, pattern[' + str(index) + '].second.first)) << ' + str(7 - i) + ')'
        if i == 7:
            code = code + ';'
            code = code + '\n'
        else:
            code = code + ' +\n                '
code = code + '    }'

output = 'code_' + str(bytes) + '.i'
file = open(output, 'w')
file.write(code)
file.close()


from typing import List
import heapq

def solution(n: int, edge: List[int]) -> int:
    answer = 0
    arr = [[] for _ in range(n+1)]
    distance = [float('inf')]*(n+1)
    for e in edge:
        arr[e[0]].append((e[1], 1))
        arr[e[1]].append((e[0], 1))

    q = []
    heapq.heappush(q, (0, 1))
    distance[1] = 0
    while q:
        dist, now = heapq.heappop(q)

        if distance[now] < dist:
            continue

        for i in arr[now]:
            cost = dist + i[1]
            if cost < distance[i[0]]:
                distance[i[0]] = cost
                heapq.heappush(q, (cost, i[0]))

    max_num = 0
    for num in distance[1:]:
        if num > max_num:
            max_num = num
            answer = 1
        elif num == max_num:
            answer += 1
    return answer


# -*- coding: utf-8 -*-
"""
Created on Tue May 18 15:46:58 2021

@author: LF
"""

import numpy as np
from scipy import stats

BAV_Num = int(input('BAV数目：'))
BAV_Avr = float(input('BAV均值：'))
BAV_B = float(input('BAV标准差：'))
TAV_Num = int(input('TAV数目：'))
TAV_Avr = float(input('TAV均值：'))
TAV_B = float(input('TAV标准差：'))

Avr = abs(BAV_Avr-TAV_Avr)
C1_Num = np.square(BAV_B)/BAV_Num
C2_Num = np.square(TAV_B)/TAV_Num
C = np.sqrt(C1_Num+C2_Num)
Z = Avr/C
print(Z)

Sw = pow(((BAV_Num-1)*pow(BAV_B,2)+(TAV_Num-1)*pow(TAV_B,2))/BAV_Num+TAV_Num-2,0.5)
Se = Sw*pow((1/BAV_Num + 1/TAV_Num),0.5)
T = Avr/ Se
print(T)
print(BAV_Num+TAV_Num-2)


from django.urls import path
from .views import Home, Search, view_article

urlpatterns = [

    path('article/<int: article_id>', view_article, name='view-article'),
    path('', Home.as_view(), name='home'),
    path('search/', Search.as_view(), name='search'),

]


from network import Network

class GoogLeNet(Network):
    def setup(self):
        (self.feed('data')
             .conv(7, 7, 64, 2, 2, name='conv1')
             .max_pool(3, 3, 2, 2, name='pool1')
             .lrn(2, 2e-05, 0.75, name='norm1')
             .conv(1, 1, 64, 1, 1, name='reduction2')
             .conv(3, 3, 192, 1, 1, name='conv2')
             .lrn(2, 2e-05, 0.75, name='norm2')
             .max_pool(3, 3, 2, 2, name='pool2')
             .conv(1, 1, 96, 1, 1, name='icp1_reduction1')
             .conv(3, 3, 128, 1, 1, name='icp1_out1'))

        (self.feed('pool2')
             .conv(1, 1, 16, 1, 1, name='icp1_reduction2')
             .conv(5, 5, 32, 1, 1, name='icp1_out2'))

        (self.feed('pool2')
             .max_pool(3, 3, 1, 1, name='icp1_pool')
             .conv(1, 1, 32, 1, 1, name='icp1_out3'))

        (self.feed('pool2')
             .conv(1, 1, 64, 1, 1, name='icp1_out0'))

        (self.feed('icp1_out0',
                   'icp1_out1',
                   'icp1_out2',
                   'icp1_out3')
             .concat(3, name='icp2_in')
             .conv(1, 1, 128, 1, 1, name='icp2_reduction1')
             .conv(3, 3, 192, 1, 1, name='icp2_out1'))

        (self.feed('icp2_in')
             .conv(1, 1, 32, 1, 1, name='icp2_reduction2')
             .conv(5, 5, 96, 1, 1, name='icp2_out2'))

        (self.feed('icp2_in')
             .max_pool(3, 3, 1, 1, name='icp2_pool')
             .conv(1, 1, 64, 1, 1, name='icp2_out3'))

        (self.feed('icp2_in')
             .conv(1, 1, 128, 1, 1, name='icp2_out0'))

        (self.feed('icp2_out0',
                   'icp2_out1',
                   'icp2_out2',
                   'icp2_out3')
             .concat(3, name='icp2_out')
             .max_pool(3, 3, 2, 2, name='icp3_in')
             .conv(1, 1, 96, 1, 1, name='icp3_reduction1')
             .conv(3, 3, 208, 1, 1, name='icp3_out1'))

        (self.feed('icp3_in')
             .conv(1, 1, 16, 1, 1, name='icp3_reduction2')
             .conv(5, 5, 48, 1, 1, name='icp3_out2'))

        (self.feed('icp3_in')
             .max_pool(3, 3, 1, 1, name='icp3_pool')
             .conv(1, 1, 64, 1, 1, name='icp3_out3'))

        (self.feed('icp3_in')
             .conv(1, 1, 192, 1, 1, name='icp3_out0'))

        (self.feed('icp3_out0',
                   'icp3_out1',
                   'icp3_out2',
                   'icp3_out3')
             .concat(3, name='icp3_out')
             .avg_pool(5, 5, 3, 3, padding='VALID', name='cls1_pool')
             .conv(1, 1, 128, 1, 1, name='cls1_reduction_pose')
             .fc(1024, name='cls1_fc1_pose')
             .fc(3, relu=False, name='cls1_fc_pose_xyz'))

        (self.feed('cls1_fc1_pose')
             .fc(4, relu=False, name='cls1_fc_pose_wpqr'))

        (self.feed('icp3_out')
             .conv(1, 1, 112, 1, 1, name='icp4_reduction1')
             .conv(3, 3, 224, 1, 1, name='icp4_out1'))

        (self.feed('icp3_out')
             .conv(1, 1, 24, 1, 1, name='icp4_reduction2')
             .conv(5, 5, 64, 1, 1, name='icp4_out2'))

        (self.feed('icp3_out')
             .max_pool(3, 3, 1, 1, name='icp4_pool')
             .conv(1, 1, 64, 1, 1, name='icp4_out3'))

        (self.feed('icp3_out')
             .conv(1, 1, 160, 1, 1, name='icp4_out0'))

        (self.feed('icp4_out0',
                   'icp4_out1',
                   'icp4_out2',
                   'icp4_out3')
             .concat(3, name='icp4_out')
             .conv(1, 1, 128, 1, 1, name='icp5_reduction1')
             .conv(3, 3, 256, 1, 1, name='icp5_out1'))

        (self.feed('icp4_out')
             .conv(1, 1, 24, 1, 1, name='icp5_reduction2')
             .conv(5, 5, 64, 1, 1, name='icp5_out2'))

        (self.feed('icp4_out')
             .max_pool(3, 3, 1, 1, name='icp5_pool')
             .conv(1, 1, 64, 1, 1, name='icp5_out3'))

        (self.feed('icp4_out')
             .conv(1, 1, 128, 1, 1, name='icp5_out0'))

        (self.feed('icp5_out0',
                   'icp5_out1',
                   'icp5_out2',
                   'icp5_out3')
             .concat(3, name='icp5_out')
             .conv(1, 1, 144, 1, 1, name='icp6_reduction1')
             .conv(3, 3, 288, 1, 1, name='icp6_out1'))

        (self.feed('icp5_out')
             .conv(1, 1, 32, 1, 1, name='icp6_reduction2')
             .conv(5, 5, 64, 1, 1, name='icp6_out2'))

        (self.feed('icp5_out')
             .max_pool(3, 3, 1, 1, name='icp6_pool')
             .conv(1, 1, 64, 1, 1, name='icp6_out3'))

        (self.feed('icp5_out')
             .conv(1, 1, 112, 1, 1, name='icp6_out0'))

        (self.feed('icp6_out0',
                   'icp6_out1',
                   'icp6_out2',
                   'icp6_out3')
             .concat(3, name='icp6_out')
             .avg_pool(5, 5, 3, 3, padding='VALID', name='cls2_pool')
             .conv(1, 1, 128, 1, 1, name='cls2_reduction_pose')
             .fc(1024, name='cls2_fc1')
             .fc(3, relu=False, name='cls2_fc_pose_xyz'))

        (self.feed('cls2_fc1')
             .fc(4, relu=False, name='cls2_fc_pose_wpqr'))

        (self.feed('icp6_out')
             .conv(1, 1, 160, 1, 1, name='icp7_reduction1')
             .conv(3, 3, 320, 1, 1, name='icp7_out1'))

        (self.feed('icp6_out')
             .conv(1, 1, 32, 1, 1, name='icp7_reduction2')
             .conv(5, 5, 128, 1, 1, name='icp7_out2'))

        (self.feed('icp6_out')
             .max_pool(3, 3, 1, 1, name='icp7_pool')
             .conv(1, 1, 128, 1, 1, name='icp7_out3'))

        (self.feed('icp6_out')
             .conv(1, 1, 256, 1, 1, name='icp7_out0'))

        (self.feed('icp7_out0',
                   'icp7_out1',
                   'icp7_out2',
                   'icp7_out3')
             .concat(3, name='icp7_out')
             .max_pool(3, 3, 2, 2, name='icp8_in')
             .conv(1, 1, 160, 1, 1, name='icp8_reduction1')
             .conv(3, 3, 320, 1, 1, name='icp8_out1'))

        (self.feed('icp8_in')
             .conv(1, 1, 32, 1, 1, name='icp8_reduction2')
             .conv(5, 5, 128, 1, 1, name='icp8_out2'))

        (self.feed('icp8_in')
             .max_pool(3, 3, 1, 1, name='icp8_pool')
             .conv(1, 1, 128, 1, 1, name='icp8_out3'))

        (self.feed('icp8_in')
             .conv(1, 1, 256, 1, 1, name='icp8_out0'))

        (self.feed('icp8_out0',
                   'icp8_out1',
                   'icp8_out2',
                   'icp8_out3')
             .concat(3, name='icp8_out')
             .conv(1, 1, 192, 1, 1, name='icp9_reduction1')
             .conv(3, 3, 384, 1, 1, name='icp9_out1'))

        (self.feed('icp8_out')
             .conv(1, 1, 48, 1, 1, name='icp9_reduction2')
             .conv(5, 5, 128, 1, 1, name='icp9_out2'))

        (self.feed('icp8_out')
             .max_pool(3, 3, 1, 1, name='icp9_pool')
             .conv(1, 1, 128, 1, 1, name='icp9_out3'))

        (self.feed('icp8_out')
             .conv(1, 1, 384, 1, 1, name='icp9_out0'))

        (self.feed('icp9_out0',
                   'icp9_out1',
                   'icp9_out2',
                   'icp9_out3')
             .concat(3, name='icp9_out')
             .avg_pool(7, 7, 1, 1, padding='VALID', name='cls3_pool')
             .fc(2048, name='cls3_fc1_pose')
             .fc(3, relu=False, name='cls3_fc_pose_xyz'))

        (self.feed('cls3_fc1_pose')
             .fc(4, relu=False, name='cls3_fc_pose_wpqr'))


from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time

def isLoggedIn(driver):
    driver.get("http://www.evanfalkenstine.net/")
    time.sleep(1)
    header = driver.find_element_by_class_name("top-menu")
    if  header.text.find("Logout") == -1: # does not contain logout
        res = False
    else:
        res = True
    time.sleep(1)
    return res

def logIn(driver):
    if isLoggedIn(driver):
        return True

    driver.get("http://www.evanfalkenstine.net/login")
    userEmail = driver.find_element_by_id("identifierId")
    userEmail.send_keys("")
    driver.find_element_by_id("identifierNext").click()

    userPW = driver.find_element_by_id("password")
    userPW = userPW.find_element_by_name("password")
    userPW.send_keys("")
    userPW.send_keys(Keys.RETURN)
    try:
        element = WebDriverWait(driver, 10).until(
            EC.title_is("Item Catalog")
        )
    finally:
        time.sleep(1)
        return isLoggedIn(driver)

def addCategory(driver, category_name):
    if isLoggedIn(driver) == False:
        return False
    driver.get("http://www.evanfalkenstine.net/item_catalog/categories/add")
    inputName = driver.find_element_by_id("catName")
    inputName.send_keys(category_name)
    time.sleep(1)
    inputName.submit()
    time.sleep(1)
    return True

def categoryExists(driver, category_name):
    driver.get("http://www.evanfalkenstine.net/item_catalog/")
    all_a_tags = driver.find_elements_by_tag_name("a")
    for anchor in all_a_tags:
        if anchor.text == category_name:
            time.sleep(1)
            return True
    time.sleep(1)
    return False

def deleteCategory(driver, category_name):
    if isLoggedIn(driver) == False:
        time.sleep(1)
        return False

    driver.get("http://www.evanfalkenstine.net/item_catalog/")
    all_a_tags = driver.find_elements_by_tag_name("a")
    for anchor in all_a_tags:
        if anchor.text == category_name:
            collapse_name = anchor.get_attribute("href")[45:]
            anchor.click()
            break

    card_body = driver.find_element_by_id(collapse_name)
    links = card_body.find_elements_by_tag_name("a")
    for link in links:
        if link.text == "Delete":
            link.click()
            break
    time.sleep(1)
    driver.find_element_by_tag_name("input").click()
    time.sleep(1)
    return True

if __name__ == '__main__':
    driver = webdriver.Chrome()
    driver.implicitly_wait(5)
    example_name = "Job Interview Supplies"

    if logIn(driver):
       print("Successfully Logged In")
    else:
       print("Login Failed")

    if categoryExists(driver, example_name):
        print("Category Found")
    else:
        print("Category Not Found")

    if addCategory(driver, example_name):
        print("Category Added")
    else:
        print("Failed to Add Category")

    if categoryExists(driver, example_name):
        print("Category Found")
    else:
        print("Category Not Found")

    if deleteCategory(driver, example_name):
        print("Category Deleted")
    else:
        print("Failed to Delete Category")

    if categoryExists(driver, example_name):
        print("Category Found")
    else:
        print("Category Not Found")


import aiohttp
import asyncio
from functools import reduce
from PLATER.services.config import config

class BLHelper:
    def __init__(self, bl_url=config.get('bl_url')):
        self.bl_url = bl_url

    @staticmethod
    async def make_request(url):
        async with aiohttp.ClientSession() as session:
            async with session.get(url) as response:
                if response.status == 200:
                    return await response.json()
                else:
                    return None

    async def get_most_specific_concept(self, concept_list: list) -> list:
        """
        Given a list of concepts find the most specific set of concepts.
        """
        tasks = []
        for concept in concept_list:
            parent_url = f"{self.bl_url}/bl/{concept}/ancestors"
            tasks.append(BLHelper.make_request(parent_url))
        response = await asyncio.gather(*tasks, return_exceptions=False)
        parents = list(reduce(lambda acc, value: acc + value, filter(lambda x: x, response), []))
        return list(filter(lambda x: x not in parents, concept_list))


def solution(n):
    answer = []

    n=str(n)
    li_n=list(n)

    for i in range(0, len(li_n)):
        answer.append(int(li_n[len(li_n)-i-1]))

    return answer

[PGS] 자연수 뒤집어 배열로 만들기.py


#有n个人围成一圈，顺序排号。从第一个人开始报数（从1到3报数），凡报到3的人退出圈子，问最后留下的是原来第几号的那位。
person_number=int(input('请输入人数：'))  #键盘录入围成圈的人数
person_list=[i for i in range(1,person_number+1)] #按人数生成人数序号列表
stay_deal_list=person_list.copy() #浅拷贝一个一样的列表实施处理
count=1 #通过计数器来判断序号是否为3的倍数
while len(stay_deal_list)!=1:
    stay_remove_list = []  # 将需要删除的列表全部放进待删除的列表中，一次性更新事实处理的列表
    for j in stay_deal_list:
        if count%3==0:
            stay_remove_list.append(j)
        count+=1
    for k in stay_remove_list:
        stay_deal_list.remove(k)
print(stay_deal_list)


import re
from music21 import note
import numpy as np

data = ['A4', 'F4', 'E.G']
# data = ['C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B' ]

keyboard = np.zeros(88)

for d in data:
    n = d.split(".")
    print('Dlugosc', len(n))
    for m in n:
        f = note.Note(m)
        # print(m, int("0x" + f.pitch.pitchClassString, 0), f.octave if f.octave else 0)
        # print(m, int("0x" + f.pitch.pitchClassString, 0), f.octave if f.octave else 0)
        octave = int(f.octave if f.octave else 0)
        mantise = int("0x" + f.pitch.pitchClassString, 0)
        # number = mantise + 12 * octave
        # print(m, number)
        keyboard[mantise] = 1
    print(keyboard)
    keyboard = np.zeros(88)