from grale.all import *
import matplotlib.pyplot as plt

# Create a cosmological model with dimensionless Hubble constant h=0.7,
# Omega_m = 0.3 and Omega_lambda = 0.7
cosm = cosmology.Cosmology(0.7, 0.3, 0, 0.7)

# For a lens at z = 0.5, calculate the angular diameter distance
z_d = 0.5
D_d = cosm.getAngularDiameterDistance(z_d)

# Let's show what this angular diameter distance is, in units of Mpc
print("D_d = {:.2f} Mpc".format(D_d/DIST_MPC))

# Create a SIS lens with a velocity dispersion of 250 km/s
sis = lenses.SISLens(D_d, { "velocityDispersion": 250000 })

# Create a SIE lens with specific velocity dispersion and ellipticity
sie = lenses.SIELens(D_d, { "velocityDispersion": 200000, "ellipticity": 0.7 })

# Combine these models using a CompositeLens
combLens = lenses.CompositeLens(D_d, [
        { "lens": sis, "factor": 1,
          "x": -1*ANGLE_ARCSEC, "y": -2*ANGLE_ARCSEC, "angle": 0 },
        { "lens": sie, "factor": 1,
          "x": 2*ANGLE_ARCSEC, "y": 1.5*ANGLE_ARCSEC, "angle": 60 }
    ])

g0 = grid.createUniformGrid(12*ANGLE_ARCSEC, [0, 0], 15)

li = plotutil.LensInfo(combLens, size=13*ANGLE_ARCSEC)
g1 = grid.createSubdivisionGrid(12*ANGLE_ARCSEC, [0, 0], li, 300, 400)

plt.figure(figsize=(10, 5))
plt.subplot(1,2,1)
plotutil.plotSubdivisionGrid(g0)
plt.title("Uniform subdivision")
plt.gca().set_xlabel("X (arcsec)")
plt.gca().set_ylabel("Y (arcsec)")
plt.subplot(1,2,2)
plt.title("Refinement based on lens model")
plotutil.plotSubdivisionGrid(g1)
plt.gca().set_xlabel("X (arcsec)")
plt.gca().set_ylabel("Y (arcsec)")
plt.show()


import numpy as np
import matplotlib.pyplot as plt

#ディレクトリ生成用
import os

#ライブラリのインポート
from PIL import Image
#画像を入れる箱を準備
pictures=[]
#画像を箱に入れていく

#gjfを生成するための画像を保存する為のディレクトリを無い場合は新規に作成する

SAMPLE_DIR = "./graphs"

if not os.path.exists(SAMPLE_DIR):
    # ディレクトリが存在しない場合、ディレクトリを作成する
    os.makedirs(SAMPLE_DIR)

def nose_cu(X):
  P = np.arange(0.0, 1.0, 0.01)

  Q=0.0

  V_s=1.0

  #X=1.0
  Y=0.00

  #簡単のため

  alpha = Q/P

  #y=ax**2+b*x+c(x=V,y=P)

  a=(1/X-Y)**2
  b=2*P*(1/X-Y)*alpha-(V_s/X)**2
  c=(1+alpha**2)*P**2

  #安定解
  V_r_1=((-b+(b**2-4*a*c)**0.5)/2*a)**0.5
  #不安定解
  V_r_2=((-b-(b**2-4*a*c)**0.5)/2*a)**0.5

  plt.plot(P,V_r_1, 'r-')
  plt.plot(P,V_r_2,'b-')
  plt.xlim(0,0.5)
  plt.ylim(0,1)

  plt.title('ノーズカーブ,X=%f'%X,fontname="MS Gothic")
  plt.xlabel('有効電力P',fontname="MS Gothic")
  plt.ylabel('受電端電圧V_r',fontname="MS Gothic")

  #plt.show()

  #保存
  plt.savefig(f"./graphs/nose{X}.png")
  #グラフの図示
  #plt.show()
  img = Image.open(f"./graphs/nose{X}.png")
  pictures.append(img)

for i in range(1,10):
    print(i)
    X=1.0+0.1*i
    nose_cu(X)

#gifアニメを出力する
pictures[0].save('anime.gif',save_all=True, append_images=pictures[1:],
optimize=True, duration=500, loop=0)


"""
El programa debe ser genérico es decir el usuario puede ingresar cualquier número entero para hallar
su combinación. Por ejemplo: si el usuario ingresa el número 3 usted deberá resolver la combinación
de una lista de 3 elementos ([1,2,3]).

Autor: Ednan Josué Merino Calderón

Versión: 1.0
"""

import numpy
import os
import math

os.system("cls")

def combinacion(iterable, r):
    '''Es una funcion para obtener la combinación de un conjunto de números/letras ingresados por el usuario
    Parametros:
    ------------
        iterable: número o palabra que ingresara el usuario
        r: Órden de las combinaciones ingresado por el usuario

    Retorna:
    ------------
        Combinación
    '''
    #tuple para almacenar datos en una misma variable
    char = tuple(iterable)
    #len regresa el número de items que se encuentran contenidos.
    n = len(char)
    #Si es que un r es mayor que n
    if r > n:
        #Si es que r es mayor que n, retorna
        return
    #numpy.arange genera un array de números, index nos permite obtener el índice o posición de la
    #primera aparición de un elemento dentro de una lista
    index = numpy.arange(r)
    #retorna un generador de objetos en este caso la combinación
    yield tuple(char[i] for i in index)
    #Bucle while true
    while True:
        #Para un i reversa un objeto de secuencia y lo devuelve en forma de lista dentro del rango r
        for i in reversed(range(r)):
            #Si la posición de i no es igual a i+n-r
            if index[i] != i + n - r:
                break
        #Si no se cumple la condición
        else:
            #Si no se cumple la condición retorna:
            return
        #la posición aumentada en uno
        index[i] += 1

        #para j dentro del rango i+1, hasta r
        for j in range(i + 1, r):
            #Para donde se encuentre la posición j
            index[j] = index[j-1] + 1
        #retorna un generador de objetos en este caso la combinación
        yield tuple(char[i] for i in index)

