import gensim
import numpy as np
import os
import tensorflow as tf
import jieba
import random
import re
from industry.models import Word, WordTest

# keyword used to locate industry entity
rules = [r'(.*)上游(.*)', r'下游(.*)', r'(.*)应用于(.*)']
keywords = ['上游', '下游', '应用']

# you should change the path to your own  model path
word2vec_model_path = 'D:\\word2vec\\word2vec_from_weixin\\word2vec\\word2vec_wx'

# you should change the path to your own data path
data_path = 'F:\\tmp_data\\temp_data\\data'

# parameters used while training
sentence_length = 15
word_dim = 256
class_size = 2
rnn_size = 256
num_layers = 2
epoch = 80
batch_size = 20
learning_rate = 0.003

# build your own word2vec
def train_data_build():
    file = r'F:\train_data.txt'
    names = file_name('F:\\data')
    for name in names:
        f = open(name, errors='ignore')
        st = f.read()
        with open(file, 'a+') as f:
            seg_list = jieba.cut(st, cut_all=False)
            f.write(" ".join(seg_list))
            f.write('\n')
        f.close()

def train_data():
    from gensim.models import word2vec
    sentences = word2vec.Text8Corpus('F:\\train_data.txt')
    model = word2vec.Word2Vec(sentences, size=50)
    model.save('word2vec_model')

# get the names of document from the path
def file_name(file_dir):
    names_list = []
    for root, dirs, files in os.walk(file_dir):
        for file in files:
            if os.path.splitext(file)[1] == '.txt':
                names_list.append(os.path.join(root, file))
    return names_list

# collect the needed data from documents to database. True means collect training data,False means collect test data
def collect_data(flag=True):
    if flag:
        total_file = 200
    else:
        total_file = 50
    names = file_name(data_path)
    names_slice = random.sample(names, total_file)
    sentence_id = 0
    for name in names_slice:
        word_counter = 0
        f = open(name, errors='ignore')
        st = f.read()
        for j in range(0, len(rules)):
            compile_name = re.compile(rules[j], re.M)
            res_name = compile_name.finditer(st)
            for m in res_name:
                seg_list = jieba.lcut(m.group(), cut_all=False)
                target_list = []
                for w in seg_list:
                    if len(w) > 1:
                        target_list.append(w)
                print(target_list)
                try:
                    target = target_list.index(keywords[j])
                except ValueError:
                    continue
                words_in_sentence = []
                index = target - 7
                for i in range(15):
                    if index >= 0:
                        try:
                            words_in_sentence.append(target_list[index])
                        except IndexError:
                            words_in_sentence.append("#")
                    else:
                        words_in_sentence.append("#")
                    index += 1
                for word in words_in_sentence:
                    if flag:
                        Word.objects.create(name=word, sentence_id=sentence_id)
                    else:
                        WordTest.objects.create(name=word, sentence_id=sentence_id)
                sentence_id += 1
            word_counter += 1

# delete the word that don't have a word2vec
def delete_word():
    words_train = Word.objects.all()
    words_test = WordTest.objects.all()
    words = words_train + words_test
    model = gensim.models.Word2Vec.load(word2vec_model_path)
    for word in words:
        if word.name == '#':
            continue
        try:
            model[word.name]
        except  KeyError:
            print(word.name)
            Word.objects.filter(name=word.name).update(name='#')

# delete sentences that do not have any industry entities
def delete_data():
    for counter in range(0, 250):
        words = Word.objects.filter(sentence_id=counter)
        flag = True
        for word in words:
            if word.div_type != 0:
                flag = False
        if flag:
            Word.objects.filter(sentence_id=counter).delete()

class Model:
    def __init__(self):
        self.input_data = tf.placeholder(tf.float32, [None, sentence_length, word_dim])
        self.output_data = tf.placeholder(tf.float32, [None, sentence_length, class_size])
        fw_cell = tf.nn.rnn_cell.LSTMCell(rnn_size, state_is_tuple=True)
        fw_cell = tf.nn.rnn_cell.DropoutWrapper(fw_cell, output_keep_prob=0.5)
        bw_cell = tf.nn.rnn_cell.LSTMCell(rnn_size, state_is_tuple=True)
        bw_cell = tf.nn.rnn_cell.DropoutWrapper(bw_cell, output_keep_prob=0.5)
        fw_cell = tf.nn.rnn_cell.MultiRNNCell([fw_cell] * num_layers, state_is_tuple=True)
        bw_cell = tf.nn.rnn_cell.MultiRNNCell([bw_cell] * num_layers, state_is_tuple=True)
        words_used_in_sent = tf.sign(tf.reduce_max(tf.abs(self.input_data), reduction_indices=2))
        self.length = tf.cast(tf.reduce_sum(words_used_in_sent, reduction_indices=1), tf.int32)
        output, _, _ = tf.nn.static_bidirectional_rnn(fw_cell, bw_cell,
                                                      tf.unstack(tf.transpose(self.input_data, perm=[1, 0, 2])),
                                                      dtype=tf.float32, sequence_length=self.length)
        weight, bias = self.weight_and_bias(2 * rnn_size, class_size)
        output = tf.reshape(tf.transpose(tf.stack(output), perm=[1, 0, 2]), [-1, 2 * rnn_size])
        prediction = tf.nn.softmax(tf.matmul(output, weight) + bias)
        self.prediction = tf.reshape(prediction, [-1, sentence_length, class_size])
        self.loss = self.cost()
        optimizer = tf.train.AdamOptimizer(learning_rate)
        tvars = tf.trainable_variables()
        grads, _ = tf.clip_by_global_norm(tf.gradients(self.loss, tvars), 10)
        self.train_op = optimizer.apply_gradients(zip(grads, tvars))

    def cost(self):
        cross_entropy = self.output_data * tf.log(self.prediction)
        cross_entropy = -tf.reduce_sum(cross_entropy, reduction_indices=2)
        mask = tf.sign(tf.reduce_max(tf.abs(self.output_data), reduction_indices=2))
        cross_entropy *= mask
        cross_entropy = tf.reduce_sum(cross_entropy, reduction_indices=1)
        cross_entropy /= tf.cast(self.length, tf.float32)
        return tf.reduce_mean(cross_entropy)

    @staticmethod
    def weight_and_bias(in_size, out_size):
        weight = tf.truncated_normal([in_size, out_size], stddev=0.01)
        bias = tf.constant(0.1, shape=[out_size])
        return tf.Variable(weight), tf.Variable(bias)

# evaluate the prediction of the model
def f1(prediction, target, length):
    tp = np.array([0] * (class_size + 1))
    fp = np.array([0] * (class_size + 1))
    fn = np.array([0] * (class_size + 1))
    target = np.argmax(target, 2)
    prediction = np.argmax(prediction, 2)
    for i in range(len(target)):
        for j in range(length[i]):
            if target[i, j] == prediction[i, j]:
                tp[target[i, j]] += 1
            else:
                fp[target[i, j]] += 1
                fn[prediction[i, j]] += 1
    for i in range(class_size):
        tp[class_size] += tp[i]
        fp[class_size] += fp[i]
        fn[class_size] += fn[i]
    precision = []
    recall = []
    fscore = []
    for i in range(class_size):
        precision.append(tp[i] * 1.0 / (tp[i] + fp[i]))
        recall.append(tp[i] * 1.0 / (tp[i] + fn[i]))
        fscore.append(2.0 * precision[i] * recall[i] / (precision[i] + recall[i]))
    print(fscore)
    return fscore[class_size - 1]

def get_train_test_data():
    zero = []
    model = gensim.models.Word2Vec.load('D:\\word2vec\\word2vec_from_weixin\\word2vec\\word2vec_wx')
    for i in range(0, 256):
        zero.append(0.1)
    words = Word.objects.all()
    i = 0
    counter = 0
    inputs = []
    outputs = []
    word_sentence = []
    while i < len(words):
        input = np.empty((15, 256))
        output = np.empty((15, class_size))
        word_test = []
        tmp_words = words[i:i + 15]
        print(tmp_words)
        j = 0
        for word in tmp_words:
            try:
                input[j] = model[word.name]
                word_test.append(word.name)
            except KeyError:
                input[j] = np.array(zero)
                word_test.append(word.name)
            if word.div_type == 0:
                tmp = [1, 0]
            elif word.div_type == 1:
                tmp = [0, 1]
            else:
                tmp = [0, 1]
            output[j] = np.array(tmp)
            counter += 1
            j += 1
        inputs.append(input)
        outputs.append(output)
        word_sentence.append(word_test)
        i += 15
    split_point = int((len(words) / 15) * 0.8)
    train_input = inputs[0:split_point]
    train_output = outputs[0:split_point]
    test_input = inputs[split_point:(len(words) / 15) - 1]
    test_output = outputs[split_point:(len(words) / 15) - 1]
    word_sentence = word_sentence[split_point:(len(words) / 15) - 1]
    return np.array(train_input), np.array(train_output), np.array(test_input), np.array(test_output), word_sentence

def train():
    train_inp, train_out, test_a_inp, test_a_out, word_sentence = get_train_test_data()
    for sentence in word_sentence:
        print(sentence)
    model = Model()
    with tf.Session() as sess:
        sess.run(tf.initialize_all_variables())
        saver = tf.train.Saver()
        for e in range(epoch):
            for ptr in range(0, len(train_inp), batch_size):
                sess.run(model.train_op, {model.input_data: train_inp[ptr:ptr + batch_size],
                                          model.output_data: train_out[ptr:ptr + batch_size]})
            if e % 10 == 0:
                save_path = saver.save(sess, "./model/model.ckpt")
                print("model saved in file: %s" % save_path)
            pred, length = sess.run([model.prediction, model.length], {model.input_data: test_a_inp,
                                                                       model.output_data: test_a_out})
            print("epoch %d:" % e)
            print('test_a score:')
            f1(pred, test_a_out, length)
            for z in pred:
                print(z)


#!/usr/bin/env python3
import pyautogui
from socket import *
import time
import json

[screenWidth, screenHeight] = pyautogui.size()
mouseVX = -1

while True:
    # 1. configure socket dest.
    serverName = '127.0.0.1'
    serverPort = 12345
    clientSocket = socket(AF_INET, SOCK_STREAM)
    try:
        clientSocket.setsockopt(SOL_SOCKET, SO_KEEPALIVE, 1)
        clientSocket.connect((serverName, serverPort))
        print(clientSocket.getsockopt(SOL_SOCKET, SO_KEEPALIVE))
    except ConnectionRefusedError as e:
        print("Server refused connection. retrying")
        time.sleep(1)
        continue

    # 2. communication routine
    while (1):
        [mouseX, mouseY] = pyautogui.position()
        if mouseX < (screenWidth - 2) and mouseVX > 0:
            mouseVX -= 1
            data = json.dumps({"x": mouseVX, "y": mouseY})
            try:
                clientSocket.send(bytes(data, "utf8"))
            except ConnectionResetError as e:
                print("Server connection closed")
                break
            pyautogui.moveTo(screenWidth - 2, mouseY)
        if mouseX > (screenWidth - 2):
            mouseVX += 1
            data = json.dumps({"x": mouseVX, "y": mouseY})
            try:
                clientSocket.send(bytes(data, "utf8"))
            except ConnectionResetError as e:
                print("Server connection closed")
                break
            pyautogui.moveTo(screenWidth - 2, mouseY)

    # 3. proper closure
    clientSocket.shutdown(SHUT_RDWR)
    clientSocket.close()


def problem2(n):
    prev = 1
    cur = 2
    total = 0
    while cur <= n:
        total += cur
        nex = cur + prev
        prev = cur + nex
        cur = nex + prev
    return total

def main():
    print(problem2(4000000))

if __name__ == "__main__":
    main()


import random

def gcd(A, B):
    while (A != B):
        if (A > B): A = A - B
        if (B > A): B = B - A
    return A

