import pygame
import os
import random
global schot
global text
import easygui
from easygui import *
global var1
name = ''
names = ''
schot = 0
text = ''
def vvod():
    global var1
    global name
    msg = "Введите имя"
    title = "Вход"
    fieldValues2 = enterbox(msg, title)
    var1 = fieldValues2
    if len(var1) > 8:
        var1 = var1[:8]
    name = var1

def saveGameState():
    global schot
    global text
    f = open("savedata.txt", "a")
    line1 = " ".join([str(schot)])
    f.write(line1 + "\n")
    f.close()
    f = open("savedata.txt", "r")
    text = f.read()
    text = text.split()
    for i in range(len(text)):
        text[i] = int(text[i])
    f.close()
    #screen.fill((0, 0, 0))
    #font = pygame.font.Font(None, 50)

    #s = font.render(text, 1, pygame.Color('red'))
    #screen.blit(s , (10, 10))
def NaMeS():
    global schot
    global names
    f = open("names.txt", "a")
    line1 = name
    f.write('\n' + line1)
    f.close()
    f = open("names.txt", "r")
    names = f.read()
    names = names.split()
    f.close()

def generate_tortik(n):
    # я решила не заморачиваться поэтому тортики это одноцветные прямоугольники
    colors = [(255, 0, 0), (0, 255, 255), (0, 0, 255), (255, 0, 255), (0, 255, 0)]
    k = pygame.Surface([n, ht])
    random.shuffle(colors)
    k.fill(colors[0])
    return k, colors[0]

def loose():
    global text
    global names
    global schot
    global running
    # это вызывается когда человек проиграл
    saveGameState()
    NaMeS()
    screen.fill((0, 0, 0))
    sm = [[text[i], names[i]] for i in range(len(names))]
    sm.sort(reverse=True)
    font = pygame.font.Font(None, 50)
    for i in range(10):
        s1 = font.render(str(sm[i][1]), 1, pygame.Color('red'))
        s2 = font.render(str(sm[i][0]), 1, pygame.Color('red'))
        screen.blit(s1 , (10, 150 + i*30))
        screen.blit(s2 , (200, 150 + i*30))
    font = pygame.font.Font(None, 50)
    my_text = 'Твой счет: ' + str(schot)
    s = font.render(my_text, 1, (255, 0, 102))
    a = font.render('Ты проиграл', 1, (128, 128, 255))
    screen.blit(s , (10, 10))
    screen.blit(a , (10, 70))

    pygame.display.flip()
    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False

def load_image(name, color_key=None):
    fullname = name
    try:
        image = pygame.image.load(fullname).convert()
    except pygame.error as message:
        print('Cannot load image:', name)
        raise SystemExit(message)
    return image

class Tortik(pygame.sprite.Sprite):
    def __init__(self):
        super().__init__(all_sprites)
        self.h = ht
        self.x = 0
        self.y = 100
        self.rect = pygame.Rect(self.x, self.y, n, self.h)
        a = generate_tortik(n)
        self.image, self.col = a[0], a[1]
        self.dir = 1

    def reinit(self):
        # это обновление текущего тортика(не обычный init чтобы страрый нигде не хранился)
        self.h = ht
        self.x = 0
        self.y = 100
        self.rect = pygame.Rect(self.x, self.y, n, self.h)
        a = generate_tortik(n)
        self.image, self.col = a[0], a[1]
        self.dir = 1

    def tuda_suda(self):
        # передвигание влево-вправо
        if self.x <= 0:
            self.dir = 1
        if self.x >= w - n:
            self.dir = -1
        self.x += self.dir
        self.update()

    def fall(self):
        global running
        global nx
        global schot

        # чтобы не ломалось если нажать на крестик пока падает
        while self.y < h - (k+1)*self.h:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    running = False
                    break
            self.y += 1
            screen.fill((0, 0, 0))
            screen.blit(fon, (0, 0))
            font = pygame.font.Font(None, 50)
            s= font.render("Score: " + str(schot), 1, pygame.Color('red'))
            screen.blit(s , (10, 10))
            all_sprites.draw(screen)
            all_sprites.update()
            pygame.display.flip()
            clock.tick(300)
        if k > 0:
            self.obrez(oldy[-1].x)
        else:
            nx = self.x

    def update(self):
        self.rect = pygame.Rect(self.x, self.y, n, ht)

    def obrez(self, mx):
        global schot
        global n
        global nx
        # проверять касание не нужно т к оно вызывается когда гарантированно касание есть
        if abs(mx - self.x) <= 2:
            n += 5
            schot += 5
            self.rect = pygame.Rect(self.x, self.y, n, ht)
        else:
            if mx > self.x:
                nx = mx
                n = n - (mx-self.x)
                self.rect = pygame.Rect(self.x, self.y, n, ht)
                schot += 1
            elif mx < self.x:
                nx = self.x
                n = n - (self.x-mx)
                self.rect = pygame.Rect(self.x, self.y, n, ht)
                schot += 1
        if n < 0:
            f = False
            loose()

class Static(pygame.sprite.Sprite):
    def __init__(self, x, y, col):
        super().__init__(all_sprites)
        super().__init__(old_sprites)
        self.x = x
        self.y = y
        self.n = n
        self.col = col
        self.rect = pygame.Rect(x, y, n, ht)
        self.image = pygame.Surface([n, ht])
        self.image.fill(col)

    def reinit(self, x, y, col, n):
        self.x = x
        self.y = y
        self.n = n
        self.col = col
        self.rect = pygame.Rect(x, y, n, ht)
        self.image = pygame.Surface([n, ht])
        self.image.fill(col)

if __name__ == '__main__':
    pygame.init()
    vvod()
    msg = "                      Добро пожаловать в игру, " + str(var1) # Str + Int = Error
    msgbox(msg, "Приветствие", "Let's go")
    w = 300
    h = 600
    ht = 50
    f = True
    K = 5 #сколько тортиков будет показываться
    k = 0 #ckoлько тортиков сейчас
    screen = pygame.display.set_mode([w, h])
    screen.fill((0, 0, 0))
    fon = pygame.image.load('tecna.png').convert_alpha()
    screen.blit(fon, (0, 0))
    oldy = [] # массив с тортиками которые внизу
    old_sprites = pygame.sprite.Group() # это вроде не пригодилось
    all_sprites = pygame.sprite.Group()
    all_sprites.draw(screen)
    all_sprites.update()
    running = True
    fps = 100
    clock = pygame.time.Clock()
    t = True
    n = 250
    nx = 0
    Tortic = Tortik() #активный тортик
    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
            if event.type == pygame.KEYDOWN:
                keys = pygame.key.get_pressed()
                if keys[pygame.K_SPACE]:
                    Tortic.fall()
                    k += 1
                    if f:
                        if k > K:
                            for i, a in enumerate(oldy[:-1]):
                                a.reinit(oldy[i+1].x,  oldy[i+1].y + ht, oldy[i+1].col, oldy[i+1].n)
                            oldy[-1].reinit(nx, Tortic.y + ht, Tortic.col, n)
                            k -= 1
                        else:
                            oldy.append(Static(nx, Tortic.y, Tortic.col))
                        Tortic.reinit()
        if f:
            Tortic.tuda_suda()
            screen.fill((0, 0, 0))
            screen.blit(fon, (0, 0))
            font = pygame.font.Font(None, 50)
            s= font.render("Score: " + str(schot), 1, pygame.Color('red'))
            screen.blit(s , (10, 10))
            all_sprites.draw(screen)
            all_sprites.update()

            pygame.display.flip()
            clock.tick(fps)
    pygame.display.flip()
pygame.quit()

супертортоик.py

супертортоик.py


# coding: utf-8
import itertools as it
import os
import sys

import numpy as np
from algorithms.hj_search import HookeJeeves
from fitter import Fitter
from scipy.interpolate import RegularGridInterpolator

if 'NN' not in locals():
    NN = Fitter()
devnull = open(os.devnull, 'w')

def func(*p):
    try:
        return interp(p)
    except ValueError:
        return np.inf

old_stdout = sys.stdout
points = [np.linspace(0, 1, 10)] * 4
x_init = np.array([0.5, 0.5, 0.5, 0.5])
delta = 0.1
scale = 0.85
list_loss_all = []
for delta in [1.0, 0.1, 0.01, 0.001]:
    for scale in [0.95, 0.85, 0.5, 0.1]:
        list_loss = []
        for target_param in list(it.product([0.222, 0.777], repeat=4)):
            sys.stdout = devnull
            target_index = NN.data.contents_addressing(target_param, NN.ya)
            loss_array = NN.be.msre(NN.xa, NN.xa[target_index], axis=1)
            interp = RegularGridInterpolator(points, loss_array.reshape(10, 10, 10, 10))

            p_tg, p, l, exp_count, dig_count, t_collapsed = HookeJeeves(func, x_init, delta=delta, scale=scale)
            print(f"Target: {list(target_param)}. Result: {p}")
            print(f"Loss: {l}. Exploration: {exp_count}. Digging: {dig_count}")
            sys.stdout = old_stdout
            list_loss.append(l.item())
        print(f"Delta {delta}, Scale {scale}. Mean loss {np.mean(list_loss)}.")
        list_loss_all.append(list_loss)

devnull.close()


from __future__ import unicode_literals

from django.test import TestCase

from .models import Category, Person

class ManyToOneRecursiveTests(TestCase):

    def setUp(self):
        self.r = Category(id=None, name='Root category', parent=None)
        self.r.save()
        self.c = Category(id=None, name='Child category', parent=self.r)
        self.c.save()

    def test_m2o_recursive(self):
        self.assertQuerysetEqual(self.r.child_set.all(),
                                 ['<Category: Child category>'])
        self.assertEqual(self.r.child_set.get(name__startswith='Child').id, self.c.id)
        self.assertIsNone(self.r.parent)
        self.assertQuerysetEqual(self.c.child_set.all(), [])
        self.assertEqual(self.c.parent.id, self.r.id)

class MultipleManyToOneRecursiveTests(TestCase):

    def setUp(self):
        self.dad = Person(full_name='John Smith Senior', mother=None, father=None)
        self.dad.save()
        self.mom = Person(full_name='Jane Smith', mother=None, father=None)
        self.mom.save()
        self.kid = Person(full_name='John Smith Junior', mother=self.mom, father=self.dad)
        self.kid.save()

    def test_m2o_recursive2(self):
        self.assertEqual(self.kid.mother.id, self.mom.id)
        self.assertEqual(self.kid.father.id, self.dad.id)
        self.assertQuerysetEqual(self.dad.fathers_child_set.all(),
                                 ['<Person: John Smith Junior>'])
        self.assertQuerysetEqual(self.mom.mothers_child_set.all(),
                                 ['<Person: John Smith Junior>'])
        self.assertQuerysetEqual(self.kid.mothers_child_set.all(), [])
        self.assertQuerysetEqual(self.kid.fathers_child_set.all(), [])


import math
import array

fileName = "out.dat"
def readFileAsShort(filename):
	with open(filename, "rb") as file:
		data = file.read()
		arr = array.array('H')
		arr.fromstring(data)
	return arr

def calcSinCos(period, clock, ncycle, data):
	'''
		return (c0,csin, ccos)
		c0+csin*sin(f)+ccos*cos(f)
	'''
	arr = array.array('f', data)
	#print "ncycle=", ncycle
	fsin = [ math.sin(2*math.pi*i/ncycle) for i in range(ncycle)]
	fcos = [ math.cos(2*math.pi*i/ncycle) for i in range(ncycle)]

	N = len(data)

	#print "N =", len(data), len(arr)
	#N = ncycle
	sum_c0 = 0
	for i in range(N):
		sum_c0 += arr[i]
	c0 = sum_c0/N

	for i in range(N):
		arr[i] -= c0

	sum_sin = 0
	sum_cos = 0
	for i in range(N):
		ic = i%ncycle
		sum_sin += arr[i]*fsin[ic]
		sum_cos += arr[i]*fcos[ic]

	csin = sum_sin*2/N
	ccos = sum_cos*2/N

	#print "c0=", c0
	print("csin=", csin)
	print("ccos=", ccos)
	#print arr
	return (c0, csin, ccos)

