import pickle
import torch
import argparse

from foresight.models import *
from foresight.pruners import *
from foresight.dataset import *
from foresight.weight_initializers import init_net

def get_num_classes(args):
    return 100 if args.dataset == 'cifar100' else 10 if args.dataset == 'cifar10' else 120

def parse_arguments():
    parser = argparse.ArgumentParser(description='Zero-cost Metrics for NAS-Bench-201')
    parser.add_argument('--api_loc', default='data/NAS-Bench-201-v1_0-e61699.pth',
                        type=str, help='path to API')
    parser.add_argument('--outdir', default='./',
                        type=str, help='output directory')
    parser.add_argument('--init_w_type', type=str, default='none', help='weight initialization (before pruning) type [none, xavier, kaiming, zero]')
    parser.add_argument('--init_b_type', type=str, default='none', help='bias initialization (before pruning) type [none, xavier, kaiming, zero]')
    parser.add_argument('--batch_size', default=64, type=int)
    parser.add_argument('--dataset', type=str, default='cifar10', help='dataset to use [cifar10, cifar100, ImageNet16-120]')
    parser.add_argument('--gpu', type=int, default=0, help='GPU index to work on')
    parser.add_argument('--num_data_workers', type=int, default=2, help='number of workers for dataloaders')
    parser.add_argument('--dataload', type=str, default='random', help='random or grasp supported')
    parser.add_argument('--dataload_info', type=int, default=1, help='number of batches to use for random dataload or number of samples per class for grasp dataload')
    parser.add_argument('--seed', type=int, default=42, help='pytorch manual seed')
    parser.add_argument('--write_freq', type=int, default=1, help='frequency of write to file')
    parser.add_argument('--start', type=int, default=0, help='start index')
    parser.add_argument('--end', type=int, default=0, help='end index')
    parser.add_argument('--noacc', default=False, action='store_true', help='avoid loading NASBench2 api an instead load a pickle file with tuple (index, arch_str)')
    args = parser.parse_args()
    args.device = torch.device("cuda:"+str(args.gpu) if torch.cuda.is_available() else "cpu")
    return args

if __name__ == '__main__':
    args = parse_arguments()

    if args.noacc:
        api = pickle.load(open(args.api_loc,'rb'))
    else:
        from nas_201_api import NASBench201API as API
        api = API(args.api_loc)

    torch.manual_seed(args.seed)
    torch.backends.cudnn.deterministic = True
    torch.backends.cudnn.benchmark = False

    train_loader, val_loader = get_cifar_dataloaders(args.batch_size, args.batch_size, args.dataset, args.num_data_workers)

    cached_res = []
    pre='cf' if 'cifar' in args.dataset else 'im'
    pfn=f'nb2_{pre}{get_num_classes(args)}_seed{args.seed}_dl{args.dataload}_dlinfo{args.dataload_info}_initw{args.init_w_type}_initb{args.init_b_type}.p'
    op = os.path.join(args.outdir,pfn)

    args.end = len(api) if args.end == 0 else args.end

    #loop over nasbench2 archs
    for i, arch_str in enumerate(api):

        if i < args.start:
            continue
        if i >= args.end:
            break

        res = {'i':i, 'arch':arch_str}

        net = nasbench2.get_model_from_arch_str(arch_str, get_num_classes(args))
        net.to(args.device)

        init_net(net, args.init_w_type, args.init_b_type)

        arch_str2 = nasbench2.get_arch_str_from_model(net)
        if arch_str != arch_str2:
            print(arch_str)
            print(arch_str2)
            raise ValueError

        measures = predictive.find_measures(net,
                                            train_loader,
                                            (args.dataload, args.dataload_info, get_num_classes(args)),
                                            args.device)

        res['logmeasures']= measures

        if not args.noacc:
            info = api.get_more_info(i, 'cifar10-valid' if args.dataset=='cifar10' else args.dataset, iepoch=None, hp='200', is_random=False)

            trainacc = info['train-accuracy']
            valacc   = info['valid-accuracy']
            testacc  = info['test-accuracy']

            res['trainacc']=trainacc
            res['valacc']=valacc
            res['testacc']=testacc

        #print(res)
        cached_res.append(res)

        #write to file
        if i % args.write_freq == 0 or i == len(api)-1 or i == 10:
            print(f'writing {len(cached_res)} results to {op}')
            pf=open(op, 'ab')
            for cr in cached_res:
                pickle.dump(cr, pf)
            pf.close()
            cached_res = []


from tensorflow.keras.models import load_model
from tensorflow.keras.preprocessing.image import ImageDataGenerator
import numpy as np
import cv2
import matplotlib.pyplot as plt
import matplotlib.image as mpimg

model = load_model("/home/yash/Desktop/PyImageSearch/checkpoints/emotion1.h5")
classifier = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')

img_size = 48

validation_dir = "/home/yash/Desktop/PyImageSearch/deep_survelliance_detector/fer2013/validation/"

validation_datagen = ImageDataGenerator(rescale=1./255)

validation_generator = validation_datagen.flow_from_directory(validation_dir,
								color_mode="grayscale",
								target_size=(img_size,img_size),
								batch_size=32,
								class_mode="categorical",
								shuffle=False)

#getting class labels
class_labels = validation_generator.class_indices
class_labels = {v:k for v,k in class_labels.items()}

#predicting
test_img = "/home/yash/Downloads/happy1.jpg"

def get_label(prediction):
	for key, val in class_labels.items():
		if prediction == val:
			return key
	return -1

def predict(test_img):
	img = cv2.imread(test_img,cv2.IMREAD_GRAYSCALE)
	faces = classifier.detectMultiScale(img,scaleFactor=1.2,minNeighbors=7)
	face = []
	for (x,y,w,h) in faces:
		roi_gray = img[y:y+h,x:x+w]
		roi = cv2.resize(roi_gray, (img_size,img_size), interpolation=cv2.INTER_AREA)
		face.append(roi)
	num_image = np.array(face, dtype=np.float32)
	num_image /= 255.0
	num_image = num_image.reshape(1,48,48,1)
	predicted = model.predict(num_image)[0] #returns a list of probabilities of diff classes
	pred = predicted.argmax() #getting the max value in the list
	label = get_label(pred)
	return label

pred_class = predict(test_img)
original_image = mpimg.imread(test_img)
plt.xlabel("Predicted: {0}".format(str(pred_class)))
plt.imshow(original_image)
plt.show()

Emotion and Gender Classification/Emotion Classification/recognition.py


import json
import os

import cherrypy
from jinja2 import Environment, FileSystemLoader

# GET CURRENT DIRECTORY
from helper import get_redis_connection, get_sorted_list
from scrapper import main1

CUR_DIR = os.path.dirname(os.path.abspath(__file__))
env = Environment(loader=FileSystemLoader(CUR_DIR), trim_blocks=True)

class Index(object):
    @cherrypy.expose
    def index(self):
        template = env.get_template('templates/home.html')
        r = get_redis_connection()
        try:
            users = json.loads(r.get('ten_users'))
        except:
            main1()  # If file was not downloaded then download the latest file.
            users = json.loads(r.get('ten_users'))

        return template.render(users=users, name='JAYANTH')

@cherrypy.expose
class UserService(object):
    @cherrypy.tools.json_out()
    def POST(self, name):
        r = get_redis_connection()
        users = json.loads(r.get('users'))
        response = {}
        try:
            res = [user for user in users if name.lower() in user["name"].lower()]  # search by name (substring match)

            result = get_sorted_list(res, 'dict')

            response['success'] = True
            response['users'] = result[:10]
            response['length'] = res.__len__()
            return response
        except:
            response['success'] = False
            return response

if __name__ == '__main__':
    conf = {
        '/': {
            'tools.sessions.on': True,
            'tools.staticdir.root': os.path.abspath(os.getcwd())
        },
        '/get_users': {
            'request.dispatch': cherrypy.dispatch.MethodDispatcher(),
            'tools.response_headers.on': True,
        },
        '/static': {
            'tools.staticdir.on': True,
            'tools.staticdir.dir': './static'
        }
    }
    webapp = Index()
    webapp.get_users = UserService()
    cherrypy.server.socket_host = '0.0.0.0'
    cherrypy.quickstart(webapp, '/', conf)


from apirequests.stratz import search_match, get_global_variables, get_items_per_time

def inicia_overlay(imagem_path, root, label, hero_id, players, heroes_against):
    regiao_busca = (580, 492, 62, 25)
    #posicao = pyautogui.locateOnScreen(imagem_path, region=regiao_busca, grayscale=True)
    label['text'] = "Aguarde..."
    posicao = 1
    if posicao:
        response_strataz = search_match(players, hero_id, heroes_against)
        while response_strataz is None and len(heroes_against) > 0:
            heroes_against.pop(-1)
            response_strataz = search_match(players, hero_id, heroes_against)

        if response_strataz is not None:
            label['text'] = response_strataz
        else:
            label['text'] = get_items_per_time(matchid=get_global_variables()[0]['id'], playerid=get_global_variables()[1])
    else:
        root.after(1, inicia_overlay(imagem_path, root, label, hero_id, players, heroes_against))


from constants import API_STACK_BASE_URL
import requests
import sys

class IpStack:
    def __init__(self, api_token: str, base_url: str):
        if base_url is None or base_url == '':
            base_url = API_STACK_BASE_URL

        self.api_token = api_token
        self.base_url = base_url

    def get_ip_location(self, ip_address: str) -> tuple[str,str]:
        endpoint = f"{self.base_url}/{ip_address}?access_key={self.api_token}"
        try:
            response = requests.get(endpoint, timeout=60)
            json_response = response.json()
        except requests.exceptions.RequestException as error:
            print(f"Error: The request could not be resolved")
            print(f"Provided base url: {self.base_url}")
            if 'doc' in error.__dict__:
                print(error.__dict__['doc'])
            sys.exit(1)
        if 'error' in json_response:
            error_code = json_response['error']['code']
            error_mesage = json_response['error']['info']
            print(f"Error {error_code}: {error_mesage}")
            sys.exit(1)
        latitude = json_response['latitude']
        longitude = json_response['longitude']
        if latitude == 0 and longitude == 0:
            print("Location not found")
            sys.exit(1)
        return latitude, longitude


import ServerModule

class StateMachine():
    current_state = None
    nickname = None
    def __init__(self, start_state):
        self.current_state = start_state

    def login(self, nickname):
        self.nickname = nickname
        return ServerModule.login(nickname)

    def view_profile(self, nickname):
        ServerModule.show_user_data(nickname)
        self.choose_stage(['BC','welcome', 'go back'], ['SL', 'sell_item', 'sell item'])

    def sell_item(self, item_id):
        ServerModule.show_user_data(nickname)
        ServerModule.sell_item_by_id(input('Press item id\n'))
        pass

    def show_items_list(self):
        ServerModule.show_items_list()
        self.choose_stage(['BC','welcome', 'go back'], ['BY', 'buy_item', 'buy item'])

    def welcome(self):
        print(f'\nNice to see you {self.nickname}!\nWhat do you wanna to do?\n')
        self.choose_stage(['LO','leave_or_stay', 'logout'], ['IT', 'show_items_list', 'show items list'], ['IN', 'view_profile', 'show inventory'])

    def choose_stage(self, stage1, stage2, stage3 = ['', '', '']):
        print(f"Press '{stage1[0]}' to {stage1[2]}\nPress '{stage2[0]}' to {stage2[2]}")
        if stage3[0] != '':
            print(f"Press '{stage3[0]}' to {stage3[2]}\n")
        stage = input().upper()
        if stage == stage1[0]:
            self.current_state = stage1[1]
        elif stage == stage2[0]:
            self.current_state = stage2[1]
        elif stage3[0] != '' and stage == stage3[0]:
            self.current_state = stage3[1]
        else:
            print('Something went wrong. Try again.')
            self.choose_stage(stage1, stage2, stage3)


class Node:
    def __init__(self, val):
        self.val = val
        self.next = None