def ExtGCD(a, b):
    "a*s + b*t = gcd(a,b),扩展欧几里德算法"
    if b == 0:
        return 1, 0, a
    else:
        s, t, q = ExtGCD(b, a % b)  # q = gcd(a, b) = gcd(b, a%b)
        s, t = t, (s - (a // b) * t)
        return s, t, q

def isPrime(n):
    '改良的判断素数方法 费马检测 + 平方根二次检测, 返回False不是素数,返回True是素数'
    if(n <= 2):
        if(n == 2):return True
        else:return False
    if(n %2 == 0):return False
    u = n - 1
    while(u % 2 == 0):
        u = int(u / 2)
    for _ in range(10):
        '检测次数为 10次 ,费马检测出错概率为(1/4^10)'
        a = random.randint(2, n - 1)
        testu = u
        x = ModExp(a,u,n)
        while(testu < n):
            y = ModExp(x,2,n)      # 二次检测原理
            if (y == 1 and x != 1 and x != n - 1):
                return False       # 不满足二次探测
            x = y
            testu = testu * 2
        if ( x != 1):
            return False
    return True

def ModExp(b,n,m):
    '反复平方乘算法 计算b^n(mod m)'
    stringN = bin(n)               # 指数转换为二进制
    stringN = stringN[3:]          # 取第三位之后
    x = b
    for i in stringN:
        if(i == '0'):
            x = x**2
        else:
            x = b*(x**2)
    return x%m

def Phi(n):
    '计算欧拉函数'
    phi = 0
    for i in range(1,n):
        if(gcd(i,n) == 1):phi += 1
    return phi

if __name__ == '__main__':
    # print(ExtGCD(3, 2))
    # print(ModExp(8,5,11))
     print(isPrime(2**16+1))
     print(Phi(5))


# Definition for singly-linked list.

class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next
class Solution:
    def mergeInBetween(self, list1: ListNode, a: int, b: int, list2: ListNode) -> ListNode:
        c = 0
        temp = list1

        while temp is not None:
            if a <= c <= b:
                temp

Linked List/Leetcode Problems/Easy/merge between.py


import random
import math
import copy

import numpy as np

import utils

class flavorText:

    std = '...'

    # assuming 3x3 player grid
    trans = {
        (0, 0): 'corner',
        (0, 1): 'wall',
        (0, 2): 'corner',

        (1, 0): 'wall',
        (1, 1): 'center',
        (1, 2): 'wall',

        (2, 0): 'corner',
        (2, 1): 'wall',
        (2, 2): 'corner',
    }

    rim = {
        'corner': ['a snowdrift is piled up in the corner'],
        'center': ['starlight streams in from above'],
        'wall': ['a crooked panel reveals numerous decrepit cables'],
    }

    locs = {
        'rim': rim,
    }

    @classmethod
    def flavor(self, location, pos):
        if random.random() < 0.1:
            return random.choice(self.locs[location][self.trans[pos]])
        else:
            return self.std

tiles = {
    'unlit': ' ',
    'lit': '•',
    'opaque': '█',
    'opaque_up': '▀',
    'opaque_down': '▄',
    'water': '~'
    # 'corpse': '×', this would be a dynamic element, not a baked room element
}

# flatgen = {}
# keys = list(tiles.keys())
#
# for i in range(len(keys)):
#     for j in range(len(keys)):

flat = {
    (0, 0): 'unlit',
    (2, 1): 'opaque_up',
    (1, 2): 'opaque_down',
    (1, 1): 'lit',

    (2, 0): 'opaque_up',
    (0, 2): 'opaque_down',
    (2, 2): 'opaque',
}

# NOTE for map data --
# 0 = unlit tile
# 1 = lit
# 2 = opaque

doorTemplate = {
    'type': 'normal',
    'position': (0, 0),
    'postr': 'left',
    'state': 'open',
}

def newDoor(type, pos, postr, state):
    return {'type': type, 'pos': pos, 'postr': postr, 'state': state}

roomTemplate = {
    'type': 'room',
    'name': 'room',
    'width' : -1,
    'height': -1,
    'playerw': 3,
    'playerh': 3,
    'draww': -1,
    'drawh': -1,
    'ptog': {},
    'flav': {},
    'map': [],
    'things': [],
    'doors': [],
    'special': None,
    'dist': 0,
}

sqRoom = {
    'type': 'room',
    'name': 'square',
    'width': 5,
    'height': 5,
    'playerw': 3,
    'playerh': 3,
    'map': [
        2, 2, 2, 2, 2,
        2, 0, 0, 0, 2,
        2, 0, 0, 0, 2,
        2, 0, 0, 0, 2,
        2, 2, 2, 2, 2,
    ],
    'things': [],
}

def formatRoom(roomdict):
    w = roomdict['draww']
    h = roomdict['drawh']
    # for final discord use:
    # output = '```'
    output = ''
    mapp = roomdict['map']
    # print(math.ceil(h/2))
    for y in range(math.ceil(h/2)):
        for x in range(w):
            pos1 = utils.od(x, y*2, w)
            pos2 = utils.od(x, y*2 + 1, w)
            # print(pos1, pos2)
            try:
                output += tiles[flat[(mapp[pos1], mapp[pos2])]]
            except IndexError:
                # print(flat[(mapp[pos1]), mapp[pos1]])
                output += tiles[flat[(mapp[pos1], 0)]]
            except KeyError:
                print('Error: room {} is poorly formatted!'.format(roomdict['name']))
                exit(1)
        output += '\n'
    # for final discord use:
    # output += '```'
    return output

doorList = [
    'up',
    'down',
    'left',
    'right'
]

doorTrans = {
    (0, 1): 'left',
    (2, 1): 'right',
    (1, 0): 'up',
    (1, 2): 'down'
}

wallTile = 2
litTile = 1

def genRect(dict, tempmap, width, height, fill, location, doors):
    # smallest size for a rect is 5x5
    for y in range(height):
        for x in range(width):
            if y == 0:
                tempmap[utils.od(x, y, width)] = wallTile
            elif y == height - 1:
                tempmap[utils.od(x, y, width)] = wallTile
            if x == 0:
                tempmap[utils.od(x, y, width)] = wallTile
            elif x == width - 1:
                tempmap[utils.od(x, y, width)] = wallTile

            if fill:
                if x > 1 and x < width - 2 and y > 1 and y < height - 2:
                    if (x + 1) % 3 == 0:
                        tempmap[utils.od(x, y, width)] = litTile
    # if width
    # dict['playerw']
    # TODO -- this should be in terms of playerw and playerh
    for y in range(3):
        for x in range(3):
            dict['ptog'][(x, y)] = (x*((dict['width'] - 1)//2),
                                   y*((dict['height'] - 1)//2))
            dict['flav'][(x, y)] = flavorText.flavor(location, (x, y))

            if (x, y) in doorTrans and doorTrans[(x, y)] in doors:
                dict['doors'].append(newDoor('normal', (x, y), doorTrans[(x, y)], 'open'))
            elif (x, y) in doorTrans and doorTrans[(x, y)] + '_k' in doors:
                dict['doors'].append(newDoor('key', (x, y), doorTrans[(x, y)], 'open'))

    # doors (hardcoded 2 pixels)
    unlit = 0
    if height % 2 == 0:
        if 'left' in doors:
            tempmap[utils.od(0, height/2 - 1, width)] = unlit
            tempmap[utils.od(0, height/2, width)] = unlit

        if 'right' in doors:
            tempmap[utils.od(width - 1, height/2 - 1, width)] = unlit
            tempmap[utils.od(width - 1, height/2, width)] = unlit
    else:
        if 'left' in doors:
            tempmap[utils.od(0, math.floor(height/2), width)] = unlit
        if 'right' in doors:
            tempmap[utils.od(width - 1, math.floor(height/2), width)] = unlit

    if width % 2 == 0:
        if 'up' in doors:
            tempmap[utils.od(width/2 - 1, 0, width)] = unlit
            tempmap[utils.od(width/2, 0, width)] = unlit

        if 'down' in doors:
            tempmap[utils.od(width/2 - 1, height - 1, width)] = unlit
            tempmap[utils.od(width/2, height - 1, width)] = unlit
    else:
        if 'up' in doors:
            tempmap[utils.od(width/2, 0, width)] = unlit
        if 'down' in doors:
            tempmap[utils.od(width/2, height - 1, width)] = unlit

def genCircle(tempmap, width, height, fill, location):
    # smallest size for a rect is 5x5
    for y in range(height):
        for x in range(width):
            if y == 0:
                tempmap[utils.od(x, y, width)] = wallTile
            elif y == height - 1:
                tempmap[utils.od(x, y, width)] = wallTile
            if x == 0:
                tempmap[utils.od(x, y, width)] = wallTile
            elif x == width - 1:
                tempmap[utils.od(x, y, width)] = wallTile

            if fill:
                if x > 1 and x < width - 2 and y > 1 and y < height - 2:
                    if (x + 1) % 3 == 0:
                        tempmap[utils.od(x, y, width)] = litTile
    # if width
    # dict['playerw']
    # TODO -- this should be in terms of playerw and playerh
    for y in range(3):
        for x in range(3):
            dict['ptog'][(x, y)] = (x*((dict['width'] - 1)//2),
                                   y*((dict['height'] - 1)//2))
            dict['flav'][(x, y)] = flavorText.flavor(location, (x, y))

    # doors (hardcoded 2 pixels)
    unlit = 0
    if height % 2 == 0:
        tempmap[utils.od(0, height/2 - 1, width)] = unlit
        tempmap[utils.od(0, height/2, width)] = unlit
        tempmap[utils.od(width - 1, height/2 - 1, width)] = unlit
        tempmap[utils.od(width - 1, height/2, width)] = unlit
    else:
        tempmap[utils.od(0, math.floor(height/2), width)] = unlit
        tempmap[utils.od(width - 1, math.floor(height/2), width)] = unlit

    if width % 2 == 0:
        tempmap[utils.od(width/2 - 1, 0, width)] = unlit
        tempmap[utils.od(width/2, 0, width)] = unlit
        tempmap[utils.od(width/2 - 1, height - 1, width)] = unlit
        tempmap[utils.od(width/2, height - 1, width)] = unlit
    else:
        tempmap[utils.od(width/2, 0, width)] = unlit
        tempmap[utils.od(width/2, height - 1, width)] = unlit

def genRoom(name, width, height, shape, doors=doorList, fill=True, location='rim', special=None, dist=0):
    dict = copy.deepcopy(roomTemplate)
    dict['name'] = name
    dict['width'] = width
    dict['height'] = height
    width = width*3 + 2
    height = height*2 + 4
    dict['draww'] = width
    dict['drawh'] = height
    dict['special'] = special
    dict['dist'] = dist
    tempmap = np.zeros((width*height,), dtype='u1')

    # note -- this will cause errors if the height is less than four
    if shape == 'rect':
        genRect(dict, tempmap, width, height, fill, location, doors)
    elif shape == 'circle':
        genCircle(tempmap, width, height, fill, location)

    dict['map'] = tempmap
    return dict

# bigg = genRoom('sq', 18, 9, 'rect')

def printRoom(roomdict):
    for y in range(roomdict['drawh']):
        string = ''
        for x in range(roomdict['draww']):
            string += str(roomdict['map'][utils.od(x, y, roomdict['draww'])])
        print(string)

# printRoom(bigg)

arenaStr = '\n'.join([
'   ░░░░░░░░░░░░░░░░░░░░░░░░   ',
'   ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒   ',
'   ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓   ',
'  /...............{6}.{3}..\\  ',
' /••{0}••••••••••••{4}•{1}••\\ ',
'/●●●●●●●●●●●●●●●●●●●{5}●{2}●●\\'
])

replacement = [
    '•••',
    '●●●',
    '...',
    '•••',
    '●●●',
    '...'
]

barStr = '\n'.join([
' {} ',
'│{}│',
'│{}│',
'│{}│',
'│{}│',
'│{}│',
])

barFill = [
    ' ',
    '▁',
    '▂',
    '▃',
    '▄',
    '▅',
    '▆',
    '▇',
    '█',
]

def drawBar(char, total, current):
    numsegs = 5
    totalRange = numsegs * 8 # as determined by box characters
    # this assumes a start of zero
    barval = utils.clamp(int(utils.remap(current, 0, total, 0, totalRange)), 0, totalRange)
    numFull = barval // 8
    partial = barval % 8
    barlist = [barFill[-1] for x in range(numFull)]
    if partial != 0:
        barlist += [barFill[partial]]
    barlist += [' ' for x in range(numsegs - len(barlist))]
    return barStr.format(char, *barlist[::-1])

def drawArena(player):
    enemyList = [x.dict['char'] for x in player.dict['enemies']]
    enemyList += replacement[len(enemyList):]
    arena = arenaStr.format(player.dict['char'], *enemyList)
    bar = drawBar('H', player.dict['stats']['hp'], player.dict['status']['hp'])
    merge1 = utils.mergeStrings(arena, bar, 3, 0)
    return merge1

rectTemplate = genRoom('chamber', 7, 5, 'rect')

class Room:
    def __init__(self, initdict=rectTemplate, name=None, width=None, height=None, shape=None, dist=None):
        self.dict = copy.deepcopy(initdict)

        self.dict['name'] = name if name is not None else self.dict['name']
        self.dict['width'] = width if width is not None else self.dict['width']
        self.dict['height'] = height if height is not None else self.dict['height']
        self.dict['shape'] = shape if shape is not None else ''

    def draw(self, player):
        if player.dict['state']['state'] == 'exploration':
            tempbuff = formatRoom(self.dict)
            for thing in self.dict['things']:
                tempbuff = self.add(tempbuff, thing)
            tempbuff = self.addPlayer(tempbuff, player)
        elif player.dict['state']['state'] == 'combat':
            tempbuff = drawArena(player)
        return tempbuff

    def add(self, buff, thing):
        pos = self.buff2coord(thing.dict['x'], thing.dict['y'])
        offset = len(thing.dict['char'])//2
        return buff[:pos - offset] + thing.dict['char'] + buff[pos + 1 + offset:]

    def addPlayer(self, buff, player):
        temppos = self.getPlayerPos(player)
        pos = self.buff2coord(temppos[0], temppos[1])
        offset = len(player.dict['char'])//2
        # print(playerpos, temppos, pos)
        return buff[:pos - offset] + player.dict['char'] + buff[pos + 1 + offset:]

    def buff2coord(self, x, y):
        # + 1 because of newline
        return (x*3 + 2) + (y + 1)*(self.dict['draww'] + 1)

    def getPlayerPos(self, player):
        playerpos = (player.dict['x'], player.dict['y'])
        return self.dict['ptog'][playerpos]

    def insert(self, thing):
        self.dict['things'].append(thing)

    def save(self):
        for i in range(len(self.dict['things'])):
            self.dict['things'][i] = self.dict['things'][i].save()
        return self.dict

    def animate(self, player):
        for thing in self.dict['things']:
            thing.animate(player)
        for thing in self.dict['things']:
            if thing.dict['type'] == 'enemy':
                thing.resolveCollision(player)
        for thing in self.dict['things']:
            if utils.distance((thing.dict['x'], thing.dict['y']), self.getPlayerPos(player)) < 2:
                thing.onTouch(player)

    def validPosition(self, pos):
        if pos[0] < 0 or pos[0] > self.dict['width'] - 1:
            return False
        if pos[1] < 0 or pos[1] > self.dict['height'] - 1:
            return False
        return True


from django.test import TestCase
import pandas as pd
# Create your tests here.

def excel_to_dict(path):
    '''读取excel的数据,存储为字典'''
    keys = ['sno','name','gender','birthday','mobile','email','address']
    data = pd.read_excel(path,sheet_name=['student'],header = None,index_col=None, names = keys )
    df = data['student']
    result = []
    for row in df.iterrows():
        result.append(row[1].to_dict())
    return result

if __name__ == "__main__":
    print(excel_to_dict('./test.xlsx'))


num = input()
no_of_digits = len(num)

num = int(num)

original_num = num
temp = 0
while num > 0:
	digit = num % 10
	num = num // 10
	temp += digit**no_of_digits

if temp == original_num:
	print("Yes")
else:
	print("No")


import PySimpleGUIWeb as sg
import numpy
acc=0
def cal():
	c=0
	z=numpy.random.randint(1,7)
	while True:
		if(v[0]==z):
			c+=10
			return True,z
			break
		else:
			c-=5
			return False,z
			break
	acc+=c
sg.ChangeLookAndFeel('Green Tan')
l1=[[sg.T('GUESS-GAME',font='courier 45',size=(60,2))],
       [sg.Text('guess a number-------------------',font='Courier 20'),sg.In('Number',                                  size=(18,1))],
       [sg.T('status'),sg.T('',text_color='red',key='k1',size=(25,1),background_color='lightblue'),sg.T('',text_color='red',key='k2',size=(18,1))],
       [sg.RButton('Submit',size=(20,1)),sg.Button('Exit',size=(7,1))]]
w=sg.Window('TITTLE').Layout(l1)
while True:
	e,v=w.Read()
	if(e=='Exit'):
		sg.PopupError('error')
		w.close()
		break
	else:
		x,y=cal()
		if(x==True):
			w.FindElement('k1').Update('Right answer your balance is '+str(acc))
		elif(x==False):
			w.FindElement('k1').Update('wrong answer your balance is '+str(acc))
			if(int(v[0])<y):
				w.FindElement('k2').Update('true answer is greater than your answer')
			elif(int(v[0])>y):
				w.FindElement('k2').Update('true answer is less than your answer')
		break


from utm import utmconv
from math import pi, cos, sin, sqrt, asin, acos

def getLattitudeConvertionError(lattitude, longitude, lattitude_difference):
    earthRadius = 6378137.0

    (hemisphere, zone, letter, e, n) = uc.geodetic_to_utm(lattitude, longitude)
    e_new = e + lattitude_difference
    n_new = n

    # convert back from UTM to geodetic
    (lattitude_new, longitude_new) = uc.utm_to_geodetic(
        hemisphere, zone, e_new, n_new)
    print("Coordinates: ", lattitude, ",", longitude)

    print("New Coordinates: ", lattitude_new, ",", longitude_new)
    # calculate the error using Great Circle Distance Formula
    calc_distance = 2*asin(sqrt((sin((lattitude*(pi/180)-lattitude_new*(pi/180))/2))**2+cos(
        lattitude*(pi/180))*cos(lattitude_new*(pi/180))*(sin((longitude*(pi/180)-longitude_new*(pi/180))/2))**2))
    # Great circle distance can be likewise be expressed in radians by defining the distance to be the angle subtended by the
    # arc at the center of the earth. Since by definition, one nautical mile subtends one minute (=1/60 degree) of arc, we have:
    calc_distance = calc_distance*((180*60)/pi)
    calc_distance = calc_distance*1852
    error = lattitude_difference - calc_distance

    print('Distance: ', lattitude_difference,
          ' Calculated distance: ', calc_distance, 'Error: ',  error)
    return error

def getLongitudeConvertionError(lattitude, longitude, longitude_difference):
    earthRadius = 6378137.0
    # Convert from geodetic to UTM and add distance
    (hemisphere, zone, letter, e, n) = uc.geodetic_to_utm(lattitude, longitude)
    e_new = e
    n_new = n + longitude_difference

    # convert back from UTM to geodetic
    (lattitude_new, longitude_new) = uc.utm_to_geodetic(
        hemisphere, zone, e_new, n_new)
    print("Coordinates: ", lattitude, ",", longitude)
    print("New Coordinates: ", lattitude_new, ",", longitude_new)

    # calculate the error using Great Circle Distance Formula
    calc_distance = 2*asin(sqrt((sin((lattitude*(pi/180)-lattitude_new*(pi/180))/2))**2+cos(
        lattitude*(pi/180))*cos(lattitude_new*(pi/180))*(sin((longitude*(pi/180)-longitude_new*(pi/180))/2))**2))
    calc_distance = ((180*60)/pi)*calc_distance  # radians to degrees*seconds
    calc_distance = calc_distance*1852  # Nautic mile to km
    error = longitude_difference - calc_distance

    print('Distance: ', longitude_difference,
          ' Calculated distance: ', calc_distance, 'Error: ',  error)
    return error

def exercise_4_1():
    # Drone center
    lat1 = 55.47
    lon1 = 10.33
    print("Error @ the Drone Center")
    getLattitudeConvertionError(lat1, lon1, 100.)

    # Iceland
    lat1 = 55.47
    lon1 = 12.33
    print("Error @ Iceland")
    getLattitudeConvertionError(lat1, lon1, 1000.)

    # Greenland
    lat1 = 55.47
    lon1 = 20.33
    print("Error @ Greenland")

    getLattitudeConvertionError(lat1, lon1, 1000.)

    # Longitude test
    lat1 = 55.47
    lon1 = 50.33
    print("Error Longitude Test")
    getLongitudeConvertionError(lat1, lon1, 1000.)

# instantiate utmconv class
uc = utmconv()

# exercise_4_1()

# lat1 = 55.12518
# lon1 = 10.25419
# print("Error @ the Drone Center")
# getLattitudeConvertionError(lat1, lon1, 1000.)


from rllab.envs.mujoco.mujoco_env import MujocoEnv
from rllab.core.serializable import Serializable
from rllab.envs.base import Step
from rllab.misc.overrides import overrides
from sandbox.ours.envs.mujoco.base_env_rand_param import BaseEnvRandParams
from sandbox.ours.envs.helpers import get_all_function_arguments
from rllab.misc import logger
import numpy as np
import warnings

class Reacher5DofEnvRandParams(BaseEnvRandParams, MujocoEnv, Serializable):
    FILE = 'reacher_5dof.xml'

    def __init__(self, *args, log_scale_limit=2.0, fix_params=False, fixed_goal=True, random_seed=None, **kwargs):
        self.sign = 1
        self.first = True
        self.penalty_ctrl = 0.01

        self.init_geom_size = None
        self.init_body_pos = None
        self.init_geom_pos = None

        args_all, kwargs_all = get_all_function_arguments(self.__init__, locals())
        BaseEnvRandParams.__init__(self, log_scale_limit=log_scale_limit, fix_params=fix_params,
                                   rand_params=['geom_size'], fixed_goal=fixed_goal, random_seed=random_seed)

        MujocoEnv.__init__(self, *args, **kwargs)
        Serializable.__init__(*args_all, **kwargs_all)

    def step(self, action):
        # distance between end of reacher and the goal
        vec = self.get_body_com("fingertip") - self.get_body_com("target")

        # calculate reward
        reward_dist = - np.linalg.norm(vec)
        reward_ctrl = - np.square(action).sum()
        reward = reward_dist + self.penalty_ctrl * reward_ctrl

        # take a step
        self.forward_dynamics(action)
        obs = self.get_current_obs()
        done = False
        return Step(obs, float(reward), done, reward_dist=reward_dist, reward_ctrl=reward_ctrl)

    @overrides
    def reset_mujoco(self, init_state=None, evaluating=None):

        if (init_state is None):

            # set random joint starting positions
            qpos = np.random.uniform(low=-1.5, high=1.5, size=self.init_qpos.shape) + self.init_qpos

            # set random goal position
            if (self.fixed_goal):
                self.goal = np.array([0.25, 0.15])
            else:
                while True:
                    potential_goal = np.random.uniform(low=-.15, high=.15, size=2)
                    if np.linalg.norm(potential_goal) > 0.03:
                        self.goal = potential_goal
                        break
            qpos[-2:, 0] = self.goal

            # set random starting joint velocities
            qvel = self.init_qvel + np.random.uniform(low=-.005, high=.005, size=self.init_qvel.shape)
            # set 0 vel for the goal
            qvel[-2:, 0] = 0

            # set vars
            self.model.data.qpos = qpos
            self.model.data.qvel = qvel
            self.model.data.qacc = self.init_qacc
            self.model.data.ctrl = self.init_ctrl

        else:
            start = 0
            for datum_name in ["qpos", "qvel", "qacc", "ctrl"]:
                datum = getattr(self.model.data, datum_name)
                datum_dim = datum.shape[0]
                datum = init_state[start: start + datum_dim]
                setattr(self.model.data, datum_name, datum)
                start += datum_dim

    def get_current_obs(self):
        # qpos 7 things (5pos, goalx, goaly)
        # qvel 7 things (5pos, goalx, goaly)
        # OBS: 5,5,2,5,2
        theta = self.model.data.qpos.flat[:-2]
        return np.concatenate([
            np.cos(theta), # joint angles
            np.sin(theta),
            self.model.data.qpos.flat[-2:], #end effector position
            self.model.data.qvel.flat[:-2], #velocities
            (self.get_body_com('fingertip') - self.get_body_com("target"))[:2] # distance from goal
        ])

    def get_reward(self, obs, next_obs, action):
        vec = next_obs[:, -2:]
        reward_dist = -np.linalg.norm(vec, axis=1)
        reward_ctrl = -np.sum(np.square(action), axis=1)
        reward = reward_dist + self.penalty_ctrl * reward_ctrl
        return reward

    @overrides
    def reset(self, init_state=None, reset_args=None, **kwargs):
        """
        resets the environment and returns the initial observation
        :param init_state: initial state -> joint angles
        :param reset_args: dicts containing a randomized parameter set for altering the mujoco model params
                         if None, a new set of model params is sampled
        :return: initial observation
        """

        if self.init_geom_size is None:
            self._save_initial_config()

        # The first time reset is called -> sample and fix the mujoco parameters
        if self.fix_params and not self.parameters_already_fixed:
            self.sample_and_fix_parameters()

        if self.fix_params and reset_args is not None:
            warnings.warn("Environment parameters are fixed - reset_ars does not have any effect", UserWarning)

        # set mujoco model parameters
        elif (not self.fix_params) and (reset_args is not None):
            self.reset_mujoco_parameters(reset_args)
        elif not self.fix_params:
            # sample parameter set
            reset_args = self.sample_env_params(1)[0]
            self.reset_mujoco_parameters(reset_args)

        self.reset_mujoco(init_state)
        self.model.forward()
        self.current_com = self.model.data.com_subtree[0]
        self.dcom = np.zeros_like(self.current_com)
        return self.get_current_obs()

    def sample_env_params(self, num_param_sets, log_scale_limit=None):
        """
              generates randomized parameter sets for the mujoco env
              :param num_param_sets: number of parameter sets to obtain
              :param log_scale_limit: lower / upper limit for uniform sampling in logspace of base 2
              :return: array of length num_param_sets with dicts containing a randomized parameter set
              """
        assert hasattr(self, 'random_state'), "random_state must be set in the constructor"

        if log_scale_limit is None:
            log_scale_limit = self.log_scale_limit

        param_sets=[]

        for _ in range(num_param_sets):

            new_params = {}

            geom_size = self.init_geom_size.copy()
            body_pos = self.init_body_pos.copy()
            geom_pos = self.init_geom_pos.copy()
            links = self.random_state.choice([0, 1, 2, 3, 4], size=2, replace=False)
            links.sort()
            for link in links:
                geom_idx = self.model.geom_names.index('link' + str(link))
                body_son_idx = self.model.body_names.index('body' + str(link)) + 1

                size_multiplier = np.array(2.0) ** self.random_state.uniform(-log_scale_limit, log_scale_limit)
                normal_size = self.init_geom_size[geom_idx][1]
                size = size_multiplier * normal_size
                geom_size[geom_idx][1] = size
                body_pos[body_son_idx][0] = 2 * size
                geom_pos[geom_idx][0] = size
            new_params['geom_size'] = geom_size
            new_params['body_pos'] = body_pos
            new_params['geom_pos'] = geom_pos

            param_sets.append(new_params)

        return param_sets

    def _save_initial_config(self):
        self.init_geom_size = self.model.geom_size.copy()
        self.init_body_pos = self.model.body_pos.copy()
        self.init_geom_pos = self.model.geom_pos.copy()

if __name__ == "__main__":

    env = Reacher5DofEnvRandParams(log_scale_limit=1.0, fix_params=False)
    env.reset()
    for _ in range(100):
        env.render()
        env.step(env.action_space.sample())  # take a random action

    env.reset()
    for _ in range(100):
        env.render()
        env.step(env.action_space.sample())  # take a random action


#
# @lc app=leetcode.cn id=53 lang=python3
#
# [53] 最大子数组和
#

# @lc code=start
class Solution:
    def maxSubArray(self, nums: List[int]) -> int:
        # 定义状态
        # dp[i]以当前元素结尾的连续子数组的最大和
        dp = []
        dp.append(nums[0])
        max_num = nums[0]
        for i in range(1,len(nums)):
            num = max(dp[i-1]+nums[i],nums[i])
            dp.append(num)
            max_num = max(max_num,num)
        return max_num

# @lc code=end

53.最大子数组和.py


import importlib
import sys

class LoadModule:

    def __init__(self, module_folder : str ='/path/to/my/models/'):
        """
        Load module folder and whatever modules in it
        """

        self.module_folder = module_folder

        # import module folder
        sys.path.insert(0, self.module_folder)

    def import_module(self, module : str):
        """
        Import modulefrom module foldder
        """
        module = __import__(module)

        return module

    def import_class(self, model : str, module : str = None, **kwargs):
        """
        Import a class from a module
        **kwargs : kwargs to load class directly if wished
        """

        # if module not given module name is same as class
        if module is None:
            module = model

        module = self.import_module(module)

        model = getattr(module, model)
        if kwargs:
            return model(**kwargs)

        else:
            return model

if __name__ == "__main__":    # how to use this
    model_name = 'my_model' # Name of the script containing the class as well as the class (if different names then specify "module" also)
    models_path = '/path/to/my/models/' # path to the folder containing the model modules(s)
    load_models = LoadModule.LoadModule(models_path)

    kwargs_model = {'arg1' : True } # kwargs for modelt
    model = load_models.import_class(model_name, **kwargs_model)


import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(-3,3,100)
y = np.sin(x)

fig = plt.figure()
ax = fig.add_subplot(111)

plt.plot(x,y)
plt.plot(y,x)
plt.xlim(-3,3)
plt.ylim(-3,3)

ax.set_aspect('equal', adjustable='box')

plt.xlabel("x")
plt.ylabel("sinx")

plt.show()


#!/usr/bin/env python
# Script: Script reads BPM parameters from FG screen
# Author: M.Fedurin, T.Morris 06/24/2022

# Version: 0.0
# Last Update: 2022/07/11 (M.Fedurin, Lines:198,207,209,252 "tol" changed to 1e+1)

# Notes:

import time
#import atf_db  #for ATF database operations
import atf_db_py3x as atf_db
import datetime
import pandas as pd
import numpy as np

#import pyvisa
#import numpy as np

host_name = '172.16.82.101'
port_name = 1505

atf_db.host_connect(host_name,port_name)  # Generate socket

print("version of Mon 27 Jun 2022 03:47:41 PM EDT ")

def ReadLaserEnergy():

    LaserEnergy = atf_db.get_real(atf_db.get_channel_index("RT_DATABASE::JOULE;RLE;LASER_ENERGY"))
    return LaserEnergy

def WriteLaserEnergy(a):
    stra = str(a)
    atf_db.put_real(atf_db.get_channel_index("NEWPORT_DB::YAG_INTENSITY;DESIRED_MOVEMENT_NATIVE_UNITS"), a)
#    atf_db.put_real(AtfDB.getchix("NEWPORT_DB::YAG_INTENSITY;DESIRED_MOVEMENT_NATIVE_UNITS"), '+5')
#do i need time in between here?
    atf_db.put_binary(atf_db.get_channel_index("NEWPORT_DB::YAG_INTENSITY;START_STOP_MOTION_CTRL"),"START")
    time.sleep(3)

LaserEnergyRead = ReadLaserEnergy()

print(" ")
print("Laser Energy = ", LaserEnergyRead)
print(" ")

fgN=3

def CameraSwitchFG3(POPN):
	atf_db.put_integer(atf_db.get_channel_index("RT_DATABASE::VID_SWITCH;CMM;VID_MON_03_MUX"),POPN)
	time.sleep(1)

def MovePOPIN(POPN,Direction):
	atf_db.put_binary(atf_db.get_channel_index("RT_DATABASE::POPCTL" + POPN + ";CPU;CTL_REQ_POP_UP_CKT_"+ POPN),Direction)

def GetPOPIN(POPN):
	return atf_db.get_binary(atf_db.get_channel_index("RT_DATABASE::POPCTL" + POPN + ";RPU;RDBK_REQ_POP_UP_CKT_"+ POPN))

# POPINLIST = [POPIN_NAME, POIPIN_#, POPIN_CAM_#],[]]
POPINLIST = [['LTR','21','6'],['LPOP1','11','2'],['HPOP1','18','4'],['HPOP2','14','75'],['CHIC_UP','36','54'],['CHIC_DOWN','36','55'],['HPOP3','13','24'],['HPOP4','12','5'],['HPOP5','38','76'],['HPOP6','39','77']]

pop_in_dict = {}

for name, n_pop, n_cam in POPINLIST:

	pop_in_dict[name] = {}
	pop_in_dict[name]['n_pop'] = n_pop
	pop_in_dict[name]['n_cam'] = n_cam

def pop_and_switch(name):

	MovePOPIN(pop_in_dict[name]['n_pop'], 'INSERT')
	CameraSwitchFG3(pop_in_dict[name]['n_cam'])

	for _name, d in pop_in_dict.items():

		if _name == name: continue

		if GetPOPIN(d['n_pop']) == "'INSERT'":

			print(f'retracting {_name}...')
			MovePOPIN(d['n_pop'], 'RETRACT')

	print(f'inserting {name}...')
	time.sleep(1)

def ReadFG(fgN):
   fgname = "FRAME" + str(fgN) + "_DB::FGR" + str(fgN) + ";"
   xpos = atf_db.get_real(atf_db.get_channel_index(fgname+"RCX;CENTROID_X"))
   ypos = atf_db.get_real(atf_db.get_channel_index(fgname+"RCY;CENTROID_Y"))
   xsig = atf_db.get_real(atf_db.get_channel_index(fgname+"RSX;SIGMA_X"))
   ysig = atf_db.get_real(atf_db.get_channel_index(fgname+"RSY;SIGMA_Y"))
#   pixsum = atf_db.get_real(atf_db.get_channel_index(fgname +"RM00;SUM_PIXELS"))
   return [xpos,ypos,xsig,ysig]

def StopFGSavePicRunFG(fgN,FullPathFileName):
   fgname = "FRAME" + str(fgN) + "_DB::FGR" + str(fgN) + ";"
   ReadButtonStatus = atf_db.get_binary(atf_db.get_channel_index(fgname+"RRS;RUN_STOP_READBACK"))
   print('FG'+str(fgN)+' is at: '+str(ReadButtonStatus))
   time.sleep(1)
   PushButton = atf_db.put_binary(atf_db.get_channel_index(fgname+"CRS;RUN_STOP_CONTROL"),"STOP")
   time.sleep(1)
   ReadButtonStatus = atf_db.get_binary(atf_db.get_channel_index(fgname+"RRS;RUN_STOP_READBACK"))
   print('FG'+str(fgN)+' is now : '+str(ReadButtonStatus))
   FileNameLog = atf_db.put_string(atf_db.get_channel_index(fgname+"CIFN;IMAGE_FILE_NAME"),FullPathFileName)
   time.sleep(1)
   PushButtonSave = atf_db.put_binary(atf_db.get_channel_index(fgname+"CSIF;SAVE_IMAGE_FILE_CTRL"),'SAVING')
   time.sleep(3)
   PushButton = atf_db.put_binary(atf_db.get_channel_index(fgname+"CRS;RUN_STOP_CONTROL"),"RUN")
   time.sleep(1)

# *~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~* VaryCurrent PART START *~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*

def PSCurrentReadSet(ChannelName,db=''):

	return atf_db.get_real(atf_db.get_channel_index(f'{db}::' + str(ChannelName) + ";CDS;SET_CURRENT_SETPT"))

def PSCurrentSet(ChannelName,CurrentSet,db=''):

	atf_db.put_real(atf_db.get_channel_index(f'{db}::' + str(ChannelName) + ";CDS;SET_CURRENT_SETPT"),CurrentSet)

def PSCurrentRead(ChannelName,db='abc'):

    return atf_db.get_real(atf_db.get_channel_index(f"{db}::" + str(ChannelName) + ";RAS;RB_CURRENT_SETPT"))

# *~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~* VaryCurrent PART START *~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*

channel_names_full_Hline = { 'HPOP1' : { "LT1HX" : "CAEN3",
	         	     "LT1VX" : "CAEN2",
	         	     "LT2HX" : "CAEN1",
	         		"LT2VX" : "CAEN4",
		 		 "TK1H" : "CAEN13",
	          	   	 "TK1V" : "CAEN14",
	         		 "TK2H" : "CAEN15",
	          		 "TK2V" : "CAEN16",
 		  		 "TK3H" : "CAEN17",
	          		 "TK3V" : "CAEN18"},

		 'HPOP2' : { "HT1HX" : "DARL1",
	        	     "HT1VX" : "DARL2",
	       			 "HT2HX" : "DARL3",
	       			 "HT2VX" : "DARL4",
				  "HQ1" : "DARL149",
		                  "HQ2" : "DARL150",
				  "HQ3" : "DARL151"},

		 'HPOP3' : {},

		 'HPOP4' : { "HT3HX" : "DARL9",
	        		 "HT3VX" : "DARL10",
	         		"HT4HX" : "DARL27",
	         		"HT4VX" : "DARL28",
		  		 "HQ4" : "DARL152",
		  		 "HQ5" : "DARL153",
		  		 "HQ6" : "DARL154"},
		  'HPOP5' : {},
		  'HPOP6' : {  "HT3HX" : "DARL29",
	        		 "HT3VX" : "DARL30",
	         		"HT4HX" : "DARL31",
	         		"HT4VX" : "DARL32",
		  		 "HQ4" : "DARL155",
		  		 "HQ5" : "DARL156",
		  		 "HQ6" : "DARL157"}

	        }

channel_names = { 'HPOP2' : { "HT1HX" : "DARL1",
	        	      "HT1VX" : "DARL2",
	       			 "HT2HX" : "DARL3",
	       			 "HT2VX" : "DARL4",
				  "HQ1" : "DARL149",
		                  "HQ2" : "DARL150",
				  "HQ3" : "DARL151"},

		 'HPOP3' : {},

		 'HPOP4' : { "HT3HX" : "DARL9",
	        		 "HT3VX" : "DARL10",
	         		"HT4HX" : "DARL27",
	         		"HT4VX" : "DARL28",
		  		 "HQ4" : "DARL152",
		  		 "HQ5" : "DARL153",
		  		 "HQ6" : "DARL154"},
		  'HPOP5' : {},
		  'HPOP6' : {  "HT3HX" : "DARL29",
	        		 "HT3VX" : "DARL30",
	         		"HT4HX" : "DARL31",
	         		"HT4VX" : "DARL32",
		  		 "HQ4" : "DARL155",
		  		 "HQ5" : "DARL156",
		  		 "HQ6" : "DARL157"}

	        }

POP_list = ['HPOP1', 'HPOP2', 'HPOP3', 'HPOP4', 'HPOP5', 'HPOP6']

channel_dict = {}

dp_max  = 0.2
dp_step = 0.05

for pop, channels in channel_names.items():

	n_pop = int(pop[-1])

	for tag, name in channels.items():

		channel_dict[tag] = {}
		channel_dict[tag]['name']  = name
		channel_dict[tag]['n_pop'] = n_pop
		channel_dict[tag]['tol']   = 1e+1

		if name[:4] == 'CAEN':
			channel_dict[tag]['db'] = 'CAEN_DB'

		else:
			channel_dict[tag]['db'] = 'RT_DATABASE'

		if name[:4] == 'PTEN':
			channel_dict[tag]['tol'] = 1e+1
		if name[:4] == 'DARL':
			channel_dict[tag]['tol'] = 1e+1

		channel_dict[tag]['orig'] = PSCurrentReadSet(name, channel_dict[tag]['db']) #changed "PSCurrentRead" to "PSCurrentReadSet" ; M.Fedurin

		channel_dict[tag]['p_list'] = channel_dict[tag]['orig'] + np.arange(-dp_max, dp_max + 1e-6, dp_step)

		#print(channel_dict[tag])
		print(tag, name)

FileName = "C:/Images/AE124/20220711/2022071542_HPOP1_"

fgN=3
#

print(channel_dict)

timestamp = int(time.time())

ps_columns = list(channel_dict.keys())

Files = 'SavedFileName'

POP_cols = ['xpos', 'ypos', 'xsig', 'ysig', 'file']

metadata = pd.DataFrame(columns=['timestamp', *ps_columns, *[f'{POP}_{col}' for POP in POP_list for col in POP_cols]])

print(metadata.columns)

ps_tol = 1e-1

min_wait_time = 1e-1
max_wait_time = 2e0

def put_complete(ps, set_point, verbose=True):

	name, db = ps['name'], ps['db']

	abs_tol = np.abs(ps['tol'] * (PSCurrentReadSet(name, db) - set_point)) #changed "PSCurrentRead" to "PSCurrentReadSet" ; M.Fedurin

	PSCurrentSet(name, set_point, db)
	t0 = time.time()
	while True:
		elapsed = time.time() - t0
		if elapsed > max_wait_time: break
		if elapsed > min_wait_time:
			if np.abs(PSCurrentReadSet(name, db) - set_point) < abs_tol: #changed "PSCurrentRead" to "PSCurrentReadSet" ; M.Fedurin
				break
			#print(PSCurrentReadSet(name, db), set_point, db)
		time.sleep(1e-1)
	t1 = time.time()
	if verbose: print(f'set {name} to {set_point:.03e} +/- {abs_tol:.01e} ({PSCurrentRead(name, db):.03e}) in {1e3*(t1-t0):.00f}ms')

from datetime import datetime

now = datetime.now()

print(metadata.columns)

dirname = f"C:/Images/AE124/{now.year}{now.month:>02}{now.day:>02}/"

POP_metadata = {}

for POP in POP_list:

	n_pop = int(POP[-1])

	pop_and_switch(POP)

	#POP_metadata[POP] = metadata.copy()

	#scan_id = 0

	for tag, ps in channel_dict.items():

		if not ps['n_pop'] == n_pop: continue

		for p in ps['p_list']:

			scan_id = len(metadata)

			put_complete(ps, p)

			filetimestamp = int(time.time())

			filename = f'{filetimestamp}_{POP}.asc'

			StopFGSavePicRunFG(3, dirname + filename)

			if len(metadata) <= scan_id: metadata.loc[scan_id] = np.nan
			metadata.loc[scan_id, ['timestamp', *ps_columns]] = time.time(),*[PSCurrentReadSet(ps['name'], ps['db']) for ps in channel_dict.values()] #changed "PSCurrentRead" to "PSCurrentReadSet" ; M.Fedurin
			metadata.loc[scan_id, [f'{POP}_{col}' for col in POP_cols]] = *ReadFG(fgN), filename
			put_complete(ps, ps['orig'])
			#scan_id += 1

metadata.to_csv(f'{timestamp}.csv')

for tag, ps in channel_dict.items():

	orig = ps['orig']
	print(f'returned {tag}:{name} to {orig}')
	put_complete(ps, orig, verbose=False)

atf_db.host_disconnect()  # Close socket

print(metadata)


'''P40 (**) Goldbach's conjecture.
Goldbach's conjecture says that every positive even number greater than 2 is the sum of two prime numbers.
Example: 28 = 5 + 23. It is one of the most famous facts in number theory that has not been proved to be correct in the general case.
It has been numerically confirmed up to very large numbers (much larger than we can go with our Prolog system).
Write a predicate to find the two prime numbers that sum up to a given even integer.
Example:
* (goldbach 28)
(5 23)'''

#function to check if a nummber is prime
def check_prime(num):
    for i in range(2, num):
        if num % i == 0:                #check if the required number is prime
            return 0                #0 indicates number is not prime
    return 1

number = int(input('Please enter any even number = '))

#function to get two prime numbers that adds up to get a even number
def goldbach(num):
    if num % 2 == 0:                         #check if number is even
        for first in range(2, num):                      #check if any number upto that number is prime,
            if check_prime(first) == 1:                  #if so,grab it as the first prime number,
                second = num - first                                  #the original number minus the prime number will give the second number,
                if check_prime(second) == 1:                 #but check if the 2nd number is prime or not
                    return first, second                              #if yes,return both the numbers
    else:
        return ('Not an even number !')

left,right = goldbach(number)                           #call the goldbach function and catch two prime numbers
print(f'{number} = {left} + {right}')


from pymongo import MongoClient
from jnturesultscrap import JNTUResult
import time
import tqdm
examCode = "1502"
mongo_url = "REDCATED"

mongo_client = MongoClient(mongo_url)
db = mongo_client['jnturesults']['jnturesult']

def sendrolltodb(rollNo):
    jr = JNTUResult(rollNo, examCode)
    jrmethod = jr.recursiveGet()
    result = jrmethod['result']

    try:
        SGPA = jrmethod['sgpa']
    except Exception as e:
        SGPA = "Coudn't Calculate due to > " + str(e)

    resultWithSGPA = {
                'unique': str(rollNo+examCode),
                'rollno': str(rollNo),
                'examcode': str(examCode),
                'result': result,
                'sgpa': SGPA,
                'usr': jrmethod['user']
            }
    if(type(resultWithSGPA['sgpa']) == float or type(resultWithSGPA['sgpa']) == int):
                db.insert_one(resultWithSGPA)

base_id = "18"
clg_id = "32"
some = "1A0"
branches = [4,5]
expanders = "0123456789ABCDEF"
final = range(1,10)

rolls = []
for branch in branches:
    for tenth in expanders:
        for units in final:
            rollNN = f"{base_id}{clg_id}{some}{branch}{tenth}{units}"
            rolls.append(rollNN)

for roll in tqdm.tqdm(rolls):
    try:
        sendrolltodb(roll)
        time.sleep(0.1)
    except Exception as e:
        print("Not added due to " + str(e) + " "+ str(roll) + " " + str(len(roll)))


from Tkinter import *
root=Tk()
root.title("Labeler")
root.geometry("200x100")
app=Frame(root)
app.grid()
button1=Button(app,text="This is a button")
button1.grid()
button2=Button(app)
button2.grid()
button2.configure(text="this will show text")
button3=Button(app)
button3.grid()
button3["text"]="this will show up as well."

root.mainloop()


import subprocess
import time
import pymongo

SMALL_SAMPLE_PATH = "./tests/utils/small_sample.mind.gz"

def run_subprocess(command):
    command = [x for x in command.split(" ")]
    process = subprocess.Popen(command,
                               stdout=subprocess.PIPE,
                               stderr=subprocess.PIPE,
                               close_fds=True)
    return process

def test_end_to_end():
    # Clearing the db:
    client = pymongo.MongoClient('mongodb://localhost:27017')
    client.drop_database('db')

    # Starting to run services:
    saver_process = run_subprocess("python -m brain_freeze.saver run-saver "
                                   "mongodb://127.0.0.1:27017 "
                                   "rabbitmq://127.0.0.1:5672/")
    time.sleep(1)
    pose_process = run_subprocess("python -m brain_freeze.parsers run-parser "
                                  "pose rabbitmq://127.0.0.1:5672/")
    time.sleep(1)
    feelings_process = run_subprocess("python -m brain_freeze.parsers "
                                      "run-parser feelings "
                                      "rabbitmq://127.0.0.1:5672/")
    time.sleep(1)
    color_process = run_subprocess("python -m brain_freeze.parsers run-parser "
                                   "color_image rabbitmq://127.0.0.1:5672/")
    time.sleep(1)
    server_process = run_subprocess("python -m brain_freeze.server run-server"
                                    " rabbitmq://127.0.0.1:5672/")
    time.sleep(5)
    # Running the client:
    client_process = run_subprocess("python -m brain_freeze.client "
                                    "upload_sample " + SMALL_SAMPLE_PATH)
    time.sleep(350)

    # Running the api and cli:
    api_process = run_subprocess("python -m brain_freeze.api run-server")
    time.sleep(5)
    cli_users_process = run_subprocess("python -m brain_freeze.cli get-users")
    time.sleep(5)
    cli_user_process = run_subprocess("python -m brain_freeze.cli get-user 42")
    time.sleep(5)
    cli_snapshots_process = run_subprocess("python -m brain_freeze.cli "
                                           "get-snapshots 42")
    time.sleep(5)
    cli_snapshot_process = run_subprocess("python -m brain_freeze.cli "
                                          "get-snapshot 42 1575446887339")
    time.sleep(5)
    cli_pose_result_process = run_subprocess("python -m brain_freeze.cli "
                                             "get-result 42 1575446887339 "
                                             "pose")
    time.sleep(5)
    cli_feelings_result_process = run_subprocess("python -m brain_freeze.cli "
                                                 "get-result 42 1575446887339 "
                                                 "feelings")
    time.sleep(5)
    cli_color_result_process = run_subprocess("python -m brain_freeze.cli "
                                              "get-result 42 1575446887339 "
                                              "color_image")
    time.sleep(5)

    # Checking the results:
    client_process.terminate()
    saver_process.terminate()
    pose_process.terminate()
    feelings_process.terminate()
    color_process.terminate()
    server_process.terminate()
    api_process.terminate()
    out, err = client_process.communicate()
    print("client out: " + out.decode())
    print("client err: " + err.decode())
    assert client_process.returncode == 0

    out, err = server_process.communicate()
    print("server out: " + out.decode())
    print("server err: " + err.decode())

    out, err = color_process.communicate()
    print("color out: " + out.decode())
    print("color err: " + err.decode())

    out, err = pose_process.communicate()
    print("pose out: " + out.decode())
    print("pose err: " + err.decode())

    out, err = feelings_process.communicate()
    print("feelings out: " + out.decode())
    print("feelings err: " + err.decode())

    out, err = saver_process.communicate()
    print("saver out: " + out.decode())
    print("saver err: " + err.decode())

    out, err = api_process.communicate()
    print("api out: " + out.decode())
    print("api err: " + err.decode())

    out, err = cli_users_process.communicate()
    print("cli_users out: " + out.decode())
    print("cli_users err: " + err.decode())
    assert b'Dan Gittik' in out

    out, err = cli_user_process.communicate()
    print("cli_user out: " + out.decode())
    print("cli_user err: " + err.decode())
    assert b'Dan Gittik' in out

    out, err = cli_snapshots_process.communicate()
    print("cli_snapshots_process out: " + out.decode())
    print("cli_snapshots_process err: " + err.decode())
    assert b'1575446887339' in out

    out, err = cli_snapshot_process.communicate()
    print("cli_snapshot_process out: " + out.decode())
    print("cli_snapshot_process err: " + err.decode())
    assert b'pose' in out
    assert b'feelings' in out

    out, err = cli_pose_result_process.communicate()
    print("cli_pose_result_process out: " + out.decode())
    print("cli_pose_result_process err: " + err.decode())
    assert b'0.4873843491077423' in out

    out, err = cli_feelings_result_process.communicate()
    print("cli_feelings_result_process out: " + out.decode())
    print("cli_feelings_result_process err: " + err.decode())
    assert b'0.0' in out

    out, err = cli_color_result_process.communicate()
    print("cli_color_result_process out: " + out.decode())
    print("cli_color_result_process err: " + err.decode())
    assert b'color_image.jpg' in out


import random
import  time

class Kumanda():

    def __init__(self,durum="",ses=0,kanallar=["trt"],kanal= ""):

        self.durum = durum
        self.ses = ses
        self.kanallar = kanallar
        self.kanal = kanal

    def tvAc(self):
        if self.durum=="Açık":
            print("Televizyon zaten açık")
        else:
            print("Televizyon açılıyor...")
            self.durum = "Açık"
    def tvKapat(self):
        if self.durum=="Kapalı":
            print("Televizyon zaten kapalı")
        else:
            print("Televizyon kapatılıyor...")
            self.durum = "Kapalı"
    def sesAyarı(self):
        while True:
            cevap = input("1.Arrıtmak için +\n2.Azaltmak için - \n3.Çıkmak için * \nGiriş: ")
            if cevap == "-":
                if self.ses != 0:
                    self.ses -=1
                    print("Ses: ",self.ses)
            elif cevap == "+":
                if self.ses !=30:
                    self.ses += 1
                    print("Ses: ",self.ses)
            else:
                print("Ses güncellendi: ",self.ses)
                break
    def kanalEkle(self,kanal):
        print("Kanal ekleniyor...")
        time.sleep(1)
        self.kanallar.append(kanal)
        print("Kanal eklendi.")
    def rasgeleKanal(self):
        rastgele = random.randint(0,len(self.kanallar)-1)
        self.kanal = self.kanallar[rastgele]
        print("Şuanki kanal: ",self.kanal)
    def __len__(self):
        return len(self.kanallar)
    def __str__(self):
        return """
                Tv durumu: {}
                Tv ses: {}
                Tv kanal listesi: {}
                Tv kanal: {}
        """.format(self.durum,self.ses,self.kanallar,self.kanal)

print("""

    Tv Uygulaması

    1.Tv Aç
    2.Tv Kapat
    3.Ses Ayarları
    4.Kanal Ekle
    5.Kanal sayısı
    6.Rastgele Kanal
    7.Televizyon bilgileri
    8.Kumanda Ekle
    9.Kumanda Sil

    Çıkmak için * basınız.

    """)

kumanda = Kumanda()
while True:
    işlem = input("İşlem seçiniz: ")
    if işlem == "*":
        print("Uygulama kapatıldı")
        break
    elif işlem == "1":
        kumanda.tvAc()
    elif işlem == "2":
        kumanda.tvKapat()
    elif işlem=="3":
        kumanda.sesAyarı()
    elif işlem=="4":
        kanal_isimleri=input("Kanal isimlerini , ile ayırarak yazınız: ")
        kanal_listesi = kanal_isimleri.split(",")
        for eklenecekler in kanal_listesi:
            kumanda.kanalEkle(eklenecekler)
    elif işlem =="5":
        print("Kanal sayısı: ",len(kumanda))
    elif işlem =="6":
        kumanda.rasgeleKanal()
    elif işlem == "7":
        print(kumanda)
    else:
        print("Geçersiz işlem....")

PyCharm Ders/Kodlama Egzersizleri/Temel Veri Yapıları ve Objeler/kumanda_sınıfı.py


from collections import Counter
from urlextract import URLExtract
from wordcloud import WordCloud
import emoji
import pandas as pd
import emoji_data_python as emoji_data
import re

extract=URLExtract()
def fetch_stats(selected_user,df):
    if selected_user!="Overall":
        df=df[df['user']==selected_user]
    num_messages=df.shape[0]

    words=[]
    for m in df['message']:
        words.extend(m.split())
    media=df[df['message']=='<Media omitted>\n'].shape[0]

    link=[]
    for message in df['message']:
        link.extend(extract.find_urls(message))

    return num_messages,len(words),media,len(link)

def most_active_user(df):
    x=df['user'].value_counts().head()
    df=round((df['user'].value_counts()/df.shape[0])*100,2).reset_index().rename(columns={'index':'name','user':'percent'})
    return x,df

def create_wordcloud(selected_user,df):
    if selected_user!="Overall":
        df=df[df['user']==selected_user]
    wc=WordCloud(width=500,height=300,min_font_size=10,background_color='white')
    df_wc=wc.generate(df['message'].str.cat(sep=" "))
    return df_wc

def emoji(selected_user,df):
    if selected_user!="Overall":
        df=df[df['user']==selected_user]

    emojis = []
    emoji_pattern = r'[\U0001F300-\U0001F64F\U0001F680-\U0001F6FF\u2600-\u26FF\u2700-\u27BF]'
    for message in df['message']:
    # Extract emojis from the message using the regular expression pattern
        extracted_emojis = re.findall(emoji_pattern, message)
        emojis.extend(extracted_emojis)
    emoji_df = pd.DataFrame(Counter(emojis).most_common(), columns=['Emoji', 'Count'])
    return emoji_df

def montly_timeline(selected_user,df):
    if selected_user!="Overall":
        df=df[df['user']==selected_user]
    timeline=df.groupby(['year','month_num','month']).count()['message'].reset_index()
    time=[]
    for i in range(timeline.shape[0]):
        time.append(timeline['month'][i]+"-"+str(timeline['year'][i]))
    timeline['time']=time
    return timeline

def daily_timeline(selected_user,df):
    if selected_user!="Overall":
        df=df[df['user']==selected_user]
    daily_timeline=df.groupby('only_date').count()['message'].reset_index()
    return daily_timeline

def week_activity_map(selected_user,df):
    if selected_user!="Overall":
        df=df[df['user']==selected_user]
    return df['day_name'].value_counts()

def month_activity_map(selected_user,df):
    if selected_user!="Overall":
        df=df[df['user']==selected_user]
    return df['month'].value_counts()


from A1_image_filtering import cross_correlation_2d, get_gaussian_filter_2d
import cv2
from about_images import show_and_save, load_lenna, load_shape, show_and_save_mag
from computational_time import TimeModule
import numpy as np
import math

def non_maximun_suppression_dir(mag, dir):
    dir = np.rad2deg(dir) + 180
    window_size = 3
    term = window_size//2
    output = mag.copy()

    for i in range(term, mag.shape[0]-term):
        for j in range(term, mag.shape[1]-term):
            angle = dir[i,j]

            if ((0 <= angle <= 22.5) or (337.5 < angle <= 360)) or (157.5 < angle <= 202.5) :
                if mag[i,j] <= mag[i,j+1] or mag[i,j] < mag[i,j-1]:
                    output[i,j] = 0

            elif (22.5 < angle <= 67.5) or (202.5< angle <= 247.5):
                if mag[i,j] < mag[i-1,j-1] or mag[i,j] <= mag[i+1,j+1]:
                    output[i,j] = 0

            elif (67.5 < angle <= 112.5) or (247.5< angle <= 292.5):
                if mag[i,j] <=  mag[i+1,j] or mag[i,j] < mag[i-1,j]:
                    output[i,j] = 0

            elif (112.5< angle <= 157.5) or (292.5< angle <= 337.5):
                if mag[i,j] <= mag[i-1,j+1] or mag[i,j] < mag[i+1,j-1]:
                    output[i,j] = 0
    output = np.where(output<0, 0, output)
    output = np.where(output>255, 255, output)
    return output

def compute_image_gradient(img):
    S_x = np.array([[-1,0,1],
                    [-2,0,2],
                    [-1,0,1]])
    S_y = S_x.T
    sobel_x = cross_correlation_2d(img, S_x)
    sobel_y = cross_correlation_2d(img, S_y)

    direction = np.arctan2(sobel_y, sobel_x)
    magnitude = np.hypot(sobel_x, sobel_y)

    return magnitude, direction

if __name__ == "__main__":

    img_shape = load_shape()
    img_lenna = load_lenna()

    gaussian_filter = get_gaussian_filter_2d(7, 1.5)
    filtered_shape = cross_correlation_2d(img_shape, gaussian_filter)
    filtered_lenna = cross_correlation_2d(img_lenna, gaussian_filter)

    t = TimeModule()
    mag_lenna, dir_lenna = compute_image_gradient(filtered_lenna)
    t.end_print("image gradient lenna")
    show_and_save_mag(mag_lenna, "part_2_edge_raw_lenna")

    t = TimeModule()
    mag_shapes, dir_shapes = compute_image_gradient(filtered_shape)
    t.end_print("image gradient shapes")
    show_and_save_mag(mag_shapes, "part_2_edge_raw_shapes")

    t = TimeModule()
    nms_lenna = non_maximun_suppression_dir(mag_lenna, dir_lenna)
    t.end_print("nms shapes")
    show_and_save(nms_lenna, "part_2_edge_sup_lenna")

    t = TimeModule()
    nms_shape = non_maximun_suppression_dir(mag_shapes, dir_shapes)
    t.end_print("ms shapes")
    show_and_save(nms_shape, "part_2_edge_sup_shapes")


class Solution:
    def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:
        # binary search
        '''
        偶数个：找到最中间的两个index相加除二即可
        奇数个：直接找最中间的值
        由于两个都是排序过的
        所以可以用binary search来寻找

        1
        如果先不用binary search加速
        时间复杂度：O(m+n)

        先找出要找的index是哪个或是哪两个，
        再去找左右两边即可
        '''

        total_len = len(nums1) + len(nums2)
        target = (total_len) // 2 # 如果total_len%2 == 0，则要再多找一个
        found = []
        count = 0
        i = j = 0

        # 直接多找一个
        while count <= target:
            if i < len(nums1) and j < len(nums2):
                if nums1[i] < nums2[j]:
                    found.append(nums1[i])
                    i += 1
                else:
                    found.append(nums2[j])
                    j += 1
            elif i < len(nums1):
                found.append(nums1[i])
                i += 1
            else:
                found.append(nums2[j])
                j += 1

            count += 1

        if total_len % 2 == 0:
            return (found[-1]+found[-2]) / 2
        else:
            return found[-1]


#---------------------------------------------------------sandwhich--------------------------------------------------------
selectedsandwhich = ""
beveragesize = ""
frenchfrysize = ""

sandwhichlist = ["a", "b", "c"]
total = 0.00
selectedsandwhich = (input("What type of sandwhich would you like?\na) Chicken Sandwhich-$5.25\nb) Beef Sandwhich-$6.25\nc) Tofu Sandwhich-$5.75\n")).lower()
while selectedsandwhich not in sandwhichlist:
    selectedsandwhich = (input("Please select a, b, or c: ")).lower()

if selectedsandwhich == "a":
  print("You selected Chicken Sandwhich\nYour current total is: $5.25")
  total = 5.25
elif selectedsandwhich == "b":
  print("You selected Beef Sandwhich\nYour current total is: $6.25")
  total = 6.25
else:
  print("You selected Tofu Sandwhich\nYour current total is: $5.75")
  total = 5.75
#---------------------------------------------------------beverages--------------------------------------------------------
beverage = (input("Would you like a beverage? Yes/No: ")).lower()
choice = ["yes","no"]
while beverage.lower() not in choice:
  beverage = (input("Please answer yes or no: ")).lower()

if beverage == "yes":
  beveragesizelist = ["small", "medium","large"]
  beveragesize=(input("What size beverage would you like?\nsmall-$1.00\nmedium-$1.75\nlarge-$2.25\n")).lower()
  while beveragesize.lower() not in beveragesizelist:
    beveragesize = input("Please select small, medium or large: ").lower()
  if beveragesize =="small":
    total = total + 1
    print(f"You selected small\n\nYour current total is ${total:.2f}\n")
  elif beveragesize =="medium":
   total = total + 1.75
   print(f"You selected medium\n\nYour current total is ${total:.2f}\n")
  else:
    total = total + 2.25
    print(f"You selected large\n\nYour current total is ${total:.2f}\n")
#---------------------------------------------------------frenchfries------------------------------------------------------
frenchfrysizelist =["small","medium","large"]
frenchfries= (input("Would you like french fries? Yes/No: ")).lower()
while frenchfries not in choice:
  frenchfries = (input("Please answer yes or no: ")).lower()

if frenchfries == "yes":
  frenchfrysize =(input("What size french fries would you like?\nsmall-$1.00\nmedium-$1.50\nlarge-$2.00\n")).lower()
  while frenchfrysize not in frenchfrysizelist:
    frenchfrysize = input("Please select small, medium or large").lower()
  if frenchfrysize == "small":
    megasize=(input("Would you like to megasize your fries? Yes/No: ")).lower()
    while megasize not in choice:
      megasize=(input("Please enter yes or no: ")).lower()
    if megasize =="no":
      total = total + 1
      print(f"\nYou selected small\n\nYour current total is ${total:.2f}\n")
    else:
      total = total + 2
      print(f"\nYou selected megasize\n\nYour current total is ${total:.2f}\n")

  elif frenchfrysize == "medium":
    total = total + 1.50
    print(f"You selected medium\n\nYour current total is ${total:.2f}\n")
  else:
    total = total + 2
    print(f"You selected large\n\nYour current total is ${total:.2f}\n")
#--------------------------------------------------------ketchup-------------------------------------------------------------
ketchupnum = input("How many keptchup packets would you like?\n")
while not ketchupnum.isnumeric():
  ketchupnum = input("Please enter a whole number greater than or equal to zero.\n")
if int(ketchupnum) >= 0:
  total = total + 0.25 * int(ketchupnum)

if selectedsandwhich != "" and beveragesize != "" and frenchfrysize != "":
  total = total - 1
  print("Because you selected a Sandwhich, French Fries and a Drink, you recieve a $1.00 discount\n")
print(f"Your final total is ${total:.2f}")


def calculator(sticker):
    if sticker[0] > sticker[1]:
        dp = [sticker[0], sticker[0]]
    else:
        dp = [sticker[0], sticker[1]]
    for i in range(2,len(sticker)):
        dp.append(max(dp[i-1], dp[i-2]+sticker[i]))
    # print(dp)
    return dp[-1]

def solution(sticker):

    if len(sticker) < 4:
        return max(sticker)

    sticker_a = sticker[:-1]
    sticker_b = sticker[1:]
    answer = max(calculator(sticker_a), calculator(sticker_b))

    return answer

def main():
    print(solution([14, 24, 5, 11, 20]))

if __name__ == "__main__":
    main()


import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
import numpy as np

FILE_NAME = 'record.txt'
SMOOTH_EPISODE = 1000

if __name__ == '__main__':
    plt.clf()
    plt.xlabel('eposide')
    plt.ylabel('score')
    plt.xlim(-1000, 11000)
    plt.ylim(-100, 2000)
    plt.grid(True)
    with open(FILE_NAME, 'r') as f:
        content = f.readlines()

    x = []
    y = []
    means = []
    tmp_value = []
    mean_idx = 0
    idx = 0
    for c in content:
        if idx > 10000:
            break
        idx += 1
        c_list = c.split(' ')
        x.append(c_list[0])
        yvalue = int(c_list[1].split('\n')[0])
        y.append(yvalue)

        tmp_value.append(yvalue)
        mean_idx += 1

        if (mean_idx % SMOOTH_EPISODE == 0 and mean_idx != 0) or mean_idx == (len(content) - 1):
            means.append(np.mean(tmp_value))
            tmp_value = []

    mean_x_idx = [_ * SMOOTH_EPISODE for _ in range(1, len(means) + 1)]
    plt.plot(mean_x_idx, means, c='#F39019', linewidth='3')
    plt.scatter(x, y, c='#51A7F9', marker='o', s=15, alpha=0.9)
    plt.savefig(FILE_NAME.split('.')[0] + '.pdf', format='pdf', bbox_inches='tight')

    plt.show()
    plt.close()


from django.urls import path
from . import views

app_name = 'community'

urlpatterns = [
    path('', views.index, name='index'),
    path('notice/', views.notice, name='notice'),
    path('help/', views.help, name='help'),
    path('info/', views.info, name='info'),
    path('marvel/', views.marvel, name='marvel'),
    path('korean/', views.korean, name='korean'),
    path('nolan/', views.nolan, name='nolan'),
    path('tarantino/', views.tarantino, name='tarantino'),
    path('create/', views.create, name='create'),
    path('<int:article_pk>/', views.detail, name='detail'),
    path('<int:article_pk>/comments/', views.create_comment, name='create_comment'),
    path('<int:article_pk>/like/', views.like, name='like'),
]


"""
Killing KILL_REQUIREMENT other players in under TIME_REQUIREMENT seconds
sends you into a rampage lasting RAMPAGE_DURATION seconds.
The rampage refills and drastically increases your weapons' rate of fire.

By default this means 3 kills in under 8 seconds to activate. For reference,
lines disappear from the killfeed 10 seconds after they appear.

Intended for use in frantic last team standing or free for all matches.

.. codeauthor:: hompy
"""

from collections import deque
from twisted.internet.reactor import callLater, seconds
from twisted.internet.task import LoopingCall
from pyspades import contained as loaders
from pyspades.common import make_color
from pyspades.constants import (
    GRENADE_KILL, RIFLE_WEAPON, SMG_WEAPON, SHOTGUN_WEAPON)

KILL_REQUIREMENT = 3
TIME_REQUIREMENT = 8.0
GRENADE_KILLS_COUNT = True
RAMPAGE_REFILLS = True
RAMPAGE_RELOADS = True
RAMPAGE_DURATION = 20.0
RAPID_INTERVALS = {
    RIFLE_WEAPON: 0.16,
    SMG_WEAPON: 0.08,
    SHOTGUN_WEAPON: 0.18
}
RAMPAGE_FOG_COLOR = (255, 0, 0)

def RAMPAGE_FOG_FUNC():
    return RAMPAGE_FOG_COLOR

ANNOUNCE_RAMPAGE = True
S_RAMPAGE_START = '{player} IS ON A RAMPAGE!!'
S_RAMPAGE_KILLED = "{victim}'s rampage was ended by {killer}"

def resend_tool(player):
    set_tool = loaders.SetTool()
    set_tool.player_id = player.player_id
    set_tool.value = player.tool
    if player.weapon_object.shoot:
        player.protocol.broadcast_contained(set_tool)
    else:
        player.send_contained(set_tool)

def rapid_cycle(player):
    resend_tool(player)
    if not player.weapon_object.shoot:
        player.rampage_rapid_loop.stop()

def send_fog(player, color):
    fog_color = loaders.FogColor()
    fog_color.color = make_color(*color)
    player.send_contained(fog_color)

def fog_switch(player, colorgetter_a, colorgetter_b):
    if player.rampage:
        send_fog(player, colorgetter_a())
        player.rampage_warning_call = callLater(0.5, fog_switch, player,
                                                colorgetter_b, colorgetter_a)

def apply_script(protocol, connection, config):
    class RampageConnection(connection):
        rampage = False
        rampage_rapid_loop = None
        rampage_call = None
        rampage_warning_call = None
        rampage_kills = None
        rampage_reenable_rapid_hack_detect = None

        def start_rampage(self):
            self.rampage = True
            self.rampage_kills.clear()
            self.rampage_reenable_rapid_hack_detect = self.rapid_hack_detect
            self.rapid_hack_detect = False
            self.rampage_call = callLater(RAMPAGE_DURATION, self.end_rampage)
            if RAMPAGE_DURATION > 4.0:
                self.rampage_warning_call = callLater(
                    RAMPAGE_DURATION - 3.0,
                    fog_switch,
                    self,
                    self.protocol.get_fog_color,
                    RAMPAGE_FOG_FUNC)
            if RAMPAGE_REFILLS:
                self.refill()
            if RAMPAGE_RELOADS:
                weapon = self.weapon_object
                was_shooting = weapon.shoot
                weapon.reset()
                weapon_reload = loaders.WeaponReload()
                weapon_reload.player_id = self.player_id
                weapon_reload.clip_ammo = weapon.current_ammo
                weapon_reload.reserve_ammo = weapon.current_stock
                weapon.set_shoot(was_shooting)
                self.send_contained(weapon_reload)
            send_fog(self, RAMPAGE_FOG_COLOR)
            if ANNOUNCE_RAMPAGE:
                message = S_RAMPAGE_START.format(player=self.name)
                self.protocol.broadcast_chat(message, global_message=None)

        def end_rampage(self):
            self.rampage = False
            self.rapid_hack_detect = self.rampage_reenable_rapid_hack_detect
            if self.rampage_call and self.rampage_call.active():
                self.rampage_call.cancel()
            self.rampage_call = None
            if (self.rampage_warning_call and
                    self.rampage_warning_call.active()):
                self.rampage_warning_call.cancel()
            self.rampage_warning_call = None
            if self.rampage_rapid_loop and self.rampage_rapid_loop.running:
                self.rampage_rapid_loop.stop()
            send_fog(self, self.protocol.fog_color)

        def on_connect(self):
            self.rampage_rapid_loop = LoopingCall(rapid_cycle, self)
            self.rampage_kills = deque(maxlen=KILL_REQUIREMENT)
            connection.on_connect(self)

        def on_disconnect(self):
            if self.rampage:
                self.end_rampage()
            self.rampage_rapid_loop = None
            connection.on_disconnect(self)

        def on_reset(self):
            if self.rampage:
                self.end_rampage()
            connection.on_reset(self)

        def on_kill(self, killer, type, grenade):
            was_rampaging = self.rampage
            if self.rampage:
                self.end_rampage()
            if killer is not None and killer is not self:
                if was_rampaging and ANNOUNCE_RAMPAGE:
                    message = S_RAMPAGE_KILLED.format(victim=self.name,
                                                      killer=killer.name)
                    self.protocol.broadcast_chat(message, global_message=None)
                if (not killer.rampage and killer.hp and
                    killer.team is not self.team and
                        (GRENADE_KILLS_COUNT or type != GRENADE_KILL)):
                    now = seconds()
                    killer.rampage_kills.append(now)
                    if (len(killer.rampage_kills) == KILL_REQUIREMENT and
                            killer.rampage_kills[0] >= now - TIME_REQUIREMENT):
                        killer.start_rampage()
            return connection.on_kill(self, killer, type, grenade)

        def on_grenade_thrown(self, grenade):
            if self.rampage:
                resend_tool(self)
            connection.on_grenade_thrown(self, grenade)

        def on_shoot_set(self, fire):
            if (self.rampage and fire and
                self.rampage_rapid_loop and
                    not self.rampage_rapid_loop.running):
                interval = RAPID_INTERVALS[self.weapon]
                self.rampage_rapid_loop.start(interval, now=False)
            connection.on_shoot_set(self, fire)

    def send_fog_rule(player):
        return not player.rampage

    class RampageProtocol(protocol):

        def set_fog_color(self, color):
            self.fog_color = color
            fog_color = loaders.FogColor()
            fog_color.color = make_color(*color)
            self.broadcast_contained(fog_color, save=True, rule=send_fog_rule)

    return RampageProtocol, RampageConnection


#usr/bin/env/python
'''
Author  : Bhekimpilo Ndhlela
Author  : 18998712
module  : TW244 Applied Mathematics
task    : Assignment 01 problem2
since   : Saturday-28-07-2018
'''

from numpy import (linspace, array, zeros)
import matplotlib.pyplot as plt
from sys import exit

def plot_functions():

    X = linspace(0, 2.5, 100)
    y = array([ p**3 - 4*(p**2) +4*p for p in X])
    plt.subplot(211)
    plt.title('Plot of function f\'(x)')
    plt.xlabel('x = linspace(0, 2.5, 1000)')
    plt.ylabel('f(x)')
    plt.plot(X, y, '-r', linewidth=4)

    plt.subplot(212)
    X = linspace(0, 2.5, 100)
    y = array([ p*(p-2)**3 * (3*p - 2) for p in X])
    plt.title('Plot of function f\'\'(x)')
    plt.xlabel('x = linspace(0, 2.5, 1000)')
    plt.ylabel('f(x)')
    plt.plot(X, zeros(len(X)), '-k', linewidth=2)
    plt.plot(X, y, '-r', linewidth=4)
    plt.show()

plot_functions()


"""
FUNCIONES:
Una funcion es un conjunto de instrucciones agrupadas bajo un nombre
concreto que pueden reutilizarse invocando a la funcion
tantas veces como sea posible.

def nameMyfuncion(parametros):
    # Bloque / conjunto de instrucciones

nameMyfuncion(mi_parametro)
nameMyfuncion(mi_parametro)
"""
# Ejemplo 1
print("####### EJEMPLO 1 ########")

# Definir funcion
def muestraNombres():
    print("Daniel")
    print("Paco")
    print("elsa")
    print("Thor")
    print("Nestro")
    print("Pipe")
    print("Felipe")
    print("\n")

# Invocar funcion
muestraNombres()
muestraNombres()
muestraNombres()
#--------------------
# EJjemplo 2: Parametros
# Un dato que le paso desde afuera hacia la funcion, para poder parametrizar
print("####### EJEMPLO 2 ########")
"""
def mostrarTuNombre(nombre,edad):
    print(f"Tu nombre es: {nombre}")

    if edad >= 18:
        print("Y eres mayor de edad")

nombre = input("Introduce tu nombre: ")
edad = int(input("Introduce tu edad: "))
#mostrarTuNombre("Jose Peres")
#mostrarTuNombre("PAquito")
#mostrarTuNombre("Juanfran")
#mostrarTuNombre(nombre,9) # esta es un dato fijo
mostrarTuNombre(nombre,edad)
"""
#---------------------
# Ejemplo 3
print("####### EJEMPLO 3 ########")
def tabla(numero):
    print(f"Tabla de multiplicar del numero: {numero}")
    for contador in range (11):
        operacion = numero *contador
        print(f"{numero} * {contador} = {operacion}")

    print("\n")

tabla(3)
tabla(7)
tabla(12)
# Ejemplo 3.1
# sacando todas las tablas de multiplicar utilizandoo esta funcion
print("---------------------------------")
for ntabla in range (1,11):
    tabla(ntabla)
#-----------------------
# Ejemplo 4.
print("\n####### EJEMPLO 4 ########")
# Parametros opcionales
def getEmpleado(nombre, dni = None):
    print("EMPLEADO")
    print(f"Nombre: {nombre}")
    if dni != None:
        print(f"DNI: {dni}")

getEmpleado("Daniel Vera",3232)
#--------------------------
# Ejemplo 5. return o devolver datos
print("\n####### EJEMPLO 5 ########")
def saludame(nombre):
    saludo = f"Hola, saludos {nombre}"
    return saludo

print(saludame("VIctor"))
#-------------------------
# Ejemplo 6.
# Generar una calculadora en un string
print("\n####### EJEMPLO 6 ########")

def calculadora(num1, num2, basicas = False):
    suma = num1 + num2
    resta = num1 - num2
    multi = num1 * num2
    division = num1 / num2

    cadena = ""
    if basicas != False:
        cadena += "Suma: "+str(suma)
        cadena += "\n"
        cadena += "Resta: "+str(resta)
    else:
        cadena += "\n"
        cadena += "Multiplicacion: "+str(multi)
        cadena += "\n"
        cadena += "Division: "+str(division)

    return cadena

print(calculadora(56,5,True))

# Ejemplo 7. Funciones dentro de otras funciones
print("\n####### EJEMPLO 7 ########")

def getNombre(nombre):
    texto = f"El nombre es: {nombre}"
    return texto

def getApellidos(apellidos):
    texto = f"El apellido es: {apellidos}"
    return texto

def devuelveTodo(nombre,apellidos):
    texto = getNombre(nombre) +"\n"+ getApellidos(apellidos)
    return texto

#print(getNombre("Daniel "),getApellidos("Vera")) # Diferencia entre codigo, con la linea siguiente
print(devuelveTodo("Felipe","Vera Arias"))

# Ejemplo 8. Funciones Lambda
print("\n####### EJEMPLO 8 ########")
# La funcion Lambda es una funciona anonima, una funcion anonima que not tiene nombre y no hace falta
# definirla con la funcion Def, son funciones que sirven para tareas pequeñas
# pero que pueden llegar a serrepetitivas.

# Crear una funcion lambda para que nos muestre el año.

# dime_el_year = lambda year: f"El año es {year}"
dime_el_year = lambda year: f"El año es {year * 10}"
# le damos nombre a nuestra funcion, la definimos con lambda luego le damos
# el parametro y le asignamos algo que devuelve, como ejemplo ese texto del año.

print(dime_el_year(2034))


import csv

from scipy.stats import pearsonr
from numpy import var

def get_row_from_input(file_path):
    with open(file_path, "r") as f:
        reader = csv.reader(f)
        headers = next(reader)
        return headers, list(reader)

class GenesFilter(object):
    def __init__(self, genes_input_path):
        self.genes_input_path = genes_input_path
        self.filters = [(self.should_filter_avg_cs_score, self.get_avg_cs_score_threshold),
                        (self.should_filter_second_lowest_cs_score, None),
                        (self.should_filter_pearson, None),
                        (self.should_filter_variance, self.get_variance_threshold)]

    @staticmethod
    def get_parsed_cs_scores(row):
        return list(map(float, row[1:]))

    def get_variance_threshold(self, rows):
        list_of_variances = self.get_list_of_variances(rows)
        return [self.get_top_2000_variance_threshold(list_of_variances)]

    @staticmethod
    def get_list_of_variances(rows):
        list_of_variances = list()
        for row in rows:
            cs_scores = GenesFilter.get_parsed_cs_scores(row)
            list_of_variances.append(var(cs_scores))
        return list_of_variances

    @staticmethod
    def get_top_2000_variance_threshold(list_of_variances):
        list_of_variances = sorted(list_of_variances)
        return list_of_variances[-2000]

    def get_avg_cs_score_threshold(self, rows):
        avg_cs_list = self.get_list_of_avg_cs_scores(rows)
        return [self.get_15_percent_cs_score_threshold(avg_cs_list)]

    @staticmethod
    def get_list_of_avg_cs_scores(rows):
        avg_cs_list = list()
        for row in rows:
            cs_scores = GenesFilter.get_parsed_cs_scores(row)
            avg_cs_list.append(sum(cs_scores) / len(cs_scores))
        return avg_cs_list

    @staticmethod
    def get_15_percent_cs_score_threshold(avg_cs_list):
        avg_cs_list = sorted(avg_cs_list)
        return avg_cs_list[int((15/100.0) * len(avg_cs_list))]

    def filter_genes(self, output_file_path):
        headers, rows = get_row_from_input(self.genes_input_path)
        for filter_method, pre_process_method in self.filters:
            data = []
            if pre_process_method:
                data = pre_process_method(rows)
            filtered_rows = list()
            for row in rows:
                if filter_method(row, *data):
                    continue
                filtered_rows.append(row)
            rows = filtered_rows
        with open(output_file_path, "w") as output_file:
            writer = csv.writer(output_file)
            writer.writerow(headers)
            writer.writerows(rows)

    def should_filter_avg_cs_score(self, row, avg_cs_score_threshold):
        cs_scores = self.get_parsed_cs_scores(row)
        if sum(cs_scores) / len(cs_scores) < avg_cs_score_threshold:
            return True

    @staticmethod
    def should_filter_second_lowest_cs_score(row):
        cs_scores = GenesFilter.get_parsed_cs_scores(row)
        cs_scores = sorted(cs_scores)
        if cs_scores[1] < -1:
            return True

    @staticmethod
    def should_filter_pearson(row):
        cs_scores = GenesFilter.get_parsed_cs_scores(row)
        for i in range(len(cs_scores)):
            identity_vector = [0] * len(cs_scores)
            identity_vector[i] = 1
            if abs(pearsonr(cs_scores, identity_vector)[0]) > 0.8:
                return True

    @staticmethod
    def should_filter_variance(row, variance_threshold):
        cs_scores = GenesFilter.get_parsed_cs_scores(row)
        if var(cs_scores) < variance_threshold:
            return True

def main(genes_input_file_path):
    genes_filter = GenesFilter(genes_input_file_path)
    genes_filter.filter_genes("../model/2000_genes_input.csv")

if __name__ == '__main__':
    main("../model/genes_input.csv")