def calcFi(csin, ccos):
	'''
		input
		csin*sin(f)+ccos*cos(f) == amplitude*sin(f+fi)
		return (amplitude, fi)
	'''
	amplitude = math.sqrt(csin*csin+ccos*ccos)
	#print "amplitude=", "{:.2f}".format(amplitude)
	csin /= amplitude
	ccos /= amplitude

	#print "sin=", math.acos(csin)
	#print "cos=", math.asin(ccos)
	fi = math.atan2(ccos, csin)
	#print "fi=", fi
	return (amplitude, fi)

def deltaError(data, c0, amplitude, fi, ncycle):
	N = len(data)
	out = [ c0+amplitude*math.sin(2*math.pi*i/ncycle+fi)-data[i] for i in range(N)]
	return out

def correctedSampleStandardDeviation(data, c0, amplitude, fi, ncycle):
	N = len(data)
	sum = 0
	for i in range(N):
		v = c0+amplitude*math.sin(2*math.pi*i/ncycle+fi)
		sum += (data[i]-v)*(data[i]-v)

	return math.sqrt(sum/(N-1))

def calcAll(period, clock, ncycle, data):
	(c0, csin, ccos) = calcSinCos(period, clock, ncycle, data)

	(amplitude, fi) = calcFi(csin, ccos)
	square_error = correctedSampleStandardDeviation(data, c0, amplitude, fi, ncycle)
	t_propagation = fi/(2*math.pi)*period/clock

	print("square_error=", square_error)

	return {"period": period, "clock": clock, "ncycle": ncycle,
		"c0": c0, "csin": csin, "ccos": ccos, "amplitude": amplitude,
		"fi": fi, "square_error": square_error, "t_propagation": t_propagation}

def main():
	pass

if __name__ == "__main__":
	main()


#!/usr/bin/env python
import cv2
import numpy as np

# always remember:
# Any primitive type from the list can be defined by an
# identifier in the form
# CV_<bit-depth>{U|S|F}C(<number_of_channels>)

def getSobelEdge(img , size=3):
    sx = cv2.Sobel(img, cv2.CV_64F,1,0,ksize=size)
    sy = cv2.Sobel(img,cv2.CV_64F,0,1,ksize=size)
    edges = np.sqrt(np.square(sx) + np.square(sy))
    edges = np.floor((edges / (np.max(edges)+0.001)) * 255 ).astype(np.uint8)
    return edges

# some global parameters
MEDIAN_BLUR_FILTER_SIZE = 5
LAPLACIAN_FILTER_SIZE = 5
EDGES_THRESHOLD = 10
# loading an image
img = cv2.imread("t.png")

# converting an image to the grayscale
imgray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# median blurring the image
imgray = cv2.medianBlur(imgray , MEDIAN_BLUR_FILTER_SIZE)

# applying the laplace filter to get the edges
# edges = cv2.Laplacian(imgray, cv2.CV_8U ,  LAPLACIAN_FILTER_SIZE).astype(np.uint8)
edges = getSobelEdge(imgray , -1)
# kernel = np.ones((5,5),np.uint8)
# erosion = cv2.erode(img,kernel,iterations = 1)
# creating the mask
_ , mask = cv2.threshold(edges , EDGES_THRESHOLD , 255 , cv2.THRESH_BINARY_INV )

cv2.imread(img)
# cv2.waitKey(0)
# cv2.destroyAllWindows()

###############################################################

# generating a color painting

# A strong bilateral filter smoothes flat regions while keeping edges sharp, and
# is therefore great as an automatic cartoonifier or painting filter, except that it
# is extremely slow (that is, measured in seconds or even minutes rather than
# milliseconds!).

# trick:-
# perform bilateral filtering at a lower resolution
# therefore if the number of pixels is more than : 400 * 400
# reduce the resolution by the factor of 4
# if the resolution is below (150 * 150) : increase it by factor of 2