#Es el main de la aplicación.
if __name__=="__main__":
    #Imprime los datos del autor
    print ("Combinación por Ednan Josué Merino Calderón")
    #El usuario ingresa por teclado la palabra o número para combinar
    palabra_numero = str(input("Ingrese una palabra o número: "))
    #El usuario ingresa por teclado el órden de las combinaciones que desea
    n = int(input("De qué órden desea las combinaciones: "))
    #Cuenta los caracteres de la palabra para poder encontrar el número de combinaciones
    caracteres = len(palabra_numero)
    #Imprime cuantas combinaciones hay
    print ("Existen: ",math.factorial(caracteres)//(math.factorial(caracteres - n)*math.factorial(n)), "combinaciones")
    #Se imprime la solución utilizando la función combinación con los atributos palabra_numero y n
    print([x for x in combinacion(palabra_numero, n)])


"""Form for admin to upload a new version of menu."""

import logging
import os

from telegram import InlineKeyboardButton, InlineKeyboardMarkup
from telegram.error import TelegramError, RetryAfter
from telegram.ext import (
	CallbackQueryHandler, CommandHandler,
	ConversationHandler, Filters, MessageHandler
)
from bot.excel import ParseError, parse_document
from bot.menu import back, reply

messages = {
	'admin': "Загрузите xlsx-файл с новым меню.",
	'fail': "Ошибка парсинга меню.",
	'test': "Тестируем сообщения...",
	'flood': "Слишком частые обновления. Попробуйте позже.",
	'success': "Меню обновлено!"
}
back_btn = InlineKeyboardMarkup([
	[InlineKeyboardButton("Назад", callback_data='back')]
])

def admin(update, context):
	if update.effective_user.id != context.bot_data['admin']:
		update.effective_message.delete()
		return -1
	reply(update, context, messages['admin'], back_btn)
	return 1

def get_file(update, context):
	file = update.effective_message.document.get_file()
	try:
		menu = parse_document(file.download())
	except ParseError as err:
		reply(update, context, messages['fail'] + "\n" + str(err), back_btn)
		return 1

	test_msg = update.effective_chat.send_message('Testing...')
	status_msg = update.effective_message.reply_text(messages['test'], quote=True)
	try:
		for submenu in menu.values():
			test_msg.edit_text(submenu['message'], reply_markup=submenu['buttons'])
	except RetryAfter as err:
		status_msg.edit_text(f"Ошибка Телеграма:\n{err}\n{messages['flood']}")
		reply(update, context, messages['fail'], back_btn)
		return 1
	except TelegramError as err:
		status_msg.edit_text(
			f"```{submenu['message']}```\nОшибка Телеграма:\n{err}\n"  # type: ignore
			"Скорее всего, в тексте неэкранированный спецсимвол, "
			"используемый для разметки."
		)
		reply(update, context, messages['fail'], back_btn)
		return 1
	finally:
		test_msg.delete()

	try:
		os.remove('menu.xlsx')
	except OSError:
		pass
	file.download(custom_path='./menu.xlsx')
	context.bot_data['menu'] = menu
	logging.info("Меню обновлено.")
	status_msg.edit_text(messages['success'])
	return back(update, context)

admin_form = ConversationHandler(
	entry_points=[CommandHandler('admin', admin)],
	states={
		1: [MessageHandler(Filters.document, get_file)],
	},
	fallbacks=[CallbackQueryHandler(back, pattern=r'^back$')],
	allow_reentry=True
)


#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
    /|
 .-((--.
( '`^'; )   Graceland Chilis
`;#    |    Climate Monitoring & Management System
 \#    |    https://github.com/andrewgwatson/graceland-climate-management
  \#   \
   '-.  )
      \(
       `
"""

import logging, csv
from datetime import datetime
import config, climate

def main():

    logging.basicConfig(filename='graceland.log', encoding='utf-8', level=logging.DEBUG, format='%(asctime)s.%(msecs)03d %(levelname)-2s %(message)s', datefmt='%Y-%m-%d %H:%M:%S')
    # logging.basicConfig(level=logging.DEBUG, format='%(asctime)s.%(msecs)03d %(levelname)-2s %(message)s', datefmt='%Y-%m-%d %H:%M:%S')

    c = climate.snapshot()
    # Write sensor data to csv as a simple timeseries
    with open(config.db["filename"], 'a', newline='') as csvfile:
        db = csv.writer(csvfile, delimiter=',',quotechar='|', quoting=csv.QUOTE_MINIMAL)
        # db.writerow([f"{datetime.now():%Y-%m-%d %H:%M:%S}",c])
        db.writerow([f"{datetime.now():%Y-%m-%d %H:%M:%S}",
                     c['temp'],
                     c['humidity'],
                     c['airpressure'],
                     c['light'],
                     c['moisturesensors'][0],
                     c['moisturesensors'][1],
                     c['moisturesensors'][2],
                     ])

if __name__ == "__main__" : main()


# Faça um programa que solicite que o usuário informe valores para preencher 10 posições
# de um vetor do tipo inteiro. Em seguida, apresente os valores inseridos em par, ou seja,
# apresente os conteúdos dos índices 0 e 1; 2 e 3; 4 e 5; 6 e 7.
# O mesmo raciocínio deve ser seguido para os demais índices.

def main():

    MAX_SIZE = 10

    valores = []

    i = 0

    print("\n")

    while i < MAX_SIZE:

      valores.append(float(input("Informe um valor: ")))

      i += 1

    print("\nEsse são os valores em duplas: ")
    i = 0
    while i < MAX_SIZE:

      print("{} e {}".format(valores[i], valores[i + 1]))

      i += 2

    return

if __name__ == "__main__":
    main()


#!/usr/bin/env python

import matplotlib.pyplot as plt
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torchvision import datasets, transforms
from torch.utils.data import random_split, DataLoader
from tqdm.notebook import tqdm, trange

'''
Helper function to display an image
Usage (without prediction):
    image, label = mnist_train[3]
    displayImage(image, label)
'''
def displayImage(image, label, prediction = None):
    image = image.reshape([28, 28])
    title = f"Label: {label}"
    if not prediction == None: title += f" Prediction: {prediction}"
    plt.figure()
    plt.imshow(image, cmap="gray")
    plt.title(title)
    plt.show()

'''
Model definition
'''
class MNIST_MLP(nn.Module):
    """Feedfoward neural network with 1 hidden layer"""
    def __init__(self, in_size, hidden_size, out_size):
        super().__init__()
        # hidden layer
        self.linear1 = nn.Linear(in_size, hidden_size)
        # output layer
        self.linear2 = nn.Linear(hidden_size, out_size)

    def forward(self, x):
        # Flatten the image tensors
        x = x.view(x.size(0), -1)
        # Get intermediate outputs using hidden layer
        out = self.linear1(x)
        # Apply activation function
        out = F.relu(out)
        # Get predictions using output layer
        out = self.linear2(out)
        return out

    def training_step(self, batch):
        images, labels = batch
        out = self(images)                  # Generate predictions
        loss = F.cross_entropy(out, labels) # Calculate loss
        return loss

    def validation_step(self, batch):
        images, labels = batch
        out = self(images)                    # Generate predictions
        loss = F.cross_entropy(out, labels)   # Calculate loss
        acc = accuracy(out, labels)           # Calculate accuracy
        return {'val_loss': loss, 'val_acc': acc}

    def validation_epoch_end(self, outputs):
        batch_losses = [x['val_loss'] for x in outputs]
        epoch_loss = torch.stack(batch_losses).mean()   # Combine losses
        batch_accs = [x['val_acc'] for x in outputs]
        epoch_acc = torch.stack(batch_accs).mean()      # Combine accuracies
        return {'val_loss': epoch_loss.item(), 'val_acc': epoch_acc.item()}

    def epoch_end(self, epoch, result):
        print("Epoch [{}], val_loss: {:.4f}, val_acc: {:.4f}".format(epoch, result['val_loss'], result['val_acc']))

def fit(epochs, lr, model, train_loader, val_loader, opt_func=torch.optim.SGD, plot=False, leaveProgressBar=False):
    optimizer = opt_func(model.parameters(), lr)
    history = [] # for recording epoch-wise results

    for epoch in trange(epochs, leave=leaveProgressBar):

        # Training Phase
        for batch in tqdm(train_loader, leave=leaveProgressBar):
            loss = model.training_step(batch)
            loss.backward()
            optimizer.step()
            optimizer.zero_grad()

        # Validation phase
        result = evaluate(model, val_loader)
        model.epoch_end(epoch, result)
        history.append(result)

    return history

def evaluate(model, val_loader):
    with torch.no_grad():
        outputs = [model.validation_step(batch) for batch in val_loader]
    return model.validation_epoch_end(outputs)

def accuracy(outputs, labels):
    _, preds = torch.max(outputs, dim=1)
    return torch.tensor(torch.sum(preds == labels).item() / len(preds))

def get_default_device():
    """Pick GPU if available, else CPU"""
    if torch.cuda.is_available():
        return torch.device('cuda')
    else:
        return torch.device('cpu')

def to_device(data, device):
    """Move tensor(s) to chosen device"""
    if isinstance(data, (list,tuple)):
        return [to_device(x, device) for x in data]
    return data.to(device, non_blocking=True)

class DeviceDataLoader():
    """Wrap a dataloader to move data to a device"""
    def __init__(self, dl, device):
        self.dl = dl
        self.device = device

    def __iter__(self):
        """Yield a batch of data after moving it to device"""
        for b in self.dl:
            yield to_device(b, self.device)

    def __len__(self):
        """Number of batches"""
        return len(self.dl)

def predict_image(img, model, device):
    x = to_device(img.unsqueeze(0), device)
    y = model(x)
    _, preds  = torch.max(y, dim=1)
    return preds[0].item()


# 신경망 모델 구성하기
import os
import torch
from torch import nn # torch.nn 네임스페이스는 신경망을 구성하는데 필요한 모든 요소들
                     # 을 제공함 Pytorch의 모든 모듈은 nn.Module의 하위 클래스임
from torch.utils.data import DataLoader
from torchvision import datasets, transforms

# 학습을 위한 장치얻기
device = 'cuda' if torch.cuda.is_available() else 'cpu'
print('Using {} device'.format(device))

# 클래스 정의하기
# 신경망 모델을 nn.Module의 하위 클래스로 정의, __init__에서 신경망 계층들을 초기화함
# nn.Module을 상속받은 모든 클래스는 forward 메소드에 입력 데이터에 대한 연산을 구현

class NeuralNetwork(nn.Module):
    def __init__(self):
        super(NeuralNetwork, self).__init__()
        self.flatten = nn.Flatten()
        self.linear_relu_stack = nn.Sequential(
                nn.Linear(28*28, 512),
                nn.ReLU(),
                nn.Linear(512, 512),
                nn.ReLU(),
                nn.Linear(512, 10),
                nn.ReLU()
                )
    def forward(self, x):
        x = self.flatten(x)
        logits = self.linear_relu_stack(x)
        return logits

# NeuralNetwork의 인스턴스를 생성하고 device로 이동, structure를 출력
model = NeuralNetwork().to(device)
print(model)

# 모델을 사용하기 위해 입력 데이터를 전달, 일부 백그라운드 연산들과 함께 모델의 forward를 실행함
# model.forward()를 직접 호출하지 말것
X = torch.rand(1, 28, 28, device = device)
logits = model(X)
pred_prob = nn.Softmax(dim=1)(logits)
y_pred = pred_prob.argmax(1)
print(f"Predicted class: {pred_prob}, {y_pred}")

# 모델 계층 ( Layer )
# FashionMNIST 모델의 계층을 살펴본다, 이를 설명하기 위해 28x28 크기의 이미지 3개로 구성된 미니 배치를 가져온다.
input_image = torch.rand(3, 28, 28)
print(input_image.size())

# nn.Flatten
# nn.Flatten 계층을 초기화하여 각 28x28의 2D 이미지를 784 픽셀 값을 갖는 연속된 배열로 변환하도록 한다. ( dim = 0 는 미니배치 차원 )
flatten = nn.Flatten()
flat_image = flatten(input_image)
print(flat_image.size())

# nn.Linear
# 선형 계층은 저장된 weight와 bias를 사용하여 입력에 선형 변환을 적용하는 모듈이다.
layer1 = nn.Linear(in_features= 28 * 28, out_features = 20)
hidden1 = layer1(flat_image)
print(hidden1.size())

# nn.ReLU
# 비선형 활성화는 모델의 입력과 출력 사이에 복잡한 관계 ( mapping )을 만든다. 비선형 활성화는 선형 변환 후에 적용되어 비선형성을 도입하고 신경망이 다양한 현상을 학습할 수 있도록 돕는다.

print(f"Before ReLU: {hidden1}\n\n")
hidden1 = nn.ReLU()(hidden1)
print(f"After ReLU: {hidden1}")

# nn.Sequential
# nn.Sequential은 순서를 갖는"모듈의 컨테이너"이다.데이터는 정의된 것과 같은 순서로 모든 모듈들을 통해 전달된다. 순차 컨테이너를 사용하여 아래의 seq_module과 같은 신경망을 빠르게 만들 수 있다.

seq_modules = nn.Sequential(
        flatten,
        layer1,
        nn.ReLU(),
        nn.Linear(20, 10)
        )
input_image = torch.rand(3,28,28)
logits = seq_modules(input_image)

# nn.Softmax
# 신경망의 마지막 선형 계층은 nn.softmax 모듈에 전달될 [ -inf, inf ]범위의 원시값인 logis를 반환한다. logits는 모델의 각 분류에 대한 예측 확률을 나타내도록 [0,1]범위로 비례하여 조정된다. dim 매개변수는 값의 합이 1이 되는 차원을 나타낸다.
softmax = nn.Softmax(dim = 1)
pred_prob = softmax(logits)

# 모델 매개변수
#신경망 내부의 많은 계층들은 매개변수화된다. 즉 학습 중에 최적화되는 가중치와 편향에 연관지어진다.
# nn.Module을 상속하면 모델 객체 내부의 모든 필드들이 자동으로 추적되며, 모델의 parameters() 및 named_parameters()메소드로 모든 매개변수에 접근할 수 있게 된다.

print("Model structure : ", model, "\n\n")
for name, param in model.named_parameters():
    print(f"Layer : {name} | Size : {param.size()} | Values : {param[:2]} \n")


import gym
import matplotlib.pyplot as plt
import numpy as np
from reinforce_keras import Agent
#from utils import plotLearning
import time

if __name__ == '__main__':
    agent = Agent(ALPHA=0.0005, input_dims=8, GAMMA=0.99, n_actions=4,
                  layer1_size=64, layer2_size=64)
    env = gym.make('LunarLander-v2')
    score_history = []

    agent.load_model_json()

    print(agent.policy.summary())

    n_episodes = 400

    for i in range(n_episodes):
        print('entered for loop...')
        done = False
        score = 0
        observation = env.reset()
        while not done:
            print('entered while loop....')
            action = agent.choose_action(observation)
            observation_, reward, done, info = env.step(action)
            agent.store_transition(observation, action, reward)
            observation = observation_
            score += reward
        print('while loop completed...')
        score_history.append(score)

        print('start agent.learn()')
        agent.learn()

        print('episode ', i, 'score %.1f' % score,
              'average_score %.1f' % np.mean(score_history[-100:]))

    agent.save_model_json()


"""
[queue를 회전시킬 수 있는가?]
풀이시간 : 43분
- 로직 21분
  1) 자석 날을 deque로 저장해서, rotate 함수 사용 😏
  2) 회전을 재귀로 처리할까 하다가 그냥 왼쪽, 오른쪽 자석에 대해 반복문 처리
  3) 대신 회전하려는 자석에서 가까운 자석부터 보면서 회전 안하면 break

- deque의 rotate https://docs.python.org/ko/3.8/library/collections.html?highlight=rotate#collections.deque.rotate
  - rotate(오른쪽으로 이동할 횟수)
  - ex) rotate(1) = deque.appendleft(deque.pop()) => 시계
        rotate(-1) = deque.append(deque.popleft()) => 반시계
