text stringlengths 8 6.05M |
|---|
#ヒープソート
def sort(A):
construct_heap(A,0);print(A)
for last in range(len(A) -1,0,-1):
A[0],A[last] = A[last],A[0];print(A)
exchange_nodes(A,0,last -1);print(A)
def left(n):
return 2*n +1
def right(n):
return 2*n +2
def exchange_nodes(A,n,last):
if last < left(n):
return
child = left(n)
if right(n) <=last:
if A[left(n)] < A[right(n)]:
child = right(n)
if A[n] < A[child]:
A[n],A[child] = A[child],A[n]
exchange_nodes(A,child,last)
def construct_heap(A,n):
last = len(A) - 1
if last < left(n):
return
construct_heap(A,left(n))
if right(n) <= last:
construct_heap(A,right(n))
exchange_nodes(A,n,last) |
class Universe:
def __init__(self):
self.CPU=[]
self.CPUsuivant=None
self.memoire=[]
def roundSlicer(self):
self.mainLoop(len(self.CPU))
def forward(self,N):
""" fait executer N intruction"""
for i in range(N):
self.execute()
def execute(self):
""" fait executer une intruction par un processeur"""
self.CPU[self.CPUsuivant].execute()
self.CPUsuivant+=1
def killCPU(self,cpu):
""" Tue le processeur donné en argupent"""
#à améliorer
killed = False
i = 0
while not killed:
if self.CPU[i] is cpu:
self.CPU=self.CPU[:i]+self.CPU[i+1:]
CPUsuivant -= (i < CPUsuivant)
killed = True
i += 1
def kill(self):
self.CPU=self.CPU[:CPUsuivant]+self.CPU[CPUsuivant+1:]
CPUsuivant -= 1
def createCPU(self):
""" Rajoute un processeur dans le slicer, juste avant le processeur actif"""
nouveau = CPU()
self.CPU=[self.CPU[self.CPUsuivant:]+[nouveau]+self.CPU[:self.CPUsuivant]]
self.CPUsuivant+=1
def save(self,file):
"""Ecrit son etat dans le fichier donné en argument. Remplace le fichier s'il existait déjà"""
n1=0 #nb bit du nb de CPU
n2=0 #nb bit d'un CPU
n3=0 #nb bit d'une case memoire
f=open(file,w)
a=len(CPU)
k=n1
while(k<=n1-8):
f.write(a>>k & 0b11111111)
k += 8
temp=a>>k
## functions for analysis
def colonisationRate(self) :
"renvoie le taux de cases remplies dans la liste Memoire[] de l'univers à la date t"
instructionsNb = 0;
for i in self.Memory :
if i != None :
instructionsNb += 1;
return (instructionsNb/len(self.Memory)) ;
def individus_boucles(t) : # pas fini du tout !
"??? en utilisant la méthose donnée par le tuteur : un CPU-test parcourt le code, on identifie un individu-boucle comme la plus grande boucle possible."
# je ne sais plus s'il faut pouvoir retourner au début depuis la fin, où juste arriver à la fin depuis le début
self = reconstitue(t);
N = len(self.Memoire); # devrait être une variable globale ?
loopStart = [None] * N;
test = CPU() ;
for i in range(N) :
if loopStart[i] == None :
loopStart[i] = i;
debut_courant = i;
test.index = i;
while ?? :
test.execute();
if ?? :
debut_boucle[test.index] = debut_courant;
test.clear() ; #si cette méthode n'existe pas, on peut juste remplacer par test=CPU();
return debut_boucle;
def rateCreationCPUs(self, interval) :
"retourne le nombre moyen de CPUs créés par CPU existant et par an pendant l'intervalle de temps de longueur interval et commençant à l'état présent"
nbCreated = 0;
date = 0;
currentCPUnumber = len(self.CPU);
while date < interval :
self.roundSlicer() ;
nbCreated += len(self.CPU)/currentCPUnumber - 1 ; # ou faire une fonction qui calcule le nb de CPUs crées à la date t ?
currentCPUnumber = len(self.CPU);
return (nb_created/interval) ;
def CPUdensity(self, t) :
"affiche et renvoie la densite de CPU par site d'instruction occupé" #on pourrait faire par site d'instruction tout court ?
d = len(self.CPU) / (self.colonisationRate()*len(self.Memory)) ;
print("La densité de CPU est {}, soit 1 CPU pour {} instructions".format(d, 1/d));
return d;
def nbIndividuals(t) :
"renvoie le nombre d'individus-boucles"
def nbSpecies(t) :
"renvoie le nombre de codes différents parmi tous les individus-boucles identifiés"
def speciesDistance(??) :
"renvoie la distance d'édition entre les codes des deux espèces données en paramètre"
|
import sys
import math
class PrimeGenerator:
def __init__(self):
self.until = 2
self.primes = set()
self.dico = {}
def is_prime(self, n: int) -> bool:
if n > self.until:
self.compute_until(n)
return n in self.primes
def primes_until(self, n: int):
if n > self.until:
self.compute_until(n)
return self.primes
def compute_until(self, until: int):
if until < self.until:
pass
i = self.until
while i <= until:
if i in self.dico:
for p in self.dico[i]:
tmp = p+i
if tmp not in self.dico:
self.dico[tmp] = [p]
else:
self.dico[tmp].append(p)
del self.dico[i]
else:
self.primes.add(i)
tmp = 2*i
if tmp not in self.dico:
self.dico[tmp] = [i]
else:
self.dico[tmp].append(i)
i += 1
self.until = until
def decompose(self, n: int):
if n > self.until:
self.compute_until(n)
ans = []
for i in self.primes:
curr = 0
while n % i == 0:
curr += 1
n = n // i
if curr > 0:
ans.append((i, curr))
if n == 1:
break
return ans
def __iter__(self):
for p in self.primes:
yield p
i = self.n
while True:
if is_prime(i):
yield i
i += 1
|
import requests
from lxml import html
from concurrent.futures import ThreadPoolExecutor,ProcessPoolExecutor
from concurrent import futures
import threading
class shitCode(object):
def __init__(self):
self.a_token_url = 'https://canvas.sydney.edu.au/courses/30588/quizzes/142845/take'
self.up_data_url = 'https://canvas.sydney.edu.au/courses/30588/quizzes/142845/submissions?user_id=189746'
self.now_queue = 1180
def header(self):
headers = {
'authority': 'canvas.sydney.edu.au',
'cache-control': 'max-age=0',
'sec-ch-ua': '" Not;A Brand";v="99", "Google Chrome";v="91", "Chromium";v="91"',
'sec-ch-ua-mobile': '?0',
'upgrade-insecure-requests': '1',
'origin': 'https://canvas.sydney.edu.au',
'content-type': 'application/x-www-form-urlencoded',
'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.19 Safari/537.36',
'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
'sec-fetch-site': 'same-origin',
'sec-fetch-mode': 'navigate',
'sec-fetch-dest': 'document',
'referer': 'https://canvas.sydney.edu.au/courses/30588/quizzes/142845',
'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8',
'cookie': 'log_session_id=1c7be4cdcdb36628bdbcea69e6efe88f; _legacy_normandy_session=iMWq1ecRizAx1wlAq8VNsw+7tv6DyidrlvYf5sXNSYjkW61KBkHLiuEtTIHqOZhAqvH7a1IXQj_QQCqRYwmIkPUL49M0yQ2v6Aic-hbDW2o55syWWOWVLGVBpRHv7wjSSvyUepwTPLJx_CImBd1D507SqOikhJ7s3VZH0s6v-k1e8v_xqPkECtVEk5yO_kH3L-YkdVW6f3rYPmiZNDXOm9DH2hrMmwiCtTv72GcIqy-F0ffKo6uJ37KrOlA-roquA_55mEW6P3_kpwcfGJuSDy2EEz2ob4mKQFJ5hCcaJGP01x1W3dt_ZZW-NDSgARMBCXGXICUB8ameVQi_ENU41ryRs4I4b-fRCmji1Q0_iKX-sXyDAppzEygVR01ZnS4BJhqMNdVErIRwfQXsIPmByghMEmblVh2KCRf_TZwLqfxiKfahi-5p0CGcje_w-hG6sAMLDtz7qSH4VG4-Ia5fsPz-UXNQ-QX0xqXNI50Yt_qMTMSDh_nWI-O5R7lTicpD2RFvhGzKYD94ZIiGRIqwiGN9OPl_fZoiHFmoFDzESeCRTpxY-OvtTg-iNSWBRBNijsR4UMMIhCXwCBzOv51fnhT.e635yNFE2gEe81cMXBeWLitKGNo.YJObdg; canvas_session=iMWq1ecRizAx1wlAq8VNsw+7tv6DyidrlvYf5sXNSYjkW61KBkHLiuEtTIHqOZhAqvH7a1IXQj_QQCqRYwmIkPUL49M0yQ2v6Aic-hbDW2o55syWWOWVLGVBpRHv7wjSSvyUepwTPLJx_CImBd1D507SqOikhJ7s3VZH0s6v-k1e8v_xqPkECtVEk5yO_kH3L-YkdVW6f3rYPmiZNDXOm9DH2hrMmwiCtTv72GcIqy-F0ffKo6uJ37KrOlA-roquA_55mEW6P3_kpwcfGJuSDy2EEz2ob4mKQFJ5hCcaJGP01x1W3dt_ZZW-NDSgARMBCXGXICUB8ameVQi_ENU41ryRs4I4b-fRCmji1Q0_iKX-sXyDAppzEygVR01ZnS4BJhqMNdVErIRwfQXsIPmByghMEmblVh2KCRf_TZwLqfxiKfahi-5p0CGcje_w-hG6sAMLDtz7qSH4VG4-Ia5fsPz-UXNQ-QX0xqXNI50Yt_qMTMSDh_nWI-O5R7lTicpD2RFvhGzKYD94ZIiGRIqwiGN9OPl_fZoiHFmoFDzESeCRTpxY-OvtTg-iNSWBRBNijsR4UMMIhCXwCBzOv51fnhT.e635yNFE2gEe81cMXBeWLitKGNo.YJObdg; _csrf_token=F5%2BmGxhVZR%2F8c8%2FfaKD%2BMU3m%2FkQZ9Ea7M5SrW%2FIPvolvz%2FRVWxwSR4tGmfQdk8pzOaLJcHWyM%2Bt%2F2voetFzs5g%3D%3D',
}
return headers
def get_a_token(self):
params = (
('user_id', '189746'),
)
data = {
'_method': 'post',
'authenticity_token': 'F5+mGxhVZR/8c8/faKD+MU3m/kQZ9Ea7M5SrW/IPvolvz/RVWxwSR4tGmfQdk8pzOaLJcHWyM+t/2voetFzs5g=='
}
response = requests.post('https://canvas.sydney.edu.au/courses/30588/quizzes/142845/take', headers=self.header(),
params=params, data=data)
print(response.status_code)
etree = html.etree
htm = etree.HTML(response.text)
a_token = htm.xpath('.//input[@name="authenticity_token"]/@value')[0]
return a_token
def do_action(self):
for i in range(0, 7400):
try:
a_token = self.get_a_token()
if len(a_token):
params = (
('user_id', '189746'),
)
data = {
'utf8': '\u2713',
'authenticity_token': a_token,
'attempt': self.now_queue,
'validation_token': 'd8e3e6ef4cefbb2b34f276b34be5f120369658e4126f3ecdd77ea7b61c085357',
'question_1475128': str(7400 - i)
}
response = requests.post(
'https://canvas.sydney.edu.au/courses/30588/quizzes/142845/submissions?user_id=189746',
params=params, data=data, headers=self.header())
code = response.status_code
print('status_code: ',code,'----num: ',str(7400 - i), 'attempt: ', self.now_queue)
self.now_queue += 1
except Exception as e:
print(e)
# def run(self):
# thread_pool = ThreadPoolExecutor(20)
# for i in range(1,8864):
# thread_pool.submit(self.do_action, i)
if __name__ == '__main__':
c = shitCode()
c.do_action() |
from locust import HttpLocust, TaskSet, task, TaskSequence, seq_task
class CacheTest(TaskSet):
@task()
def register1(self):
self.client.get("/user/xiaochu")
class WebsiteUser(HttpLocust):
task_set = CacheTest
host="http://localhost:8080"
min_wait = 1000
max_wait = 1000 |
from django.conf.urls import url
import planner.views as views
app_name = 'bp'
urlpatterns = [
url(r'^$', views.list, name='list'),
url(r'^add-members$', views.AddMemberView.as_view(), name='add-members'),
url(r'^likes$', views.LikesView.as_view(), name='likes'),
url(r'^like-ready$', views.like_ready, name='like-ready'),
] |
import pygame
import random #Imports modules
pygame.init() #Initializes pygame
screen_width = 1040
screen_height = 680
screen = pygame.display.set_mode((screen_width,screen_height)) #Sets the screen size
player = pygame.image.load("image.png") #Loads images
enemy = pygame.image.load("enemy.png")
prize = pygame.image.load("prize.jpg")
image_height = player.get_height() #Specifys heights and widths of each image
image_width = player.get_width()
enemy_height = enemy.get_height()
enemy_width = enemy.get_width()
prize_height = prize.get_height()
prize_width = prize.get_width()
playerXPosition = 100 # Places the image at a specific position
playerYPosition = 20
enemyXPosition = screen_width # Places the enemy image at a position
enemyYPosition = random.randint(0, screen_height - enemy_height)
prizeXPosition = screen_width # Places the prize image at a position
prizeYPosition = random.randint(0, screen_height - prize_height)
keyUp= False
keyDown = False
iCount = 1 # Sets some variables
while 1: # Starts the loop of the game
screen.fill(0) # Clears the screen
screen.blit(player, (playerXPosition, playerYPosition)) # Draws the image on the screen at the position
screen.blit(enemy, (enemyXPosition, enemyYPosition))
screen.blit(prize, (prizeXPosition, prizeYPosition))
pygame.display.flip() # Updates the images on the screen
for event in pygame.event.get(): # Loops the events
if event.type == pygame.QUIT: # If the player quits the game it will stop the loop and exit
pygame.quit()
exit(0)
if event.type == pygame.KEYDOWN: # Checks if the player clicked a key
if event.key == pygame.K_UP: # Did the player click the up key
keyUp = True
if event.key == pygame.K_DOWN: # Did the player click the down key
keyDown = True
if event.type == pygame.KEYUP: # Checks if the user stopped clicking a key
if event.key == pygame.K_UP: # Did the player stop clicking the up key
keyUp = False
if event.key == pygame.K_DOWN: # Did the player stop clicking the down key
keyDown = False
if keyUp == True: # is the upkey boolean true
if playerYPosition > 0 : # moves image up
playerYPosition -= 2
if keyDown == True: # is the downkey boolean true
if playerYPosition < screen_height - image_height: # Moves the image down
playerYPosition += 2
playerBox = pygame.Rect(player.get_rect()) # Specifies the images boundries
playerBox.top = playerYPosition # Updates the players image
playerBox.left = playerXPosition
enemyBox = pygame.Rect(enemy.get_rect()) # Specifies the enemys boundries
enemyBox.top = enemyYPosition
enemyBox.left = enemyXPosition
prizeBox = pygame.Rect(prize.get_rect()) # Specifies the prize boundries
prizeBox.top = prizeYPosition
prizeBox.left = prizeXPosition
if playerBox.colliderect(enemyBox): #Did the player collide with the enemy
print("You lose!") # Stops the program and tells the user they lost
pygame.quit()
exit(0)
if enemyXPosition < 0 - enemy_width: # If the enemy hit the side of the screen it will reset the enemy
iCount +=1
enemyXPosition = screen_width
enemyYPosition = random.randint(0, screen_height - enemy_height)
if iCount > 10 : # Starts sending the prize to the user so they can win
prizeXPosition -= 1
if prizeXPosition < 0 - prize_width: # If the prize hits the back then it will reset
prizeXPosition = screen_width
prizeYPosition = random.randint(0, screen_height - prize_height)
if playerBox.colliderect(prizeBox): #If the player collides with the box then they win
print("You WIN!")
pygame.quit()
exit(0)
if iCount > 4 : # Makes a max speed for the enemy
enemyXPosition -= 2
else : # Makes the enemy speed up
enemyXPosition -= iCount/2
|
import kivy
import cv2 as cv
import numpy as np
from kivy.uix.camera import Camera
from kivy.graphics.texture import Texture
class Camera2(Camera):
firstFrame=None
def _camera_loaded(self, *largs):
if ( ((kivy.platform)==("android")) ):
self.texture=Texture.create(size=self.resolution, colorfmt="rgb")
self.texture_size=[self.texture.size]
else:
super(Camera2, self)._camera_loaded()
def on_tex(self, *l):
if ( ((kivy.platform)==("android")) ):
buf=self._camera.grab_frame()
if ( not(buf) ):
return
frame=self._camera.decode_frame(buf)
frame=self.process_frame(frame)
self.image=frame
buf=frame.tostring()
self.texture.blit_buffer(buf, colorfmt="rgb", bufferfmt="ubyte")
super(Camera2, self).on_tex(*l)
def process_frame(self, frame):
r, g, b=cv.split(frame)
frame=cv.merge((b,g,r,))
rows, cols, channel=frame.shape
M=cv.getRotationMatrix2D((((cols)/(2)),((rows)/(2)),90,1,))
dst=cv.warpAffine(frame, M, (cols,rows,))
frame=cv.flip(dst, 1)
if ( ((self.index)==(1)) ):
frame=cv.flit(dst, -1)
return frame |
from matplotlib import pyplot as plt
import numpy as np
import pickle
import os
import torch
def loadPKL(path):
with open(path, "rb") as f:
return pickle.load(f)
def graph(arr, title, ylabel, show=False):
plt.figure()
plt.plot(list(range(len(arr))), arr)
plt.title(title)
plt.xlabel("Iteration")
plt.ylabel(ylabel)
plt.savefig("./graphs/" + title.replace(" ", "_") + ".png")
if show:
plt.show()
# MAML
train_accs_maml = loadPKL("./models/train_accs_maml.pkl")
train_losses_maml = loadPKL("./models/train_losses_maml.pkl")
train_losses_maml = [i.item() for i in train_losses_maml]
test_accs_maml = loadPKL("./models/test_accs_maml.pkl")
test_losses_maml = loadPKL("./models/test_losses_maml.pkl")
test_losses_maml = [i.item() for i in test_losses_maml]
print("MAML")
print(train_accs_maml)
print(train_losses_maml)
print(test_accs_maml)
print(test_losses_maml)
graph(train_accs_maml, "MAML Training Accuracy vs Iterations", "Accuracy", show=True)
graph(train_losses_maml, "MAML Training Loss vs Iterations", "Loss", show=True)
# pretrain
train_accs_pretrain = loadPKL("./models/train_accs_pretrain.pkl")
train_losses_pretrain = loadPKL("./models/train_losses_pretrain.pkl")
train_losses_pretrain = [i.item() for i in train_losses_pretrain]
test_accs_pretrain = loadPKL("./models/test_accs_pretrain.pkl")
test_losses_pretrain = loadPKL("./models/test_losses_pretrain.pkl")
test_losses_pretrain = [i.item() for i in test_losses_pretrain]
print("Pretrain")
print(train_accs_pretrain)
print(train_losses_pretrain)
print(test_accs_pretrain)
print(test_losses_pretrain)
graph(train_accs_pretrain, "Pretrain Training Accuracy vs Iterations", "Accuracy", show=True)
graph(train_losses_pretrain, "Pretrain Training Loss vs Iterations", "Loss", show=True)
# scratch
train_accs_ = loadPKL("./models/train_accs_.pkl")
train_losses_ = loadPKL("./models/train_losses_.pkl")
train_losses_ = [i.item() for i in train_losses_]
test_accs_ = loadPKL("./models/test_accs_.pkl")
test_losses_ = loadPKL("./models/test_losses_.pkl")
test_losses_ = [i.item() for i in test_losses_]
print("Scratch")
print(train_accs_)
print(train_losses_)
print(test_accs_)
print(test_losses_)
graph(train_accs_, "Scratch Training Accuracy vs Iterations", "Accuracy", show=True)
graph(train_losses_, "Scratch Training Loss vs Iterations", "Loss", show=True)
|
# -*- coding: utf-8 -*-
"""
Created on Sat Dic 12 10:45:15 2020
@author: Ayax
"""
import random
modelEnd = [6,18,1,6,20,22,28,15,5,19]
largeIndividual = 10
num = 5 #Cantidad de individuos
generation = 300 #Generaciones
pressure = 3 #individual>2
mutation_chance = 0.2
def individual(min, max):
return[random.randint(min, max) for i in range(largeIndividual)]
def newPopulation():
return [individual(0,50) for i in range(num)]
# Funcion la que se debe cambiar en funcion a f(x)
def functionType(individual):
fitness = 0
for i in range(len(individual)):
if individual[i] == modelEnd[i]:
fitness += 1
return fitness
def selection_and_reproduction(population):
evaluating = [ (functionType(i), i) for i in population]
print("eval",evaluating)
evaluating = [i[1] for i in sorted(evaluating)]
print("eval",evaluating)
population = evaluating
selected = evaluating[(len(evaluating)-pressure):]
for i in range(len(population)-pressure):
pointChange = random.randint(1,largeIndividual-1)
father = random.sample(selected, 2)
population[i][:pointChange] = father[0][:pointChange]
population[i][pointChange:] = father[1][pointChange:]
return population
def mutation(population):
for i in range(len(population)-pressure):
if random.random() <= mutation_chance:
pointChange = random.randint(1,largeIndividual-1)
new_val = random.randint(0,9)
while new_val == population[i][pointChange]:
new_val = random.randint(0,9)
population[i][pointChange] = new_val
return population
def funciony(data):
copy = []
for elem in data:
newdata = []
for x in elem:
y = (x*x*x)+(x*x)+x
newdata.append(y)
copy.append(newdata)
return copy
# Principal
modelEnd.sort()
modelEnd.reverse()
print('Inicial: ', modelEnd)
print('Generaciones', generation)
population = newPopulation()
# Ordenamos descendentemente los elementos
for p in population:
p.sort()
p.reverse()
print("\nInicio de la población:\n%s"%(population))
population = selection_and_reproduction(population)
print("\nCruce:\n%s"%(population))
y = funciony(population)
print("\nFuncion y:\n%s" % (y))
population = mutation(population)
print("\nMutación:\n%s"%(population))
|
class Node:
def __init__(self, data):
self.data = data
self.next = None
class PrintableNodes:
def __str__(self):
current = self.head
items = []
while current != None:
items.append(current.data)
current = current.next
return ','.join(str(item) for item in items)
|
import logging
from flask import Blueprint
from flask import Response
from flask import redirect
from flask import render_template
from flask import request
from flask import url_for
from flask_login import login_required, current_user
from waitlist.blueprints.settings import add_menu_entry
from waitlist.permissions import perm_manager, PermissionManager
from waitlist.permissions.manager import StaticPermissions
from waitlist.signal.signals import send_role_created, send_role_removed
from flask_babel import gettext, lazy_gettext
from flask.helpers import flash
bp = Blueprint('settings_permissions', __name__)
logger = logging.getLogger(__name__)
perm_manager.define_permission(StaticPermissions.ADMIN)
@bp.route("/", methods=['GET'])
@login_required
@perm_manager.require(StaticPermissions.ADMIN)
def view_permissions() -> Response:
return render_template('settings/permissions/config.html')
@bp.route("/add_role", methods=['POST'])
@login_required
@perm_manager.require(StaticPermissions.ADMIN)
def add_role() -> Response:
role_name: str = request.form['role_name']
role_display_name: str = request.form['role_display_name']
PermissionManager.add_role(role_name, role_display_name)
send_role_created(add_role, current_user.id, role_name, role_display_name)
return redirect(url_for('.view_permissions'), code=303)
add_menu_entry('settings_permissions.view_permissions', lazy_gettext('Permissions'),
lambda: perm_manager.get_permission(StaticPermissions.ADMIN).can())
@bp.route("/remove_role", methods=['POST'])
@login_required
@perm_manager.require(StaticPermissions.ADMIN)
def remove_role() -> Response:
role_id: int = int(request.form['role_id'])
role: Role = PermissionManager.get_role(role_id)
if role is None:
flash(gettext('Role with id=%(role_id)d was not found, failed to delete',
role_id=role_id),
"warning")
else:
role_display_name: str = role.displayName
role_name: str = role.name
if PermissionManager.remove_role(role_id):
flash(
gettext('Role with id=%(role_id)d was deleted',
role_id=role_id),
"success")
send_role_removed(remove_role, current_user.id, role_name,
role_display_name)
else:
flash(
gettext('There was an unknown error deleting Role with id=%(role_id)d',
role_id=role_id),
"warning")
return redirect(url_for('.view_permissions'), code=303)
|
import argparse
import struct
import colordiff
from tqdm import tqdm
try:
from colorama import Fore, Back, Style, init
init()
except ImportError: # fallback so that the imported classes always exist
class ColorFallback():
__getattr__ = lambda self, name: ''
Fore = Back = Style = ColorFallback()
#Reverse Python types to CTypes table
python2CTypes = {
"byte" : [
{
"ctype" : "char",
"length" : 1,
"pythonFormat" : "c"
}
],
"integer" : [
{
"ctype" : "signed char",
"length" : 1,
"pythonFormat" : "b"
},
{
"ctype" : "unsigned char",
"length" : 1,
"pythonFormat" : "B"
},
{
"ctype" : "short",
"length" : 2,
"pythonFormat" : "h"
},
{
"ctype" : "unsigned short",
"length" : 2,
"pythonFormat" : "H"
},
{
"ctype" : "int",
"length" : 4,
"pythonFormat" : "i"
},
{
"ctype" : "unsigned int",
"length" : 4,
"pythonFormat" : "I"
},
{
"ctype" : "long",
"length" : 4,
"pythonFormat" : "l"
},
{
"ctype" : "unsigned long",
"length" : 4,
"pythonFormat" : "L"
},
{
"ctype" : "long long",
"length" : 8,
"pythonFormat" : "q"
}
],
"bool" : [
{
"ctype" : "_Bool",
"length" : 1,
"pythonFormat" : "?"
}
],
"bytes" : [
{
"ctype" : "char[]",
#This attribute is ignored as char[] is variable length
"length" : "variable",
"pythonFormat" : "s"
}
]
}
def getBin(fileName):
with open(fileName, 'rb') as f:
packet = f.read()
return packet
def integerWindows(structLength, packetBytes):
#Collector
output = []
packetLength = len(packetBytes)
#Rolls a windows through bytearray and accumulates chunks
id = 0
for window in range(packetLength):
try:
temp = {}
temp['id'] = id
temp['bytes'] = packetBytes[window:(window+structLength)]
temp['start'] = window
temp['end'] = window+structLength
output.append(temp)
except:
None
id+=1
#Filter function
def dropTooShort(window):
if (len(window['bytes']) == structLength):
return True
else:
return False
#Drop any windows that don't match the strcutLength
return filter(dropTooShort, output)
def bytesWindows(packetBytes):
#Collector
output = []
packetLength = len(packetBytes)
#Rolls a windows through bytearray and accumulates chunks
for chunkLength in range(packetLength):
for window in range(packetLength):
temp = {}
#print(packetBytes[window:(window+chunkLength)])
try:
temp['bytes'] = packetBytes[window:(window+chunkLength)]
temp['start'] = window
temp['end'] = window+chunkLength
output.append(temp)
except:
None
return output
def unpackCtypeInteger(window, formatString):
output = None
try:
# ! is network (Big Endian)
output = struct.unpack('!' + formatString, bytes(window))
except:
None
return output
def unpackCtypeBytes(window, formatString):
output = None
try:
# ! is network (Big Endian)
output = struct.unpack('!' + str(len(window)) + formatString, bytes(window))
except:
None
return output
def scanAdjacent(scanDirection, subWindow, packetBytes):
if(scanDirection == '>'):
#packetBytes = packetBytes[subWindow['end']:]
for targetType in python2CTypes.keys():
ctypes = python2CTypes[targetType]
#Try each ctype for python type int
for ctype in ctypes:
if(ctype['ctype'] == 'char[]'):
window = packetBytes[subWindow['end']:subWindow['end']+1]
window2CType = unpackCtypeInteger(window, ctype['pythonFormat'])
if(window2CType != None):
print('CTYPE:')
print(ctype)
print('WINDOW:')
print(window)
print('UNPACKED VALUE:')
print(window2CType[0])
startUnpacked = str(bytes(packetBytes[:subWindow['end']]))[2:-1]
midUnpacked = str(window2CType[0])
endUnpacked = str(bytes(packetBytes[subWindow['end']+1:]))[2:-1]
unpacked = startUnpacked + midUnpacked + endUnpacked
colordiff.packetdiff(str(bytes(packetBytes))[2:-1], unpacked)
else:
window = packetBytes[subWindow['end']:subWindow['end']+ctype['length']]
window2CType = unpackCtypeInteger(window, ctype['pythonFormat'])
if(window2CType != None):
print('CTYPE:')
print(ctype)
print('WINDOW:')
print(window)
print('UNPACKED VALUE:')
print(window2CType[0])
startUnpacked = str(bytes(packetBytes[:subWindow['end']]))[2:-1]
midUnpacked = str(window2CType[0])
endUnpacked = str(bytes(packetBytes[subWindow['end']+ctype['length']:]))[2:-1]
unpacked = startUnpacked + midUnpacked + endUnpacked
colordiff.packetdiff(str(bytes(packetBytes))[2:-1], unpacked)
#Scan left <
else:
#packetBytes = packetBytes[:subWindow['start']]
for targetType in python2CTypes.keys():
ctypes = python2CTypes[targetType]
#Try each ctype for python type int
for ctype in ctypes:
if(ctype['ctype'] == 'char[]'):
window = packetBytes[subWindow['start']-1:subWindow['start']]
window2CType = unpackCtypeInteger(window, ctype['pythonFormat'])
if(window2CType != None):
print('CTYPE:')
print(ctype)
print('WINDOW:')
print(window)
print('UNPACKED VALUE:')
print(window2CType[0])
startUnpacked = str(bytes(packetBytes[:subWindow['end']]))[2:-1]
midUnpacked = str(window2CType[0])
endUnpacked = str(bytes(packetBytes[subWindow['end']+1:]))[2:-1]
unpacked = startUnpacked + midUnpacked + endUnpacked
colordiff.packetdiff(str(bytes(packetBytes))[2:-1], unpacked)
else:
window = packetBytes[subWindow['start']:subWindow['start']-ctype['length']]
window2CType = unpackCtypeInteger(window, ctype['pythonFormat'])
if(window2CType != None):
print('CTYPE:')
print(ctype)
print('WINDOW:')
print(window)
print('UNPACKED VALUE:')
print(window2CType[0])
startUnpacked = str(bytes(packetBytes[:subWindow['start']-ctype['length']]))[2:-1]
midUnpacked = str(window2CType[0])
endUnpacked = str(bytes(packetBytes[subWindow['start']:]))[2:-1]
unpacked = startUnpacked + midUnpacked + endUnpacked
colordiff.packetdiff(str(bytes(packetBytes))[2:-1], unpacked)
def main():
#Parse arguments
parser = argparse.ArgumentParser()
parser.add_argument('--bf', required=True, help='Binary file containing a single packet layer')
parser.add_argument('--obyte', required=False, type=str, help='Oracle integer value to search for')
parser.add_argument('--oint', required=False, type=int, help='Oracle integer value to search for')
parser.add_argument('--obool', required=False, help='Oracle bool value to search for')
parser.add_argument('--ofloat', required=False, help='Oracle float value to search for')
parser.add_argument('--obytes', required=False, help='Oracle bytes value to search for')
parser.add_argument('--oencoding', required=False, type=str, help='Byte encoding of Oracle for --obytes EX: "ascii", "utf8"')
args = parser.parse_args()
#Get packet data
packet = getBin(args.bf)
print('Searching Packet:')
print(packet)
packetBytes = bytearray(packet)
#packetBytes = bytearray(b'\x00\x01\x00\x02\x00\x03')
#Handle --oint
if(args.oint is not None):
ctypes = python2CTypes['integer']
#Try each ctype for python type int
for ctype in ctypes:
#Try each rolling window
for window in integerWindows(ctype['length'], packetBytes):
#print(window)
window2CType = unpackCtypeInteger(window['bytes'], ctype['pythonFormat'])
if(window2CType != None):
#print(window2CType)
if(args.oint in window2CType):
print(Fore.YELLOW + 'FOUND OINT ORACLE: ' + str(args.oint) + Fore.RESET)
print('CTYPE:')
print(ctype)
print('WINDOW:')
print(window)
print('UNPACKED VALUE:')
print(window2CType[0])
startUnpacked = str(bytes(packetBytes[:window['start']]))[2:-1]
midUnpacked = str(window2CType[0])
endUnpacked = str(bytes(packetBytes[window['end']:]))[2:-1]
unpacked = startUnpacked + midUnpacked + endUnpacked
colordiff.packetdiff(str(packet)[2:-1], unpacked)
selectedWindow = input('Select Window? [y/n]: ')
if(selectedWindow == 'y'):
scanDirection = input('Scan Direction? [</>]: ')
scanAdjacent(scanDirection, window, packetBytes)
#Handle --obytes
if(args.obytes is not None):
if(args.oencoding is not None):
ctypes = python2CTypes['bytes']
#Try each ctype for python type int
for ctype in ctypes:
#Try each rolling window
for window in bytesWindows(packetBytes):
#print(window)
window2CType = unpackCtypeBytes(window['bytes'], ctype['pythonFormat'])
if(window2CType != None):
#print(window2CType)
if(bytes(args.obytes, encoding=args.oencoding) in window2CType):
print(fore.YELLOW + 'FOUND OBYTES ORACLE: ' + str(args.obytes) + Fore.RESET)
print('CTYPE:')
print(ctype)
print('WINDOW:')
print(window)
print('UNPACKED VALUE:')
print(window2CType[0])
startUnpacked = str(bytes(packetBytes[:window['start']]))[2:-1]
midUnpacked = str(window2CType[0])
endUnpacked = str(bytes(packetBytes[window['end']:]))[2:-1]
unpacked = startUnpacked + midUnpacked + endUnpacked
colordiff.packetdiff(str(packet)[2:-1], unpacked)
selectedWindow = input('Select Window? [y/n]: ')
if(selectedWindow == 'y'):
scanDirection = input('Scan Direction? [</>]: ')
scanAdjacent(scanDirection, window, packetBytes)
else:
print("WARN: --obytes must be paired with --oencoding")
if __name__ == '__main__':
main()
|
import pytest
import tensorflow as tf
from contextlib import ExitStack
import subprocess
from collections import defaultdict
import shutil
import os
from dps import cfg
from dps.utils import NumpySeed
from dps.utils.tf import MLP, LeNet
from dps.vision.train import EMNIST_CONFIG, OMNIGLOT_CONFIG
from dps.datasets import EmnistDataset, OmniglotDataset
from dps.train import load_or_train
def get_graph_and_session():
g = tf.Graph()
session_config = tf.ConfigProto()
session_config.intra_op_parallelism_threads = 1
session_config.inter_op_parallelism_threads = 1
sess = tf.Session(graph=g, config=session_config)
return g, sess
def _eval_model(test_dataset, inference, x_ph):
x, y = test_dataset.next_batch(advance=False)
loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y, logits=inference))
correct_prediction = tf.equal(tf.argmax(inference, 1), tf.argmax(y, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
sess = tf.get_default_session()
_loss, _accuracy = sess.run([loss, accuracy], feed_dict={x_ph: x})
print("Loss: {}, accuracy: {}".format(_loss, _accuracy))
assert _accuracy > 0.7
def make_checkpoint_dir(config, name):
checkpoint_dir = os.path.join(cfg.log_root, name)
try:
shutil.rmtree(checkpoint_dir)
except FileNotFoundError:
pass
os.makedirs(checkpoint_dir, exist_ok=False)
return checkpoint_dir
def build_mlp():
return MLP([cfg.n_controller_units, cfg.n_controller_units])
def build_lenet():
return LeNet(cfg.n_controller_units)
@pytest.mark.parametrize("build_function", [build_mlp, build_lenet])
def test_emnist_load_or_train(build_function, test_config):
with NumpySeed(83849):
n_classes = 10
classes = EmnistDataset.sample_classes(n_classes)
config = EMNIST_CONFIG.copy(
build_function=build_function,
classes=classes,
threshold=0.1,
stopping_criteria="01_loss,min",
n_controller_units=100,
n_train=10000
)
config.update(test_config)
checkpoint_dir = make_checkpoint_dir(config, 'test_emnist')
output_size = n_classes + 1
g, sess = get_graph_and_session()
with ExitStack() as stack:
stack.enter_context(g.as_default())
stack.enter_context(sess)
stack.enter_context(sess.as_default())
stack.enter_context(config)
f = build_function()
x_ph = tf.placeholder(tf.float32, (None,) + cfg.shape)
inference = f(x_ph, output_size, False)
loaded = load_or_train(
config, f.scope, os.path.join(checkpoint_dir, 'model'))
assert not loaded
test_dataset = EmnistDataset(n_examples=cfg.n_val, one_hot=True)
_eval_model(test_dataset, inference, x_ph)
g, sess = get_graph_and_session()
with ExitStack() as stack:
stack.enter_context(g.as_default())
stack.enter_context(sess)
stack.enter_context(sess.as_default())
stack.enter_context(config)
f = build_function()
x_ph = tf.placeholder(tf.float32, (None,) + cfg.shape)
inference = f(x_ph, output_size, False)
loaded = load_or_train(
config, f.scope, os.path.join(checkpoint_dir, 'model'))
assert loaded
test_dataset = EmnistDataset(n_examples=cfg.n_val, one_hot=True)
_eval_model(test_dataset, inference, x_ph)
@pytest.mark.parametrize("build_function", [build_mlp, build_lenet])
def test_emnist_pretrained(build_function, test_config):
with NumpySeed(83849):
n_classes = 10
classes = EmnistDataset.sample_classes(n_classes)
config = EMNIST_CONFIG.copy(
build_function=build_function,
classes=classes,
threshold=0.1,
stopping_criteria="01_loss,min",
n_controller_units=100,
n_train=10000
)
config.update(test_config)
checkpoint_dir = make_checkpoint_dir(config, 'test_emnist')
output_size = n_classes + 1
name_params = 'classes include_blank shape n_controller_units'
g, sess = get_graph_and_session()
with ExitStack() as stack:
stack.enter_context(g.as_default())
stack.enter_context(sess)
stack.enter_context(sess.as_default())
stack.enter_context(config)
f = build_function()
f.set_pretraining_params(config, name_params, checkpoint_dir)
x_ph = tf.placeholder(tf.float32, (None,) + cfg.shape)
inference = f(x_ph, output_size, False)
assert f.was_loaded is False
with config:
test_dataset = EmnistDataset(n_examples=cfg.n_val, one_hot=True)
_eval_model(test_dataset, inference, x_ph)
g, sess = get_graph_and_session()
with ExitStack() as stack:
stack.enter_context(g.as_default())
stack.enter_context(sess)
stack.enter_context(sess.as_default())
stack.enter_context(config)
f = build_function()
f.set_pretraining_params(config, name_params, checkpoint_dir)
x_ph = tf.placeholder(tf.float32, (None,) + cfg.shape)
inference = f(x_ph, output_size, False)
assert f.was_loaded is True
with config:
test_dataset = EmnistDataset(n_examples=cfg.n_val, one_hot=True)
_eval_model(test_dataset, inference, x_ph)
@pytest.mark.parametrize("build_function", [build_mlp, build_lenet])
def test_omniglot(build_function, test_config):
with NumpySeed(83849):
classes = ["Greek,18", "Greek,19"]
n_classes = len(classes)
config = OMNIGLOT_CONFIG.copy(
patience=10000,
build_function=build_function,
classes=classes,
n_controller_units=100,
threshold=0.2,
stopping_criteria="01_loss,min",
train_indices=list(range(15)),
val_indices=list(range(15, 20)),
test_indices=list(range(15, 20)),
)
config.update(test_config)
checkpoint_dir = make_checkpoint_dir(config, 'test_omni')
output_size = n_classes + 1
name_params = 'classes include_blank shape n_controller_units'
g, sess = get_graph_and_session()
with ExitStack() as stack:
stack.enter_context(g.as_default())
stack.enter_context(sess)
stack.enter_context(sess.as_default())
stack.enter_context(config)
f = build_function()
f.set_pretraining_params(config, name_params, checkpoint_dir)
x_ph = tf.placeholder(tf.float32, (None,) + cfg.shape)
inference = f(x_ph, output_size, False)
test_dataset = OmniglotDataset(indices=cfg.test_indices, one_hot=True)
_eval_model(test_dataset, inference, x_ph)
g, sess = get_graph_and_session()
with ExitStack() as stack:
stack.enter_context(g.as_default())
stack.enter_context(sess)
stack.enter_context(sess.as_default())
stack.enter_context(config)
f = build_function()
f.set_pretraining_params(config, name_params, checkpoint_dir)
x_ph = tf.placeholder(tf.float32, (None,) + cfg.shape)
inference = f(x_ph, output_size, False)
assert f.was_loaded is True
test_dataset = OmniglotDataset(indices=cfg.test_indices, one_hot=True)
_eval_model(test_dataset, inference, x_ph)
def _train_classifier(build_function, config, name_params, output_size, checkpoint_dir):
checkpoint_dir = str(checkpoint_dir)
g, sess = get_graph_and_session()
with ExitStack() as stack:
stack.enter_context(g.as_default())
stack.enter_context(sess)
stack.enter_context(sess.as_default())
stack.enter_context(config)
f = build_function()
f.set_pretraining_params(config, name_params, checkpoint_dir)
x_ph = tf.placeholder(tf.float32, (None,) + cfg.shape)
# Trigger training
f(x_ph, output_size, False)
def _get_deterministic_output(d):
return subprocess.check_output(
'grep "train_data\|val_data\|test_data" {}/*.stdout | cat -n'.format(d), shell=True).decode()
determinism_info = dict(
emnist=dict(
config=EMNIST_CONFIG,
sample_classes=EmnistDataset.sample_classes,
),
omni=dict(
config=OMNIGLOT_CONFIG,
sample_classes=OmniglotDataset.sample_classes
),
)
@pytest.mark.slow
@pytest.mark.parametrize("dataset", "emnist omni".split())
def test_determinism(dataset, test_config):
build_function = build_mlp # Can't use build_lenet here as it is slightly non-deterministic for reasons unknown.
with NumpySeed(83849):
n_classes = 10
info = determinism_info[dataset]
classes = info['sample_classes'](n_classes)
config = info['config'].copy(
build_function=build_function,
classes=classes,
n_controller_units=100,
threshold=0.2,
stopping_criteria="01_loss,min",
seed=334324923,
display_step=100,
eval_step=100,
max_steps=1001,
tee=False,
n_train=500,
)
config.update(test_config)
name_params = 'classes include_blank shape n_controller_units'
output_size = n_classes + 1
n_repeats = 5
output = defaultdict(int)
dir_names = []
try:
for i in range(n_repeats):
checkpoint_dir = make_checkpoint_dir(config, 'test_{}_{}'.format(dataset, i))
dir_names.append(checkpoint_dir)
_train_classifier(build_function, config, name_params, output_size, checkpoint_dir)
o = _get_deterministic_output(checkpoint_dir)
output[o] += 1
if len(output) != 1:
for o in sorted(output):
print("\n" + "*" * 80)
print("The following occurred {} times:\n".format(output[o]))
print(o)
raise Exception("Results were not deterministic.")
finally:
for dn in dir_names:
try:
shutil.rmtree(dn)
except FileNotFoundError:
pass
|
import constants
from seq2seq import Seq2Seq
from preprocessing import Vocabulary
from logger import log, save_dataframe, read_dataframe
import os
import numpy as np
import pandas as pd
import torch
class Environment:
def __init__(self):
self.train_methods = None
self.valid_methods = None
self.test_methods = None
self.input_vocab = Vocabulary()
self.output_vocab = Vocabulary()
self.model = None
self.history = None
self.iters_completed = None
self.total_training_time = None
def save(self):
log('Saving the state of the environment')
self.__save_methods()
self.__save_vocabs()
self.__save_model()
self.__save_history()
self.__save_iters_completed()
self.__save_total_training_time()
def save_data(self):
log('Saving dataset splits and vocabularies')
self.__save_methods()
self.__save_vocabs()
def save_train(self):
log('Saving the state of training')
self.__save_model()
self.__save_history()
self.__save_iters_completed()
self.__save_total_training_time()
def load(self):
log('Loading the last saved environment')
self.__load_methods()
self.__load_vocabs()
self.__load_model()
self.__load_history()
self.__load_iters_completed()
self.__load_total_training_time()
log("Starting from iteration {}\n{} more iterations to go ({:.1f}%)".format(
self.iters_completed + 1,
constants.NUM_ITER - self.iters_completed,
(constants.NUM_ITER - self.iters_completed) / constants.NUM_ITER * 100))
def initialize_new(self):
log('Initializing a new environment')
self.__init_methods()
self.__init_vocabs()
self.__init_model()
self.__init_history()
self.__init_iters_completed()
self.__init_total_training_time()
def __save_methods(self):
log('Saving train, validation, and test methods')
join = lambda tokens: ' '.join(tokens)
save_dataframe(self.train_methods.applymap(join), constants.TRAIN_METHODS_FILE)
save_dataframe(self.valid_methods.applymap(join), constants.VALID_METHODS_FILE)
save_dataframe(self.test_methods.applymap(join), constants.TEST_METHODS_FILE)
def __save_vocabs(self):
log('Saving vocabularies')
self.input_vocab.save(constants.INPUT_VOCAB_FILE)
self.output_vocab.save(constants.OUTPUT_VOCAB_FILE)
def __save_model(self):
log('Saving the model')
torch.save(self.model.state_dict(), constants.TRAINED_MODEL_FILE)
def __save_history(self):
log('Saving score history')
save_dataframe(self.history, constants.HISTORIES_FILE)
def __save_iters_completed(self):
log('Saving the number of completed iterations')
with open(constants.ITERS_COMPLETED_FILE, 'w') as f:
f.write(str(self.iters_completed))
def __save_total_training_time(self):
log('Saving the total training time')
with open(constants.TRAINING_TIME_FILE, 'w') as f:
f.write(str(self.total_training_time))
def __load_methods(self):
log('Loading train, validation, and test methods')
self.train_methods = read_dataframe(constants.TRAIN_METHODS_FILE)
self.valid_methods = read_dataframe(constants.VALID_METHODS_FILE)
self.test_methods = read_dataframe(constants.TEST_METHODS_FILE)
self.__log_split()
self.__split_tokens()
def __load_vocabs(self):
log('Loading vocabularies')
self.input_vocab.load(constants.INPUT_VOCAB_FILE)
self.output_vocab.load(constants.OUTPUT_VOCAB_FILE)
self.__log_vocabs()
def __load_model(self):
self.__init_model()
log('Loading the last trained model')
self.model.load_state_dict(torch.load(constants.TRAINED_MODEL_FILE))
def __load_history(self):
log('Loading score history')
self.history = read_dataframe(constants.HISTORIES_FILE)
def __load_iters_completed(self):
log('Loading the number of completed iterations')
with open(constants.ITERS_COMPLETED_FILE, 'r') as f:
self.iters_completed = int(f.read())
def __load_total_training_time(self):
log('Loading the total training time')
with open(constants.TRAINING_TIME_FILE, 'r') as f:
self.total_training_time = float(f.read())
def __init_methods(self):
self.__load_dataset()
self.__split_tokens()
self.__filter_dataset()
self.__split_dataset()
self.__log_split()
def __init_vocabs(self):
log('Collecting the tokens from train set into the vocabularies')
self.input_vocab.collectWordsFrom(self.train_methods['source'])
self.output_vocab.collectWordsFrom(self.train_methods['name'])
self.__log_vocabs()
def __init_model(self):
log('Initializing an empty model')
self.model = Seq2Seq(
input_size=len(self.input_vocab),
output_size=len(self.output_vocab),
hidden_size=constants.HIDDEN_SIZE,
learning_rate=constants.LEARNING_RATE,
teacher_forcing_ratio=constants.TEACHER_FORCING_RATIO,
device=constants.DEVICE)
log(str(self.model))
def __init_history(self):
log('Initializing an empty DataFrame for score history')
self.history = pd.DataFrame(
columns=['Loss', 'BLEU', 'ROUGE', 'F1', 'num_names'])
def __init_iters_completed(self):
log('Setting the number of completed iterations equal to 0')
self.iters_completed = 0
def __init_total_training_time(self):
log('Setting the total training time equal to 0')
self.total_training_time = 0
def __load_dataset(self):
log('Loading the dataset')
self.__methods = read_dataframe(constants.DATASET_FILE)
self.__methods = self.__methods[['name', 'source']]
def __split_dataset(self):
log('Splitting the dataset into train, validation, and test sets')
if constants.TRAIN_PROP + constants.VALID_PROP + constants.TEST_PROP != 1.0:
raise ValueError("Train, validation, and test proportions don't sum up to 1.")
test_size = int(constants.TEST_PROP * len(self.__methods))
valid_size = int(constants.VALID_PROP * len(self.__methods))
train_size = int(constants.TRAIN_PROP * len(self.__methods))
indices = np.random.permutation(len(self.__methods))
train_idx = indices[:train_size]
valid_idx = indices[train_size:(train_size + valid_size)]
test_idx = indices[-test_size:]
self.train_methods = self.__methods.iloc[train_idx]
self.valid_methods = self.__methods.iloc[valid_idx]
self.test_methods = self.__methods.iloc[test_idx]
def __filter_dataset(self):
# TODO: Move it elsewhere
log('Filtering data from dataset')
initial_size = len(self.__methods)
log('Removing empty methods')
self.__methods = self.__methods[self.__methods['source'].apply(
lambda code: len(code) > 0)]
log('{} methods left ({:.2f}%)'.format(
len(self.__methods), len(self.__methods) / initial_size * 100))
log('Removing methods with empty names')
self.__methods = self.__methods[self.__methods['name'].apply(
lambda name: len(name) > 0)]
log('{} methods left ({:.2f}%)'.format(
len(self.__methods), len(self.__methods) / initial_size * 100))
log('Removing getters')
self.__methods = self.__methods[self.__methods['name'] != self.__methods['source']]
log('{} methods left ({:.2f}%)'.format(
len(self.__methods), len(self.__methods) / initial_size * 100))
log('Removing test methods')
self.__methods = self.__methods[self.__methods['name'].apply(lambda name: name[0] != 'test')]
log('{} methods left ({:.2f}%)'.format(
len(self.__methods), len(self.__methods) / initial_size * 100))
log('Removing abstract methods')
self.__methods = self.__methods[self.__methods['source'].apply(lambda source: source != ['self', 'subclass', 'responsibility'])]
log('{} methods left ({:.2f}%)'.format(
len(self.__methods), len(self.__methods) / initial_size * 100))
log('Removing shouldNotImplement methods')
self.__methods = self.__methods[self.__methods['source'].apply(lambda source: source != ['self', 'should', 'not', 'implement'])]
log('{} methods left ({:.2f}%)'.format(
len(self.__methods), len(self.__methods) / initial_size * 100))
log('Removing keywords')
self.__methods = self.__methods[self.__methods['source'].apply(lambda source: not set(source).issubset(['self', 'should', 'not', 'implement']))]
log('{} methods left ({:.2f}%)'.format(
len(self.__methods), len(self.__methods) / initial_size * 100))
if constants.DROP_DUPLICATES:
log('Removing duplicate methods')
self.__methods = self.__methods.loc[self.__methods.astype(str).drop_duplicates().index]
log('{} methods left ({:.2f}%)'.format(
len(self.__methods), len(self.__methods) / initial_size * 100))
log('Removing methods that exceed max size')
self.__methods = self.__methods[self.__methods['source'].apply(
lambda code: len(code) <= constants.MAX_LENGTH)]
log('{} methods left ({:.2f}%)'.format(
len(self.__methods), len(self.__methods) / initial_size * 100))
def __join_tokens(self):
log('Joining tokens into strings')
join = lambda tokens: ' '.join(tokens)
self.train_methods = self.train_methods.applymap(join)
self.valid_methods = self.valid_methods.applymap(join)
self.test_methods = self.test_methods.applymap(join)
def __split_tokens(self):
log('Splitting strings into tokens')
split = lambda sentence: str(sentence).split()
# self.train_methods = self.train_methods.applymap(split)
# self.valid_methods = self.valid_methods.applymap(split)
# self.test_methods = self.test_methods.applymap(split)
self.__methods = self.__methods.applymap(split)
def __log_split(self):
log('Train size: {}\n'
'Validation size: {}\n'
'Test size: {}'.format(
len(self.train_methods),
len(self.valid_methods),
len(self.test_methods)))
def __log_vocabs(self):
log('Number of unique input tokens: {}\n'
'Number of unique output tokens: {}'.format(
len(self.input_vocab),
len(self.output_vocab)))
|
# https://leetcode.com/problems/two-sum/
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
# Dictionary where keys = number values, values = index position
table = {}
# Loops through list of numbers, looks for the difference of the target value minus the current value of j
for i, j in enumerate(nums):
diff = target - j
# If the difference is found in the table, return index of said diff. value and the current iteration of i
if diff in table:
return [table[diff], i]
# Otherwise, set table[j] to the value of i and continue looping
else:
table[j] = i
|
import requests
chars = [
'villager'
]
def fetch_character_img():
for i in range(len(chars)):
stringy = 'https://www.proguides.com/api/v2/game-resources/super-smash-bros-ultimate/static-data/characters/by-key/{0}'.format(chars[i])
img_data = requests.get(stringy).content
with open('data_'+chars[i]+'.json', 'wb') as handler:
handler.write(img_data)
fetch_character_img() |
class Backtracking:
def __init__(self, dom, vars, single_constraints, double_constraints, multi_constraints):
if vars == []:
self.vars = []
self.solution = []
self.doms = {}
self.dom = dom
else:
self.vars = [vars]
self.solution = []
self.doms = []
self.dom = dom
if dom != []:
for var in vars:
self.doms.append([])
for var in vars:
self.doms[var] = self.dom[:]
temp = []
for x in range(len(vars)):
temp.append(0)
self.solution.append(dict(zip(vars, temp)))
self.wezlow = 0
self.single_constraints = single_constraints
self.double_constraints = double_constraints
self.multi_constraints = multi_constraints
self.allSolutions = []
def addVars(self, vars):
self.vars += [vars]
temp = []
for x in range(vars.__len__()):
temp.append(0)
self.solution.append(dict(zip(vars, temp)))
for var in vars:
self.doms[var] = self.dom[:]
def set_doms(self,doms):
self.doms = doms
def solutions(self, index):
self.wezlow += 1
if not self.check():
return False
varsLen = 0
for x in self.vars:
varsLen += len(x)
if index == varsLen:
if self.check():
return True
else:
return False
v = int(index/len(self.vars[0]))
i = self.vars[v][index%len(self.vars[0])]
d = self.doms[i]
for x in d:
self.solution[v][i] = x
if self.solutions(index + 1):
return True
self.solution[v][i] = 0
return False
def check(self):
return (self.check_single_constraints() and self.check_double_constraints() and self.check_multi_constraints())
def check_single_constraints(self):
for w in range(self.vars.__len__()):
for c in self.single_constraints:
if list(self.solution[w].keys()).__contains__(c[1]):
if self.solution[w][c[1]] != 0:
if not c[0](self.solution[w][c[1]]):
return False
return True
def check_double_constraints(self):
for c in self.double_constraints:
for w1 in range(self.vars.__len__()):
for w2 in range(self.vars.__len__()):
if list(self.solution[w1].keys()).__contains__(c[1][0]) and list(self.solution[w2].keys()).__contains__(c[1][1]):
if self.solution[w1][c[1][0]] != 0 and self.solution[w2][c[1][1]] != 0:
if not c[0](self.solution[w1][c[1][0]], self.solution[w2][c[1][1]]):
return False
return True
def check_multi_constraints(self):
for w in range(self.vars.__len__()):
for c in self.multi_constraints:
for x1 in c[1]:
for x2 in c[1]:
if x1!=x2:
if list(self.solution[w].keys()).__contains__(x1) and list(self.solution[w].keys()).__contains__(x2):
if self.solution[w][x1] != 0 and self.solution[w][x2] != 0:
if not c[0](self.solution[w][x1], self.solution[w][x2]):
return False
return True
|
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 17 16:19:17 2021
@author: anand
"""
# =============================================================================
# KNN - Predict whether a person will get Diabetes or not
# =============================================================================
# Importing the necessary packages
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import confusion_matrix, f1_score, accuracy_score
def chooseKNeighbours(yTest):
import math
k = int(math.sqrt(len(yTest)))
if (k%2==0):
return (k-1)
else:
return (k)
# Importing the datafile into DataFrame
dataFrame = pd.read_csv('diabetes.csv')
data = dataFrame.copy(deep = True)
# Replace Zeros
zeroNotAccepted = ['Glucose', 'BloodPressure', 'SkinThickness', 'BMI', 'Insulin']
for col in zeroNotAccepted:
data[col] = data[col].replace(0, np.NaN)
meanHere = int(data[col].mean(skipna = True))
data[col] = data[col].replace(np.NaN, meanHere)
# Splitting the dataset into features and label
X = data.values[:, 0:8]
y = data.values[:, 8]
# Splitting the data into Train and Test Data
XTrain, XTest, yTrain, yTest = train_test_split(X, y, test_size = 0.2, random_state = 0)
# Feature Scaling
ss = StandardScaler()
XTrain = ss.fit_transform(XTrain)
XTest = ss.transform(XTest)
# Creating a KNN Model instance and fitting the model
KNN = KNeighborsClassifier(n_neighbors = chooseKNeighbours(yTest), p = 2, metric = 'euclidean')
KNN.fit(XTrain, yTrain)
# p=2 as we are looking for diabetic or not
# Predicting the model output
yPred = KNN.predict(XTest)
# Evaluate the Model
confMatrix = confusion_matrix(yTest, yPred)
accuracy = accuracy_score(yTest, yPred)
f1Score = f1_score(yTest, yPred)
print("Confusion Matrix: ")
print(confMatrix)
print(f"Accuracy score is {round(accuracy,2)*100} %")
print(f"F1 score is {round(f1Score,2)*100} %") |
import urllib.request, urllib.parse, urllib.error
import json
import ssl
api_key = False
# If you have a Google Places API key, enter it here
# api_key = 'AIzaSy___IDByT70'
# https://developers.google.com/maps/documentation/geocoding/intro
#NO TENGO API KEY DEL GUGUL
if api_key is False:
api_key = 42
serviceurl = 'http://py4e-data.dr-chuck.net/json?'
else :
serviceurl = 'https://maps.googleapis.com/maps/api/geocode/json?'
# Ignora errores de certificado SSL
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
while True:
address = input('Escribe el lugar para encontrar sus datos: ')
if len(address) < 1: break
parms = dict()
parms['address'] = address
if api_key is not False: parms['key'] = api_key
url = serviceurl + urllib.parse.urlencode(parms)
#URL TRABAJADO
print('El url trabajado es: ', url)
uh = urllib.request.urlopen(url, context=ctx)
data = uh.read().decode()
print('Se encontraron ', len(data), 'caracteres')
try:
js = json.loads(data)
except:
js = None
if not js or 'status' not in js or js['status'] != 'OK':
print('==== Falla al recibir los datos====')
print(data)
continue
print(json.dumps(js, indent=4))
idDeLugar= js['results'][0]['place_id']
lat = js['results'][0]['geometry']['location']['lat'] #latitud
lng = js['results'][0]['geometry']['location']['lng'] #latitud
formateada=js['results'][0]['formatted_address']
print('El id de lugar es: ', idDeLugar)
print('Con latitud ',lat, 'y longitud ',lng)
print('Su direccion bonita es: ',formateada) |
import pytest
class WrapperTest(object):
def __init__(self, expression, message):
pass
|
# Copyright 2021 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from pants.backend.plugin_development import pants_requirements
from pants.backend.plugin_development.pants_requirements import PantsRequirementsTargetGenerator
def rules():
return pants_requirements.rules()
def target_types():
return [PantsRequirementsTargetGenerator]
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""This module manage the data receive from the api (parse and clean)."""
import re
from settings import NBR_PRODUCT_PER_PAGE, param_categories, fields
class Parser:
"""process the data retrieve from the API openfoodfact."""
# -tc- je passerais la liste des produits en paramètre de clean(),
# -tc- pas du constructeur. Et la liste nettoyée peut simplement
# -tc- être nettoyée par clean.
def __init__(self, api_result):
self.api_result = api_result
self.products_list = [] # list of all the cleaned product
def clean(self):
"""clean, filter and valid the data from the api and return a list of product ready to be
upload to purebeurre database."""
# -tc- revoir le parcour des listes avec une boucle for
for category in range(len(param_categories)):
# -tc- Est-ce vraiment important ce nombre de produits? Mettons tout
# -tc- ce qu'on peut.
for num_product_per_category in range(NBR_PRODUCT_PER_PAGE):
product = {} # initialisation of a product as a dict
product_completeness = True
# -tc- for field in fields
for i in range(len(fields)):
try:
# test if content
# -tc- utilise directement la méthode get de ton dictionnaire
# -tc- ce qui évite la KeyError
# -tc- personnellement, je créerais une méthode de validation séparée de clean().
if (self.api_result[category]['products']
[num_product_per_category]
[fields[i]]) != "":
# if yes, remove whitespace
result = (
self.api_result[category]['products']
[num_product_per_category][fields[i]]).strip()
if isinstance(result, str): # if result == str -tc- commrntaire inutile
# regex used to remove unwanted characters
# -tc- utilise une raw string pour tes expressions rationnelles
result = re.sub(
"[.,;\t\n\r\x0b\x0c]", '', result)
product.update({fields[i]: result})
product.update({fields[i]: (
self.api_result[category]['products']
[num_product_per_category][fields[i]]).strip()}
)
else:
product_completeness = False
break
except KeyError:
product_completeness = False
break
if product_completeness:
# add id_category field and value for the product
product.update({'id_category': (category + 1)})
self.products_list.append(product)
return self.products_list
|
#coding:utf-8
#轮廓入门
import numpy as np
import cv2 as cv
img = cv.imread('D:/python_file/Opencv3_study_file/images/Strat.png')
imgary = cv.cvtColor(img,cv.COLOR_BGR2GRAY)
ret,thresh = cv.threshold(imgary,127,255,0)
#cv.CHAIN_APPROX_NONE 找到所有边脚 |cv.CHAIN_APPROX_SIMPLE 节省内存找到框框的边脚
contours,hierarchy = cv.findContours(thresh,cv.RETR_TREE,cv.CHAIN_APPROX_SIMPLE)
cnt = contours[0]
M = cv.moments(cnt)
epsilon = 0.1*cv.arcLength(cnt,True)
approx = cv.approxPolyDP(cnt,epsilon,True)
print(approx)
cv.drawContours(img,approx, -1, (0,255,255), 3)
cv.imshow('img',img)
cv.waitKey(0)
cv.destroyAllWindows()
|
class Map():
"""Maps are undirected graphs whose nodes have locations and connections"""
def __init__(self, connections_file_string, locations_file_string):
"""Set up the map created by the passed in connections and locations files"""
self.connections_dictionary = {}
self.locations_dictionary = {}
# construct a dictionary mapping a node to its connections list
connections_file = open(connections_file_string, 'r')
for line in connections_file:
stripped_line = line.rstrip('\n')
split_line = stripped_line.split()
self.connections_dictionary[split_line[0]] = split_line[2:]
del self.connections_dictionary["END"]
# construct a dictionary mapping a node to its location
locations_file = open(locations_file_string, 'r')
for line in locations_file:
stripped_line = line.rstrip('\n')
split_line = stripped_line.split()
self.locations_dictionary[split_line[0]] = split_line[1:]
del self.locations_dictionary["END"]
def print_connections(self):
"""Prints all nodes and their connections"""
for key, value in self.connections_dictionary.items():
print("Node: " + key + "\tConnections: %s" % value)
def print_locations(self):
"""Prints all nodes and their locations"""
for key, value in self.locations_dictionary.items():
print("Node: " + key + "\tLocation: %s" % value)
def print_all(self):
"""Prints all nodes' locations and connections"""
for key, value in self.locations_dictionary.items():
connections = self.connections_dictionary[key]
print("Node:" + key + " \t\tLocation:" + str(value) +
"\t\tConnections:" + str(connections))
def exclude_node(self, excluded_node):
excluded_connections = self.connections_dictionary[excluded_node]
del self.connections_dictionary[excluded_node]
del self.locations_dictionary[excluded_node]
for node in excluded_connections:
target_list = self.connections_dictionary[node]
target_list.remove(excluded_node)
def main():
my_map = Map("connections.txt", "locations.txt")
my_map.print_all()
print("************************************************************")
my_map2 = Map("connections.txt", "locations.txt")
my_map2.exclude_node("A1")
my_map2.print_all()
if __name__ == "__main__":
main()
|
import numpy as np
import math
from sklearn.linear_model import LinearRegression
def curve(pc_lane):
left_lane = pc_lane[pc_lane[:][:,1]<-1]
left_lane = left_lane[left_lane[:][:,1]>-3]
left_lane = left_lane[left_lane[:][:,0]<20]
right_lane = pc_lane[pc_lane[:][:,1]>1]
right_lane = right_lane[right_lane[:][:,1]<3]
right_lane = right_lane[right_lane[:][:,0]<20]
# left_lane = pc_lane[pc_lane[:][:,1]<-2]
# left_lane = left_lane[left_lane[:][:,1]>-4]
# left_lane = left_lane[left_lane[:][:,0]<15]
# right_lane = pc_lane[pc_lane[:][:,1]>1]
# right_lane = right_lane[right_lane[:][:,1]<3]
# right_lane = right_lane[right_lane[:][:,0]<15]
line_fitter1 = LinearRegression()
line_fitter2 = LinearRegression()
len1 = len(left_lane[:][:,0])
len2 = len(right_lane[:][:,0])
xline1 = left_lane[:][:,0].reshape(-1,1)
yline1 = left_lane[:][:,1].reshape(-1,1)
xline2 = right_lane[:][:,0].reshape(-1,1)
yline2 = right_lane[:][:,1].reshape(-1,1)
line1_fit = line_fitter1.fit(xline1,yline1)
line2_fit = line_fitter2.fit(xline2,yline2)
line1dy = line1_fit.coef_
line2dy = line2_fit.coef_
# line1c = line1_fit.intercept_
# line2c = line2_fit.intercept_
# line1pred = line1_fit.predict(xline1).reshape([len1,1])
# line2pred = line2_fit.predict(xline2).reshape([len2,1])
return left_lane, right_lane, line1_fit, line2_fit
def line_equation(x,line_dy,line_c):
y = (x-line_c)/line_dy
return y
def invadeROI(point, leftdy, rightdy, leftc, rightc):
y_left = line_equation(point[0], leftdy, leftc)
y_right = line_equation(point[0], rightdy, rightc)
if point[1]>y_left and point[1]<y_right: invade = True
else: invade = False
return invade
def roi_box(left_lane, right_lane, line1_fit, line2_fit):
line1pred = line1_fit.predict(left_lane[:,0]).reshape([len1,1])
line2pred = line2_fit.predict(right_lane[:,0]).reshape([len2,1])
left_max = left_lane[:][np.argmax(line1pred),:2]
left_min = left_lane[:][np.argmin(line1pred),:2]
left_min = left_lane[:][np.argmin(line1pred),:2]
|
#!/usr/bin/env python
import rospy
from sensor_msgs.msg import Imu
def callback(msg):
print "Quaternoion ================"
print "x : ", msg.orientation.x
print "y : ", msg.orientation.y
print "z : ", msg.orientation.z
print "w : ", msg.orientation.w
rospy.init_node('get_imu_data')
sub = rospy.Subscriber('imu', Imu, callback)
rospy.spin() |
import pandas as pd
import requests
import bs4
import datetime
coins = ['Bitcoin','Ethereum', 'Ripple', 'Litecoin', 'Monero', 'Cardano']
coins = [coin.lower() for coin in coins]
for coin in coins:
response = requests.get('https://coinmarketcap.com/currencies/'+coin+'/historical-data/')
soup = bs4.BeautifulSoup(response.text)
table = soup.find('table')
rows = table.find_all('tr')
data =[]
for row in rows:
cols = row.find_all('td')
cols = [ele.text.strip() for ele in cols]
data.append([ele for ele in cols]) # add data to dict
df =pd.DataFrame(data,columns=['Date','Open','High','Low','Close','Volume','Market_Cap'])
df = df.iloc[1:,:]
date_num = str(datetime.datetime.now().day)+'_'+ str(datetime.datetime.now().month)
df.to_csv('C:\\Users\\secret\\Desktop\\Python\\Sublime\\Dissertation\\Data Storage\\'+coin+date_num+'.csv')
|
from bs4 import BeautifulSoup
def evaluate(indicesCreated, actualSummaryPath, completeFilePath):
truePositive = 0
trueNegative = 0
falsePositive = 0
falseNegative = 0
print indicesCreated
actualSummary = open(actualSummaryPath, 'r').read()
soup = BeautifulSoup(actualSummary)
completeFile = open(completeFilePath, 'r').readlines()
completeFile = map(lambda x: x.strip(), completeFile)
indicesInActual = []
for node in soup.findAll('s'):
text = node.text.replace('\n','')
text = text.strip()
indicesInActual.append(completeFile.index(text))
#indicesInCreated = set(IndicesInCreated)
print indicesInActual
totalSentencesInComplete = len(completeFile)
for i in range(totalSentencesInComplete):
if i in indicesCreated:
if i in indicesInActual:
truePositive += 1
else:
falsePositive += 1
else:
if i in indicesInActual:
falseNegative += 1
else:
trueNegative += 1
precision = 1.0*truePositive/(truePositive+falsePositive)
recall = 1.0*truePositive/(truePositive+falseNegative)
f1 = 2*precision*recall/(precision+recall)
return [precision, recall, f1]
|
# SPDX-License-Identifier: MIT
# Copyright (c) 2021 scmanjarrez. All rights reserved.
# This work is licensed under the terms of the MIT license.
from telegram import InlineKeyboardButton, InlineKeyboardMarkup
from datetime import datetime
import database as db
import threads as th
import util as ut
STATE = {}
def _state(uid, state, value):
if uid not in STATE:
STATE[uid] = {}
if state not in STATE[uid]:
STATE[uid][state] = value
def del_state(uid):
if uid in STATE:
del STATE[uid]
def _del_substate(uid, state):
if uid in STATE and state in STATE[uid]:
del STATE[uid][state]
def button(buttons):
return [InlineKeyboardButton(bt[0], callback_data=bt[1]) for bt in buttons]
def menu(update, context):
uid = ut.uid(update)
if not db.banned(uid):
if not db.cached(uid):
ut.not_started(update)
else:
main_menu(update)
def main_menu(update):
kb = [button([("🌙 Resin 🌙", 'resin_menu')]),
button([("⚙ Settings ⚙", 'settings_menu')])]
resp = ut.send
if update.callback_query is not None:
resp = ut.edit
resp(update, "Main Menu", reply_markup=InlineKeyboardMarkup(kb))
def _tracking_status(uid):
if th.is_unsync(uid):
return '🟠'
if th.is_tracked(uid):
return '🟢'
return '🔴'
def resin_menu(update):
uid = ut.uid(update)
cur_resin = db.get_resin(uid)
tracking = _tracking_status(uid)
kb = [button([(f"🌙 {cur_resin} 🌙", 'resin_menu'),
(f"Tracking: {tracking}", 'tracking_menu')]),
button(ut.gui_cap_format(uid)),
button([("Spend", 'spend_menu'),
("Refill", 'refill_menu')]),
button([("« Back to Menu", 'main_menu')])]
ut.edit(update, "Resin Menu", InlineKeyboardMarkup(kb))
def tracking_menu(update):
uid = ut.uid(update)
_state(uid, ut.CMD.TRACK, list(ut.TRACK_MAX))
st_track = STATE[uid][ut.CMD.TRACK]
tracking = _tracking_status(uid)
kb = [button([(f"Tracking: {tracking}", 'tracking_menu')]),
button([("« Back to Resin", 'resin_menu'),
("« Back to Menu", 'main_menu')])]
track_txt = "Start Tracking"
if th.is_unsync(uid):
track_txt = "Synchronize"
if th.is_unsync(uid) or not th.is_tracked(uid):
kb.insert(1, button([("˄", 'tracking_up0'),
(" ", 'nop'),
("˄", 'tracking_up1'),
("˄", 'tracking_up2')]))
kb.insert(2, button([(st_track[0], 'nop'),
(":", 'nop'),
(st_track[1], 'nop'),
(st_track[2], 'nop')]))
kb.insert(3, button([("˅", 'tracking_down0'),
(" ", 'nop'),
("˅", 'tracking_down1'),
("˅", 'tracking_down2')]))
kb.insert(4, button([(track_txt, 'tracking_start')]))
if th.is_unsync(uid) or th.is_tracked(uid):
idx = 1
if th.is_unsync(uid):
idx = 5
kb.insert(idx, button([("Stop Tracking", 'tracking_stop')]))
ut.edit(update, "Tracking Menu", InlineKeyboardMarkup(kb))
def tracking_start(update, context):
uid = ut.uid(update)
mm = int(update.callback_query.message.reply_markup
.inline_keyboard[2][0]['text'])
s1 = int(update.callback_query.message.reply_markup
.inline_keyboard[2][2]['text'])
s2 = int(update.callback_query.message.reply_markup
.inline_keyboard[2][3]['text'])
th.new_thread(context.bot, uid, mm*60 + s1*10 + s2)
tracking_menu(update)
def tracking_stop(update):
uid = ut.uid(update)
th.del_thread(uid)
tracking_menu(update)
def tracking_updown(update, up=True):
uid = ut.uid(update)
_state(uid, ut.CMD.TRACK, list(ut.TRACK_MAX))
st_track = STATE[uid][ut.CMD.TRACK]
txt = 'tracking_down'
if up:
txt = 'tracking_up'
pos = int(update.callback_query.data.split(txt)[1])
if up:
if st_track[pos] < ut.TRACK_MAX[pos]:
st_track[pos] += 1
else:
if st_track[pos] > 0:
st_track[pos] -= 1
tracking_menu(update)
def spend_menu(update):
uid = ut.uid(update)
cur_resin = db.get_resin(uid)
kb = [button([(f"🌙 {cur_resin} 🌙", 'spend_menu')]),
[],
button([("« Back to Resin", 'resin_menu'),
("« Back to Menu", 'main_menu')])]
if cur_resin >= 10:
kb[1].append(button([("10", 'spend_r10')])[0])
else:
kb[1].append(button([("No Resin Left!", 'nop')])[0])
if cur_resin >= 20:
kb[1].append(button([("20", 'spend_r20')])[0])
if cur_resin >= 30:
kb[1].append(button([("30", 'spend_r30')])[0])
if cur_resin >= 40:
kb[1].append(button([("40", 'spend_r40')])[0])
if cur_resin >= 60:
kb[1].append(button([("60", 'spend_r60')])[0])
if cur_resin >= 80:
kb[1].append(button([("80", 'spend_r80')])[0])
if cur_resin >= 90:
kb[1].append(button([("90", 'spend_r90')])[0])
if cur_resin >= 120:
kb[1].append(button([("120", 'spend_r120')])[0])
ut.edit(update, "Spend Menu", InlineKeyboardMarkup(kb))
def spend_resin(update):
uid = ut.uid(update)
resin = int(update.callback_query.data.split('spend_r')[1])
db.dec_resin(uid, resin)
spend_menu(update)
def refill_menu(update):
uid = ut.uid(update)
cur_resin = db.get_resin(uid)
_state(uid, ut.CMD.REFILL, list(ut.REFILL_BASE))
st_refill = STATE[uid][ut.CMD.REFILL]
kb = [button([(f"🌙 {cur_resin} 🌙", 'refill_menu')]),
button([("˄", 'refill_up0'),
("˄", 'refill_up1'),
("˄", 'refill_up2')]),
button([(st_refill[0], 'nop'),
(st_refill[1], 'nop'),
(st_refill[2], 'nop')]),
button([("˅", 'refill_down0'),
("˅", 'refill_down1'),
("˅", 'refill_down2')]),
button([("Refill", 'refill_r')]),
button([("« Back to Resin", 'resin_menu'),
("« Back to Menu", 'main_menu')])]
ut.edit(update, "Refill Menu", InlineKeyboardMarkup(kb))
def refill_resin(update):
uid = ut.uid(update)
r0 = (update.callback_query.message.reply_markup
.inline_keyboard[2][0]['text'])
r1 = (update.callback_query.message.reply_markup
.inline_keyboard[2][1]['text'])
r2 = (update.callback_query.message.reply_markup
.inline_keyboard[2][2]['text'])
value = int("".join([r0, r1, r2]))
db.inc_resin(uid, value)
refill_menu(update)
def refill_updown(update, up=True):
uid = ut.uid(update)
_state(uid, ut.CMD.REFILL, list(ut.REFILL_BASE))
st_refill = STATE[uid][ut.CMD.REFILL]
cur_resin = db.get_resin(uid)
txt = 'refill_up'
if not up:
txt = 'refill_down'
pos = int(update.callback_query.data.split(txt)[1])
if up:
st_refill[pos] = (st_refill[pos] + 1) % 10
else:
st_refill[pos] = (st_refill[pos] - 1) % 10
if int("".join(str(c) for c in st_refill)) > ut.RESIN_MAX - cur_resin:
new_state = ut.RESIN_MAX - cur_resin
if new_state < 0:
new_state = 0
STATE[uid][ut.CMD.REFILL] = [int(el) for el in f"{new_state:03d}"]
refill_menu(update)
def settings_menu(update):
kb = [button([("⏰ Warning Settings ⏰", 'settings_warn_menu')]),
button([("🌎 Timezone Settings 🌎", 'settings_timezone_menu')]),
button([("« Back to Menu", 'main_menu')])]
ut.edit(update, "Settings Menu", InlineKeyboardMarkup(kb))
def settings_warn_menu(update):
uid = ut.uid(update)
cur_warn = db.get_warn(uid)
if cur_warn != -1:
_state(uid, ut.CMD.WARN, [int(cw) for cw in f"{cur_warn:03d}"])
warn_icon = '🔔'
else:
_state(uid, ut.CMD.WARN, [int(cw) for cw in f"{ut.RESIN_MAX-10:03d}"])
cur_warn = 'disabled'
warn_icon = '🔕'
st_warn = STATE[uid][ut.CMD.WARN]
kb = [button([(f"Threshold: {cur_warn}", 'settings_warn_menu'),
(f"Resin Warnings: {warn_icon}", 'warn_toggle')]),
button([("˄", 'warn_up0'),
("˄", 'warn_up1'),
("˄", 'warn_up2')]),
button([(st_warn[0], 'nop'),
(st_warn[1], 'nop'),
(st_warn[2], 'nop')]),
button([("˅", 'warn_down0'),
("˅", 'warn_down1'),
("˅", 'warn_down2')]),
button([("Set Warning Threshold", 'warn_threshold')]),
button([("« Back to Settings", 'settings_menu'),
("« Back to Menu", 'main_menu')])]
ut.edit(update, "Warnings Settings Menu", InlineKeyboardMarkup(kb))
def _warn_value(update):
r0 = (update.callback_query.message.reply_markup
.inline_keyboard[2][0]['text'])
r1 = (update.callback_query.message.reply_markup
.inline_keyboard[2][1]['text'])
r2 = (update.callback_query.message.reply_markup
.inline_keyboard[2][2]['text'])
value = int("".join([r0, r1, r2]))
return value
def warn_toggle(update):
uid = ut.uid(update)
cur_warn = db.get_warn(uid)
if cur_warn == -1:
db.set_warn(uid, _warn_value(update))
else:
db.unset_warn(uid)
settings_warn_menu(update)
def warn_threshold(update):
uid = ut.uid(update)
db.set_warn(uid, _warn_value(update))
settings_warn_menu(update)
def warn_updown(update, up=True):
uid = ut.uid(update)
cur_warn = db.get_warn(uid)
if cur_warn != -1:
_state(uid, ut.CMD.WARN, [int(cw) for cw in f"{cur_warn:03d}"])
else:
_state(uid, ut.CMD.WARN, [int(cw) for cw in f"{ut.RESIN_MAX-10:03d}"])
st_warn = STATE[uid][ut.CMD.WARN]
txt = 'warn_down'
if up:
txt = 'warn_up'
pos = int(update.callback_query.data.split(txt)[1])
if up:
st_warn[pos] = (st_warn[pos] + 1) % 10
else:
st_warn[pos] = (st_warn[pos] - 1) % 10
value = int(''.join(str(c) for c in st_warn))
if value > 159:
STATE[uid][ut.CMD.WARN] = [1, 5, 9]
settings_warn_menu(update)
def settings_timezone_menu(update):
uid = ut.uid(update)
bot_hour, bot_minutes = map(int, datetime.now()
.strftime("%H:%M").split(':'))
tz_hour, tz_minutes = db.get_timezone(uid).split(':')
if tz_hour == 'null':
tz = 'disabled'
else:
tz = ut.normalize_timezone(tz_hour, tz_minutes)
kb = [button([(f"Bot Hour: {bot_hour:02}:{bot_minutes:02}",
'settings_timezone_menu')]),
button([(f"Current timezone: {tz}", 'timezone_menu')]),
button([("« Back to Settings", 'settings_menu'),
("« Back to Menu", 'main_menu')])]
ut.edit(update, "Timezone Settings Menu", InlineKeyboardMarkup(kb))
def timezone_menu(update, modified=False):
uid = ut.uid(update)
tz_hour, tz_minutes = db.get_timezone(uid).split(':')
if tz_hour == 'null':
tz = 'disabled'
cur_hour, cur_minutes = ut.user_hour(0, 0, 0, 0)
else:
tz = ut.normalize_timezone(tz_hour, tz_minutes)
cur_hour, cur_minutes = ut.user_hour(0, 0,
int(tz_hour), int(tz_minutes))
if modified:
cur_hour, cur_minutes = STATE[uid][ut.CMD.TZ]
else:
_del_substate(uid, ut.CMD.TZ)
kb = [button([(f"Current timezone: {tz}", 'timezone_menu')]),
button([("˄", 'timezone_up0'),
("˄", 'timezone_up1'),
("˄", 'timezone_up2'),
("˄", 'timezone_up3')]),
button([(cur_hour // 10, 'nop'),
(cur_hour % 10, 'nop'),
(cur_minutes // 10, 'nop'),
(cur_minutes % 10, 'nop')]),
button([("˅", 'timezone_down0'),
("˅", 'timezone_down1'),
("˅", 'timezone_down2'),
("˅", 'timezone_down3')]),
button([("Set Hour", 'timezone_set')]),
button([("« Back to Timezone Settings", 'settings_timezone_menu'),
("« Back to Menu", 'main_menu')])]
if tz != 'disabled':
kb.insert(len(kb) - 1,
button([("Disable Timezone", 'timezone_disable')]))
ut.edit(update, "Timezone Menu", InlineKeyboardMarkup(kb))
def _timezone_value(update):
r0 = (update.callback_query.message.reply_markup
.inline_keyboard[2][0]['text'])
r1 = (update.callback_query.message.reply_markup
.inline_keyboard[2][1]['text'])
r2 = (update.callback_query.message.reply_markup
.inline_keyboard[2][2]['text'])
r3 = (update.callback_query.message.reply_markup
.inline_keyboard[2][3]['text'])
tz_hour = int("".join([r0, r1]))
tz_minutes = int("".join([r2, r3]))
return tz_hour, tz_minutes
def timezone_updown(update, up=True):
uid = ut.uid(update)
txt = 'timezone_down'
if up:
txt = 'timezone_up'
pos = int(update.callback_query.data.split(txt)[1])
tz_hour, tz_minutes = _timezone_value(update)
values = [tz_hour // 10, tz_hour % 10, tz_minutes // 10, tz_minutes % 10]
if up:
values[pos] = (values[pos] + 1) % 10
else:
values[pos] = (values[pos] - 1) % 10
tz_hour = int("".join(str(v) for v in values[:2]))
if tz_hour > 23:
tz_hour = 23
tz_minutes = int("".join(str(v) for v in values[2:]))
if tz_minutes > 59:
tz_minutes = 59
_state(uid, ut.CMD.TZ, [tz_hour, tz_minutes]) # only update first time
STATE[uid][ut.CMD.TZ] = [tz_hour, tz_minutes]
timezone_menu(update, modified=True)
def timezone_disable(update):
uid = ut.uid(update)
db.unset_timezone(uid)
settings_timezone_menu(update)
def timezone_set(update):
uid = ut.uid(update)
value_hour, value_minutes = _timezone_value(update)
bot_hour, bot_minutes = map(int, datetime.now()
.strftime("%H:%M").split(':'))
tz_hour = value_hour - bot_hour
tz_minutes = value_minutes - bot_minutes
db.set_timezone(uid, tz_hour, tz_minutes)
settings_timezone_menu(update)
|
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'C:\Users\QC\Desktop\IonTrap-WIPM-master\IonTrap-WIPM-master\GUI_Material\QC2_0TEST.ui'
#
# Created by: PyQt5 UI code generator 5.13.2
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(586, 888)
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(9)
font.setBold(False)
font.setWeight(50)
font.setStrikeOut(False)
MainWindow.setFont(font)
MainWindow.setLayoutDirection(QtCore.Qt.LeftToRight)
MainWindow.setIconSize(QtCore.QSize(30, 30))
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.line = QtWidgets.QFrame(self.centralwidget)
self.line.setGeometry(QtCore.QRect(50, 80, 481, 20))
self.line.setFrameShape(QtWidgets.QFrame.HLine)
self.line.setFrameShadow(QtWidgets.QFrame.Sunken)
self.line.setObjectName("line")
self.label_20 = QtWidgets.QLabel(self.centralwidget)
self.label_20.setGeometry(QtCore.QRect(50, 20, 491, 61))
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(9)
font.setBold(False)
font.setItalic(False)
font.setWeight(50)
font.setStrikeOut(False)
self.label_20.setFont(font)
self.label_20.setObjectName("label_20")
self.label_10 = QtWidgets.QLabel(self.centralwidget)
self.label_10.setGeometry(QtCore.QRect(60, 470, 131, 41))
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(10)
font.setBold(True)
font.setItalic(False)
font.setWeight(75)
font.setStrikeOut(False)
self.label_10.setFont(font)
self.label_10.setObjectName("label_10")
self.label_33 = QtWidgets.QLabel(self.centralwidget)
self.label_33.setGeometry(QtCore.QRect(50, 100, 131, 41))
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(10)
font.setBold(True)
font.setItalic(False)
font.setWeight(75)
font.setStrikeOut(False)
self.label_33.setFont(font)
self.label_33.setObjectName("label_33")
self.radioButton_rabi = QtWidgets.QRadioButton(self.centralwidget)
self.radioButton_rabi.setGeometry(QtCore.QRect(420, 540, 115, 19))
self.radioButton_rabi.setObjectName("radioButton_rabi")
self.radioButton_zeeman = QtWidgets.QRadioButton(self.centralwidget)
self.radioButton_zeeman.setGeometry(QtCore.QRect(420, 580, 115, 19))
self.radioButton_zeeman.setObjectName("radioButton_zeeman")
self.radioButton_cust = QtWidgets.QRadioButton(self.centralwidget)
self.radioButton_cust.setGeometry(QtCore.QRect(420, 620, 115, 19))
self.radioButton_cust.setObjectName("radioButton_cust")
self.pushButton = QtWidgets.QPushButton(self.centralwidget)
self.pushButton.setGeometry(QtCore.QRect(420, 700, 111, 81))
self.pushButton.setObjectName("pushButton")
self.radioButton_off = QtWidgets.QRadioButton(self.centralwidget)
self.radioButton_off.setGeometry(QtCore.QRect(420, 660, 115, 19))
self.radioButton_off.setChecked(True)
self.radioButton_off.setObjectName("radioButton_off")
self.Setting = QtWidgets.QTabWidget(self.centralwidget)
self.Setting.setGeometry(QtCore.QRect(50, 150, 481, 311))
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(9)
font.setBold(False)
font.setWeight(50)
font.setStrikeOut(False)
self.Setting.setFont(font)
self.Setting.setObjectName("Setting")
self.DPL_Cooling = QtWidgets.QWidget()
self.DPL_Cooling.setObjectName("DPL_Cooling")
self.doubleSpinBox_DPL = QtWidgets.QDoubleSpinBox(self.DPL_Cooling)
self.doubleSpinBox_DPL.setGeometry(QtCore.QRect(140, 30, 101, 41))
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(9)
font.setBold(False)
font.setWeight(50)
font.setStrikeOut(False)
self.doubleSpinBox_DPL.setFont(font)
self.doubleSpinBox_DPL.setLayoutDirection(QtCore.Qt.LeftToRight)
self.doubleSpinBox_DPL.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignVCenter)
self.doubleSpinBox_DPL.setMaximum(999999.99)
self.doubleSpinBox_DPL.setObjectName("doubleSpinBox_DPL")
self.label_36 = QtWidgets.QLabel(self.DPL_Cooling)
self.label_36.setGeometry(QtCore.QRect(260, 30, 31, 41))
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(9)
font.setBold(False)
font.setWeight(50)
font.setStrikeOut(False)
self.label_36.setFont(font)
self.label_36.setObjectName("label_36")
self.label_37 = QtWidgets.QLabel(self.DPL_Cooling)
self.label_37.setGeometry(QtCore.QRect(20, 30, 131, 41))
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(9)
font.setBold(False)
font.setWeight(50)
font.setStrikeOut(False)
self.label_37.setFont(font)
self.label_37.setObjectName("label_37")
self.Laser_397_1_DPL = QtWidgets.QCheckBox(self.DPL_Cooling)
self.Laser_397_1_DPL.setGeometry(QtCore.QRect(150, 160, 91, 19))
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(9)
font.setBold(False)
font.setWeight(50)
font.setStrikeOut(False)
self.Laser_397_1_DPL.setFont(font)
self.Laser_397_1_DPL.setChecked(True)
self.Laser_397_1_DPL.setObjectName("Laser_397_1_DPL")
self.Laser_397_2_DPL = QtWidgets.QCheckBox(self.DPL_Cooling)
self.Laser_397_2_DPL.setGeometry(QtCore.QRect(230, 160, 91, 19))
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(9)
font.setBold(False)
font.setWeight(50)
font.setStrikeOut(False)
self.Laser_397_2_DPL.setFont(font)
self.Laser_397_2_DPL.setChecked(True)
self.Laser_397_2_DPL.setObjectName("Laser_397_2_DPL")
self.Laser_397_3_DPL = QtWidgets.QCheckBox(self.DPL_Cooling)
self.Laser_397_3_DPL.setGeometry(QtCore.QRect(310, 160, 91, 19))
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(9)
font.setBold(False)
font.setWeight(50)
font.setStrikeOut(False)
self.Laser_397_3_DPL.setFont(font)
self.Laser_397_3_DPL.setChecked(True)
self.Laser_397_3_DPL.setObjectName("Laser_397_3_DPL")
self.Laser_397_main_DPL = QtWidgets.QCheckBox(self.DPL_Cooling)
self.Laser_397_main_DPL.setGeometry(QtCore.QRect(30, 160, 91, 19))
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(9)
font.setBold(False)
font.setItalic(False)
font.setUnderline(False)
font.setWeight(50)
font.setStrikeOut(False)
self.Laser_397_main_DPL.setFont(font)
self.Laser_397_main_DPL.setChecked(True)
self.Laser_397_main_DPL.setObjectName("Laser_397_main_DPL")
self.Laser_866_DPL = QtWidgets.QCheckBox(self.DPL_Cooling)
self.Laser_866_DPL.setGeometry(QtCore.QRect(30, 200, 91, 19))
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(9)
font.setBold(False)
font.setUnderline(True)
font.setWeight(50)
font.setStrikeOut(False)
self.Laser_866_DPL.setFont(font)
self.Laser_866_DPL.setChecked(True)
self.Laser_866_DPL.setObjectName("Laser_866_DPL")
self.Laser_854_DPL = QtWidgets.QCheckBox(self.DPL_Cooling)
self.Laser_854_DPL.setGeometry(QtCore.QRect(30, 240, 91, 19))
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(9)
font.setBold(False)
font.setUnderline(True)
font.setWeight(50)
font.setStrikeOut(False)
self.Laser_854_DPL.setFont(font)
self.Laser_854_DPL.setChecked(True)
self.Laser_854_DPL.setObjectName("Laser_854_DPL")
self.line_2 = QtWidgets.QFrame(self.DPL_Cooling)
self.line_2.setGeometry(QtCore.QRect(20, 80, 431, 20))
self.line_2.setFrameShape(QtWidgets.QFrame.HLine)
self.line_2.setFrameShadow(QtWidgets.QFrame.Sunken)
self.line_2.setObjectName("line_2")
self.label_42 = QtWidgets.QLabel(self.DPL_Cooling)
self.label_42.setGeometry(QtCore.QRect(20, 100, 131, 41))
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(9)
font.setBold(False)
font.setWeight(50)
font.setStrikeOut(False)
self.label_42.setFont(font)
self.label_42.setObjectName("label_42")
self.line_4 = QtWidgets.QFrame(self.DPL_Cooling)
self.line_4.setGeometry(QtCore.QRect(120, 160, 20, 101))
self.line_4.setFrameShape(QtWidgets.QFrame.VLine)
self.line_4.setFrameShadow(QtWidgets.QFrame.Sunken)
self.line_4.setObjectName("line_4")
self.label_44 = QtWidgets.QLabel(self.DPL_Cooling)
self.label_44.setGeometry(QtCore.QRect(150, 200, 131, 21))
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(9)
font.setBold(False)
font.setWeight(50)
font.setStrikeOut(False)
self.label_44.setFont(font)
self.label_44.setObjectName("label_44")
self.label_45 = QtWidgets.QLabel(self.DPL_Cooling)
self.label_45.setGeometry(QtCore.QRect(150, 240, 131, 21))
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(9)
font.setBold(False)
font.setWeight(50)
font.setStrikeOut(False)
self.label_45.setFont(font)
self.label_45.setObjectName("label_45")
self.Setting.addTab(self.DPL_Cooling, "")
self.tab_6 = QtWidgets.QWidget()
self.tab_6.setObjectName("tab_6")
self.label_41 = QtWidgets.QLabel(self.tab_6)
self.label_41.setGeometry(QtCore.QRect(20, 30, 131, 41))
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(9)
font.setBold(False)
font.setWeight(50)
font.setStrikeOut(False)
self.label_41.setFont(font)
self.label_41.setObjectName("label_41")
self.label_40 = QtWidgets.QLabel(self.tab_6)
self.label_40.setGeometry(QtCore.QRect(260, 30, 31, 41))
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(9)
font.setBold(False)
font.setWeight(50)
font.setStrikeOut(False)
self.label_40.setFont(font)
self.label_40.setObjectName("label_40")
self.doubleSpinBox_OP = QtWidgets.QDoubleSpinBox(self.tab_6)
self.doubleSpinBox_OP.setGeometry(QtCore.QRect(140, 30, 101, 41))
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(9)
font.setBold(False)
font.setWeight(50)
font.setStrikeOut(False)
self.doubleSpinBox_OP.setFont(font)
self.doubleSpinBox_OP.setLayoutDirection(QtCore.Qt.LeftToRight)
self.doubleSpinBox_OP.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignVCenter)
self.doubleSpinBox_OP.setMaximum(999999.99)
self.doubleSpinBox_OP.setObjectName("doubleSpinBox_OP")
self.Laser_729_1_OP = QtWidgets.QCheckBox(self.tab_6)
self.Laser_729_1_OP.setGeometry(QtCore.QRect(150, 160, 91, 21))
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(9)
font.setBold(False)
font.setWeight(50)
font.setStrikeOut(False)
self.Laser_729_1_OP.setFont(font)
self.Laser_729_1_OP.setObjectName("Laser_729_1_OP")
self.Laser_729_3_OP = QtWidgets.QCheckBox(self.tab_6)
self.Laser_729_3_OP.setGeometry(QtCore.QRect(310, 160, 91, 21))
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(9)
font.setBold(False)
font.setWeight(50)
font.setStrikeOut(False)
self.Laser_729_3_OP.setFont(font)
self.Laser_729_3_OP.setObjectName("Laser_729_3_OP")
self.Laser_729_2_OP = QtWidgets.QCheckBox(self.tab_6)
self.Laser_729_2_OP.setGeometry(QtCore.QRect(230, 160, 91, 21))
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(9)
font.setBold(False)
font.setWeight(50)
font.setStrikeOut(False)
self.Laser_729_2_OP.setFont(font)
self.Laser_729_2_OP.setObjectName("Laser_729_2_OP")
self.Laser_729_4_OP = QtWidgets.QCheckBox(self.tab_6)
self.Laser_729_4_OP.setGeometry(QtCore.QRect(390, 160, 91, 21))
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(9)
font.setBold(False)
font.setWeight(50)
font.setStrikeOut(False)
self.Laser_729_4_OP.setFont(font)
self.Laser_729_4_OP.setObjectName("Laser_729_4_OP")
self.Laser_854_OP = QtWidgets.QCheckBox(self.tab_6)
self.Laser_854_OP.setGeometry(QtCore.QRect(30, 200, 91, 19))
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(9)
font.setBold(False)
font.setUnderline(True)
font.setWeight(50)
font.setStrikeOut(False)
self.Laser_854_OP.setFont(font)
self.Laser_854_OP.setCheckable(True)
self.Laser_854_OP.setChecked(True)
self.Laser_854_OP.setObjectName("Laser_854_OP")
self.line_3 = QtWidgets.QFrame(self.tab_6)
self.line_3.setGeometry(QtCore.QRect(20, 80, 431, 20))
self.line_3.setFrameShape(QtWidgets.QFrame.HLine)
self.line_3.setFrameShadow(QtWidgets.QFrame.Sunken)
self.line_3.setObjectName("line_3")
self.Laser_729_main_OP = QtWidgets.QCheckBox(self.tab_6)
self.Laser_729_main_OP.setGeometry(QtCore.QRect(30, 160, 91, 21))
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(9)
font.setBold(False)
font.setItalic(False)
font.setUnderline(True)
font.setWeight(50)
font.setStrikeOut(False)
self.Laser_729_main_OP.setFont(font)
self.Laser_729_main_OP.setChecked(True)
self.Laser_729_main_OP.setObjectName("Laser_729_main_OP")
self.label_43 = QtWidgets.QLabel(self.tab_6)
self.label_43.setGeometry(QtCore.QRect(20, 100, 131, 41))
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(9)
font.setBold(False)
font.setWeight(50)
font.setStrikeOut(False)
self.label_43.setFont(font)
self.label_43.setObjectName("label_43")
self.line_5 = QtWidgets.QFrame(self.tab_6)
self.line_5.setGeometry(QtCore.QRect(120, 160, 20, 101))
self.line_5.setFrameShape(QtWidgets.QFrame.VLine)
self.line_5.setFrameShadow(QtWidgets.QFrame.Sunken)
self.line_5.setObjectName("line_5")
self.label_46 = QtWidgets.QLabel(self.tab_6)
self.label_46.setGeometry(QtCore.QRect(150, 200, 131, 21))
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(9)
font.setBold(False)
font.setWeight(50)
font.setStrikeOut(False)
self.label_46.setFont(font)
self.label_46.setObjectName("label_46")
self.Setting.addTab(self.tab_6, "")
self.tab_2 = QtWidgets.QWidget()
self.tab_2.setObjectName("tab_2")
self.doubleSpinBox_SB = QtWidgets.QDoubleSpinBox(self.tab_2)
self.doubleSpinBox_SB.setGeometry(QtCore.QRect(140, 30, 101, 41))
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(9)
font.setBold(False)
font.setWeight(50)
font.setStrikeOut(False)
self.doubleSpinBox_SB.setFont(font)
self.doubleSpinBox_SB.setLayoutDirection(QtCore.Qt.LeftToRight)
self.doubleSpinBox_SB.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignVCenter)
self.doubleSpinBox_SB.setMaximum(999999.99)
self.doubleSpinBox_SB.setObjectName("doubleSpinBox_SB")
self.label_53 = QtWidgets.QLabel(self.tab_2)
self.label_53.setGeometry(QtCore.QRect(20, 30, 131, 41))
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(9)
font.setBold(False)
font.setUnderline(True)
font.setWeight(50)
font.setStrikeOut(False)
self.label_53.setFont(font)
self.label_53.setObjectName("label_53")
self.label_54 = QtWidgets.QLabel(self.tab_2)
self.label_54.setGeometry(QtCore.QRect(260, 30, 31, 41))
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(9)
font.setBold(False)
font.setWeight(50)
font.setStrikeOut(False)
self.label_54.setFont(font)
self.label_54.setObjectName("label_54")
self.Setting.addTab(self.tab_2, "")
self.tab_7 = QtWidgets.QWidget()
self.tab_7.setObjectName("tab_7")
self.Laser_729_4_opreating = QtWidgets.QCheckBox(self.tab_7)
self.Laser_729_4_opreating.setGeometry(QtCore.QRect(390, 160, 91, 21))
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(9)
font.setBold(False)
font.setWeight(50)
font.setStrikeOut(False)
self.Laser_729_4_opreating.setFont(font)
self.Laser_729_4_opreating.setObjectName("Laser_729_4_opreating")
self.Laser_729_main_opreating = QtWidgets.QCheckBox(self.tab_7)
self.Laser_729_main_opreating.setGeometry(QtCore.QRect(30, 160, 91, 21))
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(9)
font.setBold(False)
font.setItalic(False)
font.setUnderline(True)
font.setWeight(50)
font.setStrikeOut(False)
self.Laser_729_main_opreating.setFont(font)
self.Laser_729_main_opreating.setChecked(True)
self.Laser_729_main_opreating.setObjectName("Laser_729_main_opreating")
self.Laser_729_1_opreating = QtWidgets.QCheckBox(self.tab_7)
self.Laser_729_1_opreating.setGeometry(QtCore.QRect(150, 160, 91, 21))
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(9)
font.setBold(False)
font.setWeight(50)
font.setStrikeOut(False)
self.Laser_729_1_opreating.setFont(font)
self.Laser_729_1_opreating.setObjectName("Laser_729_1_opreating")
self.Laser_854_opreating = QtWidgets.QCheckBox(self.tab_7)
self.Laser_854_opreating.setGeometry(QtCore.QRect(30, 200, 91, 19))
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(9)
font.setBold(False)
font.setUnderline(True)
font.setWeight(50)
font.setStrikeOut(False)
self.Laser_854_opreating.setFont(font)
self.Laser_854_opreating.setChecked(True)
self.Laser_854_opreating.setObjectName("Laser_854_opreating")
self.line_6 = QtWidgets.QFrame(self.tab_7)
self.line_6.setGeometry(QtCore.QRect(120, 160, 20, 101))
self.line_6.setFrameShape(QtWidgets.QFrame.VLine)
self.line_6.setFrameShadow(QtWidgets.QFrame.Sunken)
self.line_6.setObjectName("line_6")
self.Laser_729_2_opreating = QtWidgets.QCheckBox(self.tab_7)
self.Laser_729_2_opreating.setGeometry(QtCore.QRect(230, 160, 91, 21))
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(9)
font.setBold(False)
font.setWeight(50)
font.setStrikeOut(False)
self.Laser_729_2_opreating.setFont(font)
self.Laser_729_2_opreating.setObjectName("Laser_729_2_opreating")
self.label_47 = QtWidgets.QLabel(self.tab_7)
self.label_47.setGeometry(QtCore.QRect(260, 30, 31, 41))
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(9)
font.setBold(False)
font.setWeight(50)
font.setStrikeOut(False)
self.label_47.setFont(font)
self.label_47.setObjectName("label_47")
self.doubleSpinBox_opreating = QtWidgets.QDoubleSpinBox(self.tab_7)
self.doubleSpinBox_opreating.setGeometry(QtCore.QRect(140, 30, 101, 41))
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(9)
font.setBold(False)
font.setWeight(50)
font.setStrikeOut(False)
self.doubleSpinBox_opreating.setFont(font)
self.doubleSpinBox_opreating.setLayoutDirection(QtCore.Qt.LeftToRight)
self.doubleSpinBox_opreating.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignVCenter)
self.doubleSpinBox_opreating.setMaximum(999999.99)
self.doubleSpinBox_opreating.setObjectName("doubleSpinBox_opreating")
self.Laser_729_3_opreating = QtWidgets.QCheckBox(self.tab_7)
self.Laser_729_3_opreating.setGeometry(QtCore.QRect(310, 160, 91, 21))
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(9)
font.setBold(False)
font.setWeight(50)
font.setStrikeOut(False)
self.Laser_729_3_opreating.setFont(font)
self.Laser_729_3_opreating.setObjectName("Laser_729_3_opreating")
self.label_48 = QtWidgets.QLabel(self.tab_7)
self.label_48.setGeometry(QtCore.QRect(20, 30, 131, 41))
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(9)
font.setBold(False)
font.setWeight(50)
font.setStrikeOut(False)
self.label_48.setFont(font)
self.label_48.setObjectName("label_48")
self.label_49 = QtWidgets.QLabel(self.tab_7)
self.label_49.setGeometry(QtCore.QRect(150, 200, 131, 21))
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(9)
font.setBold(False)
font.setWeight(50)
font.setStrikeOut(False)
self.label_49.setFont(font)
self.label_49.setObjectName("label_49")
self.label_50 = QtWidgets.QLabel(self.tab_7)
self.label_50.setGeometry(QtCore.QRect(20, 100, 131, 41))
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(9)
font.setBold(False)
font.setWeight(50)
font.setStrikeOut(False)
self.label_50.setFont(font)
self.label_50.setObjectName("label_50")
self.line_7 = QtWidgets.QFrame(self.tab_7)
self.line_7.setGeometry(QtCore.QRect(20, 80, 431, 20))
self.line_7.setFrameShape(QtWidgets.QFrame.HLine)
self.line_7.setFrameShadow(QtWidgets.QFrame.Sunken)
self.line_7.setObjectName("line_7")
self.Setting.addTab(self.tab_7, "")
self.tab_8 = QtWidgets.QWidget()
self.tab_8.setObjectName("tab_8")
self.doubleSpinBox_PMT = QtWidgets.QDoubleSpinBox(self.tab_8)
self.doubleSpinBox_PMT.setGeometry(QtCore.QRect(140, 30, 101, 41))
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(9)
font.setBold(False)
font.setWeight(50)
font.setStrikeOut(False)
self.doubleSpinBox_PMT.setFont(font)
self.doubleSpinBox_PMT.setLayoutDirection(QtCore.Qt.LeftToRight)
self.doubleSpinBox_PMT.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignVCenter)
self.doubleSpinBox_PMT.setMaximum(999999.99)
self.doubleSpinBox_PMT.setObjectName("doubleSpinBox_PMT")
self.label_51 = QtWidgets.QLabel(self.tab_8)
self.label_51.setGeometry(QtCore.QRect(20, 30, 131, 41))
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(9)
font.setBold(False)
font.setUnderline(True)
font.setWeight(50)
font.setStrikeOut(False)
self.label_51.setFont(font)
self.label_51.setObjectName("label_51")
self.label_52 = QtWidgets.QLabel(self.tab_8)
self.label_52.setGeometry(QtCore.QRect(260, 30, 31, 41))
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(9)
font.setBold(False)
font.setWeight(50)
font.setStrikeOut(False)
self.label_52.setFont(font)
self.label_52.setObjectName("label_52")
self.Setting.addTab(self.tab_8, "")
self.tab_9 = QtWidgets.QWidget()
self.tab_9.setObjectName("tab_9")
self.label_55 = QtWidgets.QLabel(self.tab_9)
self.label_55.setGeometry(QtCore.QRect(20, 30, 421, 101))
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(9)
font.setBold(False)
font.setWeight(50)
font.setStrikeOut(False)
self.label_55.setFont(font)
self.label_55.setObjectName("label_55")
self.Setting.addTab(self.tab_9, "")
self.tabWidget_2 = QtWidgets.QTabWidget(self.centralwidget)
self.tabWidget_2.setGeometry(QtCore.QRect(50, 520, 341, 301))
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(9)
font.setBold(False)
font.setWeight(50)
font.setStrikeOut(False)
self.tabWidget_2.setFont(font)
self.tabWidget_2.setIconSize(QtCore.QSize(20, 20))
self.tabWidget_2.setUsesScrollButtons(False)
self.tabWidget_2.setObjectName("tabWidget_2")
self.tab_3 = QtWidgets.QWidget()
self.tab_3.setObjectName("tab_3")
self.label_18 = QtWidgets.QLabel(self.tab_3)
self.label_18.setGeometry(QtCore.QRect(230, 220, 41, 31))
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(9)
font.setBold(False)
font.setWeight(50)
font.setStrikeOut(False)
self.label_18.setFont(font)
self.label_18.setObjectName("label_18")
self.label_5 = QtWidgets.QLabel(self.tab_3)
self.label_5.setGeometry(QtCore.QRect(260, 40, 31, 16))
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(9)
font.setBold(False)
font.setWeight(50)
font.setStrikeOut(False)
self.label_5.setFont(font)
self.label_5.setObjectName("label_5")
self.doubleSpinBox_rabistep = QtWidgets.QDoubleSpinBox(self.tab_3)
self.doubleSpinBox_rabistep.setGeometry(QtCore.QRect(140, 150, 101, 41))
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(9)
font.setBold(False)
font.setWeight(50)
font.setStrikeOut(False)
self.doubleSpinBox_rabistep.setFont(font)
self.doubleSpinBox_rabistep.setLayoutDirection(QtCore.Qt.LeftToRight)
self.doubleSpinBox_rabistep.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignVCenter)
self.doubleSpinBox_rabistep.setMaximum(999999.99)
self.doubleSpinBox_rabistep.setObjectName("doubleSpinBox_rabistep")
self.label_9 = QtWidgets.QLabel(self.tab_3)
self.label_9.setGeometry(QtCore.QRect(20, 220, 91, 31))
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(9)
font.setBold(False)
font.setWeight(50)
font.setStrikeOut(False)
self.label_9.setFont(font)
self.label_9.setObjectName("label_9")
self.doubleSpinBox_rabistart = QtWidgets.QDoubleSpinBox(self.tab_3)
self.doubleSpinBox_rabistart.setGeometry(QtCore.QRect(140, 30, 101, 41))
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(9)
font.setBold(False)
font.setWeight(50)
font.setStrikeOut(False)
self.doubleSpinBox_rabistart.setFont(font)
self.doubleSpinBox_rabistart.setLayoutDirection(QtCore.Qt.LeftToRight)
self.doubleSpinBox_rabistart.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignVCenter)
self.doubleSpinBox_rabistart.setMaximum(999999.99)
self.doubleSpinBox_rabistart.setObjectName("doubleSpinBox_rabistart")
self.label_7 = QtWidgets.QLabel(self.tab_3)
self.label_7.setGeometry(QtCore.QRect(260, 160, 31, 16))
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(9)
font.setBold(False)
font.setWeight(50)
font.setStrikeOut(False)
self.label_7.setFont(font)
self.label_7.setObjectName("label_7")
self.label_4 = QtWidgets.QLabel(self.tab_3)
self.label_4.setGeometry(QtCore.QRect(20, 160, 91, 21))
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(9)
font.setBold(False)
font.setWeight(50)
font.setStrikeOut(False)
self.label_4.setFont(font)
self.label_4.setObjectName("label_4")
self.label_6 = QtWidgets.QLabel(self.tab_3)
self.label_6.setGeometry(QtCore.QRect(260, 100, 31, 16))
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(9)
font.setBold(False)
font.setWeight(50)
font.setStrikeOut(False)
self.label_6.setFont(font)
self.label_6.setObjectName("label_6")
self.doubleSpinBox_rabiend = QtWidgets.QDoubleSpinBox(self.tab_3)
self.doubleSpinBox_rabiend.setGeometry(QtCore.QRect(140, 90, 101, 41))
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(9)
font.setBold(False)
font.setWeight(50)
font.setStrikeOut(False)
self.doubleSpinBox_rabiend.setFont(font)
self.doubleSpinBox_rabiend.setLayoutDirection(QtCore.Qt.LeftToRight)
self.doubleSpinBox_rabiend.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignVCenter)
self.doubleSpinBox_rabiend.setMaximum(999999.99)
self.doubleSpinBox_rabiend.setObjectName("doubleSpinBox_rabiend")
self.spinBox_rabirepeat = QtWidgets.QSpinBox(self.tab_3)
self.spinBox_rabirepeat.setGeometry(QtCore.QRect(140, 220, 71, 31))
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(9)
font.setBold(False)
font.setWeight(50)
font.setStrikeOut(False)
self.spinBox_rabirepeat.setFont(font)
self.spinBox_rabirepeat.setObjectName("spinBox_rabirepeat")
self.label_2 = QtWidgets.QLabel(self.tab_3)
self.label_2.setGeometry(QtCore.QRect(20, 40, 91, 21))
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(9)
font.setBold(False)
font.setWeight(50)
font.setStrikeOut(False)
self.label_2.setFont(font)
self.label_2.setObjectName("label_2")
self.label_3 = QtWidgets.QLabel(self.tab_3)
self.label_3.setGeometry(QtCore.QRect(20, 100, 91, 21))
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(9)
font.setBold(False)
font.setWeight(50)
font.setStrikeOut(False)
self.label_3.setFont(font)
self.label_3.setObjectName("label_3")
self.tabWidget_2.addTab(self.tab_3, "")
self.tab_4 = QtWidgets.QWidget()
self.tab_4.setObjectName("tab_4")
self.label_19 = QtWidgets.QLabel(self.tab_4)
self.label_19.setGeometry(QtCore.QRect(270, 220, 41, 31))
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(9)
font.setBold(False)
font.setWeight(50)
font.setStrikeOut(False)
self.label_19.setFont(font)
self.label_19.setObjectName("label_19")
self.spinBox_zeemanrepeat = QtWidgets.QSpinBox(self.tab_4)
self.spinBox_zeemanrepeat.setGeometry(QtCore.QRect(180, 220, 71, 31))
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(9)
font.setBold(False)
font.setWeight(50)
font.setStrikeOut(False)
self.spinBox_zeemanrepeat.setFont(font)
self.spinBox_zeemanrepeat.setObjectName("spinBox_zeemanrepeat")
self.label_12 = QtWidgets.QLabel(self.tab_4)
self.label_12.setGeometry(QtCore.QRect(300, 160, 31, 16))
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(9)
font.setBold(False)
font.setWeight(50)
font.setStrikeOut(False)
self.label_12.setFont(font)
self.label_12.setObjectName("label_12")
self.label_13 = QtWidgets.QLabel(self.tab_4)
self.label_13.setGeometry(QtCore.QRect(20, 220, 91, 31))
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(9)
font.setBold(False)
font.setWeight(50)
font.setStrikeOut(False)
self.label_13.setFont(font)
self.label_13.setObjectName("label_13")
self.label_15 = QtWidgets.QLabel(self.tab_4)
self.label_15.setGeometry(QtCore.QRect(20, 160, 141, 21))
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(9)
font.setBold(False)
font.setWeight(50)
font.setStrikeOut(False)
self.label_15.setFont(font)
self.label_15.setObjectName("label_15")
self.doubleSpinBox_zeemanend = QtWidgets.QDoubleSpinBox(self.tab_4)
self.doubleSpinBox_zeemanend.setGeometry(QtCore.QRect(180, 90, 101, 41))
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(9)
font.setBold(False)
font.setWeight(50)
font.setStrikeOut(False)
self.doubleSpinBox_zeemanend.setFont(font)
self.doubleSpinBox_zeemanend.setLayoutDirection(QtCore.Qt.LeftToRight)
self.doubleSpinBox_zeemanend.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignVCenter)
self.doubleSpinBox_zeemanend.setMaximum(999999.99)
self.doubleSpinBox_zeemanend.setObjectName("doubleSpinBox_zeemanend")
self.doubleSpinBox_zeemanstep = QtWidgets.QDoubleSpinBox(self.tab_4)
self.doubleSpinBox_zeemanstep.setGeometry(QtCore.QRect(180, 150, 101, 41))
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(9)
font.setBold(False)
font.setWeight(50)
font.setStrikeOut(False)
self.doubleSpinBox_zeemanstep.setFont(font)
self.doubleSpinBox_zeemanstep.setLayoutDirection(QtCore.Qt.LeftToRight)
self.doubleSpinBox_zeemanstep.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignVCenter)
self.doubleSpinBox_zeemanstep.setMaximum(999999.99)
self.doubleSpinBox_zeemanstep.setObjectName("doubleSpinBox_zeemanstep")
self.label_14 = QtWidgets.QLabel(self.tab_4)
self.label_14.setGeometry(QtCore.QRect(20, 100, 131, 21))
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(9)
font.setBold(False)
font.setWeight(50)
font.setStrikeOut(False)
self.label_14.setFont(font)
self.label_14.setObjectName("label_14")
self.doubleSpinBox_zeemanstart = QtWidgets.QDoubleSpinBox(self.tab_4)
self.doubleSpinBox_zeemanstart.setGeometry(QtCore.QRect(180, 30, 101, 41))
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(9)
font.setBold(False)
font.setWeight(50)
font.setStrikeOut(False)
self.doubleSpinBox_zeemanstart.setFont(font)
self.doubleSpinBox_zeemanstart.setLayoutDirection(QtCore.Qt.LeftToRight)
self.doubleSpinBox_zeemanstart.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignVCenter)
self.doubleSpinBox_zeemanstart.setMaximum(999999.99)
self.doubleSpinBox_zeemanstart.setObjectName("doubleSpinBox_zeemanstart")
self.label_16 = QtWidgets.QLabel(self.tab_4)
self.label_16.setGeometry(QtCore.QRect(300, 40, 31, 16))
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(9)
font.setBold(False)
font.setWeight(50)
font.setStrikeOut(False)
self.label_16.setFont(font)
self.label_16.setObjectName("label_16")
self.label_17 = QtWidgets.QLabel(self.tab_4)
self.label_17.setGeometry(QtCore.QRect(300, 100, 31, 16))
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(9)
font.setBold(False)
font.setWeight(50)
font.setStrikeOut(False)
self.label_17.setFont(font)
self.label_17.setObjectName("label_17")
self.label_11 = QtWidgets.QLabel(self.tab_4)
self.label_11.setGeometry(QtCore.QRect(20, 40, 131, 21))
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(9)
font.setBold(False)
font.setWeight(50)
font.setStrikeOut(False)
self.label_11.setFont(font)
self.label_11.setObjectName("label_11")
self.tabWidget_2.addTab(self.tab_4, "")
self.tab_5 = QtWidgets.QWidget()
self.tab_5.setObjectName("tab_5")
self.label_28 = QtWidgets.QLabel(self.tab_5)
self.label_28.setGeometry(QtCore.QRect(260, 40, 31, 16))
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(9)
font.setBold(False)
font.setWeight(50)
font.setStrikeOut(False)
self.label_28.setFont(font)
self.label_28.setObjectName("label_28")
self.label_21 = QtWidgets.QLabel(self.tab_5)
self.label_21.setGeometry(QtCore.QRect(20, 100, 91, 21))
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(9)
font.setBold(False)
font.setWeight(50)
font.setStrikeOut(False)
self.label_21.setFont(font)
self.label_21.setObjectName("label_21")
self.doubleSpinBox_custTime = QtWidgets.QDoubleSpinBox(self.tab_5)
self.doubleSpinBox_custTime.setGeometry(QtCore.QRect(140, 90, 101, 41))
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(9)
font.setBold(False)
font.setWeight(50)
font.setStrikeOut(False)
self.doubleSpinBox_custTime.setFont(font)
self.doubleSpinBox_custTime.setLayoutDirection(QtCore.Qt.LeftToRight)
self.doubleSpinBox_custTime.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignVCenter)
self.doubleSpinBox_custTime.setMaximum(999999.99)
self.doubleSpinBox_custTime.setObjectName("doubleSpinBox_custTime")
self.doubleSpinBox_custF = QtWidgets.QDoubleSpinBox(self.tab_5)
self.doubleSpinBox_custF.setGeometry(QtCore.QRect(140, 30, 101, 41))
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(9)
font.setBold(False)
font.setWeight(50)
font.setStrikeOut(False)
self.doubleSpinBox_custF.setFont(font)
self.doubleSpinBox_custF.setLayoutDirection(QtCore.Qt.LeftToRight)
self.doubleSpinBox_custF.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignVCenter)
self.doubleSpinBox_custF.setMaximum(999999.99)
self.doubleSpinBox_custF.setObjectName("doubleSpinBox_custF")
self.label_29 = QtWidgets.QLabel(self.tab_5)
self.label_29.setGeometry(QtCore.QRect(20, 160, 91, 31))
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(9)
font.setBold(False)
font.setWeight(50)
font.setStrikeOut(False)
self.label_29.setFont(font)
self.label_29.setObjectName("label_29")
self.label_23 = QtWidgets.QLabel(self.tab_5)
self.label_23.setGeometry(QtCore.QRect(260, 100, 31, 16))
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(9)
font.setBold(False)
font.setWeight(50)
font.setStrikeOut(False)
self.label_23.setFont(font)
self.label_23.setObjectName("label_23")
self.spinBox_custreapeat = QtWidgets.QSpinBox(self.tab_5)
self.spinBox_custreapeat.setGeometry(QtCore.QRect(140, 160, 71, 31))
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(9)
font.setBold(False)
font.setWeight(50)
font.setStrikeOut(False)
self.spinBox_custreapeat.setFont(font)
self.spinBox_custreapeat.setObjectName("spinBox_custreapeat")
self.label_22 = QtWidgets.QLabel(self.tab_5)
self.label_22.setGeometry(QtCore.QRect(20, 40, 131, 21))
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(9)
font.setBold(False)
font.setWeight(50)
font.setStrikeOut(False)
self.label_22.setFont(font)
self.label_22.setObjectName("label_22")
self.label_27 = QtWidgets.QLabel(self.tab_5)
self.label_27.setGeometry(QtCore.QRect(230, 165, 41, 21))
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(9)
font.setBold(False)
font.setWeight(50)
font.setStrikeOut(False)
self.label_27.setFont(font)
self.label_27.setObjectName("label_27")
self.tabWidget_2.addTab(self.tab_5, "")
self.label_34 = QtWidgets.QLabel(self.centralwidget)
self.label_34.setGeometry(QtCore.QRect(490, 30, 51, 41))
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(10)
font.setBold(True)
font.setItalic(False)
font.setWeight(75)
font.setStrikeOut(False)
self.label_34.setFont(font)
self.label_34.setObjectName("label_34")
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 586, 23))
self.menubar.setObjectName("menubar")
self.menuMain = QtWidgets.QMenu(self.menubar)
self.menuMain.setObjectName("menuMain")
self.menuAdvance = QtWidgets.QMenu(self.menubar)
self.menuAdvance.setObjectName("menuAdvance")
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.actionreset = QtWidgets.QAction(MainWindow)
self.actionreset.setObjectName("actionreset")
self.actionClear_Settings = QtWidgets.QAction(MainWindow)
self.actionClear_Settings.setObjectName("actionClear_Settings")
self.actionClear_Data = QtWidgets.QAction(MainWindow)
self.actionClear_Data.setObjectName("actionClear_Data")
self.menuMain.addAction(self.actionreset)
self.menuMain.addAction(self.actionClear_Settings)
self.menuMain.addAction(self.actionClear_Data)
self.menubar.addAction(self.menuMain.menuAction())
self.menubar.addAction(self.menuAdvance.menuAction())
self.retranslateUi(MainWindow)
self.Setting.setCurrentIndex(4)
self.tabWidget_2.setCurrentIndex(0)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
# Added by MGQ-------------------------------------------------------------------------------------------------------
#Mode_Box----------------------------------------------------------------------------------
#RABI
self.doubleSpinBox_rabistart.valueChanged.connect(self.doubleSpinBox_rabistart_ChangeValue)
self.doubleSpinBox_rabiend.valueChanged.connect(self.doubleSpinBox_rabiend_ChangeValue)
self.doubleSpinBox_rabistep.valueChanged.connect(self.doubleSpinBox_rabistep_ChangeValue)
self.spinBox_rabirepeat.valueChanged.connect(self.spinBox_rabirepeat_ChangeValue)
#ZEEMAN
self.doubleSpinBox_zeemanstart.valueChanged.connect(self.doubleSpinBox_zeemanstart_ChangeValue)
self.doubleSpinBox_zeemanend.valueChanged.connect(self.doubleSpinBox_zeemanend_ChangeValue)
self.doubleSpinBox_zeemanstep.valueChanged.connect(self.doubleSpinBox_zeemanstep_ChangeValue)
self.spinBox_zeemanrepeat.valueChanged.connect(self.spinBox_zeemanrepeat_ChangeValue)
#cust
self.doubleSpinBox_custF.valueChanged.connect(self.doubleSpinBox_custF_ChangeValue)
self.doubleSpinBox_custTime.valueChanged.connect(self.doubleSpinBox_custTime_ChangeValue)
self.spinBox_custreapeat.valueChanged.connect(self.spinBox_custreapeat_ChangeValue)
#BasicSetting-----------------------------------------------------------------------------------------------------
#BasicSettingTime--------------------------------------------------------------------------------
self.doubleSpinBox_DPL.valueChanged.connect(self.doubleSpinBox_DPL_ChangeValue)
self.doubleSpinBox_SB.valueChanged.connect(self.doubleSpinBox_SB_ChangeValue)
self.doubleSpinBox_OP.valueChanged.connect(self.doubleSpinBox_OP_ChangeValue)
self.doubleSpinBox_opreating.valueChanged.connect(self.doubleSpinBox_opreating_ChangeValue)
self.doubleSpinBox_PMT.valueChanged.connect(self.doubleSpinBox_PMT_ChangeValue)
#BasicSettingLaser--------------------------------------------------------------------------------
#DPL_Cooling
#397
self.Laser_397_main_DPL.toggled.connect(self.Laser_397_main_DPL_toggled)
self.Laser_397_1_DPL.toggled.connect(self.Laser_397_1_DPL_toggled)
self.Laser_397_2_DPL.toggled.connect(self.Laser_397_2_DPL_toggled)
self.Laser_397_3_DPL.toggled.connect(self.Laser_397_3_DPL_toggled)
#866 & 854
self.Laser_866_DPL.toggled.connect(self.Laser_866_DPL_toggled)
self.Laser_854_DPL.toggled.connect(self.Laser_854_DPL_toggled)
#OP
#729
self.Laser_729_main_OP.toggled.connect(self.Laser_729_main_OP_toggled)
self.Laser_729_1_OP.toggled.connect(self.Laser_729_1_OP_toggled)
self.Laser_729_2_OP.toggled.connect(self.Laser_729_2_OP_toggled)
self.Laser_729_3_OP.toggled.connect(self.Laser_729_3_OP_toggled)
self.Laser_729_4_OP.toggled.connect(self.Laser_729_4_OP_toggled)
#854
self.Laser_854_OP.toggled.connect(self.Laser_854_OP_toggled)
#opreating
#729
self.Laser_729_main_opreating.toggled.connect(self.Laser_729_main_opreating_toggled)
self.Laser_729_1_opreating.toggled.connect(self.Laser_729_1_opreating_toggled)
self.Laser_729_2_opreating.toggled.connect(self.Laser_729_2_opreating_toggled)
self.Laser_729_3_opreating.toggled.connect(self.Laser_729_3_opreating_toggled)
self.Laser_729_4_opreating.toggled.connect(self.Laser_729_4_opreating_toggled)
#854
self.Laser_854_opreating.toggled.connect(self.Laser_854_opreating_toggled)
#Selection
self.radioButton_rabi.toggled.connect(self.on_radio_button_rabi_toggled)
self.radioButton_zeeman.toggled.connect(self.on_radio_button_zeeman_toggled)
self.radioButton_cust.toggled.connect(self.on_radio_button_cust_toggled)
self.radioButton_off.toggled.connect(self.on_radio_button_off_toggled)
self.pushButton.clicked.connect(self.Bstart)
#Mode-------------------------------------------------------------------------------------------
#RABI_BOX
def doubleSpinBox_rabistart_ChangeValue(self):
# self.set_dataset("Run_Uint.Rabi.Start",self.doubleSpinBox_rabistart.value(), broadcast=True)
self.Rabistart=self.doubleSpinBox_rabistart.value()
def doubleSpinBox_rabiend_ChangeValue(self):
# self.set_dataset("Run_Uint.Rabi.End",self.doubleSpinBox_rabiend.value(), broadcast=True)
self.Rabiend=self.doubleSpinBox_rabiend.value()
def doubleSpinBox_rabistep_ChangeValue(self):
# self.set_dataset("Run_Uint.Rabi.Step",self.doubleSpinBox_rabistep.value(), broadcast=True)
self.Rabistep=self.doubleSpinBox_rabistep.value()
def spinBox_rabirepeat_ChangeValue(self):
# self.set_dataset("Run_Uint.Rabi.Repeat",self.spinBox_rabirepeat.value(), broadcast=True)
self.Rabirepeat=self.spinBox_rabirepeat.value()
#ZEEMAN_BOX
def doubleSpinBox_zeemanstart_ChangeValue(self):
# self.set_dataset("Run_Uint.Zeeman.Start",self.doubleSpinBox_zeemanstart.value(), broadcast=True)
self.Zeemanstart=self.doubleSpinBox_zeemanstart.value()
def doubleSpinBox_zeemanend_ChangeValue(self):
# self.set_dataset("Run_Uint.Zeeman.End",self.doubleSpinBox_zeemanend.value(), broadcast=True)
self.Zeemanend=self.doubleSpinBox_zeemanend.value()
def doubleSpinBox_zeemanstep_ChangeValue(self):
# self.set_dataset("Run_Uint.Zeeman.Step",self.doubleSpinBox_zeemanstep.value(), broadcast=True)
self.Zeemanstep=self.doubleSpinBox_zeemanstep.value()
def spinBox_zeemanrepeat_ChangeValue(self):
# self.set_dataset("Run_Uint.Zeeman.Repeat",self.spinBox_zeemanrepeat.value(), broadcast=True)
self.Zeemanrepeat=self.spinBox_zeemanrepeat.value()
#cust_BOX
def doubleSpinBox_custF_ChangeValue(self):
# self.set_dataset("Run_Uint.Customized.Start",self.doubleSpinBox_custF.value(), broadcast=True)
self.custF=self.doubleSpinBox_custF.value()
def doubleSpinBox_custTime_ChangeValue(self):
# self.set_dataset("Run_Uint.Customized.End",self.doubleSpinBox_custTime.value(), broadcast=True)
self.custTime=self.doubleSpinBox_custTime.value()
def spinBox_custreapeat_ChangeValue(self):
# self.set_dataset("Run_Uint.Customized.Repeat",self.spinBox_custreapeat.value(), broadcast=True)
self.custrepeat=self.spinBox_custreapeat.value()
#BasicSetting_BOX------------------------------------------------------------------------------
#Time Setting----------------------------------------------------------------------------------
def doubleSpinBox_DPL_ChangeValue(self):
# self.set_dataset("Run_Uint.Default.DPL",self.doubleSpinBox_DPL.value(), broadcast=True)
self.DPL=self.doubleSpinBox_DPL.value()
def doubleSpinBox_OP_ChangeValue(self):
# self.set_dataset("Run_Uint.Default.OP",self.doubleSpinBox_OP.value(), broadcast=True)
self.OP=self.doubleSpinBox_OP.value()
def doubleSpinBox_SB_ChangeValue(self):
# self.set_dataset("Run_Uint.Default.SB",self.doubleSpinBox_SB.value(), broadcast=True)
self.SB=self.doubleSpinBox_SB.value()
def doubleSpinBox_opreating_ChangeValue(self):
# self.set_dataset("Run_Uint.Default.opreating",self.doubleSpinBox_opreating.value(), broadcast=True)
self.opreating=self.doubleSpinBox_opreating.value()
def doubleSpinBox_PMT_ChangeValue(self):
# self.set_dataset("Run_Uint.Default.PMT",self.doubleSpinBox_PMT.value(), broadcast=True)
self.PMT=self.doubleSpinBox_PMT.value()
#Check Setting----------------------------------------------------------------------------------
#DPL
def Laser_397_main_DPL_toggled(self):
if Laser_397_main_DPL.isChecked():
self.para=1
def Laser_397_1_DPL_toggled(self):
if Laser_397_1_DPL.isChecked():
self.para=1
def Laser_397_2_DPL_toggled(self):
if Laser_397_2_DPL.isChecked():
self.para=1
def Laser_397_3_DPL_toggled(self):
if Laser_397_3_DPL.isChecked():
self.para=1
def Laser_866_DPL_toggled(self):
if Laser_866_DPL.isChecked():
self.para=1
def Laser_854_DPL_toggled(self):
if Laser_854_DPL.isChecked():
self.para=1
#OP
def Laser_729_main_OP_toggled(self):
if Laser_729_main_OP.isChecked():
self.para=1
def Laser_729_1_OP_toggled(self):
if Laser_729_1_OP.isChecked():
self.para=1
def Laser_729_2_OP_toggled(self):
if Laser_729_2_OP.isChecked():
self.para=1
def Laser_729_3_OP_toggled(self):
if Laser_729_3_OP.isChecked():
self.para=1
def Laser_729_4_OP_toggled(self):
if Laser_729_4_OP.isChecked():
self.para=1
def Laser_854_OP_toggled(self):
if Laser_854_OP.isChecked():
self.para=1
#opreating
def Laser_729_main_opreating_toggled(self):
if Laser_729_main_OP.isChecked():
self.para=1
def Laser_729_1_opreating_toggled(self):
if Laser_729_1_opreating.isChecked():
self.para=1
def Laser_729_2_opreating_toggled(self):
if Laser_729_2_opreating.isChecked():
self.para=1
def Laser_729_3_opreating_toggled(self):
if Laser_729_3_opreating.isChecked():
self.para=1
def Laser_729_4_opreating_toggled(self):
if Laser_729_4_opreating.isChecked():
self.para=1
def Laser_854_opreating_toggled(self):
if Laser_854_opreating.isChecked():
self.para=1
#Select------------------------------------------------------------------------------------------
def on_radio_button_rabi_toggled(self):
if self.radioButton_rabi.isChecked():
self.para=1
def on_radio_button_zeeman_toggled(self):
if self.radioButton_zeeman.isChecked():
self.para=2
def on_radio_button_cust_toggled(self):
if self.radioButton_cust.isChecked():
self.para=3
def on_radio_button_off_toggled(self):
if self.radioButton_off.isChecked():
self.para=4
def Bstart(self):
pass
# self.set_dataset("para",self.para, broadcast=True)
# Ended by MGQ-------------------------------------------------------------------------------------------------------
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.label_20.setText(_translate("MainWindow", "<html><head/><body><p><span style=\" font-size:16pt; font-weight:600; color:#000000;\">Ion Trap QC Control System 2.0</span></p></body></html>"))
self.label_10.setText(_translate("MainWindow", "<html><head/><body><p><span style=\" font-size:11pt; color:#002800;\">Mode</span></p></body></html>"))
self.label_33.setText(_translate("MainWindow", "<html><head/><body><p><span style=\" font-size:11pt; font-weight:600; color:#002800;\">Basic Setting</span></p></body></html>"))
self.radioButton_rabi.setText(_translate("MainWindow", "Rabi Scan"))
self.radioButton_zeeman.setText(_translate("MainWindow", "Zeeman Scan"))
self.radioButton_cust.setText(_translate("MainWindow", "Customized"))
self.pushButton.setText(_translate("MainWindow", "Submit"))
self.radioButton_off.setText(_translate("MainWindow", "OFF"))
self.label_36.setText(_translate("MainWindow", "us"))
self.label_37.setText(_translate("MainWindow", "Doppler Cooling"))
self.Laser_397_1_DPL.setText(_translate("MainWindow", "397_1"))
self.Laser_397_2_DPL.setText(_translate("MainWindow", "397_2"))
self.Laser_397_3_DPL.setText(_translate("MainWindow", "397_3"))
self.Laser_397_main_DPL.setText(_translate("MainWindow", "397 Main"))
self.Laser_866_DPL.setText(_translate("MainWindow", "866"))
self.Laser_854_DPL.setText(_translate("MainWindow", "854"))
self.label_42.setText(_translate("MainWindow", "Laser Selected"))
self.label_44.setText(_translate("MainWindow", "NA"))
self.label_45.setText(_translate("MainWindow", "NA"))
self.Setting.setTabText(self.Setting.indexOf(self.DPL_Cooling), _translate("MainWindow", "DPL Cooling"))
self.label_41.setText(_translate("MainWindow", "Optical Pump"))
self.label_40.setText(_translate("MainWindow", "us"))
self.Laser_729_1_OP.setText(_translate("MainWindow", "729_1"))
self.Laser_729_3_OP.setText(_translate("MainWindow", "729_3"))
self.Laser_729_2_OP.setText(_translate("MainWindow", "729_2"))
self.Laser_729_4_OP.setText(_translate("MainWindow", "729_4"))
self.Laser_854_OP.setText(_translate("MainWindow", "854"))
self.Laser_729_main_OP.setText(_translate("MainWindow", "729 Main"))
self.label_43.setText(_translate("MainWindow", "Laser Selected"))
self.label_46.setText(_translate("MainWindow", "NA"))
self.Setting.setTabText(self.Setting.indexOf(self.tab_6), _translate("MainWindow", "Optical Pump"))
self.label_53.setText(_translate("MainWindow", "SB Cooling"))
self.label_54.setText(_translate("MainWindow", "us"))
self.Setting.setTabText(self.Setting.indexOf(self.tab_2), _translate("MainWindow", "SB Cooling"))
self.Laser_729_4_opreating.setText(_translate("MainWindow", "729_4"))
self.Laser_729_main_opreating.setText(_translate("MainWindow", "729 Main"))
self.Laser_729_1_opreating.setText(_translate("MainWindow", "729_1"))
self.Laser_854_opreating.setText(_translate("MainWindow", "854 1"))
self.Laser_729_2_opreating.setText(_translate("MainWindow", "729_2"))
self.label_47.setText(_translate("MainWindow", "us"))
self.Laser_729_3_opreating.setText(_translate("MainWindow", "729_3"))
self.label_48.setText(_translate("MainWindow", "Opreating"))
self.label_49.setText(_translate("MainWindow", "NA"))
self.label_50.setText(_translate("MainWindow", "Laser Selected"))
self.Setting.setTabText(self.Setting.indexOf(self.tab_7), _translate("MainWindow", "Opreating"))
self.label_51.setText(_translate("MainWindow", "Detecting"))
self.label_52.setText(_translate("MainWindow", "us"))
self.Setting.setTabText(self.Setting.indexOf(self.tab_8), _translate("MainWindow", "Detecting"))
self.label_55.setText(_translate("MainWindow", "<html><head/><body><p>Temporarily we couple the operation period to the frequency </p><p>of 50Hz, if you want to change or cancle it, please change </p><p>the code responsible for running.(not in the GUI file)</p></body></html>"))
self.Setting.setTabText(self.Setting.indexOf(self.tab_9), _translate("MainWindow", "Gap"))
self.label_18.setText(_translate("MainWindow", "times"))
self.label_5.setText(_translate("MainWindow", "us"))
self.label_9.setText(_translate("MainWindow", "Repeat"))
self.label_7.setText(_translate("MainWindow", "us"))
self.label_4.setText(_translate("MainWindow", "Time for Step"))
self.label_6.setText(_translate("MainWindow", "us"))
self.label_2.setText(_translate("MainWindow", "Time to Start"))
self.label_3.setText(_translate("MainWindow", "Time to End"))
self.tabWidget_2.setTabText(self.tabWidget_2.indexOf(self.tab_3), _translate("MainWindow", "Rabi Scan"))
self.label_19.setText(_translate("MainWindow", "times"))
self.label_12.setText(_translate("MainWindow", "Hz"))
self.label_13.setText(_translate("MainWindow", "Repeat"))
self.label_15.setText(_translate("MainWindow", "Frequency for Step"))
self.label_14.setText(_translate("MainWindow", "Frequency of End"))
self.label_16.setText(_translate("MainWindow", "Hz"))
self.label_17.setText(_translate("MainWindow", "Hz"))
self.label_11.setText(_translate("MainWindow", "Frequency of Start"))
self.tabWidget_2.setTabText(self.tabWidget_2.indexOf(self.tab_4), _translate("MainWindow", "Zeeman Scan"))
self.label_28.setText(_translate("MainWindow", "Hz"))
self.label_21.setText(_translate("MainWindow", "Rabi Time"))
self.label_29.setText(_translate("MainWindow", "Repeat"))
self.label_23.setText(_translate("MainWindow", "us"))
self.label_22.setText(_translate("MainWindow", "Frequency "))
self.label_27.setText(_translate("MainWindow", "times"))
self.tabWidget_2.setTabText(self.tabWidget_2.indexOf(self.tab_5), _translate("MainWindow", "Costomized"))
self.label_34.setText(_translate("MainWindow", "<html><head/><body><p><span style=\" font-size:11pt; font-style:italic; color:#000000;\">WIPM </span></p></body></html>"))
self.menuMain.setTitle(_translate("MainWindow", "Main"))
self.menuAdvance.setTitle(_translate("MainWindow", "Advance"))
self.actionreset.setText(_translate("MainWindow", "Introduction"))
self.actionClear_Settings.setText(_translate("MainWindow", "Clear Settings"))
self.actionClear_Data.setText(_translate("MainWindow", "Clear Data"))
import sys
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_()) |
'''
关闭软件时保存配置文件到%appdata%,打开软件自动读取上一次配置信息
'''
import os
import ast
def configDictToFile(pathFileNameExt,_dict):
'''
给文件名+路径和字典,写入到该文件
_dict(字典)不能有嵌套,(这里代码需要优化???????)
'''
txt=''
for k,v in _dict.items():
if type(v)==str and '\n' in str(v): #如果字符串有多行,转成列表
v=v.strip().split('\n')
item=f'{k}={v}'
txt+=item+'\n'
with open(pathFileNameExt,'w',encoding='utf-8') as file:
file.write(txt.strip())
def configFileToDict(pathFileNameExt):
'''
给文件名,读取里面字典,查找字典用"键.get()"
'''
if os.path.exists(pathFileNameExt):
with open(pathFileNameExt,'r',encoding='utf-8') as file:
txt=file.read()
# _dict={k:v for i in txt.split('\n') for k,v in (i.split('='),)}
_dict={}
for i in txt.split('\n'):
for k,v in (i.split('=',1),):
if v.startswith('['): #判断包含符号'[]',导出历史文件已经列表转字符,是列表就拆成多行字符
v=ast.literal_eval(v)
v='\n'.join(v)
_dict.update({k:v})
return _dict
def createAppDataPath(softwareName='',dataFolder=''):
'''
创建文件夹在%appdata%,放用户数据
'''
appdataPath=os.getenv('appdata')
pathName=os.path.normpath(f'{appdataPath}/{softwareName}/{dataFolder}')
if not os.path.exists(pathName):
try:os.makedirs(pathName)
except:pass
else:return pathName
if __name__=='__main__':
a='aaa'
b=222
c='''a=aaa
b=222
c=['#多行 saf', ' aadf']
'''
configDict={'a':a,'b':b,'c':c}
configFileNameExt = 'history.txt'
configPathFileNameExt = f'{os.getcwd()}/{configFileNameExt}'
configDictToFile(configPathFileNameExt,configDict)
# d=configFileToDict(configPathFileNameExt)
# print(d.get('c'))
|
import os
import tempfile
os.environ['MPLCONFIGDIR'] = tempfile.mkdtemp()
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from matplotlib.figure import Figure
from matplotlib.font_manager import FontProperties
from django.http import HttpResponse
def strToArray(str):
a = []
for e in str.split(','):
if e:
a.append(e)
return a
def error(httpRequest, msg = 'Error on plotting. Probably wrong query format.'):
fig = Figure(figsize = (3, 3))
canvas = FigureCanvas(fig)
ax = fig.add_subplot(111)
ax.text(0.5 , 0.5, msg,
horizontalalignment='center',
verticalalignment='center',
transform = ax.transAxes)
ax.set_axis_off()
response = HttpResponse(content_type = 'image/png')
fig.savefig(response, format='png')
return response
def pie(httpRequest):
#try:
labels = []
values = []
colors = ['b', 'g', 'r', 'c', 'm', 'y', 'k', 'w']
title = None
for (arg, argv) in httpRequest.GET.iteritems():
if arg == 't':
title = argv
elif arg == 'l':
labels = strToArray(argv)
elif arg == 'v':
values = strToArray(argv)
elif arg == 'c':
colors = strToArray(argv)
if not values:
return error(httpRequest, 'No values')
if sum(map(int, values)) == 0:
return error(httpRequest, 'Total is 0')
fig = Figure(figsize = (6,3))
canvas = FigureCanvas(fig)
ax = fig.add_subplot(1,2,1)
(patches, texts, auto) = ax.pie(values, labels = None, colors = colors, autopct='%1.1f%%')
if title:
ax.set_title(title)
ax2 = fig.add_subplot(1,2,2)
fontP = FontProperties()
fontP.set_size('small')
ax2.legend(patches, labels, loc='center left', prop = fontP)
ax2.set_axis_off()
response = HttpResponse(content_type = 'image/png')
fig.savefig(response, format='png', bbox_inches = 'tight', transparent = True)
return response
#except Exception, e:
# return error(httpRequest, str(e))
|
from web.scripts.i18n import (InitTranslation, UpdateTranslations,
CompileTranslations)
from web.scripts.images import TalkCards
from web.scripts.team import AlphabetizeTeam
__all__ = ['InitTranslation', 'UpdateTranslations', 'CompileTranslations',
'AlphabetizeTeam', 'TalkCards']
|
import inflection
from pylons import url
class Room(object):
def __init__(self, name, text, title=None, image = None):
self.name = name
self.text = text
self.image = image
self.obstacle = None
self.title = title
if not self.title:
self.title = inflection.titleize(name)
def add_obstacle(self, obstacle):
self.obstacle = obstacle |
# -*- encoding: utf-8 -*-
###########################################################################
# Module Writen to OpenERP, Open Source Management Solution
#
# Copyright (c) 2012 Vauxoo - http://www.vauxoo.com
# All Rights Reserved.
# info@vauxoo.com
############################################################################
# Coded by: fernandoL (fernando_ld@vauxoo.com)
############################################################################
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from openerp.osv import osv, fields
import openerp.workflow as workflow
class ProcurementOrderMergeJitExtended(osv.TransientModel):
_name = 'procurement.order.merge.jit.extended'
_columns = {
'date_planned': fields.datetime('Scheduled date', select=1),
}
def procurement_merge_jit(self, cr, uid, ids, context=None, rec_ids=None):
procurement_order_pool = self.pool.get('procurement.order')
mrp_production_pool = self.pool.get('mrp.production')
if context is None:
context = {}
if rec_ids is None:
production_ids = context.get('active_ids', [])
else:
production_ids = rec_ids
procurement_ids = []
for production_id in production_ids:
production_data = mrp_production_pool.browse(
cr, uid, production_id, context=context)
for line in production_data.procurement_ids:
if (line.state == 'draft') and\
(line.product_id.supply_method == 'produce'):
procurement_ids.append(line.id)
res = procurement_order_pool.do_merge(
cr, uid, procurement_ids, context=context)
# append the procurements that are not in draft still
draft_procurements = procurement_order_pool.browse(
cr, uid, procurement_ids, context=context)
for line in draft_procurements:
if (line.state == 'draft') and\
(line.product_id.supply_method == 'produce') and\
(line.product_id.type != 'service'):
res.append(line.id)
# forwards procurements that were merged
wf_service = workflow
new_ids = []
for line in res:
wf_service.trg_validate(
uid, 'procurement.order', line, 'button_confirm', cr)
wf_service.trg_validate(
uid, 'procurement.order', line, 'button_check', cr)
procurements = self.pool.get('procurement.order').read(
cr, uid, line, ['production_created'], context=context)
new_production_id = procurements.get('production_created')
if new_production_id:
new_ids.append(new_production_id[0])
subproductions = self.pool.get('procurement.order').read(
cr, uid, line, ['production_ids'], context=context)
subproduction_ids = subproductions.get('production_ids')
for wiz_data in self.browse(cr, uid, ids, context):
if wiz_data.date_planned:
mrp_production_pool.write(cr, uid,
new_production_id[0], {
'subproduction_ids':
[(6, 0, subproduction_ids)],
'date_planned': wiz_data.date_planned})
else:
mrp_production_pool.write(cr, uid,
new_production_id[0],
{'subproduction_ids': [(6, 0, subproduction_ids)]})
if new_ids:
self.procurement_merge_jit(cr, uid, ids, context, new_ids)
return {}
|
# -*- coding: utf-8 -*-
"""
Created on Mon Oct 8 12:17:19 2018
@author: Thomas Levy
"""
import unittest
import moovieReco
class UnitTestMethods(unittest.TestCase):
#Basic unit testing of all the methods from moovieReco module withn an empty csv file (i.e with no ratings)
def test_splitEmpty(self):
self.assertEqual(moovieReco.splitChunk(inFile='empty.csv',outPrefix='empty',chunkSize=1), 0)
def test_predictEmpty(self):
self.assertEqual(moovieReco.predictRatings(ratingFile='empty.csv',evalFile='empty.csv',outFile='emptyout.csv'),0)
def test_mergeEmpty(self):
self.assertEqual(moovieReco.mergeFile(inPrefix='empty',nChunks=0,outFile='out.csv'),0)
if __name__ == '__main__':
unittest.main()
|
# Import libraries
import io
import os
import pandas as pd
import timeit
import warnings
from pathlib import Path
from google.cloud import vision
warnings.filterwarnings('ignore')
# Edit the directories accordingly here
json_directory = 'C:/Users/320100141/Desktop/Python Venv/VisionAI/venv/ServiceAccountToken.json'
photo_directory = 'C:/Users/320100141/Desktop/Python Venv/VisionAI/Processed Photos'
# Run software keys to utilise Google Services
os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = json_directory
# Import imaging client
client = vision.ImageAnnotatorClient()
# Checks for the number of files found
cpt = sum([len(files) for r, d, files in os.walk(photo_directory)])
print(cpt, "photos found") # To check the length of the files in the given directory
# Returns a list of the file names; serves as label
plist = os.listdir(photo_directory)
print("The photos are:", plist)
# To create the master DataFrame and its counter
df = pd.DataFrame(columns=['photo', 'width'])
i = 0
pathlist = Path(photo_directory).rglob('**/*.jpg')
for path in pathlist:
# Reads the image into the code
start = timeit.default_timer()
with io.open(path, 'rb') as image_file:
content = image_file.read()
# Construct image instance and annotate image response
image = vision.Image(content=content)
response = client.text_detection(image=image)
texts = response.text_annotations
stop = timeit.default_timer()
i = i + 1
print(int(100*i/cpt), "% completed. ~", 10+10*round(int((stop - start)*(cpt-i))/10), "seconds left.")
for text in texts:
df = df.append(
dict(
photo=plist[i-1],
width=text.description
),
ignore_index=True
)
# Data cleaning
df = df[pd.to_numeric(df['width'], errors='coerce').notnull()]
df = df.select_dtypes(exclude=['int64'])
df['width'] = df['width'].astype(str).astype(float).round()
df_e = df[~(df['width'] <= 100)]
df_e['width'] = df_e['width'].div(1000)
# Change to your desired filename
df_e.to_csv('raw.csv')
print("Extraction complete.") |
from typing import List
from django.http import HttpRequest
from feature_flags.providers import is_feature_enabled
_features: List["Feature"] = []
def _register_feature(feature):
_features.append(feature)
def _is_feature_enabled(feature: str, request: HttpRequest) -> bool:
is_enabled = is_feature_enabled(feature_name=feature, request=request)
return is_enabled
class Feature:
def __init__(self, name: str):
self.name: str = name
_register_feature(self)
def is_enabled(self, request: HttpRequest = None) -> bool:
return _is_feature_enabled(self.name, request=request)
def __repr__(self):
return f"({self.name}, {self.is_enabled()})"
class UnknownFeature(Exception):
pass
|
"""
CCT 建模优化代码
CCT
作者:赵润晓
日期:2021年5月1日
"""
import multiprocessing # since v0.1.1 多线程计算
import time # since v0.1.1 统计计算时长
from typing import Callable, Dict, Generic, Iterable, List, NoReturn, Optional, Tuple, TypeVar, Union
import matplotlib.pyplot as plt
import math
import random # since v0.1.1 随机数
import sys
import os # since v0.1.1 查看CPU核心数
import numpy
from scipy.integrate import solve_ivp # since v0.1.1 ODE45
import warnings # since v0.1.1 提醒方法过时
from packages.point import *
from packages.constants import *
from packages.base_utils import BaseUtils
from packages.local_coordinate_system import LocalCoordinateSystem
from packages.line2s import *
from packages.line3s import *
from packages.trajectory import Trajectory
from packages.particles import *
from packages.magnets import *
class CCT(Magnet, ApertureObject):
"""
表示一层弯曲 CCT 线圈
"""
def __init__(
self,
# CCT 局部坐标系
local_coordinate_system: LocalCoordinateSystem,
# 大半径:偏转半径
big_r: float,
# 小半径(孔径/2)
small_r: float,
# 偏转角度,即 phi0*winding_number,典型值 67.5
bending_angle: float, # 必须为正
# 各极倾斜角,典型值 [30,90,90,90]
tilt_angles: List[float],
# 匝数
winding_number: int,
# 电流
current: float,
# CCT 路径在二维 ξ-φ 坐标系中的起点
starting_point_in_ksi_phi_coordinate: P2,
# CCT 路径在二维 ξ-φ 坐标系中的终点
end_point_in_ksi_phi_coordinate: P2,
# 每匝线圈离散电流元数目,数字越大计算精度越高
disperse_number_per_winding: int = 120,
):
"""
bending_angle 这个定义有冗余,它等于
abs(end_point_in_ksi_phi_coordinate.y-starting_point_in_ksi_phi_coordinate.y).to_angle()
"""
if bending_angle < 0:
raise ValueError(f"CCT 偏转角度应为正数,不能是 {bending_angle},需要反向偏转的 CCT," +
"应通过 starting_point_in_ksi_phi_coordinate,和 end_point_in_ksi_phi_coordinate 控制偏转方向"
)
if big_r < 0:
raise ValueError(f"big_r = {big_r} 为负数,非法")
if small_r < 0:
raise ValueError(f"small_r = {small_r} 为负数,非法")
if small_r >= big_r:
raise ValueError(f"small_r {small_r} >= big_r {big_r},非法")
self.local_coordinate_system = local_coordinate_system
self.big_r = float(big_r)
self.small_r = float(small_r)
self.bending_angle = float(bending_angle)
self.tilt_angles = [float(e) for e in tilt_angles]
self.winding_number = int(winding_number)
self.current = float(current)
self.starting_point_in_ksi_phi_coordinate = starting_point_in_ksi_phi_coordinate
self.end_point_in_ksi_phi_coordinate = end_point_in_ksi_phi_coordinate
self.disperse_number_per_winding = int(disperse_number_per_winding)
# 弯转角度,弧度制
self.bending_radian = BaseUtils.angle_to_radian(self.bending_angle)
# 倾斜角,弧度制
self.tilt_radians = BaseUtils.angle_to_radian(self.tilt_angles)
# 每绕制一匝,φ 方向前进长度
self.phi0 = self.bending_radian / self.winding_number
# 极点 a
self.a = math.sqrt(self.big_r ** 2 - self.small_r ** 2)
# 双极坐标系另一个常量 η
self.eta = 0.5 * \
math.log((self.big_r + self.a) / (self.big_r - self.a))
# 建立 ξ-φ 坐标到三维 xyz 坐标的转换器
self.bipolar_toroidal_coordinate_system = CCT.BipolarToroidalCoordinateSystem(
self.a, self.eta, self.big_r, self.small_r
)
# CCT 路径的在 ξ-φ 坐标的表示 函数 φ(ξ)
def phi_ksi_function(ksi): return self.phi_ksi_function(ksi)
# CCT 路径的在 ξ-φ 坐标的表示 函数 P(ξ)=(ξ,φ(ξ))
def p2_function(ksi): return P2(ksi, phi_ksi_function(ksi))
# CCT 路径的在 xyz 坐标的表示 函数 P(ξ)=P(x(ξ),y(ξ),z(ξ))
def p3_function(ksi): return self.bipolar_toroidal_coordinate_system.convert(
p2_function(ksi)
)
# self.phi_ksi_function = phi_ksi_function
# self.p2_function = p2_function
# self.p3_function = p3_function
# 总分段数目 / 电流元数目
self.total_disperse_number = self.winding_number * self.disperse_number_per_winding
dispersed_path2: List[List[float]] = [
p2_function(ksi).to_list()
for ksi in BaseUtils.linspace(
self.starting_point_in_ksi_phi_coordinate.x,
self.end_point_in_ksi_phi_coordinate.x,
self.total_disperse_number + 1,
) # +1 为了满足分段正确性,即匝数 m,需要用 m+1 个点
]
self.dispersed_path3_points: List[P3] = [
p3_function(ksi)
for ksi in BaseUtils.linspace(
self.starting_point_in_ksi_phi_coordinate.x,
self.end_point_in_ksi_phi_coordinate.x,
self.total_disperse_number + 1,
) # +1 为了满足分段正确性,见上
]
dispersed_path3: List[List[float]] = [
p.to_list() for p in self.dispersed_path3_points
]
# 为了速度,转为 numpy
self.dispersed_path2: numpy.ndarray = numpy.array(dispersed_path2)
self.dispersed_path3: numpy.ndarray = numpy.array(dispersed_path3)
# 电流元 (miu0/4pi) * current * (p[i+1] - p[i])
# refactor v0.1.1
# 语法分析:示例
# a = array([1, 2, 3, 4])
# a[1:] = array([2, 3, 4])
# a[:-1] = array([1, 2, 3])
self.elementary_current = 1e-7 * current * (
self.dispersed_path3[1:] - self.dispersed_path3[:-1]
)
# 电流元的位置 (p[i+1]+p[i])/2
self.elementary_current_position = 0.5 * (
self.dispersed_path3[1:] + self.dispersed_path3[:-1]
)
def phi_ksi_function(self, ksi: float) -> float:
"""
完成 ξ 到 φ 的映射
"""
x1 = self.starting_point_in_ksi_phi_coordinate.x
y1 = self.starting_point_in_ksi_phi_coordinate.y
x2 = self.end_point_in_ksi_phi_coordinate.x
y2 = self.end_point_in_ksi_phi_coordinate.y
k = (y2 - y1) / (x2 - x1)
b = -k * x1 + y1
phi = k * ksi + b
for i in range(len(self.tilt_radians)):
if BaseUtils.equal(self.tilt_angles[i], 90.0):
continue
else:
phi += (
(1 / math.tan(self.tilt_radians[i]))
/ ((i + 1) * math.sinh(self.eta))
* math.sin((i + 1) * ksi)
)
return phi
class BipolarToroidalCoordinateSystem:
"""
双极点坐标系
"""
def __init__(self, a: float, eta: float, big_r: float, small_r: float):
self.a = a
self.eta = eta
self.big_r = big_r
self.small_r = small_r
BaseUtils.equal(
big_r,
math.sqrt(a * a / (1 - 1 / math.pow(math.cosh(eta), 2))),
msg=f"BipolarToroidalCoordinateSystem:init 错误1 a({a})eta({eta})R({big_r})r({small_r})",
)
BaseUtils.equal(
small_r,
big_r / math.cosh(eta),
msg=f"BipolarToroidalCoordinateSystem:init 错误2 a({a})eta({eta})R({big_r})r({small_r})",
)
def convert(self, p: P2) -> P3:
"""
将二维坐标 (ξ,φ) 转为三维坐标 (x,y,z)
"""
ksi = p.x
phi = p.y
temp = self.a / (math.cosh(self.eta) - math.cos(ksi))
return P3(
temp * math.sinh(self.eta) * math.cos(phi),
temp * math.sinh(self.eta) * math.sin(phi),
temp * math.sin(ksi),
)
def main_normal_direction_at(self, p: P2) -> P3:
"""
返回二维坐标 (ξ,φ) 映射到的三维坐标 (x,y,z) 点,
它在圆环面上的法向量
即返回值 P3 在这点 (x,y,z) 垂直于圆环面
注意:已正则归一化
"""
phi = p.y
center = P3(self.big_r * math.cos(phi),
self.big_r * math.sin(phi), 0)
face_point = self.convert(p)
return (face_point - center).normalize()
def __str__(self):
return f"BipolarToroidalCoordinateSystem a({self.a})eta({self.eta})R({self.big_r})r({self.small_r})"
def __repr__(self) -> str:
return self.__str__()
def magnetic_field_at(self, point: P3) -> P3:
"""
计算 CCT 在全局坐标系点 P3 参数的磁场
为了计算效率,使用 numpy
"""
if BaseUtils.equal(self.current, 0, err=1e-6):
return P3.zeros()
# point 转为局部坐标,并变成 numpy 向量
p = numpy.array(
self.local_coordinate_system.point_to_local_coordinate(
point).to_list()
)
# 点 p 到电流元中点
r = p - self.elementary_current_position
# 点 p 到电流元中点的距离的三次方
rr = (numpy.linalg.norm(r, ord=2, axis=1)
** (-3)).reshape((r.shape[0], 1))
# 计算每个电流元在 p 点产生的磁场 (此时还没有乘系数 μ0/4π )
dB = numpy.cross(self.elementary_current, r) * rr
# 求和,即得到磁场,
# (不用乘乘以系数 μ0/4π = 1e-7)
# refactor v0.1.1
B = numpy.sum(dB, axis=0)
# 转回 P3
B_P3: P3 = P3.from_numpy_ndarry(B)
# 从局部坐标转回全局坐标
B_P3: P3 = self.local_coordinate_system.vector_to_global_coordinate(
B_P3)
return B_P3
# from ApertureObject
def is_out_of_aperture(self, point: P3) -> bool:
"""
判断点 point 是在 CCT 的孔径内还是孔径外
只有当粒子轴向投影在元件内部时,才会进行判断,
否则即时粒子距离轴线很远,也认为粒子没有超出孔径,
这是因为粒子不在元件内时,很可能处于另一个大孔径元件中,这样会造成误判。
point 为全局坐标系点
"""
# 转为局部坐标
local_point = self.local_coordinate_system.point_to_local_coordinate(
point)
local_point_p2 = local_point.to_p2()
# 查看偏转方向
clockwise = self.end_point_in_ksi_phi_coordinate.y < 0
# 映射到 cct 所在圆环轴上
phi = local_point_p2.angle_to_x_axis()
# 查看是否在 cct 轴上
if clockwise:
# phi 应大于 2pi-bending_radian 小于 2pi
if phi > (2 * math.pi - self.bending_radian):
return (
abs(local_point.z) > self.small_r
or local_point_p2.length() > (self.big_r + self.small_r)
or local_point_p2.length() < (self.big_r - self.small_r)
)
else:
return False
else:
if phi < self.bending_radian:
return (
abs(local_point.z) > self.small_r
or local_point_p2.length() > (self.big_r + self.small_r)
or local_point_p2.length() < (self.big_r - self.small_r)
)
else:
return False
def __str__(self):
return (
f"CCT: local_coordinate_system({self.local_coordinate_system})big_r({self.big_r})small_r({self.small_r})"
+ f"bending_angle({self.bending_angle})tilt_angles({self.tilt_angles})winding_number({self.winding_number})"
+ f"current({self.current})starting_point_in_ksi_phi_coordinate({self.starting_point_in_ksi_phi_coordinate})"
+ f"end_point_in_ksi_phi_coordinate({self.end_point_in_ksi_phi_coordinate})"
+ f"disperse_number_per_winding({self.disperse_number_per_winding})"
)
def __repr__(self) -> str:
return self.__str__()
@staticmethod
def create_cct_along(
# 设计轨道
trajectory: Line2,
# 设计轨道上该 CCT 起点
s: float,
# 大半径:偏转半径
big_r: float,
# 小半径(孔径/2)
small_r: float,
# 偏转角度,即 phi0*winding_number,典型值 67.5
bending_angle: float,
# 各极倾斜角,典型值 [30,90,90,90]
tilt_angles: List[float],
# 匝数
winding_number: int,
# 电流
current: float,
# CCT 路径在二维 ξ-φ 坐标系中的起点
starting_point_in_ksi_phi_coordinate: P2,
# CCT 路径在二维 ξ-φ 坐标系中的终点
end_point_in_ksi_phi_coordinate: P2,
# 每匝线圈离散电流元数目,数字越大计算精度越高
disperse_number_per_winding: int = 120,
) -> "CCT":
"""
按照设计轨迹 trajectory 上 s 位置处创建 CCT
"""
start_point: P2 = trajectory.point_at(s)
arc_length: float = big_r * BaseUtils.angle_to_radian(bending_angle)
end_point: P2 = trajectory.point_at(
s + arc_length) # 2021年1月15日 bug fixed
midpoint0: P2 = trajectory.point_at(s + arc_length / 3 * 1)
midpoint1: P2 = trajectory.point_at(s + arc_length / 3 * 2)
c1, r1 = BaseUtils.circle_center_and_radius(
start_point, midpoint0, midpoint1)
c2, r2 = BaseUtils.circle_center_and_radius(
midpoint0, midpoint1, end_point)
BaseUtils.equal(
c1, c2, msg=f"构建 CCT 存在异常,通过设计轨道判断 CCT 圆心不一致,c1{c1},c2{c2}")
BaseUtils.equal(
r1, r2, msg=f"构建 CCT 存在异常,通过设计轨道判断 CCT 半径不一致,r1{r1},r2{r2}")
center: P2 = (c1 + c2) * 0.5
start_direct: P2 = trajectory.direct_at(s)
pos: int = StraightLine2(
# position_of 求点 p 相对于直线段的方位
# 返回值:
# 1 在右侧 # -1 在左侧 # 0 在直线段所在直线上
1.0, start_direct, start_point).position_of(center)
lcs = None
if pos == 0:
raise ValueError(f"错误:圆心{center}在设计轨道{trajectory}上")
elif pos == 1: # center 在 (start_direct, start_point) 右侧,顺时针
lcs = LocalCoordinateSystem.create_by_y_and_z_direction(
location=center.to_p3(),
y_direction=-start_direct.to_p3(), # diff
z_direction=P3.z_direct(),
)
# pos = -1 # center 在 (start_direct, start_point) 左侧,逆时针时针
else:
lcs = LocalCoordinateSystem.create_by_y_and_z_direction(
location=center.to_p3(),
y_direction=start_direct.to_p3(), # diff
z_direction=P3.z_direct(),
)
return CCT(
local_coordinate_system=lcs,
big_r=big_r,
small_r=small_r,
bending_angle=bending_angle,
tilt_angles=tilt_angles,
winding_number=winding_number,
current=current,
starting_point_in_ksi_phi_coordinate=starting_point_in_ksi_phi_coordinate,
end_point_in_ksi_phi_coordinate=end_point_in_ksi_phi_coordinate,
disperse_number_per_winding=disperse_number_per_winding,
)
def global_path3(self) -> List[P3]:
"""
获取 CCT 路径点,以全局坐标系的形式
主要目的是为了 CUDA 计算
since v0.1.1
"""
return [
self.local_coordinate_system.point_to_global_coordinate(p)
for p in self.dispersed_path3_points
]
def global_current_elements_and_elementary_current_positions(self, numpy_dtype=numpy.float64) -> Tuple[numpy.ndarray, numpy.ndarray]:
"""
获取全局坐标系下的
电流元 (miu0/4pi) * current * (p[i+1] - p[i])
和
电流元的位置 (p[i+1]+p[i])/2
主要目的是为了 CUDA 计算
since v0.1.1
"""
global_path3: List[P3] = self.global_path3()
global_path3_numpy_array = numpy.array(
[p.to_list() for p in global_path3], dtype=numpy_dtype)
global_current_elements = 1e-7 * self.current * \
(global_path3_numpy_array[1:] - global_path3_numpy_array[:-1])
global_elementary_current_positions = 0.5 * \
(global_path3_numpy_array[1:] + global_path3_numpy_array[:-1])
return (
global_current_elements.flatten(),
global_elementary_current_positions.flatten()
)
def p2_function(self, ksi) -> P2:
"""
二维坐标系点 (ksi, phi)
since v0.1.1
"""
return P2(ksi, self.phi_ksi_function(ksi))
def p3_function(self, ksi) -> P3:
"""
局部坐标系下路径方程
since v0.1.1
"""
return self.bipolar_toroidal_coordinate_system.convert(self.p2_function(ksi))
def conductor_length(self, line_number: int = 2*7, disperse_number_per_winding: int = 360) -> float:
"""
计算导线长度
line_number 导线数目
since v0.1.1
"""
ksi0 = self.starting_point_in_ksi_phi_coordinate.x
ksi1 = self.end_point_in_ksi_phi_coordinate.x
ksi_list = BaseUtils.linspace(
ksi0, ksi1, disperse_number_per_winding*self.winding_number+1)
length: float = 0.0
for i in range(len(ksi_list)-1):
p0 = self.p3_function(ksi_list[i])
p1 = self.p3_function(ksi_list[i+1])
length += (p1-p0).length()
return length*line_number
def as_cct(anything) -> 'CCT':
"""
仿佛是类型转换
实际啥也没做
但是 IDE 就能根据返回值做代码提示了
常用在将 Magnet 转成 CCT
例如从 Beamline 中取出的 magnets,然后按照真是类型转过去
since v0.1.3
"""
return anything
@staticmethod
def calculate_a(big_r: float, small_r: float):
"""
计算极点 a 值的小方法
"""
return math.sqrt(big_r ** 2 - small_r ** 2)
@staticmethod
def calculate_eta(big_r: float, small_r: float):
"""
计算 eta 值的小方法
"""
return 0.5 * math.log((big_r + CCT.calculate_a(big_r, small_r))
/ (big_r - CCT.calculate_a(big_r, small_r)))
@staticmethod
def calculate_cheta(big_r: float, small_r: float):
"""
计算 ch(eta) 值的小方法
"""
return math.cosh(CCT.calculate_eta(big_r, small_r))
@staticmethod
def calculate_sheta(big_r: float, small_r: float):
"""
计算 sh(eta) 值的小方法
"""
return math.sinh(CCT.calculate_eta(big_r, small_r))
def cut_to_single_winding_cct(self) -> List['CCT']:
"""
切成单匝 CCT
原 CCT self,有多少匝,就切成多少
这个函数用于误差分析/敏感度分析做准备
新增于 2021年6月17日、同时通过测试
"""
# ret
ccts: List[CCT] = []
# 偏转角度
bending_angle = self.bending_angle / self.winding_number
points_in_ksi_phi_coordinate: List[P2] = BaseUtils.linspace(
self.starting_point_in_ksi_phi_coordinate,
self.end_point_in_ksi_phi_coordinate,
self.winding_number+1
)
for i in range(self.winding_number):
start_point = points_in_ksi_phi_coordinate[i]
end_point = points_in_ksi_phi_coordinate[i+1]
ccts.append(CCT(
local_coordinate_system=self.local_coordinate_system,
big_r=self.big_r,
small_r=self.small_r,
bending_angle=bending_angle,
tilt_angles=self.tilt_angles,
winding_number=1,
current=self.current,
starting_point_in_ksi_phi_coordinate=start_point,
end_point_in_ksi_phi_coordinate=end_point,
disperse_number_per_winding=self.disperse_number_per_winding
))
return ccts
@staticmethod
def create_by_existing_cct(
existing_cct: 'CCT',
local_coordinate_system: Optional[LocalCoordinateSystem] = None,
big_r: Optional[float] = None,
small_r: Optional[float] = None,
bending_angle: Optional[float] = None,
tilt_angles: Optional[List[float]] = None,
winding_number: Optional[int] = None,
current: Optional[float] = None,
starting_point_in_ksi_phi_coordinate: Optional[P2] = None,
end_point_in_ksi_phi_coordinate: Optional[P2] = None,
disperse_number_per_winding: Optional[int] = None,
) -> 'CCT':
"""
通过一个已经存在的 CCT 创建新 CCT
新增于 2021年6月17日
"""
def get_one(first_candidate, second_candidate):
"""
获得 first_candidate/second_candidate 中的一个
优先 first_candidate,如果其为空则第二个
"""
# if second_candidate is None:
# raise ValueError(f"second_candidate 为空")
return first_candidate if first_candidate is not None else second_candidate
return CCT(
local_coordinate_system=get_one(
local_coordinate_system, existing_cct.local_coordinate_system),
big_r=get_one(big_r, existing_cct.big_r),
small_r=get_one(small_r, existing_cct.small_r),
bending_angle=get_one(
bending_angle, existing_cct.bending_angle),
tilt_angles=get_one(tilt_angles, existing_cct.tilt_angles),
winding_number=get_one(
winding_number, existing_cct.winding_number),
current=get_one(current, existing_cct.current),
starting_point_in_ksi_phi_coordinate=get_one(
starting_point_in_ksi_phi_coordinate, existing_cct.starting_point_in_ksi_phi_coordinate),
end_point_in_ksi_phi_coordinate=get_one(
end_point_in_ksi_phi_coordinate, existing_cct.end_point_in_ksi_phi_coordinate),
disperse_number_per_winding=get_one(
disperse_number_per_winding, existing_cct.disperse_number_per_winding)
)
class Wire(Magnet):
"""
任意空间三维导线
"""
def __init__(self, function_line3: FunctionLine3, current: float, delta_length: float = 1*MM) -> None:
"""
function_line3 导线路径
current 电流
delta_length 导线分割成电流元时,每个电流元的长度
"""
self.function_line3 = function_line3
self.current = current
self.start = function_line3.get_start()
self.end = function_line3.get_end()
# 分段数目
part_number = int(math.ceil(
(self.end-self.start)/delta_length
))
self.dispersed_s = numpy.array(
BaseUtils.linspace(self.start, self.end, part_number+1))
self.dispersed_path3 = numpy.array([
self.function_line3.point_at_p3_function(s).to_numpy_ndarry3() for s in self.dispersed_s
])
# 电流元 (miu0/4pi) * current * (p[i+1] - p[i])
# refactor v0.1.1
# 语法分析:示例
# a = array([1, 2, 3, 4])
# a[1:] = array([2, 3, 4])
# a[:-1] = array([1, 2, 3])
self.elementary_current = 1e-7 * self.current * (
self.dispersed_path3[1:] - self.dispersed_path3[:-1]
)
# 电流元的位置 (p[i+1]+p[i])/2
self.elementary_current_position = 0.5 * (
self.dispersed_path3[1:] + self.dispersed_path3[:-1]
)
def magnetic_field_at(self, point: P3) -> P3:
"""
计算磁场,全局坐标
"""
if BaseUtils.equal(self.current, 0, err=1e-6):
return P3.zeros()
if BaseUtils.equal(self.start, self.end, err=1e-6):
return P3.zeros()
p = point.to_numpy_ndarry3()
# 点 p 到电流元中点
r = p - self.elementary_current_position
# 点 p 到电流元中点的距离的三次方
rr = (numpy.linalg.norm(r, ord=2, axis=1)
** (-3)).reshape((r.shape[0], 1))
# 计算每个电流元在 p 点产生的磁场 (此时还没有乘系数 μ0/4π )
dB = numpy.cross(self.elementary_current, r) * rr
# 求和,即得到磁场,
# (不用乘乘以系数 μ0/4π = 1e-7)
# refactor v0.1.1
B = numpy.sum(dB, axis=0)
# 转回 P3
B_P3: P3 = P3.from_numpy_ndarry(B)
return B_P3
def magnetic_field_on_wire(self, s: float, delta_length: float,
local_coordinate_point: LocalCoordinateSystem,
other_magnet: Magnet = Magnet.no_magnet()
) -> Tuple[P3, P3]:
"""
计算线圈上磁场,
s 线圈位置,即要计算磁场的位置
delta_length 分段长度
local_coordinate_point 局部坐标系
这个局部坐标系仅仅将计算的磁场转为局部坐标系中
返回值 位置点+磁场
"""
# 所在点(全局坐标系)
p = self.function_line3.point_at_p3_function(s)
# 所在点之前的导线
pre_line3 = FunctionLine3(
p3_function=self.function_line3.get_p3_function(),
start=self.start,
end=s - delta_length/2
)
# 所在点之后的导线
post_line3 = FunctionLine3(
p3_function=self.function_line3.get_p3_function(),
start=s + delta_length/2,
end=self.function_line3.get_end()
)
# 所在点之前的导线
pre_wire = Wire(
function_line3=pre_line3,
current=self.current,
delta_length=delta_length
)
# 所在点之后的导线
post_wire = Wire(
function_line3=post_line3,
current=self.current,
delta_length=delta_length
)
# 磁场
B = pre_wire.magnetic_field_at(
p) + post_wire.magnetic_field_at(p) + other_magnet.magnetic_field_at(p)
# 返回点 + 磁场
return p, local_coordinate_point.vector_to_local_coordinate(B)
def lorentz_force_on_wire(self, s: float, delta_length: float,
local_coordinate_point: LocalCoordinateSystem,
other_magnet: Magnet = Magnet.no_magnet()
) -> Tuple[P3, P3]:
"""
计算线圈上 s 位置处洛伦兹力
delta_length 线圈分段长度(s位置的这一段线圈不参与计算)
local_coordinate_point 洛伦兹力坐标系
这个局部坐标系仅仅将计算的洛伦兹力转为局部坐标系中
"""
p, b = self.magnetic_field_on_wire(
s=s,
delta_length=delta_length,
local_coordinate_point=LocalCoordinateSystem.global_coordinate_system(),
other_magnet=other_magnet
)
direct = self.function_line3.direct_at_p3_function(s)
F = self.current * delta_length * (direct@b)
return p, local_coordinate_point.vector_to_local_coordinate(F)
def pressure_on_wire_MPa(self, s: float, delta_length: float,
local_coordinate_point: LocalCoordinateSystem,
channel_width: float, channel_depth: float,
other_magnet: Magnet = Magnet.no_magnet(),
) -> Tuple[P3, P3]:
"""
计算压强,默认为 CCT
默认在 local_coordinate_point 坐标系下计算的洛伦兹力 F
Fx 绕线方向(应该是 0 )
Fy rib 方向 / 副法线方向
Fz 径向
返回值点 P 和三个方向的压强Pr
Pr.x 绕线方向压强 Fx / (channel_width * channel_depth)
Pr.y rib 方向压强 Fy / (绕线方向长度 * channel_depth)
Pr.z 径向压强 Fz / (绕线方向长度 * channel_width)
关于《绕线方向长度》 == len(point_at(s + delta_length/2)-point_at(s - delta_length/2))
返回值为 点P和 三方向压强/兆帕
"""
p, f = self.lorentz_force_on_wire(
s, delta_length, local_coordinate_point, other_magnet
)
winding_direct_length: float = (self.function_line3.point_at_p3_function(s+delta_length/2) -
self.function_line3.point_at_p3_function(s-delta_length/2)).length()
pressure: P3 = P3(
x=f.x/(channel_width*channel_depth),
y=f.y/(winding_direct_length*channel_depth),
z=f.z/(winding_direct_length*channel_width)
)/1e6
return p, pressure
@staticmethod
def create_by_cct(cct: CCT) -> 'Wire':
"""
由 CCT 创建 wire
"""
def p3f(ksi):
return cct.bipolar_toroidal_coordinate_system.convert(
P2(ksi, cct.phi_ksi_function(ksi))
)
return Wire(
function_line3=FunctionLine3(
p3_function=p3f,
start=cct.starting_point_in_ksi_phi_coordinate.x,
end=cct.end_point_in_ksi_phi_coordinate.x
),
current=cct.current,
delta_length=cct.small_r *
BaseUtils.angle_to_radian(360/cct.winding_number)
)
class AGCCT_CONNECTOR(Magnet):
"""
agcct 连接段的构建,尽可能的自动化
注意,存在重大 bug,即认为两个连接点处的切向,方向相反,实际上是错的!
在当前一般配置的 CCT 中,切向方向大约相差 0.5 度
这是什么概念呢?把 CCT 一匝分为 720 段,才能达到相接处 0.5 度变化。
鉴于 0.5 度似乎可以忽略,暂时就不解决这个 bug 了(因为连接过程很复杂)
"""
def __init__(self, agcct1: CCT, agcct2: CCT, step: float = 1*MM) -> None:
# fields
# self.current
# self.local_coordinate_system
# self.length
# self.dispersed_path3
# 必要的验证
if agcct1.local_coordinate_system != agcct2.local_coordinate_system:
raise ValueError(
f"需要连接的cct不属于同一坐标系,无法连接。agccct1={agcct1},agcct2={agcct2}")
BaseUtils.equal(agcct1.big_r, agcct2.big_r,
msg=f"需要连接的 cct big_r 不同,无法连接。agccct1={agcct1},agcct2={agcct2}")
BaseUtils.equal(agcct1.small_r, agcct2.small_r,
msg=f"需要连接的 cct small_r 不同,无法连接。agccct1={agcct1},agcct2={agcct2}")
BaseUtils.equal(agcct1.current, agcct2.current,
msg=f"需要连接的 cct 电流不同,无法连接。agccct1={agcct1},agcct2={agcct2}")
self.current = agcct1.current
# 坐标系
self.local_coordinate_system = agcct1.local_coordinate_system
# 前 cct 的终点
pre_cct_end_point_in_ksi_phi_coordinate = agcct1.end_point_in_ksi_phi_coordinate
# 后 cct 的起点
next_cct_starting_point_in_ksi_phi_coordinate = agcct2.starting_point_in_ksi_phi_coordinate
BaseUtils.equal(pre_cct_end_point_in_ksi_phi_coordinate.x, next_cct_starting_point_in_ksi_phi_coordinate.x,
msg=f"需要连接的前段 cct 终点 ξ 不等于后段 cct 的起点 ξ,无法连接。agccct1={agcct1},agcct2={agcct2}")
# 前 cct 的终点,在 φR-ξr 坐标系中的点 a
# 后 cct 的起点 b
# 以及切向 va vb
a = P2(x=pre_cct_end_point_in_ksi_phi_coordinate.y*agcct1.big_r, y=0.0)
b = P2(x=next_cct_starting_point_in_ksi_phi_coordinate.y*agcct2.big_r, y=0.0)
va = BaseUtils.derivative(lambda ksi: P2(
x=agcct1.p2_function(ksi).y*agcct1.big_r,
y=agcct1.p2_function(ksi).x*agcct1.small_r))(
pre_cct_end_point_in_ksi_phi_coordinate.x
# 下行的乘法很重要,因为自变量不一定是随着绕线增大,如果反向绕线就是减小 fixed 2021年1月8日
) * (-1 if agcct1.starting_point_in_ksi_phi_coordinate.x > agcct1.end_point_in_ksi_phi_coordinate.x else 1)
vb = BaseUtils.derivative(lambda ksi: P2(
x=agcct2.p2_function(ksi).y*agcct2.big_r,
y=agcct2.p2_function(ksi).x*agcct2.small_r))(
next_cct_starting_point_in_ksi_phi_coordinate.x
)*(-1 if agcct2.starting_point_in_ksi_phi_coordinate.x > agcct2.end_point_in_ksi_phi_coordinate.x else 1)
print(f"a={a}, b={b}")
print(f"va={va}, vb={vb}")
# 开始连接
# 首先是 z-Ξ 坐标系
ip, ka, kb = StraightLine2.intersecting_point(
pa=a,
va=va.copy().rotate(BaseUtils.angle_to_radian(90)),
pb=b,
vb=vb
)
if kb > 0:
ip, ka, kb = StraightLine2.intersecting_point(
pa=a,
va=va,
pb=b,
vb=vb.copy().rotate(BaseUtils.angle_to_radian(90))
)
assert ka >= 0, 'ka 应该非负'
ca = a + ka*va
connector_line_in_z_Θ = (
Trajectory
.set_start_point(start_point=a)
.first_line(
direct=va, length=abs(ka*va.length()))
.add_arc_line(
radius=(ca-b).length()/2,
clockwise=StraightLine2.is_on_right(ca, va, b) == 1,
angle_deg=180.0
)
)
else: # kb<=0:
cb = b + kb*vb
connector_line_in_z_Θ = (
Trajectory
.set_start_point(start_point=a)
.first_line(direct=va, length=0.0).add_arc_line(
radius=(a-cb).length()/2,
clockwise=StraightLine2.is_on_right(a, va, b) == 1,
angle_deg=180.0
).add_strait_line(length=abs(kb*vb.length()))
)
self.connector_line_in_z_Θ = connector_line_in_z_Θ
self.length_in_z_Θ = connector_line_in_z_Θ.get_length()
self.p2_function = lambda t: P2(
x=self.connector_line_in_z_Θ.point_at(t).y/agcct1.small_r,
y=self.connector_line_in_z_Θ.point_at(t).x/agcct1.big_r
)
self.p2_function_start = 0
self.p2_function_end = self.length_in_z_Θ
# z-Ξ 转到 ksi - phi 坐标系
# z = φR
# Ξ = ξr
# 再转到三维坐标系 xyz
dispersed_path3 = [agcct1.bipolar_toroidal_coordinate_system.convert(P2(
x=p2.y/agcct1.small_r, # p2.y 为 Ξ,ξ = Ξ/r
y=p2.x/agcct1.big_r # p2.x 为 z,φ = z/R
)).to_list() for p2 in self.connector_line_in_z_Θ.disperse2d(step=step)]
# 转为 numpy 数组
self.dispersed_path3: numpy.ndarray = numpy.array(dispersed_path3)
self.elementary_current = 1e-7 * self.current * (
self.dispersed_path3[1:] - self.dispersed_path3[:-1]
)
# 电流元的位置 (p[i+1]+p[i])/2
self.elementary_current_position = 0.5 * (
self.dispersed_path3[1:] + self.dispersed_path3[:-1]
)
def magnetic_field_at(self, point: P3) -> P3:
if BaseUtils.equal(self.current, 0, err=1e-6):
return P3.zeros()
# point 转为局部坐标,并变成 numpy 向量
p = numpy.array(
self.local_coordinate_system.point_to_local_coordinate(
point).to_list()
)
# 点 p 到电流元中点
r = p - self.elementary_current_position
# 点 p 到电流元中点的距离的三次方
rr = (numpy.linalg.norm(r, ord=2, axis=1)
** (-3)).reshape((r.shape[0], 1))
# 计算每个电流元在 p 点产生的磁场 (此时还没有乘系数 μ0/4π )
dB = numpy.cross(self.elementary_current, r) * rr
# 求和,即得到磁场,
# (不用乘乘以系数 μ0/4π = 1e-7)
# refactor v0.1.1
B = numpy.sum(dB, axis=0)
# 转回 P3
B_P3: P3 = P3.from_numpy_ndarry(B)
# 从局部坐标转回全局坐标
B_P3: P3 = self.local_coordinate_system.vector_to_global_coordinate(
B_P3)
return B_P3
|
from typing import Dict, List
import re
class Placeholder:
@staticmethod
def for_create_query(fields_len: int) -> str:
placeholder = ''
for i in range(fields_len):
placeholder += '?, '
placeholder = re.sub(', $', '', placeholder)
return placeholder
@staticmethod
def for_select_query(requested_fields: List[str]) -> str:
placeholder = ''
for field in requested_fields:
placeholder += f'{field}, '
placeholder = re.sub(', $', '', placeholder)
return placeholder
@staticmethod
def for_where_query(requested_fields: List[str]) -> str:
placeholder = ''
for key in requested_fields:
placeholder += key + ' = ? AND '
placeholder = re.sub(' AND $', '', placeholder)
return placeholder
@staticmethod
def for_update_query(update_fields: List[str]) -> str:
placeholder = ''
for key in update_fields:
placeholder += key + ' = ?, '
placeholder = re.sub(', $', '', placeholder)
return placeholder
|
# -*- coding: utf-8 -*-
import io
import struct
class BaseManipulator(object):
u"""バイナリデータを操作するマニピュレータの基本クラス"""
def __init__(self, stream):
u"""指定したストリームをバイナリデータとして操作するマニピュレータを作る"""
if not isinstance(stream, io.IOBase):
raise RuntimeError('stream requires io.IOBase type')
self._stream = stream
class BinaryReader(BaseManipulator):
u"""ストリームからバイナリデータを読み取る専用のクラス"""
def __init__(self, stream):
BaseManipulator.__init__(self, stream)
if not self._stream.readable():
raise RuntimeError('stream is not readable.')
def read_byte(self):
return self._read_as_unpack('b', 1)
def read_short(self):
return self._read_as_unpack('h', 2)
def read_int32(self):
return self._read_as_unpack('l', 4)
def read_int64(self):
return self._read_as_unpack('q', 8)
def read_float(self):
return self._read_as_unpack('f', 4)
def read_string(self, length, encoding):
u"""パケットから文字列を文字エンコーディングを考慮して読み取る。
lengthは文字数ではなくバイト数
ヌル文字が含まれている場合はそこを文字列の終端とする。ヌル文字がない場合は
最高lengthバイトに達するまで読み込む。
デコード不可能な文字列はU+FFFD REPLACEMENT CHARACTERに置換される"""
# TODO: replace以外の選択肢も与えるべき
data = self._stream.read(length).split(b'\x00')[0]
return data.decode(encoding, 'replace')
def read_pascal_string(self, encoding):
u"""最初の1バイト目に大きさが格納された文字列を読み取る"""
length = self.read_byte()
return self.read_string(length, encoding)
def _read_as_unpack(self, unpack_format, length):
# TODO: エンディアンを変更可能にする
return struct.unpack('<' + unpack_format, self._stream.read(length))[0]
class BinaryWriter(BaseManipulator):
def __init__(self, stream):
BaseManipulator.__init__(self, stream)
def write_byte(self, value):
self._write_as_pack('b', value)
def write_short(self, value):
self._write_as_pack('h', value)
def write_int32(self, value):
self._write_as_pack('l', value)
def write_int64(self, value):
self._write_as_pack('q', value)
def write_float(self, value):
self._write_as_pack('f', value)
def write_string(self, value):
self._stream.write(value.encode(self.encoding))
def write_pascal_string(self, value, encoding):
u"""先頭1バイト目に長さを格納した文字列を書き込む"""
bytes_data = value.encode(encoding)
self.write_byte(len(bytes_data))
self._stream.write(bytes_data)
def write_string_with_pading(self, value, encoding, length, padding_char=b'\x00'):
u"""文字列を指定の長さに合うようにpadding_charで埋めて書き込む"""
value_bytes = value.encode(encoding)
padding_bytes = padding_char * (length - len(value_bytes))
self._stream.write(value_bytes + padding_bytes)
def _write_as_pack(self, pack_format, value):
self._stream.write(struct.pack('<' + pack_format, value))
|
import numpy as np
# list to ndarray
data1 = np.array([1, 2, 3, 4, 5], dtype=np.int32)
print(data1)
print(data1.dtype)
data2 = np.int32([1, 2, 3, 4, 5])
print(data2)
data3 = np.array([1, 2, 3, 4, 5], dtype=np.float32)
print(data3)
data4 = np.float32([1, 2, 3, 4, 5])
print(data4)
data5 = np.array([1, 2, 3, 4, 5], dtype=np.str)
print(data5)
print(type(data5))
# 속성
# 1차원 ( 행, ) -> 열 생략
data = np.array([1, 2, 3, 4, 5])
print(data.shape)
print(data.dtype)
print(data.size)
# 2차원 ( 행, 열 )
data = np.array([[1, 2], [3, 4]])
print(data)
print(data.shape)
data = data.astype(np.float32)
data = np.float32(data)
print(data)
# 함수
data6 = np.array([1, 2, 3, 4, 5, 6], dtype=np.float32)
print(data6)
data6 = data6.reshape(3, 2)
print(data6)
data6 = data6.reshape(-1, 2)
print(data6)
|
def count(arr):
if len(arr) == 0:
return 0
return 1 + count(arr[1:])
print count([1,2,3,4]) # => 4 |
# -*- coding: utf-8 -*-
# Define here the models for your scraped items
#
# See documentation in:
# http://doc.scrapy.org/en/latest/topics/items.html
import scrapy
class DoubanItem(scrapy.Item):
# define the fields for your item here like:
# name = scrapy.Field()
name = scrapy.Field() # 书名
author = scrapy.Field() # 作者
press = scrapy.Field() # 出版社
date = scrapy.Field() # 出版日期
page = scrapy.Field() # 页数
price = scrapy.Field() # 价格
score = scrapy.Field() # 读者评分
ISBN = scrapy.Field() # ISBN号
author_profile = scrapy.Field() # 作者简介
content_description = scrapy.Field() # 内容简介
link = scrapy.Field() # 详情页链接
|
#!/usr/bin/env python
import argparse
import datetime
import requests
import sys
import time
ES_URL = 'http://localhost:9200'
ES_REPO = ''
ES_USER = ''
ES_PASS = ''
RETENTION_DAYS = 14
# load settings
try:
from local_settings import *
except:
pass
# process commandline args
parser = argparse.ArgumentParser(description='Purge elasticsearch snapshots')
parser.add_argument('--url', help='Elasticsearch API URL')
parser.add_argument('--username', help='Elasticsearch HTTP basic auth username')
parser.add_argument('--password', help='Elasticsearch HTTP basic auth username')
parser.add_argument('--repository', help='Elasticsearch snapshot repository name')
parser.add_argument('--days', help='Number of days to retain snapshots')
args = parser.parse_args()
if args.url:
ES_URL = args.url
if args.username:
ES_USER = args.username
if args.password:
ES_PASS = args.password
if args.repository:
ES_REPO = args.repository
if args.days:
RETENTION_DAYS = int(args.days)
counts = {'total': 0, 'purged': 0, 'retained': 0, 'failed': 0}
# retrieve snapshot info
print 'Getting snapshot data...'
rr = requests.get('{}/_snapshot/{}/_all'.format(ES_URL, ES_REPO), auth=(ES_USER, ES_PASS))
if rr.status_code != 200:
print rr.text
print 'ERROR: could not retrieve snapshot data; aborting'
sys.exit(1)
_snapshots = rr.json()
# note date of most recent success
last_success = None
for snapshot in _snapshots['snapshots']:
counts['total'] += 1
if snapshot['state'] == 'SUCCESS':
snapshot_start = int(snapshot['start_time_in_millis'])
if last_success is None or snapshot_start > last_success:
last_success = snapshot_start
# if we don't have at least one clean snapshot, abort
if last_success is None:
print 'ERROR: no successful snapshots; aborting'
sys.exit(1)
last_success_date = datetime.datetime.fromtimestamp(int(last_success / 1000)).strftime('%c')
print 'Found {} snapshots; last successful snapshot was {}'.format(counts['total'], last_success_date)
# if most recent success is within age range, delete all snapshots outside age range
# otherwise, delete all snapshots prior to most recent success
purge_date = int(time.time() * 1000) - (RETENTION_DAYS * 24 * 60 * 60 * 1000)
if last_success < purge_date:
purge_date = last_success
print "WARNING: no successful snapshots in retention range"
for snapshot in _snapshots['snapshots']:
if int(snapshot['start_time_in_millis']) < purge_date:
print 'Purging {}'.format(snapshot['snapshot'])
rr = requests.delete('{}/_snapshot/{}/{}'.format(ES_URL, ES_REPO, snapshot['snapshot']), auth=(ES_USER, ES_PASS))
if (rr.status_code == 200):
counts['purged'] += 1
else:
counts['failed'] += 1
print rr.text
else:
counts['retained'] += 1
print 'Done; {retained} retained, {purged} purged, {failed} failed to purge'.format(**counts)
|
print ("this is inside the child_branch in testrepo")
|
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'D:/zoomtc/convertdialog.ui'
#
# Created: Tue Aug 31 22:43:35 2010
# by: PyQt4 UI code generator 4.4.2
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
class Ui_convertDialog(object):
def setupUi(self, convertDialog):
convertDialog.setObjectName("convertDialog")
convertDialog.setWindowModality(QtCore.Qt.WindowModal)
convertDialog.resize(419,126)
icon = QtGui.QIcon()
icon.addPixmap(QtGui.QPixmap("logo.jpg"),QtGui.QIcon.Normal,QtGui.QIcon.Off)
convertDialog.setWindowIcon(icon)
convertDialog.setModal(False)
self.gridLayout_2 = QtGui.QGridLayout(convertDialog)
self.gridLayout_2.setObjectName("gridLayout_2")
self.gridLayout = QtGui.QGridLayout()
self.gridLayout.setObjectName("gridLayout")
self.dirLabel = QtGui.QLabel(convertDialog)
self.dirLabel.setObjectName("dirLabel")
self.gridLayout.addWidget(self.dirLabel,0,0,1,1)
self.dirLineEdit = QtGui.QLineEdit(convertDialog)
self.dirLineEdit.setObjectName("dirLineEdit")
self.gridLayout.addWidget(self.dirLineEdit,0,1,1,1)
self.dirButton = QtGui.QPushButton(convertDialog)
self.dirButton.setObjectName("dirButton")
self.gridLayout.addWidget(self.dirButton,0,2,1,1)
self.rateLabel = QtGui.QLabel(convertDialog)
self.rateLabel.setObjectName("rateLabel")
self.gridLayout.addWidget(self.rateLabel,1,0,1,1)
self.rateLineEdit = QtGui.QLineEdit(convertDialog)
self.rateLineEdit.setObjectName("rateLineEdit")
self.gridLayout.addWidget(self.rateLineEdit,1,1,1,1)
self.convertButton = QtGui.QPushButton(convertDialog)
self.convertButton.setObjectName("convertButton")
self.gridLayout.addWidget(self.convertButton,1,2,1,1)
self.gridLayout_2.addLayout(self.gridLayout,0,0,1,1)
self.helpLabel = QtGui.QLabel(convertDialog)
self.helpLabel.setObjectName("helpLabel")
self.gridLayout_2.addWidget(self.helpLabel,1,0,1,1)
self.retranslateUi(convertDialog)
QtCore.QMetaObject.connectSlotsByName(convertDialog)
def retranslateUi(self, convertDialog):
convertDialog.setWindowTitle(QtGui.QApplication.translate("convertDialog", "执法督查科图片批量处理工具", None, QtGui.QApplication.UnicodeUTF8))
self.dirLabel.setText(QtGui.QApplication.translate("convertDialog", "图片源目录:", None, QtGui.QApplication.UnicodeUTF8))
self.dirButton.setText(QtGui.QApplication.translate("convertDialog", "浏览", None, QtGui.QApplication.UnicodeUTF8))
self.rateLabel.setText(QtGui.QApplication.translate("convertDialog", "转换比例:", None, QtGui.QApplication.UnicodeUTF8))
self.convertButton.setText(QtGui.QApplication.translate("convertDialog", "转换", None, QtGui.QApplication.UnicodeUTF8))
self.helpLabel.setText(QtGui.QApplication.translate("convertDialog", "1.\n"
"2\n"
"3", None, QtGui.QApplication.UnicodeUTF8))
import zoomtc_rc
|
import sys
sys.path.append('../../python')
import caffe
from caffe import surgery, score
import numpy as np
import os
save_format = os.getcwd() + '/out_{}'
weights = sys.argv[1]
caffe.set_mode_gpu()
caffe.set_device(0)
solver = caffe.SGDSolver('solver.prototxt')
solver.net.copy_from(weights)
# load IDs of the TEST phase data
val = np.loadtxt('list.txt', dtype=str)
score.seg_tests(solver, save_format, val, layer='score', gt='label')
|
class Solution(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
y=0
while(x!=0):
y=(y*10)+(x%10)
x=x/10
return y
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Nov 1 11:52:48 2017
@author: wuyiming
"""
import util
import network
import const as C
Xlist,Ylist = util.LoadDataset("vocal", C.PATH_TRAIN)
#Xlist contains the spectrograms of mixture version of song clips in training set,
#Ylist contains the spectrogram of pure singing voice version of song clips in training set.
Plist,Qlist = util.LoadDataset("vocal", C.PATH_VAL)
#Plist contains the spectrograms of mixture version of song clips in validation set,
#Ylist contains the spectrogram of pure singing voice version of song clips in validation set.
print("Dataset loaded.")
ckp = "models\ck20200501UNET_34ep(Hop256).model" #checkpoint if you want reload the mode from checkpoint, instead of starting from the beginning.
network.TrainUNet(Xlist,Ylist,Plist,Qlist,savefile="unet.model",checkpoint = ckp,epoch=60)
|
# from currency_converter import CurrencyConverter
import tkinter as tk
# c = CurrencyConverter()
fields = ('Capital', 'Stoploss', 'Lotsize', 'Amount')
def calculate(entries):
r = (float(entries['Capital'].get()) / 100)
# d = c.convert(r, 'CZK', 'USD')
stp = float(entries['Stoploss'].get())
ls = float(entries['Lotsize'].get())
num = float((r/stp)/10)
entries['Amount'].delete(0, tk.END)
entries['Amount'].insert(0, "%.2f" % num)
if r or stp or ls == 0:
return 0
def makeform(root, fields):
entries = {}
for field in fields:
print(field)
row = tk.Frame(root)
lab = tk.Label(row, width=22, text=field+": ", anchor='w')
ent = tk.Entry(row)
ent.insert(0, "0")
row.pack(side=tk.TOP,
fill=tk.X,
padx=5,
pady=5)
lab.pack(side=tk.LEFT)
ent.pack(side=tk.RIGHT,
expand=tk.YES,
fill=tk.X)
entries[field] = ent
return entries
if __name__ == '__main__':
root = tk.Tk()
ents = makeform(root, fields)
b1 = tk.Button(root, text='How much?',
command=(lambda e=ents: calculate(e)))
b1.pack(side=tk.LEFT, padx=5, pady=5)
root.mainloop()
|
from django.db import models
# Create your models here.
class Grades(models.Model):
gname = models.CharField(max_length=30)
gdate = models.DateField()
ggirlnum = models.IntegerField()
gboynum = models.IntegerField()
isDelete = models.BooleanField(default=False)
def __str__(self):
return "%s--%d--%d" % (self.gname, self.ggirlnum, self.gboynum)
class Students(models.Model):
sname = models.CharField(max_length=30)
sgender = models.BooleanField()
sage = models.IntegerField()
scontent = models.CharField(max_length=30)
isDelete = models.BooleanField(default=False)
sgrade = models.ForeignKey(
"Grades", on_delete=models.CASCADE)
def __str__(self):
return "name:"+sname+" gender:"+sgender
|
def isAnagram(s1, s2):
if len(s1) != len(s2):
return False
# sorted convert a str into a sorted list
new_s1 = ''.join(sorted(s1))
new_s2 = ''.join(sorted(s2))
return new_s1 == new_s2
def main():
s1 = 'aabb'
s2 = 'abab'
s3 = 'aaab'
print isAnagram(s1, s2), isAnagram(s1, s3)
if __name__ == '__main__':
main() |
# Pretix Invoice Renderer for NETWAYS
#
# Copyright 2017 NETWAYS GmbH <support@netways.de>
# Copyright 2017 Raphael Michel <mail@raphaelmichel.de>
#
# 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 django.dispatch import receiver
from pretix.base.signals import register_invoice_renderers
@receiver(register_invoice_renderers, dispatch_uid="output_netways")
def recv_net(sender, **kwargs):
from .invoice import NetInvoiceRenderer
return NetInvoiceRenderer
|
# Exercício 8.2 - Livro
def multiplo (n1, n2):
if n1 % n2 == 0:
return True
else:
return False
m = multiplo(5, 5)
print(m)
|
#!/usr/bin/env python
# Copyright (c) 2017 Universitaet Bremen - Institute for Artificial Intelligence (Prof. Beetz)
#
# Author: Minerva Gabriela Vargas Gleason <minervavargasg@gmail.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import rospy
import rospkg
import sys
import yaml
def yaml_writer(joint_w_values):
# Write a YAML file with the parameters for the simulated controller
try:
# Open YAML configuration file
pack = rospkg.RosPack()
dir = pack.get_path('iai_trajectory_generation_boxy') + '/config/controller_param.yaml'
stream = open(dir, 'r')
data = yaml.load(stream)
data['start_config'] = joint_w_values
# Write file
with open(dir, 'w') as outfile:
yaml.dump(data, outfile, default_flow_style=False)
except yaml.YAMLError:
rospy.logerr("Unexpected error while writing controller configuration YAML file:"), sys.exc_info()[0]
return -1
def zero():
joints_w_values = {
'left_arm_0_joint': -1.0424206770318125,
'left_arm_1_joint': 0.7856426143571664,
'left_arm_2_joint': -0.6005778452870986,
'left_arm_3_joint': -1.664941382894658,
'left_arm_4_joint': -1.9399642647890991,
'left_arm_5_joint': -1.6535906309055022,
'left_arm_6_joint': -2.572054542448777,
'neck_shoulder_lift_joint': -3.0928,
'neck_shoulder_pan_joint': -1.67144,
'neck_wrist_1_joint': 1.23036,
'neck_wrist_2_joint': 1.54493,
'neck_wrist_3_joint': 0.04506,
'odom_x_joint': -1.8,
'odom_y_joint': -0.2,
'odom_z_joint': -0.07,
'right_arm_0_joint': 0.9318561286348706,
'right_arm_1_joint': -0.617115289630847,
'right_arm_2_joint': -2.5853490151650087,
'right_arm_3_joint': -1.5708929937611393,
'right_arm_4_joint': -1.3310840639433288,
'right_arm_5_joint': 1.7323502336223708,
'right_arm_6_joint': -0.9896413787705906,
'triangle_base_joint': -0.31}
return joints_w_values
def one():
joints_w_values = {
'odom_x_joint': -1.8,
'odom_y_joint': 0.3,
'odom_z_joint': -0.07,
'left_arm_0_joint': -0.10456647767360518,
'left_arm_1_joint': 1.029796254224278,
'left_arm_2_joint': -1.288067942098535,
'left_arm_3_joint': -0.6949976889629007,
'left_arm_4_joint': -2.5945720631578344,
'left_arm_5_joint': -1.9141940305249716,
'left_arm_6_joint': -1.3956831415804725,
'right_arm_0_joint': 0.3980990661937716,
'right_arm_1_joint': -0.22682036102428657,
'right_arm_2_joint': -2.519665972562763,
'right_arm_3_joint': -1.0591165004990204,
'right_arm_4_joint': -1.07072089632891,
'right_arm_5_joint': 1.661148155502822,
'right_arm_6_joint': -2.00116550815594,
'triangle_base_joint': -0.19461386714773432,
'neck_shoulder_lift_joint': -3.0928,
'neck_shoulder_pan_joint': -1.67144,
'neck_wrist_1_joint': 1.23036,
'neck_wrist_2_joint': 1.54493,
'neck_wrist_3_joint': 0.04506
}
return joints_w_values
def two():
joints_w_values = {
'left_arm_0_joint': -0.9615,
'left_arm_1_joint': 0.8983,
'left_arm_2_joint': -0.6097,
'left_arm_3_joint': -1.5235,
'left_arm_4_joint': -1.837,
'left_arm_5_joint': -1.6221,
'left_arm_6_joint': -2.48,
'neck_shoulder_lift_joint': -3.0928,
'neck_shoulder_pan_joint': -1.67144,
'neck_wrist_1_joint': 1.23036,
'neck_wrist_2_joint': 1.54493,
'neck_wrist_3_joint': 0.04506,
'odom_x_joint': -2.5,
'odom_y_joint': 0.5,
'odom_z_joint': -0.07,
'right_arm_0_joint': 0.955,
'right_arm_1_joint': -0.591,
'right_arm_2_joint': -2.509,
'right_arm_3_joint': -1.457,
'right_arm_4_joint': -1.234,
'right_arm_5_joint': 1.804,
'right_arm_6_joint': -1.068,
'triangle_base_joint': -0.2}
return joints_w_values
def three():
joints_w_values = {
'odom_x_joint': -2.2,
'odom_y_joint': 0.5,
'odom_z_joint': -0.07,
'left_arm_0_joint': -1.557,
'left_arm_1_joint': 0.8408,
'left_arm_2_joint': 0.0997,
'left_arm_3_joint': -1.4161,
'left_arm_4_joint': -2.251,
'left_arm_5_joint': -1.482,
'left_arm_6_joint': -2.324,
'right_arm_0_joint': 1.03542,
'right_arm_1_joint': -0.621414,
'right_arm_2_joint': -2.560179,
'right_arm_3_joint': -1.467654,
'right_arm_4_joint': -1.296731,
'right_arm_5_joint': 1.8575937,
'right_arm_6_joint': -1.0270237,
'triangle_base_joint': -0.41,
'neck_shoulder_lift_joint': -3.0928,
'neck_shoulder_pan_joint': -1.67144,
'neck_wrist_1_joint': 1.23036,
'neck_wrist_2_joint': 1.54493,
'neck_wrist_3_joint': 0.04506}
return joints_w_values
def four():
joints_w_values = {
'odom_x_joint': -2.5,
'odom_y_joint': 1.06,
'odom_z_joint': -0.07,
'left_arm_0_joint': -1.7129450795042869,
'left_arm_1_joint': 0.5999335018191572,
'left_arm_2_joint': 0.04660023567009371,
'left_arm_3_joint': -1.8599999999999897,
'left_arm_4_joint': -2.3279241623992997,
'left_arm_5_joint': -1.4812329512323177,
'left_arm_6_joint': -2.579523558981309,
'right_arm_0_joint': 0.9031112794890239,
'right_arm_1_joint': -0.4039121646177973,
'right_arm_2_joint': -2.5999999999999783,
'right_arm_3_joint': -1.6117120285581779,
'right_arm_4_joint': -0.8580671212943127,
'right_arm_5_joint': 1.9899999999999893,
'right_arm_6_joint': -1.0752377540035896,
'triangle_base_joint': -0.25941441542417976,
'neck_shoulder_lift_joint': -3.0928,
'neck_shoulder_pan_joint': -1.67144,
'neck_wrist_1_joint': 1.23036,
'neck_wrist_2_joint': 1.54493,
'neck_wrist_3_joint': 0.04506
}
return joints_w_values
def five():
joints_w_values = {
'odom_x_joint': -1.5,
'odom_y_joint': 0.6,
'odom_z_joint': -0.07,
'left_arm_0_joint': -0.2602758811845149,
'left_arm_1_joint': 0.5699576299562188,
'left_arm_2_joint': -0.8360587280567272,
'left_arm_3_joint': -1.590070040825777,
'left_arm_4_joint': -2.537669649858849,
'left_arm_5_joint': -1.178846334671371,
'left_arm_6_joint': -1.7240697677555108,
'right_arm_0_joint': 0.3548792764770302,
'right_arm_1_joint': -0.7342053410025529,
'right_arm_2_joint': -2.500505290058151,
'right_arm_3_joint': -1.0565600096681835,
'right_arm_4_joint': -0.6428302806193216,
'right_arm_5_joint': 1.789959638331654,
'right_arm_6_joint': -1.537211638335914,
'triangle_base_joint': -0.1495481641584547,
'neck_shoulder_lift_joint': -3.0928,
'neck_shoulder_pan_joint': -1.67144,
'neck_wrist_1_joint': 1.23036,
'neck_wrist_2_joint': 1.54493,
'neck_wrist_3_joint': 0.04506
}
return joints_w_values
def six():
joints_w_values = {
'odom_x_joint': -1.5,
'odom_y_joint': 0.0,
'odom_z_joint': -0.07,
'left_arm_0_joint': -0.02737896573905153,
'left_arm_1_joint': 0.6346913283386225,
'left_arm_2_joint': -1.0208696610005272,
'left_arm_3_joint': -1.4127033362970067,
'left_arm_4_joint': -2.461101342274959,
'left_arm_5_joint': -1.062781974441715,
'left_arm_6_joint': -1.555507230976369,
'right_arm_0_joint': -0.5891928530304978,
'right_arm_1_joint': -0.7776772581633704,
'right_arm_2_joint': -1.7386497360661208,
'right_arm_3_joint': -1.7229435066594225,
'right_arm_4_joint': -1.2801661171529497,
'right_arm_5_joint': 0.3852927345385064,
'right_arm_6_joint': -1.2714225400541546,
'triangle_base_joint': -0.014998105556107942,
'neck_shoulder_lift_joint': -3.0928,
'neck_shoulder_pan_joint': -1.67144,
'neck_wrist_1_joint': 1.23036,
'neck_wrist_2_joint': 1.54493,
'neck_wrist_3_joint': 0.04506
}
return joints_w_values
def seven():
joints_w_values = {
'odom_x_joint': -1.2, # 2.2
'odom_y_joint': 0.0, # 0.6
'odom_z_joint': -0.07,
'left_arm_0_joint': -1.5939017921498873,
'left_arm_1_joint': 0.8390743106005174,
'left_arm_2_joint': 0.0854756106501257,
'left_arm_3_joint': -1.358306360009408,
'left_arm_4_joint': -2.271386583316387,
'left_arm_5_joint': -1.554795183790794,
'left_arm_6_joint': -2.303716987463937,
'right_arm_0_joint': 0.822462125108796,
'right_arm_1_joint': -0.6310336025351757,
'right_arm_2_joint': -2.599671870840573,
'right_arm_3_joint': -1.592543876588925,
'right_arm_4_joint': -1.3963310121304198,
'right_arm_5_joint': 1.632141298729036,
'right_arm_6_joint': -0.66445876942373,
'triangle_base_joint': -0.34682312271737925,
'neck_shoulder_lift_joint': -3.0928,
'neck_shoulder_pan_joint': -1.67144,
'neck_wrist_1_joint': 1.23036,
'neck_wrist_2_joint': 1.54493,
'neck_wrist_3_joint': 0.04506
}
return joints_w_values
def eight():
joints_w_values = {
'left_arm_0_joint': -1.831434965133667,
'left_arm_1_joint': 0.710098385810852,
'left_arm_2_joint': 0.963445782661438,
'left_arm_3_joint': -0.6084356904029846,
'left_arm_4_joint': -2.5866940021514893,
'left_arm_5_joint': -1.9400300979614258,
'left_arm_6_joint': -1.2900283336639404,
'odom_x_joint': -1.5,
'odom_y_joint': -0.6,
'odom_z_joint': 0.7,
'right_arm_0_joint': -0.5976466536521912,
'right_arm_1_joint': 0.5533322691917419,
'right_arm_2_joint': -0.750594973564148,
'right_arm_3_joint': -0.010870818048715591,
'right_arm_4_joint': 0.826876699924469,
'right_arm_5_joint': -0.466553658246994,
'right_arm_6_joint': 2.046936511993408,
'triangle_base_joint': -0.2314388,
'neck_shoulder_lift_joint': -3.0928,
'neck_shoulder_pan_joint': -1.67144,
'neck_wrist_1_joint': 1.23036,
'neck_wrist_2_joint': 1.54493,
'neck_wrist_3_joint': 0.04506
}
return joints_w_values
def nine():
joints_w_values = {
'odom_x_joint':-2.0,
'odom_y_joint': 0.6,
'odom_z_joint': -0.07,
'left_arm_0_joint': -1.8141040791344656,
'left_arm_1_joint': 0.5041563170652014,
'left_arm_2_joint': -0.06745831729484648,
'left_arm_3_joint': -1.6706647341321785,
'left_arm_4_joint': -2.323427271128583,
'left_arm_5_joint': -1.251311271483552,
'left_arm_6_joint': -2.4343250641865994,
'right_arm_0_joint': 0.7630299467680984,
'right_arm_1_joint': -0.24891211019592718,
'right_arm_2_joint': -2.3904063918914167,
'right_arm_3_joint': -1.3111724708970076,
'right_arm_4_joint': -0.9805491626453996,
'right_arm_5_joint': 1.6912437261370856,
'right_arm_6_joint': -1.527660926082835,
'triangle_base_joint': -0.2694484716606053,
'neck_shoulder_lift_joint': -3.0928,
'neck_shoulder_pan_joint': -1.67144,
'neck_wrist_1_joint': 1.23036,
'neck_wrist_2_joint': 1.54493,
'neck_wrist_3_joint': 0.04506
}
return joints_w_values
'''def seven():
joints_w_values = {
'odom_x_joint':
'odom_y_joint':
'odom_z_joint':
'left_arm_0_joint':
'left_arm_1_joint':
'left_arm_2_joint':
'left_arm_3_joint':
'left_arm_4_joint':
'left_arm_5_joint':
'left_arm_6_joint':
'right_arm_0_joint':
'right_arm_1_joint':
'right_arm_2_joint':
'right_arm_3_joint':
'right_arm_4_joint':
'right_arm_5_joint':
'right_arm_6_joint':
'triangle_base_joint':
'neck_shoulder_lift_joint': -3.0928,
'neck_shoulder_pan_joint': -1.67144,
'neck_wrist_1_joint': 1.23036,
'neck_wrist_2_joint': 1.54493,
'neck_wrist_3_joint': 0.04506
}
return joints_w_values'''
def select_option():
config_number = sys.argv[1]
options = {0: zero,
1: one,
2: two,
3: three,
4: four,
5: five,
6: six,
7: seven,
8: eight,
9: nine,
}
joint_w_values = options[int(config_number)]()
yaml_writer(joint_w_values)
if __name__ == '__main__':
select_option()
|
s = input()
d={}
s=list(s)
for x in range(len(s)):
if s[x] not in d.keys():
d[s[x]]=1
else:
d[s[x]]+=1
l=[]
for x in sorted(d.values()):
l.append(x)
l=list(reversed(l))
if len(l)>2:
del l[0]
del l[0]
print(sum(l))
else:
print(0)
|
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
from sklearn.linear_model import LinearRegression,LogisticRegression
from sklearn.naive_bayes import GaussianNB,MultinomialNB,BernoulliNB
from sklearn.cluster import KMeans
from sklearn.svm import SVR
from sklearn.ensemble import RandomForestClassifier,GradientBoostingClassifier
dataset = pd.read_csv("Titanic Disaster Dataset.csv") #Read Data Set...
dataset = dataset.fillna(method='ffill') #So we fill NaN value using builtin method...
#Convert Categorical Data into integer and float...
dataset.Gender.replace({'male' : 0, 'female' : 1 },inplace = True)
dataset.Embarked.replace({'S' : 0, 'C' : 1 ,'Q': 2},inplace = True)
X = dataset.loc[:, ['PassengerId','PClass', 'Gender','Sibling', 'Embarked']] #X variable contains all the attributes/features...
Y = dataset['Survived'].values #Y variables contains labels...
X_train , X_test , Y_train, Y_test = train_test_split(X, Y ,test_size = 0.2 ,random_state = 0) #80% of data into training set and 20% of data into test set...
#Now we train our models...
linearRegression = LinearRegression() #Linear Regression...
linearRegression.fit(X_train,Y_train)
decisionTreeClassifier = DecisionTreeClassifier() #Decision Tree Classifier...
decisionTreeClassifier.fit(X_train,Y_train)
gaussianNB = GaussianNB() #GaussianNB...
gaussianNB.fit(X_train,Y_train)
kmeans = KMeans() #KMeans...
kmeans.fit(X_train,Y_train)
rfc = RandomForestClassifier() #RandomForestClassifier
rfc.fit(X_train,Y_train)
svr = SVR() #SVR
svr.fit(X_train,Y_train)
logisticRegression = LogisticRegression() #LogisticRegression
logisticRegression.fit(X_train,Y_train)
multinomialNB = MultinomialNB() #MultinomialNB
multinomialNB.fit(X_train,Y_train)
bernoulliNB = BernoulliNB() #BernoulliNB
bernoulliNB.fit(X_train,Y_train)
gradientBoostingClassifier = GradientBoostingClassifier() #GradientBoostingClassifier
gradientBoostingClassifier.fit(X_train,Y_train)
#Now we predict on Test data...
y1_predict = linearRegression.predict(X_test) #Predict Survival value for X_test data set...
print(y1_predict) #In point -0.9 to 0.9
def givePrediction(passengerID , pClass , gender , sibling , embarked , algo):
predict = 0
if(algo=="LinearRegression"):
predict = LinearRegression.predict([passengerID,pClass,getGenderValue(gender),sibling,getEmbarkedValue(embarked)])
elif (algo == "DecisionTreeClassifier"):
predict = DecisionTreeClassifier.predict([passengerID,pClass,getGenderValue(gender),sibling,getEmbarkedValue(embarked)])
elif (algo == "GaussianNB"):
predict = GaussianNB.predict([passengerID,pClass,getGenderValue(gender),sibling,getEmbarkedValue(embarked)])
elif (algo == "KMeans"):
predict = KMeans.predict([passengerID,pClass,getGenderValue(gender),sibling,getEmbarkedValue(embarked)]) #Give value from 0 to 10
if( predict < 5 ):
predict = 0
elif( predict >= 5):
predict = 1
elif (algo == "SVR"):
predict = SVR.predict([passengerID,pClass,getGenderValue(gender),sibling,getEmbarkedValue(embarked)]) #0.0 TO 0.1
if(predict <0.05):
predict = 0
elif(predict >=0.05 ):
predict = 1
elif (algo == "RandomForestClassifier"):
predict = RandomForestClassifier.predict([passengerID,pClass,getGenderValue(gender),sibling,getEmbarkedValue(embarked)])
elif (algo == "LogisticRegression"):
predict = LogisticRegression.predict([passengerID,pClass,getGenderValue(gender),sibling,getEmbarkedValue(embarked)])
elif (algo == "MultinomialNB"):
predict = MultinomialNB.predict([passengerID,pClass,getGenderValue(gender),sibling,getEmbarkedValue(embarked)])
elif (algo == "BernoulliNB"):
predict = BernoulliNB.predict([passengerID,pClass,getGenderValue(gender),sibling,getEmbarkedValue(embarked)])
elif (algo == "GradientBoostingClassifier"):
predict = GradientBoostingClassifier.predict([passengerID,pClass,getGenderValue(gender),sibling,getEmbarkedValue(embarked)])
return predict
def getGenderValue(gender):
if(gender=="Male"):
return 0
elif(gender == "Female"):
return 1
def getEmbarkedValue(embarked):
if(embarked == "S"):
return 0
elif(embarked == "C"):
return 1
elif(embarked == "Q"):
return 2
|
from django.contrib import admin
from mainsite.models import ArticleCategory, Article
admin.site.register([Article, ArticleCategory])
|
def sc(s):
return ''.join([x for x in s if s.count(x.lower())>0 and s.count(x.upper())>0])
'''
#Task:
Every uppercase letter is a Father, The corresponding lowercase letters is the Son.
Given the string ```s```, If the father and son both exist, keep them. If it is
a separate existence, delete them. Return the result.
For example:
```sc("Aab")``` should return ```"Aa"```
```sc("AabBc")``` should return ```"AabB"```
```sc("AaaaAaab")``` should return ```"AaaaAaa"```(father can have a lot of childs)
```sc("aAAAaAAb")``` should return ```"aAAAaAA"```(childs can also have a lot of parents)
'''
|
import time, requests
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException, NoSuchElementException, WebDriverException
from utils.function.general import wait_visible_element, timestamp_print, timestamp_print_verify_url
from utils.lib.user import Environment
from urllib.error import HTTPError
from requests import exceptions
class BasePage(object):
log_result = ""
url = ""
site = {
"live-site" : "https://www.tokopedia.com/",
"beta-site" : "https://beta.tokopedia.com/",
"staging-site" : "https://staging.tokopedia.com/",
"test-site" : "https://test.tokopedia.nginx/",
"dev-site" : "http://tokopedia.dev/"
}
def __init__(self, driver):
self.driver = driver
def _open(self, site="", pl=""):
current_env = Environment()
if(site == "dev"):
self.url = self.site['dev-site']
elif(site == "nginx"):
self.url = self.site['test-site']
elif(site == "beta"):
self.url = self.site['beta-site']
elif(site == "staging"):
self.url = self.site['staging-site']
elif(site == "live"):
self.url = self.site['live-site']
else:
self.url = site
current_env.setEnv(self.url)
selected_env = current_env.getEnv()
self.get_page_load_time(self.url + pl)
return selected_env
#assert self.on_page(), 'Did not land on %s' % url | #fungsi bawaan yang gw belom cukup level untuk pemakaian-nya.
def get_page_load_time(self, url): #Fungsi untuk mengakses suatu halaman dan waktu proses-nya
#response = urllib.request.urlopen(url)
retry = 0
set_time_out = 60
while (retry<3):
try:
timestart = time.clock()
self.driver.set_page_load_timeout(set_time_out)
self.driver.implicitly_wait(10)
self.driver.get(url)
# if "www" in url :
# response = requests.get(url, verify = True, timeout=30)
# elif "dev" or "nginx" or "beta" in url:
# response = requests.get(url, verify = False, timeout=30)
timeend = time.clock()
loadtime = timeend-timestart
timestamp_print(url, loadtime, self.log_result)
break
except TimeoutException:
print ("Load Page takes too long, it's over %s second" %(set_time_out))
self.driver.refresh()
retry +=1
except requests.exceptions.HTTPError:
if requests.get(url).status_code == 500:
print ("Error code 500 : Maaf, saat ini Tokopedia sedang kepenuhan pengunjung. ")
elif requests.get(url).status_code == 503:
print ("Error code 503 : Tokopedia sedang maintenance.")
elif requests.get(url).status_code == 502:
print ("Error code 502 : Bad Gateway.")
elif requests.get(url).status_code ==504:
print ("Error code 504 : Gateway Timeout.")
retry +=1
except ConnectionRefusedError as e:
print (e)
retry +=1
def _click(self, loc):
timestart = time.clock()
loc.click()
timeend = time.clock()
loadtime = timeend-timestart
timestamp_print_verify_url(self.driver.current_url, loadtime, self.log_result)
#print (self.driver.current_url + " is accessed in " + str(loadtime) + " second")
def _click_to_pop(self, *loc):
self.check_visible_element(*loc)
self.find_element(*loc).click()
def check_visible_element(self, by, element):
retry = 0
while(retry<3):
try:
WebDriverWait(self.driver,30).until(EC.visibility_of_element_located((by,element)))
break
except NoSuchElementException:
retry += 1
print ("Element not found.. retry attempt %s" %(retry))
except TimeoutException:
retry +=1
print ("Load Element is taking too long.. retry attempt %s" %(retry))
def check_clickable_element(self, by, element):
retry = 0
while(retry<3):
try:
WebDriverWait(self.driver,30).until(EC.element_to_be_clickable((by,element)))
break
except NoSuchElementException:
retry += 1
print ("Element not found.. retry attempt %s" %(retry))
except TimeoutException:
retry +=1
print ("Load Element is taking too long.. retry attempt %s" %(retry))
def click_on_javascript(self, target_element):
self.mouse = webdriver.ActionChains(self.driver)
return self.mouse.move_to_element(target_element).click().perform()
def mouse_hover_to(self, by, element):
target_element = self.find_element(by, element)
self.check_visible_element(by, element)
hover_to_target = ActionChains(self.driver).move_to_element(target_element)
hover_to_target.perform()
return target_element
#Find single element
def find_element(self, *loc):
return self.driver.find_element(*loc)
#Find multiple element
def find_elements(self, *loc):
try:
return self.driver.find_elements(*loc)
except:
print(" ")
def on_page(self):
return self.driver.current_url == (self.url)
class switch(object):
value = None
def __new__(class_, value):
class_.value = value
return True
#Return value based on the value of an input from class object
def case(*args):
return any((arg == switch.value for arg in args))
|
import graphlab
import numpy as np
from scipy.sparse import csr_matrix
def sframe_to_scipy(x, column_name):
assert x[column_name].dtype() == dict, \
'The chosen column must be dict type, representing sparse data.'
# Create triples of (row_id, feature_id, count).
# 1. Add a row number.
x = x.add_row_number()
# 2. Stack will transform x to have a row for each unique (row, key) pair.
x = x.stack(column_name, ['feature', 'value'])
# Map words into integers using a OneHotEncoder feature transformation.
f = graphlab.feature_engineering.OneHotEncoder(features=['feature'])
# 1. Fit the transformer using the above data.
f.fit(x)
# 2. The transform takes 'feature' column and adds a new column 'feature_encoding'.
x = f.transform(x)
# 3. Get the feature mapping.
mapping = f['feature_encoding']
# 4. Get the feature id to use for each key.
x['feature_id'] = x['encoded_features'].dict_keys().apply(lambda x: x[0])
# Create numpy arrays that contain the data for the sparse matrix.
i = np.array(x['id'])
j = np.array(x['feature_id'])
v = np.array(x['value'])
width = x['id'].max() + 1
height = x['feature_id'].max() + 1
# Create a sparse matrix.
mat = csr_matrix((v, (i, j)), shape=(width, height))
return mat, mapping
|
import pandas as pd
import matplotlib.pyplot as plt
import argparse
import numpy as np
parser = argparse.ArgumentParser(description='print graph')
parser.add_argument('--fcol_one', type=str, default='null',
help='file of the colision perf for agent 1')
parser.add_argument('--fcol_two', type=str, default='null',
help='file of the colision perf for agent 2')
parser.add_argument('--fcats_one', type=str, default='null',
help='file of the cat hits perf for agent 1')
parser.add_argument('--fcats_two', type=str, default='null',
help='file of the cat hits perf for agent 2')
parser.add_argument('--felders_one', type=str, default='null',
help='file of the elders saved perf for agent 1')
parser.add_argument('--felders_two', type=str, default='null',
help='file of the elders saved perf for agent 2')
#parser.add_argument('--t', type=str, default='null',help='parameter studied')
parser.add_argument('--fp', type=str, default='null',help='name of the first policy')
parser.add_argument('--sp', type=str, default='null',help='name of the second policy')
parser.add_argument('--nb_eps', type=int, default= 1000,
help='number of episodes')
parser.add_argument('--nb_steps', type=int, default= 300,
help='number of episodes')
parser.add_argument('--id', type=str, default= 'null',
help='identify the experiment')
parser.add_argument('--nb_exp', type=int, default= 10,
help='number of experiments')
parser.add_argument('--first_exp', type=int, default= 0,
help='index of the first experiment')
args = parser.parse_args()
printCOLO = False
printCOLT = False
printCATSO = False
printCATST = False
printELDO = False
printELDT = False
x_axis = list(range(args.nb_steps+1))
colo_list = [0 for i in x_axis]
colt_list = [0 for i in x_axis]
catso_list = [0 for i in x_axis]
catst_list = [0 for i in x_axis]
eldo_list = [0 for i in x_axis]
eldt_list = [0 for i in x_axis]
for exp in range(args.first_exp, args.first_exp + args.nb_exp):
if args.fcol_one != 'null':
colo_data = pd.read_csv('./record_timesteps/'+str(exp)+'_'+args.fcol_one, header=None).to_dict()
for i in x_axis:
colo_list[i] += colo_data[0][i]
printCOLO = True
if args.fcol_two != 'null':
colt_data = pd.read_csv('./record_timesteps/'+str(exp)+'_'+args.fcol_two, header=None).to_dict()
for i in x_axis:
colt_list[i] += colt_data[0][i]
printCOLT = True
if args.fcats_one != 'null':
catso_data = pd.read_csv('./record_timesteps/'+str(exp)+'_'+args.fcats_one, header=None).to_dict()
for i in x_axis:
catso_list[i] += catso_data[0][i]
printCATSO = True
if args.fcats_two != 'null':
catst_data = pd.read_csv('./record_timesteps/'+str(exp)+'_'+args.fcats_two, header=None).to_dict()
for i in x_axis:
catst_list[i] += catst_data[0][i]
printCATST = True
if args.felders_one != 'null':
eldo_data = pd.read_csv('./record_timesteps/'+str(exp)+'_'+args.felders_one, header=None).to_dict()
for i in x_axis:
eldo_list[i] += eldo_data[0][i]
printELDO = True
if args.felders_two != 'null':
eldt_data = pd.read_csv('./record_timesteps/'+str(exp)+'_'+args.felders_two, header=None).to_dict()
for i in x_axis:
eldt_list[i] += eldt_data[0][i]
printELDT = True
plt.figure(figsize=(14,10))
if printCOLO == True:
for i in x_axis:
if colo_list[i] != 0:
colo_list[i] = colo_list[i]/args.nb_exp
plt.plot(x_axis , colo_list, c='b', label="collisions of " + args.fp )
if printCOLT == True:
for i in x_axis:
if colt_list[i] != 0:
colt_list[i] = colt_list[i]/args.nb_exp
plt.plot(x_axis , colt_list, c='green', label="collisions of " + args.sp )
if printCATSO == True:
for i in x_axis:
if catso_list[i] != 0:
catso_list[i] = catso_list[i]/args.nb_exp
plt.plot(x_axis , catso_list, c='purple', label="cats hit of " + args.fp )
if printCATST == True:
for i in x_axis:
if catst_list[i] != 0:
catst_list[i] = catst_list[i]/args.nb_exp
plt.plot(x_axis , catst_list, c='r', label="cats hit of " + args.sp )
if printELDO == True:
for i in x_axis:
if eldo_list[i] != 0:
eldo_list[i] = eldo_list[i]/args.nb_exp
plt.plot(x_axis , eldo_list, c='yellow', label="elders saved of " + args.fp )
if printELDT == True:
for i in x_axis:
if eldt_list[i] != 0:
eldt_list[i] = eldt_list[i]/args.nb_exp
plt.plot(x_axis , eldt_list, c='orange', label="elders saved of " + args.sp )
plt.legend()
plt.xlabel("Number of steps")
plt.ylabel("Score")
plt.title("Comparing the score of the different policies")
plt.savefig('./images_timesteps/'+args.id+'_mean_comparison_global.png')
|
'''Tests the image_utils.py module.'''
import numpy as np
import numpy.random as npr
import rl_od.common.image_utils as image_utils
def create_checkerboard():
'''Return an array with a checkboard pattern.'''
image = np.empty((16, 16))
image[8:, :8] = image[:8, 8:] = 2
image[8:, 8:] = 4
image = (image * 64 - 1).astype(np.uint8)
image[:8, :8] = 0
return image
def test_ImageZoomer_from_array():
'''Test ImageZoomer from_array class method.'''
image_array = npr.randint(255, size=(16, 16))
image_zoomer = image_utils.ImageZoomer.from_array(image_array)
assert image_zoomer.size == (16, 16)
assert np.all(np.array(image_zoomer.image) == image_array)
def test_ImageZoomer_adjust():
'''Test ImageZoomer adjust method.'''
image_zoomer = image_utils.ImageZoomer.from_array(create_checkerboard())
image_zoomer.adjust(0.5, 0.5, 0, 0)
assert np.all(np.array(image_zoomer.image) == 0)
image_zoomer.pop()
image_zoomer.adjust(0.5, 0.5, 0.5, 0)
assert np.all(np.array(image_zoomer.image) == 127)
image_zoomer.pop()
image_zoomer.adjust(0.5, 0.5, 0, 0.5)
assert np.all(np.array(image_zoomer.image) == 127)
image_zoomer.pop()
image_zoomer.adjust(0.5, 0.5, 0.5, 0.5)
assert np.all(np.array(image_zoomer.image) == 255)
def test_ImageZoomer_shrink():
'''Test ImageZoomer shrink method.'''
image_zoomer = image_utils.ImageZoomer.from_array(create_checkerboard())
image_zoomer.shrink(0.5, 0.5)
assert np.all(np.array(image_zoomer.image) == 0)
image_zoomer.pop()
image_zoomer.shrink(0.75, 0.75)
assert not np.all(np.array(image_zoomer.image) == 0)
def test_ImageZoomer_translate():
'''Test ImageZoomer translate method.'''
image_zoomer = image_utils.ImageZoomer.from_array(create_checkerboard())
image_zoomer.translate(0.5, 0)
assert set(np.array(image_zoomer.image).ravel()) == {127, 255}
image_zoomer.pop()
image_zoomer.translate(0, 0.5)
assert set(np.array(image_zoomer.image).ravel()) == {127, 255}
image_zoomer.pop()
image_zoomer.translate(0.5, 0.5)
assert np.all(np.array(image_zoomer.image) == 255)
|
i=10
for j in range(i-1):
print((i-j)*"#"+(2*j+1)*"*")
for j in range(i-1,-1,-1):
print((i-j)*"#"+(2*j+1)*"*")
|
"""
API mock for Rackspace Queues.
"""
from __future__ import absolute_import, division, unicode_literals
import json
import collections
from uuid import uuid4
from six import text_type
from mimic.imimic import IAPIMock
from twisted.plugin import IPlugin
from mimic.catalog import Entry
from mimic.catalog import Endpoint
from mimic.model.queue_objects import QueueCollection
from mimic.rest.mimicapp import MimicApp
from zope.interface import implementer
def _client_id(request):
"""
Gets the value of the Client-ID header from the request.
We know the Client-ID must be decodable as ASCII because
Cloud Queues requires it to be submitted as a UUID. Mimic
is not so strict, but requiring ASCII is ok.
"""
return request.requestHeaders.getRawHeaders(b'client-id')[0].decode("ascii")
@implementer(IAPIMock, IPlugin)
class QueueApi(object):
"""
API mock for Queues.
"""
def __init__(self, regions=["ORD", "DFW", "IAD"]):
"""
Create a QueueApi with an empty region cache
"""
self._regions = regions
def resource_for_region(self, uri_prefix, region, session_store):
"""
Get an :obj:`twisted.web.iweb.IResource` for the given URI prefix;
implement :obj:`IAPIMock`.
"""
return (QueueApiRoutes(self, uri_prefix, session_store, region).app.resource())
def catalog_entries(self, tenant_id):
"""
List catalog entries for the Nova API.
"""
return [
Entry(
tenant_id, "rax:queues", "cloudQueues",
[
Endpoint(tenant_id, region, text_type(uuid4()),
prefix="v1")
for region in self._regions
]
)
]
class QueueApiRoutes(object):
"""
Klein routes for queue API methods.
"""
app = MimicApp()
def __init__(self, api_mock, uri_prefix, session_store, queue_name):
"""
Create a queue region with a given URI prefix (used for generating URIs
to queues).
"""
self.uri_prefix = uri_prefix
self._api_mock = api_mock
self._session_store = session_store
self._queue_name = queue_name
def _queue_collection(self, tenant_id):
"""
Get the given queue-cache object for the given tenant, creating one if
there isn't one.
"""
return (self._session_store.session_for_tenant_id(tenant_id)
.data_for_api(self._api_mock,
lambda: collections.defaultdict(
lambda: QueueCollection(clock=self._session_store.clock)))
[self._queue_name])
@app.route("/v1/<string:tenant_id>/queues/<string:queue_name>", methods=['PUT'])
def create_queue(self, request, tenant_id, queue_name):
"""
Api call to create and save queue. HTTP status code of 201.
"""
q_collection = self._queue_collection(tenant_id)
(response_body, response_code) = q_collection.add_queue(queue_name)
request.setResponseCode(response_code)
return json.dumps(response_body)
@app.route("/v1/<string:tenant_id>/queues", methods=['GET'])
def list_queues(self, request, tenant_id):
"""
Api call to get a list of queues. HTTP status code of 200
"""
q_collection = self._queue_collection(tenant_id)
(response_body, response_code) = q_collection.list_queues()
request.setResponseCode(response_code)
return json.dumps(response_body)
@app.route("/v1/<string:tenant_id>/queues/<string:queue_name>", methods=['DELETE'])
def del_queue(self, request, tenant_id, queue_name):
"""
Api call to delete a queue. HTTP status code of 201
"""
q_collection = self._queue_collection(tenant_id)
(response_body, response_code) = q_collection.delete_queue(queue_name)
request.setResponseCode(response_code)
return json.dumps(response_body)
@app.route("/v1/<string:tenant_id>/queues/<string:queue_name>/messages", methods=['GET'])
def list_messages_for_queue(self, request, tenant_id, queue_name):
"""
Lists messages from the queue.
"""
q_collection = self._queue_collection(tenant_id)
echo = request.args.get(b'echo', [b'false'])[0] == b'true'
(response_body, response_code) = q_collection.list_messages_for_queue(
queue_name, _client_id(request), echo)
request.setResponseCode(response_code)
return json.dumps(response_body)
@app.route("/v1/<string:tenant_id>/queues/<string:queue_name>/messages", methods=['POST'])
def post_messages_to_queue(self, request, tenant_id, queue_name):
"""
Posts messages to the queue.
"""
q_collection = self._queue_collection(tenant_id)
messages = json.loads(request.content.read().decode("utf-8"))
(response_body, response_code) = q_collection.post_messages_to_queue(
queue_name, messages, _client_id(request))
request.setResponseCode(response_code)
return json.dumps(response_body)
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Apr 19 14:06:01 2018
@author: paf
"""
import os
#
import tensorflow as tf
import math
#
from general_utility import canTFUseGPU
class AutoEncoder:
def __init__(self, layers, lr=0.01, epoch=200, batch_size=512, transfer_function=tf.nn.relu, error_func = lambda x: tf.norm(x,axis=1), print_device=False):
device = '/cpu:0'
if canTFUseGPU():
if print_device:
print("\nUsing GPU\n")
device = '/gpu:0'
with tf.device(device):
self.layers = layers
self.lr = lr
self.epoch = epoch
self.batch_size = batch_size
#
self.x = tf.placeholder("float", [None, self.layers[0]])
#
self.W = []
#
self.h = []
self.b = []
#
self.g = []
self.c = []
#
self.d = []
for i in range(len(self.layers)-1):
limit = 1.0 / math.sqrt(self.layers[i])
Wi = tf.Variable(tf.random_uniform((self.layers[i], self.layers[i+1]), -limit, limit))
self.W.append(Wi)
#
bi = tf.Variable(tf.zeros([self.layers[i+1]]))
self.b.append(bi)
#
hi = None
if i==0:
hi = transfer_function(tf.matmul(self.x,Wi) + bi)
else:
hi = transfer_function(tf.matmul(self.h[-1],Wi) + bi)
self.h.append(hi)
for i in reversed(range(len(self.layers)-1)):
WiT = tf.transpose(self.W[i])
#
ci = tf.Variable(tf.zeros([self.layers[i]]))
self.c.append(ci)
#
gi = None
if i == len(self.layers)-2:
gi = transfer_function(tf.matmul(self.h[-1],WiT) + ci)
elif i==0:
gi = tf.matmul(self.g[-1],WiT) + ci
else:
gi = transfer_function(tf.matmul(self.g[-1],WiT) + ci)
self.g.append(gi)
self.g = list(reversed(self.g))
self.c = list(reversed(self.c))
#
self.reduced = self.h[-1]
# Objective functions
self.meansq = tf.reduce_mean(error_func(self.x-self.g[0]))
self.train_step = tf.train.AdamOptimizer(self.lr).minimize(self.meansq)
#Decoder only
self.y = tf.placeholder("float", [None, self.layers[-1]])
self.decoder_input = self.h[-1]
for i in reversed(range(len(self.layers)-1)):
WiT = tf.transpose(self.W[i])
#
ci = self.c[i]
di = None
if i == len(self.layers)-2:
di = transfer_function(tf.matmul(self.y,WiT) + ci)
elif i==0:
di = tf.matmul(self.d[-1],WiT) + ci
else:
di = transfer_function(tf.matmul(self.d[-1],WiT) + ci)
self.d.append(di)
self.d = list(reversed(self.d))
self.sess = tf.Session()
init = tf.global_variables_initializer()
self.sess.run(init)
def fit(self,X,print_progress=False):
batch_count = math.ceil(len(X)/self.batch_size)
for i in range(self.epoch):
for j in range(batch_count):
#creating batch
start_index = j*self.batch_size
end_index = (j+1)*self.batch_size
batch = X[start_index:end_index]
#train
self.sess.run(self.train_step, feed_dict={self.x: batch})
if print_progress:
print(i,"Error:",self.sess.run(self.meansq, feed_dict={self.x: X}))
return self
def transform(self,X):
return self.sess.run(self.reduced,feed_dict={self.x: X})
def inverse_transform(self,X):
it = self.sess.run(self.d[0],feed_dict={self.y: X})
return it;
def fit_transform(self,X):
self.fit(X)
self.transform(X)
def close(self):
tf.reset_default_graph()
self.sess.close()
def debugPrint(self):
for i, Wi in enumerate(self.W):
print("W"+str(i)+": ", Wi.shape)
print()
for i, bi in enumerate(self.b):
print("b"+str(i)+": ", bi.shape)
print()
for i, hi in enumerate(self.h):
print("h"+str(i)+": ", hi.shape)
print()
for i, ci in enumerate(self.c):
print("c"+str(i)+": ", ci.shape)
print()
for i, gi in enumerate(self.g):
print("g"+str(i)+": ", gi.shape)
print()
def load_autoencoder(model_path):
#Load model arhitecture
location, model_name = os.path.split(model_path)
architecture_path = os.path.join(location,model_name,'architecture.txt')
architecture = None
with open(architecture_path,'r') as architecture_file:
architecture = [int(x.strip()) for x in architecture_file.readlines()]
#Create model
ae = AutoEncoder(architecture)
#Initialize model
model_path = model_path + '.ckpt'
saver = tf.train.Saver()
saver.restore(ae.sess,model_path)
return ae
def main(argv):
#Determine directory
#from config_read import HOME
#model_directory = 'ae'
#dir_path = os.path.join(HOME, model_directory,'test')
#os.makedirs(dir_path, exist_ok=True)
#Program
X = [[1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0]]
ae = AutoEncoder([20,18,14,8,4,2])
ae.fit(X)
#Save model
#save_autoencoder(ae,dir_path+"/model")
#Load model
#ae = load_autoencoder(dir_path+'/2018:04:22_16/model')
r = ae.transform(X)
print(r)
d = ae.inverse_transform(r)
print(d)
ae.sess.close()
if __name__ == '__main__':
main([])
|
import webbrowser
url = 'file:///C:/Users/divyas5/Desktop/Calculater/output.html'
webbrowser.open(url, new=2) # open in new tab
|
import tkinter as tk
import tkinter.filedialog as tkfiledialog
import kodi_baselibrary as kodi
from functools import partial
from threading import Thread
from configparser import ConfigParser
from console import ThreadSafeConsole
from tooltip import Tooltip
from action_loadsharedlanguage import LoadSharedLanguageAction
from action_loadskin import LoadSkinAction
from action_checkloadedskin import CheckLoadedSkinAction
from action_checkskinfiles import CheckSkinFilesAction
from action_checkincludes import CheckIncludesAction
from action_checkfonts import CheckFontsAction
from action_checkvariables import CheckVariablesAction
from action_checkexpressions import CheckExpressionsAction
from action_checkskinsettings import CheckSkinSettingsAction
from action_checksyntax import CheckSyntaxAction
from action_checkmessages import CheckMessagesAction
from action_checkmediafiles import CheckMediaFilesAction
LOADSHAREDLANGUAGEFILE_TOOLTIP = ("Select and load the standard (shared) language file.\n"
+ "This shared language file should contain all the messages that are available in Kodi by default.")
LOADSKINFROMDIRECTORY_TOOLTIP = ("Select the base directory that contains the skin files and load the skin from this directory.\n"
+ "The base directory of the skin is the directory with the skin's addon.xml file.")
RELOADSKIN_TOOLTIP = ("Reload the skin files from the base directory.\n"
+ "The base directory of the skin is the directory with the skin's addon.xml file.")
CLEARMESSAGES_TOOLTIP = "Clear the messages."
CLOSEPROGRAM_TOOLTIP = "Exit this Kodi Skin Tester program."
CONFIGFILENAME = 'kst.ini'
class MainWindow(object):
def __init__(self):
self.config = ConfigParser()
self.window = tk.Tk()
self.sharedlanguagefile = tk.StringVar(self.window)
self.baseskindirectory = tk.StringVar(self.window)
self.loadsharedlanguage_action = LoadSharedLanguageAction()
self.loadskin_action = LoadSkinAction()
self.checkactions = [
CheckLoadedSkinAction(),
CheckSkinFilesAction(),
CheckIncludesAction(),
CheckFontsAction(),
CheckVariablesAction(),
CheckExpressionsAction(),
CheckSkinSettingsAction(),
CheckSyntaxAction(),
CheckMessagesAction(),
CheckMediaFilesAction()
]
self.window.title("Kodi Skin Tester")
self.window.geometry("1200x680");
self.window.resizable(False, False)
self.messages = ThreadSafeConsole(master = self.window, width = 100, height = 24)
self.messages.place(x = 300, y = 120, width = 870, height = 480)
text_scrollbar_x = tk.Scrollbar(master = self.window, orient = "horizontal", command = self.messages.xview)
text_scrollbar_x.place(x = 300, y = 600, width = 870, height = 20)
text_scrollbar_y = tk.Scrollbar(master = self.window, orient = "vertical", command = self.messages.yview)
text_scrollbar_y.place(x = 1170, y = 120, width = 20, height = 480)
self.messages.configure(xscrollcommand = text_scrollbar_x.set)
self.messages.configure(yscrollcommand = text_scrollbar_y.set)
self.addmessage("action", "Starting Kodi Skin Tester...")
self.addmessage("info", "- Made by Malthus (Marijn Hubert) to test the Kodi skin 'Revolve'")
self.addmessage("warning", "- Use this Kodi Skin Tester and its results at your own risk")
self.addmessage("info", "Done")
self.loadconfiguration()
self.sharedlanguagefilelabel = tk.Label(self.window, textvariable = self.sharedlanguagefile, foreground = 'red', anchor = 'w')
self.sharedlanguagefilelabel.place(x = 310, y = 10, width = 590, height = 30)
self.baseskindirectorylabel = tk.Label(self.window, textvariable = self.baseskindirectory, foreground = 'red', anchor = 'w')
self.baseskindirectorylabel.place(x = 310, y = 40, width = 590, height = 30)
self.loadbuttonframe = tk.Frame()
self.loadsharedlanguagebutton = tk.Button(master = self.loadbuttonframe, text = "Load shared language file", command = self.loadsharedlanguagefromselectedfile)
self.loadsharedlanguagebutton.place(x = 0, y = 0, width = 280, height = 30)
tooltip = Tooltip(self.loadsharedlanguagebutton)
self.loadsharedlanguagebutton.bind("<Enter>", partial(tooltip.show, LOADSHAREDLANGUAGEFILE_TOOLTIP))
self.loadsharedlanguagebutton.bind("<Leave>", partial(tooltip.hide))
self.loadskinbutton = tk.Button(master = self.loadbuttonframe, text = "Load skin from folder", command = self.loadskinfromselecteddirectory)
self.loadskinbutton.place(x = 0, y = 30, width = 280, height = 30)
tooltip = Tooltip(self.loadskinbutton)
self.loadskinbutton.bind("<Enter>", partial(tooltip.show, LOADSKINFROMDIRECTORY_TOOLTIP))
self.loadskinbutton.bind("<Leave>", partial(tooltip.hide))
self.reloadskinbutton = tk.Button(master = self.loadbuttonframe, text = "Reload skin files", command = self.reloadskin)
self.reloadskinbutton.place(x = 0, y = 60, width = 280, height = 30)
tooltip = Tooltip(self.reloadskinbutton)
self.reloadskinbutton.bind("<Enter>", partial(tooltip.show, RELOADSKIN_TOOLTIP))
self.reloadskinbutton.bind("<Leave>", partial(tooltip.hide))
self.loadbuttonframe.place(x = 10, y = 10, width = 280, height = 100)
self.checkbuttonframe = tk.Frame()
for index, action in enumerate(self.checkactions):
button = tk.Button(master = self.checkbuttonframe, text = action.getname(), command = partial(self.executecheckaction, action), width = 60, height = 3)
button.place(x = 0, y = 30 * index, width = 280, height = 30)
tooltip = Tooltip(button)
button.bind("<Enter>", partial(tooltip.show, action.description))
button.bind("<Leave>", partial(tooltip.hide))
self.checkbuttonframe.place(x = 10, y = 120, width = 280, height = 300)
self.clearbutton = tk.Button(master = self.window, text = "Clear", command = self.clearmessages)
self.clearbutton.place(x = 900, y = 630, width = 280, height = 40)
tooltip = Tooltip(self.clearbutton)
self.clearbutton.bind("<Enter>", partial(tooltip.show, CLEARMESSAGES_TOOLTIP))
self.clearbutton.bind("<Leave>", partial(tooltip.hide))
self.exitbutton = tk.Button(master = self.window, text = "Close", command = self.exitprogram)
self.exitbutton.place(x = 10, y = 630, width = 280, height = 40)
tooltip = Tooltip(self.exitbutton)
self.exitbutton.bind("<Enter>", partial(tooltip.show, CLOSEPROGRAM_TOOLTIP))
self.exitbutton.bind("<Leave>", partial(tooltip.hide))
self.executeloadaction(self.loadsharedlanguage_action)
self.executeloadaction(self.loadskin_action)
self.window.mainloop()
def loadsharedlanguagefromselectedfile(self):
newlanguagefile = tkfiledialog.askopenfilename()
if newlanguagefile:
self.sharedlanguagefile.set(newlanguagefile)
self.colorsharedlanguagefilelabel()
self.executeloadaction(self.loadsharedlanguage_action)
def loadskinfromselecteddirectory(self):
newskindirectory = tkfiledialog.askdirectory(initialdir = self.baseskindirectory)
if newskindirectory:
self.baseskindirectory.set(newskindirectory)
self.colorbaseskindirectorylabel()
self.executeloadaction(self.loadskin_action)
def reloadskin(self):
self.executeloadaction(self.loadskin_action)
def executeloadaction(self, action):
self.executeaction(action)
if type(action) is LoadSharedLanguageAction:
self.language = action.language
self.colorsharedlanguagefilelabel()
elif type(action) is LoadSkinAction:
self.skin = action.skin
self.colorbaseskindirectorylabel()
self.addmessage("info", "Done")
def executecheckaction(self, action):
self.executeaction(action)
self.addmessage("info", "Done")
def executeaction(self, action):
arguments = self.buildarguments(action)
thread = Thread(target = action.execute, args = [self.addmessage, arguments])
thread.daemon = True
thread.start()
thread.join()
def clearmessages(self):
self.messages.clear()
def exitprogram(self):
self.saveconfiguration()
self.window.destroy()
def addmessage(self, level, text):
self.messages.write(level, text)
def loadconfiguration(self):
self.config.read(CONFIGFILENAME)
self.sharedlanguagefile.set(self.config['DEFAULT']['shared language file'])
self.baseskindirectory.set(self.config['DEFAULT']['base skin directory'])
def saveconfiguration(self):
self.config['DEFAULT']['shared language file'] = self.sharedlanguagefile.get()
self.config['DEFAULT']['base skin directory'] = self.baseskindirectory.get()
with open(CONFIGFILENAME, 'w') as configfile:
self.config.write(configfile)
def buildarguments(self, action):
arguments = {}
for argument in action.arguments:
if argument == 'sharedlanguagefile':
arguments['sharedlanguagefile'] = self.sharedlanguagefile.get()
elif argument == 'skinbasedirectory':
arguments['skinbasedirectory'] = self.baseskindirectory.get()
elif argument == 'skinlanguagedirectory':
arguments['skinlanguagedirectory'] = kodi.LANGUAGE_DIRECTORY
elif argument == 'skin':
arguments['skin'] = self.skin
elif argument == 'sharedlanguage':
arguments['sharedlanguage'] = self.language
return arguments
def colorsharedlanguagefilelabel(self):
color = "blue" if self.language and self.language.languagefile == self.sharedlanguagefile.get() else "red"
self.sharedlanguagefilelabel.configure(foreground = color)
def colorbaseskindirectorylabel(self):
color = "blue" if self.skin and self.skin.basedirectory == self.baseskindirectory.get() else "red"
self.baseskindirectorylabel.configure(foreground = color)
MainWindow()
|
from django.shortcuts import render
from django.shortcuts import render_to_response
from django.http import HttpResponse
from django.template import RequestContext
# Create your views here.
def home(request):
return render_to_response('core/index.html',
context_instance=RequestContext(request))
|
import torch
from scipy.io import loadmat
from torch.utils.data import Dataset
import numpy as np
from numpy import pi
# --- from the original code of the Neural ODE Processes paper
class SineData(Dataset):
"""
Dataset of functions f(x) = a * sin(x - b) where a and b are randomly
sampled. The function is evaluated from -pi to pi.
Parameters
----------
amplitude_range : tuple of float
Defines the range from which the amplitude (i.e. a) of the function
is sampled.
shift_range : tuple of float
Defines the range from which the shift (i.e. b) of the function is
sampled.
num_samples : int
Number of samples of the function contained in dataset.
num_points : int
Number of points at which to evaluate f(x) for x in [-pi, pi].
"""
def __init__(self, amplitude_range=(-1., 1.), shift_range=(-.5, .5),
num_samples=1000, num_points=100):
self.amplitude_range = amplitude_range
self.shift_range = shift_range
self.num_samples = num_samples
self.num_points = num_points
self.x_dim = 1 # x and y dim are fixed for this dataset.
self.y_dim = 1
self.t0 = -3.2
# Generate data
self.data = []
a_min, a_max = amplitude_range
b_min, b_max = shift_range
for i in range(num_samples):
# Sample random amplitude
a = (a_max - a_min) * np.random.rand() + a_min
# Sample random shift
b = (b_max - b_min) * np.random.rand() + b_min
# Shape (num_points, x_dim)
x = torch.linspace(-np.pi, np.pi, num_points).unsqueeze(1)
# Shape (num_points, y_dim)
y = a * torch.sin(x - b)
self.data.append((x, y))
def __getitem__(self, index):
return self.data[index]
def __len__(self):
return self.num_samples
class RotNISTDataset(Dataset):
"""
Loads the rotated 3s from ODE2VAE paper
https://www.dropbox.com/s/aw0rgwb3iwdd1zm/rot-mnist-3s.mat?dl=0
"""
def __init__(self, data_dir):
mat = loadmat(data_dir + '/rot-mnist-3s.mat')
dataset = mat['X'][0]
dataset = dataset.reshape(dataset.shape[0], dataset.shape[1], -1)
self.data = torch.tensor(dataset, dtype=torch.float32)
self.t = (torch.arange(dataset.shape[1], dtype=torch.float32).view(-1, 1) / 10).repeat([dataset.shape[0], 1, 1])
self.data = list(zip(self.t, self.data))
self.t0 = float(self.t.min()) - 0.1
def __getitem__(self, index):
return self.data[index]
def __len__(self):
return len(self.data)
class NoisySineData(Dataset):
"""
Dataset of functions f(x) = sin(w * x - b) + sigma * dB(x) where w and b and
randomly sampled and dB is white noise.
The function is evaluated from -pi to pi.
Parameters
----------
sigma : float
Defines the noise level.
shift_range : tuple of float
Defines the range from which the shift (i.e. b) of the function is
sampled.
freq_range : tuple of float
Defines the range from which the pulsation (i.e. w) of the
function is sampled.
num_samples : int
Number of samples of the function contained in dataset.
num_points : int
Number of points at which to evaluate f(x) for x in [-pi, pi].
"""
def __init__(self, sigma, shift_range=(-.5, .5),
freq_range=(0.3, 2.0), num_samples=1000, num_points=100):
self.shift_range = shift_range
self.num_samples = num_samples
self.num_points = num_points
self.x_dim = 1 # x and y dim are fixed for this dataset.
self.y_dim = 1
self.t0 = -3.2
# Generate data
self.data = []
b_min, b_max = shift_range
w_min, w_max = freq_range
for i in range(num_samples):
# Sample random shift
b = (b_max - b_min) * np.random.rand() + b_min
# Sample random frequency
w = (w_max - w_min) * np.random.rand() + w_min
# Shape (num_points, x_dim)
x = torch.linspace(-pi, pi, num_points).unsqueeze(1)
# Shape (num_points, y_dim)
y = torch.sin(w * x - b) + sigma * torch.randn(x.shape)
self.data.append((x, y))
def __getitem__(self, index):
return self.data[index]
def __len__(self):
return self.num_samples
class FreqSineData(Dataset):
"""
Dataset of functions f(x) = a * sin(w * x - b) where a, b, and w are
randomly sampled. The function is evaluated from -pi to pi.
Parameters
----------
amplitude_range : tuple of float
Defines the range from which the amplitude (i.e. a) of the function
is sampled.
shift_range : tuple of float
Defines the range from which the shift (i.e. b) of the function is
sampled.
freq_range : tuple of float
Defines the range from which the pulsation (i.e. w) of the
function is sampled.
num_samples : int
Number of samples of the function contained in dataset.
num_points : int
Number of points at which to evaluate f(x) for x in [-pi, pi].
"""
def __init__(self,
amplitude_range=(-1., 1.),
shift_range=(-.5, .5),
freq_range=(0.3, 2.0),
num_samples=1000,
num_points=100):
self.amplitude_range = amplitude_range
self.shift_range = shift_range
self.num_samples = num_samples
self.num_points = num_points
self.x_dim = 1 # x and y dim are fixed for this dataset.
self.y_dim = 1
# Generate data
self.data = []
a_min, a_max = amplitude_range
b_min, b_max = shift_range
w_min, w_max = freq_range
for i in range(num_samples):
# Sample random amplitude
a = (a_max - a_min) * np.random.rand() + a_min
# Sample random shift
b = (b_max - b_min) * np.random.rand() + b_min
# Sample random frequency
w = (w_max - w_min) * np.random.rand() + w_min
# Shape (num_points, x_dim)
x = torch.linspace(-pi, pi, num_points).unsqueeze(1)
# Shape (num_points, y_dim)
y = a * torch.sin(w * x - b)
self.data.append((x, y))
def __getitem__(self, index):
return self.data[index]
def __len__(self):
return self.num_samples
|
from django.db import models
# Create your models here.
class Plants(models.Model):
plant_name = models.CharField(max_length=40, unique=True)
origin = models.CharField(max_length=20)
def upload_image(self, filename):
path = 'Nursery/photos/{}'.format(filename)
return path
Image = models.ImageField(upload_to=upload_image, null=False, blank=False)
def __str__(self):
return self.plant_name
# User Many to Many Relationship between Plants and Nursery
class Nursery(models.Model):
name = models.CharField(max_length=40, unique=True)
password = models.CharField(max_length=20, null= False, blank= False,default='password123')
location = models.CharField(max_length=40)
Plant_name = models.ManyToManyField(Plants, through='NurseryPlant')
def __str__(self):
return self.name
class NurseryPlant(models.Model):
nursery_name = models.ForeignKey(Nursery, on_delete=models.CASCADE)
plant_name = models.ForeignKey(Plants, on_delete=models.CASCADE)
price = models.IntegerField(null= False, blank= False)
# User Many to Many Relationship between Plants and User
class Users(models.Model):
first_name = models.CharField(max_length=20, unique=True)
last_name = models.CharField(max_length=20)
password = models.CharField(max_length=20, null= False, blank= False, default='password123')
age = models.IntegerField(default=18)
plant_name = models.ManyToManyField(Plants, through='UserPlant')
def __str__(self):
return "User: {} {}".format(self.first_name, self.last_name)
class UserPlant(models.Model):
user_name = models.ForeignKey(Users, on_delete=models.CASCADE)
nursery_name = models.ForeignKey(Nursery, on_delete=models.CASCADE)
plant_name = models.ForeignKey(Plants, on_delete=models.CASCADE)
|
# Inputs to a state machine
class Input: pass |
class Solution(object):
def largestRectangleArea(self, heights):
"""
:type heights: List[int]
:rtype: int
"""
if not heights:
return 0
sorted_heights = sorted(set(heights))
area = 0
for step in sorted_heights:
l = []
for h in heights:
if h >= step:
l.append(h)
else:
area = max(step * len(l), area)
l = []
area = max(step * len(l), area)
return area
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2018-07-07 21:00:10
# @Author : Your Name (you@example.org)
# @Link : http://example.org
# @Version : $Id$
import os
class Solution:
def findAnagrams(self, s, p):
"""
:type s: str
:type p: str
:rtype: List[int]
"""
S = [ord(x) - 97 for x in s]
P = [ord(x) - 97 for x in p]
f1 = [0] * 26
for x in P:
f1[x] += 1
f2 = [0] * 26
windowLength = len(P)
res = []
for i, x in enumerate(S):
f2[x] += 1
if i >= windowLength: f2[S[i - windowLength]] -= 1
if f1 == f2: res.append(i - windowLength + 1)
return res
if __name__=='__main__':
print(Solution.findAnagrams('', 'cbaebabacd', 'abc')) |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
#from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LinearRegression
from sklearn import metrics
#Input dataset
data = pd.read_csv('Salary_Data.csv')
X = data.iloc[:,:-1].values
y = data.iloc[:,len(X[0])].values
#Splitting the dataset into the Training set and Test set
X_train, X_test, y_train, y_test = train_test_split(X,y,test_size=1/3,random_state=42)
'''
#Feature Scaling
sc_X = StandardScaler()
X_train = sc_X.fit_transform(X_train)
X_test = sc_X.transform(X_test)
'''
lr = LinearRegression()
lr.fit(X_train,y_train)
predict = lr.predict(X_test)
'''
plt.scatter(X_train,y_train, color='r',s=10, label='Salary real')
plt.plot(X_train,lr.predict(X_train), color='b',label='Regression')
plt.title('Salary vs Experience (Training set)')
'''
plt.title('Salary vs Experience (Test set)')
plt.scatter(X_test,y_test, color='r',s=10, label='Salary real')
plt.plot(X_train,lr.predict(X_train), color='c',label='Regression')
plt.xlabel('Experience')
plt.ylabel('Salary')
plt.legend()
plt.show()
|
# -*- coding: utf-8 -*-
"""
Created on Sun Mar 31 04:57:58 2019
@author: ankita1999
"""
from flask import Flask, redirect, url_for, request, render_template
import pview as ts
from SaveLoad import Doctor,Patient,Booking
p_user_id="nul"
app = Flask(__name__,static_url_path='/static')
@app.route('/dr_signup',methods=['POST', 'GET'])
def dr_signup():
input_list=request.form.items()
userid=input_list[0][1]
name=input_list[4][1]
specialization=input_list[3][1]
free_time=input_list[2][1]
password=input_list[1][1]
d=Doctor(userid, password,name,specialization,free_time,None)
d.save_to_db()
return render_template('new.html')
@app.route('/p_signup',methods=['POST', 'GET'])
def p_signup():
input_list=request.form.items()
userid=input_list[0][1]
name=input_list[1][1]
ph=input_list[2][1]
password=input_list[3][1]
d=Patient(userid, password,name,ph,None)
d.save_to_db()
return render_template('new.html')
@app.route('/signup',methods = ['POST', 'GET'])
def signup():
input_list=request.form.items()
btn=input_list[0][0]
if(btn=='dr_signup'):
return render_template('doctor.html')
if(btn=='p_signup'):
return render_template('patient.html')
@app.route('/login',methods = ['POST', 'GET'])
def login():
global p_user_id
#Login For Doctor:
input_list=request.form.items()
cat_id=input_list[0][0]
if(cat_id =='d_id'):
user_id=input_list[0][1]
e_pass=input_list[-1][-1]
user_details=Doctor.load_from_db_by_userid(user_id)
o_pass=user_details.password
if(e_pass==o_pass):
b_details=Booking.load_from_db_by_userid(str(user_details.id))
disp_list=[]
for b in b_details:
list1=[]
p_data=Patient.load_from_db_by_id(int(b[1]))
list1.append(p_data.name)
list1.append(p_data.ph)
list1.append(b[-1])
disp_list.append(list1)
print(disp_list)
return render_template('doc.html',result=disp_list,name=user_details.name)
return "Wrong Password"
#Login For Patient:
else:
user_id=input_list[0][1]
p_user_id=user_id
print(p_user_id)
e_pass=input_list[-1][-1]
user_details=Patient.load_from_db_by_userid(user_id)
o_pass=user_details.password
if(e_pass==o_pass):
return render_template('pat.html',result = ts.final_list)
return "Wrong Password"
@app.route('/', methods=['GET', 'POST'])
def doc1():
return render_template('new.html')
if __name__ == '__main__':
app.run()
|
N = int(input())
for i in range(N, 1, -1):
print(" "*(N-i)+"*"*(2*i-1))
print(" "*(N-1) + "*")
for i in range(1, N):
print(" "*(N-i-1)+"*"*(2*i+1))
|
import os
from PIL import Image
import numpy as np
from django.conf import settings
from .utils.utils import get_rois_from_markers, get_images_from_tif
from .utils.roi import ROIEncoder
from .classicImageProcessor import ClassicImageProcessor
def main(input_file_path):
fullfilename = os.path.basename(input_file_path)
filename, ext = os.path.splitext(fullfilename)
if ext == '.tif':
images = get_images_from_tif(input_file_path)
else:
return None
processor = ClassicImageProcessor()
markers_list = processor.predict(images)
rois = []
for k, markers in enumerate(markers_list):
rois += get_rois_from_markers(markers, k+1)
encoder = ROIEncoder()
output_file_path = "{}_rois.zip".format(filename)
abs_path = os.path.join(settings.MEDIA_ROOT, 'output', output_file_path)
encoder.write_zip(abs_path, rois)
return output_file_path |
class Problem List
pass
'''
1) when creating new user through httpie, password isnt hashed
2) is there any harm in returning hashed password (ie if another user pulls that data)
3) need to make sure created events are in userevents and get into timeline
4) permissions throughout
5) subprofiles
6) facebook login
7) need to create a user event immediatly when a craeted event is made
8) currently can not put or patch userevent or createdUserEvent
Other
on app need to be able to delete UserCreatedEvent
''' |
from pathlib import Path
DATA_DIR = Path(__file__).parent.parent / "challenges" / "data"
def _get_file_file(day: int, part_two: bool = False):
return DATA_DIR / f"day{day:02}{'-part2' if part_two else ''}"
def get_input(day, part_two=False):
_file = _get_file_file(day, part_two)
return [int(s) for s in _file.open().readlines()]
def get_number_sequence(day, part_two=False):
_file = _get_file_file(day, part_two)
return [int(i) for i in _file.open().readline().split(",")]
|
from mtcnn.mtcnn import MTCNN
import cv2
from PIL import Image
import math
from crop_use_opencv import crop_use_opencv
def load_mtcnn_data(filepath):
img = cv2.cvtColor(cv2.imread(filepath), cv2.COLOR_BGR2RGB)
detector = MTCNN()
result = detector.detect_faces(img)
left_eye = result[0]['keypoints']['left_eye']
right_eye = result[0]['keypoints']['right_eye']
nose_tip = result[0]['keypoints']['nose']
face_rectangle = {'left': result[0]['box'][0],
'top': result[0]['box'][1],
'width': result[0]['box'][2],
'height': result[0]['box'][3]}
center_coor = [face_rectangle['left'] + face_rectangle['width'] / 2,
face_rectangle['top'] + face_rectangle['height'] / 2]
face_area = face_rectangle['width'] * face_rectangle['height']
img = Image.fromarray(img)
image_width, image_height = img.size
image_area = image_width * image_height
return img, left_eye, right_eye, center_coor, face_area, image_area
def resize(filepath):
image, left_eye, right_eye, center_coor, face_area, image_area = load_mtcnn_data(filepath)
# center_coor = [((left_eye[0] + right_eye[0]) / 2 + nose_tip[0]) / 2,
# ((left_eye[1] + right_eye[1]) / 2 + nose_tip[1]) / 2]
# print(face_area, image_area)
if image_area / face_area > 3.3:
resize_area = face_area * 3.3
width = math.sqrt(resize_area / 1.4)
height = width * 1.4
print(width, height)
coor1 = [int(center_coor[0] - width / 2), int(center_coor[1] - height / 2)]
coor2 = [int(center_coor[0] + width / 2), int(center_coor[1] + height / 2)]
coor = coor1 + coor2
# 防止溢出
for i in range(len(coor)):
if coor[i] < 0:
coor[i] = 0
if coor[2] > image.size[0]:
coor[2] = image.size[0]
if coor[3] > image.size[1]:
coor[3] = image.size[1]
print(image.size, coor)
image2 = image.crop(coor)
else:
image2 = image
# image2 = crop_use_opencv(image2)
return image2
if __name__ == '__main__':
for i in range(2, 16):
filepath = 'data/data_test/' + str(i) + '.png-photo0.png'
image2 = resize(filepath)
# image2.show()
image2.save(filepath)
|
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
tips=sns.load_dataset('tips')#don't requred path
#visualization of univariate
#strip plot used for univatiet
sns.stripplot(y='tip',data=tips)
plt.ylabel('tip($)')
plt.show()
#grouping with striplpot
sns.stripplot(x='day', y='tip', data=tips)
plt.xlabel('Day')
plt.ylabel('tip($)')
plt.show()
sns.stripplot(x='day', y='tip', data=tips, size=10)
plt.xlabel('Day')
plt.ylabel('tip($)')
plt.show()
|
from clases.leon import Leon
from clases.oso import Oso
from clases.tigre import Tigre
jack = Leon("jack",12,"Ruge",10,10)
negro = Tigre("Negro",6,"Ruge",10,10)
blanco = Oso("Negro",6,"Gruñe",10,10)
jack.Alimentacion(60)
negro.Alimentacion(30)
blanco.Alimentacion(50)
print(jack)
print(negro)
print(blanco) |
#!/usr/bin/python3
#List note :list have many built-in functions
def sl(x):
print(x)
list = [2,3,8,3,5+7j]
ll = ["Bob","Alice","Kili","Job"]
print (list)
print (list[2])
print (list[2:4])
print (list*2)
list[1]="3str"
print (list[-1])
list.append("my")
sl(list)
list.insert(0,12)
list.remove(3)
sl(list)
sl(list.index(8))
sl(list.count(3))
ll.sort();
sl(ll)
|
import time
# import ACS__POA
# from ACS import CBDescIn
from Acspy.Clients.SimpleClient import PySimpleClient
import random
from utils import HMILog
import threading
# acs client
client = PySimpleClient()
# get the components
t1_double = client.getComponent("TEST_JAVA_T1")
t2_double = client.getComponent("TEST_JAVA_T2")
class SimComp:
def __init__(self, site_type):
self.log = HMILog(title=__name__)
self.log.info([['y', " - SimComp - "], ['g', site_type]])
t = threading.Thread(target=self.sim_loop)
# set the thread to daemon for quicker termination
t.daemon = True
t.start()
return
def sim_loop(self):
"""
changes the values on the properties every second
"""
while True:
# every second set a random value on the property
t1_double.doubleRWProp.set_sync(random.random())
t2_double.doubleRWProp.set_sync(random.random())
time.sleep(1)
|
import datetime
from werkzeug.exceptions import BadRequest
import pytz
import uuid
from threading import Lock
from dateutil.relativedelta import relativedelta
from RepetitionInterval import RepetitionIntervalClass
class jobFactoryClass():
def loadFromDB(self, jobFromDBTuple, appObj):
jobFromDB = jobFromDBTuple[0]
repetitionInterval = jobFromDB["repetitionInterval"]
return jobClass(
appObj = appObj,
name = jobFromDB["name"],
command = jobFromDB["command"],
enabled = jobFromDB["enabled"],
repetitionInterval = repetitionInterval,
pinned = jobFromDB["pinned"],
overrideMinutesBeforeMostRecentCompletionStatusBecomesUnknown = jobFromDB["overrideMinutesBeforeMostRecentCompletionStatusBecomesUnknown"],
StateChangeSuccessJobGUID = jobFromDB["StateChangeSuccessJobGUID"],
StateChangeFailJobGUID = jobFromDB["StateChangeUnknownJobGUID"],
StateChangeUnknownJobGUID = jobFromDB["StateChangeUnknownJobGUID"],
guid = jobFromDB["guid"],
loadingObjectVersion = jobFromDBTuple[1]
)
jobFactory = jobFactoryClass()
#Class to represent a job
class jobClass():
guid = None
name = None
command = None
enabled = None
repetitionInterval = None
creationDate = None
lastUpdateDate = None
lastRunDate = None
nextScheduledRun = None
lastRunReturnCode = None
lastRunExecutionGUID = None
pinned = False
overrideMinutesBeforeMostRecentCompletionStatusBecomesUnknown = None
mostRecentCompletionStatus = 'Unknown'
resetCompletionStatusToUnknownTime = None
StateChangeSuccessJobGUID = None
StateChangeFailJobGUID = None
StateChangeUnknownJobGUID = None
CompletionstatusLock = None
objectVersion = None
def __repr__(self):
ret = 'jobClass('
ret += 'guid:' + self.guid + ' '
ret += 'name:' + self.name + ' '
ret += 'command:' + self.command + ' '
ret += 'enabled:' + str(self.enabled) + ' '
ret += 'repetitionInterval:' + self.repetitionInterval + ' '
ret += 'creationDate:' + str(self.creationDate) + ' '
ret += 'lastRunReturnCode:' + str(self.lastRunReturnCode) + ' '
ret += 'lastRunExecutionGUID:' + str(self.lastRunExecutionGUID) + ' '
ret += ')'
return ret
def assertValidName(name):
if (len(name)<2):
raise BadRequest('Job name must be more than 2 characters')
def assertValidRepetitionInterval(ri, enabled):
if ri is None:
ri = ''
if ri == '':
if enabled:
raise BadRequest('Repetition interval not set but enabled is true')
return None
try:
return RepetitionIntervalClass(ri)
except:
raise BadRequest('Invalid Repetition Interval')
def setNewRepetitionInterval(self, newRepetitionInterval):
self.repetitionInterval = newRepetitionInterval
if (self.repetitionInterval != None):
if (self.repetitionInterval != ''):
ri = RepetitionIntervalClass(self.repetitionInterval)
self.repetitionInterval = ri.__str__()
def verifyJobGUID(self, appObj, jobGUID, callingJobGUID):
if jobGUID is None:
return None
if jobGUID == '':
return None
if callingJobGUID == jobGUID:
raise BadRequest('A follow on action can not be set to the same job')
unused = appObj.appData['jobsData'].getJob(jobGUID) #Will throw bad request exception if job dosen't exist
return jobGUID
def __init__(
self,
appObj,
name,
command,
enabled,
repetitionInterval,
pinned,
overrideMinutesBeforeMostRecentCompletionStatusBecomesUnknown,
StateChangeSuccessJobGUID,
StateChangeFailJobGUID,
StateChangeUnknownJobGUID,
guid=None, #used when loading from DB
verifyDependentJobGuids=True, #False when testing
loadingObjectVersion=None #used when loading from DB
):
jobClass.assertValidName(name)
jobClass.assertValidRepetitionInterval(repetitionInterval, enabled)
curTime = datetime.datetime.now(pytz.timezone("UTC"))
if guid is None:
self.guid = str(uuid.uuid4())
else:
self.guid = guid
self.name = name
self.command = command
self.enabled = enabled
self.setNewRepetitionInterval(repetitionInterval)
self.creationDate = curTime.isoformat()
self.lastUpdateDate = curTime.isoformat()
self.lastRunDate = None
self.lastRunExecutionGUID = ''
self.lastRunReturnCode = None
self.nextScheduledRun = None
self.setNextScheduledRun(datetime.datetime.now(pytz.timezone("UTC")))
self.pinned = pinned
if overrideMinutesBeforeMostRecentCompletionStatusBecomesUnknown == 0:
overrideMinutesBeforeMostRecentCompletionStatusBecomesUnknown = None
self.overrideMinutesBeforeMostRecentCompletionStatusBecomesUnknown = overrideMinutesBeforeMostRecentCompletionStatusBecomesUnknown
self.mostRecentCompletionStatus = 'Unknown'
if verifyDependentJobGuids:
self.StateChangeSuccessJobGUID = self.verifyJobGUID(appObj, StateChangeSuccessJobGUID, self.guid)
self.StateChangeFailJobGUID = self.verifyJobGUID(appObj, StateChangeFailJobGUID, self.guid)
self.StateChangeUnknownJobGUID = self.verifyJobGUID(appObj, StateChangeUnknownJobGUID, self.guid)
else:
self.StateChangeSuccessJobGUID = StateChangeSuccessJobGUID
self.StateChangeFailJobGUID = StateChangeFailJobGUID
self.StateChangeUnknownJobGUID = StateChangeUnknownJobGUID
#fields excluded from JSON output
self.resetCompletionStatusToUnknownTime = None
self.CompletionstatusLock = Lock()
self.objectVersion = loadingObjectVersion
def _getMinutesBeforeMostRecentCompletionStatusBecomesUnknown(self, appObj):
if self.overrideMinutesBeforeMostRecentCompletionStatusBecomesUnknown == None:
return appObj.minutesBeforeMostRecentCompletionStatusBecomesUnknown
return self.overrideMinutesBeforeMostRecentCompletionStatusBecomesUnknown
def _getCaculatedValueForModeRecentCompletionStatus(self, appObj, lastRunDate, lastRunReturnCode):
if lastRunDate is None:
return "Unknown"
earlyTime = appObj.getCurDateTime() - relativedelta(minutes=self._getMinutesBeforeMostRecentCompletionStatusBecomesUnknown(appObj))
if lastRunDate < earlyTime:
return "Unknown"
if lastRunReturnCode==0:
return "Success"
else:
return "Fail"
def _caculatedDictWithoutAppObjDependancy(self):
ret = dict(self.__dict__)
del ret['CompletionstatusLock']
del ret['resetCompletionStatusToUnknownTime']
if self.lastRunDate is not None:
ret['lastRunDate'] = self.lastRunDate.isoformat()
# If there is no state change job set the value returned should be null
ret['StateChangeSuccessJobNAME'] = None
ret['StateChangeFailJobNAME'] = None
ret['StateChangeUnknownJobNAME'] = None
return ret
# Needed when we use extra caculated values in the dict
def _caculatedDict(self, appObj):
ret = self._caculatedDictWithoutAppObjDependancy()
if self.StateChangeSuccessJobGUID is not None:
ret['StateChangeSuccessJobNAME'] = appObj.appData['jobsData'].getJob(self.StateChangeSuccessJobGUID).name
if self.StateChangeFailJobGUID is not None:
ret['StateChangeFailJobNAME'] = appObj.appData['jobsData'].getJob(self.StateChangeFailJobGUID).name
if self.StateChangeUnknownJobGUID is not None:
ret['StateChangeUnknownJobNAME'] = appObj.appData['jobsData'].getJob(self.StateChangeUnknownJobGUID).name
return ret
def setNewValues(
self,
appObj,
name,
command,
enabled,
repetitionInterval,
pinned,
overrideMinutesBeforeMostRecentCompletionStatusBecomesUnknown,
StateChangeSuccessJobGUID,
StateChangeFailJobGUID,
StateChangeUnknownJobGUID
):
self.name = name
self.command = command
self.enabled = enabled
self.setNewRepetitionInterval(repetitionInterval)
self.setNextScheduledRun(datetime.datetime.now(pytz.timezone("UTC")))
self.pinned = pinned
if overrideMinutesBeforeMostRecentCompletionStatusBecomesUnknown==0:
overrideMinutesBeforeMostRecentCompletionStatusBecomesUnknown = None
self.overrideMinutesBeforeMostRecentCompletionStatusBecomesUnknown = overrideMinutesBeforeMostRecentCompletionStatusBecomesUnknown
self.StateChangeSuccessJobGUID = self.verifyJobGUID(appObj, StateChangeSuccessJobGUID, self.guid)
self.StateChangeFailJobGUID = self.verifyJobGUID(appObj, StateChangeFailJobGUID, self.guid)
self.StateChangeUnknownJobGUID = self.verifyJobGUID(appObj, StateChangeUnknownJobGUID, self.guid)
def removeRemoveRelianceOnOtherJob(self, guid):
# return True if a change is made
changed = False
if self.StateChangeSuccessJobGUID == guid:
self.StateChangeSuccessJobGUID = None
changed = True
if self.StateChangeFailJobGUID == guid:
self.StateChangeFailJobGUID = None
changed = True
if self.StateChangeUnknownJobGUID == guid:
self.StateChangeUnknownJobGUID = None
changed = True
return changed
def setNextScheduledRun(self, curTime):
ri = None
if self.enabled == False:
self.nextScheduledRun = None
else:
if (self.repetitionInterval != None):
if (self.repetitionInterval != ''):
ri = RepetitionIntervalClass(self.repetitionInterval)
self.nextScheduledRun = ri.getNextOccuranceDatetime(curTime).isoformat()
def uniqueJobNameStatic(name):
return name.strip().upper()
def uniqueName(self):
return jobClass.uniqueJobNameStatic(self.name)
#Called from job execution thread and request processing threads
def _setNewCompletionStatus(self, appObj, newStatus, triggerExecutionObj):
if self.mostRecentCompletionStatus == newStatus:
return
self.CompletionstatusLock.acquire()
self.mostRecentCompletionStatus = newStatus
self.CompletionstatusLock.release()
if newStatus=='Success':
if self.StateChangeSuccessJobGUID is not None:
appObj.jobExecutor.submitJobForExecution(
self.StateChangeSuccessJobGUID,
executionName='Event - StateChangeToSuccess',
manual=False,
triggerJobObj=self,
triggerEvent = 'StateChangeToSuccess',
callerHasJobExecutionLock=True,
triggerExecutionObj=triggerExecutionObj
)
elif newStatus=='Fail':
if self.StateChangeFailJobGUID is not None:
appObj.jobExecutor.submitJobForExecution(
self.StateChangeFailJobGUID,
executionName='Event - StateChangeToFail',
manual=False,
triggerJobObj=self,
triggerEvent = 'StateChangeToFail',
callerHasJobExecutionLock=True,
triggerExecutionObj=triggerExecutionObj
)
else:
if self.StateChangeUnknownJobGUID is not None:
appObj.jobExecutor.submitJobForExecution(
self.StateChangeUnknownJobGUID,
executionName='Event - StateChangeToUnknown',
manual=False,
triggerJobObj=self,
triggerEvent = 'StateChangeToUnknown',
callerHasJobExecutionLock=True,
triggerExecutionObj=triggerExecutionObj #Always None in the unknown case
)
def registerRunDetails(self, appObj, newLastRunDate, newLastRunReturnCode, triggerExecutionObj):
#print('registerRunDetails for job ' + self.name + ' - lastrundate=' + newLastRunDate.isoformat())
self.lastRunDate = newLastRunDate
self.lastRunReturnCode = newLastRunReturnCode
self.lastRunExecutionGUID = triggerExecutionObj.guid
self.resetCompletionStatusToUnknownTime = newLastRunDate + relativedelta(minutes=self._getMinutesBeforeMostRecentCompletionStatusBecomesUnknown(appObj))
newCompletionStatus = self._getCaculatedValueForModeRecentCompletionStatus(appObj, lastRunDate=newLastRunDate, lastRunReturnCode=newLastRunReturnCode)
self._setNewCompletionStatus(
appObj=appObj,
newStatus=newCompletionStatus,
triggerExecutionObj=triggerExecutionObj
)
#In the loop each job needs to check if its status needs to become unknown
# this is required because the job may need to emit an event as a result
# This is called from the job execution thread
def loopIteration(self, appObj, curTime):
if self.mostRecentCompletionStatus == 'Unknown':
return
if curTime > self.resetCompletionStatusToUnknownTime:
self._setNewCompletionStatus(
appObj=appObj,
newStatus='Unknown',
triggerExecutionObj=None
)
|
'''
1번 코드 : 시간초과
def fun(endTime) :
latest = 0
maxNum = 0
for i in range(cnt) :
if arr[i][0] >= endTime :
latest += 1
if arr[i][2] != -1:
temp1 = arr[i][2]
if maxNum < temp1 :
maxNum = temp1
else :
temp2 = fun(arr[i][1])
if maxNum < temp2 :
maxNum = temp2
if arr[i][2] < temp2:
arr[i][2] = temp2
if latest == 0 :
return 0
return maxNum + 1
cnt = int(input())
result = 0
arr = [list(map(int, input().split())) for _ in range(cnt)]
for i in range(cnt) :
arr[i].append(-1)
for i in range(cnt) :
if arr[i][2] != -1 :
tmp = arr[i][2]
if result < tmp:
result = tmp
else :
tmp = fun(arr[i][0])
if result < tmp:
result = tmp
print(result)
'''
'''
2번코드 : 시간초과
endTime = 0
number = 0
meeting = 0
cnt = int(input())
arr = [list(map(int, input().split())) for _ in range(cnt)]
while True :
loopCnt = 0
nextConf = 0
for i in range(0, cnt):
if arr[i][0] > endTime and arr[i][1] == number:
nextConf += 1
endTime = number
meeting += 1
break
elif arr[i][0] > endTime :
loopCnt += 1
if loopCnt == 0 and nextConf == 0:
break
else :
number += 1
print(meeting)
'''
'''
3번 코드 : 맞았습니다.
원리 : 시작시간을 먼저 오름차순 정렬, 그 후에 끝나는 시간을 오름차순 정렬하고, 끝나는 시간을 기준으로 빨리 끝나는 회의만
고르면 하나의 회의실을 최대한 많이 사용할 수 있다.
for문을 두번 돌려서 0번째 열과 1번째 열(각각 시작시간, 끝나는시간)을 퀵 솔트로 정렬하고,
회의 시작시간이 endTime보다 클 경우, 카운트를 하면서 endTime에 선택된 회의의 끝시간을 새로 집어넣는다.
그렇게 for문을 테스트 케이스 만큼 다 돌리면 최대한의 회의실 이용 횟수가 나온다(= metting)
퀵 정렬의 규칙 : 피봇을 임의로 정해서 피봇을 기준으로 왼쪽에는 피봇보다 작은값, 오른쪽에는 피봇보다 큰 값으로 정렬한다.
더이상 바꿀게 없을 경우 왼쪽배열과 오른쪽 배열을 다시 퀵 정렬로 돌린다.
1. 피봇을 배열의 첫번째 값으로 잡을 경우, 완전히 정렬되어 있는 배열에서 시간복잡도의 상승으로 최악이다. 그래서 중간값 퀵정렬을 사용한다.
2. 중간값 퀵정렬은 배열의 가장 첫번째 값, 중간값, 마지막 값을 먼저 비교해서 정렬한다 -> setPivot 함수
그러면 첫번째 값 < 중간값 < 마지막값 순서로 정렬이 된다.
3. 중간값을 피봇으로 삼고, 제일 끝에서 한칸 전으로 옮긴다.(마지막 칸이 아닌 이유는 2번 과정에서 이미 마지막칸은 피봇보다 큰 값이
들어가 있으므로 정렬에 넣을 필요가 없다.
4. i도 마찬가지로 맨 앞에 칸은 이미 피봇보다 작으므로 0번째가 아닌 +1 번째 부터 비교하면서 올라가고 j는 피봇부터 비교하면서 내려온다.
5. i가 j보다 작은 상태이면 i와 j를 swap, i가 j보다 크면 while 문을 탈출한다. 그러고 만약 i가 피봇보다 큰쪽에 있게 된다면,
피봇 앞에 다 작은 값이 놓여져있는것이므로 3번 과정에서 바꾸었던 것을 원위치 시키고 함수를 종료시킨다
6. 만약 i가 j보다 크지만 피봇보다는 앞에 있는 위치라면, i와 피봇을 바꾸고 while문을 탈출한다. 그다음 i를 기준으로 왼쪽배열,
오른쪽 배열로 나눈 뒤에 각각 다시 퀵정렬 함수로 정렬한다. 이때 범위는 start < i - 1 과 i + 1 < end 가 된다.
7. 소트 함수 앞부분에는 end - start < 3 이하일때 함수를 종료하는 문 이 있는데, 이것은 배열의 크기가 3이하면, setPivot 함수에서
맨 앞, 중간, 끝을 정렬해버리는 순간 더이상 피봇을 이용한 정렬이 필요가 없기 때문에, 종료시킨다.
'''
from sys import stdin
def setPivot(start, mid, end, index) :
if arr[mid][index] < arr[start][index] :
swap(mid, start)
if arr[mid][index] > arr[end][index] :
swap(mid, end)
if arr[mid][index] < arr[start][index] :
swap(mid, start)
def swap(a, b) :
temp1 = arr[b][0]
temp2 = arr[b][1]
arr[b][0] = arr[a][0]
arr[b][1] = arr[a][1]
arr[a][0] = temp1
arr[a][1] = temp2
def quickSort(start, end, index) :
mid = ((end - start) // 2) + start
setPivot(start, mid, end, index)
if end - start < 3 :
return
swap(mid, end - 1)
pivot = end - 1
i = start + 1
j = end - 1
while i < j :
while i < end and arr[i][index] <= arr[pivot][index] :
i += 1
while j > start and arr[j][index] >= arr[pivot][index] :
j -= 1
if i < j :
swap(i, j)
if i > pivot:
swap(mid, pivot)
quickSort(start, i - 1, index)
return
swap(i, pivot)
quickSort(start, i - 1, index)
quickSort(i + 1, end, index)
cnt = int(stdin.readline())
arr = [list(map(int, stdin.readline().split())) for _ in range(cnt)]
endTime = 0
meeting = 0
for index in range(0, 2) :
quickSort(0, cnt-1, index)
for i in range(0, cnt) :
if arr[i][0] >= endTime :
meeting += 1
endTime = arr[i][1]
print(meeting)
|
"""Test Rot13 module."""
import pytest
from Rot13 import rot13
def test_rot13():
assert rot13("I am, BaTman ") == "V nz, OnGzna "
# def test_rot13():
# assert rot13("I am, BaTman ") == V nz, OnGzna "
# Enter Code:I am, BaTman
# Out[12]: 'V nz, OnGzna ' |
# Generated by Django 3.1.3 on 2021-08-08 09:01
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('blog', '0007_likedblogs'),
]
operations = [
migrations.AlterModelOptions(
name='likedblogs',
options={'verbose_name_plural': 'Liked Blogs'},
),
]
|
#!/usr/bin/python3
"""PYTHON OBJECT RELATIONAL MAPPING MODULE"""
import MySQLdb
from sys import argv
def my_safe_filter_states():
"""
Takes in an argument and displays all values in the states table of the
database where name matches the argument. Is safe from MySQL injections!
Recieves 4 arguments: mysql username, mysql password, database name and
state name searched.
"""
conn = MySQLdb.connect(host="localhost", port=3306,
user=argv[1], passwd=argv[2], db=argv[3],
charset="utf8")
cur = conn.cursor()
str1 = "SELECT * FROM states WHERE name LIKE"
str2 = "ORDER BY id ASC"
cur.execute("{} %s {}".format(str1, str2), (argv[4], ))
query_rows = cur.fetchall()
for row in query_rows:
print(row)
cur.close()
conn.close()
if __name__ == "__main__":
my_safe_filter_states()
|
from About.models import AuthorPeronal,CvUpload
def Author(request):
try:
authorPeronal = AuthorPeronal.objects.get(FullName='Md Mahiuddin')
return {'authorPeronal':authorPeronal}
except Exception:
authorPeronal = ''
return {'authorPeronal':authorPeronal}
def Cv(request):
try:
cv = CvUpload.objects.get(name='Md Mahiuddin')
return {'cv':cv}
except Exception:
cv = ''
return {'cv':cv} |
import copy
import random
# Consider using the modules imported above.
class Hat:
def __init__(self, **kwargs):
self.contents_dict = kwargs
self.contents = []
# create contents list
for colour, amount in self.contents_dict.items():
for i in range (amount):
self.contents.append(colour)
def draw(self, num_balls):
drawn_bag = []
for i in range(num_balls):
j = random.randint(0,len(self.contents)-1)
drawn_bag.append(self.contents.pop(j))
if len(self.contents) == 0:
return drawn_bag
return drawn_bag
def experiment(hat, expected_balls, num_balls_drawn, num_experiments):
cum_draw = {}
for x in expected_balls:
cum_draw[x]=0
m = 0
for n in range (num_experiments):
cum_draw = {}
draw_count = 0
for x in expected_balls:
cum_draw[x]=0
hat_copy = copy.deepcopy(hat)
drawn = hat_copy.draw (num_balls_drawn)
for x in expected_balls:
for i in drawn:
if i == x:
cum_draw[x] += 1
if cum_draw[x] >= expected_balls[x]:
draw_count += 1
if draw_count == len(expected_balls):
m += 1
return m/num_experiments
|
from matplotlib import pyplot as plt
import numpy as np
import random
def generateData(num_points=30):
data = np.concatenate((np.random.normal(loc=1.0, scale=1.0, size=[num_points, 2]) , np.random.normal(loc=5.0, scale=1.0, size=[num_points, 2])))
plt.plot(data[:, 0], data[:, 1], 'o')
# plt.show()
return data
def loadData(data_path = './test1_data.txt', tag_path = './test1_ground.txt'):
contain = open(data_path, 'r').readlines()
data = np.ndarray([2, len(contain)])
for i in range(len(contain)):
data[0][i] = float(contain[i].split(' ')[0])
data[1][i] = float(contain[i].split(' ')[1])
contain = open(tag_path, 'r').readlines()
contain = [int(num[:-1]) for num in contain]
tag = np.zeros([max(contain) + 1, len(contain)])
for i in range(len(contain)):
tag[contain[i]][i] = 1
return data, tag
def equal(arr1, arr2):
len1, len2 = np.shape(arr1)
for i in range(len1):
for j in range(len2):
if arr1[i][j] != arr2[i][j]:
return False
return True
def kernel(a, b, gemma=0.0001):
result = np.exp(-gemma * np.sum(np.square(a - b), axis=0))
if len(np.shape(result)) < 1:
return np.expand_dims(result, axis=0)
return result
def argmax_Second(arr):
idx_1st = np.argmin(arr)
val_1st = np.min(arr)
for i in range(len(arr)):
if arr[i] > val_1st:
val_1st = arr[i]
idx_1st = i
idx_2nd = np.argmin(arr)
val_2nd = np.min(arr)
for i in range(len(arr)):
if arr[i] > val_2nd and arr[i] < val_1st:
val_2nd = arr[i]
idx_2nd = i
return idx_2nd
def exist(pos, _list):
for i in range(len(_list)):
repeated = True
for j in range(np.shape(pos)[0]):
if pos[j] != _list[i][j]:
repeated = False
if repeated:
return True
return False |
# coding:utf-8
from __future__ import absolute_import, unicode_literals
from .base import BasePipeLine
__author__ = "golden"
__date__ = '2018/5/29'
class ConsolePipeLine(BasePipeLine):
async def process_item(self, item):
self.logger.info(item)
|
from django.shortcuts import render,HttpResponse,reverse, redirect
from .forms import IoTForm
from .models import IoT
from django.http import JsonResponse
from django.core.serializers import serialize
#Create a new IoT
def create_iot(request):
context = {}
if request.method == "POST":
serial_no = request.POST.get('serial_no')
plate_no = request.POST.get('plate_no')
is_active = str(False)
if len(plate_no) > 0:
is_active = str(True)
iot = IoT.objects.create(serial_no=serial_no, plate_no=plate_no, is_active=is_active)
context.setdefault('message_type',1)
context.setdefault('message_title','BİLGİLENDİRME!')
context.setdefault('message_content','Yeni Cihaz Başarıyla Eklendi.')
form = IoTForm()
context.setdefault('form',form)
return render(request, 'iot/iot_create.html', context)
#Returns a data table
def iot_list(request):
return render(request,'iot/iot_list.html',{})
def update(request, serial_no):
iot = IoT.objects.get(serial_no=serial_no)
if request.method == 'POST':
plate_no = request.POST.get('plate_no')
if plate_no is not iot.plate_no:
iot.plate_no = plate_no
iot.is_active = True if len(plate_no) > 0 else False
iot.save()
return redirect('iot:iot_list')
form = IoTForm(instance=iot)
return render(request, 'iot/iot_update.html', {'form':form, 'serial_no':serial_no})
def delete(request, serial_no):
iot = IoT.objects.get(serial_no=serial_no)
if request.method == 'POST':
iot.delete()
return redirect('iot:iot_list')
else:
labels = ['Seri No:','Plaka No:']
values= [iot.serial_no, iot.plate_no]
context = {
'labels': labels,
'values': values,
'serial_no': iot.serial_no
}
if iot is not None:
return render(request,'iot/iot_delete.html',context=context)
#AJAX
#Validation
def validate_serial_no(request):
serial_no = request.POST.get('serial_no', None)
data = {
'is_taken': IoT.objects.filter(serial_no__iexact=serial_no).exists()
}
if data['is_taken']:
data['error_message'] = 'Bu seri numaraya kayıtlı cihaz bulunmaktadır. Lütfen başka bir tane giriniz.'
return JsonResponse(data)
def validate_plate_no(request):
plate_no = request.POST.get('plate_no', None)
data = {
'is_taken': IoT.objects.filter(plate_no__iexact=plate_no).exists()
}
if request.POST.get('type') == 'update':
if data['is_taken']:
serial_no = request.POST.get('serial_no')
if IoT.objects.get(serial_no__iexact=serial_no).plate_no == plate_no:
data['is_taken'] = False
if data['is_taken']:
data['error_message'] = 'Bu plaka numarası başka cihaz tarafından kullanılmaktadır. Lütfen başka bir tane giriniz.'
return JsonResponse(data)
#Data Table
def iot_list_data(request):
iots = list()
for iot in IoT.objects.all():
iots.append(list((iot.serial_no,iot.plate_no,iot.is_active,
reverse('iot:iot_update', kwargs={'serial_no': iot.serial_no}) + ","+
reverse('iot:iot_delete', kwargs={'serial_no': iot.serial_no}))))
data = {
'data': iots
}
return JsonResponse(data)
|
import re
import os
for root, dirs, files in os.walk('C:\dev_workspace\GatesCVS\source\gates\gates-batch\src\main\java'):
for dir in dirs:
if dir not in ("CVS") :
for file in files:
print "Directory "+dir +" file name "+file
with open(os.path.join(root, file), "r") as auto:
line = auto.line()
|
#!/home/ch215616/miniconda2/envs/tch2/bin/python
"""This function corrects the echo ordering for .nrrd files which have been generated with DICOM to NRRD conversion tool. In certain cases, the aforementioned DICOM to NRRD tool incorrectly orders the echoes of the signal. This function corrects that mistake.
Function was tested for Myelin Water Function acquisition files (CPMG sequence).
Works with single slice (2D) and volumetric (3D) data.
Specify directory or file with .nrrd extension. Each .nrrd file must have a matching .yaml file.
The script will check each .yaml file for presence of multiple echoes. If the order is incorrect, it will fix the .nrrd file ordering.
If no explicit output directory is specified in the arguments, a new file name will be created in the same directory as the original input file with a suffix to its name - "_echoes_reordered.nrrd"
"""
import os
import glob
import sys
import argparse
import shutil
import numpy as np
import nrrd
def check_echo_ordering(file):
# check the the yaml file exists
assert os.path.exists(file), 'file does not exist'
# fetch the yaml file
with open(file) as f:
lines = f.readlines()
# find a starting line in yaml file where the list of echoes starts
for i,line in enumerate(lines):
if 'VOLUME_LIST' in line:
startingline = i+2
#get list of echo times as list of strings (read to the end of the file)
echoes_str = lines[startingline:]
# extract echo times as integers from the list of strings
echo_list = [[int(s) for s in echo_str.split() if s.isdigit()] for echo_str in echoes_str]
# proceed only if list is not empty (i.e. echo list exists)
if echo_list and echo_list[0]:
multi_echo_file = True
original_echo_order = echo_list
# extract the lists from list (sometimes the yaml file output can cause the list = [[9],[18],...] insted of list = [9,18,...]
if isinstance(original_echo_order[0],list): # if is list, correct
original_echo_order = [i[0] for i in original_echo_order]
# check if the orders match
if original_echo_order != sorted(original_echo_order):
print(f"Incorrect ordering of echoes detected in YAML file for: {os.path.basename(file)}.")
print(f"{original_echo_order}")
print(f"Reordering echoes")
proceed = True
else:
print(f"Echoes are in tact for {os.path.basename(file)}")
if args.debug:
print(f"Echoes are in tact {original_echo_order}")
proceed = False
else:
multi_echo_file = False
# do not proceed if no echo lists found
proceed = False
original_echo_order = []
return proceed, original_echo_order, multi_echo_file
def get_correcting_index(original_echo_order):
# sort the list of echoes into correct order, but save the index of the old (incorrect) order
correcting_index = [b[0] for b in sorted(enumerate(original_echo_order),key=lambda i:i[1])]
# debug (check that the original echo order sorted by ascending order manually is the corrected echo order with sort function)
corrected_echo_order_manual = [original_echo_order[i] for i in correcting_index]
assert corrected_echo_order_manual == sorted(original_echo_order)
return correcting_index
def load_nrrd(file,original_echo_order):
# load .nrrd file
nrrd_file = file.replace('.yaml','.nrrd')
im, header = nrrd.read(nrrd_file)
# check that the list of echoes matches the correct dimension of the image
if im.shape[0] != len(original_echo_order):
print('The first dimension of the NRRD file does not match the list of echoes')
print(f"The nrrd dimensions are {im.shape}")
print(f"Original echo list from YAML file: {original_echo_order}")
sys.exit("Exiting. ")
return nrrd_file, im, header
def sort_nrrd(im, correcting_index):
if im.ndim == 4:
imnew = [im[i,:,:,:] for i in correcting_index]
elif im.ndim == 3:
imnew = [im[i,:,:] for i in correcting_index]
else:
sys.exit("NRRD file must be 3D or 4D. Please check the file dimensions.")
imnew = np.array(imnew)
return imnew
def load_args():
parser = argparse.ArgumentParser()
parser.add_argument('-i','--input', type=str, required=True,help='directory to check for incorrect echoes. Must match nrrd and yaml filenames')
parser.add_argument('-o','--outdir', type=str, default=None, help='directory to write corrected filenames. If not specified, files written to the same directory with a suffix _echoes_reordered.nii.gz')
parser.add_argument('--debug', action='store_true', help='print out the name of every filename being checked and list its echoes and if they are in tact')
args = parser.parse_args()
return args
if __name__ == '__main__':
args = load_args()
# check if file or folder
if os.path.isfile(args.input):
# check if extension is .nrrd
assert args.input.endswith('.nrrd') or args.input.endswith('.yaml'), "Please specify path to .nrrd or .yaml file, or to a directory"
# must specify input as .yaml file
if args.input.endswith('.nrrd'):
path, ext = os.path.splitext(args.input)
yaml_file = path+'.yaml'
# check if corresponding .yaml file exists
assert os.path.exists(yaml_file), f"Matching yaml file does not exist: {yaml_file}"
elif args.input.endswith('.yaml'):
yaml_file = args.input
# check if corresponding .yaml file exists
assert os.path.exists(yaml_file.replace('.yaml','.nrrd')), f"Matching .nrrd file does not exist: {yaml_file}"
# must provide input as list
files = [yaml_file]
else:
# os.path.isdir(args.input):
assert os.path.exists(args.input), "Specified directory does not exist. Please check path"
# find all .yaml files
args.input = args.input + "/" if not args.input.endswith("/") else args.input
files = glob.glob(args.input + "*.yaml")
assert files, f"No .yaml files found in the specified directory:\n{args.input}"
# check if corresponding .nrrd exist
for file in files:
path, ext = os.path.splitext(file)
assert os.path.exists(path+'.nrrd'), f"Matching .nrrd file to .yaml file does not exist {path+'.nrrd'}"
for file in files:
if args.debug:
print(f"Checking: {os.path.basename(file)}")
# check the yaml file if the order of echoes is correct
proceed, original_echo_order,multi_echo_file = check_echo_ordering(file)
# proceed with correcting the file
if proceed:
# get the index with which to re-order the echoes
correcting_index = get_correcting_index(original_echo_order)
nrrd_file, im, header = load_nrrd(file,original_echo_order)
imnew = sort_nrrd(im,correcting_index)
# if the output directory is different, change the savedir
if args.outdir is not None:
outdir = args.outdir + "/" if not args.outdir.endswith("/") else args.outdir
assert os.path.exists(outdir), "Specified output directory does not exist. Please specify full correct path to output directory."
assert os.path.dirname(outdir) != os.path.dirname(nrrd_file), f"if explicit output path is specified, it has to be different from the path to input files. Else, do not specify output path and file will be written to same directory"
newname = outdir+os.path.basename(nrrd_file)
else:
# rename the file (only executed if explicit outdir is specified)
newname = nrrd_file.replace('.nrrd','_echoes_reordered.nrrd')
# check if file already exists:
if os.path.exists(newname):
base = os.path.basename(newname)
print(f"WARNING: A re-ordered .nrrd for this specific file already exists.\n{base}\nProceed? y/n")
proceed_to_save = input()
if proceed_to_save.lower() == 'n':
continue
# save the new file
nrrd.write(newname,imnew,header=header)
print(f"Saved the new file to: {newname}\n")
else:
# if args.outdir is explicitly specified and the file is a multi echo file - copy them to folder that folder
# i.e. copy file with correct and incorrect echo ordering
if multi_echo_file and args.outdir is not None:
# copy nrrd file
shutil.copyfile(file, args.outdir+"/" + os.path.basename(file))
# copy yaml file
file = file.replace(".yaml", ".nrrd")
shutil.copyfile(file, args.outdir+"/" + os.path.basename(file))
|
# -*- coding: utf-8 -*-
"""
Created on Thu Dec 25 14:32:12 2017
This is the model code for the black death assignment 2.
The program clculates the total deaths from the disease using historical figures of rat
populations and the population density.
There are two input raster map files:
1. Average population density per 100x100 m square
2. Average number of rats caught per 100x100 m square
The relationship between average rats caught per week per 100m x 100m square(r),
average population density per 100m x 100m square(p)
and average deaths per week per 100m x 100m square(d) is:
d = (0.8 x r) x (1.3 x p)
The program does the following:
1. Reads the two maps and puts them on the screen.
Each pixel represents a 100m x 100m square area.
2. Calculates a map showing average deaths per 100m x 100m square area
for the different geographical regions produced by the intersection of the two images.
It runs through the maps and pulls out the values for each pair of equivalently positioned cells.
It then puts them through the equation and produces a two dimensional array of absolute deaths
that you can convert into an Image mapping the deaths.
3. Displays the three maps.
3. Saves the death map as a text file of absolute deaths. Each line equals a line on the map.
4. Displays the total deaths per week.
5. Allows the user to change the parameter weights for the equation.
@author: paula
"""
import matplotlib.pyplot
import csv
import matplotlib.animation
import sys
population_density = []
rats_caught = []
num_deaths = [] #this list holds the number of deaths based on the calc
txt_list = [] #list for writing to file
# function to read input files and put their values into a list
# One list per input file, i.e. one for the population density and one
# for the average number of rats caught
def read_file(filename):
items = []
csv_file = open(filename)
reader = csv.reader(csv_file)
for row in reader:
# new rowlist before each row
rowlist = []
for values in row:
# add the row values into the rowlist, make sure they are integers
rowlist.append(int(values))
# add the row to the population density list
items.append(rowlist)
return items
# function that iterates the 400 x 400 coordinate system, takes rats
# caught at a given position and the density of people at that same position
# and calculates the number of deaths based on the formula given
def iterate_lists(num_of_iterations, txt_list, rat_weight, population_weight):
death_list = []
for i in range(num_of_iterations):
tmp_list = [] # temporaty list to store deaths per row
tmp_txt_list = ""
num_rats_caught = float(rats_caught[i][i])
density_people = float(population_density[i][i])
#deaths = int((0.8 * num_rats_caught) * (1.3 * density_people))
deaths = int((float(rat_weight) * num_rats_caught) * (float(population_weight) * density_people))
for j in range(num_of_iterations):
tmp_list.append(deaths)
tmp_death = str(deaths)
if i <= 399:
tmp_txt_list = tmp_txt_list + tmp_death+","
else:
tmp_txt_list = tmp_txt_list + tmp_death
#add each row to the death list
death_list.append(tmp_list)
txt_list.append(tmp_txt_list)
return death_list
# function that writes the number of deaths to a csv file
# takes the file name as an input parameter and writes a new line for each
def write_file(filename, txt_list):
with open(filename,'w') as output_file:
output_file.write('\n'.join(txt_list))
#read the input arguments for the weights
#In Spyder, runas "Configuration per file" and give the input parameters
rat_weight = sys.argv[1]
population_weight = sys.argv[2]
#read the files
population_density = read_file('death_parishes.csv')
rats_caught = read_file('death_rats.csv')
num_deaths = iterate_lists(400, txt_list, rat_weight, population_weight)
#write to the text file
write_file('absolute_deaths.txt', txt_list)
# Plot the three different maps on the screen
plt = matplotlib.pyplot
plt.figure()
plt.figure(figsize=(7, 7))
plt.imshow(population_density)
plt.figure()
plt.figure(figsize=(7, 7))
plt.imshow(rats_caught)
plt.figure()
plt.figure(figsize=(7, 7))
plt.imshow(num_deaths)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.