def deleteNode(root, target):

    if not root or not target:
        return "Error"

    if target.next:
        print(target.val)
        target.val = target.next.val
        target.next = target.next.next

    if not target.next:
        while root and root.next:
            if not root.next.next:
                root.next = None
            root = root.next

def main():
    root = Node(10)
    point = root

    for i in range(10):
        point.next = Node(i)
        point = point.next
        target = point

    deleteNode(root,target)

    while root:
        print(root.val)
        root = root.next

if __name__ == "__main__":
    main()

剑指offer代码/算法和数据操作/面试题18:删除链表的节点.py

面试题18:删除链表的节点.py


import pygame
from pygame.locals import *
import numpy as np
from conway import Life

class GameOfLife(Life):
    def __init__(self, width = 1600, height = 1000, cell_size = 5, speed = 10):
        Life.__init__(self, width // 10, height // 10)
        self.width = width
        self.height = height
        self.cell_size = cell_size

        # Устанавливаем размер окна
        self.screen_size = width, height
        # Создание нового окна
        self.screen = pygame.display.set_mode(self.screen_size)

        # Вычисляем количество ячеек по вертикали и горизонтали
        self.cell_width = self.width // self.cell_size
        self.cell_height = self.height // self.cell_size

        # Скорость протекания игры
        self.speed = speed
        self.Mboard()

    def draw_grid(self):

        for x in range(0, self.width, self.cell_size):
            pygame.draw.line(self.screen, pygame.Color('black'),
                (x, 0), (x, self.height))
        for y in range(0, self.height, self.cell_size):
            pygame.draw.line(self.screen, pygame.Color('black'),
                (0, y), (self.width, y))

    def cells(self):
        for row in range(self.rows):
            for column in range(self.columns):
                if self.board[row, column] == 1:
                    pygame.draw.rect(self.screen, (57, 255, 20), ((row * self.cell_size) + 1, (column * self.cell_size) +1, self.cell_size -1,
                                     self.cell_size -1))
                else:
                    pygame.draw.rect(self.screen, (255, 255, 255), ((row * self.cell_size) + 1, (column * self.cell_size) + 1, self.cell_size -1,
                                     self.cell_size -1))

    def run(self):
        pygame.init()
        clock = pygame.time.Clock()
        pygame.display.set_caption('Game of Life')
        self.screen.fill(pygame.Color('white'))
        running = True
        while running:
            for event in pygame.event.get():
                if event.type == QUIT:
                    running = False
            self.draw_grid()
            self.cells()
            self.cell()
            pygame.display.flip()
            clock.tick(self.speed)
        pygame.quit()

if __name__ == '__main__':
    game = GameOfLife()
    game.run()


# Sales Program
# Written by Tanner McCarthy
# 9/20/21
# Prof Fried

packagePrice = 99
discount = 0

#used a while loop so that it will keep running until I am satisfied with the input given to me
#by the user

#use True so that it will always run
while True:
  #used try and except so that if an error comes up that would crash the program occurs, this keeps
  #the program running and ask the user again for a valid input
  try:
    numPack = int(input("How many packages did you purchase?\nPackages Purchased: "))
    print("")
  #except ValueError is to catch any error thrown so the program doesnt stop
  except ValueError:
    print("\nINVALID, Please try again\n")
    #continue will continue the program and reask the user for a valid input
    continue

  #this if statement is to make sure that the user does not enter 0 or any negative numebrs
  #since it would not make sense to have purchased 0 or a negative amount of packages
  if numPack < 0 or numPack == 0:
    print("\nINVALID, Please try again\n")
    #continue will continue the program and reask the user for a valid input
    continue

  #this else is so that when we have a valid input we can break out of this forever running while loop
  else:
    #break will simply break us out of the while loop and continue the rest of the program
    break

#made it its own if statement bc it will read "...purchased 1 package..." and not
#"...purchased 1 packages...". All of this so that it has correct grammar
if numPack == 1:
  print("Since you purchased", numPack, "package, you are NOT entitled to any discount.")

#elif statements for the rest to check what discount they fall into

elif numPack <= 9:
  print("Since you purchased", numPack, "packages, you are NOT entitled to any discount.")

elif numPack >= 10 and numPack <= 19:
  print("Since you purchased", numPack, "packages, you are entitled to a 10% discount.")
  discount  = .10

elif numPack >= 20 and numPack <= 49:
  print("Since you purchased", numPack, "packages, you are entitled to a 20% discount.")
  discount  = .20

elif numPack >= 50 and numPack <= 99:
  print("Since you purchased", numPack, "packages, you are entitled to a 30% discount.")
  discount  = .30

#else statement and not a elif bc it is the last to run and I do not need to check anything since
#everything I needed to check has already been checked
else:
  print("Since you purchased", numPack, "packages, you are entitled to a 40% discount.")
  discount  = .40

#math formula to apply the discount to get the total price
totalAmt = packagePrice * numPack*(1 - discount)

#commented this print line out bc the print(f) can format a nonconstant variable
#print("The total cost after applying your discount is", totalAmt )

print(f'The total cost after applying your discount is ${totalAmt:,.2f}.\n' )

#end of the first part of the program

#Start of the second part of the program
#The Fast Freight Shipping Company program

#use True so that it will always run
while True:
  #used try and except so that if an error comes up that would crash the program occurs, this keeps
  #the program running and ask the user again for a valid input
  try:
    weight = float(input("Please enter the weight of the package.\nPackage weight: "))
    print("")
  #except ValueError is to catch any error thrown so the program doesnt stop
  except ValueError:
    print("\nINVALID, Please try again.\n")
    #continue will continue the program and reask the user for a valid input
    continue

  #this if statement is to make sure that the user does not enter 0 or any negative numebrs
  #since it would not make sense to have a weight of 0 or a negative weight
  if weight < 0 or weight == 0:
    print("\nINVALID, Please try again.\n")
    #continue will continue the program and reask the user for a valid input
    continue

  #this else is so that when we have a valid input we can break out of this forever running while loop
  else:
    #break will simply break us out of the while loop and continue the rest of the program
    break

#created the variable finalCost
finalCost = float(0)

#test to see if weight is less than 2lbs it applies the correct rpp
if weight <= 2.00:
  finalCost = float(weight * 1.50)
  print(f'The total cost after applying our rate per pound, $1.50, the shipping cost is ${finalCost:,.2f}')

#test to see if weight is inbetween 2lbs and 6lbs and applies the correct rpp
elif weight > 2.00 and weight <= 6.00:
  finalCost = float(weight * 3.00)
  print(f'The total cost after applying our rate per pound, $3.00, the shipping cost is ${finalCost:,.2f}')

#test to see if weight is inbetween 2lbs and 6lbs and applies the correct rpp
elif weight > 6.00 and weight <= 10.00:
  finalCost = float(weight * 4.00)
  print(f'The total cost after applying our rate per pound, $4.00, the shipping cost is ${finalCost:,.2f}')

#else statement and not a elif bc it is the last to run and I do not need to check anything since
#everything I needed to check has already been checked
else:
  finalCost = float(weight * 4.75)
  print(f'The total cost after applying our rate per pound, $4.75, the shipping cost is ${finalCost:,.2f}')

#end of the second part of the program

#end of the entire program


import os
import numpy as np
import pickle
import argparse

from implicit.bpr import BayesianPersonalizedRanking
from implicit.nearest_neighbours import CosineRecommender
from scipy.sparse import csr_matrix

from methods import consul, oracle, PrivateRank, PrivateWalk

np.random.seed(0)

def recall(li, gt):
    if gt in li:
        return 1
    return 0

def nDCG(li, gt):
    if gt in li:
        return 1 / np.log2(li.tolist().index(gt) + 2)
    return 0

def list_minimum_group(li, sensitive):
    return np.bincount(sensitive[li], minlength=sensitive.max() + 1).min()

parser = argparse.ArgumentParser()
parser.add_argument('--data', choices=['100k', '1m', 'home', 'hetrec'], default='100k')
parser.add_argument('--prov', choices=['cosine', 'bpr'], default='cosine')
parser.add_argument('--sensitive', choices=['popularity', 'old'], default='popularity', help='`old` is valid only for MovieLens')
parser.add_argument('--split', type=int, default=1, help='Total number of parallel execusion (only for parallel execusion, set 1 otherwise)')
parser.add_argument('--block', type=int, default=0, help='Id of the current execusion (only for parallel excecusion, set 0 otherwise)')
args = parser.parse_args()
assert(args.sensitive == 'popularity' or args.data in ['100k', '1m'])
assert(0 <= args.block and args.block < args.split)

#
# Load Data
#

if args.data == '100k':
    n = 943
    m = 1682
    filename = 'ml-100k/u.data'
    delimiter = '\t'
elif args.data == '1m':
    n = 6040
    m = 3952
    filename = 'ml-1m/ratings.dat'
    delimiter = '::'

K = 10

if args.data == '100k' or args.data == '1m':
    raw_R = np.zeros((n, m))
    history = [[] for i in range(n)]
    with open(filename) as f:
        for r in f:
            user, movie, r, t = map(int, r.split(delimiter))
            user -= 1
            movie -= 1
            raw_R[user, movie] = r
            history[user].append((t, movie))
elif args.data == 'hetrec':
    raw_R = np.log2(np.load('hetrec.npy') + 1)
    n, m = raw_R.shape
    history = [[] for i in range(n)]
    for i in range(n):
        for j in np.nonzero(raw_R[i] > 0)[0]:
            history[i].append((np.random.rand(), j))
elif args.data == 'home':
    raw_R = np.load('Home_and_Kitchen.npy')
    n, m = raw_R.shape
    with open('Home_and_Kitchen_history.pickle', 'br') as f:
        history = pickle.load(f)

if args.sensitive == 'popularity':
    mask = raw_R > 0
    if args.data == '100k':
        sensitive = mask.sum(0) < 50
    elif args.data == '1m':
        sensitive = mask.sum(0) < 300
    elif args.data == 'hetrec':
        sensitive = mask.sum(0) < 50
    elif args.data == 'home':
        sensitive = mask.sum(0) < 50
    sensitive = sensitive.astype('int')
elif args.sensitive == 'old':
    sensitive = np.zeros(m, dtype='int')
    if args.data == '100k':
        filename = 'ml-100k/u.item'
        delimiter = '|'
    elif args.data == '1m':
        filename = 'ml-1m/movies.dat'
        delimiter = '::'
    with open(filename, encoding='utf8', errors='ignore') as f:
        for r in f:
            li = r.strip().split(delimiter)
            if '(19' in li[1]:
                year = 1900 + int(li[1].split('(19')[1].split(')')[0])
            elif '(20' in li[1]:
                year = 2000 + int(li[1].split('(20')[1].split(')')[0])
            sensitive[int(li[0]) - 1] = year < 1990

#
# Data Loaded
#

damping_factor = 0.01
tau = 5

provider_recall = 0
provider_nDCG = 0
provider_minimum = 0
oracle_recall = 0
oracle_nDCG = 0
oracle_minimum = 0
PR_recall = 0
PR_nDCG = 0
PR_minimum = 0
PW_recall = 0
PW_nDCG = 0
PW_minimum = 0
random_recall = 0
random_nDCG = 0
random_minimum = 0
consul_recall = 0
consul_nDCG = 0
consul_minimum = 0

PW_cnt = np.array(0)
consul_cnt = np.array(0)

start_index = int(n * args.block / args.split)
end_index = int(n * (args.block + 1) / args.split)

for i in range(start_index, end_index):
    gt = sorted(history[i])[-1][1]
    source = sorted(history[i])[-2][1]
    used = [y for x, y in history[i] if y != gt]

    R = raw_R.copy()
    R[i, gt] = 0

    mask = R > 0

    if args.prov == 'bpr':
        model = BayesianPersonalizedRanking(num_threads=1, random_state=0)
    elif args.prov == 'cosine':
        model = CosineRecommender()

    sR = csr_matrix(mask.T)
    model.fit(sR, show_progress=False)
    if args.prov == 'bpr':
        score = model.item_factors @ model.item_factors.T
    else:
        score = np.zeros((m, m))
        for item in range(m):
            for j, v in model.similar_items(item, m):
                score[item, j] = v

    score_remove = score.copy()
    score_remove[:, used] -= score.max() + 1
    score_remove -= np.eye(m) * (score.max() + 1)

    list_provider = np.argsort(-score_remove[source])[:K]
    provider_recall += recall(list_provider, gt)
    provider_nDCG += nDCG(list_provider, gt)
    provider_minimum += list_minimum_group(list_provider, sensitive)

    oracle_list = oracle(score_remove[source], sensitive, tau, used, K)
    oracle_recall += recall(oracle_list, gt)
    oracle_nDCG += nDCG(oracle_list, gt)
    oracle_minimum += list_minimum_group(oracle_list, sensitive)

    # Construct the recsys graph
    A = np.zeros((m, m))
    rank = np.argsort(-score_remove, 1)[:, :K]
    weight = 1 / np.log2(np.arange(K) + 2)
    weight /= weight.sum()
    A[np.arange(m).repeat(K), rank.reshape(-1)] += weight.repeat(m).reshape(K, m).T.reshape(-1)

    # Consul
    consul_list = consul(rank, sensitive, tau, source, used, K, access_conuter=consul_cnt)
    consul_recall += recall(consul_list, gt)
    consul_nDCG += nDCG(consul_list, gt)
    consul_minimum += list_minimum_group(consul_list, sensitive)

    # PrivateRank
    PR_list = PrivateRank(A, sensitive, tau, source, used, K, damping_factor)
    PR_recall += recall(PR_list, gt)
    PR_nDCG += nDCG(PR_list, gt)
    PR_minimum += list_minimum_group(PR_list, sensitive)

    # PrivateWalk
    PW_list = PrivateWalk(rank, sensitive, tau, source, used, K, access_conuter=PW_cnt)
    PW_recall += recall(PW_list, gt)
    PW_nDCG += nDCG(PW_list, gt)
    PW_minimum += list_minimum_group(PW_list, sensitive)

    # Random
    np.random.seed(0)
    random_score = np.random.rand(m)
    random_list = oracle(random_score, sensitive, tau, used, K)
    random_recall += recall(random_list, gt)
    random_nDCG += nDCG(random_list, gt)
    random_minimum += list_minimum_group(random_list, sensitive)

    print('#')
    print('# User {} - {}'.format(start_index, i))
    print('#')
    print('-' * 30)
    print('provider recall    {:.2f}'.format(provider_recall))
    print('oracle recall     ', oracle_recall)
    print('consul recall     ', consul_recall)
    print('PrivateRank recall', PR_recall)
    print('PrivateWalk recall', PW_recall)
    print('random recall     ', random_recall)
    print('-' * 30)
    print('provider nDCG    {:.2f}'.format(provider_nDCG))
    print('oracle nDCG     ', oracle_nDCG)
    print('consul nDCG     ', consul_nDCG)
    print('PrivateRank nDCG', PR_nDCG)
    print('PrivateWalk nDCG', PW_nDCG)
    print('random nDCG     ', random_nDCG)
    print('-' * 30)
    print('provider least count    {:.2f}'.format(provider_minimum))
    print('oracle least count     ', oracle_minimum)
    print('consul least count     ', consul_minimum)
    print('PrivateRank least count', PR_minimum)
    print('PrivateWalk least count', PW_minimum)
    print('random least count     ', random_minimum)
    print('-' * 30)
    print('consul access     ', consul_cnt)
    print('PrivateWalk access', PW_cnt)
    print('-' * 30)

if not os.path.exists('out'):
    os.mkdir('out')

with open('out/{}-{}-{}-{}.txt'.format(args.data, args.prov, args.sensitive, args.block), 'w') as f:
    print(provider_recall, file=f)
    print(provider_nDCG, file=f)
    print(provider_minimum, file=f)

    print(oracle_recall, file=f)
    print(oracle_nDCG, file=f)
    print(oracle_minimum, file=f)

    print(consul_recall, file=f)
    print(consul_nDCG, file=f)
    print(consul_minimum, file=f)
    print(consul_cnt, file=f)

    print(PR_recall, file=f)
    print(PR_nDCG, file=f)
    print(PR_minimum, file=f)

    print(PW_recall, file=f)
    print(PW_nDCG, file=f)
    print(PW_minimum, file=f)
    print(PW_cnt, file=f)

    print(random_recall, file=f)
    print(random_nDCG, file=f)
    print(random_minimum, file=f)


from time import time
from gurobipy import Model

class MDSP:

    def __init__(self, d: list, filename: str, optimize=False, time_limit=3600):
        self.D = d
        self.B = sum(d)
        self.k = len(self.D)
        self.D_ = self.get_unique_distances()
        self.M = self.get_mult()
        self.P = list(range(self.B + 1))
        self.filename = filename

        if optimize:
            self.P = self.valid_points()

        self.model = Model()
        self.model.setParam('LogFile', f'{filename}.log')
        self.model.setParam('LogToConsole', 0)
        self.model.setParam('TimeLimit', time_limit)

    def solve(self):
        t1 = time()
        self.model.update()
        self.model.optimize()
        t2 = time()

        self.write_time_file(t1, t2)
        self.model.write(f'{self.filename}.lp')

        if self.model.status == 3:
            print('Infeasible')
        else:
            self.model.write(f'{self.filename}.sol')
            print('Obj: %s' % self.model.ObjVal)

    def get_unique_distances(self):
        d = list(set(self.D))
        d.sort()

        return d

    def get_mult(self):
        m = dict()

        for i in self.D_:
            m[i] = self.D.count(i)

        return m

    def valid_points(self):
        c = {0}

        for d in self.D:
            t = set()

            for p in c:
                t = t.union({p-d, p+d})

            c = c.union(t)

        p = [x for x in c if x >= 0]
        p.sort()

        return p

    def write_time_file(self, t1, t2):
        with open(f'{self.filename}.time', 'w') as file:
            file.write(f'{self.model.Status}\n')
            file.write(f'{t2 - t1}\n')
            file.close()


# -*- coding: utf-8 -*-
'''Polynomial basis linear model data generator'''

import numpy as np
import hw3_1a

def polynomial(basis,var,weights,n=1):

    noise = hw3_1a.normal_generating(0, var)
    x = np.random.uniform(-1, 1, n)

    X=[]
    for power in range(basis):
        X.append( x[:] ** power)

    X=np.array(X)
    weights=np.array(weights)
    y=weights.dot(X)+ noise

    return y

def main():
     basis=int(input("n=")) #basis num
     var=float(input("a=")) #var
     weights=[float(x) for x in input("w=").split()] #weight list
     #n=1 #Number of data to generate
     values = polynomial(basis,var,weights)

     print(*values, sep=' ')

if __name__ == '__main__':
    main()


import rabacus as ra
import pylab as plt
import numpy as np

z = 3.0
Nnu = 100
q_min = 1.0e-2
q_max = 1.0e6
uvb = ra.BackgroundSource( q_min, q_max, 'hm12', z=z, Nnu=Nnu )

NT=100

T = np.logspace( 4.0, 5.0, NT ) * ra.u.K

nH = np.ones( NT ) * 1.0e-2 / ra.u.cm**3
nHe = nH * 10**(-1.0701)

H1i = np.ones(T.size) * uvb.thin.H1i
He1i = np.ones(T.size) * uvb.thin.He1i
He2i = np.ones(T.size) * uvb.thin.He2i

H1h = np.ones(T.size) * uvb.thin.H1h
He1h = np.ones(T.size) * uvb.thin.He1h
He2h = np.ones(T.size) * uvb.thin.He2h

fcA_H2 = 1.0
fcA_He2 = 1.0
fcA_He3 = 1.0

kchem = ra.ChemistryRates( T, fcA_H2, fcA_He2, fcA_He3,
                           H1i=H1i, He1i=He1i, He2i=He2i )

kcool = ra.CoolingRates( T, fcA_H2, fcA_He2, fcA_He3,
                         H1h=H1h, He1h=He1h, He2h=He2h )

x_pce = ra.Solve_PCE( nH, nHe, kchem )

heat_H1 = H1h * nH * x_pce.H1
heat_He1 = He1h * nHe * x_pce.He1
heat_He2 = He2h * nHe * x_pce.He2
heat = heat_H1 + heat_He1 + heat_He2

plt.loglog( T, heat, color='black', lw=2.0 )
plt.loglog( T, heat_H1 )
plt.loglog( T, heat_He1 )
plt.loglog( T, heat_He2 )


#!/usr/local/bin/python3.7
# -*- coding: utf-8 -*-
# @Time    : 2020-06-20 16:15
# @Author  : 小凌
# @Email   : 296054210@qq.com
# @File    : test_06_audit.py
# @Software: PyCharm
import json
import unittest
import ddt

from common.excel_handler import ExcelHandler
from common.http_handler import visit
from middlerware.handler import Handler

logger = Handler.logger
excel = Handler.excel
yaml = Handler.yaml
sheet_name = yaml['excel']['auditsheet']
test_data = excel.get_data(sheet_name)

@ddt.ddt
class TestAudit(unittest.TestCase):
    @classmethod
    def setUpClass(cls) -> None:
        logger.info('------------------------------TestAuditBegin------------------------------')
        cls.admin_token = Handler().admin_token
        cls.token = Handler().token

    def setUp(self) -> None:
        # 封装使用测试号生成的项目,并提取loan_id
        self.loan_id = Handler().loan_id
        self.db = Handler.database_cls()
        self.excel = ExcelHandler(Handler.excel_path)

    @ddt.data(*test_data)
    def test01_audit(self, case_data):
        """审核项目接口测试"""
        global case_result
        logger.info('**********正在获取第%d条<%s>用例**********' % (case_data['case_id'], case_data['title']))
        headers = case_data['headers']
        # 增加一个用户登陆登陆进行审核的失败操作用例
        if ("#admin_token#" in headers) or ("#token#" in headers):
            headers = headers.replace("#admin_token#", self.admin_token)
            headers = headers.replace("#token#", self.token)

        data = case_data['data']
        if "#loan_id#" in data:
            data = data.replace("#loan_id#", str(self.loan_id))

        # 取一个不存在的项目id
        if "#fail_loan_id#" in data:
            data = data.replace("#fail_loan_id#", str(self.loan_id + 1000))

        # 判断是否为已审批的用例,若为已审批的账号则从数据库提取一条status != 1的数据
        if "#approve_loan_id#" in data:
            self.loan_id = self.db.query("select * from futureloan.loan where `status` !=2 limit 1;")['id']
            data = data.replace("#approve_loan_id#", str(self.loan_id))

        response = visit(
            url=yaml['host'] + case_data['url'],
            method=case_data['method'],
            json=json.loads(data),
            headers=json.loads(headers)
        )
        expected = json.loads(case_data["expected"])

        try:
            self.assertEqual(response.json()["code"], expected['code'])
            if response.json()['code'] == 0:
                sql = "select `status` from futureloan.loan where id = {};".format(self.loan_id)
                after_state = self.db.query(sql)['status']
                self.assertEqual(expected['status'], after_state)
            logger.info('**********第%d条<%s>用例测试结束**********' % (case_data['case_id'], case_data['title']))
            case_result = "pass"

        except AssertionError as error:
            logger.error("第{}用例出现异常,异常为{}".format(case_data['case_id'], error))
            case_result = "fail"
            raise error

        finally:
            # 最后执行用例回写操作
            row = case_data['case_id'] + 1
            self.excel.excel_write(name=sheet_name, row=row, column=len(case_data), value=case_result)
            self.excel.excel_write(name=sheet_name, row=row, column=len(case_data) - 1, value=str(response.json()))
            logger.info("Write the response and result: %s " % case_result)

    def tearDown(self) -> None:
        self.db.close()

    @classmethod
    def tearDownClass(cls) -> None:
        logger.info('------------------------------TestAuditOver------------------------------')

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


n , k = [int(s) for s in input().split()]
s = set([str(s) for s in range(n + 1)])
mm = set()
for i in range(k):
    a_i, b_i = [int(s) for s in input().split()]
    j = 0
    while a_i + j * b_i <= n:
        m = a_i + j * b_i
        mm.update(str(m))
        s.remove(m)
        j += 1
print(len(s))


from enum import Enum
from typing import List

import sqlalchemy as sa
from sqlalchemy import orm as so

from .base import BaseMixin, db, IdentityMixin, TimestampMixin

__all__ = ['Chat', 'ChatEntry']

class Chat(BaseMixin, IdentityMixin, TimestampMixin, db.Model):
    """Chat Model.

    Represents a chat conversation in the application.
    """

    __tablename__ = 'chats'

    title: so.Mapped[str] = so.mapped_column(
        sa.String(64),
        unique=False,
        index=True,
        nullable=False,
    )

    entry: so.Mapped[List['ChatEntry']] = so.relationship(
        back_populates='chat',
    )

    def teaser(self, length=None) -> str:
        """Return a teaser for the chat."""
        if not self.entry:
            return ''

        first_entry = min(self.entry, key=lambda x: x.created_at)
        length = length or 150

        if len(first_entry.content) > length:
            return first_entry.content[:length - 3] + '...'

        return first_entry.content[:length]

    @classmethod
    def create_new_chat(cls, title=None):
        """Create a new chat and return the new chat."""
        title = title or 'New chat'
        new_chat = cls.create(title=title)
        new_chat.save()
        return new_chat

class ChatEntry(BaseMixin, IdentityMixin, TimestampMixin, db.Model):
    """ChatEntry Model.

    Represents a single message in a Chat.
    """
    class Role(Enum):
        """Represents the role of a :class:`.ChatEntry`."""

        USER = 'user'
        ASSISTANT = 'assistant'

        def __str__(self) -> str:
            """Get a string representation of this role.

            :return: The name of this role.
            :rtype: str
            """
            return self.name.strip().lower()

    __tablename__ = 'chat_entries'

    content: so.Mapped[str] = so.mapped_column(
        sa.Text,
        nullable=False,
    )

    chat_id: so.Mapped[int] = so.mapped_column(
        sa.ForeignKey('chats.id'),
        nullable=False
    )

    role: so.Mapped[Role] = so.mapped_column(
        sa.Enum(
            Role,
            name='role_types',
            values_callable=lambda obj: [str(item.value) for item in obj]
        ),
        nullable=False,
    )

    chat: so.Mapped['Chat'] = so.relationship(
        back_populates='entry',
    )


# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def kthSmallest(self, root, k):
        """
        :type root: TreeNode
        :type k: int
        :rtype: int
        """
        count = [0]
        ret = [0]
        self.travel(root, k, count, ret)
        return ret[0]

    def travel(self, root, k, count, ret):
        if not root:
            return None
        if root:
            self.travel(root.left, k, count, ret)
            count[0] += 1
            if count[0] == k:
                ret[0] = root.val
            self.travel(root.right, k, count, ret)

# if we can modify BST
class Solution(object):
    def kthSmallest(self, root, k):
        """
        :type root: TreeNode
        :type k: int
        :rtype: int
        """
        count = []
        self.helper(root, count)
        return count[k - 1]

    def helper(self, node, count):
        if not node:
            return

        self.helper(node.left, count)
        count.append(node.val)
        self.helper(node.right, count)

Leetcode/230_Kth Smallest Element in a BST.py


# -*- coding: utf-8 -*-
import numpy as np
from progbar import progress
import sys

def findBchange(initialPDB, multiDoseList, Bmetric, relative=True):
    # function to determine the Bfactor/Bdamage (specified by Bmetric)
    # change between the initial and later datasets --> becomes an
    # object attribute for the later datasets

    # check that valid metric specified
    if Bmetric not in ('Bfactor', 'Bdamage'):
        print('Unrecognised metric (choose between Bfactor and Bdamage)')
        print('---> terminating script...')
        sys.exit()

    print('------------------------------------------------------------')
    print('Finding {} change between first and later datasets'.format(Bmetric))
    num_atoms = len(multiDoseList)

    # ensure atom list ordered by number of atom in structure (atomnum)
    multiDoseList.sort(key=lambda x: x.atomnum)
    initialPDB.sort(key=lambda x: x.atomnum)

    BmetDic = {}
    initBfacDic = {a.getAtomID(): getattr(a, Bmetric) for a in initialPDB}

    for c, atom in enumerate(multiDoseList):

        # unessential loading bar add-in
        progress(c+1, num_atoms, suffix='')

        atmID = atom.getAtomID()
        try:
            initB = initBfacDic[atmID]
        except KeyError:
            print('Error!! Atom "{}" not present in dataset 1'.format(atmID))
            initB = np.nan
        laterBs = np.array(
            map(float, atom.densMetric[Bmetric]['Standard']['values']))

        if not relative:
            metric = list(laterBs - initB)
        else:
            metric = list((laterBs - initB)/initB)
        BmetDic[atom.getAtomID()] = metric

    print('\n---> success...')
    return BmetDic


from utilities.Constants import Constants
from indicators.Indicator import Indicator
import pandas as pd

class MACD(Indicator):

    # price is DataFrame, = adj_close
    def __init__(self, df=None, fast_period=12, slow_period=26, signal_period=9):
        super().__init__()

        self.fast_period = fast_period
        self.slow_period = slow_period
        self.signal_period = signal_period

        # Set dataframe keys
        self.indicator_key = None
        self.signal_key = None

        if df is not None:
            self.set_input_data(df)

    def set_input_data(self, df):
        super().set_input_data(df)

        self.indicator_key = Constants.get_key("MACD")
        self.signal_key = Constants.get_key("Signal")

        prices_temp = pd.DataFrame()

        df_list = []
        for ticker in self.tickers:
            if ticker in df:
                df_list.append(
                    pd.concat(
                        [df[ticker].loc[:, [self.prices_key]], prices_temp],
                        axis=1,
                        keys=[ticker]
                    )
                )

        df_indicator = pd.concat(
            df_list,
            axis=1
        )

        self.df = df_indicator.copy()

    def calculate(self):
        """function to calculate MACD
           typical values a = 12; b =26, c =9"""

        super().calculate()

        # Set temp dataframe keys
        fast_key = Constants.get_key("MA_Fast")
        slow_key = Constants.get_key("MA_Slow")

        df_result = []

        for ticker in self.tickers:

            df_data = self.df[ticker].copy()

            df_data[fast_key] = \
                df_data[self.prices_key].ewm(
                    span=self.fast_period,
                    min_periods=self.fast_period
                ).mean()

            df_data[slow_key] = \
                df_data[self.prices_key].ewm(
                    span=self.slow_period,
                    min_periods=self.slow_period
                ).mean()

            df_data[self.indicator_key] = \
                df_data[fast_key] - df_data[slow_key]

            df_data[self.signal_key] = \
                df_data[self.indicator_key].ewm(
                    span=self.signal_period,
                    min_periods=self.signal_period
                ).mean()

            df_data.drop(columns=[fast_key, slow_key], inplace=True)

            df_data.dropna(inplace=True)

            df_result.append(df_data.loc[:, [self.indicator_key, self.signal_key]])

        self.df = pd.concat(df_result, axis=1, keys=self.tickers)

        return self.df


"""Celery를 사용하는 예제"""
import random
import time
from os import path
from urllib import parse
import requests
from celery import Celery
from pydub import AudioSegment
from my_logging import get_my_logger

logger = get_my_logger(__name__)

# 크롤링 요청 간격 리스트 정의
RANDOM_SLEEP_TIMES = [x * 0.1 for x in range(10, 40, 5)]

# 아티스트 이름
ARTIST_NAME = "Maurice RAVEL "

# 앨범 타이틀
ALBUM_NAME = "The Piano Music of Maurice Ravel from archive.org"

# 크롤링 대상 URL 리스트
MUSIC_URLS = [
    'https://archive.org/download/ThePianoMusicOfMauriceRavel/01PavanePourUneInfanteDfuntePourPianoMr19.mp3',
    'https://archive.org/download/ThePianoMusicOfMauriceRavel/02JeuxDeauPourPianoMr30.mp3',
    'https://archive.org/download/ThePianoMusicOfMauriceRavel/03SonatinePourPianoMr40-Modr.mp3',
    'https://archive.org/download/ThePianoMusicOfMauriceRavel/04MouvementDeMenuet.mp3',
    'https://archive.org/download/ThePianoMusicOfMauriceRavel/05Anim.mp3',
]

# Reids의 0번째 DB를 사용하는 예
app = Celery('crawler_with_celery_sample', broker='redis://localhost:6379/0')
app.conf.update(
    # Redis에 태스크 또는 실행 결과를 저장할 때의 형식을 JSON으로 지정
    task_serializer='json',
    accept_content=['json'],
    result_serializer='json',
    timezone='Asia/Seoul',
    enable_utc=True,  # Celery 태스크 내부의 시간을 UTC로 다룸
    # 1개의 워커는 동시에 1개의 프로세스만 실행하게 함
    worker_max_tasks_per_child=1,
    # Redis에 저장되는 태스크의 실행 결과는 60초가 지나면 제거(파기)함
    result_expires=60,
    # 워커가 표준 출력으로 출력한 내용을 명령어 실행 터미널에 출력하지 않음
    worker_redirect_stdouts=False,
    # 태스크 실행 시간이 180초를 넘으면 자동으로 종료함
    task_soft_time_limit=180,

    # 어떤 태스크를 어떤 워커로 라우팅할지 설정함
    task_routes={
        'crawler_with_celery_sample.download': {
            'queue': 'download',
            'routing_key': 'download',
        },
        'crawler_with_celery_sample.cut_mp3': {
            'queue': 'media',
            'routing_key': 'media',
        },
    },
)

# 재시도는 최대 2회까지, 재시도할 때는 10초 간격을 둠
@app.task(bind=True, max_retries=2, default_retry_delay=10)
def download(self, url, timeout=180):
    """파일 내려받기"""
    try:
        # mp3 파일 이름을 URL을 기반으로 추출
        parsed_url = parse.urlparse(url)
        file_name = path.basename(parsed_url.path)

        # 요청 간격을 랜덤하게 선택
        sleep_time = random.choice(RANDOM_SLEEP_TIMES)

        # 내려받기 시작을 로그에 출력
        logger.info("[download start] sleep: {time} {file_name}".format(time=sleep_time, file_name=file_name))

        # 요청 대기
        time.sleep(sleep_time)

        # 음악 파일 내려받기
        r = requests.get(url, timeout=timeout)
        with open(file_name, 'wb') as fw:
            fw.write(r.content)

        # 내려받기 종료를 로그에 출력
        logger.info("[download finished] {file_name}".format(file_name=file_name))
        cut_mp3.delay(file_name)  # cut_mp3 함수 실행을 태스크로 큐에 넣음

    except requests.exceptions.RequestException as e:
        # 예외가 발생하면 로그를 출력하고 재시도
        logger.error("[download error - retry] file: {file_name}, e: {e}".format( file_name=file_name, e=e))
        raise self.retry(exc=e, url=url)

@app.task
def cut_mp3(file_name):
    """앞의 2초를 추출해서 저장하기"""
    logger.info("[cut_mp3 start] {file_name}".format(file_name=file_name))
    # 내려받은 파일을 pydub 데이터 형식으로 변환해서 읽어 들임
    music = AudioSegment.from_mp3(file_name)

    # mp3 파일의 앞 2초만 잘라내기
    head_time = 2 * 1000  # milliseconds
    head_part = music[:head_time]  # 잘라냄
    root_name, ext = path.splitext(file_name)  # 파일 이름을 확장자와 이외의 부분으로 분할

    # 저장
    # 원래 파일과 구별할 수 있게 확장자 이름 앞에 _head를 붙임
    file_handler = head_part.export(
        root_name + "_head" + ext,
        format="mp3",
        tags={
            'title': root_name,
            'artist': ARTIST_NAME,
            'album': ALBUM_NAME,
        }
    )
    # 주의: 파일 핸들러 닫기를 잊으면 안 됩니다.
    file_handler.close()
    logger.info("[cut_mp3 finished] {file_name}".format(file_name=file_name))

if __name__ == '__main__':
    logger.info("[main start]")
    # 크롤링 대상 URL 별로 download() 함수를 태스크로 큐에 넣음
    # 큐에 들어간 태스크는 워커에 의해서 자동 실행됨
    for music_url in MUSIC_URLS:
        download.delay(music_url)
    logger.info("[main finished]")


import pytest

from pytest_persistence import plugin

plg = plugin.Plugin()

@pytest.mark.parametrize("scope", ["session", "package", "module", "class", "function"])
@pytest.mark.parametrize("result", ["result", 42])
def test_store_fixture(result, scope):
    fixture_id = ('fixture1', scope, 'tests/test_mock.py')
    plg.store_fixture(result, fixture_id, 'tests/test_mock.py', None)
    if scope == "session":
        assert plg.output[scope] == {"('fixture1', 'session', 'tests/test_mock.py', None)": result}
    else:
        assert plg.output[scope]["tests/test_mock.py"] == {
            f"('fixture1', '{scope}', 'tests/test_mock.py', None)": result}

@pytest.fixture(params=[(x, y)
                        for x in ["session", "package", "module", "class", "function"]
                        for y in ["result", 42]])
def store_fixtures(request):
    scope = request.param[0]
    result = request.param[1]
    fixture_id = ('fixture1', scope, 'tests/test_mock.py')
    plg.store_fixture(result, fixture_id, 'tests/test_mock.py', None)
    plg.input = plg.output
    return scope, result

def test_load_fixture(store_fixtures):
    scope = store_fixtures[0]
    result = store_fixtures[1]
    fixture_id = ('fixture1', scope, 'tests/test_mock.py')
    fixture_result = plg.load_fixture(fixture_id, 'tests/test_mock.py')
    assert fixture_result == result


testname = 'TestCase apwds_1.2.1'
avoiderror(testname)
printTimer(testname,'Start','Check Ac basic wds configuration in open mode')

###############################################################################
#Step 1
#操作
# AC上show wireless network 2
#预期
# 显示WDS Mode....................................... Disable
################################################################################
printStep(testname,'Step 1','WDS mode is disable by default')
res1=1
#operate
data = SetCmd(switch1,'show wireless network 2')
res1 = CheckLine(data,'WDS Mode','Disable',IC=True)
#result
printCheckStep(testname, 'Step 1',res1)

################################################################################
#Step 2
#操作
#AC上配置
# Network 2
# wds-mode rootap
#预期
#显示WDS Mode is enabled and the other network configuration is cleared
################################################################################

printStep(testname,'Step 2',\
                    'Config network 2 as wds mode')
res1=1
#operate
EnterNetworkMode(switch1,2)
data = SetCmd(switch1,'wds-mode rootap')
res1 = CheckLine(data,'WDS Mode is enabled and the other network configuration is cleared',IC=True)
#result
printCheckStep(testname, 'Step 2',res1)
################################################################################
#Step 3
#操作
#AC在network2下配置vlan 200
#预期
#显示The Network WDS mode has been enabled, so this configuration is invalid.
################################################################################
printStep(testname,'Step 3',\
                    'Config vlan 200 in network 2')
res1=1
# operate
data = SetCmd(switch1,'vlan 200')
res1 = CheckLine(data,'The Network WDS mode has been enabled, so this configuration is invalid')
#result
printCheckStep(testname, 'Step 3',res1)
################################################################################
#Step 4
#操作
# AC配置
# network 2
# wds-mode rootap
# security mode none
# wds-remote-vap ap2mac
# ssid ${wds_ssid}
#预期
# AC上show wireless network 2，显示
# SSID........................................... ${wds_ssid}
# WDS Mode....................................... RootAP
# WDS Remote VAP MAC............................. ap2mac
# Security Mode.................................. None
################################################################################
printStep(testname,'Step 4',\
                    'Config network 2 as wds and open mode')
res1=1
#operate
# AC上配置network2为wds，apmode为rootap
Ac_wds_config(switch1,2,
                ssid=wds_ssid,
                remotemac=ap2vapmac)
data = SetCmd(switch1,'show wireless network 2')
res1 = CheckLineList(data,[('SSID',wds_ssid),
                        ('WDS Mode','RootAP'),
                        ('WDS Remote VAP MAC',ap2vapmac),
                        ('Security Mode','None')],
                        IC=True)
#result
printCheckStep(testname, 'Step 4',res1)
################################################################################
#Step 5
#操作
# AC配置
# network 2
# no wds-mode
#预期
# AC上show wireless network 2，显示
# 显示WDS Mode....................................... Disable
################################################################################
printStep(testname,'Step 5',\
                    'No wds mode in network 2')
res1=1
#operate
EnterNetworkMode(switch1,2)
data = SetCmd(switch1,'no wds-mode')
IdleAfter(5)
data = SetCmd(switch1,'show wireless network 2')
res1 = CheckLine(data,'WDS Mode','Disable',IC=True)
#result
printCheckStep(testname, 'Step 5',res1)
################################################################################
#Step 6
#操作
# AC配置
# network 2
# wds-mode rootap
# security mode none
# wds-remote-vap ap2mac
# ssid ${wds_ssid}
# 下发配置apply ap profile 1
#预期
# AP1上get wds wds1
# 显示
# radio wlan0
# wds-status up
# wds-mode rootap
# wds-ssid ${wds_ssid}
# wds-security-policy plain-text
# remote-mac ap2mac
################################################################################
printStep(testname,'Step 6',\
                    'Config network 2 as wds and open mode',\
                    'Apply ap profile 1')
res1=res2=1
#operate
# AC上配置network2为wds，apmode为rootap，并下发profile 1
Ac_wds_config(switch1,2,
                ssid=wds_ssid,
                remotemac=ap2vapmac)
res1=WirelessApplyProfileWithCheck(switch1,['1'],[ap1mac])
res2 = Check_ap_wdsconfig(ap1,Ap1cmdtype,wds1num,
                        check=[('radio',wlan),
                            ('wds-status','up'),
                            ('wds-mode','rootap'),
                            ('wds-ssid',wds_ssid),
                            ('wds-security-policy','plain-text'),
                            ('remote-mac',ap2mac_type1)],
                            IC=True)
#result
printCheckStep(testname, 'Step 6',res1,res2)
################################################################################
#Step 7
#操作
#恢复默认配置
################################################################################
printStep(testname,'Step 7',\
          'Recover initial config for switches.')

#operate
# 清除network2配置
ClearNetworkConfig(switch1,2)
WirelessApplyProfileWithCheck(switch1,['1'],[ap1mac])
#end
printTimer(testname, 'End')


"""
To render html web pages
"""
import random
from django.http import HttpResponse

from django.template.loader import render_to_string

from articles.models import Article

def home_view(request, id=None, *args, **kwargs):
    """
    Take in a request (Django send request)
    return HTML as a response
    (We pick to return the response)
    """
    name = "Artem" # hard coded
    number = random.randint(1, 2) # pseudo random

    article_obj = Article.objects.get(id=number)
    article_queryset = Article.objects.all()

    context = {
        "object_list": article_queryset,
        "title": article_obj.title,
        "content": article_obj.content,
        "id": article_obj.id
    }

    # Django templates
    HTML_STRING =  render_to_string("home-view.html", context=context)
    return HttpResponse(HTML_STRING)


import os
import subprocess
import time
import sys
import tracemalloc
import concurrent.futures
import threading

stopProcessing = False

def get_all_pids():
    ps_cmd =  ['ps', '-e', '-o', 'pid']
    out = subprocess.Popen(ps_cmd, stdout = subprocess.PIPE).communicate()[0]
    out = ''.join(map(chr,out))
    out = out.splitlines()
    out.pop(0)
    return out

def perf_run(pid):
    i=0

    while(True):
        i+=1
        op_file = 'cpu_output_%s'%(pid)
        cmd='perf stat -x, -o %s -p %s sleep %s' % (op_file, pid, sys.argv[1])
        start_time = time.time()
        p=os.system(cmd)
        end_time = time.time()
        power_thread = threading.Thread(target=power_calc,args=(pid,start_time,end_time,))
        power_thread.start()
    rm(pid)

def power_calc(pid,start,end):
    cpu_output = 'cpu_output_%s' %(pid)
    with open(cpu_output) as reader:
        lines = [line.rstrip('\n') for line in reader]
    task_clock=0.0 if (lines[2].split(',')[4]=="<not defined>" or lines[2].split(',')[4]=="") else float(lines[2].split(',')[4])
    context_switch = 0.0 if (lines[3].split(',')[4]=="<not defined>" or lines[3].split(',')[4]=="") else float(lines[3].split(',')[4])
    cpu_migration = 0.0 if (lines[4].split(',')[4]=="<not defined>" or lines[4].split(',')[4]=="") else float(lines[4].split(',')[4])
    page_faults = 0.0 if (lines[5].split(',')[4]=="<not defined>" or lines[5].split(',')[4]=="") else float(lines[5].split(',')[4])
    cycles = 0.0 if (lines[6].split(',')[4]=="<not defined>" or lines[6].split(',')[4]=="") else float(lines[6].split(',')[4])
    instructions =0.0 if (lines[7].split(',')[4]=="<not defined>" or lines[7].split(',')[4]=="") else float( lines[7].split(',')[4])
    branches = 0.0 if (lines[8].split(',')[4]=="<not defined>" or lines[8].split(',')[4]=="") else float(lines[8].split(',')[4])
    branch_misses = 0.0 if (lines[9].split(',')[4]=="<not defined>" or lines[9].split(',')[4]=="") else float(lines[9].split(',')[4])

    lock = threading.Lock()
    lock.acquire()

    cmd2 = ["python3", "predict.py",str(task_clock)+","+str(context_switch)+","+str(cpu_migration)+","+str(page_faults)+","+str(cycles)+","+str(instructions)+","+str(branches)+","+str(branch_misses)]
    p1 = str(subprocess.Popen(cmd2,stdout=subprocess.PIPE).communicate()[0])

    with open("power_output2","a") as fp:
        fp.write(str(start)+","+str(end)+","+pid+","+p1[2:-3]+" \n")

    lock.release()
    print(str(start)+"-"+str(end)+" for pid:"+pid+" carbon output:" + p1[2:-3])

def rm(pid):
    cmd='sudo rm cpu_output_%s' %(pid)
    os.system(cmd)

if __name__=='__main__':
    pids = get_all_pids()

    with open("power_output2","w") as fp:
        fp.write("start_time,end_time,pid,power \n")

    with concurrent.futures.ThreadPoolExecutor(max_workers=len(pids)) as executor:
        for i in range(0,len(pids)):
            executor.submit(perf_run,str(pids[i]).strip())
        executor.shutdown()

#Task Clock, Context-Switches, CPU-migrations, page-faults, cycles, instructions, branches, branch-misses


# tree ! 트리 나라 관광 가이드
# 부모 도시 없다면 만들어주기

K = int(input())
A = list(map(int, input().split()))
N = max(A)

parent = [-2] * (N+1) # 루트 도시의 부모는 -1이니 존재하지 않는 값인 -2로 통일
parent[A[0]] = -1 # 루트 도시가 0번이 아닌 경우도 있다!
for i in range(K-1): # 만약 아직 부모가 없는 도시라면 바로 전 도시를 부모로 하기
    if parent[A[i+1]] == -2:
        parent[A[i+1]] = A[i]

print(N+1)
print(*parent)


#!/usr/bin/python

import curses
import sys
import RPi.GPIO as GPIO

def main(stdscr):
    # do not wait for input when calling getch
    stdscr.nodelay(1)

    initGPIO()

    while True:
        # get keyboard input, returns -1 if none available
        c = stdscr.getch()
        if c != -1:
            # print numeric value
            stdscr.addstr(str(c))
            stdscr.refresh()
            # return curser to start position
            stdscr.move(0, 0)
        if c == 97:
            GPIO.cleanup()
            sys.exit('Bye bye')
        elif c == 117:
            lightToggle()
        elif c == 114:
            light()

def initGPIO():
    GPIO.setmode(GPIO.BCM)
    GPIO.setup(8, GPIO.OUT)

def lightToggle():
    GPIO.output(8, not GPIO.input(8))

def light():
    GPIO.output(8, GPIO.HIGH)

def dark():
    GPIO.output(8, GPIO.LOW)

if __name__ == '__main__':
    curses.wrapper(main)


import re
import json
from collections import defaultdict

def file_paths(file_path= 'logs_2/postcts.log1'):
    with open(file_path, 'r') as file:
        file_data = file.read()
    return file_data

def parse_log_file():
    file_contents = file_paths()

    # Compile regex patterns for improved performance
    regex_pattern_summary = re.compile(
        r'\s+opt_design Final Summary(.*?)Routing Overflow:\s*(.*?)\n', re.DOTALL)
    regex_pattern_setupHold = re.compile(
        r'\|\s+(?:WNS \(ns\):\|\s*(-?\d+\.?\d+)|TNS \(ns\):\|\s*(-?\d+\.?\d+)|Violating Paths:\|\s*(\d+\.?\d+)\s*)')
    pattern_DRV = re.compile(
        r'\|\s+(max_cap|max_tran|max_fanout)\s*\|\s*(\d+\s*\(\d+\))\s*\|\s*(-?\d+\.?\d+)\s*')
    regex_pattern_density = re.compile(r'Density:\s*(\d+\.?\d+)\s*')
    # regex_pattern_routing = re.compile(
    #     r'Routing Overflow:\s*(-?\d+\.?\d+)\%\s*H and (-?\d+\.?\d+)\%\s*V')
    # or
    regex_pattern_routing = re.compile(
        r'(-?\d+\.?\d+)\%\s*H and (-?\d+\.?\d+)\%\s*V')
    regex_pattern_total_power = re.compile(
        r'^(Total Power\s*\n)[-]*\n(Total Internal Power:\s*(.*?)\s*(\d+\.?\d+)%\n)(Total Switching Power:\s*(.*?)\s*(\d+\.?\d+)%\n)(Total Leakage Power:\s*(.*?)\s*(\d+\.?\d+)%\n)', re.MULTILINE)
    regex_pattern_instance_design = re.compile(
        r'Instances in design\s*=\s*(\d+)')
    regex_pattern_vt = re.compile(
        r'(LVT|SVT|HVT) : inst = (\d+) \((\d+\.?\d+)%\)')
    regex_pattern_run_time = re.compile(
        r'totcpu=(.*?),\s*real=(.*?),\s*mem=(.*?)$')

    setUpMode = defaultdict(list)
    holdMode = defaultdict(list)
    DRV = {}
    density = []
    congestion_overflow = {"H": [], "V": []}
    VT_dist = defaultdict(list)
    insts_count = []
    power = {"Dynamic": [], "Leakage": []}
    runTime = []

    summary_match = regex_pattern_summary.findall(file_contents)

    # Finding Total Summary (WNS, TNS, FEP), DRV's, Density, Routing_Overflow
    if summary_match:
        summary_data = summary_match[-1][0]
        # print(summary_data)
        wns_tns_match = re.findall(regex_pattern_setupHold, summary_data)

        if len(wns_tns_match) > 4:
            setUpMode["WNS"].append(wns_tns_match[0][0])
            setUpMode["TNS"].append(wns_tns_match[1][1])
            setUpMode["FEP"].append(wns_tns_match[2][2])
            holdMode["WNS"].append(wns_tns_match[3][0])
            holdMode["TNS"].append(wns_tns_match[4][1])
            holdMode["FEP"].append(wns_tns_match[5][2])
        else:
            setUpMode["WNS"].append(wns_tns_match[0][0])
            setUpMode["TNS"].append(wns_tns_match[1][1])
            setUpMode["FEP"].append(wns_tns_match[2][2])
            holdMode["WNS"].append("-")
            holdMode["TNS"].append("-")
            holdMode["FEP"].append("-")

        matches = re.findall(pattern_DRV, summary_data)
        DRV = {key: {"terms": value, "slack": slack}
               for key, value, slack in matches}

        density_match = re.search(regex_pattern_density, summary_data)
        density_val = density_match.group(1) if density_match else "-"
        density.append(density_val)

        # routing_overflow_match = re.search(regex_pattern_routing, summary_match[-1])
        routing_overflow_match = re.search(
            regex_pattern_routing, summary_match[-1][1])
        routing_overflow_h = routing_overflow_match.group(
            1) if routing_overflow_match else "-"
        routing_overflow_v = routing_overflow_match.group(
            2) if routing_overflow_match else "-"
        congestion_overflow["H"].append(routing_overflow_h)
        congestion_overflow['V'].append(routing_overflow_v)
    else:
        print("Setup value pattern not found")

    # Finding the Total Power (Switching, Leakage)
    total_power_match = regex_pattern_total_power.search(file_contents)
    if total_power_match:
        power['Dynamic'].append(total_power_match.group(6))
        power['Leakage'].append(total_power_match.group(9))
    else:
        print("Pattern not found for Total Power.")

    # Find Instance count
    matches = regex_pattern_instance_design.findall(file_contents)
    if matches:
        instances_in_design = matches[-1].strip()
        insts_count.append(instances_in_design)
    else:
        print("Pattern not found for Instances in Design.")

    # Find LVT, SVT, HVT and %
    matches = regex_pattern_vt.findall(file_contents)
    for design_type, inst_value, percentage in matches[-3:]:
        VT_dist[design_type].append(inst_value)
        VT_dist[f"{design_type} %"].append(percentage)

    # Find Run_Time
    run_time_match = regex_pattern_run_time.search(file_contents)
    if run_time_match:
        runTime.append(run_time_match.group(2))
    else:
        print("Pattern not found for Run Time.")

    return {
        "setUpMode": dict(setUpMode),
        "holdMode": dict(holdMode),
        "DRV": DRV,
        "density": density,
        "congestion_overflow": congestion_overflow,
        "VT_dist": dict(VT_dist),
        "insts_count": insts_count,
        "power": power,
        "runTime": runTime
    }

# parsed_data = parse_log_file()

# output_file_path = 'parsed_data.json'

# # Write the data to the JSON file
# with open(output_file_path, 'w') as json_file:
#     json.dump(parsed_data, json_file, indent=4)

# def main():
#     file_contents = file_paths()
#     try:

#         pattern_text_between = r'\s+flow\.cputime\s+flow.realtime\s+timing\.setup\.tns\s+timing\.setup\.wns\s+snapshot\nUM:\s*\d+\.?\d+\s+\d+\.?\d+\s+report_finish'

#         # Use re.search() to find the pattern in the string
#         match = re.search(pattern_text_between, file_contents, re.DOTALL | re.MULTILINE)

#         if match:
#             print(match)
#         else:
#             print("Pattern not found.")
#     except Exception as e
#         print(e)

# file_path = 'logs_2/postcts.log1'
# main(file_path)

import os

def get_max_numbered_log(logfiles, base_name):
    pattern = re.compile(fr"{base_name}\.log(\d*)")
    number_logs = [file for file in log_files if pattern.fullmatch(file)]
    # print(number_logs)

    if number_logs:
        print(number_logs)

    return False

folder_path = 'D:/COE_07/COE-PRO/ZLogParse/logs_1'
log_files = os.listdir(folder_path)

selected_logs = []
base_names_to_check = ['floorplan', 'cts', 'prects', 'postcts']

for base_name in base_names_to_check:
    selected_log = get_max_numbered_log(log_files, base_name)
    # if selected_log:
    #     selected_logs.append(selected_log)

# print(selected_logs)


import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import sklearn
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import confusion_matrix, classification_report
import xlsxwriter

#Reading the file into the system
file1 = pd.read_csv("/home/user/Downloads/portugese bank/bank-full-encoded.csv", sep=";" ,parse_dates= True)
print(file1.shape)

#Splitting into x,y and train and test data
y = file1["y"].values
x = file1.drop("y", axis = 1).values

x_train, x_test, y_train, y_test = train_test_split(x, y, test_size= 0.3, random_state= 25)

#Running the Random Forrest Classifier
rf_classifier = RandomForestClassifier()
rf_classifier.fit(x_train, y_train)
rf_prediction = rf_classifier.predict(x_test)

print("\nThe Confusion Matrix is as follows:\n", confusion_matrix(y_test,rf_prediction))

print("\nThe Classification Report for the random forrest classifier is as follows:\n", classification_report(y_test, rf_prediction))

# Writing output to Excel

writer = pd.ExcelWriter(path = "/home/user/Downloads/portugese bank/Random Forrest.xlsx", engine = 'xlsxwriter')
workbook = writer.book

rf_output = []
for i in rf_prediction:
    rf_output.append(i)

df_rfoutput = pd.DataFrame(rf_output)
df_rfoutput.to_excel(writer, sheet_name="RandomForrest", startrow=0, startcol=0)

print(len(rf_prediction))

features = rf_classifier.feature_importances_
print(features)
print(len(features))

feature_list = file1.columns.values.tolist()
print(feature_list)

x = 0
for (i,j) in np.ndenumerate(features):
    x = x + j

print(x)

print("\nThe feature list and its corresponding importance is as follows:")
feature_output = []
for i in range(26):
    print(feature_list[i], "=", features[i]*100, "%")
    feature_output.append(features[i]*100)

df_feature_names = pd.DataFrame(feature_list)
df_feature_values = pd.DataFrame(feature_output)
df_feature_values.to_excel(writer, sheet_name="RandomForrest", startrow= 0, startcol=5)
df_feature_names.to_excel(writer, sheet_name="RandomForrest", startrow= 0, startcol=4)

workbook.close()
writer.save()

Models/Decision Trees and Random Forrest.py


""" Отсортируйте по убыванию методом пузырька одномерный целочисленный массив,
    заданный случайными числами на промежутке [-100; 100). Выведите на экран исходный
    и отсортированный массивы.
"""
import random, math

def bubble_sort(array):
    n = 1
    while n < len(array):
        change = 0
        for i in range(len(array) - n):
            if array[i] < array[i + 1]:  # чуть не забыл, блин..!
                array[i], array[i + 1] = array[i + 1], array[i]
                change += 1
        if not change:
            break
        n += 1

package = [math.floor(random.uniform(-1, 1) * 100) for i in range(11)]
print(package)
print('*' * 100)
bubble_sort(package)
print(package)


#!/usr/bin/python3

# Codeforces - Educational Round #90
# Author: frostD
# Problem B - 01 Game

def read_int():
	n = int(input())
	return n

def read_ints():
	ints = [int(x) for x in input().split(" ")]
	return ints

#---

def solve(s):
	moves = 0
	ms1 = s.split('10') # move set 1
	ms2 = s.split('01') # move set 2

	while len(ms1) > 1 or len(ms2) > 1:
		if len(ms1) > len(ms2):
			moves += len(ms1) - 1
			s = ''.join(ms1)

		else:
			moves += len(ms2) - 1
			s = ''.join(ms2)

		ms1 = s.split('10') # move set 1
		ms2 = s.split('01') # move set 2

	if moves % 2 == 1:
		return "DA"
	else:
		return "NET"

# Main
t = read_int()
for case in range(t):
	s = input()
	sol = solve(s)
	print (sol)


def read_cook_book(file, cook_book_):
    list_temp = []
    line1 = str(file.readline().strip())
    num2 = int(file.readline())
    i = 0
    while i < num2:
        line = file.readline()
        list_line = line.split(' | ')
        dict_ingr = {'ingredient_name': list_line[0],
                     'quantity': int(list_line[1]),
                     'measure': list_line[2].strip()}
        list_temp.append(dict_ingr)
        i += 1
    cook_book_[line1] = list_temp
    return cook_book_

def get_shop_list_by_dishes(dishes, person_count):
    ingredient_order = {}
    for dish in dish_order:
        ing_ord = cook_book[dish]
        for ingr in ing_ord:
            measure_quantity = {}
            measure = ingr.get('measure')
            measure_quantity['measure'] = measure
            quantity = ingr.get('quantity')*pers_count
            measure_quantity['quantity'] = quantity
            ing = list(ingredient_order.keys())
            ingr_key = ingr.get('ingredient_name')
            if ing.count(ingr_key) > 0:
                ingredient_order.get(ingr_key)
                del(ingredient_order[ingr_key])
                quantity_rep = ingr.get('quantity') * pers_count
                measure_quantity['quantity'] = quantity + quantity_rep
            ingredient_order[ingr_key] = measure_quantity
    return ingredient_order

file_ = 'recipes.txt'
cook_book = {}

with open(file_, encoding="utf-8") as file_:
    read_cook_book(file_, cook_book)
    for line in file_:
        read_cook_book(file_, cook_book)

dish_order = ['Омлет', 'Фахитос', 'Утка по-пекински']
pers_count = 3

order = get_shop_list_by_dishes(dish_order, pers_count)
print(order)


# !/usr/bin/python
import os
import sys

# Logging configuration
import logging

class logger(logging.Logger):

    def __init__(self):
        """Initializer."""
        super().__init__()
        logging.basicConfig(filename="errlog.log",
                    filemode="a",
                    format="(%(asctime)s)  | %(name)s | %(levelname)s:%(message)s",
                    datefmt="%d  %B  %Y , %H:%M:%S",
                    level=os.environ.get("LOGLEVEL", "INFO"))


import matplotlib.pyplot as plt
import numpy as np

#plot 1
x=np.arange(-8,8,0.1)
y=x**3
plt.subplot(2,2,1)
plt.plot(x,y)
plt.title("plot 1")

#plot 2
x=np.linspace(0,3*np.pi,400)
y=x/(1+(x**4)*(np.sin(x))**2)
plt.subplot(2,2,2)
plt.plot(x,y)
plt.title("plot 2")

#plot 3
x=np.linspace(1,10,400)
y=np.sin(1/(x**(1/2)))
plt.subplot(2,2,3)
plt.plot(x,y)
plt.title("plot 3")

#plot 4
x=np.linspace(0,2*np.pi,400)
y=x**(np.sin(x))
plt.subplot(2,2,4)
plt.plot(x,y)
plt.title("plot 4")

plt.show()


from __future__ import annotations
import typing
from dataclasses import dataclass
from anchorpy.borsh_extension import EnumForCodegen
import borsh_construct as borsh

class UninitializedJSON(typing.TypedDict):
    kind: typing.Literal["Uninitialized"]

class ActiveJSON(typing.TypedDict):
    kind: typing.Literal["Active"]

class PostOnlyJSON(typing.TypedDict):
    kind: typing.Literal["PostOnly"]

class PausedJSON(typing.TypedDict):
    kind: typing.Literal["Paused"]

class ClosedJSON(typing.TypedDict):
    kind: typing.Literal["Closed"]

class TombstonedJSON(typing.TypedDict):
    kind: typing.Literal["Tombstoned"]

@dataclass
class Uninitialized:
    discriminator: typing.ClassVar = 0
    kind: typing.ClassVar = "Uninitialized"

    @classmethod
    def to_json(cls) -> UninitializedJSON:
        return UninitializedJSON(
            kind="Uninitialized",
        )

    @classmethod
    def to_encodable(cls) -> dict:
        return {
            "Uninitialized": {},
        }

@dataclass
class Active:
    discriminator: typing.ClassVar = 1
    kind: typing.ClassVar = "Active"

    @classmethod
    def to_json(cls) -> ActiveJSON:
        return ActiveJSON(
            kind="Active",
        )

    @classmethod
    def to_encodable(cls) -> dict:
        return {
            "Active": {},
        }

@dataclass
class PostOnly:
    discriminator: typing.ClassVar = 2
    kind: typing.ClassVar = "PostOnly"

    @classmethod
    def to_json(cls) -> PostOnlyJSON:
        return PostOnlyJSON(
            kind="PostOnly",
        )

    @classmethod
    def to_encodable(cls) -> dict:
        return {
            "PostOnly": {},
        }

@dataclass
class Paused:
    discriminator: typing.ClassVar = 3
    kind: typing.ClassVar = "Paused"

    @classmethod
    def to_json(cls) -> PausedJSON:
        return PausedJSON(
            kind="Paused",
        )

    @classmethod
    def to_encodable(cls) -> dict:
        return {
            "Paused": {},
        }

@dataclass
class Closed:
    discriminator: typing.ClassVar = 4
    kind: typing.ClassVar = "Closed"

    @classmethod
    def to_json(cls) -> ClosedJSON:
        return ClosedJSON(
            kind="Closed",
        )

    @classmethod
    def to_encodable(cls) -> dict:
        return {
            "Closed": {},
        }

@dataclass
class Tombstoned:
    discriminator: typing.ClassVar = 5
    kind: typing.ClassVar = "Tombstoned"

    @classmethod
    def to_json(cls) -> TombstonedJSON:
        return TombstonedJSON(
            kind="Tombstoned",
        )

    @classmethod
    def to_encodable(cls) -> dict:
        return {
            "Tombstoned": {},
        }

MarketStatusKind = typing.Union[
    Uninitialized, Active, PostOnly, Paused, Closed, Tombstoned
]
MarketStatusJSON = typing.Union[
    UninitializedJSON, ActiveJSON, PostOnlyJSON, PausedJSON, ClosedJSON, TombstonedJSON
]

def from_decoded(obj: dict) -> MarketStatusKind:
    if not isinstance(obj, dict):
        raise ValueError("Invalid enum object")
    if "Uninitialized" in obj:
        return Uninitialized()
    if "Active" in obj:
        return Active()
    if "PostOnly" in obj:
        return PostOnly()
    if "Paused" in obj:
        return Paused()
    if "Closed" in obj:
        return Closed()
    if "Tombstoned" in obj:
        return Tombstoned()
    raise ValueError("Invalid enum object")

def from_json(obj: MarketStatusJSON) -> MarketStatusKind:
    if obj["kind"] == "Uninitialized":
        return Uninitialized()
    if obj["kind"] == "Active":
        return Active()
    if obj["kind"] == "PostOnly":
        return PostOnly()
    if obj["kind"] == "Paused":
        return Paused()
    if obj["kind"] == "Closed":
        return Closed()
    if obj["kind"] == "Tombstoned":
        return Tombstoned()
    kind = obj["kind"]
    raise ValueError(f"Unrecognized enum kind: {kind}")

layout = EnumForCodegen(
    "Uninitialized" / borsh.CStruct(),
    "Active" / borsh.CStruct(),
    "PostOnly" / borsh.CStruct(),
    "Paused" / borsh.CStruct(),
    "Closed" / borsh.CStruct(),
    "Tombstoned" / borsh.CStruct(),
)


from django.conf.urls import patterns, include, url

urlpatterns = patterns('',
    url(r'^$', 'informes.views.home', name='i_home'),
    url(r'^pendientes/$', 'informes.views.informes_pendientes', name='i_pend'),
    url(r'^arreglados/$', 'informes.views.informes_arreglados', name='i_fixed'),
    url(r'^noarreglados/$', 'informes.views.informes_wontfix', name='i_wontfix'),

    url(r'^equipo/(?P<equipo_id>\d+)/levantar/$', 'informes.views.levantar_informe_equipo', name='informe_le'),
    url(r'^(?P<informe_id>\d+)/resolver/$', 'informes.views.resolver_informe', name='informe_r'),

)


num = input()

#First Method for python
print(num[::-1])

#Second Method for c
num,a = int(num),0
while num > 0:
    a = a*10 + num%10
    num = num//10

print(a)

EveryOther/python/Codes/New codes/Rev num in 2 ays.py


#!/usr/bin/python

from websocket import create_connection
import unittest
from common import read_info
from common import read_message
from common import check_action as c
import time
import json

class websocket_request(unittest.TestCase):
    """32. 安装脚本"""
    def setUp(self):
        rt=read_info.ReadInfo()
        web=rt.get_device_ip()
        port=rt.get_port()
        url=web+":"+port
        try:
            self.ws=create_connection(url,timeout=5)    #建立设备连接
            if self.ws.connected:
                print("服务：%s连接成功!"%url)
        except Exception as e:
            print("websocket连接失败：%s"%e)
            pass

    def test_install_script(self):
        """32. 安装脚本/32.1. 发送数据 """
        rm=read_message.ReadMessage()
        data_c=rm.get_data("5","control")
        url=self.ws
        print("step 1、控制设备：")
        c.checkAction(url,data_c)
        time.sleep(1)

        data_initialize=rm.get_data("3","initialize")
        print("step 2、初始化：")
        c.checkAction(url,data_initialize)
        time.sleep(8)

        data_install_script=rm.get_data("32","install_script")

        """重新设置安装文件名"""
        data_dict=json.loads(data_install_script)
        data_dict["data"]["index"]=1
        data_dict["data"]["name"]="test.lua"
        print("安装脚本："+data_dict["data"]["name"])
        data_install_script=json.dumps(data_dict)
        print(data_install_script)

        print("step 3、安装test.lua文件")
        c.checkAction(url,data_install_script)
        time.sleep(2)

        data_script_start=rm.get_data("1","run_script_start_test")
        print("step 4、运行step 3安装的脚本：test.lua：")
        c.checkAction(url,data_script_start)
        time.sleep(6)

        data_script_stop=rm.get_data("1","run_script_stop")
        print("step 5、停止脚本运行：")
        c.checkAction(url,data_script_stop)

        data_r=rm.get_data("6","release")
        print("step 6、释放设备：")
        c.checkAction(url,data_r)

    def tearDown(self):
        self.ws.close()

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


import pickle
import numpy as np
from flask import Flask, request, jsonify

# Load the pickled model
with open('model.pkl', 'rb') as file:
    model = pickle.load(file)

app = Flask(__name__)

# Endpoint for making predictions
@app.route('/predict', methods=['POST'])
def predict():
    try:
        data = request.get_json(force=True)
        # Assuming your input data is in the format of a list of dictionaries
        # where each dictionary represents a row in the CSV
        predictions = []
        for row in data:
            # Preprocess the input data (You may need to adjust this based on your actual data)
            input_data = [
                int(row['AGE']), int(row['PackHistory']),
                int(row['MWT1']), int(row['MWT2']), float(row['FEV1']), float(row['FVC']),
                int(row['CAT']), int(row['HAD']), float(row['SGRQ']),
                int(row['copd']), int(row['gender']), int(row['smoking'])
            ]
            # Make prediction using the loaded model
            prediction = model.predict([input_data])
            predictions.append(int(prediction[0]))

        return jsonify({'predictions': predictions})
    except Exception as e:
        return jsonify({'error': str(e)}), 400

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


from timeit import default_timer as timer
import re

start = timer()
file = open('input.txt')

# exponential growth, every 7 days, after 0
# unsynchronized
# +2 day before first cycle

memo = {} # global const
def solve_babies(days, initial_clock, spawn_clock, cycle):
	if initial_clock > days:
		return 0

	key = (days, initial_clock)
	if key in memo:
		return memo[key]

	# sync to first cycle and spawn
	days -= initial_clock
	count = 1 + solve_babies(days, spawn_clock, spawn_clock, cycle)

	# if still enough for more cycles, recurse further
	while days >= cycle:
		days -= cycle
		count += 1 + solve_babies(days, spawn_clock, spawn_clock, cycle)

	memo[key] = count
	return count

spawn = 9
cycle = 7
days = 80

result = 0
for initial_clock in file.readlines()[0].split(","):
	initial_clock = int(initial_clock) + 1 # converting so that spawn happens on 0th day instead of after
	result += 1 + solve_babies(days, initial_clock, spawn, cycle)

print("Completed in %fms" % ((timer() - start) * 1000))
print("%d is the result" % result)


import logging
from sentry.client.handlers import SentryHandler

logger = logging.getLogger()
# ensure we havent already registered the handler
if SentryHandler not in map(lambda x: x.__class__, logger.handlers):
    logger.addHandler(SentryHandler(logging.WARNING))

    # Add StreamHandler to sentry's default so you can catch missed exceptions
    logger = logging.getLogger('sentry.errors')
    logger.propagate = False
    logger.addHandler(logging.StreamHandler())


from NaiveTruthReader import NaiveTruthReader
from headbytes import HeadBytes
import numpy as np

feature_maker = HeadBytes(10)
reader = NaiveTruthReader(feature_maker, "test.csv")
reader.run()

data = [line for line in reader.data]

split_index = int(0.5 * len(data))
train_data = data[:split_index]  # split% of data.
test_data = data[split_index:]  # 100% - split% of data.

# np.zeros: create empty 2D X numpy array (and 1D Y numpy array) for features.
X_train = np.zeros((len(train_data), int(reader.feature.nfeatures)))
Y_train = np.zeros(len(train_data))

X_test = np.zeros((len(test_data), int(reader.feature.nfeatures)))
Y_test = np.zeros(len(test_data))

groups = [[train_data, X_train, Y_train],
        [test_data, X_test, Y_test]]

for group in groups:
	raw_data, X, Y = group
	print("new group")
	for i in range(len(raw_data)):
		print(raw_data[i][2])
		x, y = reader.feature.translate(raw_data[i])
		X[i] = x
		Y[i] = y
	print("X:", X)
	print("Y:", Y)


from app.shared.common.recaptcha import CaptchaValidation
from app.shared.database.dynamodb_client import DynamodbClient
from app.shared.models import CustomerReviewModel

def main(object_id: str) -> dict:
    dynamodb = DynamodbClient()
    try:
        dynamodb.contact_us.delete(object_id)
    except Exception as error:
        return({'error': error}, 400)

    return ({'success': 'Message deleted successfully'}, 200)


# reference: J. P. Tignol
#   "Galois Thoery of Algebraic Equations" chapter 12

import numpy as np
from sympy import factorint,root,expand

class Period:# Gaussian periods
    @classmethod
    def init(cls,p):# p must be prime
        n = p-1

        g = 2 # generator mod p
        f = factorint(n)
        while True:
            for q in f:
                if pow(g, n//q, p)==1: break
            else:
                break
            g+=1

        i = np.empty(p, dtype=np.int)
        x = np.empty(n, dtype=np.int)
        a = 1
        for j in range(n):
            x[j] = a
            i[a] = j
            a *= g
            a %= p

        cls.p = p
        cls.x = x
        cls.index = i
        cls.factor = f

    @classmethod
    def SetDim(cls,e):# e must divide p-1
        p = cls.p
        x = cls.x
        i = cls.index
        n = p-1
        f = n//e

        # multiplication table
        w = np.zeros((e,e), dtype=np.int)
        for j in range(e):
            for k in range(j,n,e):
                l = (1 + x[k])%p
                if l: w[j,i[l]%e] += 1
                else: w[j] -= f

        w = [np.roll(w,j,(0,1)) for j in range(e)]
        cls.w = np.asarray(w)

    @classmethod
    def save_context(cls):
        if not hasattr(cls, 'p'): return
        context = {'p':cls.p, 'x':cls.x,
                   'index':cls.index,
                   'factor':cls.factor}
        if hasattr(cls, 'context'):
            cls.context.append(context)
        else:
            cls.context = [context]

    @classmethod
    def restore_context(cls):
        if(not hasattr(cls, 'context') or
           len(cls.context)==0): return
        context = cls.context.pop()
        cls.p = context['p']
        cls.x = context['x']
        cls.index = context['index']
        cls.factor = context['factor']

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

    def __mul__(self, p):
        c = np.dot(self.c, np.dot(p.c, self.w))
        return Period(c)

    def __pow__(self, n):
        m = (1<<(n.bit_length() - 1))>>1
        p = self
        while m:
            p *= p
            if n&m: p *= self
            m >>= 1
        return p

class Ring:# ring of cyclotomic polynomial
    def __init__(self, c):# symbolic representation
        self.c = c # by array of coefficients

    def __add__(self, a):
        if isinstance(a, Ring):
            return Ring(self.c + a.c)
        elif a==0:
            return self
        else:# never occurs
            c = self.c.copy()
            c[0] += a
            return Ring(c)

    def __mul__(self, a):
        if isinstance(a, Ring):
            n = len(self.c)
            t = np.convolve(self.c, a.c)
            c = t[:n]
            c[:-1] += t[n:] - c[-1]
            c[-1] = 0 # normalize
            return Ring(c)
        else:
            return Ring(a*self.c)

    def __rmul__(self, a):
        return Ring(a*self.c)

def cyclo_(p, recur=True):
    """ solve cyclotomic equation by radicals
    return p-th roots of unity (except 1)
           [exp(2pi ij/p) for j=1,2,...,p-1]
    p must be prime
    if recur is True, q-th roots of unity (q<p) are
      recursively replaced by radical expressions
    """
    if p==2: return -1
    if recur: Period.save_context()
    Period.init(p)
    n = 1
    y = np.zeros(p-1, dtype='object')
    y[0] = -1
    for p in list(Period.factor)[::-1]:
        r = np.eye(p, dtype=np.int64)
        r = [Ring(x) for x in r]
        if recur: w = cyclo_(p)
        else: w = [root(1,p,i) for i in range(1,p)]
        w = np.insert(w,0,1)
        i = np.outer(np.r_[:p], np.r_[:p])%p
        w,z = w[i],w[-i]
        for _ in range(Period.factor[p]):
            m = n*p
            Period.SetDim(m)
            v = np.zeros(m, dtype='object')
            v[::n] = r
            u = (Period(v)**p).c
            u = [x.c for x in np.r_[u[:n], u[-n:]]]
            # DFT (a.k.a. Lagrange resolvent)
            u = np.dot(u, w[:,1:])
            for k in range(n):
                t = np.dot(y[:n], u[:n])
                y[k+n:m:n] = [root(x,p,0) for x in t]
                # inverse DFT
                v[k::n] = np.dot(z, y[k:m:n])/p
                # cyclic permutation of periods
                u = np.roll(u, 1, axis=0)

            n = m
            y[:n] = [expand(x) for x in v]

    y = y[Period.index[1:]]
    if recur: Period.restore_context()
    return y

def cyclo(n, recur=True):
    """ solve cyclotomic equation by radicals
    return n-th roots of unity (except 1)
           [exp(2pi ij/n) for j=1,2,...,n-1]
    if recur is True, q-th roots of unity (q<n) are
      recursively replaced by radical expressions
    """
    if n<2:
        raise RuntimeError("n<2 in cyclo")

    f = factorint(n)
    z = np.empty(n, dtype='object')
    j = n
    for p in f:
        k,m = n//p,n
        z[k::k] = cyclo_(p, recur)
        for _ in range(1,f[p]):
            l = k//p
            a = np.r_[k:n:k][:,np.newaxis]
            b = np.r_[l:k:l]
            z[b] = [root(x,p,0) for x in z[k:m:k]]
            z[a+b] = z[a]*z[b]
            k,m = l,k

        if j<n:
            a = np.r_[j:n:j][:,np.newaxis]
            b = np.r_[k:n:k]
            z[(a+b)%n] = z[a]*z[b]

        j = j*k//n

    return z[1:]


from model.flyweight import Flyweight
from model.static.database import database

class Operation(Flyweight):
    def __init__(self,activity_id):
        #prevents reinitializing
        if "_inited" in self.__dict__:
            return
        self._inited = None
        #prevents reinitializing

        self.activity_id = activity_id

        cursor = database.get_cursor(
            "select * from staOperations where activityID={};".format(
                self.activity_id))
        row = cursor.fetchone()

        self.operation_id = row["operationID"]
        self.operation_name = row["operationName"]
        self.description = row["description"]
        self.fringe = row["fringe"]
        self.corridor = row["corridor"]
        self.hub = row["hub"]
        self.border = row["border"]
        self.ratio = row["ratio"]
        self.caldari_station_type_id = row["caldariStationTypeID"]
        self.minmatar_station_type_id = row["minmatarStationTypeID"]
        self.amarr_station_type_id = row["amarrStationTypeID"]
        self.gallente_station_type_id = row["gallenteStationTypeID"]
        self.jove_station_type_id = row["joveStationTypeID"]

        cursor.close()


from hydra import compose, initialize
import logging
import torch
from torch.utils.tensorboard import SummaryWriter

from data.dataset import get_dex_dataloader
from trainer import Trainer
from utils.global_utils import log_loss_summary, add_dict
from omegaconf import OmegaConf
from omegaconf.omegaconf import open_dict
import os
from os.path import join as pjoin
from tqdm import tqdm

import argparse

from utils.interrupt_handler import InterruptHandler

def process_config(cfg, save=True):
    root_dir = cfg["exp_dir"]
    os.makedirs(root_dir, exist_ok=True)

    with open_dict(cfg):
        cfg["device"] = f'cuda:{cfg["cuda_id"]}' if torch.cuda.is_available() else "cpu"

    if save:
        yaml_path = pjoin(root_dir, "config.yaml")
        print(f"Saving config to {yaml_path}")
        with open(yaml_path, 'w') as f:
            print(OmegaConf.to_yaml(cfg), file=f)

    return cfg

def log_tensorboard(writer, mode, loss_dict, cnt, epoch):
    for key, value in loss_dict.items():
        writer.add_scalar(mode + "/" + key, value / cnt, epoch)
    writer.flush()

def main(cfg):
    cfg = process_config(cfg)

    """ Logging """
    log_dir = cfg["exp_dir"]
    os.makedirs(log_dir, exist_ok=True)

    logger = logging.getLogger("TrainModel")
    logger.setLevel(logging.INFO)
    formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    file_handler = logging.FileHandler(f'{log_dir}/log.txt')
    file_handler.setLevel(logging.INFO)
    file_handler.setFormatter(formatter)
    logger.addHandler(file_handler)

    """ Tensorboard """
    writer = SummaryWriter(pjoin(log_dir, "tensorboard"))

    """ DataLoaders """
    train_loader = get_dex_dataloader(cfg, "train")
    test_loader = get_dex_dataloader(cfg, "test")

    """ Trainer """
    trainer = Trainer(cfg, logger)
    start_epoch = trainer.resume()

    """ Test """
    def test_all(dataloader, mode, iteration):
        test_loss = {}
        for _, data in enumerate(tqdm(dataloader)):
            _, loss_dict = trainer.test(data)
            loss_dict["cnt"] = 1
            add_dict(test_loss, loss_dict)

        cnt = test_loss.pop("cnt")
        log_loss_summary(test_loss, cnt,
                         lambda x, y: logger.info(f'{mode} {x} is {y}'))
        log_tensorboard(writer, mode, test_loss, cnt, iteration)

    """ Train """
    # Upon SIGINT, it will save the current model before exiting
    with InterruptHandler() as h:
        train_loss = {}
        for epoch in range(start_epoch, cfg["total_epoch"]):
            for _, data in enumerate(tqdm(train_loader)):
                loss_dict = trainer.update(data)
                loss_dict["cnt"] = 1
                add_dict(train_loss, loss_dict)

                if trainer.iteration % cfg["freq"]["plot"] == 0:
                    cnt = train_loss.pop("cnt")
                    log_loss_summary(train_loss, cnt,
                                     lambda x, y: logger.info(f"Train {x} is {y}"))
                    log_tensorboard(writer, "train", train_loss, cnt, trainer.iteration)

                    train_loss = {}

                if trainer.iteration % cfg["freq"]["step_epoch"] == 0:
                    trainer.step_epoch()

                if trainer.iteration % cfg["freq"]["test"] == 0:
                    test_all(test_loader, "test", trainer.iteration)

                if trainer.iteration % cfg["freq"]["save"] == 0:
                    trainer.save()

                if h.interrupted:
                    break

            if h.interrupted:
                break

    trainer.save()

def parse_args():
    parser = argparse.ArgumentParser()
    parser.add_argument("--config-name", type=str, default="ipdf_config")
    parser.add_argument("--exp-dir", type=str, help="E.g., './ipdf_train'.")
    return parser.parse_args()

if __name__ == "__main__":
    args = parse_args()
    initialize(version_base=None, config_path="../configs", job_name="train")
    if args.exp_dir is None:
        cfg = compose(config_name=args.config_name)
    else:
        cfg = compose(config_name=args.config_name, overrides=[f"exp_dir={args.exp_dir}"])
    main(cfg)