height , width, _ = img.shape
img = cv2.resize(img,(width//2, height//2), interpolation = cv2.INTER_LINEAR)

# four parameters that control the bilateral filter:
# color strength, positional strength, size, and repetition count

# use resizedImg instead of the img
tmp = img
# repetitions for stronger cartoon effect
REPETITIONS = 17
# filter size
ksize = 9
# Filter color strength
sigmaColor = 9
# spatial strength
sigmaSpace = 7

for i in range(REPETITIONS):
    tmp = cv2.bilateralFilter(img, ksize, sigmaColor , sigmaSpace)
    img = cv2.bilateralFilter(tmp , ksize, sigmaColor , sigmaSpace)

img = cv2.resize(img, (width, height))
newimg = np.zeros(img.shape).astype(np.uint8)
print(newimg.shape)
for i in range(3):
    newimg[:,:,i] = cv2.bitwise_and(img[:,:,i],mask)

# cv2.imshow("cartoon" , img)
cv2.imshow("cartoon-border" , newimg)
cv2.waitKey(0)
cv2.destroyAllWindows()


# -*- coding: utf-8 -*-
"""
Created on Sun Aug 14 17:27:53 2016

@author: yuxitao
"""

import pylab as pl
import scipy as sp
#img = sp.misc.face()
img = pl.imread('lepetitpoisson.jpg')
pl.imshow(img,cmap=pl.cm.gray)

img2 = img[:-2,1:-1]-img[2:,1:-1]+img[1:-1,:-2]
pl.figure()
pl.imshow(img2,cmap=pl.cm.gray)

pl.show()


class Solution(object):
    def isValidBST(self, root):
        """
        :type root: TreeNode
        :rtype: bool
        """
        output = []
        self.inOrder(root, output)

        for i in range(1, len(output)):
            if output[i-1] >= output[i]:
                return False
        return True

    def inOrder(self, root, output):
        if root is None:
            return

        self.inOrder(root.left, output)
        output.append(root.val)
        self.inOrder(root.right, output)

# The reason to use a MIN and MAX is to help pass the previous min/max value to next level.
# If we don't have such infomation the BST order can't be valid.

# python max/min number: float('inf')/float('-inf')


import numpy as np
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import torch
from sklearn import metrics
import argparse
import timeit
import os

from model import MolecularGNN

def data_load(args, device):
    data = torch.load('data/%s.pth' % (args.dataset))
    train_data = data['train_data']
    test_data = data['test_data']
    N_fingerprints = data['N_fingerprints']

    # Transform numpy data to torch tensor
    for index, (fingerprints, adjacency, outcome) in enumerate(train_data):
        fingerprints = torch.LongTensor(fingerprints).to(device)
        adjacency = torch.FloatTensor(adjacency).to(device)
        outcome = torch.LongTensor([int(outcome)]).to(device)
        train_data[index] = (fingerprints, adjacency, outcome)

    for index, (fingerprints, adjacency, outcome) in enumerate(test_data):
        fingerprints = torch.LongTensor(fingerprints).to(device)
        adjacency = torch.FloatTensor(adjacency).to(device)
        outcome = torch.LongTensor([int(outcome)]).to(device)
        test_data[index] = (fingerprints, adjacency, outcome)

    return train_data, test_data, N_fingerprints

def main(args):
    device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
    print('Using %s device.' % (device))

    train_data, test_data, N_fingerprints = data_load(args, device)

    print('train %d compounds' % (len(train_data)))
    print('test %d compounds' % (len(test_data)))

    net = MolecularGNN(N_fingerprints,
            dim=args.dim,
            layer_hidden=args.layer_hidden,
            layer_output=args.layer_output,
            n_output=args.num_classes)
    net = net.to(device)

    print('# of parameters', sum([np.prod(layer.size()) for layer in net.parameters()]))

    if os.path.exists('model/%s.pth' % (args.dataset)):
        net.load_state_dict(torch.load('model/%s.pth' % (args.dataset)))

    optimizer = optim.Adam(net.parameters(), lr=args.lr)
    criterion = F.cross_entropy

    for epoch in range(1, args.epochs+1):
        epoch_start = timeit.default_timer()

        if epoch % args.decay_interval == 0:
            optimizer.param_groups[0]['lr'] *= args.lr_decay

        np.random.shuffle(train_data)

        train_loss = 0
        net.train()
        for batch_index, index in enumerate(range(0, len(train_data), args.batch_size), 1):
            data_batch = list(zip(*train_data[index:index+args.batch_size]))
            data = data_batch[:-1]
            labels = torch.cat(data_batch[-1])

            outputs = net(data)
            loss = criterion(outputs, labels)
            train_loss += loss.item()

            optimizer.zero_grad()
            loss.backward()
            optimizer.step()

            print('\repoch %4d batch %4d/%4d train_loss %5.3f' % (
                epoch, batch_index, len(train_data) // args.batch_size + 1, train_loss / batch_index), end='')

        net.eval()
        test_loss = 0
        y_score = []
        y_true = []
        for batch_index, index in enumerate(range(0, len(test_data), args.batch_size), 1):
            data_batch = list(zip(*test_data[index:index+args.batch_size]))
            data = data_batch[:-1]
            labels = torch.cat(data_batch[-1])

            with torch.no_grad():
                outputs = net(data)

            loss = criterion(outputs, labels)
            test_loss += loss.item()

            outputs = F.softmax(outputs, 1)

            y_score.append(outputs.detach().cpu().numpy())
            y_true.append(labels.cpu().numpy())

        y_score = np.concatenate(y_score)
        y_pred = [np.argmax(x) for x in y_score]
        y_true = np.concatenate(y_true)

        print(' test_loss %5.3f' % (test_loss / batch_index), end='')

        if np.sum(y_pred) > 0:
            auc = metrics.roc_auc_score(y_true, y_score[:,1])
            prec = metrics.precision_score(y_true, y_pred)
            recall = metrics.recall_score(y_true, y_pred)

            print(' test_auc %5.3f test_prec %5.3f test_recall %5.3f' % (auc, prec, recall), end='')

        print(' %5.2fsec' % (timeit.default_timer() - epoch_start))

        torch.save(net.state_dict(), 'model/%s.pth' % (args.dataset))

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    # classification target is a binary value (e.g., drug or not).
    parser.add_argument('--random_seed', default=123, type=int)
    parser.add_argument('--dataset', default='hiv', type=str)
    parser.add_argument('--epochs', default=10, type=int)
    parser.add_argument('--batch_size', default=32, type=int)
    parser.add_argument('--lr', default=1e-4, type=float)
    parser.add_argument('--lr_decay', default=0.99, type=float)
    parser.add_argument('--decay_interval', default=10, type=int)
    parser.add_argument('--num_classes', default=2, type=int)
    parser.add_argument('--dim', default=50, type=int)
    parser.add_argument('--layer_hidden', default=6, type=int)
    parser.add_argument('--layer_output', default=6, type=int)
    args = parser.parse_args()
    print(vars(args))

    main(args)


"""

"""
from doors.config import DoorsConfig

class APIConfig:

    AUTHENTICATION_SERVER = DoorsConfig.DOORS_AUTH_SERVER
    SERVER_ADDRESS = DoorsConfig.DOORS_SERVER_ADDRESS

    #AUTHENTICATION_SERVER = DoorsConfig.DOORS_AUTH_SERVER
    #SERVER_ADDRESS = DoorsConfig.DOORS_SERVER_ADDRESS

    AUTH_URL_SUFFIX = '/auth/j_security_check'
    DEBUG = True

    OPERATION_SUCCESS = 200
    OPERATION_ERROR = 500
    HEADER = {'accept': 'application/rdf+xml'}
    GET_DEFAULT_HEADERS = {'OSLC-Core-Version': '2.0',
                           'Accept': 'application/rdf+xml'}
    PUT_DEFAULT_HEADERS = {'OSLC-Core-Version': '2.0',
                           'Accept': 'application/rdf+xml',
                           'Content-Type': 'application/rdf+xml'}
    POST_DEFAULT_HEADERS = {'OSLC-Core-Version': '2.0',
                            'Accept': 'application/rdf+xml',
                            'Content-Type': 'application/rdf+xml'}
    OSLC_NAMESPACE_MAP = {'rdf': 'http://www.w3.org/1999/02/22-rdf-syntax-ns#',
                          'rdfs': 'http://www.w3.org/2000/01/rdf-schema#',
                          'dc': 'http://purl.org/dc/terms/',
                          'oslc': 'http://open-services.net/ns/core#',
                          'rm': 'http://www.ibm.com/xmlns/rdm/rdf/',
                          'xmlns_rm': 'http://open-services.net/xmlns/rm/1.0/',
                          'oslc_config': 'http://open-services.net/ns/config#',
                          'qm_rqm': 'http://jazz.net/ns/qm/rqm#',
                          'oslc_qm': 'http://open-services.net/xmlns/qm/1.0/',
                          'oslc_qm_ns': 'http://open-services.net/ns/qm#',
                          'xmlns_cm': 'http://open-services.net/xmlns/cm/1.0/',
                          'oslc_cm': 'http://open-services.net/ns/cm#',
                          'oslc_disc': 'http://open-services.net/xmlns/discovery/1.0/',
                          'namespace': 'http://www.w3.org/XML/1998/namespace',
                          'dc_elements': 'http://purl.org/dc/elements/1.1/',
                          'alm': 'http://jazz.net/xmlns/alm/v0.1/',
                          'alm_qm': 'http://jazz.net/xmlns/alm/qm/v0.1/',
                          'testscript': 'http://jazz.net/xmlns/alm/qm/v0.1/testscript/v0.1/',
                          'xhtml1999': 'http://www.w3.org/1999/xhtml',
                          'rtc_ext': 'http://jazz.net/xmlns/prod/jazz/rtc/ext/1.0/',
                          'myns': 'http://mydomain.net/some/custom/namespace/v0.1/',
                          'oslc_rm': 'http://open-services.net/ns/rm#',
                          'atom': 'http://www.w3.org/2005/Atom',
                          'BTattr': 'http://rail.bombardier.com/xmlns/rm/attr/',
                          'rtc_cm': 'http://jazz.net/xmlns/prod/jazz/rtc/cm/1.0/',
                          'oslc_cmx': 'http://open-services.net/ns/cm-x#',
                          'soapenv': 'http://schemas.xmlsoap.org/soap/envelope/',
                          'xsi': 'http://www.w3.org/2001/XMLSchema-instance',
                          'jazzns_rm': 'http://jazz.net/ns/rm#',
                          'BTlinks': 'http://rail.bombardier.com/xmlns/rm/linktypes/',
                          'BTinks': 'http://rail.bombardier.com/xmlns/rm/linkypes/',
                          'rdm_types': 'http://www.ibm.com/xmlns/rdm/types/',
                          'nav': 'http://jazz.net/ns/rm/navigation#',
                          'jd': 'http://jazz.net/xmlns/prod/jazz/discovery/1.0/',
                          'jp06': 'http://jazz.net/xmlns/prod/jazz/process/0.6/',
                          'process': 'http://jazz.net/ns/process#',
                          'public_rm_10': 'http://www.ibm.com/xmlns/rm/public/1.0/',
                          'restDTO': 'com.ibm.team.workitem.rest.dto',
                          'queryDTO': 'com.ibm.team.workitem.query.rest.dto',
                          'trs': 'http://jazz.net/ns/trs#',
                          'jfs': 'http://jazz.net/xmlns/prod/jazz/jfs/1.0/'}


# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('okna', '0009_auto_20170106_2329'),
    ]

    operations = [
        migrations.AlterField(
            model_name='currency',
            name='currency_id',
            field=models.IntegerField(unique=True, auto_created=True, primary_key=True, serialize=False),
        ),
    ]


import logging
from typing import Any, List

from click.testing import CliRunner, Result

_logger = logging.getLogger(__name__)

def invoke_cli(args: List[str],
               root_command: Any,
               *,
               verify_successful=True,
               always_log_output=True):
    runner = CliRunner()
    result: Result = runner.invoke(root_command, args, catch_exceptions=False)

    if verify_successful:
        if result.exit_code != 0:
            _logger.info("cli call output (on next line):\n" + str(result.output))
        assert result.exit_code == 0
    if always_log_output:
        _logger.info("cli call output (on next line):\n" + str(result.output))
    return result


import os
import flask
from flask import json, request, jsonify
from flask_cors import CORS
import subprocess
from subprocess import check_output as CO
import time
import datetime

from kubernetes import client, config
from pprint import pprint

from flask_restx import Api, Resource, fields

app = flask.Flask(__name__)
api = Api(app, verion='1.0', title='Upayan-Admin-Api', description="Admin Api for Upayan Loyalty Platform")

ns = api.namespace('admin', description= 'Admin Operations')

CORS(app)
app.config['DEBUG'] = True

response_json = {
    "program" : "admin_server",
    "version" : "TEST",
}

def populate_response(resp = response_json, status = "No info", code = "100", message = "message was not set", data = {}):
    # resp["program"] = "admin_server";
    # resp["version"] = "TEST";
    resp["datetime"] = datetime.datetime.now().strftime("%m/%d/%Y, %H:%M:%S")
    resp["status"] = status
    resp["code"] = code
    resp["data"] = data
    resp["message"] = message
    return resp

def read_json(filename):
    with open(filename) as f:
        data = json.load(f)
        return data

# @app.route('/', methods=['GET'])
# def home():
#     resp = populate_response(status = "success", code = "200")
#     return resp

@ns.route('/hello')
class home(Resource):
    def get(self):
        resp = populate_response(status = "success", code = "200")
        return resp

cluster = api.model("cluster", {"name": fields.String(readonly=True, description='Name of the cluster')})

@ns.route('/cluster')
class cluster(Resource):
    @ns.doc('get cluster status')
    def get(self):
        resp = populate_response(status = "success", code = "200", message = "get cluster")
        return resp
    @ns.doc('create cluster')
    @ns.expect(cluster)
    def post(self):
        # message = request.form['message']
        resp = populate_response(status = "success", code = "200", message = message)
        return resp
# @app.route('/cluster', methods=['POST'])

app.run(port=9997)


import torch
import torch.nn as nn
from datetime import datetime

class AverageMeter(object):
    """Computes and stores the average and current value"""

    def __init__(self):
        self.reset()

    def reset(self):
        self.val = 0
        self.avg = 0
        self.count = 0
        self.total = 0

    def update(self, val, delta):
        self.val = val
        self.count += val * delta
        self.total += delta
        if self.total > 0:
            self.avg = self.count / self.total

class Plugin:

    def __init__(self):
        pass

    def __current_time__(self):
        current_time = datetime.now().strftime('%Y-%b-%d-%H-%M-%S')
        return current_time

    def register(self, trainer):
        self.trainer = trainer

    def logger(self):
        print('------------%s--------------' % self.name)

    def call(self):
        raise NotImplementedError

class IterationMonitor(Plugin):

    def __init__(self):
        self.plugin_type = 'iteration'

class EpochMonitor(Plugin):

    def __init__(self):
        self.plugin_type = 'epoch'

class BatchMonitor(Plugin):

    def __init__(self):
        self.plugin_type = 'batch'

class UpdateMonitor(Plugin):

    def __init__(self):
        self.plugin_type = 'update'

class DataForward(Plugin):

    def __init__(self, train_forward, validation_forward=None, **kwargs):
        self.plugin_type = 'dataforward'
        self.train_forward = train_forward
        self.validation_forward = validation_forward
        self.kwargs = kwargs

    def call(self, data, target, train=True):
        if train:
            return self.train_forward(self, data, target)
        elif self.validation_forward:
            return self.validation_forward(self, data, target)
        else:
            return self.train_forward(self, data, target)

class ModelGradHandler(UpdateMonitor):

    def __init__(self, lambda_=None, **kwargs):
        super(ModelGradHandler, self).__init__()
        self.lambda_ = lambda_
        self.kwargs = kwargs

    def register(self, trainer):
        self.model = trainer.model

    def call(self):
        self.lambda_(self)

class DataMonitor(IterationMonitor):

    def call(self, output, target, loss):
        if not isinstance(output, tuple):
            self.__handle__(output.data, target.data, loss.item())
        else:
            self.__handle__(output[0].data, target.data, loss.item())

    def __handle__(self, output, target):
        raise NotImplementedError

    def getState(self):
        raise NotImplementedError

    def reset(self):
        raise NotImplementedError

class LossMonitor(DataMonitor):
    name = 'Loss'

    def __init__(self):
        super(LossMonitor, self).__init__()
        self.batch_idx = 0
        self.loss = AverageMeter()
        self.lr = None

    def __handle__(self, output, target, loss):
        self.batch_idx += 1
        self.batch_size = output.size(0)
        self.loss.update(loss, output.size(0))

    def logger(self, e=None, train=True):
        if train:
            self.lr = iter(self.trainer.optimizer.param_groups).__next__()['lr']
            print('=======================================')
            print('{}\t Epoch: {} [{}/{}]\t'
                  'Loss: {loss.val:.6f}\t'
                  'LR: {}'
                  .format(
                      self.__current_time__(),
                      e,
                      self.batch_idx * self.batch_size,
                      len(self.trainer.train_loader.dataset),
                      self.lr,
                      loss=self.loss,
                  ))

        else:
            if self.trainer.model.training:
                self.lr = iter(
                    self.trainer.optimizer.param_groups).__next__()['lr']
                print(
                    '==================Training Epoch Summary=====================')
                print('{}\t'
                      'Loss: {loss.avg:.6f}\t'
                      'LR: {}'
                      .format(
                        self.__current_time__(),
                        self.lr,
                        loss=self.loss,
                          ))
            else:
                print(
                    '==================Validation Summary=====================')
                print('{}\t'
                      'Loss: {loss.avg:.6f}\t'
                      .format(
                          self.__current_time__(),
                          loss=self.loss,
                      ))

    def getState(self):
        State = {'Loss': self.loss.avg}
        return State

    def reset(self):
        self.loss.reset()
        self.batch_idx = 0

class TopKAccuracy(DataMonitor):
    name = 'TopK Accuracy'

    def __init__(self, topk=(1,)):
        super(TopKAccuracy, self).__init__()
        self.topk = topk
        self.topAcc = [AverageMeter() for i in self.topk]

    def __handle__(self, output, target, loss):
        maxk = max(self.topk)
        batch_size = target.size(0)

        _, pred = output.topk(maxk, 1, True, True)
        pred = pred.t()
        correct = pred.eq(target.view(1, -1).expand_as(pred))

        for i, k in enumerate(self.topk):
            correct_k = correct[:k].view(-1).float().sum(0)
            val = correct_k.mul_(100.0 / batch_size)
            self.topAcc[i].update(val, output.size(0))

    def register(self, trainer):
        super().register(trainer)
        if max(self.topk) >= len(trainer.classes):
            raise ValueError("k should be less than number of classes!")

    def logger(self, e=None, train=True):
        super().logger()
        log = ''
        if train:
            for i, k in enumerate(self.topk):
                log += 'Top {} Acc:{Acc.val:.2f}%\t'.format(
                    k, Acc=self.topAcc[i])
        else:
            for i, k in enumerate(self.topk):
                log += 'Top {} Acc:{Acc.avg:.2f}%\t'.format(
                    k, Acc=self.topAcc[i])

        print(log)

    def getState(self):
        State = {}
        for i, k in enumerate(self.topk):
            State['Top %d' % k] = self.topAcc[i].avg
        return State

    def reset(self):
        for k in self.topAcc:
            k.reset()

class ClassAccuracy(DataMonitor):
    name = 'Classes Accuracy'

    def __init__(self):
        super(ClassAccuracy, self).__init__()

    def register(self, trainer):
        super().register(trainer)
        self.classes = trainer.classes
        self.classesAcc = [AverageMeter() for c in self.classes]

    def __handle__(self, output, target, loss):
        classes_total = torch.zeros(len(self.classes)).to(torch.int)
        classes_count = torch.zeros(len(self.classes)).to(torch.int)

        target_idx = target.view(-1).to(torch.int)
        for idx in target_idx:
            classes_total[idx] += 1

        _, pred = output.topk(1, 1, True, True)
        pred = pred.t()
        correct = pred.eq(target.view(1, -1).expand_as(pred))
        classes_idx = pred.masked_select(correct).to(torch.int)

        for idx in classes_idx:
            classes_count[idx] += 1

        total_np = classes_total.numpy()
        those_are_zero_idx = total_np == 0
        total_np[those_are_zero_idx] = 1
        classes_acc = classes_count.mul_(100).div(classes_total)
        total_np[those_are_zero_idx] = 0

        for i, _ in enumerate(self.classes):
            self.classesAcc[i].update(
                classes_acc[i].item(), classes_total[i].item())

    def logger(self, e=None, train=True):
        super().logger()
        if train:
            for i, c in enumerate(self.classes):
                print(
                    '{} Acc:{Acc.val:.2f}%\t'.format(
                        c, Acc=self.classesAcc[i]))
        else:
            for i, c in enumerate(self.classes):
                print('{} Acc:{Acc.avg:.2f}%[{:d}/{Acc.total:d}]\t'.format(
                    c, int(self.classesAcc[i].count / 100), Acc=self.classesAcc[i]))

    def getState(self):
        State = {}
        for i, c in enumerate(self.classes):
            State['%s' % c] = self.classesAcc[i].avg
        return State

    def reset(self):
        for c in self.classesAcc:
            c.reset()

class IterationSummaryMonitor(EpochMonitor):

    def call(self, train_results, validation_results, e):
        for p in self.trainer.plugins['iteration']:
            self.trainer.writer.add_scalars(
                '%s/Training' % p.name, train_results[p.name], e)
            self.trainer.writer.add_scalars(
                '%s/Validation' % p.name,
                validation_results[
                    p.name],
                e)

class DistributionOfBNMonitor(EpochMonitor):

    def call(self, train_results, validation_results, e):
        bn_idx = 0
        for m in self.trainer.model.modules():
            if isinstance(m, nn.BatchNorm1d) or isinstance(m, nn.BatchNorm2d):
                bn_idx += 1
                self.trainer.writer.add_histogram(
                    'BatchNorm Layer%d Gamma' %
                    bn_idx, m.weight.clone().cpu().data.numpy(), e)
                self.trainer.writer.add_histogram(
                    'BatchNorm Layer%d Beta' %
                    bn_idx, m.bias.clone().cpu().data.numpy(), e)

class DownSampleMonitor(EpochMonitor):

    def call(self, train_results, validation_results, e):
        self.trainer.train_loader.dataset.reset()


from django.shortcuts import render,get_object_or_404,redirect
from django.http import HttpResponse
from blog.models import Post
from django.contrib.auth import get_user_model
from django.views.generic import View,DetailView

from taggit.models import Tag
from taggit.managers import TaggableManager
from .forms import BlogCreationForm
from django.contrib.auth.mixins import LoginRequiredMixin

User = get_user_model()

def home(request):
    context = {
        "posts" : Post.objects.all(),
        "tags" : Tag.objects.all().distinct(),
    }
    return render(request,'blog/post_list.html',context)

class BlogDetailView(DetailView):
    queryset = Post.objects.all()

    def get_object(self):
        pk = self.kwargs.get("pk")
        return Post.objects.get(id=pk)

class TagSearchView(View):

    def get(self,request,tag,*args,**kwargs):

        tags = get_object_or_404(Tag,slug = tag)

        obj = Post.objects.filter(tags__in=[tags])

        return render(request,'blog/post_list.html',{"posts":obj})

class BlogCreateView(LoginRequiredMixin,View):
    login_url = '/user/login/'

    def get(self,request):
        form = BlogCreationForm()
        return render(request,'blog/writearticle.html',{'form':form})

    def post(self,request):

        # print(request.POST['editor1'])

        # title = request.POST['title']
        # content = request.POST['editor1']
        # tags = request.POST['tag']

        # post = Post.objects.create(author=request.user , title=title,content=content)
        # for t in tags.split(","):

        #     tag = Tag.objects.create(name=t)
        #     post.tags.add(tag)
        # post.save()

        # return redirect('/blog')

        form  = BlogCreationForm(request.POST)
        print(form.errors.as_data())
        if form.is_valid():
            print("form saving")
            instance = form.save(commit=False)
            instance.author = request.user
            instance.save()
            form.save_m2m()

        return redirect('/blog')


from django.db.models import Q
from django.shortcuts import render
from typing import NamedTuple
from song.models import Song

__all__ = (
    'song_search',
)

def song_search(request):

    # Song과 연결된 Artist의 name에 keyword가 포함되는 경우
    # Song과 연결된 Album의 title에 keyword가 포함되는 경우
    # Song의 title에 keyword가 포함되는 경우
    #   를 모두 포함(or -> Q object)하는 쿼리셋을 'songs'에 할당

    # songs_from_artists
    # songs_from_albums
    # songs_from_title
    #  위 세 변수에 더 위의 조건 3개에 부합하는 쿼리셋을 각각 전달
    #  세 변수를 이용해 검색 결과를 3단으로 분리해서 출력
    #  -> 아티스트로 검색한 노래 결과, 앨범으로 검색한 노래 결과, 제목으로 검색한 노래 결과
    context = {
        'song_infos': [],
    }
    keyword = request.GET.get('keyword')

    # SongInfo = namedtuple('SongInfo', ['type', 'q'])

    class SongInfo(NamedTuple):
        type: str
        q: Q

    if keyword:
        song_infos = (
            SongInfo(
                type='아티스트명',
                q=Q(album__artists__name__contains=keyword)),
            SongInfo(
                type='앨범명',
                q=Q(album__title__contains=keyword)),
            SongInfo(
                type='노래제목',
                q=Q(title__contains=keyword)),
        )
        for type, q in song_infos:
            context['song_infos'].append({
                'type': type,
                'songs': Song.objects.filter(q),
            })

    return render(request, 'song/song_search.html', context)


#!/usr/bin/env python
# -*- coding: utf-8 -*-
import requests,re

response = requests.get('http://httpbin.org/get')

import json
res1 = json.loads(response.text)
res2 = response.json()   #直接获取json数据

print('res1==',res1)
print('res2==',res2)
print(res1 == res2)


#!/usr/bin/env python

'''
Based on:
=======
https://github.com/vmayoral/basic_reinforcement_learning
https://gist.github.com/wingedsheep/4199594b02138dd427c22a540d6d6b8d
'''
import json
import os
import time
from distutils.dir_util import copy_tree

import gym
import gym_gazebo
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
from gym import logger, wrappers
from keras import backend as K

from settings import my_board
from dqn import DeepQ

# To equal the inputs, we set the channels first and the image next.
K.set_image_data_format('channels_first')

def detect_monitor_files(training_dir):
    return [os.path.join(training_dir, f) for f in os.listdir(training_dir) if f.startswith('openaigym')]

def clear_monitor_files(training_dir):
    files = detect_monitor_files(training_dir)
    if len(files) == 0:
        return
    for file in files:
        os.unlink(file)

def plot_durations():
    plt.figure(1)
    plt.clf()

    plt.title('Training...')
    plt.xlabel('Episode')
    plt.ylabel('Duration')
    plt.plot(episode_durations)

    # Take 100 episode averages and plot them too
    if step % 10 == 0:
        mean_episode = np.mean(episode_durations)
        plt.plot(mean_episode)

    plt.pause(0.001)  # pause a bit so that plots are updated

episode_durations = []

####################################################################################################################
# MAIN PROGRAM
####################################################################################################################
if __name__ == '__main__':

    #REMEMBER!: turtlebot_cnn_setup.bash must be executed.
    env = gym.make('GazeboF1CameraEnvDQN-v0')
    outdir = './logs/f1_gym_experiments/'

    current_file_path = os.path.abspath(os.path.dirname(__file__))

    print("=====================\nENV CREATED\n=====================")

    continue_execution = False
    # Fill this if continue_execution=True
    weights_path = os.path.join(current_file_path, 'logs/f1_dqn_ep27000.h5')
    monitor_path = os.path.join(current_file_path, 'logs/f1_dqn_ep27000')
    params_json  = os.path.join(current_file_path, 'logs/f1_dqn_ep27000.json')

    img_rows, img_cols, img_channels = env.img_rows, env.img_cols, env.img_channels

    epochs = 10000000
    steps = 1000000

    if not continue_execution:
        minibatch_size = 32
        learningRate = 1e-3  # 1e6
        discountFactor = 0.95
        network_outputs = 5
        memorySize = 100000
        learnStart = 10000  # timesteps to observe before training (default: 10.000)
        EXPLORE = memorySize  # frames over which to anneal epsilon
        INITIAL_EPSILON = 1  # starting value of epsilon
        FINAL_EPSILON = 0.01  # final value of epsilon
        explorationRate = INITIAL_EPSILON
        current_epoch = 0
        stepCounter = 0
        loadsim_seconds = 0

        deepQ = DeepQ(network_outputs, memorySize, discountFactor, learningRate, learnStart, img_rows, img_cols, img_channels)
        deepQ.initNetworks()
        env = gym.wrappers.Monitor(env, outdir, force=True)
    else:
        #Load weights, monitor info and parameter info.
        with open(params_json) as outfile:
            d = json.load(outfile)
            explorationRate = d.get('explorationRate')
            minibatch_size = d.get('minibatch_size')
            learnStart = d.get('learnStart')
            learningRate = d.get('learningRate')
            discountFactor = d.get('discountFactor')
            memorySize = d.get('memorySize')
            network_outputs = d.get('network_outputs')
            current_epoch = d.get('current_epoch')
            stepCounter = d.get('stepCounter')
            EXPLORE = d.get('EXPLORE')
            INITIAL_EPSILON = d.get('INITIAL_EPSILON')
            FINAL_EPSILON = d.get('FINAL_EPSILON')
            loadsim_seconds = d.get('loadsim_seconds')

        deepQ = DeepQ(network_outputs, memorySize, discountFactor, learningRate, learnStart, img_rows, img_cols, img_channels)
        deepQ.initNetworks()
        deepQ.loadWeights(weights_path)

        clear_monitor_files(outdir)
        copy_tree(monitor_path,outdir)
        env = gym.wrappers.Monitor(env, outdir, resume=True)

    last100Rewards = [0] * 100
    last100RewardsIndex = 0
    last100Filled = False

    start_time = time.time()

    # Start iterating from 'current epoch'.
    for epoch in xrange(current_epoch+1, epochs+1, 1):

        observation, pos = env.reset()

        cumulated_reward = 0

        # Number of timesteps
        for step in xrange(steps):

            # make the model.predict
            qValues = deepQ.getQValues(observation)
            action = deepQ.selectAction(qValues, explorationRate)
            newObservation, reward, done, _ = env.step(action)
            deepQ.addMemory(observation, action, reward, newObservation, done)

            # print("Step: {}".format(t))
            # print("Action: {}".format(action))
            # print("Reward: {}".format(reward))

            observation = newObservation

            # We reduced the epsilon gradually
            if explorationRate > FINAL_EPSILON and stepCounter > learnStart:
                explorationRate -= (INITIAL_EPSILON - FINAL_EPSILON) / EXPLORE

            if stepCounter == learnStart:
                print("Starting learning")

            if stepCounter >= learnStart:
                deepQ.learnOnMiniBatch(minibatch_size, False)

            if (step == steps-1):
                print("reached the end")
                done = True

            env._flush(force=True)
            cumulated_reward += reward

            if done:
                episode_durations.append(step)
                if my_board:
                    plot_durations()

                last100Rewards[last100RewardsIndex] = cumulated_reward
                last100RewardsIndex += 1
                if last100RewardsIndex >= 100:
                    last100Filled = True
                    last100RewardsIndex = 0
                m, s = divmod(int(time.time() - start_time + loadsim_seconds), 60)
                h, m = divmod(m, 60)
                if not last100Filled:
                    print("EP: {} - Steps: {} - Pos: {} - CReward: {} - Eps: {} - Time: {}:{}:{} ".format(epoch, step+1, pos, round(cumulated_reward, 2), round(explorationRate, 2), h, m, s))
                else:
                    print("EP: {} - Steps: {} - Pos: {} - last100 C_Rewards: {} - CReward: {} - Eps={} - Time: {}:{}:{}".format(epoch, step+1, pos, sum(last100Rewards)/len(last100Rewards), round(cumulated_reward, 2), round(explorationRate, 2), h, m, s))

                    # SAVE SIMULATION DATA
                    if (epoch)%1000==0:
                        # Save model weights and monitoring data every 100 epochs.
                        deepQ.saveModel('./logs/f1_dqn_ep'+str(epoch)+'.h5')
                        env._flush()
                        copy_tree(outdir,'./logs/f1_dqn_ep'+str(epoch))
                        # Save simulation parameters.
                        parameter_keys = ['explorationRate','minibatch_size','learnStart','learningRate','discountFactor','memorySize','network_outputs','current_epoch','stepCounter','EXPLORE','INITIAL_EPSILON','FINAL_EPSILON','loadsim_seconds']
                        parameter_values = [explorationRate, minibatch_size, learnStart, learningRate, discountFactor, memorySize, network_outputs, epoch, stepCounter, EXPLORE, INITIAL_EPSILON, FINAL_EPSILON,s]
                        parameter_dictionary = dict(zip(parameter_keys, parameter_values))
                        with open('./logs/f1_dqn_ep'+str(epoch)+'.json', 'w') as outfile:
                            json.dump(parameter_dictionary, outfile)

                break

            stepCounter += 1
            # if stepCounter % 250 == 0:
            #     print("Frames = " + str(stepCounter))

    env.close()


import socket
import json
import uuid
import asyncio

class JsonProtocol(object):
    def __init__(self, version, method, *params):
        self.version = version
        self.method  = method
        self.params  = list(params)
        self.id      = str(uuid.uuid4())

    def __repr__(self):
        return json.dumps(
            {
                "version"   : self.version,
                "method"    : self.method,
                "params"    : self.params,
                "id"        : self.id}
        )

    @staticmethod
    def BuildMessage(version, method, *params):
        return str(JsonProtocol(list(params), version, method))

class RpcTcpClient(object):
    def __init__(self, address):
        self.address      = address
        self.socket       = None
        self.writer       = None
        self.reader       = None
        self.__connected  = False

    def connect(self):
        if not self.__connected:
            self.socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
            self.socket.connect(self.address)
            self.__connected = True

    def disconnect(self):
        if self.__connected and self.socket:
            self.socket.close()
            self.__connected = False

    async def async_connect(self):
        if not self.__connected:
            self.__connected = True
            self.reader, self.writer = await asyncio.open_unix_connection(self.address)

    async def async_disconnect(self):
        if self.__connected and self.writer:
            self.writer.close()
            # This should be call in python version > 3.7.4
            # await self.writer.wait_close()
            self.__connected = False

    def send(self, message):
        if not self.__connected:
            raise ConnectionError("Client is not connected to any TCP server.")
        self.socket.sendall(message.encode())
        data = self.socket.recv(2048)
        return json.loads(data.decode())

    async def async_send(self, message):
        if not self.__connected or not self.writer or not self.reader:
            raise ConnectionError("Client is not connected to any TCP server.")
        self.writer.write(message.encode())
        data = await self.reader.read(2048)
        return json.loads(data.decode())

    def __enter__(self):
        self.connect()
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.disconnect()

    def __await__(self):
        yield

    async def __aenter__(self):
        await self.async_connect()
        return self

    async def __aexit__(self, exc_type, exc_val, exc_tb):
        await self.async_disconnect()

if __name__ == "__main__":
    bunkr_address = "/tmp/bunkr_daemon.sock"
    create = str(JsonProtocol("1.0", "CommandProxy.HandleCommand", {"Command": "new-text-secret", "Args" : ["foo_test", "foo content"]}))
    access = str(JsonProtocol("1.0", "CommandProxy.HandleCommand", {"Command": "access", "Args" : ["foo_test"]}))
    delete = str(JsonProtocol("1.0", "CommandProxy.HandleCommand", {"Command": "delete", "Args" : ["foo_test"]}))

    with RpcTcpClient(bunkr_address) as client:
        print(client.send(create))

    async def test_send_message():
        async with RpcTcpClient(bunkr_address) as client:
            for c in (access, delete):
                data = await client.async_send(c)
                print(data)

    asyncio.run(test_send_message())


from typing import Union, List

from spotipy.client.base import SpotifyBase
from spotipy.serialise import ModelList
from spotipy.convert import to_uri
from spotipy.model import (
    CurrentlyPlayingContext,
    CurrentlyPlaying,
    PlayHistoryPaging,
    RepeatState,
    Device
)

class SpotifyPlayer(SpotifyBase):
    def playback(
            self,
            market: str = None
    ) -> CurrentlyPlayingContext:
        """
        Get information about user's current playback.

        Requires the user-read-playback-state or
        the user-read-currently-playing scope.

        Parameters
        ----------
        market
            an ISO 3166-1 alpha-2 country code or 'from_token'

        Returns
        -------
        CurrentlyPlayingContext
            information about current playback
        """
        json = self._get('me/player', market=market)
        if json is not None:
            return CurrentlyPlayingContext(**json)

    def playback_currently_playing(
            self,
            market: str = None
    ) -> CurrentlyPlaying:
        """
        Get user's currently playing track.

        Requires the user-read-playback-state scope.

        Parameters
        ----------
        market
            an ISO 3166-1 alpha-2 country code or 'from_token'

        Returns
        -------
        CurrentlyPlaying
            information about the current track playing
        """
        json = self._get('me/player/currently-playing', market=market)
        if json is not None:
            return CurrentlyPlaying(**json)

    def playback_recently_played(
            self,
            limit: int = 20,
            after: int = None,
            before: int = None
    ) -> PlayHistoryPaging:
        """
        Get tracks from the current user's recently played tracks.

        Only after or before should be specified at one time.
        Requires the user-read-recently-played scope.

        Parameters
        ----------
        limit
            the number of items to return (1..50)
        after
            a unix timestamp in milliseconds, must not be specified with 'before'
        before
            a unix timestamp in milliseconds, must not be specified with 'after'

        Returns
        -------
        PlayHistoryPaging
            cursor-based paging containing play history objects
        """
        json = self._get(
            'me/player/recently-played',
            limit=limit,
            after=after,
            before=before
        )
        return PlayHistoryPaging(**json)

    def playback_devices(self) -> List[Device]:
        """
        Get a user's available devices.

        Requires the user-read-playback-state scope.

        Returns
        -------
        ModelList
            list of device objects
        """
        json = self._get('me/player/devices')
        return ModelList(Device(**d) for d in json['devices'])

    def playback_transfer(self, device_id: str, force_play: bool = False) -> None:
        """
        Transfer playback to another device.

        Requires the user-modify-playback-state scope.
        Note that the API accepts a list of device ids,
        but only actually supports one.

        Parameters
        ----------
        device_id
            device to transfer playback to
        force_play
            true: play after transfer, false: keep current state
        """
        data = {
            'device_ids': [device_id],
            'play': force_play
        }
        self._put('me/player', payload=data)

    def playback_start(
            self,
            context_uri: str = None,
            track_ids: list = None,
            offset: Union[int, str] = None,
            position_ms: int = None,
            device_id: str = None
    ) -> None:
        """
        Start or resume user's playback.

        Requires the user-modify-playback-state scope.

        Use a `context_uri` to start playback of an album, artist, or playlist.
        Use `track_ids` to start playback of one or more tracks.
        Provide `offset` as index or track ID to start playback at some offset.
        Only available when context_uri is an album or playlist,
        or when track_ids is used.

        Parameters
        ----------
        context_uri
            context uri to play, must not be specified with track_ids
        track_ids
            track IDs, must not be specified with context_uri
        offset
            offset into context by index or track ID
        position_ms
            position of track
        device_id
            device to start playback on
        """
        if isinstance(offset, int):
            offset_dict = {'position': offset}
        elif isinstance(offset, str):
            offset_dict = {'uri': to_uri('track', offset)}
        else:
            offset_dict = None

        if track_ids is not None:
            track_uris = [to_uri('track', t) for t in track_ids]
        else:
            track_uris = None

        payload = {
            'context_uri': context_uri,
            'uris': track_uris,
            'offset': offset_dict,
            'position_ms': position_ms,
        }
        payload = {k: v for k, v in payload.items() if v is not None}
        self._put('me/player/play', payload=payload, device_id=device_id)

    def playback_pause(self, device_id: str = None) -> None:
        """
        Pause a user's playback.

        Requires the user-modify-playback-state scope.

        Parameters
        ----------
        device_id
            device to pause playback on
        """
        self._put('me/player/pause', device_id=device_id)

    def playback_next(self, device_id: str = None) -> None:
        """
        Skip user's playback to next track.

        Requires the user-modify-playback-state scope.

        Parameters
        ----------
        device_id
            device to skip track on
        """
        self._post('me/player/next', device_id=device_id)

    def playback_previous(self, device_id: str = None) -> None:
        """
        Skip user's playback to previous track.

        Requires the user-modify-playback-state scope.

        Parameters
        ----------
        device_id
            device to skip track on
        """
        self._post('me/player/previous', device_id=device_id)

    def playback_seek(self, position_ms: int, device_id: str = None) -> None:
        """
        Seek to position in current playing track.

        Requires the user-modify-playback-state scope.

        Parameters
        ----------
        position_ms
            position on track
        device_id
            device to seek on
        """
        self._put(
            'me/player/seek',
            position_ms=position_ms,
            device_id=device_id
        )

    def playback_repeat(
            self,
            state: Union[str, RepeatState],
            device_id: str = None
    ) -> None:
        """
        Set repeat mode for playback.

        Requires the user-modify-playback-state scope.

        Parameters
        ----------
        state
            `track`, `context`, or `off`
        device_id
            device to set repeat on
        """
        self._put('me/player/repeat', state=str(state), device_id=device_id)

    def playback_shuffle(self, state: bool, device_id: str = None) -> None:
        """
        Toggle shuffle for user's playback.

        Requires the user-modify-playback-state scope.

        Parameters
        ----------
        state
            shuffle state
        device_id
            device to toggle shuffle on
        """
        state = 'true' if state else 'false'
        self._put('me/player/shuffle', state=state, device_id=device_id)

    def playback_volume(self, volume_percent: int, device_id: str = None) -> None:
        """
        Set volume for user's playback.

        Requires the user-modify-playback-state scope.

        Parameters
        ----------
        volume_percent
            volume to set (0..100)
        device_id
            device to set volume on
        """
        self._put(
            'me/player/volume',
            volume_percent=volume_percent,
            device_id=device_id
        )


import gzip

from collections import OrderedDict
from operator import or_
from struct import pack, unpack
from functools import reduce

class TabixIndex(object):
    def __init__(self, filename):
        with gzip.open(filename, 'rb') as fileobj:
            magic, n_ref, self.format, self.col_seq, self.col_beg, self.col_end, self.meta, self.skip, l_nm =\
                unpack('<4siiiiiiii', fileobj.read(36))
            names = unpack('<{}s'.format(l_nm), fileobj.read(l_nm))[0].strip('\x00').split('\x00')
            self.bins = OrderedDict()
            self.ioffs = OrderedDict()
            for name in names:
                n_bins = unpack('<i', fileobj.read(4))[0]
                self.bins[name] = OrderedDict()
                for bin in range(n_bins):
                    bin, n_chunk = unpack('<Ii', fileobj.read(8))
                    chunks = [unpack('<QQ', fileobj.read(16)) for chunk in range(n_chunk)]
                    self.bins[name][bin] = set(chunks)
                n_intv = unpack('<i', fileobj.read(4))[0]
                self.ioffs[name] = unpack('<' + n_intv * 'Q', fileobj.read(8 * n_intv))

    def fetch(self, chromosome, start, stop):
        bins = self.get_overlapping_bins(start, stop)
        chunks = reduce(or_, (self.bins[chromosome][bin] for bin in bins))
        print(chunks)

    def get_bin(self, start, stop):
        stop -= 1
        for rshift, lshift in [(14, 15), (17, 12), (20, 9), (23, 6), (26, 3)]:
            if start >> rshift == stop >> rshift:
                return ((1 << lshift) - 1) / 7 + (start >> rshift)
        return 0

    def get_overlapping_bins(self, start, stop):
        stop -= 1
        res = [0]
        for c, rshift in [(1, 26), (9, 23), (73, 20), (585, 17), (4681, 14)]:
            res.extend(range(c + (start >> rshift), c + (stop >> rshift)))
        return res

    def write_to_file(self, filename):
        concatenated_names = '\x00'.join(self.bins) + '\x00'

        fileobj = gzip.open(filename, 'wb')
        fileobj.write(pack('>4siiiiiiii{}s'.format(len(concatenated_names)), 'TBI\x00', len(self.bins), self.format,
                           self.col_seq, self.col_beg, self.col_end, self.meta, self.skip, len(concatenated_names),
                           concatenated_names))
        for name in self.bins:
            fileobj.write(pack('<i', len(self.bins[name])))
            for bin in self.bins:
                fileobj.write(pack('<Ii', bin, len(self.bins[name][bin])))
                for cnk_beg, cnk_end in self.bins[name][bin]:
                    fileobj.write(pack('<QQ', cnk_beg, cnk_end))
            fileobj.write(pack('<i', len(self.ioffs[name])))
        fileobj.close()


from typing import Dict

from .constants import SUFFIX_TYPE

from wai.common.adams.imaging.locateobjects import LocatedObjects

def fix_labels(objects: LocatedObjects, mappings: Dict[str, str]):
    """
    Fixes the labels in the parsed objects, using the specified mappings (old: new).

    :param objects:     The parsed objects.
    :param mappings:    The label mappings (old: new).
    """
    # Process each object
    for obj in objects:
        # If the object doesn't have a label, skip it
        if SUFFIX_TYPE not in obj.metadata:
            continue

        # Get the object's current label
        label: str = obj.metadata[SUFFIX_TYPE]

        # If there is a mapping for this label, change it
        if label in mappings:
            obj.metadata[SUFFIX_TYPE] = mappings[label]


import os
import shutil

from cogs.util.bot import TWOWBot

def main():
    bot = TWOWBot()

    if not os.path.exists('config.yml'):
        shutil.copy('config.example.yml', 'config.yml')

    bot.run()

if __name__ == '__main__':
    main()


# Copyright 2018 AT&T Corporation.
# All Rights Reserved.
#
#    Licensed under the Apache License, Version 2.0 (the "License"); you may
#    not use this file except in compliance with the License. You may obtain
#    a copy of the License at
#
#         http://www.apache.org/licenses/LICENSE-2.0
#
#    Unless required by applicable law or agreed to in writing, software
#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
#    License for the specific language governing permissions and limitations
#    under the License.

from tempest.lib.common.utils import data_utils
from tempest.lib.common.utils import test_utils
from tempest.lib import decorators

from patrole_tempest_plugin import rbac_rule_validation
from patrole_tempest_plugin.tests.api.network import rbac_base as base

class FlavorsExtRbacTest(base.BaseNetworkExtRbacTest):

    @classmethod
    def resource_setup(cls):
        super(FlavorsExtRbacTest, cls).resource_setup()
        providers = cls.ntp_client.list_service_providers()
        if not providers["service_providers"]:
            raise cls.skipException("No service_providers available.")
        cls.service_type = providers["service_providers"][0]["service_type"]

    @decorators.idempotent_id('2632a61b-831e-4da5-82c8-a5f7d448589b')
    @rbac_rule_validation.action(service="neutron",
                                 rules=["create_flavor"])
    def test_create_flavor(self):
        """Create flavor.

        RBAC test for the neutron "create_flavor" policy
        """
        with self.override_role():
            flavor = self.ntp_client.create_flavor(
                service_type=self.service_type)

        self.addCleanup(
            test_utils.call_and_ignore_notfound_exc,
            self.ntp_client.delete_flavor, flavor["flavor"]["id"])

    @decorators.idempotent_id('9c53164c-117d-4b44-a5cb-96f08386513f')
    @rbac_rule_validation.action(service="neutron",
                                 rules=["get_flavor",
                                        "update_flavor"],
                                 expected_error_codes=[404, 403])
    def test_update_flavor(self):
        """Update flavor.

        RBAC test for the neutron "update_flavor" policy
        """
        flavor = self.ntp_client.create_flavor(service_type=self.service_type)
        self.addCleanup(
            test_utils.call_and_ignore_notfound_exc,
            self.ntp_client.delete_flavor, flavor["flavor"]["id"])

        name = data_utils.rand_name(self.__class__.__name__ + '-Flavor')
        with self.override_role():
            self.ntp_client.update_flavor(flavor["flavor"]["id"], name=name)

    @decorators.idempotent_id('1de15f9e-5080-4259-ab41-e230bb312de8')
    @rbac_rule_validation.action(service="neutron",
                                 rules=["get_flavor",
                                        "delete_flavor"],
                                 expected_error_codes=[404, 403])
    def test_delete_flavor(self):
        """Delete flavor.

        RBAC test for the neutron "delete_flavor" policy
        """
        flavor = self.ntp_client.create_flavor(service_type=self.service_type)
        self.addCleanup(
            test_utils.call_and_ignore_notfound_exc,
            self.ntp_client.delete_flavor, flavor["flavor"]["id"])

        with self.override_role():
            self.ntp_client.delete_flavor(flavor["flavor"]["id"])

    @decorators.idempotent_id('c2baf35f-e6c1-4833-9114-aadd9b1f6aaa')
    @rbac_rule_validation.action(service="neutron",
                                 rules=["get_flavor"],
                                 expected_error_codes=[404])
    def test_show_flavor(self):
        """Show flavor.

        RBAC test for the neutron "get_flavor" policy
        """
        flavor = self.ntp_client.create_flavor(service_type=self.service_type)
        self.addCleanup(
            test_utils.call_and_ignore_notfound_exc,
            self.ntp_client.delete_flavor, flavor["flavor"]["id"])

        with self.override_role():
            self.ntp_client.show_flavor(flavor["flavor"]["id"])

    @decorators.idempotent_id('ab10bd5d-987e-4255-966f-947670ffd0fa')
    @rbac_rule_validation.action(service="neutron",
                                 rules=["get_flavor"])
    def test_list_flavors(self):
        """List flavors.

        RBAC test for the neutron "get_flavor" policy for "list_flavors" action
        """
        flavor = self.ntp_client.create_flavor(service_type=self.service_type)
        self.addCleanup(
            test_utils.call_and_ignore_notfound_exc,
            self.ntp_client.delete_flavor, flavor["flavor"]["id"])

        with self.override_role_and_validate_list(
            admin_resource_id=flavor["flavor"]["id"]
        ) as ctx:
            ctx.resources = self.ntp_client.list_flavors()['flavors']


#Упражнение 2.1
#Химические элементы

value = input("Атомный номер: ")

if value:

    num = int(value)

    if num == 2:
        print("Li - литий")

    elif num ==25:
        print("Mn - марганец")

    elif num == 80:
        print("Hg - ртуть")

    elif num == 17:
        print("Cl - хлор")

    else:
        print("Такого элемента я не знаю.")
else:
    print("Значение не введено!")


def linear_sort(arr):
    i = j = 0
    for i in range(i,len(arr)):
        for j in range(i+1, len(arr)):
            if arr[i] > arr[j]:
                arr[j], arr[i] = arr[i], arr[j]
    return arr

arr = list(range(99999999))
import random
random.shuffle(arr)
print("done")
linear_sort(arr)
print("done")


import requests
import os

class KnowledgeBase:

    TRANSLATION_CHAR_TABLE = {
        '\"': None
    }

    @classmethod
    def insee_rules(cls, builder):
        url = "http://rdf.insee.fr/sparql"
        headers = {"Accept": "application/json"}
        query = """
        PREFIX skos:<http://www.w3.org/2004/02/skos/core#>
        PREFIX xkos:<http://rdf-vocabulary.ddialliance.org/xkos#>

        SELECT ?concept ?libelle ?acronym ?definitionValue ?shortDefinitionValue WHERE {
            ?concept skos:inScheme ?conceptScheme;
                     skos:prefLabel ?libelle .
            FILTER(regex(str(?conceptScheme),'/concepts/definitions/scheme'))
            FILTER(lang(?libelle) = 'fr')
            OPTIONAL {
                ?concept skos:altLabel ?acronym .
                FILTER(lang(?acronym) = 'fr')
            }
            OPTIONAL {
                ?concept skos:definition ?definition ;
                         skos:scopeNote ?shortDefinition.
                ?definition xkos:plainText ?definitionValue .
                ?shortDefinition xkos:plainText ?shortDefinitionValue .
                FILTER(lang(?definitionValue) = 'fr')
                FILTER(lang(?shortDefinitionValue ) = 'fr')
            }
        }
        ORDER BY ?concept
        """
        params = {"query": query}
        nes = []
        definitions = {
            "short": {},
            "standard": {}
        }
        entities = {}
        proxies = {}

        # Yep, dirty...
        if 'HTTP_PROXY' in os.environ:
            proxies = {
                'http': os.environ['HTTP_PROXY']
            }

        response = requests.get(url=url, headers=headers, params=params, proxies=proxies).json()
        for bind in response["results"]["bindings"]:
            entity = bind["libelle"]["value"].lower().translate(cls.TRANSLATION_CHAR_TABLE)
            id = bind["concept"]["value"].split('/')[-1]
            while entity[len(entity) - 1] == ' ' or entity[len(entity) - 1] == '\xa0':
                entity = entity[0:len(entity) - 1]
            ne = {
                'level': 'permis',
                'label': 'STAT-CPT',
                'entity': entity,
                'id': id
            }
            if "shortDefinitionValue" in bind:
                definitions["short"][id] = bind["shortDefinitionValue"]["value"]
            if "definitionValue" in bind:
                definitions["standard"][id] = bind["definitionValue"]["value"]
            entities[id] = entity
            nes.append(ne)
            if "acronym" in bind:
                acronym = bind["acronym"]["value"].translate(cls.TRANSLATION_CHAR_TABLE)
                ne = {
                    'level': 'strict',
                    'label': 'STAT-CPT',
                    'entity': acronym,
                    'id': id
                }
                nes.append(ne)
        return builder(nes), definitions, entities


survey_launch = {
    "type": "object",
    "properties": {
        "name": {"type": "string"},
        "institution_id": {"type": "string"},
        "start_datetime": {
            "type": "string",
            "format": "date-time"
        },
        "end_datetime": {
            "type": "string",
            "format": "date-time"
        },
        "teacher": {
            "type": "object",
            "properties": {
                "first_name": {"type": "string"},
                "last_name": {"type": "string"},
                "email": {
                    "type": "string",
                    "format": "email"
                },
            },
            "required":  ["first_name", "last_name", "email"]
        },
        "survey_url": {"type": "string"},
        "teams": {
            "type": "array",
            "minItems": 1,
            "items": {
                "type": "object",
                "properties":  {
                    "name": {"type": "string"},
                    "members": {
                        "type": "array",
                        "minItems": 1,
                        "items": {
                            "type": "object",
                            "properties": {
                                "first_name": {"type": "string"},
                                "last_name": {"type": "string"},
                                "student_id": {"type": "string"},
                                "email": {
                                    "type": "string",
                                    "format": "email"
                                },
                            },
                            "required":  ["first_name", "last_name", "student_id"]
                        }
                    }
                },
                "required": ["name", "members"]
            }
        }
    },
    "required": ["institution_id", "start_datetime", "survey_url", "end_datetime", "teacher", "name", "teams"]
}

assessment_submission = {
    "type": "object",
    "properties": {
        "peer_assessments": {
            "type": "array",
            "minItems": 1,
            "items": {
                "type": "object",
                "properties": {
                    "assessee_id": {"type": ["string", "integer"]},
                    "recommendation": {"$ref": "#/definitions/givenScore"},
                    "initiativeness": {"$ref": "#/definitions/givenScore"},
                    "attendance": {"$ref": "#/definitions/givenScore"},
                    "contribution": {"$ref": "#/definitions/givenScore"},
                    "professionalism": {"$ref": "#/definitions/givenScore"},
                    "ideas": {"$ref": "#/definitions/givenScore"},
                    "focus": {"$ref": "#/definitions/givenScore"},
                    "encouragement": {"$ref": "#/definitions/givenScore"},
                    "listening": {"$ref": "#/definitions/givenScore"},
                    "conflict_management": {"$ref": "#/definitions/givenScore"},
                    "chairmanship": {"$ref": "#/definitions/givenScore"},
                    "contribution_t": {"type": "string"},
                    "leadership_t": {"type": "string"},
                    "feedback_t": {"type": "string"}
                },
                "required": [
                    "assessee_id",
                    "recommendation",
                    "initiativeness",
                    "attendance",
                    "contribution",
                    "professionalism",
                    "ideas",
                    "focus",
                    "encouragement",
                    "listening",
                    "conflict_management",
                    "chairmanship",
                    "contribution_t",
                    "leadership_t",
                    "feedback_t"
                ]
            }
        },
        "teacher_advice": {"type": "string"}
    },
    "required": ["peer_assessments", "teacher_advice"],
    "definitions": {
        "givenScore": {
            "type": "integer",
            "minimum": 1,
            "maximum": 5
        }
    }
}

team_results = {
    "type": "object",
    "properties": {
        "results": {
            "type": "array",
            "minItems": 1,
            "items": {
                "type": "object",
                "properties": {
                    "team_name": {"type": "string"},
                    "score": {
                        "type": "number",
                        "minimum": 0,
                        "maximum": 1
                    }
                },
                "required": ["team_name", "score"]
            }
        }
    },
    "required": ["results"]
}


# John Asare
# Apr 27 2020 16:57

""" Complete the code to iterate through the keys and values of the car_prices dictionary,
printing out some information about each one."""

def car_listing(car_prices):
    #adding to test
    result = ""
    for car, price in car_prices.items():
        result += "{} costs {} dollars".format(car, price) + "\n"
    return result

print("Testing my Git skills to see if I still got it")

print(car_listing({"Kia Soul":19000, "Lamborghini Diablo":55000, "Ford Fiesta":13000, "Toyota Prius":24000}))


from application import db
from application.exc import AppBaseException
from application.model import GroupModel, GoalModel

class GroupService:

    def create(self, title, description, criteria):
        try:
            group = GroupModel(title, description)
            db.session.add(group)
            db.session.flush()
            goal = GoalModel(group.id, criteria, '2018-10-12', '2018-10-31')
            db.session.add(goal)
            db.session.commit()
            return group
        except Exception as e:
            db.session.rollback()
            raise e

    def enroll_user(self, group_id: int = 0, user_id: int = 0):
        group: GroupModel = GroupModel.get(group_id)
        if group.is_enrolled(user_id=user_id):
            raise AppBaseException('이미 그룹에 가입했어요.', 409)

        group.insert_user_into_group(user_id=user_id)
        goal = group.goal

        achievements = goal.create_achievements(user_id) if goal else []

        return group, goal, achievements

    def upsert_goal_with_group(self):
        pass

group_service = GroupService()


'''
python:数据类型
   int str float bool
   list[]、tuple()
          key      value
   dict{   ""   :   ""   }
         键    值    键值对
         取键来获取值
   回家:
   三层字典：第一层:几号线{，，，，，}input出入了一个地铁没有的线路 为错
           第二层:那个小区 input出入了一个地铁没有的线路为错
          打印 乘法表 99 1010：我输入的数字打印出来的乘法表
'''
#dict1={"小宝":"男"}
#print(dict1["小宝"])
# dict1={"01": {"011":"北京"},"02": {"012":"上海"}
#     ,"03": {"013":"天津"},"04": {"014":"香港"}
#     ,"05": {"015":"浙江"},"06":{"016":"河南"}}
# a=dict1["01"]["011"]
# print(a)
#
#
# name = input("请输入一个数字")
# if name == "01":
#     print(dict1["01"])
#     name = input("请输入一个数字")
#     if name == "011":
#         print(dict1["01"]["011"])
'''
list=[1,2,3,4,5,6,7,8,9]
#while True/范围:
    #       循环数数 (        5)
for i in range(len(list)): #range 数数  数出来的数字给了i 0 1 2 3 4 5
    p=list[i]
    print(p)
'''
for i in range(1,10):
    for j in range(1,i+1):
        print(j,'*',i,'=',j*i,end='')
    print()

n = int(input("请输入一个数字:"))
for i in range(1,n+1):
    for j in range(1,i+1):
        print(j,'*',i,'=',j*i,end='')
    print()

data = {'13号线':{
             '流星花园':
                   ['001','002','003'],
             '育荣教育园区':
                   ['0001','0002','0003'],

       },
      '1号线':{
          '兴隆花园':
              ['001','002','003'],
          '康家园小区':
          ['0001','0002','0003']
      },
       '昌平线':{
           '博雅德园':
               ['001','002','003'],
           '润泽家园':
           ['0001','0002','0003']
       }
}
def print_adress(choose):
    for i in choose:
        print(i)

for x in data.keys():
    print(x)
line = input("请选择地铁线路:")
if line in data:
    print_adress(data[line])
    adress = input("请选择小区:")
    if adress in data[line]:
        print_adress(data[line][adress])
        num = input("请输入门牌号:")
        if num in data[line][adress]:
            print(num)


"""
sync_seo_models.py

    Goes through all the registered models syncing the seo information.

"""
from optparse import make_option

from django.core.management.base import NoArgsCommand, CommandError
from django.core.urlresolvers import resolve, Resolver404
from django.contrib.contenttypes.models import ContentType

from painlessseo import settings
from painlessseo.utils import (
    delete_seo, update_seo, get_fallback_metadata
    )
from painlessseo.models import SeoRegisteredModel, SeoMetadata
import hashlib

DEFAULT_CREATE_LANG = []
DEFAULT_SEO_MODELS = settings.SEO_MODELS

class Command(NoArgsCommand):
    option_list = NoArgsCommand.option_list + (
        make_option('--langs', dest='update_langs', default=DEFAULT_CREATE_LANG,
                    help='Use this to indicate which languages must be generated'),
        make_option('--models', dest='seo_models', default=DEFAULT_SEO_MODELS,
                    help='Use this to indicate which apps must be updated'),
    )
    help = '''DEBUG only: Sync the SEO info in the database for registered models. '''
    requires_model_validation = True

    def handle_noargs(self, **options):
        seo_models = options.get('seo_models')
        if isinstance(seo_models, str):
            models = seo_models.split(' ')
            seo_models = []
            for model in models:
                seo_models.append(model.split('.'))

        update_langs = options.get('update_langs')
        if isinstance(update_langs, str):
            langs = update_langs.split(' ')
            update_langs = []
            for lang in langs:
                update_langs.append(lang)
        languages = settings.SEO_LANGUAGES
        base_lang = settings.DEFAULT_LANG_CODE

        # Update SeoPath
        metadatas = SeoMetadata.objects.filter(
            lang_code=base_lang, content_type__isnull=True)

        count = 0
        for metadata in list(metadatas):
            # Each metadata, sync it for the rest of the languages
            view_name = metadata.view_name
            if view_name:
                for lang_code, language in languages:
                    # If not exists a metadata on this lang for this view
                    if not SeoMetadata.objects.filter(
                            lang_code=lang_code, view_name=view_name).exists():
                        SeoMetadata.objects.create(
                            lang_code=lang_code, view_name=view_name,
                            description=metadata.description,
                            title=metadata.title,
                            has_parameters=metadata.has_parameters,
                            path=metadata.path,
                            )
                        count += 1

        print(str(count) + " metadatas created.")

        # Update SeoModels
        count = 0
        for app, model in seo_models:
            ctype = ContentType.objects.get(app_label=app.lower(), model=model.lower())
            seomodels = SeoRegisteredModel.objects.filter(
                lang_code=base_lang, content_type=ctype)
            if seomodels.exists():
                for seomodel in seomodels:
                    for lang_code, language in languages:
                        # If not exists a metadata on this lang for this model
                        if not SeoRegisteredModel.objects.filter(
                                lang_code=lang_code, content_type=ctype).exists():
                            SeoRegisteredModel.objects.create(
                                lang_code=lang_code, content_type=ctype,
                                title=seomodel.title,
                                description=seomodel.description)
                            count += 1

        print(str(count) + " seomodels created.")


import os
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import numpy as np

class DDQNDoubleOutput(nn.Module):
    def __init__(self, input_n, output_n, n_hidden=256, lr=1e-3, name='dqn', checkpoint_dir='models'):
        """
        :param lr:
        :param input_n:
        :param output_n: number of actions
        :param name: name of the network, for saving
        :param checkpoint_dir: directory in which to save the network
        """
        super(DDQNDoubleOutput, self).__init__()
        self.checkpoint_dir = checkpoint_dir
        self.checkpoint_file = os.path.join(self.checkpoint_dir, name)

        self.fc1 = nn.Linear(input_n, n_hidden)
        self.fc2 = nn.Linear(n_hidden, 32)
        self.fc3 = nn.Linear(32, output_n)
        self.pen_status = nn.Linear(32, 2)
        # self.optimizer = optim.RMSprop(self.parameters(), lr=lr)
        self.optimizer = optim.Adam(self.parameters(), lr=lr)
        self.loss = nn.MSELoss()
        #self.loss = nn.SmoothL1Loss()

        self.device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
        self.to(self.device)

    def forward(self, state):
        x = F.relu(self.fc1(state))
        x = F.relu(self.fc2(x))  # action values

        actions = self.fc3(x)  # action values
        pen_out = self.pen_status(x)
        #x = F.relu(self.fc1(state))
        #actions = self.fc2(x)
        return actions, pen_out

    def save_checkpoint(self):
        print('....saving model....')
        torch.save(self.state_dict(), self.checkpoint_file)

    def load_checkpoint(self):
        print('... loading checkpoint ...')
        if self.device.type == 'cpu':
            self.load_state_dict(torch.load(self.checkpoint_file, map_location=torch.device('cpu')))
        else:
            self.load_state_dict(torch.load(self.checkpoint_file))


import matplotlib as mpl
mpl.use('Agg')
import  matplotlib.pyplot as plt
import time
import itertools as it
import pandas as pd
import numpy as np
import warnings
import argparse
from utility import *
from models import *
import pdb
import os
import torch
from sklearn import metrics
from collections import defaultdict
from torch import nn
from torch.utils.data import DataLoader

#
# TrainDNNs.py
#

warnings.filterwarnings("ignore")

parser = argparse.ArgumentParser()
# parse arguments
parser.add_argument('-arch', dest = 'ARCH', default = [5, 5], nargs = '+', type = int, help = 'set the architecture of the n-layers DNN model. ex 100 in 1st , 2000 in second is typed : -arch 100 2000')
parser.add_argument('-epochs',dest = 'EPOCHS', default = 50 , type = int, help = 'nb of max epochs')
parser.add_argument('-wd', dest = 'WEIGHT_DECAY', type = float, default = 0.2, help = 'L2 parametrization [0:no regularization]')
parser.add_argument('-xval', dest = 'XVAL', default = 5, type = int, help= 'number of folds for crossvalidation')
parser.add_argument('-seed', dest = 'SEED', default= 1, type = int, help = 'random seed')
parser.add_argument('-d', dest = 'DEVICE', default= 'cuda:0', type = str, help = 'device ex cuda:0')
parser.add_argument('-target', dest = 'TARGET', default= 'RF00005', type = str, help = 'RFAM identifier to predict from seed')
parser.add_argument('-task', dest = 'TASK', default= 'ZP', type = str, help ='type of dataset randomness / padding sequences [ZP, RP, NUCSHFLZP, NUCSHFLRP, DINUCSHFL]')

args = parser.parse_args()

# some other global variables
# paths
datapath = 'data'
# static values
modelname = 'DNN'
lr = 1e-4
drp=0
vs = 'REST'
bs = 128
loader = 'balanced'
seq_len = 600 # how to get the optimal number efficiently ?

# Set RFs to include
RFs =[path for path in os.listdir(datapath) if os.path.isdir(os.path.join(datapath,path))]
# TASKS = ['ZP','RP','NUCSHFLZP', 'DINUCSHFL']
# update some variables
target = args.TARGET
rfID = args.TARGET
modelID = 'WD{}EP{}'.format(args.WEIGHT_DECAY, args.EPOCHS)
CLSFID = 'BIN'
taskID = args.TASK
ARCH = args.ARCH
# loading data into data frame
data, labels = load_data_in_df(target, RFs, taskID, datapath = datapath, max_len = seq_len)
np.random.seed(args.SEED) # set numpy seed for data shuffle
# multiclass ONLY
# numeric_labels = dict(zip(np.unique(labels['RFAM']), np.arange(len(np.unique(labels['RFAM'])))))
# labels['numeral'] = [numeric_labels[l] for l in labels['RFAM']]
labels['numeral'] = np.array(labels['RFAM'] == target, dtype = int)
torch.manual_seed(args.SEED) # set torch seed for model initialization
rnd_idxs = np.arange(labels.shape[0]) # get ids
np.random.shuffle(rnd_idxs)    # shuffles ids
labels = labels.iloc[rnd_idxs] # shuffle labels
data = data.iloc[rnd_idxs] # shuffle data
# static stats variables
nseeds = labels.shape[0]
test_size = int(float(nseeds) / args.XVAL)
train_size = nseeds - test_size
gr_steps = int(float(train_size) / bs) + 1

# prepare_outfile_paths
SETS_path = os.path.join(modelname, 'SETS')
MODELSPECS_path = os.path.join(modelname, 'MODELSPECS')
MODELS_path = os.path.join(modelname, 'MODELS')
RES_path = os.path.join(modelname, 'OUT')
TRPLOTS_path = os.path.join(modelname, 'TRPLOTS')
assert_mkdir(SETS_path)
assert_mkdir(MODELSPECS_path)
assert_mkdir(MODELS_path)
assert_mkdir(RES_path)
assert_mkdir(TRPLOTS_path)

# define train function
from train import train
# init fig, axes for plotting
fig, axes = plt.subplots(ncols = 2, figsize = (20,10))
annotations = ""
frames = []
# foreach fold in xval (5)
for foldn in range(1 , args.XVAL + 1):

    # define model specs
    model_specs = {
        'xval' : args.XVAL,
        'shfl_seed' : args.SEED,
        'nseeds' : nseeds,
        'test_size': test_size,
        'train_size' : train_size,
        'gr_steps': gr_steps,
        'model_layout': modelname,
        'ARCH': ARCH, # needs update bcs it's array
        'n_hid_lyrs': len(ARCH),
        'n_free_params': None,
        'loader': loader,
        'target': target,
        'seq_len': seq_len,
        'input_size': data.shape[1],
        'batch_size' : bs, # train_size / 10 ,
        'wd' : args.WEIGHT_DECAY,
        'lr': lr,
        'drp': drp,
        'ARCHID': '.'.join([str(e) for e in ARCH]),
        'CLSFID': CLSFID,
        'TASKID': taskID,
        'MODID': modelID,
        'RFID': rfID,
        'FOLDID': foldn,
        'lossfn': torch.nn.BCELoss(),
        'epochs': args.EPOCHS,
        'levels' : max(labels['numeral']) + 1,
        'output_size' : max(labels['numeral']) + 1,
        'device' : args.DEVICE,
        'tr_acc' : None,
        'tr_auc' : None,
        'tr_l' : None,
        'tr_proc_time': None,
        'tst_acc' : None,
        'tst_auc' : None,
        'tst_l' : float('nan')
        }
    print('RFID {} (BINARY) TASK {} ARCH {} MODEL {} fold {} / {}'.format(rfID, taskID, ARCH, modelID, foldn, args.XVAL))
    # store some static values
    nsamples = model_specs['nseeds']
    test_size = model_specs['test_size']
    IDs = np.array([model_specs['RFID'], model_specs['CLSFID'], model_specs['TASKID'], model_specs['ARCHID'], model_specs['MODID'], foldn],dtype = str )
    MODELFULLNAME = '_'.join(IDs)
    # split train and test
    # prepare data splitting
    samplesID = range((foldn - 1) * test_size , min((foldn ) * test_size, nsamples))

    TEST_X = data.iloc[samplesID]
    TEST_Y = labels.iloc[samplesID]
    TRAIN_X = data.iloc[np.setdiff1d(labels.index, samplesID)]
    TRAIN_Y = labels.iloc[np.setdiff1d(labels.index, samplesID)]
    # init dataset objects
    # dataset = Dataset({'data': np.array(TRAIN_X),'labels':np.array(TRAIN_Y.numeral)})
    dataset  = BalancedDataPicker({'data': np.array(TRAIN_X),'labels':np.array(TRAIN_Y.numeral)[np.newaxis].T })
    dl = DataLoader(dataset, batch_size = model_specs['batch_size'])
    # init model
    model = DNN(model_specs).to(model_specs['device'])
    # store nb of params in model
    model_specs['n_free_params'] = get_n_params(model)
    # train model
    print('training model...')
    # time stamp
    startime = time.clock()
    train(model, dl,  model_specs, device = model_specs['device'], foldn=foldn)
    # model is trained, record time, prepare to save model under a REFID
    # save torch model on disk under the name MODELFULLNAME.txt
    torch.save(model.state_dict(), os.path.join(MODELS_path, '{}.txt'.format(MODELFULLNAME)))
    # save up some reported values
    # update model_specs with various reports
    model_specs['tr_proc_time'] = time.clock() - startime
    model_specs['ARCH'] = ".".join([str(e) for e in model_specs['ARCH']])
    # test
    model.eval()
    out = model(torch.Tensor(TEST_X.values).cuda(args.DEVICE))
    TEST_Y['yscore'] = out.detach().cpu().numpy()[:,1]
    frames.append(TEST_Y)
    acc = out.argmax(dim = -1).detach().cpu().numpy() == TEST_Y.numeral
    model_specs['tst_acc'] = float(acc.mean())
    if len(np.unique(TEST_Y.numeral)) > 1: model_specs['tst_auc'] = metrics.roc_auc_score(y_true = TEST_Y.numeral, y_score = out[:,1].detach().cpu().numpy())
    else: model_specs['tst_auc'] = float('nan')
    # store training curves and final accuracies on train
    nbsteps = len(model_specs['tr_l'])
    skip = 1
    losses = model_specs['tr_l'][np.arange(1,nbsteps,skip)]
    accuracies = model_specs['tr_acc'][np.arange(1, nbsteps,skip)]
    aucs = model_specs['tr_auc'][np.arange(1, nbsteps,skip)]
    model_specs['tr_l'] = model_specs['tr_l'][-1]
    model_specs['tr_acc'] = model_specs['tr_acc'][-1]
    model_specs['tr_auc'] = model_specs['tr_auc'][-1]
    auc_annotm = [str(e).zfill(5) for e in np.round([model_specs['tr_acc'], model_specs['tr_auc'] , model_specs['tst_acc'], model_specs['tst_auc']], 3)]
    loss_annotm = [str(e).zfill(5) for e in np.round([model_specs['tr_l'], model_specs['tr_proc_time'] , model_specs['tst_l']], 3)]

    auc_annots = "FOLD NB {} | TR. ACC: {} | TR. AUC:{} | TST. ACC: {} | TST. AUC: {}".format(foldn,auc_annotm[0], auc_annotm[1], auc_annotm[2], auc_annotm[3])
    loss_annots = "FOLD NB {} | TR. LOSS: {} | TR. PROC TIME:{} | TST. L: {}".format(foldn,loss_annotm[0], loss_annotm[1], loss_annotm[2])
    print(loss_annots)
    print(auc_annots)
    # report Training in outfile
    pd.DataFrame({'tr_loss': losses, 'tr_acc': accuracies, 'tr_auc': aucs}).to_csv(os.path.join(RES_path,MODELFULLNAME + ".tr_curves"))
    # save model_specs dict under the name MODELFULLNAME.specs
    with open(os.path.join(MODELSPECS_path, '{}.specs'.format(MODELFULLNAME)), 'w') as o : o.write(str(model_specs)) # to be updated

    # PLOT RESULTS
    # plot | tr_l | tr_acc | tr_auc
    axes[0].plot(np.arange(len(losses)) * skip, losses, lw = 1, c = 'grey')
    axes[1].plot(np.arange(len(aucs)) * skip, aucs, lw = 1, c = 'b')
    # annotate last tr_l, _tr_acc, tr_auc, tr_proc_time
    # annotate/scatter tst_l, tst_acc, tst_auc
    axes[0].scatter(x = [nbsteps], y = [model_specs['tr_l']], s = 5, label = loss_annots)
    axes[1].scatter(x = [nbsteps], y = [model_specs['tr_auc']], s = 5,  c= 'b')
    axes[1].scatter(x = [nbsteps], y = [model_specs['tst_auc']], s = 5, label = auc_annots)
    axes[0].legend()
    axes[1].legend()
    # xlabel = gradient steps
    axes[0].set_xlabel('gradient steps')
    axes[0].set_ylabel('BCEloss')
    axes[1].set_xlabel('gradient steps')
    axes[1].set_ylabel('auc')
    # title the figure with REFID
    REF ="_".join(np.array([model_specs['RFID'], taskID, model_specs['ARCHID'], model_specs['MODID']], dtype = str))
    fig.suptitle(REF)
    # make outpath
    outpath = os.path.join(TRPLOTS_path, REF + '.png')
    plt.savefig(outpath, dpi = 300)
RES = pd.concat(frames)
AGG_AUC = metrics.roc_auc_score(y_true = RES.numeral , y_score = RES.yscore)
RES.to_csv(os.path.join(RES_path, MODELFULLNAME + "_AGG_AUC_{}.scores".format(round(AGG_AUC,4))))