"""
from collections import deque

T = int(input())

for tc in range(T):
    N = int(input())
    magnets = []  # [deque([0, 0, 1, 0, 0, 1, 0, 0]), ...]

    # 각 자석을 rotate 시키기 위해 deque로 생성
    for _ in range(4):
        magnets.append(deque(list(map(int, input().split()))))

    # N번 반복
    for _ in range(N):
        num, d = map(int, input().split())
        num -= 1

        # 각 자석이 회전을 할지 말지 표기함. 1이면 시계, -1이면 반시계, 0이면 안함
        rotate_list = [0] * 4
        rotate_list[num] = d  # 회전을 시작하는 자석(메인)

        # 메인의 왼쪽에 있는 자석들
        for left in range(num-1, -1, -1):
            if magnets[left+1][6] != magnets[left][2]:
                # 한칸 떨어지면 반대, 두칸 떨어지면 같은 방향이다.
                rotate_list[left] = d * ((-1) ** abs(num - left))
            else:
                # 회전하지 않았다면 그 이후의 자석들은 볼 필요 없음.
                break

        # 메인의 오른쪽에 있는 자석들.
        for right in range(num+1, 4):
            if magnets[right-1][2] != magnets[right][6]:
                rotate_list[right] = d * ((-1) ** abs(num - right))
            else:
                break

        # 자석의 회전이 순차적으로 일어나는게 아니고 동시에 일어나기 때문에
        # 회전 방향을 저장해놓은 뒤 처리한다.
        for idx in range(4):
            if rotate_list[idx] == 1:
                magnets[idx].rotate(1)
            elif rotate_list[idx] == -1:
                magnets[idx].rotate(-1)

    answer = 0

    for idx in range(4):
        if magnets[idx][0] == 1:
            answer += 2 ** idx

    print(f"#{tc+1} {answer}")

SS/A형대비/특이한자석_배하은.py

특이한자석_배하은.py


"""Index analyzer plugin for Yeti indicators."""

import json
import re

from typing import Dict, List

from flask import current_app
import requests

from timesketch.lib.analyzers import interface
from timesketch.lib.analyzers import manager
from timesketch.lib import emojis

class YetiIndicators(interface.BaseAnalyzer):
    """Analyzer for Yeti threat intel indicators."""

    NAME = "yetiindicators"
    DISPLAY_NAME = "Yeti CTI indicators"
    DESCRIPTION = "Mark events using CTI indicators from Yeti"

    DEPENDENCIES = frozenset(["domain"])

    def __init__(self, index_name, sketch_id, timeline_id=None):
        """Initialize the Analyzer.

        Args:
            index_name: OpenSearch index name
            sketch_id: The ID of the sketch.
            timeline_id: The ID of the timeline.
        """
        super().__init__(index_name, sketch_id, timeline_id=timeline_id)
        self.intel = {}
        root = current_app.config.get("YETI_API_ROOT")
        if root.endswith("/"):
            root = root[:-1]
        self.yeti_api_root = root
        self.yeti_web_root = root.replace("/api/v2", "")
        self.yeti_api_key = current_app.config.get("YETI_API_KEY")

    def get_neighbors(self, yeti_object: Dict) -> List[Dict]:
        """Retrieves a list of neighbors associated to a given entity.

        Args:
          yeti_object: The Yeti object to get neighbors from.

        Returns:
          A list of JSON objects describing a Yeti entity.
        """
        extended_id = f"{yeti_object['root_type']}/{yeti_object['id']}"
        results = requests.post(
            f"{self.yeti_api_root}/graph/search",
            json={
                "source": extended_id,
                "graph": "links",
                "hops": 1,
                "direction": "any",
                "include_original": False,
            },
            headers={"X-Yeti-API": self.yeti_api_key},
        )
        if results.status_code != 200:
            return []
        neighbors = []
        for neighbor in results.json().get("vertices", {}).values():
            neighbors.append(neighbor)

        return neighbors

    def get_indicators(self, indicator_type: str) -> Dict[str, dict]:
        """Populates the intel attribute with entities from Yeti.

        Returns:
            A dictionary of indicators obtained from yeti, keyed by indicator
            ID.
        """
        response = requests.post(
            self.yeti_api_root + "/indicators/search",
            json={"name": "", "type": indicator_type},
            headers={"X-Yeti-API": self.yeti_api_key},
        )
        if response.status_code != 200:
            raise RuntimeError(
                f"Error {response.status_code} retrieving indicators from Yeti:"
                + response.json()
            )
        data = response.json()
        indicators = {item["id"]: item for item in data["indicators"]}
        for _id, indicator in indicators.items():
            indicator["compiled_regexp"] = re.compile(indicator["pattern"])
            indicators[_id] = indicator
        return indicators

    def mark_event(
        self, indicator: Dict, event: interface.Event, neighbors: List[Dict]
    ):
        """Annotate an event with data from indicators and neighbors.

        Tags with skull emoji, adds a comment to the event.
        Args:
            indicator: a dictionary representing a Yeti indicator object.
            event: a Timesketch sketch Event object.
            neighbors: a list of Yeti entities related to the indicator.
        """
        event.add_emojis([emojis.get_emoji("SKULL")])
        tags = []
        for n in neighbors:
            slug = re.sub(r"[^a-z0-9]", "-", n["name"].lower())
            slug = re.sub(r"-+", "-", slug)
            tags.append(slug)
        event.add_tags(tags)
        event.commit()

        msg = f'Indicator match: "{indicator["name"]}" ({indicator["id"]})\n'
        msg += f'Related entities: {[n["name"] for n in neighbors]}'
        comments = {c.comment for c in event.get_comments()}
        if msg not in comments:
            event.add_comment(msg)
            event.commit()

    def run(self):
        """Entry point for the analyzer.

        Returns:
            String with summary of the analyzer result
        """
        if not self.yeti_api_root or not self.yeti_api_key:
            return "No Yeti configuration settings found, aborting."

        indicators = self.get_indicators("regex")

        entities_found = set()
        total_matches = 0
        new_indicators = set()

        intelligence_attribute = {"data": []}
        existing_refs = set()

        try:
            intelligence_attribute = self.sketch.get_sketch_attributes("intelligence")
            existing_refs = {
                (ioc["ioc"], ioc["externalURI"])
                for ioc in intelligence_attribute["data"]
            }
        except ValueError:
            print("Intelligence not set on sketch, will create from scratch.")

        intelligence_items = []

        for indicator in indicators.values():
            query_dsl = {
                "query": {
                    "regexp": {"message.keyword": ".*" + indicator["pattern"] + ".*"}
                }
            }

            events = self.event_stream(query_dsl=query_dsl, return_fields=["message"])
            neighbors = self.get_neighbors(indicator)

            for n in neighbors:
                entities_found.add(f"{n['name']}:{n['type']}")

            uri = f"{self.yeti_web_root}/indicators/{indicator['id']}"

            for event in events:
                total_matches += 1
                self.mark_event(indicator, event, neighbors)

                regex = indicator["compiled_regexp"]
                match = regex.search(event.source.get("message"))
                if match:
                    match_in_sketch = match.group()
                else:
                    match_in_sketch = indicator["pattern"]

                intel = {
                    "externalURI": uri,
                    "ioc": match_in_sketch,
                    "tags": [n["name"] for n in neighbors],
                    "type": "other",
                }
                if (match_in_sketch, uri) not in existing_refs:
                    intelligence_items.append(intel)
                    existing_refs.add((match_in_sketch, uri))
                new_indicators.add(indicator["id"])

        if not total_matches:
            self.output.result_status = "SUCCESS"
            self.output.result_priority = "NOTE"
            note = "No indicators were found in the timeline."
            self.output.result_summary = note
            return str(self.output)

        for entity in entities_found:
            name, _type = entity.split(":")
            self.sketch.add_view(
                f"Indicator matches for {name} ({_type})",
                self.NAME,
                query_string=f'tag:"{name}"',
            )

        all_iocs = intelligence_attribute["data"] + intelligence_items
        self.sketch.add_sketch_attribute(
            "intelligence",
            [json.dumps({"data": all_iocs})],
            ontology="intelligence",
            overwrite=True,
        )

        success_note = (
            f"{total_matches} events matched {len(new_indicators)} "
            f"new indicators. Found: {', '.join(entities_found)}"
        )
        self.output.result_status = "SUCCESS"
        self.output.result_priority = "HIGH"
        self.output.result_summary = success_note

        return str(self.output)

manager.AnalysisManager.register_analyzer(YetiIndicators)


"""
This module is used to create the output
for `Clockify.me` service data.
"""
import re
from datetime import datetime
from itertools import groupby

def pull_out_tasks_names(tasks: list[dict]) -> list[str] | list:
    """
    Pull out tasks names from data about tasks
    that got from API.
    """
    return [task.get("name") for task in tasks if task.get("name")]

def _convert_to_int_if_int(string: str) -> int | str:
    return int(string) if string.isdigit() else string

def _to_int_serial_numbers(string: str) -> list[str | int]:
    """Convert to `int` serial numbers of the string."""
    return [_convert_to_int_if_int(s) for s in re.split(r"(\d+)", string)]

def sort_tasks_names_by_serial_numbers(tasks_names: list[str]) -> list[str]:
    return sorted(tasks_names, key=_to_int_serial_numbers)

def pull_out_report_data(tasks: list[dict], time_entries: list[dict]) -> list:
    """Pull out needed data for report file."""
    report_data = []

    for time_entry in time_entries:
        for task in tasks:
            if time_entry["taskId"] == task["id"]:
                desc = time_entry["description"]
                description = desc if desc else "it does\'t have a description"

                report_data.append({
                    "name": task["name"],
                    "description": description,
                    "date": time_entry["timeInterval"]["start"],
                    "duration": time_entry["timeInterval"]["duration"] or "-"
                })

    return report_data

def convert_duration_to_time_format(duration: str) -> str:
    """Convert `PT2H0M20S` to readable time."""
    if "H" in duration:
        time = datetime.strptime(duration, "PT%HH%MM%SS")
    elif "M" in duration:
        time = datetime.strptime(duration, "PT%MM%SS")
    else:
        time = datetime.strptime(duration, "PT%SS")

    return str(time.time())

def create_report_data_to_show(report_data: list[dict]) -> tuple:
    """Create needed view for report file."""
    all_info_report = []
    grouped_by_date_report = []

    for time_entry in report_data:
        try:
            duration = convert_duration_to_time_format(time_entry["duration"])
        except ValueError:
            duration = "-"

        all_info_report.append({
                    "name": time_entry["name"],
                    "description": time_entry["description"],
                    "duration": duration
                })

        grouped_by_date_report.append({
            "name": time_entry["name"],
            "date": time_entry["date"][0:10],
            "duration": duration
        })

    return all_info_report, grouped_by_date_report

def _to_int_serial_numbers_from_dict(time_entry: dict) -> list[str | int]:
    """Convert to `int` serial numbers of the dict."""
    return [_convert_to_int_if_int(c) for c in re.split(
        r"(\d+)", time_entry["name"])]

def sort_all_info_report(all_info_report: list[dict]) -> list[dict]:
    return sorted(all_info_report, key=_to_int_serial_numbers_from_dict)

def sort_grouped_by_date_report(
        grouped_by_date_report: list[dict]) -> list[dict]:
    grouped_by_date_report.reverse()
    return grouped_by_date_report

def group_report_by_date(report: list[dict]) -> list[dict]:
    """Group report data by date."""
    grouped_by_date_report = []

    for k, v in groupby(report, key=lambda x: x["date"]):
        grouped_by_date_report.append({k: list(v)})

    return grouped_by_date_report


# tutorial from: https://pythonprogramming.net/tables-xml-scraping-parsing-beautiful-soup-tutorial/?completed=/navigating-pages-scraping-parsing-beautiful-soup-tutorial/

import bs4 as bs
import urllib.request

source = urllib.request.urlopen('https://pythonprogramming.net/parsememcparseface/').read()
soup = bs.BeautifulSoup(source,'lxml')

# get table - this website has only one
table = soup.find("table") # here, find_all() is not possible - why?

# get all rows
table_rows = table.find_all("tr")

# iterate through rows and find data tags (td) for each
for tr in table_rows:
    td = tr.find_all('td')
    row = [i.text for i in td]
    print(row)

# better option for parsing tables: pandas
import pandas as pd

dfs = pd.read_html('https://pythonprogramming.net/parsememcparseface/',header=0)
for df in dfs: # here, there is only on df -> len(dfs) = 1
    print(df) # you could simply call print(dfs) instead

# parse XML
import bs4 as bs
import urllib.request

source = urllib.request.urlopen('https://pythonprogramming.net/sitemap.xml').read() # we are grabbing the sitemap now
soup = bs.BeautifulSoup(source,'xml') # here is the difference

# get all urls
urls = soup.find_all("loc")
for url in urls:
    print(url.text)

Web scraping/Beatiful soup basics/ex3.py


from Command import Command, auto
import sys

class Click(Command):
    type = "click"

    def __init__(self, json):
        super().__init__(json)
        try:
            self.button = json["button"]
        except KeyError:
            print("Backend: Error: missing 'button' parameter, set default to left click" )
            self.button = "left"

    def execute(self, commands, commands_counter):
            try:
                if self.button != 'double':
                    auto.click(button=self.button)
                else:
                    auto.doubleClick()
            except  auto.PyAutoGUIException:
                print(auto.PyAutoGUIException)
                sys.exit(1)

    def is_valid(self):
        return self.button in ['left', 'right', 'middle', 'double']

    def print(self):
        return ""


import time
import zmq
import sys
import os
import socket as sok

#READIGN ARGUMENTS
port = 10000
MasterIP = sys.argv[1]
N = int(sys.argv[2])
MyIp = str(sys.argv[3])
MasterPort = 4000

def endRequest(request, filename, socket):
    #list order ["dataKeeperSuccess" ,[ip, request(upload, download), filename]]
    print(["dataKeeperSuccess" ,[str(MyIp) + ":" + str(port), request, filename]])
    socket.send_pyobj(["dataKeeperSuccess" ,[str(MyIp) + ":" + str(port), str(request), str(filename)]])
    print ("Ahmed Here")
    msg = socket.recv_pyobj()
    print(msg)

###################################################################################
def download(socket, Msocket):
    print("entered the client upload function")
    socket.send_pyobj("send the video name\n")
    FILE_OUTPUT = socket.recv_pyobj()
    print("recieved the video")
    #print(msg)
    socket.send_pyobj("send the video")
    msg = socket.recv_pyobj()
    print("sent the ack")
    # Checks and deletes the output file
    # You cant have a existing file or it will through an error
    if os.path.isfile(FILE_OUTPUT):
        os.remove(FILE_OUTPUT)

    # opens the file 'output.avi' which is accessable as 'out_file'
    with open(FILE_OUTPUT, "wb") as out_file:  # open for [w]riting as [b]inary
        out_file.write(msg)
    print("the video was saved")
    socket.send_pyobj("the file is saved successfully")
    endRequest("upload", FILE_OUTPUT, Msocket)
###################################################################################

############################################
def Upload(socket, Msocket):
    print("entered the client download function")
    socket.send_pyobj("send the video name\n")
    msg = socket.recv_pyobj()
    print("filename needed to be downloaded ",msg)
    file = open(msg, 'rb').read()
    socket.send_pyobj(file)
    print("sent the file to client")
    endRequest("download", msg, Msocket)
############################################

##################################################
# def get_ip_address():
#     s = sok.socket(sok.AF_INET, sok.SOCK_DGRAM)
#     s.connect(("8.8.8.8", 80))
#     return s.getsockname()[0]
# def get_ip_address():
#     return MyIp
###################################################

################        MAIN        ##################
context = zmq.Context()
socket = context.socket(zmq.REP)
print("binding to my ip tcp://" + str(MyIp) + ":" + str(port))
socket.bind("tcp://" + str(MyIp) + ":" + str(port))

masterContext = zmq.Context()
masterSocket = masterContext.socket(zmq.REQ)
print("connecting to all master processes")
for i in range(MasterPort, MasterPort + N):
    print("tcp://" + MasterIP + ":" + str(i), " THIS IP FOR SUCCESS")
    masterSocket.connect("tcp://" + MasterIP + ":" + str(i))

while True:
    message = socket.recv_pyobj()
    print(message)
    #Upload(socket1)
    if (message == "upload"):
        download(socket, masterSocket)

    elif (message == "download"):
        Upload(socket, masterSocket)

#in success send ip and port, upload or download, filename
#4000
#5000
#6000
#7000
#10000


from django.shortcuts import render, get_object_or_404, redirect
from django.utils import timezone

from myauth.utils import authorized_users_only

from .models import Feedback
from .forms import FeedbackForm

def feedback_main(request):
    feedbacks = Feedback.objects.filter(published_date__lte=timezone.now()).order_by('-published_date')
    return render(request, 'feedback_main.html', {"feedbacks": feedbacks, 'title': 'Гадости'})

def trying_to_delete_or_edit_not_your_feedback(request):
    feedbacks = Feedback.objects.filter(published_date__lte=timezone.now()).order_by('-published_date')
    return render(request, 'feedback_main.html', {"feedbacks": feedbacks, 'title': 'Гадости'})

@authorized_users_only
def feedback_new(request):
    if not Feedback.objects.filter(author=request.user):
        if request.method == "POST":
            form = FeedbackForm(request.POST)
            if form.is_valid():
                feedback = form.save(commit=False)
                feedback.create(request.user)
                feedback.publish()
                return redirect("feedback_main")
        else:
            form = FeedbackForm()
        return render(request, 'feedback_new.html', {'form': form, 'title': 'Написать гадости'})
    else:
        return cheater(request, 'В одни руки один фидбек')

@authorized_users_only
def feedback_edit(request, pk):
    feedback = get_object_or_404(Feedback, pk=pk)
    if request.user == feedback.author:
        if request.method == "POST":
            form = FeedbackForm(request.POST, instance=feedback)
            if form.is_valid():
                feedback = form.save(commit=False)
                feedback.save()
                return redirect("feedback_main")
        else:
            form = FeedbackForm(instance=feedback)
        return render(request, 'feedback_new.html', {'form': form, 'title': 'Приукрасить гадости'})
    else:
        return cheater(request, 'Пытались редактировать жужой фидбек?')

@authorized_users_only
def feedback_delete(request, pk):
    feedback = Feedback.objects.filter(pk=pk)[0]
    if request.user == feedback.author or request.user.is_superuser:
        feedback.delete()
        return redirect("feedback_main")
    else:
        return cheater(request, 'Пытались удалить чужой фидбек?')

def cheater(request, message):
    return render(request, 'cheater.html', {'title': 'Читерок', 'cheater_message': message})


from enum import Enum

all = ['PriceTypeEnum']

class PriceTypeEnum(Enum):
  """
  Provides enumerated values for types of prices in the Price data type in order to explain how to interpret the amount and use it in calculations.
  """
  ASSET_PRICE = "ASSET_PRICE"
  """
  Denotes a price expressed as a cash amount in a given currency to purchase a unit of an asset (e.g. a security or a commodity).
  """
  CASH_PRICE = "CASH_PRICE"
  """
  Denotes a price expressed as a cash amount for an upfront fee or other purposes. For example, {amount, unitOfAmount, PerUnitOfAmount} = [12,500, USD, null] = USD 12,500.
  """
  CORRELATION = "CORRELATION"
  """
  Denotes a price expressed as the weighted average of all pairwise correlation coefficients.
  """
  DIVIDEND = "DIVIDEND"
  """
  Denotes a price expressed as the dividend payment from a index or share.
  """
  EXCHANGE_RATE = "EXCHANGE_RATE"
  """
  Denotes a rate to convert one currency or other measure of value to another. Foreign Exchange rates are represented in decimals, e.g. {amount, unitOfAmount, PerUnitOfAmount} = [1.23, USD, GBP] = USD 1.23 for every 1 GBP.
  """
  INTEREST_RATE = "INTEREST_RATE"
  """
  Denotes a price expressed as a rate to be applied to quantity/notional amount and represented as decimal, e.g. {amount, unitOfAmount, PerUnitOfAmount} = [0.08, EUR, EUR] = 8%  of the EUR notional quantity/amount or 8 cents for every EUR of notional amount.
  """
  MULTIPLIER_OF_INDEX_VALUE = "MULTIPLIER_OF_INDEX_VALUE"
  """
  Denotes a value to be multiplied by the observed index value to scale it before adding a spread.
  """
  VARIANCE = "VARIANCE"
  """
  Denotes a price expressed as the the arithmetic average of the squared differences from the mean value of an observable price.
  """
  VOLATILITY = "VOLATILITY"
  """
  Denotes a price expressed as the the square root of the arithmetic average of the squared differences from the mean value of an observable price.
  """


import math

sen = math.sin
cos = math.cos
pi = math.pi
sqrt = math.sqrt
v_inicial = 0
v_final = 6*pi
lista = []
lista2 = []

n = 1000000

def funcao(t):
    x = 7*cos(t)-4*cos((7*t)/3)
    y = 7*sen(t)-4*sen((7*t)/3)

    return x, y

h = (v_final - v_inicial) / n

lista.append(funcao(v_inicial))

for i in range(n):
    v_inicial += h
    lista.append(funcao(v_inicial))
    lista2.append(sqrt((lista[0][0] - lista[1][0])**2 + (lista[0][1] - lista[1][1])**2))
    lista.pop(0)

print(sum(lista2))


import numpy as np
from sklearn.decomposition import PCA
import matplotlib.pyplot as plt

def create_data(x1, x2, x3):
    x4 = -4.0 * x1
    x5 = 10 * x1 + 10
    x6 = -1 * x2 / 2
    x7 = np.multiply(x2, x2)
    x8 = -1 * x3 / 10
    x9 = 2.0 * x3 + 2.0
    X = np.hstack((x1, x2, x3, x4, x5, x6, x7, x8, x9))
    return X

def pca(X):
    '''
    PCA step by step
      1. normalize matrix X
      2. compute the covariance matrix of the normalized matrix X
      3. do the eigenvalue decomposition on the covariance matrix
    Return: [d, V]
      d is the column vector containing all the corresponding eigenvalues,
      V is the matrix containing all the eigenvectors.
    If you do not remember Eigenvalue Decomposition, please review the linear
    algebra
    In this assignment, we use the ``unbiased estimator'' of covariance. You
    can refer to this website for more information
    http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.cov.html
    Actually, Singular Value Decomposition (SVD) is another way to do the
    PCA, if you are interested, you can google SVD.
    '''

    ####################################################################
    #normalize matrix X
    mean = np.mean(X,axis=0)
    X_norm = X - mean
    #compute the covariance matrix of the normalized matrix X
    cov_matrix = np.dot(X_norm.T,X_norm)
    #
    d, V = np.linalg.eig(cov_matrix)

    print("d:",d)
    print("V:",V)

    ####################################################################
    # here d is the column vector containing all the corresponding eigenvalues.
    # V is the matrix containing all the eigenvectors,
    return [d, V]

def plot_figs(X):
    """
    1. perform PCA (you can use pca(X) completed by yourself) on this matrix X
    2. plot (a) The figure of eigenvalues v.s. the order of eigenvalues. All eigenvalues in a decreasing order.
    3. plot (b) The figure of POV v.s. the order of the eigenvalues.
    """

    ####################################################################
    d,V=pca(X)
    order_eig=np.flipud(np.argsort(d))

    ####################################################################
    return a

def main():
    N = 1000
    shape = (N, 1)
    x1 = np.random.normal(0, 1, shape) # samples from normal distribution
    x2 = np.random.exponential(10.0, shape) # samples from exponential distribution
    x3 = np.random.uniform(-100, 100, shape) # uniformly sampled data points
    X = create_data(x1, x2, x3)

    print(pca(X))
    plot_figs(X)

if __name__ == '__main__':
    main()


"""Data-module for the Global Wheat dataset."""
from enum import Enum, auto
from typing import Any

import attr
from conduit.data.constants import IMAGENET_STATS
from conduit.data.datasets.utils import PillowTform
from pytorch_lightning import LightningDataModule
from ranzen import implements
from ranzen.decorators import enum_name_str
import torchvision.transforms as T  # type: ignore
from wilds.datasets.globalwheat_dataset import GlobalWheatDataset  # type: ignore
from wilds.datasets.unlabeled.globalwheat_unlabeled_dataset import (  # type: ignore
    GlobalWheatUnlabeledDataset,
)

from src.data.datamodules.base import (
    EvalSplit,
    Split,
    TrainValTestSplit,
    WILDSVisionDataModule,
)

__all__ = [
    "GlobalWheatDatamodule",
    "GlobalWheatSplit",
]

@enum_name_str
class GlobalWheatSplit(Enum):
    official = auto()
    official_with_subsampled_test = auto()
    fixed_test = auto()
    mixed_train = auto()

@attr.define(kw_only=True)
class GlobalWheatDatamodule(WILDSVisionDataModule):
    """Data-module for the iWildCam dataset."""

    use_unlabeled_y: bool = False
    split_scheme: GlobalWheatSplit = GlobalWheatSplit.official

    @property  # type: ignore[misc]
    @implements(WILDSVisionDataModule)
    def _default_train_transforms(self) -> T.Compose:
        # Although GlobalWheat is an image dataset and can be transformed using augmentations
        # we omit data-augmentations for simplicity, because such augmentations would generally
        # require changing y as well as x (e.g., random translations on the input image also
        # require translating the bounding box labels).
        transforms_ls: list[PillowTform] = [T.ToTensor(), T.Normalize(*IMAGENET_STATS)]
        return T.Compose(transforms_ls)

    @property  # type: ignore[misc]
    @implements(WILDSVisionDataModule)
    def _default_test_transforms(self) -> T.Compose:
        transforms_ls: list[PillowTform] = [T.ToTensor(), T.Normalize(*IMAGENET_STATS)]
        return T.Compose(transforms_ls)

    @implements(LightningDataModule)
    def prepare_data(self, *args: Any, **kwargs: Any) -> None:
        GlobalWheatDataset(root_dir=self.root, split_scheme=str(self.split_scheme), download=True)
        if self.use_unlabeled:
            GlobalWheatUnlabeledDataset(
                root_dir=self.root, split_scheme=str(self.split_scheme), download=True
            )

    @implements(WILDSVisionDataModule)
    def _get_splits(self) -> TrainValTestSplit:
        labeled_data = GlobalWheatDataset(root_dir=self.root, split_scheme=str(self.split_scheme))
        train_data = labeled_data.get_subset(split="train")
        ood_val_data = labeled_data.get_subset(split="val")
        ood_test_data = labeled_data.get_subset(split="test")

        id_val_data = labeled_data.get_subset(split="id_val")  # ID validation set
        id_test_data = labeled_data.get_subset(split="id_test")  # ID test set

        train_data_u = None
        val_data_u = None
        test_data_u = None

        if self.use_unlabeled:
            unlabeled_data = GlobalWheatUnlabeledDataset(
                root_dir=self.root, split_scheme=str(self.split_scheme)
            )

            train_data_u = unlabeled_data.get_subset(
                split="train_unlabeled", load_y=self.use_unlabeled_y
            )
            val_data_u = unlabeled_data.get_subset(
                split="val_unlabeled", load_y=self.use_unlabeled_y
            )
            test_data_u = unlabeled_data.get_subset(
                split="test_unlabeled", load_y=self.use_unlabeled_y
            )

        train_data = Split(labeled=train_data, unlabeled=train_data_u)
        ood_val_data = Split(labeled=ood_val_data, unlabeled=val_data_u)
        ood_test_data = Split(labeled=ood_test_data, unlabeled=test_data_u)

        test_data = EvalSplit(ood=ood_test_data, id=id_test_data)
        val_data = EvalSplit(ood=ood_val_data, id=id_val_data)

        return TrainValTestSplit(train=train_data, val=val_data, test=test_data)


import sys
input = sys.stdin.readline

n, k = map(int, input().split())
peoples = [i+1 for i in range(n)]
l = len(peoples)
s = 0
# 1. k * i index 의 숫자를 빼낸다
# 2. k * i > old_peoples 이면 k * i % len(old_peoples)
# 2-2. 이때 len 을 재정의
# 3. new_peoples 의 k * i % len(old_peoples) index 의 숫자를 빼낸다

print('<', end='')
for _ in range(n-1):
    # print(peoples)
    s += k - 1
    if s > l-1:
        s %= l
    print(peoples.pop(s), end=', ')
    l = len(peoples)
print(f'{peoples.pop()}>')

요세푸스 문제 0.py


import gym

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

import warnings
warnings.filterwarnings("ignore")

EPISODE = 3000  # episode限制
STEP = 300  # 采样上限
BATCH_SIZE = 32
GAMMA = 0.9

# # 就用这个来代替我们的experience replay把
# Transition = namedtuple("Transition", ("states", "actions", "rewards"))
# 这样的做法确实很方便，但是这并非我们传统意义上的结构体，比如我们不能自由地访问其成员

class Memory:
    def __init__(self):
        self.states = []
        self.actions = []
        self.rewards = []

    def Store(self, state, action, reward):
        self.states.append(state)
        self.actions.append(action)
        self.rewards.append(reward)

    def Empty(self):
        self.states = []
        self.actions = []
        self.rewards = []

class PolicyNet(nn.Module):
    def __init__(self, in_features, out_features):
        super(PolicyNet, self).__init__()
        self.hidden = nn.Linear(in_features, 20)
        self.output = nn.Linear(20, out_features)

    def forward(self, x):
        """ 返回概率值 """
        if not isinstance(x, torch.Tensor):
            x = torch.tensor(x, dtype=torch.float, requires_grad=True)
        x = F.relu(self.hidden(x))
        # 由于对于动作的选择是一个二分类问题，所以我这里使用sigmoid做激活函数
        x = F.softmax(self.output(x))
        return x

class PG:
    def __init__(self):
        # Environment part
        self.state_dim = env.observation_space.shape[0]
        self.action_dim = env.action_space.n
        # Memory replay
        self.memory = Memory()
        # Policy network(原来这里才引入了policy network,之前的DQN里面根本就没有这个概念)
        self.policy_network = PolicyNet(self.state_dim, self.action_dim)
        self.optimizer = optim.Adam(self.policy_network.parameters(), lr=0.2)

    def __SelectAction(self, state):
        policy = self.policy_network(state).detach().numpy()
        # 用random choice只是其中一种写法而已, pytorch已经集成了一种更好的写法
        return np.random.choice(policy.shape[0], p=policy)

    def __Train(self, step):
        # 说实话，这里的长度就是我们的step
        # Step1: Get state's value
        values = np.zeros(step)
        temp = 0
        for i in reversed(range(step)):
            temp = self.memory.rewards[i] + temp * GAMMA
            values[i] = temp
        # Whiten
        values -= np.mean(values)
        values /= np.std(values)

        # Step2: Calculate reinforce
        # 确实，即便是MCPG，也需要接受一个或者多个样本
        # 之前在做竞赛的时候，就没有碰到过要输入一个单独样本的情况
        actions = torch.tensor(self.memory.actions)
        values = torch.tensor(values, dtype=torch.float)
        policies = self.policy_network(self.memory.states)
        self.optimizer.zero_grad()

        for i in range(step):
            m = Categorical(policies[i])
            loss = -m.log_prob(actions[i]) * values[i]
            # Loss倒确实是标量，我们之前搞图像的时候，loss也是标量
            loss.backward(retain_graph=True)

        self.optimizer.step()

    def Episode(self):
        state = env.reset()
        for step in range(STEP):
            action = self.__SelectAction(state)
            next_state, reward, done, _ = env.step(action)
            self.memory.Store(state, action, reward)
            state = next_state
            if done:
                self.__Train(step)
                self.memory.Empty()
                break

    def Test(self, episode, TEST=10):
        if episode % 100 == 0:
            total_reward = 0
            for i in range(TEST):
                state = env.reset()
                for j in range(STEP):
                    env.render()
                    action = self.__SelectAction(state)
                    state, reward, done, _ = env.step(action)
                    total_reward += reward
                    if done:
                        break
            avg_reward = total_reward / TEST
            print("Episode: ", (episode + 100), "Evaluation Average Reward:", avg_reward)

if __name__ == "__main__":
    # 环境部分
    env = gym.make('CartPole-v0')
    solution = PG()
    for episode in range(EPISODE):
        solution.Episode()
        solution.Test(episode)
    env.close()


# -*- coding: utf-8 -*-
"""
Created on Sat Jan  6 18:56:16 2018
@author: Gebruiker
"""
from BS_Framework import *
from pandas import *
from datetime import *
from tkinter import *
import tkinter as tk
from tkinter import ttk
from numpy import *
import pandas as pd
import matplotlib.pyplot as plt
from PIL import Image, ImageTk

LLLARGE_FONT= ("Verdana", 14)
LLARGE_FONT= ("Verdana", 13)
LARGE_FONT= ("Verdana", 12)
NORM_FONT= ("Verdana", 10)

now = datetime.now()

BS_Class_1 = BS(100, 100, 1,1,1,1,'Espen')

width = 0.35

barwidth = 0.5

ToolBarExists = 0.0

PortfolioManagerClassOnOff = 0.0

NumDigitsRound = 0

VersionNumber = ' v1.01'

photoName = 'wallStreetBull.jpg'

DataBaseFileName = "TradeDatabase.csv"

plot_types = array(['c_delta','p_delta','gamma','gammaP','vega','c_theta',
                    'p_theta','c_rho','p_rho','c_psi','p_psi','c_carry',
                    'p_carry','DdeltaDvol','DdeltaDtime'])
BS_Model_type = array(['BachelierThorp','Norm'])
option_trade_economic_title = array(["Contract Size:","Quantity:","Strike:",
                                          "Start Date (dd-mm-yyyy):","Maturity (dd-mm-yyyy):",
                                          "Interest rate % :","Dividend Yield % :", "sigma :"])
EntryBox_Default_Option_Parameters = array([10,10,100,"10-01-2018","12-03-2018",0.05,0.02,0.2])
option_underlyings = array(["UKX Index","SPX Index","SX5E Index","NKY Index"])
option_underlyings_price = array([100,100,100,100])
#option_underlyings_price = array([7696.51,2747.39,3618.00,23714.53])
optionTradeDetailsForPlot = array(["Strike:","Maturity (Years) :","Interest rate % :","Dividend Yield % :","Sigma % :"])
optionTradeDetailsForPlot_initial_values = array([100,1,0.05,0.02,0.25])
option_BuySell = array(["Buy","Sell"])
option_CallPut = array(["Call","Put"])
option_greeks = array([ "delta","gamma", "vega", "theta","rho","psi","carry","DdeltaDvol","DdeltaDtime"])


import time
from encap_lib.machines import SSHMachine, LocalMachine, run_code_local
import encap_lib.encap_settings as settings

def isfloat(value):
  try:
    float(value)
    return True
  except ValueError:
    return False

# Minimal memory requirements for 16 August 2019
def get_minimal_memory(cpus):
    if cpus == 1:
        return 1.
    else:
        return int((cpus - 1) // 10 + 1) * 0.25 + 1.75 * cpus / 2

def list_instances(project):
    global instances
    result = instances.aggregatedList(project=project).execute()
    if "items" in result:
        instances_list = {}
        for key, item in result['items'].items():
             if 'instances' in item:
                 for i in item['instances']:
                     i['zone'] = key[6:]
                     instances_list[i['name']] = i
        return instances_list
    else:
        return None

def create_machine(vm, core_number, memory, image, zone, project, flags, preemptible=True):

    command = f"gcloud beta compute --project={project} instances create {vm} --custom-cpu {core_number} --custom-memory {int(memory * 1024)}MB --zone {zone} --image={image} {flags}"

    if preemptible:
        command = command + " --preemptible"

    output = run_code_local(command, verbose=True)
    assert not output[0][:5] == "ERROR"
    #print(command)

class GCMachine(SSHMachine):
    def __init__(self, vm, username, local_project_dir, remote_project_dir, zone, project, nfs_name=None, machine_config=None, **kwargs):
        # If True will write the timeout variable to ~/.encap/timeout
        write_timeout = False

        self.nfs = None
        if nfs_name is not None:
            self.nfs = GCMachine(nfs_name, username, local_project_dir, remote_project_dir, zone, project, **kwargs)

        self.vm = vm
        self.project = project
        self.vm_info = self.get_info()

        if self.vm_info is None:
            c = input(f"The VM {self.vm} does not exist. Do you whish to create it? y/n : ")
            if c == "y":
                assert machine_config is not None, "The configuration file has no entry for machine_config."
                core_number = 2
                timeout = 10
                memory = get_minimal_memory(core_number)
                flags = ""

                if "core_number" in machine_config:
                    core_number = machine_config["core_number"]
                    memory = get_minimal_memory(core_number)

                if "preemptible" in machine_config:
                    preemptible = machine_config["preemptible"]
                else:
                    preemptible = False

                if "timeout" in machine_config:
                    timeout = machine_config["timeout"]

                if "memory" in machine_config:
                    memory = machine_config["memory"]

                if "flags" in machine_config:
                    flags = machine_config["flags"]

                c = input(f"Input core number={core_number}, preemptible={preemptible*1}, timeout={timeout}m, memory={memory}GB, flags={flags}, seperate by comas, leave empty for default: \n")
                settings = c.replace(" ", "").split(',')
                ls = len(settings)
                if ls > 0:
                    if settings[0].isdigit():
                        core_number = int(settings[0])
                        memory = get_minimal_memory(core_number)

                if ls > 1:
                    if settings[1].isdigit():
                        preemptible = int(settings[1]) == 1

                if ls > 2:
                    if settings[2].isdigit():
                        timeout = int(settings[2])

                if ls > 3:
                    if isfloat(settings[3]):
                        memory = float(settings[3])

                if ls > 4:
                    flags = settings[4]

                c = input(f"Is this correct core number={core_number}, preemptible={preemptible*1}, timeout={timeout}m, memory={memory}GB, flags={flags} ?:")
                if c == "" or c == "y":
                    image = machine_config["image"]

                    create_machine(vm, core_number, memory, image, zone, self.project, flags, preemptible=preemptible)
                    write_timeout = True

                else:
                    quit()
            else:
                quit()

        if zone is None:
            zone = self.vm_info['zone']

        self.zone = zone
        # Starts VM if it is off
        self.start_vm()
        ip = self.vm_info["networkInterfaces"][0]["accessConfigs"][0]["natIP"]
        super().__init__(username=username, ip=ip, local_project_dir=local_project_dir, remote_project_dir=remote_project_dir, **kwargs)
        if write_timeout:
            out = self.run_code(f"echo {timeout} > ~/.encap/timeout", verbose=True)
            if len(out) > 0:
                out = self.run_code(f"echo {timeout} > ~/.encap/timeout", verbose=True)

                if len(out) > 0:
                    out = self.run_code(f"echo {timeout} > ~/.encap/timeout", verbose=True)

                else:
                    print(f"Timeout {timeout} could not be written to ~/.encap/timeout")
                    quit()

    def start_vm(self):
        self.vm_info = self.get_info()
        while self.vm_info['status'] != 'RUNNING':

            if self.vm_info['status'] == "TERMINATED":
                c = input(f"The VM {self.vm} is not running. Status is {self.vm_info['status']}. Do you whish to start it? y/n : ")

                if c == "y" or c == "Y":
                    out = instances.start(project=self.project, zone=self.zone, instance=self.vm).execute()
                    time.sleep(20)
                    self.vm_info = self.get_info()
                else:
                    quit()
            else :
                time.sleep(1)
                print(f"Status is {self.vm_info['status']}.")
            self.vm_info = self.get_info()

    def get_info(self):
        instances_list = list_instances(self.project)

        if self.vm in instances_list:
            return instances_list[self.vm]
        else:
            return None

    def push(self, *args, **kwargs):
        if self.nfs is not None:
            return self.nfs.push(*args, **kwargs)
        else:
            return super().push(*args, **kwargs)

    def pull(self, *args, **kwargs):
        if self.nfs is not None:
            return self.nfs.pull(*args, **kwargs)
        else:
            return super().pull(*args, **kwargs)

    def rsync_push(self, *args, **kwargs):
        if self.nfs is not None:
            return self.nfs.rsync_push(*args, **kwargs)
        else:
            return super().rsync_push(*args, **kwargs)

    def sync_files(self, *args, **kwargs):
        if self.nfs is not None:
            return self.nfs.sync_files(*args, **kwargs)
        else:
            return super().sync_files(*args, **kwargs)


"""Impements functionality for automatic upgrade inputs"""
import itertools
import logging
import os
from copy import copy

from jade.utils.utils import load_data

from disco.distribution.distribution_inputs import DistributionInputs
from disco.extensions.automated_upgrade_simulation.automated_upgrade_parameters import \
    AutomatedUpgradeParameters

logger = logging.getLogger(__name__)

class AutomatedUpgradeInputs(DistributionInputs):
    """Implements functionality for automated upgrade inputs"""

    def __init__(
        self,
        base_directory,
        sequential_upgrade=False,
        nearest_redirect=False
    ):
        """
        Initialize automated upgrade inputs.

        Parameters
        ----------
        base_directory : str
            The base directory of configuration.
        sequential_upgrade : bool
            Sequential upgrade enabled, default False.
        nearest_redirect : bool
            Redirect DSS files from nearest lower jobs.
        """
        self.sequential_upgrade = sequential_upgrade
        self.nearest_redirect = nearest_redirect
        super().__init__(base_directory)

    def _parse_config_files(self):
        logger.info("Parsing configured job parameters...")
        filename = os.path.join(self._base, self._CONFIG_FILE)
        data = load_data(filename)
        if self.sequential_upgrade:
            parameters = self._parse_parameters_with_blocking_jobs(data)
        else:
            parameters = self._parse_parameters(data)
        self._parameters = parameters
        logger.info("Parsing done.")

    @staticmethod
    def _create_data_groups(data):
        """Sort data based on feeder, and user specified job_order"""
        if len(list(filter(lambda x: x["job_order"] is None, data))) > 0:
            raise ValueError(
                "Invalid 'job_order' value - None, should be int or float."
            )
        keyfunc = lambda x: (x['deployment']["feeder"], x["job_order"])
        data = sorted(data, key=keyfunc)
        groups = itertools.groupby(data, key=keyfunc)
        return groups

    def _parse_parameters_with_blocking_jobs(self, data):
        """
        Parse jobs with blocked_by attributes,
        The blockers are jobs with lower job_order.
        """
        parameters = {}
        groups = self._create_data_groups(data)

        marker = None
        blocking_jobs = set()
        lower_order_job_names = set()
        for (feeder, job_order), group_data in groups:
            if marker is None:
                marker = feeder

            elif marker != feeder:
                blocking_jobs = set()
                lower_order_job_names = set()

            if self.nearest_redirect:
                lower_order_job_names = set()
            for job_data in group_data:
                job = AutomatedUpgradeParameters(job_data)
                job.add_blocking_jobs(blocking_jobs)
                assert job.name not in parameters
                parameters[job.name] = job
                lower_order_job_names.add(job.name)

            if marker != feeder:
                marker = None

            blocking_jobs = copy(lower_order_job_names)

        return parameters

    def _parse_parameters(self, data):
        """Parse jobs without blocked_by attribute."""
        parameters = {}
        for job_data in data:
            job = AutomatedUpgradeParameters(job_data)
            assert job.name not in parameters
            parameters[job.name] = job
        return parameters


from flask import render_template
from flask import redirect
from flask import flash, url_for
from app_folder import app, db, login_manager
from .forms import LoginForm, RegistrationForm, DeleteAccountForm, AvailabitityForm, MeetingsForm, EmailConfirmationForm, AppointmentForm, SendEmailForm, SearchUserForm
from .models import User, Availability,Meetings, listOfMeetings, CustomHTMLCalendar
import flask_login
import flask
from flask_login import login_user,login_required, logout_user
from wtforms import ValidationError
from flask import request
import datetime
from flask_mail import Mail, Message

current_user = flask_login.current_user
mail= Mail(app)

app.config['MAIL_SERVER']='smtp.gmail.com'
app.config['MAIL_PORT'] = 465
app.config['MAIL_USERNAME'] = '2020131springteam6@gmail.com'
app.config['MAIL_PASSWORD'] = 'abc!123ab'
app.config['MAIL_USE_TLS'] = False
app.config['MAIL_USE_SSL'] = True
mail = Mail(app)

cal = CustomHTMLCalendar(0)

@login_manager.user_loader
def load_user(user_id):
    '''
    This method takes the ID of a user and returns the corresponding user object.

    Args:
         user_id (String) : The ID that will be used to find a corresponding user in the data base.

    Returns:
            The user Object that corresponds with the user_id that was passed or none if there is no corresponding user.
    '''
    return User.query.get(int(user_id))

@app.route('/index')
def index():
    '''This method creates the webpage that will display when a guest first visits the application.

    Returns:
            The HTML template that will be rendered when a guest first visits the application. This is the home page.
    '''
    return render_template('index.html', title='Home', User=User, current_user=current_user)

@app.route("/", methods=['GET', 'POST'])
def splashpage():
    '''This method creates the webpage that will display when a guest visits the splash page for this application.

    Returns:
            The HTML template that will be rendered when a guest visists the splash page.
    '''
    form = SearchUserForm(request.form)
    if request.method == 'POST':
        userscal = User.query.filter_by(username=form.username.data).first()
        if userscal is not None:
            return redirect(userscal.username)

    return render_template('SplashPage.html', form = form)

@app.route('/login', methods=['GET', 'POST'])
def login():
    '''
    This method creates the webpage that will display when a guest goes to log into their account.

    Returns:
            the HTML template that will be rendered when a guest wants to log into their account.
    '''
    if current_user.is_authenticated:
        return redirect(url_for('index'))
    form = LoginForm()
    if form.validate_on_submit():
        user = User.query.filter_by(username=form.username.data).first()
        if user is None or not user.check_password(form.password.data):
            flash('**Invalid username or password**')
            return redirect(url_for('login'))
        login_user(user, remember=form.remember_me.data)
        return redirect('meetingsPage')
    return render_template('login.html', title='Sign In', form=form)

@app.route('/logout')
def logout():
    '''
    This method creates the webpage that will display when a guest logs out of the application.

    Returns:
            The HTML template that will be rendered when a guest wants to log out of the application.
    '''
    logout_user()
    return redirect(url_for('index'))

@app.route('/createAccount', methods=['GET', 'POST'])
def createAccount():
    '''
    This method creates the webpage that will display when a guest wants to create an account.

    Returns:
            The HTML template that will be rendered when a guest wants to create an account.
    '''
    if current_user.is_authenticated:
        return redirect (url_for('index'))
    current_form = RegistrationForm()
    if current_form.validate_on_submit():
        login_user = User(username=current_form.username.data, email=current_form.email.data, sendEmailConfirm="Yes")
        login_user.set_password(current_form.password.data)
        db.session.add(login_user)
        db.session.commit()
        flash('**Congratulations, you are now a registered user!**')
        return redirect(url_for('login'))
    elif current_form.username.data != None:
        try:
            if 'email' in current_form.errors:
                flash(current_form.errors['email'][0])
            if 'password2' in current_form.errors:
                flash(current_form.errors['password2'][0])
            current_form.validate_username(current_form.username)
            current_form.validate_email(current_form.email)
        except ValidationError as e:
            flash(e)
    return render_template('createAccount.html', title='Create Account', form=current_form)

import time

def isTimeFormat(input):
    try:
        time.strptime(input, '%H:%M')
        return True
    except ValueError:
        return False

def time_in_range(start, end, x):
    """Return true if x is in the range [start, end]"""
    if start <= end:
        return start <= x <= end
    else:
        return start <= x or x <= end

@login_required
@app.route('/meetingsPage', methods=['GET', 'POST'])
def meetingsPage():
    appointments_list = None
    if not current_user.is_anonymous and current_user.appointments != None :
        appointments_list = current_user.appointments.query.filter_by(user_id = current_user.id)
    return render_template('meetingsPage.html', title='Scheduled Meeting List', current_user=current_user, appointments_list=appointments_list)

@login_required
@app.route('/settings', methods=['GET', 'POST'])
def settings():
	delete_acc_form = DeleteAccountForm(request.form)
	availability_form = AvailabitityForm(request.form)
	email_confirmation_form = EmailConfirmationForm(request.form)
	meetings_form = MeetingsForm(request.form)
	send_email_form = SendEmailForm(request.form)
	current_user = flask_login.current_user
	if request.method == 'POST':
		if 'Delete Account' == request.form['submit'] :
			db.session.delete(current_user)
			db.session.commit()
			print("Deleting account")
			return redirect(url_for('login'))

		elif 'Set Availability' == request.form['submit']:
			availability = Availability(user_id=current_user.id,from_time=availability_form.from_time.data,to_time=availability_form.to_time.data)
			if not isTimeFormat(availability_form.from_time.data) or not  isTimeFormat(availability_form.to_time.data) or availability_form.from_time.data > availability_form.to_time.data:
				flash('**Invalid availability!**')
			else:
				if not time_in_range("09:00","22:00",availability_form.from_time.data) or not time_in_range("09:00","22:00",availability_form.to_time.data):
					flash('**Invalid range choose between 09:00 am  and 10:00 pm!**')
				else:
					if current_user.availability:
						availability = Availability.query.get(current_user.availability.id)
						availability.from_time = availability_form.from_time.data
						availability.to_time = availability_form.to_time.data
						db.session.merge(availability)
						db.session.commit()
						print(availability.user)
					else:
						db.session.add(availability)
						db.session.commit()
					print("Setting availability")
					current_user = User.query.get(int(current_user.id))

		elif 'Set Meetings length' == request.form['submit']:
			meetings = Meetings(user_id=current_user.id,length=meetings_form.length.data)
			if  str(meetings_form.length.data) != "00:15" and str(meetings_form.length.data) != "00:30" and str(meetings_form.length.data) != "01:00" :
				flash("Use 00:15, 00:30 minutes or 01:00 hour  slots. You selected: "+str(meetings_form.length.data))
			else:
				if current_user.meetings:
					meetings = Meetings.query.get(current_user.meetings.id)
					meetings.length = meetings_form.length.data
					db.session.merge(meetings)
					db.session.commit()
					print(meetings.user)
				else:
					db.session.add(meetings)
					db.session.commit()
				print("Setting meetings length")
				current_user = User.query.get(int(current_user.id))

		elif 'Change notification settings' == request.form['submit']:
			current_user.sendEmailConfirm = send_email_form.sendEmail.data
			db.session.merge(current_user)
			db.session.commit()

		elif 'Change email' == request.form['submit']:
			current_user.email = email_confirmation_form.confirmation.data
			db.session.merge(current_user)
			db.session.commit()
			current_user = User.query.get(int(current_user.id))

			msg = Message('Calendar Scheduling App Email Changed', sender = '2020131springteam6@gmail.com', recipients = [email_confirmation_form.confirmation.data])
			msg.body = "Hello " + current_user.username +"," + "\n" + "You have successfully updated your email for the Calendar Scheduling App."
			mail.send(msg)
			flash("Email confirmation sent.")

	return render_template('settings.html', title='Settings', form=delete_acc_form,availability_form=availability_form,user=current_user,meetings_form=meetings_form,email_form=email_confirmation_form, send_email_form=send_email_form)

@app.route('/<userpage>', methods=['GET', 'POST'])
def show_user_cal(userpage):
    '''
    This method takes a username and loads the users event calendar.

    Args:
         userpage (String) : The username that will be checked for validity in the data base and used as the url.

    Returns:
            The users event calendar if the username that was passed corresponds to a valid user.
            Otherwise, this method will return an html page saying the page does not exist.
    '''
    userscal = User.query.filter_by(username=userpage).first()
    cal = CustomHTMLCalendar()
    cal.set_username(userpage)
    if userscal is None:
        return render_template('404.html', badurl=userpage)
    else:
        return render_template('calendar.html', user=userpage,cal=cal.formatmonth(datetime.date.today().year, datetime.date.today().month))

@app.route('/<userpage>/<day>', methods=['GET', 'POST'])
def createAppointment(userpage, day):
    current_form = AppointmentForm()
    userscal = User.query.filter_by(username=userpage).first()
    if userscal is None:
        return render_template('404.html', badurl=userpage)
    availability = userscal.availability
    meetings = userscal.meetings
    listOfMadeMeetings = userscal.appointments
    if availability != None:
        totalappointments = availability.set_available_times(availability.from_time, meetings.length, availability.to_time)
        today = str(datetime.date.today().month) + "/" + str(day)
        if userscal.appointments != None:
            listOfTotalPossibleAppt = userscal.appointments.query.filter_by(meetingDate=today, user_id=userscal.id)
            toChooseFrom = availability.remove_busy_times(totalappointments, listOfTotalPossibleAppt)
        else:
            toChooseFrom = totalappointments
        allBooked = False
        if len(toChooseFrom) != 0:
            current_form.times.choices = toChooseFrom
        else:
            allBooked = True
            current_form.times.choices = None

    if current_form.validate_on_submit():
        try:
            appointments = listOfMeetings(
                user_id=userscal.id,
                meetingDate="{}/{}".format(datetime.date.today().month,day),
                meetingTime=current_form.times.data,
                participants=current_form.person.data,
                descriptionOfMeeting=current_form.details.data)
            db.session.merge(appointments)
            db.session.commit()
            dateTime = "{}/{}".format(datetime.date.today().month,day)
            if(userscal.sendEmailConfirm == "True"):
                msg = Message('Appointment Made', sender = '2020131springteam6@gmail.com', recipients = [userscal.email])
                msg.body = "Hello " + current_user.username + "," + "\n"+ current_form.person.data + " just made an appointment with you on " + dateTime + " from " + current_form.times.data + "."
                mail.send(msg)
            flash("** Successfully Created Appointment! You can now close this tab. **")
        except ValidationError as e:
            flash(e)

    return render_template('createAppointment.html', user=userpage, month=datetime.date.today().month, day=day, form=current_form, availability=availability, meetings=meetings, allBooked=allBooked)


from django.shortcuts import render, get_object_or_404, redirect
from .models import Address
from django.utils import timezone
from .forms import AddressForm
from django.contrib.auth.decorators import login_required

# Create your views here.

def address_list(request):
    address = Address.objects.filter(published_date__isnull=False).order_by('created_date')
    return render(request, 'blog/address_list.html', {'address': address})

def address_detail(request, pk):
    address = get_object_or_404(Address, pk=pk)
    return render(request, 'blog/address_detail.html', {'address': address})

@login_required
def address_new(request):
    if request.method == "POST":
        form = AddressForm(request.POST)
        if form.is_valid():
            address = form.save(commit=False)
            address.name
            address.created_date = timezone.now()
            address.save()
            return redirect('address_detail', pk=address.pk)
    else:
        form = AddressForm()
    return render(request, 'blog/address_edit.html', {'form': form})

@login_required
def address_edit(request, pk):
    address = get_object_or_404(Address, pk=pk)
    if request.method == "POST":
        form = AddressForm(request.POST)
        if form.is_valid():
            address = form.save(commit=False)
            address.name
            address.created_date = timezone.now()
            address.save()
            return redirect('address_detail', pk=address.pk)
    else:
        form = AddressForm(instance=address)
    return render(request, 'blog/address_edit.html', {'form': form})

@login_required
def address_draft_list(request):
    address = Address.objects.filter(published_date__isnull=True).order_by('created_date')
    return render(request, 'blog/address_draft_list.html', {'address': address})

@login_required
def address_publish(request, pk):
    address = get_object_or_404(Address, pk=pk)
    address.publish()
    return redirect('address_detail', pk=pk)

@login_required
def address_remove(request, pk):
    address = get_object_or_404(Address, pk=pk)
    address.delete()
    return redirect('address_list')


#!/usr/bin/python
# coding=utf-8

from __future__ import print_function
from collections import defaultdict
import rospy
from geometry_msgs.msg import Point, Vector3
from autoware_msgs.msg import DetectedObjectArray
from visualization_msgs.msg import Marker, MarkerArray
from std_msgs.msg import ColorRGBA

class TrajectoryVisualizer:
    def __init__(self):

        self.prev_track_ids = set()
        self.mode_set = set()
        self.last_attention_ids = []

        # Subscribers
        rospy.Subscriber("predicted_objects",
                         DetectedObjectArray, self.predicted_objects_callback)

        rospy.Subscriber("yield_eval_attention",
                         DetectedObjectArray, self.yield_eval_attention_callback)

        # Publishers
        self.marker_array_pub = rospy.Publisher(
            "/trajectory_markers", MarkerArray, queue_size=10)

    def predicted_objects_callback(self, msg):
        """
        :type msg: DetectedObjectArray
        """

        trajectory_marker_array = MarkerArray()
        mark_attention = False

        curr_modes = defaultdict(list)
        track_ids = []

        for predicted_object in msg.objects:

            traj_size = len(predicted_object.candidate_trajectories.lanes)

            track_ids.append(predicted_object.id)

            if predicted_object.id in self.last_attention_ids:
                mark_attention = True

            if traj_size == 0 and predicted_object.velocity.linear.x > 0:
                rospy.logwarn("No trajectory for ObstacleID %s with speed %s", str(predicted_object.id), str(predicted_object.velocity.linear.x))

            for i in range(traj_size):

                line_marker = Marker()
                line_marker.id = predicted_object.id
                line_marker.ns = "mode_"+str(i)
                self.mode_set.add("mode_"+str(i))
                curr_modes[predicted_object.id].append("mode_"+str(i))
                line_marker.header.frame_id = "map"
                line_marker.type = Marker.LINE_STRIP
                line_marker.action = line_marker.ADD
                line_marker.pose.orientation.w = 1.0
                line_marker.scale = Vector3(x=0.5, y=0.5, z=0.5)
                if mark_attention:
                    line_marker.color = ColorRGBA(r=1.0, g=0.0, b=0.0, a=1.0)
                else:
                    if predicted_object.candidate_trajectories.lanes[i].cost <= 0.5:
                        line_marker.color = ColorRGBA(
                            r=1.0, g=1.0, b=0.0, a=1.0)
                    else:
                        line_marker.color = ColorRGBA(
                            r=0.0, g=1.0, b=1.0, a=1.0)
                for waypoint in predicted_object.candidate_trajectories.lanes[i].waypoints:
                    line_marker.points.append(Point(
                        waypoint.pose.pose.position.x, waypoint.pose.pose.position.y, waypoint.pose.pose.position.z))

                trajectory_marker_array.markers.append(line_marker)

            mark_attention = False

        new_tracks = set(track_ids)
        tracks_to_delete = self.prev_track_ids - new_tracks
        self.prev_track_ids = new_tracks

        for ns in self.mode_set:
            for old_track in tracks_to_delete:

                line_marker = Marker()
                line_marker.id = old_track
                line_marker.header.frame_id = "map"
                line_marker.type = Marker.LINE_STRIP
                line_marker.action = line_marker.DELETE
                line_marker.ns = ns
                line_marker.pose.orientation.w = 1.0
                line_marker.scale = Vector3(x=0.5, y=0.5, z=0.5)
                trajectory_marker_array.markers.append(line_marker)

            for key in curr_modes:
                if ns not in curr_modes[key]:

                    line_marker = Marker()
                    line_marker.id = key
                    line_marker.header.frame_id = "map"
                    line_marker.type = Marker.LINE_STRIP
                    line_marker.action = line_marker.DELETE
                    line_marker.ns = ns
                    line_marker.pose.orientation.w = 1.0
                    line_marker.scale = Vector3(x=0.5, y=0.5, z=0.5)
                    trajectory_marker_array.markers.append(line_marker)

        self.marker_array_pub.publish(trajectory_marker_array)

    def yield_eval_attention_callback(self, msg):
        """
        :type msg: DetectedObjectArray
        """

        attention_ids = []

        for predicted_object in msg.objects:
            attention_ids.append(predicted_object.id)

        self.last_attention_ids = attention_ids

    def run(self):
        rospy.spin()

if __name__ == '__main__':
    rospy.init_node('trajectory_visualizer',
                    anonymous=False, log_level=rospy.INFO)
    node = TrajectoryVisualizer()
    node.run()


#介绍
# import logging
# logging.basicConfig(
#     # filename='access.log',
#     format='%(asctime)s - %(name)s - %(levelname)s -%(module)s:  %(message)s',
#     datefmt='%Y-%m-%d %H:%M:%S %p',
#     level=10
# )
#
# logging.debug('debug') # 10
# logging.info('info') # 20
# logging.warning('warn') #30
# logging.error('error') #40
# logging.critical('critial') #50

#日志模块的详细用法：
import logging
#1、Logger：产生日志
logger1=logging.getLogger('访问日志')
# logger2=logging.getLogger('错吴日志')

#2、Filter：几乎不用

#3、Handler：接收Logger传过来的日志，进行日志格式化，可以打印到终端，也可以打印到文件
sh=logging.StreamHandler() #打印到终端
fh1=logging.FileHandler('s1.log',encoding='utf-8')
fh2=logging.FileHandler('s2.log',encoding='utf-8')

#4、Formatter：日志格式
formatter1=logging.Formatter(
    fmt='%(asctime)s - %(name)s - %(levelname)s -%(module)s:  %(message)s',
    datefmt='%Y-%m-%d %H:%M:%S %p',
)
formatter2=logging.Formatter(
    fmt='%(asctime)s : %(message)s',
    datefmt='%Y-%m-%d %H:%M:%S %p',
)
formatter3=logging.Formatter(
    fmt='%(asctime)s : %(module)s : %(message)s',
    datefmt='%Y-%m-%d %H:%M:%S %p',
)

#5、为handler绑定日志格式
sh.setFormatter(formatter1)
fh1.setFormatter(formatter2)
fh2.setFormatter(formatter3)

#6、为logger绑定handler
logger1.addHandler(sh)
logger1.addHandler(fh1)
logger1.addHandler(fh2)

#7、设置日志级别:logger对象的日志级别应该＜＝handler的日志界别
# logger1.setLevel(50)
logger1.setLevel(10) #
sh.setLevel(10)
fh1.setLevel(10)
fh2.setLevel(10)

#8、测试
logger1.debug('测试着玩')
logger1.info('运行还算正常')
logger1.warning('可能要有bug了')
logger1.error('不好了，真tm出bug了')
logger1.critical('完犊子，推倒重写')


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

import uuid
import random
import tkinter as tk

class Results(tk.Toplevel):
    """
    Description: This class creates a new window containing only a listbox
    The listbox occupies the entire window and sticks to all boundaries.
    There is only the __init__ function on this class.
    There is a logic to display a minimum of 34 digits + 25% in order to show the full window header.

    Parameters:
        data = the data that will be displayed in the listbox
        digits = the width of the listbox, althought it can be expanded manually
        master = the parent window that owns this one

    Properties:
        data = receives the value of the data parameter
        ListValues = the variable that controls the what is displayed on the listbox
        digits = receives the value of the digits parameter
    """

    def __init__(self, data, digits, master=None):
        tk.Toplevel.__init__(self)

        # Properties:
        self.master = master
        self.ListValues = tk.StringVar()
        self.data = data
        self.ListValues.set(self.data)
        # This will make the window header to be full displayed
        if digits < 34:
            self.digits = 34
        else:
            self.digits = digits+int(digits/4)

        # row and column configuration
        self.rowconfigure(0, weight=1)
        self.columnconfigure(0, weight=1)

        # widget creation
        self.listbox = tk.Listbox(self, listvariable=self.ListValues, exportselection=1, width=self.digits, height=11,
                                  activestyle='dotbox')

        # widget deployment
        self.listbox.grid(row=0, column=0, sticky=tk.W+tk.E+tk.N+tk.S)

class Application(tk.Frame):

    def __init__(self, master=None):
        tk.Frame.__init__(self, master)

        self.master.title('Password Generator')
        self.master.resizable(True, False)

        self.grid(pady=10, padx=10, sticky=tk.W+tk.E+tk.N+tk.S)
        self.radios_value = tk.StringVar()
        self.radios_value.set('n')
        self.spin_value = tk.StringVar()
        self.spin_value.set('16')
        self.special_value = tk.StringVar()
        self.special_value.set('!@#$%-_*')

        self.generateButton = tk.Button(self, text='Generate!', command=self.showresults)
        self.label_radios = tk.Label(self, text='Choose one of the options below:')
        self.radio_n_only = tk.Radiobutton(self, text='Numbers Only', variable=self.radios_value, value='n')
        self.radio_c_only = tk.Radiobutton(self, text='Characters Only', variable=self.radios_value, value='c')
        self.radio_ch_n = tk.Radiobutton(self, text='Character and Numbers', variable=self.radios_value, value='cn')
        self.radio_ch_n_sc = tk.Radiobutton(self, text='Characters, Numbers and Special Characters',
                                            variable=self.radios_value, value='cns')
        self.label_digits = tk.Label(self, text='How many digits?')
        self.spin_digits = tk.Spinbox(self, from_=1, to=256, increment=1, textvariable=self.spin_value)
        self.label_special = tk.Label(self, text='Special characters included (if needed):')
        self.entry_special = tk.Entry(self, width=30, textvariable=self.special_value)

        self.create_widgets()

        self.update_idletasks()
        x = (self.master.winfo_screenwidth() - self.master.winfo_reqwidth()) / 2
        y = (self.master.winfo_screenheight() - self.master.winfo_reqheight()) / 2
        self.master.geometry("+%d+%d" % (x, y))

    def create_widgets(self):
        top = self.winfo_toplevel()

        top.rowconfigure(0, weight=1)
        top.columnconfigure(0, weight=1)
        self.rowconfigure(0, weight=0)
        self.rowconfigure(1, weight=0)
        self.rowconfigure(2, weight=0)
        self.rowconfigure(3, weight=0)
        self.rowconfigure(4, weight=0)
        self.rowconfigure(5, weight=1)
        self.rowconfigure(6, weight=1)
        self.rowconfigure(7, weight=1)
        self.columnconfigure(0, weight=1)
        self.columnconfigure(1, weight=1)

        self.label_radios.grid(row=0, column=0, sticky=tk.W+tk.E, columnspan=2)
        self.radio_n_only.grid(row=1, column=0, sticky=tk.W)
        self.radio_c_only.grid(row=2, column=0, sticky=tk.W)
        self.radio_ch_n.grid(row=3, column=0, sticky=tk.W)
        self.radio_ch_n_sc.grid(row=4, column=0, sticky=tk.W)
        self.label_special.grid(row=5, column=0, sticky=tk.W)
        self.entry_special.grid(row=5, column=1, sticky=tk.E+tk.W)
        self.label_digits.grid(row=6, column=0, sticky=tk.W)
        self.spin_digits.grid(row=6, column=1, stick=tk.E)

        self.generateButton.grid(row=7, column=0, columnspan=2, stick=tk.S)

    def showresults(self):
        data = self.generateresults()
        digits = int(self.spin_value.get())
        results = Results(data=data, digits=digits, master=self)
        results.title('Results')
        results.transient(self)
        results.resizable(True, False)
        results.update_idletasks()
        x = (results.winfo_screenwidth() - results.winfo_reqwidth()) / 2
        y = (results.winfo_screenheight() - results.winfo_reqheight()) / 2
        results.geometry("+%d+%d" % (x, y))
        results.mainloop()

    def generateresults(self):
        size = int(self.spin_value.get())
        data = list()
        if self.radios_value.get() == 'n':
            minimum = str('0')*size
            maximum = str('9')*size
            for i in range(0, 11):
                value = str(random.randint(int(minimum), int(maximum)))
                while len(value) < size:
                    value = '0'+value
                data.append(value)
        elif self.radios_value.get() == 'c':
            import string
            chars_list = string.ascii_lowercase + string.ascii_uppercase
            for i in range(0, 11):
                chars_only = ''
                for j in range(0, size+1):
                    chars_only += random.choice(chars_list)
                data.append(chars_only)
        elif self.radios_value.get() == 'cn':
            for i in range(0, 11):
                my_uuid = str(uuid.uuid4())*(int(size / 32)+1)
                my_uuid = my_uuid.replace('-', '')
                my_uuid = my_uuid[:size]
                my_list = list(my_uuid)
                for j in range(len(my_list)):
                    randomness = random.random()
                    if randomness > 0.5 and not str(my_list[j]).isnumeric():
                        my_list[j] = my_list[j].upper()
                data.append(''.join(my_list))
        elif self.radios_value.get() == 'cns':
            special_chars = self.special_value.get()
            for i in range(0, 11):
                my_uuid = str(uuid.uuid4())*(int(size / 32)+1)
                my_uuid = my_uuid.replace('-', '')
                my_uuid = my_uuid[:size]
                my_list = list(my_uuid)
                for j in range(len(my_list)):
                    randomness = random.random()
                    # 10% of chance to include a special char
                    if randomness > 0.9:
                        random_special = random.choice(special_chars)
                        my_list[j] = random_special

                    # 50% of chance to upper case a non-numeric character
                    if randomness > 0.5 and not str(my_list[j]).isnumeric():
                        my_list[j] = my_list[j].upper()
                data.append(''.join(my_list))

        return tuple(data)

# startup
if __name__ == '__main__':
    window_name = tk.Tk(None, None, 'Password Generator')
    app = Application()
    app.mainloop()