max_stars_repo_path stringlengths 4 286 | max_stars_repo_name stringlengths 5 119 | max_stars_count int64 0 191k | id stringlengths 1 7 | content stringlengths 6 1.03M | content_cleaned stringlengths 6 1.03M | language stringclasses 111 values | language_score float64 0.03 1 | comments stringlengths 0 556k | edu_score float64 0.32 5.03 | edu_int_score int64 0 5 |
|---|---|---|---|---|---|---|---|---|---|---|
module2-sql-for-analysis/cleanSql.py | DAVIDnHANG/DS-Unit-3-Sprint-2-SQL-and-Databases | 0 | 6623051 | import psycopg2
import sqlite3
#setting up for psycopy2.connect
dbname = 'wbtaflae'
user = 'wbtaflae'
password = ''
host = 'salt.db.elephantsql.com'
rpg_conn = psycopg2.connect( dbname =dbname, user=user, password=password, host=host)
#create the cursor once we established a connection to database server
rpg_curs = rpg_conn.cursor()
#once the cursor is established, we can now execute quires command
rpg_curs.execute('SELECT * FROM test_table;')
import sqlite3
sl_conn = sqlite3.connect('C:\\Users\\D3MoNa\\PycharmProjects\\Month3\\SQLAndDataBase\\module1-introduction-to-sql\\rpg_db.sqlite3')
sl_curs = sl_conn.cursor()
items = sl_curs.execute('SELECT * from charactercreator_character_inventory').fetchall()
sl_curs.execute('PRAGMA table_info(charactercreator_character_inventory);').fetchall()
#create_character_table_two = """
#CREATE TABLE charactercreator_character_inventory_web (
#character_id SERIAL PRIMARY KEY,
#name VARCHAR(30),
#item_id INT
#);
#"""
#rpg_curs.execute(create_character_table_two)
for item in items:
insert_item = """INSERT INTO charactercreator_character_inventory_web (name, item_id) VALUES""" + str(item[1:]) + ';'
rpg_curs.execute(insert_item)
rpg_curs.execute('SELECT * from charactercreator_character_inventory_web')
print(rpg_curs.fetchall())
#make the table for titanic table
create_titanic_table = """
CREATE TABLE titanic (
Survived INT,
Pclass INT,
Name VARCHAR(30),
Sex VARCHAR(15),
Age INT,
SiblingsSpousesAboard INT,
ParentsChildrenAboard INT,
Fare FLOAT);
"""
#insert the row in dataframe into table
#create column list for insertion
df.head(0).to_sql('table_name', engine, if_exists='replace',index=False) #truncates the table
conn = engine.raw_connection()
cur = conn.cursor()
output = io.StringIO()
df.to_csv(output, sep='\t', header=False, index=False)
output.seek(0)
contents = output.getvalue()
cur.copy_from(output, 'table_name', null="") # null values become ''
conn.commit()
rpg_curs.close()
rpg_conn.commit()
| import psycopg2
import sqlite3
#setting up for psycopy2.connect
dbname = 'wbtaflae'
user = 'wbtaflae'
password = ''
host = 'salt.db.elephantsql.com'
rpg_conn = psycopg2.connect( dbname =dbname, user=user, password=password, host=host)
#create the cursor once we established a connection to database server
rpg_curs = rpg_conn.cursor()
#once the cursor is established, we can now execute quires command
rpg_curs.execute('SELECT * FROM test_table;')
import sqlite3
sl_conn = sqlite3.connect('C:\\Users\\D3MoNa\\PycharmProjects\\Month3\\SQLAndDataBase\\module1-introduction-to-sql\\rpg_db.sqlite3')
sl_curs = sl_conn.cursor()
items = sl_curs.execute('SELECT * from charactercreator_character_inventory').fetchall()
sl_curs.execute('PRAGMA table_info(charactercreator_character_inventory);').fetchall()
#create_character_table_two = """
#CREATE TABLE charactercreator_character_inventory_web (
#character_id SERIAL PRIMARY KEY,
#name VARCHAR(30),
#item_id INT
#);
#"""
#rpg_curs.execute(create_character_table_two)
for item in items:
insert_item = """INSERT INTO charactercreator_character_inventory_web (name, item_id) VALUES""" + str(item[1:]) + ';'
rpg_curs.execute(insert_item)
rpg_curs.execute('SELECT * from charactercreator_character_inventory_web')
print(rpg_curs.fetchall())
#make the table for titanic table
create_titanic_table = """
CREATE TABLE titanic (
Survived INT,
Pclass INT,
Name VARCHAR(30),
Sex VARCHAR(15),
Age INT,
SiblingsSpousesAboard INT,
ParentsChildrenAboard INT,
Fare FLOAT);
"""
#insert the row in dataframe into table
#create column list for insertion
df.head(0).to_sql('table_name', engine, if_exists='replace',index=False) #truncates the table
conn = engine.raw_connection()
cur = conn.cursor()
output = io.StringIO()
df.to_csv(output, sep='\t', header=False, index=False)
output.seek(0)
contents = output.getvalue()
cur.copy_from(output, 'table_name', null="") # null values become ''
conn.commit()
rpg_curs.close()
rpg_conn.commit()
| en | 0.50463 | #setting up for psycopy2.connect #create the cursor once we established a connection to database server #once the cursor is established, we can now execute quires command #create_character_table_two = """ #CREATE TABLE charactercreator_character_inventory_web ( #character_id SERIAL PRIMARY KEY, #name VARCHAR(30), #item_id INT #); #""" #rpg_curs.execute(create_character_table_two) INSERT INTO charactercreator_character_inventory_web (name, item_id) VALUES #make the table for titanic table CREATE TABLE titanic (
Survived INT,
Pclass INT,
Name VARCHAR(30),
Sex VARCHAR(15),
Age INT,
SiblingsSpousesAboard INT,
ParentsChildrenAboard INT,
Fare FLOAT); #insert the row in dataframe into table #create column list for insertion #truncates the table # null values become '' | 3.408939 | 3 |
Implementation/models/ShoppingCart.py | AchuthaVVyas/259902_Ltts_StepIN- | 0 | 6623052 | from models.Item import Item
class ShoppingCart:
def __init__(self):
self.items = []
def addToCart(self, item):
self.items.append(item)
def removeFromCart(self, itemIndex):
self.items.pop(itemIndex)
def getTotalPrice(self):
totalPrice = 0
for item in self.items:
totalPrice += item.price
return totalPrice
def getCartItems(self):
return self.items
def emptyCart(self):
self.items.clear()
| from models.Item import Item
class ShoppingCart:
def __init__(self):
self.items = []
def addToCart(self, item):
self.items.append(item)
def removeFromCart(self, itemIndex):
self.items.pop(itemIndex)
def getTotalPrice(self):
totalPrice = 0
for item in self.items:
totalPrice += item.price
return totalPrice
def getCartItems(self):
return self.items
def emptyCart(self):
self.items.clear()
| none | 1 | 3.078922 | 3 | |
Working1/Init.py | fovtran/PyGame_samples | 0 | 6623053 | <gh_stars>0
# -*- coding: utf-8 -*-
from AllImports import *
w = 1200
h = 600
FPS = 10
def SetScreen():
global screen
pygame.init ()
pygame.font.init()
info = pygame.display.Info()
print(info)
flags = pygame.OPENGL | pygame.DOUBLEBUF | pygame.HWSURFACE | pygame.RESIZABLE
screen = pygame.display.set_mode((w,h), flags, 32, vsync=0)
glViewport (0, 0, w, h)
return screen
def SetLights():
lightZeroPosition = [0., -4., 10., 1.]
lightZeroColor = [0.9, 1.0, 0.9, 1.0]
glLightfv(GL_LIGHT0, GL_POSITION, lightZeroPosition)
glLightfv(GL_LIGHT0, GL_DIFFUSE, lightZeroColor)
glLightf(GL_LIGHT0, GL_CONSTANT_ATTENUATION, 0.05)
glLightf(GL_LIGHT0, GL_LINEAR_ATTENUATION, 0.05)
glEnable(GL_LIGHT0)
def init():
screen = SetScreen()
SetLights()
glDisable(GL_DEPTH_TEST)
glDisable(GL_CULL_FACE)
glEnable(GL_COLOR_MATERIAL)
glEnable( GL_TEXTURE_2D )
glEnable(GL_MULTISAMPLE)
#glEnable(GL_NORMALIZE)
glEnable(GL_POINT_SMOOTH)
glEnable(GL_LINE_SMOOTH)
glEnable(GL_POLYGON_SMOOTH)
glEnable(GL_POLYGON_OFFSET_FILL)
#glEnable(GL_BLEND);
#glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
glShadeModel( GL_SMOOTH )
glHint(GL_LINE_SMOOTH_HINT, GL_NICEST)
glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE)
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL)
glLineWidth(1.0)
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
gluPerspective(95, float(w) / h, .000001, 275)
gluLookAt(-2, 2, -4, 0, 0, 0, 0, 1, 0)
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
glMatrixMode(GL_MODELVIEW)
glLoadIdentity()
pygame.display.update()
return screen
def pygame_init():
screen = SetScreen()
SetLights()
glEnable(GL_DEPTH_TEST)
glDisable(GL_CULL_FACE)
glEnable(GL_COLOR_MATERIAL)
glEnable( GL_TEXTURE_2D )
glDisable(GL_MULTISAMPLE)
#glEnable(GL_NORMALIZE)
glEnable(GL_POINT_SMOOTH)
glEnable(GL_LINE_SMOOTH)
glEnable(GL_POLYGON_SMOOTH)
glEnable(GL_POLYGON_OFFSET_FILL)
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
glShadeModel( GL_SMOOTH )
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL)
glHint(GL_LINE_SMOOTH_HINT, GL_NICEST)
glClearColor(.05, .05, .05, 1.0)
glColorMaterial(GL_FRONT_AND_BACK, GL_DIFFUSE)
pygame.display.update()
return screen
| # -*- coding: utf-8 -*-
from AllImports import *
w = 1200
h = 600
FPS = 10
def SetScreen():
global screen
pygame.init ()
pygame.font.init()
info = pygame.display.Info()
print(info)
flags = pygame.OPENGL | pygame.DOUBLEBUF | pygame.HWSURFACE | pygame.RESIZABLE
screen = pygame.display.set_mode((w,h), flags, 32, vsync=0)
glViewport (0, 0, w, h)
return screen
def SetLights():
lightZeroPosition = [0., -4., 10., 1.]
lightZeroColor = [0.9, 1.0, 0.9, 1.0]
glLightfv(GL_LIGHT0, GL_POSITION, lightZeroPosition)
glLightfv(GL_LIGHT0, GL_DIFFUSE, lightZeroColor)
glLightf(GL_LIGHT0, GL_CONSTANT_ATTENUATION, 0.05)
glLightf(GL_LIGHT0, GL_LINEAR_ATTENUATION, 0.05)
glEnable(GL_LIGHT0)
def init():
screen = SetScreen()
SetLights()
glDisable(GL_DEPTH_TEST)
glDisable(GL_CULL_FACE)
glEnable(GL_COLOR_MATERIAL)
glEnable( GL_TEXTURE_2D )
glEnable(GL_MULTISAMPLE)
#glEnable(GL_NORMALIZE)
glEnable(GL_POINT_SMOOTH)
glEnable(GL_LINE_SMOOTH)
glEnable(GL_POLYGON_SMOOTH)
glEnable(GL_POLYGON_OFFSET_FILL)
#glEnable(GL_BLEND);
#glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
glShadeModel( GL_SMOOTH )
glHint(GL_LINE_SMOOTH_HINT, GL_NICEST)
glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE)
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL)
glLineWidth(1.0)
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
gluPerspective(95, float(w) / h, .000001, 275)
gluLookAt(-2, 2, -4, 0, 0, 0, 0, 1, 0)
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
glMatrixMode(GL_MODELVIEW)
glLoadIdentity()
pygame.display.update()
return screen
def pygame_init():
screen = SetScreen()
SetLights()
glEnable(GL_DEPTH_TEST)
glDisable(GL_CULL_FACE)
glEnable(GL_COLOR_MATERIAL)
glEnable( GL_TEXTURE_2D )
glDisable(GL_MULTISAMPLE)
#glEnable(GL_NORMALIZE)
glEnable(GL_POINT_SMOOTH)
glEnable(GL_LINE_SMOOTH)
glEnable(GL_POLYGON_SMOOTH)
glEnable(GL_POLYGON_OFFSET_FILL)
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
glShadeModel( GL_SMOOTH )
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL)
glHint(GL_LINE_SMOOTH_HINT, GL_NICEST)
glClearColor(.05, .05, .05, 1.0)
glColorMaterial(GL_FRONT_AND_BACK, GL_DIFFUSE)
pygame.display.update()
return screen | en | 0.369955 | # -*- coding: utf-8 -*- #glEnable(GL_NORMALIZE) #glEnable(GL_BLEND); #glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) #glEnable(GL_NORMALIZE) | 2.389301 | 2 |
stream/generate/create.py | sanjeevkanabargi/python | 0 | 6623054 | import random
import json
from datetime import datetime, timedelta
import csv
timestamp = datetime.now() + timedelta(days=-3)
def randomIP():
arrVal = ["127.1.1.0","192.168.1.1","192.168.0.1","192.168.3.1","192.168.8.1","192.168.100.1","10.0.0.138"]
return arrVal[random.randint(0,len(arrVal)-1)]
def randomPort():
return random.randint(1000,1050)
def randomSession():
return random.randint(2000,2050)
def randomValue(arrVal):
#print("returning : "+arrVal[random.randint(0,len(arrVal)-1)])
return arrVal[random.randint(0,len(arrVal)-1)]
def getRandomIPLoc():
return {
"AccuracyRadius": random.randint(1,101),
"Latitude": random.randint(1,101),
"Longitude": random.randint(1,101),
"MetroCode": random.randint(1,101),
"TimeZone": "IST"
}
def createRandomData():
data = {}
timestamp = getFromatedDate(gettimestamp())
#print("thje date :"+str(timestamp))
data['timestamp'] = timestamp
data['event_type'] = randomValue(["flow-event","login","logout","download","upload"])
data['action'] = randomValue(["allow","deny","auth","start","stope"])
data['src_ip'] = randomIP()
data['dst_ip'] = randomIP()
data['nat_src_ip'] = randomIP()
data['nat_src_port'] = randomPort()
data['session_id'] = randomSession()
data['src_port'] = randomPort()
data['dst_port'] = randomPort()
data['protocol'] = randomValue(["http","https","ftp"])
appid = randomValue(["facebook","linkedin","google","netskope","zomato","swiggy"])
data['app_id']= appid
data['rule_name'] = str(appid)+"_rule"
data['user_name'] = randomValue(["Sanjeev","Ying","Muneer","Azham","Aniket","Linto","Tejasvi"])
data['repeat_count'] = random.randint(0,10)
data['bytes_sent'] = random.randint(100,500)
data['bytes_rcvd'] = random.randint(100,500)
data['packet_sent'] = random.randint(10,50)
data['packet_rcvd'] = random.randint(10,50)
data['start_time'] = timestamp
data['session_duration'] = random.randint(1,50)
data['tunnel_type'] = randomValue(["ipsec","L2TP","PPTP","TLS","ssh","OpenVPN"])
data['tenant_id'] = randomValue(["VM","Wallmart","Nike","Addidas","HP","Cisco","Google","Flipkart"])
#data['dst_ip_location'] = getRandomIPLoc()
#data['src_ip_location'] = getRandomIPLoc()
return data
#Create JSON message from above variables.
#create CSV files from above message.
def gettimestamp():
return timestamp - timedelta(minutes=-1)
def getFromatedDate(value):
mylist = []
mylist.append(value)
tempVal = str(mylist[0]).split(" ")
toPrint = tempVal[0]+"T"+tempVal[1].split(".")[0]
#print(toPrint)
return toPrint
if __name__ == '__main__':
#message = createRandomData()
#print(message)
#get Timestamps..
timestamp = datetime.now() + timedelta(days=-3)
#src_port,dst_port,protocol,app_id,rule_name,user_name,repeat_count,bytes_sent,bytes_rcvd,packet_sent,packet_rcvd,start_time,session_duration,tunnel_type,tenant_id,dst_ip_location.AccuracyRadius,dst_ip_location.Latitude,dst_ip_location.Longitude,dst_ip_location.MetroCode,dst_ip_location.TimeZone,src_ip_location.AccuracyRadius,src_ip_location.Latitude,src_ip_location.Longitude,src_ip_location.MetroCode,src_ip_location.TimeZone,
#data =
with open('cfw-sample.json', 'w') as f: # Just use 'w' mode in 3.x
for i in range(10000000):
data = createRandomData()
jsondata = json.dumps(data)
f.write(jsondata+"\n") | import random
import json
from datetime import datetime, timedelta
import csv
timestamp = datetime.now() + timedelta(days=-3)
def randomIP():
arrVal = ["127.1.1.0","192.168.1.1","192.168.0.1","192.168.3.1","192.168.8.1","192.168.100.1","10.0.0.138"]
return arrVal[random.randint(0,len(arrVal)-1)]
def randomPort():
return random.randint(1000,1050)
def randomSession():
return random.randint(2000,2050)
def randomValue(arrVal):
#print("returning : "+arrVal[random.randint(0,len(arrVal)-1)])
return arrVal[random.randint(0,len(arrVal)-1)]
def getRandomIPLoc():
return {
"AccuracyRadius": random.randint(1,101),
"Latitude": random.randint(1,101),
"Longitude": random.randint(1,101),
"MetroCode": random.randint(1,101),
"TimeZone": "IST"
}
def createRandomData():
data = {}
timestamp = getFromatedDate(gettimestamp())
#print("thje date :"+str(timestamp))
data['timestamp'] = timestamp
data['event_type'] = randomValue(["flow-event","login","logout","download","upload"])
data['action'] = randomValue(["allow","deny","auth","start","stope"])
data['src_ip'] = randomIP()
data['dst_ip'] = randomIP()
data['nat_src_ip'] = randomIP()
data['nat_src_port'] = randomPort()
data['session_id'] = randomSession()
data['src_port'] = randomPort()
data['dst_port'] = randomPort()
data['protocol'] = randomValue(["http","https","ftp"])
appid = randomValue(["facebook","linkedin","google","netskope","zomato","swiggy"])
data['app_id']= appid
data['rule_name'] = str(appid)+"_rule"
data['user_name'] = randomValue(["Sanjeev","Ying","Muneer","Azham","Aniket","Linto","Tejasvi"])
data['repeat_count'] = random.randint(0,10)
data['bytes_sent'] = random.randint(100,500)
data['bytes_rcvd'] = random.randint(100,500)
data['packet_sent'] = random.randint(10,50)
data['packet_rcvd'] = random.randint(10,50)
data['start_time'] = timestamp
data['session_duration'] = random.randint(1,50)
data['tunnel_type'] = randomValue(["ipsec","L2TP","PPTP","TLS","ssh","OpenVPN"])
data['tenant_id'] = randomValue(["VM","Wallmart","Nike","Addidas","HP","Cisco","Google","Flipkart"])
#data['dst_ip_location'] = getRandomIPLoc()
#data['src_ip_location'] = getRandomIPLoc()
return data
#Create JSON message from above variables.
#create CSV files from above message.
def gettimestamp():
return timestamp - timedelta(minutes=-1)
def getFromatedDate(value):
mylist = []
mylist.append(value)
tempVal = str(mylist[0]).split(" ")
toPrint = tempVal[0]+"T"+tempVal[1].split(".")[0]
#print(toPrint)
return toPrint
if __name__ == '__main__':
#message = createRandomData()
#print(message)
#get Timestamps..
timestamp = datetime.now() + timedelta(days=-3)
#src_port,dst_port,protocol,app_id,rule_name,user_name,repeat_count,bytes_sent,bytes_rcvd,packet_sent,packet_rcvd,start_time,session_duration,tunnel_type,tenant_id,dst_ip_location.AccuracyRadius,dst_ip_location.Latitude,dst_ip_location.Longitude,dst_ip_location.MetroCode,dst_ip_location.TimeZone,src_ip_location.AccuracyRadius,src_ip_location.Latitude,src_ip_location.Longitude,src_ip_location.MetroCode,src_ip_location.TimeZone,
#data =
with open('cfw-sample.json', 'w') as f: # Just use 'w' mode in 3.x
for i in range(10000000):
data = createRandomData()
jsondata = json.dumps(data)
f.write(jsondata+"\n") | en | 0.311362 | #print("returning : "+arrVal[random.randint(0,len(arrVal)-1)]) #print("thje date :"+str(timestamp)) #data['dst_ip_location'] = getRandomIPLoc() #data['src_ip_location'] = getRandomIPLoc() #Create JSON message from above variables. #create CSV files from above message. #print(toPrint) #message = createRandomData() #print(message) #get Timestamps.. #src_port,dst_port,protocol,app_id,rule_name,user_name,repeat_count,bytes_sent,bytes_rcvd,packet_sent,packet_rcvd,start_time,session_duration,tunnel_type,tenant_id,dst_ip_location.AccuracyRadius,dst_ip_location.Latitude,dst_ip_location.Longitude,dst_ip_location.MetroCode,dst_ip_location.TimeZone,src_ip_location.AccuracyRadius,src_ip_location.Latitude,src_ip_location.Longitude,src_ip_location.MetroCode,src_ip_location.TimeZone, #data = # Just use 'w' mode in 3.x | 2.679731 | 3 |
mytest.py | djun100/aircv | 0 | 6623055 | <reponame>djun100/aircv
import aircv as ac
imsrc = ac.imread('tests/testdata/g18/screen_big.png') # 原始图像
imsch = ac.imread('tests/testdata/g18/task.png') # 带查找的部分
print((ac.find_sift(imsrc, imsch)))
| import aircv as ac
imsrc = ac.imread('tests/testdata/g18/screen_big.png') # 原始图像
imsch = ac.imread('tests/testdata/g18/task.png') # 带查找的部分
print((ac.find_sift(imsrc, imsch))) | zh | 0.993423 | # 原始图像 # 带查找的部分 | 2.200836 | 2 |
test/win/gyptest-cl-compile-as-winrt.py | chlorm-forks/gyp | 2,151 | 6623056 | # Copyright (c) 2016 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import TestGyp
import os
import sys
if (sys.platform == 'win32' and
int(os.environ.get('GYP_MSVS_VERSION', 0)) >= 2015):
test = TestGyp.TestGyp(formats=['msvs'])
CHDIR = 'compiler-flags'
test.run_gyp('compile-as-winrt.gyp', chdir=CHDIR)
test.build('compile-as-winrt.gyp', 'test-compile-as-winrt', chdir=CHDIR)
test.pass_test() | # Copyright (c) 2016 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import TestGyp
import os
import sys
if (sys.platform == 'win32' and
int(os.environ.get('GYP_MSVS_VERSION', 0)) >= 2015):
test = TestGyp.TestGyp(formats=['msvs'])
CHDIR = 'compiler-flags'
test.run_gyp('compile-as-winrt.gyp', chdir=CHDIR)
test.build('compile-as-winrt.gyp', 'test-compile-as-winrt', chdir=CHDIR)
test.pass_test() | en | 0.921492 | # Copyright (c) 2016 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. | 1.82641 | 2 |
igcommit/utils.py | hasegeli/igcommit | 189 | 6623057 | <gh_stars>100-1000
"""igcommit - Utility functions
Copyright (c) 2021 InnoGames GmbH
Portions Copyright (c) 2021 <NAME>
"""
from os import X_OK, access, environ
def get_exe_path(exe):
"""Traverse the PATH to find where the executable is
This should behave similar to the shell built-in "which".
"""
for dir_path in environ['PATH'].split(':'):
path = dir_path.strip('"') + '/' + exe
if access(path, X_OK):
return path
def iter_buffer(generator, amount):
"""Iterate with buffering
This is a utility function that's useful for asynchronous processing.
It buffers the elements of the given generator to earn time for items
to do their processing.
The argument is assumed to be a generator (although it would work with
any iterable) that generates items which start their processing in
the background at the time they are generated. And the caller is assumed
to consume those items when their processing is complete.
This function is going to maintain a FIFO buffer up to the given size.
It'd start with an empty buffer (memo), buffer all of the generated items
until the buffer is full or the generator starts generating None, then
start adding items to the end yielding from the beginning of the buffer,
and finally yield the ones that are left in the buffer after the generator
is consumed.
The buffering is short-cut when the generator generates None as the next
item. This is a useful feature when the caller needs to wait for some
item in the buffer to complete. The generated None's are never yielded
to the caller.
Note that this procedure does not support out-of-order consumption of
the items. The caller would always have to wait for the first yielded
item to be done with its processing. While the caller is waiting,
another item in the buffer may become ready, but we wouldn't even know.
This is how this function remains very simple.
"""
assert amount > 1
memo = []
for elem in generator:
if elem is not None:
memo.append(elem)
if len(memo) < amount:
continue
yield memo.pop(0)
for elem in memo:
yield elem
| """igcommit - Utility functions
Copyright (c) 2021 InnoGames GmbH
Portions Copyright (c) 2021 <NAME>
"""
from os import X_OK, access, environ
def get_exe_path(exe):
"""Traverse the PATH to find where the executable is
This should behave similar to the shell built-in "which".
"""
for dir_path in environ['PATH'].split(':'):
path = dir_path.strip('"') + '/' + exe
if access(path, X_OK):
return path
def iter_buffer(generator, amount):
"""Iterate with buffering
This is a utility function that's useful for asynchronous processing.
It buffers the elements of the given generator to earn time for items
to do their processing.
The argument is assumed to be a generator (although it would work with
any iterable) that generates items which start their processing in
the background at the time they are generated. And the caller is assumed
to consume those items when their processing is complete.
This function is going to maintain a FIFO buffer up to the given size.
It'd start with an empty buffer (memo), buffer all of the generated items
until the buffer is full or the generator starts generating None, then
start adding items to the end yielding from the beginning of the buffer,
and finally yield the ones that are left in the buffer after the generator
is consumed.
The buffering is short-cut when the generator generates None as the next
item. This is a useful feature when the caller needs to wait for some
item in the buffer to complete. The generated None's are never yielded
to the caller.
Note that this procedure does not support out-of-order consumption of
the items. The caller would always have to wait for the first yielded
item to be done with its processing. While the caller is waiting,
another item in the buffer may become ready, but we wouldn't even know.
This is how this function remains very simple.
"""
assert amount > 1
memo = []
for elem in generator:
if elem is not None:
memo.append(elem)
if len(memo) < amount:
continue
yield memo.pop(0)
for elem in memo:
yield elem | en | 0.940195 | igcommit - Utility functions Copyright (c) 2021 InnoGames GmbH Portions Copyright (c) 2021 <NAME> Traverse the PATH to find where the executable is This should behave similar to the shell built-in "which". Iterate with buffering This is a utility function that's useful for asynchronous processing. It buffers the elements of the given generator to earn time for items to do their processing. The argument is assumed to be a generator (although it would work with any iterable) that generates items which start their processing in the background at the time they are generated. And the caller is assumed to consume those items when their processing is complete. This function is going to maintain a FIFO buffer up to the given size. It'd start with an empty buffer (memo), buffer all of the generated items until the buffer is full or the generator starts generating None, then start adding items to the end yielding from the beginning of the buffer, and finally yield the ones that are left in the buffer after the generator is consumed. The buffering is short-cut when the generator generates None as the next item. This is a useful feature when the caller needs to wait for some item in the buffer to complete. The generated None's are never yielded to the caller. Note that this procedure does not support out-of-order consumption of the items. The caller would always have to wait for the first yielded item to be done with its processing. While the caller is waiting, another item in the buffer may become ready, but we wouldn't even know. This is how this function remains very simple. | 3.506577 | 4 |
setup.py | jgoodknight/spectroscopy | 6 | 6623058 | <reponame>jgoodknight/spectroscopy<gh_stars>1-10
#!/usr/bin/env python
from distutils.core import setup
with open("README.md", 'r') as f:
long_description = f.read()
setup(name='spectroscopy',
version='0.10',
description='Spectroscopy of systems with explicit vibrational degrees of Freedom',
author='<NAME>',
author_email='<EMAIL>',
url='https://github.com/jgoodknight/spectroscopy/',
long_description=long_description,
license="MIT",
packages=['spectroscopy', 'spectroscopy.experiments'],
package_dir = {'spectroscopy': 'src'} #,install_requires=['numpy', 'scipy', 'matplotlib']
)
| #!/usr/bin/env python
from distutils.core import setup
with open("README.md", 'r') as f:
long_description = f.read()
setup(name='spectroscopy',
version='0.10',
description='Spectroscopy of systems with explicit vibrational degrees of Freedom',
author='<NAME>',
author_email='<EMAIL>',
url='https://github.com/jgoodknight/spectroscopy/',
long_description=long_description,
license="MIT",
packages=['spectroscopy', 'spectroscopy.experiments'],
package_dir = {'spectroscopy': 'src'} #,install_requires=['numpy', 'scipy', 'matplotlib']
) | ru | 0.095953 | #!/usr/bin/env python #,install_requires=['numpy', 'scipy', 'matplotlib'] | 1.281402 | 1 |
settings.py | bgmnbear/RetroMusicPlayer | 0 | 6623059 | MUSIC_PATH = r'../music/'
LYRIC_PATH = r'../lyric/'
| MUSIC_PATH = r'../music/'
LYRIC_PATH = r'../lyric/'
| none | 1 | 1.143017 | 1 | |
pyeccodes/defs/mars/grib_gfas_gsd_def.py | ecmwf/pyeccodes | 7 | 6623060 | import pyeccodes.accessors as _
def load(h):
h.unalias('mars.levtype')
h.unalias('mars.levelist')
h.unalias('mars.channel')
h.unalias('mars.step')
| import pyeccodes.accessors as _
def load(h):
h.unalias('mars.levtype')
h.unalias('mars.levelist')
h.unalias('mars.channel')
h.unalias('mars.step')
| none | 1 | 1.601236 | 2 | |
test/test_apisearch.py | WallaceLiu/distributed-realtime-capfaiss | 0 | 6623061 | import unittest
import requests
import json
from core_test.base.test_base import http, headers, NpEncoder
import numpy as np
from core.utils.io_utils import write
class SearchApiTest(unittest.TestCase):
def test(self):
url = '%s/%s' % (http, 'rc/search')
d = 100
nb = 2000
np.random.seed(1234)
xb = np.random.random((nb, d)).astype('float32')
xb[:, 0] += np.arange(nb) / 1000.
ids = ['u' + str(i) for i in range(1)]
data = json.dumps({
'rcId': "101001101",
'ids': ids,
'vectors': json.loads(json.dumps(xb[0:1], cls=NpEncoder)),
})
write('./op_searc_data', json.dumps(data))
# r = requests.post(url, data=data, headers=headers)
# print("""
#
# url...%s
# content...%s
#
# """ % (url, r.content))
| import unittest
import requests
import json
from core_test.base.test_base import http, headers, NpEncoder
import numpy as np
from core.utils.io_utils import write
class SearchApiTest(unittest.TestCase):
def test(self):
url = '%s/%s' % (http, 'rc/search')
d = 100
nb = 2000
np.random.seed(1234)
xb = np.random.random((nb, d)).astype('float32')
xb[:, 0] += np.arange(nb) / 1000.
ids = ['u' + str(i) for i in range(1)]
data = json.dumps({
'rcId': "101001101",
'ids': ids,
'vectors': json.loads(json.dumps(xb[0:1], cls=NpEncoder)),
})
write('./op_searc_data', json.dumps(data))
# r = requests.post(url, data=data, headers=headers)
# print("""
#
# url...%s
# content...%s
#
# """ % (url, r.content))
| en | 0.256857 | # r = requests.post(url, data=data, headers=headers) # print(""" # # url...%s # content...%s # # """ % (url, r.content)) | 2.777094 | 3 |
UI.py | privacyrespected/Alpha | 0 | 6623062 | #This program is used for linkage of the UI to the backend algorithm such as the live computer stats shown on the left menu
from platform import platform
import eel
import psutil
import sys
import platform
from frontend_command import Pcommand
eel.init("web")
@eel.expose
def checkram():
memory_info=psutil.virtual_memory()
current_ram = "Ram: " + str(memory_info.percent)+"%"
#uncomment to print and debug
#print(current_ram)
return current_ram
@eel.expose
def checkcpu():
cpustat= psutil.cpu_percent()
current_cpu= "CPU: " + str(cpustat)+"%"
return current_cpu
@eel.expose
def checknetwork1():
checknetwork= psutil.sensors_battery().percent
checknetwork= str(checknetwork)
current_network="Energy: " + checknetwork + "%"
return current_network
@eel.expose
def checkcommand(commandinput):
print(commandinput)
Pcommand(commandinput)
#frontend functions
def alpha_frontend():
if sys.platform in ['win32', 'win64'] and int(platform.release())>=10:
eel.start("index.html", cmdline_args=['--start-fullscreen'],port=4000)
else:
raise EnvironmentError("Error: system is not windows 10 or above")
#uncomment this line to purely debug this function
#alpha_frontend()
alpha_frontend()
| #This program is used for linkage of the UI to the backend algorithm such as the live computer stats shown on the left menu
from platform import platform
import eel
import psutil
import sys
import platform
from frontend_command import Pcommand
eel.init("web")
@eel.expose
def checkram():
memory_info=psutil.virtual_memory()
current_ram = "Ram: " + str(memory_info.percent)+"%"
#uncomment to print and debug
#print(current_ram)
return current_ram
@eel.expose
def checkcpu():
cpustat= psutil.cpu_percent()
current_cpu= "CPU: " + str(cpustat)+"%"
return current_cpu
@eel.expose
def checknetwork1():
checknetwork= psutil.sensors_battery().percent
checknetwork= str(checknetwork)
current_network="Energy: " + checknetwork + "%"
return current_network
@eel.expose
def checkcommand(commandinput):
print(commandinput)
Pcommand(commandinput)
#frontend functions
def alpha_frontend():
if sys.platform in ['win32', 'win64'] and int(platform.release())>=10:
eel.start("index.html", cmdline_args=['--start-fullscreen'],port=4000)
else:
raise EnvironmentError("Error: system is not windows 10 or above")
#uncomment this line to purely debug this function
#alpha_frontend()
alpha_frontend()
| en | 0.78592 | #This program is used for linkage of the UI to the backend algorithm such as the live computer stats shown on the left menu #uncomment to print and debug #print(current_ram) #frontend functions #uncomment this line to purely debug this function #alpha_frontend() | 3.056116 | 3 |
train.py | dali-ambiguity/dali-full-anaphora | 5 | 6623063 | #!/usr/bin/env python
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import time
import tensorflow as tf
import coref_model as cm
import util
if __name__ == "__main__":
config = util.initialize_from_env()
report_frequency = config["report_frequency"]
eval_frequency = config["eval_frequency"]
#evaluate unlimited cluster only used in the final evaluation
config["eval_unlimited_cluster"] = False
with_split_antecedent = config["with_split_antecedent"]
model = cm.CorefModel(config)
saver = tf.train.Saver(max_to_keep=1)
log_dir = config["log_dir"]
writer = tf.summary.FileWriter(log_dir, flush_secs=20)
max_step = config["max_step"]
session_config = tf.ConfigProto()
session_config.gpu_options.allow_growth = True
session_config.allow_soft_placement = True
max_f1 = 0
max_point = 0
with tf.Session(config=session_config) as session:
session.run(tf.global_variables_initializer())
model.start_enqueue_thread(session)
accumulated_loss = 0.0
ckpt = tf.train.get_checkpoint_state(log_dir)
if ckpt and ckpt.model_checkpoint_path:
print("Restoring from: {}".format(ckpt.model_checkpoint_path))
saver.restore(session, ckpt.model_checkpoint_path)
initial_time = time.time()
tf_global_step = 0
while tf_global_step < max_step:
tf_loss, tf_global_step, _ = session.run([model.loss, model.global_step, model.train_op])
accumulated_loss += tf_loss
if tf_global_step % report_frequency == 0:
total_time = time.time() - initial_time
steps_per_second = tf_global_step / total_time
average_loss = accumulated_loss / report_frequency
print("Coref: [{}] loss={:.2f}, steps/s={:.2f}".format(tf_global_step, average_loss, steps_per_second))
writer.add_summary(util.make_summary({"loss": average_loss}), tf_global_step)
accumulated_loss = 0.0
if tf_global_step % eval_frequency == 0:
saver.save(session, os.path.join(log_dir, "model.ckpt"), global_step=tf_global_step)
eval_summary, eval_f1 = model.evaluate(session,mode='coref')
if eval_f1 > max_f1:
max_f1 = eval_f1
max_point = tf_global_step
util.copy_checkpoint(os.path.join(log_dir, "model.ckpt-{}".format(tf_global_step)), os.path.join(log_dir, "model.max.ckpt"))
writer.add_summary(eval_summary, tf_global_step)
writer.add_summary(util.make_summary({"max_eval_f1": max_f1}), tf_global_step)
print("Coref: [{}] evaL_f1={:.2f}, max_f1={:.2f} from step {}".format(tf_global_step, eval_f1, max_f1,max_point))
if with_split_antecedent:
util.copy_checkpoint(os.path.join(log_dir, "model.max.ckpt"),
os.path.join(log_dir, "model.max.coref.ckpt"))
print('\n\nCoref training finished!\n\n Starting training split antecedent.')
eval_frequency = 500 # more freq
accumulated_loss = 0
max_f1 = 0
model.restore(session)
model.train_mode = 'split_antecedent'
session.run(model.reset_global_step)
tf_global_step = 0
initial_time = time.time()
while tf_global_step < max_step * 0.2:
tf_loss, tf_global_step, _ = session.run([model.split_antecedent_loss, model.global_step, model.split_antecedent_train_op])
accumulated_loss += tf_loss
if tf_global_step % report_frequency == 0:
total_time = time.time() - initial_time
steps_per_second = tf_global_step / total_time
average_loss = accumulated_loss / report_frequency
print(
"Split antecedent - [{}] loss={:.2f}, steps/s={:.2f}".format(tf_global_step, average_loss, steps_per_second))
writer.add_summary(util.make_summary({"loss": average_loss}), tf_global_step)
accumulated_loss = 0.0
if tf_global_step % eval_frequency == 0:
saver.save(session, os.path.join(log_dir, "model.ckpt"), global_step=tf_global_step)
eval_summary, eval_f1 = model.evaluate(session, mode="split_antecedent")
if eval_f1 > max_f1:
max_f1 = eval_f1
max_point = tf_global_step
util.copy_checkpoint(os.path.join(log_dir, "model.ckpt-{}".format(tf_global_step)),
os.path.join(log_dir, "model.max.ckpt"))
writer.add_summary(eval_summary, tf_global_step)
writer.add_summary(util.make_summary({"max_eval_f1": max_f1}), tf_global_step)
print("Split antecedent - [{}] evaL_f1={:.2f}, max_f1={:.2f} from step {}".format(tf_global_step, eval_f1, max_f1,
max_point)) | #!/usr/bin/env python
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import time
import tensorflow as tf
import coref_model as cm
import util
if __name__ == "__main__":
config = util.initialize_from_env()
report_frequency = config["report_frequency"]
eval_frequency = config["eval_frequency"]
#evaluate unlimited cluster only used in the final evaluation
config["eval_unlimited_cluster"] = False
with_split_antecedent = config["with_split_antecedent"]
model = cm.CorefModel(config)
saver = tf.train.Saver(max_to_keep=1)
log_dir = config["log_dir"]
writer = tf.summary.FileWriter(log_dir, flush_secs=20)
max_step = config["max_step"]
session_config = tf.ConfigProto()
session_config.gpu_options.allow_growth = True
session_config.allow_soft_placement = True
max_f1 = 0
max_point = 0
with tf.Session(config=session_config) as session:
session.run(tf.global_variables_initializer())
model.start_enqueue_thread(session)
accumulated_loss = 0.0
ckpt = tf.train.get_checkpoint_state(log_dir)
if ckpt and ckpt.model_checkpoint_path:
print("Restoring from: {}".format(ckpt.model_checkpoint_path))
saver.restore(session, ckpt.model_checkpoint_path)
initial_time = time.time()
tf_global_step = 0
while tf_global_step < max_step:
tf_loss, tf_global_step, _ = session.run([model.loss, model.global_step, model.train_op])
accumulated_loss += tf_loss
if tf_global_step % report_frequency == 0:
total_time = time.time() - initial_time
steps_per_second = tf_global_step / total_time
average_loss = accumulated_loss / report_frequency
print("Coref: [{}] loss={:.2f}, steps/s={:.2f}".format(tf_global_step, average_loss, steps_per_second))
writer.add_summary(util.make_summary({"loss": average_loss}), tf_global_step)
accumulated_loss = 0.0
if tf_global_step % eval_frequency == 0:
saver.save(session, os.path.join(log_dir, "model.ckpt"), global_step=tf_global_step)
eval_summary, eval_f1 = model.evaluate(session,mode='coref')
if eval_f1 > max_f1:
max_f1 = eval_f1
max_point = tf_global_step
util.copy_checkpoint(os.path.join(log_dir, "model.ckpt-{}".format(tf_global_step)), os.path.join(log_dir, "model.max.ckpt"))
writer.add_summary(eval_summary, tf_global_step)
writer.add_summary(util.make_summary({"max_eval_f1": max_f1}), tf_global_step)
print("Coref: [{}] evaL_f1={:.2f}, max_f1={:.2f} from step {}".format(tf_global_step, eval_f1, max_f1,max_point))
if with_split_antecedent:
util.copy_checkpoint(os.path.join(log_dir, "model.max.ckpt"),
os.path.join(log_dir, "model.max.coref.ckpt"))
print('\n\nCoref training finished!\n\n Starting training split antecedent.')
eval_frequency = 500 # more freq
accumulated_loss = 0
max_f1 = 0
model.restore(session)
model.train_mode = 'split_antecedent'
session.run(model.reset_global_step)
tf_global_step = 0
initial_time = time.time()
while tf_global_step < max_step * 0.2:
tf_loss, tf_global_step, _ = session.run([model.split_antecedent_loss, model.global_step, model.split_antecedent_train_op])
accumulated_loss += tf_loss
if tf_global_step % report_frequency == 0:
total_time = time.time() - initial_time
steps_per_second = tf_global_step / total_time
average_loss = accumulated_loss / report_frequency
print(
"Split antecedent - [{}] loss={:.2f}, steps/s={:.2f}".format(tf_global_step, average_loss, steps_per_second))
writer.add_summary(util.make_summary({"loss": average_loss}), tf_global_step)
accumulated_loss = 0.0
if tf_global_step % eval_frequency == 0:
saver.save(session, os.path.join(log_dir, "model.ckpt"), global_step=tf_global_step)
eval_summary, eval_f1 = model.evaluate(session, mode="split_antecedent")
if eval_f1 > max_f1:
max_f1 = eval_f1
max_point = tf_global_step
util.copy_checkpoint(os.path.join(log_dir, "model.ckpt-{}".format(tf_global_step)),
os.path.join(log_dir, "model.max.ckpt"))
writer.add_summary(eval_summary, tf_global_step)
writer.add_summary(util.make_summary({"max_eval_f1": max_f1}), tf_global_step)
print("Split antecedent - [{}] evaL_f1={:.2f}, max_f1={:.2f} from step {}".format(tf_global_step, eval_f1, max_f1,
max_point)) | en | 0.54524 | #!/usr/bin/env python #evaluate unlimited cluster only used in the final evaluation # more freq | 1.939866 | 2 |
tests/models/test_highgantt.py | GenomicsNX/panel-highcharts | 107 | 6623064 | # pylint: disable=redefined-outer-name,protected-access
# pylint: disable=missing-function-docstring,missing-module-docstring,missing-class-docstring
import pytest
from panel_highcharts.models.highgantt import HighGantt
@pytest.fixture
def backup_js_files():
javascript = HighGantt.__javascript__
js_require = HighGantt.__js_require__
yield
HighGantt.__javascript__ = javascript
HighGantt.__js_require__ = js_require
def test_class():
# pylint: disable=unsubscriptable-object
assert "https://code.highcharts.com/highcharts.js" in HighGantt.__javascript__
assert "https://code.highcharts.com/modules/gantt.js" in HighGantt.__javascript__
assert "https://code.highcharts.com/highcharts.js" in HighGantt.__js_skip__["highcharts"]
assert "https://code.highcharts.com/modules/gantt.js" in HighGantt.__js_skip__["highcharts"]
assert HighGantt.__js_require__["packages"] == [{"name": "highcharts", "main": "highcharts"}]
assert HighGantt.__js_require__["paths"]["highcharts"] == "https://code.highcharts.com"
assert (
HighGantt.__js_require__["paths"]["highcharts/modules/gantt"]
== "https://code.highcharts.com/modules/gantt"
)
assert HighGantt.__js_require__["exports"]["highcharts"] == "Highcharts"
assert (
HighGantt.__js_require__["exports"]["highcharts/modules/gantt"] == "highchartsmodulesgantt"
)
def test_js_files(backup_js_files): # pylint: disable=unused-argument
# Given
javascript = HighGantt.__javascript__
js_skip = HighGantt.__js_skip__
js_require = HighGantt.__js_require__
# When
HighGantt.js_files()
# Then
assert HighGantt.__javascript__ == javascript
assert HighGantt.__js_skip__ == js_skip
assert HighGantt.__js_require__ == js_require
def test_js_files_data(backup_js_files): # pylint: disable=unused-argument
# When
HighGantt.js_files(highcharts_data=True)
# Then
assert "https://code.highcharts.com/modules/data.js" in HighGantt.__javascript__
# pylint: disable=unsubscriptable-object
assert "https://code.highcharts.com/modules/data.js" in HighGantt.__js_skip__["highcharts"]
assert (
HighGantt.__js_require__["paths"]["highcharts/modules/data"]
== "https://code.highcharts.com/modules/data"
)
| # pylint: disable=redefined-outer-name,protected-access
# pylint: disable=missing-function-docstring,missing-module-docstring,missing-class-docstring
import pytest
from panel_highcharts.models.highgantt import HighGantt
@pytest.fixture
def backup_js_files():
javascript = HighGantt.__javascript__
js_require = HighGantt.__js_require__
yield
HighGantt.__javascript__ = javascript
HighGantt.__js_require__ = js_require
def test_class():
# pylint: disable=unsubscriptable-object
assert "https://code.highcharts.com/highcharts.js" in HighGantt.__javascript__
assert "https://code.highcharts.com/modules/gantt.js" in HighGantt.__javascript__
assert "https://code.highcharts.com/highcharts.js" in HighGantt.__js_skip__["highcharts"]
assert "https://code.highcharts.com/modules/gantt.js" in HighGantt.__js_skip__["highcharts"]
assert HighGantt.__js_require__["packages"] == [{"name": "highcharts", "main": "highcharts"}]
assert HighGantt.__js_require__["paths"]["highcharts"] == "https://code.highcharts.com"
assert (
HighGantt.__js_require__["paths"]["highcharts/modules/gantt"]
== "https://code.highcharts.com/modules/gantt"
)
assert HighGantt.__js_require__["exports"]["highcharts"] == "Highcharts"
assert (
HighGantt.__js_require__["exports"]["highcharts/modules/gantt"] == "highchartsmodulesgantt"
)
def test_js_files(backup_js_files): # pylint: disable=unused-argument
# Given
javascript = HighGantt.__javascript__
js_skip = HighGantt.__js_skip__
js_require = HighGantt.__js_require__
# When
HighGantt.js_files()
# Then
assert HighGantt.__javascript__ == javascript
assert HighGantt.__js_skip__ == js_skip
assert HighGantt.__js_require__ == js_require
def test_js_files_data(backup_js_files): # pylint: disable=unused-argument
# When
HighGantt.js_files(highcharts_data=True)
# Then
assert "https://code.highcharts.com/modules/data.js" in HighGantt.__javascript__
# pylint: disable=unsubscriptable-object
assert "https://code.highcharts.com/modules/data.js" in HighGantt.__js_skip__["highcharts"]
assert (
HighGantt.__js_require__["paths"]["highcharts/modules/data"]
== "https://code.highcharts.com/modules/data"
)
| en | 0.439365 | # pylint: disable=redefined-outer-name,protected-access # pylint: disable=missing-function-docstring,missing-module-docstring,missing-class-docstring # pylint: disable=unsubscriptable-object # pylint: disable=unused-argument # Given # When # Then # pylint: disable=unused-argument # When # Then # pylint: disable=unsubscriptable-object | 2.026682 | 2 |
tests/core/txs/test_SimpleTransaction.py | scottdonaldau/QRL | 1 | 6623065 | from unittest import TestCase
import simplejson as json
from mock import patch, PropertyMock, Mock
from pyqrllib.pyqrllib import bin2hstr
from qrl.core.misc import logger
from qrl.core.AddressState import AddressState
from qrl.core.ChainManager import ChainManager
from qrl.core.TransactionInfo import TransactionInfo
from qrl.core.txs.Transaction import Transaction
from qrl.core.txs.TransferTransaction import TransferTransaction
from tests.core.txs.testdata import test_json_Simple, test_signature_Simple
from tests.misc.helper import get_alice_xmss, get_bob_xmss, get_slave_xmss, replacement_getTime
logger.initialize_default()
@patch('qrl.core.txs.Transaction.logger')
class TestSimpleTransaction(TestCase):
def __init__(self, *args, **kwargs):
super(TestSimpleTransaction, self).__init__(*args, **kwargs)
self.alice = get_alice_xmss()
self.bob = get_bob_xmss()
self.slave = get_slave_xmss()
self.alice.set_ots_index(10)
self.maxDiff = None
def setUp(self):
self.tx = TransferTransaction.create(
addrs_to=[self.bob.address],
amounts=[100],
fee=1,
xmss_pk=self.alice.pk
)
def test_create(self, m_logger):
# Alice sending coins to Bob
tx = TransferTransaction.create(addrs_to=[self.bob.address],
amounts=[100],
fee=1,
xmss_pk=self.alice.pk)
self.assertTrue(tx)
def test_create_negative_amount(self, m_logger):
with self.assertRaises(ValueError):
TransferTransaction.create(addrs_to=[self.bob.address],
amounts=[-100],
fee=1,
xmss_pk=self.alice.pk)
def test_create_negative_fee(self, m_logger):
with self.assertRaises(ValueError):
TransferTransaction.create(addrs_to=[self.bob.address],
amounts=[-100],
fee=-1,
xmss_pk=self.alice.pk)
def test_to_json(self, m_logger):
tx = TransferTransaction.create(addrs_to=[self.bob.address],
amounts=[100],
fee=1,
xmss_pk=self.alice.pk)
txjson = tx.to_json()
self.assertEqual(json.loads(test_json_Simple), json.loads(txjson))
def test_from_json(self, m_logger):
tx = Transaction.from_json(test_json_Simple)
tx.sign(self.alice)
self.assertIsInstance(tx, TransferTransaction)
# Test that common Transaction components were copied over.
self.assertEqual(0, tx.nonce)
self.assertEqual('010300a1da274e68c88b0ccf448e0b1916fa789b01eb2ed4e9ad565ce264c9390782a9c61ac02f',
bin2hstr(tx.addr_from))
self.assertEqual('01030038ea6375069f8272cc1a6601b3c76c21519455603d370036b97c779ada356'
'5854e3983bd564298c49ae2e7fa6e28d4b954d8cd59398f1225b08d6144854aee0e',
bin2hstr(tx.PK))
self.assertEqual('554f546305d4aed6ec71c759942b721b904ab9d65eeac3c954c08c652181c4e8', bin2hstr(tx.txhash))
self.assertEqual(10, tx.ots_key)
self.assertEqual(test_signature_Simple, bin2hstr(tx.signature))
# Test that specific content was copied over.
self.assertEqual('0103001d65d7e59aed5efbeae64246e0f3184d7c42411421eb385ba30f2c1c005a85ebc4419cfd',
bin2hstr(tx.addrs_to[0]))
self.assertEqual(100, tx.total_amount)
self.assertEqual(1, tx.fee)
def test_validate_tx(self, m_logger):
# If we change amount, fee, addr_from, addr_to, (maybe include xmss stuff) txhash should change.
# Here we use the tx already defined in setUp() for convenience.
# We must sign the tx before validation will work.
self.tx.sign(self.alice)
# We have not touched the tx: validation should pass.
self.assertTrue(self.tx.validate_or_raise())
def test_validate_tx2(self, m_logger):
tx = TransferTransaction.create(
addrs_to=[self.bob.address],
amounts=[100],
fee=1,
xmss_pk=self.alice.pk
)
tx.sign(self.alice)
self.assertTrue(tx.validate_or_raise())
tx._data.transaction_hash = b'abc'
# Should fail, as we have modified with invalid transaction_hash
with self.assertRaises(ValueError):
tx.validate_or_raise()
@patch('qrl.core.txs.Transaction.config')
def test_validate_tx_invalid(self, m_config, m_logger):
# Test all the things that could make a TransferTransaction invalid
self.tx.sign(self.alice)
# Validation in creation, Protobuf, type conversion etc. gets in our way all the time!
# So to get dirty data to the validate() function, we need PropertyMocks
with patch('qrl.core.txs.TransferTransaction.TransferTransaction.amounts',
new_callable=PropertyMock) as m_amounts:
# TX amount of 0 shouldn't be allowed.
m_amounts.return_value = [0]
with self.assertRaises(ValueError):
self.tx.validate_or_raise()
with patch('qrl.core.txs.TransferTransaction.TransferTransaction.fee', new_callable=PropertyMock) as m_fee:
m_fee.return_value = -1
with self.assertRaises(ValueError):
self.tx.validate_or_raise()
with patch('qrl.core.txs.TransferTransaction.TransferTransaction.addrs_to',
new_callable=PropertyMock) as m_addrs_to:
with patch('qrl.core.txs.TransferTransaction.TransferTransaction.amounts',
new_callable=PropertyMock) as m_amounts:
# Validation could fail because len(m_addrs_to) != len(m_amounts),
# or if len(m_addrs_to) > transaction_multi_output_limit.
# This second patch level is to make sure the only the latter case happens.
m_amounts = [100, 100, 100, 100]
m_config.dev.transaction_multi_output_limit = 3
m_addrs_to.return_value = [2, 2, 2, 2]
with self.assertRaises(ValueError):
self.tx.validate_or_raise()
with patch('qrl.core.txs.TransferTransaction.TransferTransaction.addrs_to',
new_callable=PropertyMock) as m_addrs_to:
# len(addrs_to) must equal len(amounts)
m_addrs_to.return_value = [2, 2]
with self.assertRaises(ValueError):
self.tx.validate_or_raise()
with patch('qrl.core.txs.TransferTransaction.TransferTransaction.addr_from',
new_callable=PropertyMock) as m_addr_from:
m_addr_from.return_value = b'If this isnt invalid Ill eat my shoe'
with self.assertRaises(ValueError):
self.tx.validate_or_raise()
with patch('qrl.core.txs.TransferTransaction.TransferTransaction.addrs_to',
new_callable=PropertyMock) as m_addrs_to:
with patch('qrl.core.txs.TransferTransaction.TransferTransaction.amounts',
new_callable=PropertyMock) as m_amounts:
m_amounts.return_value = [100, 100]
m_addrs_to.return_value = [self.bob.address, b'If this isnt invalid Ill eat my shoe']
with self.assertRaises(ValueError):
self.tx.validate_or_raise()
def test_validate_extended(self, m_logger):
"""
validate_extended() handles these parts of the validation:
1. Master/slave
2. balance, amount + fee from AddressState
3. OTS key reuse from AddressState
:return:
"""
m_addr_state = Mock(autospec=AddressState, balance=200)
m_addr_from_pk_state = Mock(autospec=AddressState)
m_addr_from_pk_state.ots_key_reuse.return_value = False
self.tx.validate_slave = Mock(autospec=Transaction.validate_slave, return_value=True)
self.tx.sign(self.alice)
result = self.tx.validate_extended(m_addr_state, m_addr_from_pk_state)
self.assertTrue(result)
# Suppose there was ots key reuse. The function should then return false.
m_addr_from_pk_state.ots_key_reuse.return_value = True
result = self.tx.validate_extended(m_addr_state, m_addr_from_pk_state)
self.assertFalse(result)
# Reset conditions from above
m_addr_from_pk_state.ots_key_reuse.return_value = False
# Suppose the slave XMSS address does not have permission for this type of Transaction. It should return False.
self.tx.validate_slave.return_value = False
result = self.tx.validate_extended(m_addr_state, m_addr_from_pk_state)
self.assertFalse(result)
# Reset conditions from above
self.tx.validate_slave.return_value = True
# Suppose the address doesn't have enough coins.
m_addr_state.balance = 99
result = self.tx.validate_extended(m_addr_state, m_addr_from_pk_state)
self.assertFalse(result)
def test_validate_transaction_pool(self, m_logger):
"""
Two TransferTransactions. Although they're the same, they are signed with different OTS indexes.
Therefore they should not conflict when they are both in the TransactionPool.
:return:
"""
tx = self.tx
tx2 = TransferTransaction.create(
addrs_to=[self.bob.address],
amounts=[100],
fee=1,
xmss_pk=self.alice.pk
)
tx.sign(self.alice)
tx2.sign(self.alice)
tx_info = Mock(autospec=TransactionInfo, transaction=tx)
tx2_info = Mock(autospec=TransactionInfo, transaction=tx2)
transaction_pool = [(replacement_getTime(), tx_info), (replacement_getTime(), tx2_info)]
result = tx.validate_transaction_pool(transaction_pool)
self.assertTrue(result)
def test_validate_transaction_pool_reusing_ots_index(self, m_logger):
"""
Two different TransferTransactions. They are signed with the same OTS indexe, from the same public key.
Therefore they should conflict.
:return:
"""
tx = self.tx
tx2 = TransferTransaction.create(
addrs_to=[self.bob.address],
amounts=[100],
fee=5,
xmss_pk=self.alice.pk
)
# alice_clone's OTS index is still at 10, while self.alice will be at 11 after signing.
alice_clone = get_alice_xmss()
alice_clone.set_ots_index(10)
tx.sign(self.alice)
tx2.sign(alice_clone)
tx_info = Mock(autospec=TransactionInfo, transaction=tx)
tx2_info = Mock(autospec=TransactionInfo, transaction=tx2)
transaction_pool = [(replacement_getTime(), tx_info), (replacement_getTime(), tx2_info)]
result = tx.validate_transaction_pool(transaction_pool)
self.assertFalse(result)
def test_validate_transaction_pool_different_pk_same_ots_index(self, m_logger):
"""
Two TransferTransactions. They are signed with the same OTS indexes, but from different public keys.
Therefore they should NOT conflict.
:return:
"""
tx = self.tx
tx2 = TransferTransaction.create(
addrs_to=[self.bob.address],
amounts=[100],
fee=1,
xmss_pk=self.bob.pk
)
tx.sign(self.alice)
tx2.sign(self.bob)
tx_info = Mock(autospec=TransactionInfo, transaction=tx)
tx2_info = Mock(autospec=TransactionInfo, transaction=tx2)
transaction_pool = [(replacement_getTime(), tx_info), (replacement_getTime(), tx2_info)]
result = tx.validate_transaction_pool(transaction_pool)
self.assertTrue(result)
def test_apply_state_changes(self, m_logger):
"""
apply_state_changes() is the part that actually updates everybody's balances.
Then it forwards the addresses_state to _apply_state_changes_for_PK(), which updates everybody's addresses's
nonce, OTS key index, and associated TX hashes
If there is no AddressState for a particular Address, nothing is done.
"""
addresses_state = {
self.alice.address: Mock(autospec=AddressState, name='alice AddressState', transaction_hashes=[],
balance=200),
self.bob.address: Mock(autospec=AddressState, name='bob AddressState', transaction_hashes=[], balance=0),
self.slave.address: Mock(autospec=AddressState, name='slave AddressState', transaction_hashes=[], balance=0)
}
self.tx._apply_state_changes_for_PK = Mock(autospec=TransferTransaction._apply_state_changes_for_PK)
self.tx.apply_state_changes(addresses_state)
# Now Alice should have 99 coins left (200 - 100 - 1) and Bob should have 100 coins.
self.assertEqual(99, addresses_state[self.alice.address].balance)
self.assertEqual(100, addresses_state[self.bob.address].balance)
self.tx._apply_state_changes_for_PK.assert_called_once()
# If there are no AddressStates related to the Addresses in this transaction, do nothing.
self.tx._apply_state_changes_for_PK.reset_mock()
addresses_state_dummy = {
b'a': 'ABC',
b'b': 'DEF'
}
self.tx.apply_state_changes(addresses_state_dummy)
self.assertEqual(addresses_state_dummy, {b'a': 'ABC', b'b': 'DEF'})
self.tx._apply_state_changes_for_PK.assert_called_once()
def test_apply_state_changes_tx_sends_to_self(self, m_logger):
"""
If you send coins to yourself, you should only lose the fee for the Transaction.
"""
addresses_state = {
self.alice.address: Mock(autospec=AddressState, name='alice AddressState', transaction_hashes=[],
balance=200),
self.bob.address: Mock(autospec=AddressState, name='bob AddressState', transaction_hashes=[], balance=0),
self.slave.address: Mock(autospec=AddressState, name='slave AddressState', transaction_hashes=[], balance=0)
}
tx = TransferTransaction.create(
addrs_to=[self.alice.address],
amounts=[100],
fee=1,
xmss_pk=self.alice.pk
)
tx._apply_state_changes_for_PK = Mock(autospec=TransferTransaction._revert_state_changes_for_PK)
tx.apply_state_changes(addresses_state)
self.assertEqual(199, addresses_state[self.alice.address].balance)
self.assertIn(tx.txhash, addresses_state[self.alice.address].transaction_hashes)
def test_apply_state_changes_multi_send(self, m_logger):
"""
Test that apply_state_changes() also works with multiple recipients.
"""
addresses_state = {
self.alice.address: Mock(autospec=AddressState, name='alice AddressState', transaction_hashes=[],
balance=200),
self.bob.address: Mock(autospec=AddressState, name='bob AddressState', transaction_hashes=[], balance=0),
self.slave.address: Mock(autospec=AddressState, name='slave AddressState', transaction_hashes=[], balance=0)
}
tx_multisend = TransferTransaction.create(
addrs_to=[self.bob.address, self.slave.address],
amounts=[20, 20],
fee=1,
xmss_pk=self.alice.pk
)
tx_multisend._apply_state_changes_for_PK = Mock(autospec=TransferTransaction._apply_state_changes_for_PK)
tx_multisend.apply_state_changes(addresses_state)
# Now Alice should have 159 coins left (200 - 20 - 20 - 1) and Bob should have 100 coins.
self.assertEqual(159, addresses_state[self.alice.address].balance)
self.assertEqual(20, addresses_state[self.bob.address].balance)
self.assertEqual(20, addresses_state[self.slave.address].balance)
tx_multisend._apply_state_changes_for_PK.assert_called_once()
def test_apply_state_changes_for_PK(self, m_logger):
"""
This updates the node's AddressState database with which OTS index a particular address should be on, and what
tx hashes is this address associated with.
Curiously enough, if the TX was signed by a master XMSS tree, it doesn't add this tx's txhash to the list of
txs that address is associated with.
:return:
"""
addr_state = {
self.alice.address: Mock(autospec=AddressState)
}
old_ots_index = self.alice.ots_index
self.tx.sign(self.alice)
self.tx._apply_state_changes_for_PK(addr_state)
addr_state[self.alice.address].increase_nonce.assert_called_once()
addr_state[self.alice.address].set_ots_key.assert_called_once_with(old_ots_index)
def test_apply_state_changes_for_PK_master_slave_XMSS(self, m_logger):
"""
If the TX was signed by a slave XMSS, the slave XMSS's AddressState should be updated (not the master's).
:return:
"""
tx = TransferTransaction.create(
addrs_to=[self.bob.address],
amounts=[100],
fee=1,
xmss_pk=self.slave.pk,
master_addr=self.alice.address
)
addr_state = {
self.alice.address: Mock(autospec=AddressState, name='alice AddressState'),
self.slave.address: Mock(autospec=AddressState, name='slave AddressState')
}
old_ots_index = self.slave.ots_index
tx.sign(self.slave)
tx._apply_state_changes_for_PK(addr_state)
addr_state[self.slave.address].increase_nonce.assert_called_once()
addr_state[self.slave.address].set_ots_key.assert_called_once_with(old_ots_index)
addr_state[self.slave.address].transaction_hashes.append.assert_called_once()
def test_revert_state_changes(self, m_logger):
"""
Alice has sent 100 coins to Bob, using 1 as Transaction fee. Now we need to undo this.
"""
addresses_state = {
self.alice.address: Mock(autospec=AddressState, name='alice AddressState',
transaction_hashes=[self.tx.txhash],
balance=99),
self.bob.address: Mock(autospec=AddressState, name='bob AddressState', transaction_hashes=[self.tx.txhash],
balance=100),
self.slave.address: Mock(autospec=AddressState, name='slave AddressState', transaction_hashes=[], balance=0)
}
unused_chain_manager_mock = Mock(autospec=ChainManager, name='unused ChainManager')
self.tx._revert_state_changes_for_PK = Mock(autospec=TransferTransaction._revert_state_changes_for_PK)
self.tx.revert_state_changes(addresses_state, unused_chain_manager_mock)
self.assertEqual(200, addresses_state[self.alice.address].balance)
self.assertEqual(0, addresses_state[self.bob.address].balance)
self.assertEqual([], addresses_state[self.alice.address].transaction_hashes)
self.assertEqual([], addresses_state[self.bob.address].transaction_hashes)
self.tx._revert_state_changes_for_PK.assert_called_once()
# If there are no AddressStates related to the Addresses in this transaction, do nothing.
self.tx._revert_state_changes_for_PK.reset_mock()
addresses_state_dummy = {
b'a': 'ABC',
b'b': 'DEF'
}
self.tx.revert_state_changes(addresses_state_dummy, unused_chain_manager_mock)
self.assertEqual(addresses_state_dummy, {b'a': 'ABC', b'b': 'DEF'})
self.tx._revert_state_changes_for_PK.assert_called_once()
def test_revert_state_changes_multi_send(self, m_logger):
"""
Alice has sent 20 coins to Bob and Slave each, using 1 as Transaction fee. Now we need to undo this.
"""
addresses_state = {
self.alice.address: Mock(autospec=AddressState, name='alice AddressState',
transaction_hashes=[self.tx.txhash],
balance=159),
self.bob.address: Mock(autospec=AddressState, name='bob AddressState', transaction_hashes=[self.tx.txhash],
balance=20),
self.slave.address: Mock(autospec=AddressState, name='slave AddressState',
transaction_hashes=[self.tx.txhash], balance=20)
}
unused_chain_manager_mock = Mock(autospec=ChainManager, name='unused ChainManager')
tx_multisend = TransferTransaction.create(
addrs_to=[self.bob.address, self.slave.address],
amounts=[20, 20],
fee=1,
xmss_pk=self.alice.pk
)
tx_multisend._revert_state_changes_for_PK = Mock(autospec=TransferTransaction._revert_state_changes_for_PK)
tx_multisend.revert_state_changes(addresses_state, unused_chain_manager_mock)
self.assertEqual(200, addresses_state[self.alice.address].balance)
self.assertEqual(0, addresses_state[self.bob.address].balance)
self.assertEqual(0, addresses_state[self.slave.address].balance)
self.assertEqual([], addresses_state[self.alice.address].transaction_hashes)
self.assertEqual([], addresses_state[self.bob.address].transaction_hashes)
self.assertEqual([], addresses_state[self.slave.address].transaction_hashes)
tx_multisend._revert_state_changes_for_PK.assert_called_once()
def test_revert_state_changes_tx_sends_to_self(self, m_logger):
"""
Alice sent coins to herself, but she still lost the Transaction fee. Undo this.
"""
addresses_state = {
self.alice.address: Mock(autospec=AddressState, name='alice AddressState',
transaction_hashes=[self.tx.txhash],
balance=199),
self.bob.address: Mock(autospec=AddressState, name='bob AddressState', transaction_hashes=[],
balance=0),
self.slave.address: Mock(autospec=AddressState, name='slave AddressState', transaction_hashes=[], balance=0)
}
unused_chain_manager_mock = Mock(autospec=ChainManager, name='unused ChainManager')
tx = TransferTransaction.create(
addrs_to=[self.alice.address],
amounts=[100],
fee=1,
xmss_pk=self.alice.pk
)
tx._revert_state_changes_for_PK = Mock(autospec=TransferTransaction._revert_state_changes_for_PK)
tx.revert_state_changes(addresses_state, unused_chain_manager_mock)
self.assertEqual(200, addresses_state[self.alice.address].balance)
self.assertEqual(0, addresses_state[self.bob.address].balance)
self.assertEqual([], addresses_state[self.alice.address].transaction_hashes)
self.assertEqual([], addresses_state[self.bob.address].transaction_hashes)
tx._revert_state_changes_for_PK.assert_called_once()
def test_revert_state_changes_for_PK(self, m_logger):
"""
This is just an undo function.
:return:
"""
tx = TransferTransaction.create(
addrs_to=[self.bob.address],
amounts=[100],
fee=1,
xmss_pk=self.alice.pk
)
addr_state = {
self.alice.address: Mock(autospec=AddressState)
}
tx.sign(self.alice)
tx._revert_state_changes_for_PK(addr_state, Mock(name='unused State Mock'))
addr_state[self.alice.address].decrease_nonce.assert_called_once()
addr_state[self.alice.address].unset_ots_key.assert_called_once()
def test_revert_state_changes_for_PK_master_slave_XMSS(self, m_logger):
tx = TransferTransaction.create(
addrs_to=[self.bob.address],
amounts=[100],
fee=1,
xmss_pk=self.slave.pk,
master_addr=self.alice.address
)
addr_state = {
self.alice.address: Mock(autospec=AddressState, name='alice AddressState'),
self.slave.address: Mock(autospec=AddressState, name='slave AddressState')
}
tx.sign(self.slave)
tx._revert_state_changes_for_PK(addr_state, Mock(name='unused State Mock'))
addr_state[self.slave.address].decrease_nonce.assert_called_once()
addr_state[self.slave.address].unset_ots_key.assert_called_once()
addr_state[self.slave.address].transaction_hashes.remove.assert_called_once()
def test_affected_address(self, m_logger):
# The default transaction params involve only two addresses.
affected_addresses = set()
self.tx.set_affected_address(affected_addresses)
self.assertEqual(2, len(affected_addresses))
# This transaction should involve 3 addresses.
affected_addresses = set()
tx = TransferTransaction.create(
addrs_to=[self.bob.address, self.slave.address],
amounts=[100, 100],
fee=1,
xmss_pk=self.alice.pk
)
tx.set_affected_address(affected_addresses)
self.assertEqual(3, len(affected_addresses))
| from unittest import TestCase
import simplejson as json
from mock import patch, PropertyMock, Mock
from pyqrllib.pyqrllib import bin2hstr
from qrl.core.misc import logger
from qrl.core.AddressState import AddressState
from qrl.core.ChainManager import ChainManager
from qrl.core.TransactionInfo import TransactionInfo
from qrl.core.txs.Transaction import Transaction
from qrl.core.txs.TransferTransaction import TransferTransaction
from tests.core.txs.testdata import test_json_Simple, test_signature_Simple
from tests.misc.helper import get_alice_xmss, get_bob_xmss, get_slave_xmss, replacement_getTime
logger.initialize_default()
@patch('qrl.core.txs.Transaction.logger')
class TestSimpleTransaction(TestCase):
def __init__(self, *args, **kwargs):
super(TestSimpleTransaction, self).__init__(*args, **kwargs)
self.alice = get_alice_xmss()
self.bob = get_bob_xmss()
self.slave = get_slave_xmss()
self.alice.set_ots_index(10)
self.maxDiff = None
def setUp(self):
self.tx = TransferTransaction.create(
addrs_to=[self.bob.address],
amounts=[100],
fee=1,
xmss_pk=self.alice.pk
)
def test_create(self, m_logger):
# Alice sending coins to Bob
tx = TransferTransaction.create(addrs_to=[self.bob.address],
amounts=[100],
fee=1,
xmss_pk=self.alice.pk)
self.assertTrue(tx)
def test_create_negative_amount(self, m_logger):
with self.assertRaises(ValueError):
TransferTransaction.create(addrs_to=[self.bob.address],
amounts=[-100],
fee=1,
xmss_pk=self.alice.pk)
def test_create_negative_fee(self, m_logger):
with self.assertRaises(ValueError):
TransferTransaction.create(addrs_to=[self.bob.address],
amounts=[-100],
fee=-1,
xmss_pk=self.alice.pk)
def test_to_json(self, m_logger):
tx = TransferTransaction.create(addrs_to=[self.bob.address],
amounts=[100],
fee=1,
xmss_pk=self.alice.pk)
txjson = tx.to_json()
self.assertEqual(json.loads(test_json_Simple), json.loads(txjson))
def test_from_json(self, m_logger):
tx = Transaction.from_json(test_json_Simple)
tx.sign(self.alice)
self.assertIsInstance(tx, TransferTransaction)
# Test that common Transaction components were copied over.
self.assertEqual(0, tx.nonce)
self.assertEqual('010300a1da274e68c88b0ccf448e0b1916fa789b01eb2ed4e9ad565ce264c9390782a9c61ac02f',
bin2hstr(tx.addr_from))
self.assertEqual('01030038ea6375069f8272cc1a6601b3c76c21519455603d370036b97c779ada356'
'5854e3983bd564298c49ae2e7fa6e28d4b954d8cd59398f1225b08d6144854aee0e',
bin2hstr(tx.PK))
self.assertEqual('554f546305d4aed6ec71c759942b721b904ab9d65eeac3c954c08c652181c4e8', bin2hstr(tx.txhash))
self.assertEqual(10, tx.ots_key)
self.assertEqual(test_signature_Simple, bin2hstr(tx.signature))
# Test that specific content was copied over.
self.assertEqual('0103001d65d7e59aed5efbeae64246e0f3184d7c42411421eb385ba30f2c1c005a85ebc4419cfd',
bin2hstr(tx.addrs_to[0]))
self.assertEqual(100, tx.total_amount)
self.assertEqual(1, tx.fee)
def test_validate_tx(self, m_logger):
# If we change amount, fee, addr_from, addr_to, (maybe include xmss stuff) txhash should change.
# Here we use the tx already defined in setUp() for convenience.
# We must sign the tx before validation will work.
self.tx.sign(self.alice)
# We have not touched the tx: validation should pass.
self.assertTrue(self.tx.validate_or_raise())
def test_validate_tx2(self, m_logger):
tx = TransferTransaction.create(
addrs_to=[self.bob.address],
amounts=[100],
fee=1,
xmss_pk=self.alice.pk
)
tx.sign(self.alice)
self.assertTrue(tx.validate_or_raise())
tx._data.transaction_hash = b'abc'
# Should fail, as we have modified with invalid transaction_hash
with self.assertRaises(ValueError):
tx.validate_or_raise()
@patch('qrl.core.txs.Transaction.config')
def test_validate_tx_invalid(self, m_config, m_logger):
# Test all the things that could make a TransferTransaction invalid
self.tx.sign(self.alice)
# Validation in creation, Protobuf, type conversion etc. gets in our way all the time!
# So to get dirty data to the validate() function, we need PropertyMocks
with patch('qrl.core.txs.TransferTransaction.TransferTransaction.amounts',
new_callable=PropertyMock) as m_amounts:
# TX amount of 0 shouldn't be allowed.
m_amounts.return_value = [0]
with self.assertRaises(ValueError):
self.tx.validate_or_raise()
with patch('qrl.core.txs.TransferTransaction.TransferTransaction.fee', new_callable=PropertyMock) as m_fee:
m_fee.return_value = -1
with self.assertRaises(ValueError):
self.tx.validate_or_raise()
with patch('qrl.core.txs.TransferTransaction.TransferTransaction.addrs_to',
new_callable=PropertyMock) as m_addrs_to:
with patch('qrl.core.txs.TransferTransaction.TransferTransaction.amounts',
new_callable=PropertyMock) as m_amounts:
# Validation could fail because len(m_addrs_to) != len(m_amounts),
# or if len(m_addrs_to) > transaction_multi_output_limit.
# This second patch level is to make sure the only the latter case happens.
m_amounts = [100, 100, 100, 100]
m_config.dev.transaction_multi_output_limit = 3
m_addrs_to.return_value = [2, 2, 2, 2]
with self.assertRaises(ValueError):
self.tx.validate_or_raise()
with patch('qrl.core.txs.TransferTransaction.TransferTransaction.addrs_to',
new_callable=PropertyMock) as m_addrs_to:
# len(addrs_to) must equal len(amounts)
m_addrs_to.return_value = [2, 2]
with self.assertRaises(ValueError):
self.tx.validate_or_raise()
with patch('qrl.core.txs.TransferTransaction.TransferTransaction.addr_from',
new_callable=PropertyMock) as m_addr_from:
m_addr_from.return_value = b'If this isnt invalid Ill eat my shoe'
with self.assertRaises(ValueError):
self.tx.validate_or_raise()
with patch('qrl.core.txs.TransferTransaction.TransferTransaction.addrs_to',
new_callable=PropertyMock) as m_addrs_to:
with patch('qrl.core.txs.TransferTransaction.TransferTransaction.amounts',
new_callable=PropertyMock) as m_amounts:
m_amounts.return_value = [100, 100]
m_addrs_to.return_value = [self.bob.address, b'If this isnt invalid Ill eat my shoe']
with self.assertRaises(ValueError):
self.tx.validate_or_raise()
def test_validate_extended(self, m_logger):
"""
validate_extended() handles these parts of the validation:
1. Master/slave
2. balance, amount + fee from AddressState
3. OTS key reuse from AddressState
:return:
"""
m_addr_state = Mock(autospec=AddressState, balance=200)
m_addr_from_pk_state = Mock(autospec=AddressState)
m_addr_from_pk_state.ots_key_reuse.return_value = False
self.tx.validate_slave = Mock(autospec=Transaction.validate_slave, return_value=True)
self.tx.sign(self.alice)
result = self.tx.validate_extended(m_addr_state, m_addr_from_pk_state)
self.assertTrue(result)
# Suppose there was ots key reuse. The function should then return false.
m_addr_from_pk_state.ots_key_reuse.return_value = True
result = self.tx.validate_extended(m_addr_state, m_addr_from_pk_state)
self.assertFalse(result)
# Reset conditions from above
m_addr_from_pk_state.ots_key_reuse.return_value = False
# Suppose the slave XMSS address does not have permission for this type of Transaction. It should return False.
self.tx.validate_slave.return_value = False
result = self.tx.validate_extended(m_addr_state, m_addr_from_pk_state)
self.assertFalse(result)
# Reset conditions from above
self.tx.validate_slave.return_value = True
# Suppose the address doesn't have enough coins.
m_addr_state.balance = 99
result = self.tx.validate_extended(m_addr_state, m_addr_from_pk_state)
self.assertFalse(result)
def test_validate_transaction_pool(self, m_logger):
"""
Two TransferTransactions. Although they're the same, they are signed with different OTS indexes.
Therefore they should not conflict when they are both in the TransactionPool.
:return:
"""
tx = self.tx
tx2 = TransferTransaction.create(
addrs_to=[self.bob.address],
amounts=[100],
fee=1,
xmss_pk=self.alice.pk
)
tx.sign(self.alice)
tx2.sign(self.alice)
tx_info = Mock(autospec=TransactionInfo, transaction=tx)
tx2_info = Mock(autospec=TransactionInfo, transaction=tx2)
transaction_pool = [(replacement_getTime(), tx_info), (replacement_getTime(), tx2_info)]
result = tx.validate_transaction_pool(transaction_pool)
self.assertTrue(result)
def test_validate_transaction_pool_reusing_ots_index(self, m_logger):
"""
Two different TransferTransactions. They are signed with the same OTS indexe, from the same public key.
Therefore they should conflict.
:return:
"""
tx = self.tx
tx2 = TransferTransaction.create(
addrs_to=[self.bob.address],
amounts=[100],
fee=5,
xmss_pk=self.alice.pk
)
# alice_clone's OTS index is still at 10, while self.alice will be at 11 after signing.
alice_clone = get_alice_xmss()
alice_clone.set_ots_index(10)
tx.sign(self.alice)
tx2.sign(alice_clone)
tx_info = Mock(autospec=TransactionInfo, transaction=tx)
tx2_info = Mock(autospec=TransactionInfo, transaction=tx2)
transaction_pool = [(replacement_getTime(), tx_info), (replacement_getTime(), tx2_info)]
result = tx.validate_transaction_pool(transaction_pool)
self.assertFalse(result)
def test_validate_transaction_pool_different_pk_same_ots_index(self, m_logger):
"""
Two TransferTransactions. They are signed with the same OTS indexes, but from different public keys.
Therefore they should NOT conflict.
:return:
"""
tx = self.tx
tx2 = TransferTransaction.create(
addrs_to=[self.bob.address],
amounts=[100],
fee=1,
xmss_pk=self.bob.pk
)
tx.sign(self.alice)
tx2.sign(self.bob)
tx_info = Mock(autospec=TransactionInfo, transaction=tx)
tx2_info = Mock(autospec=TransactionInfo, transaction=tx2)
transaction_pool = [(replacement_getTime(), tx_info), (replacement_getTime(), tx2_info)]
result = tx.validate_transaction_pool(transaction_pool)
self.assertTrue(result)
def test_apply_state_changes(self, m_logger):
"""
apply_state_changes() is the part that actually updates everybody's balances.
Then it forwards the addresses_state to _apply_state_changes_for_PK(), which updates everybody's addresses's
nonce, OTS key index, and associated TX hashes
If there is no AddressState for a particular Address, nothing is done.
"""
addresses_state = {
self.alice.address: Mock(autospec=AddressState, name='alice AddressState', transaction_hashes=[],
balance=200),
self.bob.address: Mock(autospec=AddressState, name='bob AddressState', transaction_hashes=[], balance=0),
self.slave.address: Mock(autospec=AddressState, name='slave AddressState', transaction_hashes=[], balance=0)
}
self.tx._apply_state_changes_for_PK = Mock(autospec=TransferTransaction._apply_state_changes_for_PK)
self.tx.apply_state_changes(addresses_state)
# Now Alice should have 99 coins left (200 - 100 - 1) and Bob should have 100 coins.
self.assertEqual(99, addresses_state[self.alice.address].balance)
self.assertEqual(100, addresses_state[self.bob.address].balance)
self.tx._apply_state_changes_for_PK.assert_called_once()
# If there are no AddressStates related to the Addresses in this transaction, do nothing.
self.tx._apply_state_changes_for_PK.reset_mock()
addresses_state_dummy = {
b'a': 'ABC',
b'b': 'DEF'
}
self.tx.apply_state_changes(addresses_state_dummy)
self.assertEqual(addresses_state_dummy, {b'a': 'ABC', b'b': 'DEF'})
self.tx._apply_state_changes_for_PK.assert_called_once()
def test_apply_state_changes_tx_sends_to_self(self, m_logger):
"""
If you send coins to yourself, you should only lose the fee for the Transaction.
"""
addresses_state = {
self.alice.address: Mock(autospec=AddressState, name='alice AddressState', transaction_hashes=[],
balance=200),
self.bob.address: Mock(autospec=AddressState, name='bob AddressState', transaction_hashes=[], balance=0),
self.slave.address: Mock(autospec=AddressState, name='slave AddressState', transaction_hashes=[], balance=0)
}
tx = TransferTransaction.create(
addrs_to=[self.alice.address],
amounts=[100],
fee=1,
xmss_pk=self.alice.pk
)
tx._apply_state_changes_for_PK = Mock(autospec=TransferTransaction._revert_state_changes_for_PK)
tx.apply_state_changes(addresses_state)
self.assertEqual(199, addresses_state[self.alice.address].balance)
self.assertIn(tx.txhash, addresses_state[self.alice.address].transaction_hashes)
def test_apply_state_changes_multi_send(self, m_logger):
"""
Test that apply_state_changes() also works with multiple recipients.
"""
addresses_state = {
self.alice.address: Mock(autospec=AddressState, name='alice AddressState', transaction_hashes=[],
balance=200),
self.bob.address: Mock(autospec=AddressState, name='bob AddressState', transaction_hashes=[], balance=0),
self.slave.address: Mock(autospec=AddressState, name='slave AddressState', transaction_hashes=[], balance=0)
}
tx_multisend = TransferTransaction.create(
addrs_to=[self.bob.address, self.slave.address],
amounts=[20, 20],
fee=1,
xmss_pk=self.alice.pk
)
tx_multisend._apply_state_changes_for_PK = Mock(autospec=TransferTransaction._apply_state_changes_for_PK)
tx_multisend.apply_state_changes(addresses_state)
# Now Alice should have 159 coins left (200 - 20 - 20 - 1) and Bob should have 100 coins.
self.assertEqual(159, addresses_state[self.alice.address].balance)
self.assertEqual(20, addresses_state[self.bob.address].balance)
self.assertEqual(20, addresses_state[self.slave.address].balance)
tx_multisend._apply_state_changes_for_PK.assert_called_once()
def test_apply_state_changes_for_PK(self, m_logger):
"""
This updates the node's AddressState database with which OTS index a particular address should be on, and what
tx hashes is this address associated with.
Curiously enough, if the TX was signed by a master XMSS tree, it doesn't add this tx's txhash to the list of
txs that address is associated with.
:return:
"""
addr_state = {
self.alice.address: Mock(autospec=AddressState)
}
old_ots_index = self.alice.ots_index
self.tx.sign(self.alice)
self.tx._apply_state_changes_for_PK(addr_state)
addr_state[self.alice.address].increase_nonce.assert_called_once()
addr_state[self.alice.address].set_ots_key.assert_called_once_with(old_ots_index)
def test_apply_state_changes_for_PK_master_slave_XMSS(self, m_logger):
"""
If the TX was signed by a slave XMSS, the slave XMSS's AddressState should be updated (not the master's).
:return:
"""
tx = TransferTransaction.create(
addrs_to=[self.bob.address],
amounts=[100],
fee=1,
xmss_pk=self.slave.pk,
master_addr=self.alice.address
)
addr_state = {
self.alice.address: Mock(autospec=AddressState, name='alice AddressState'),
self.slave.address: Mock(autospec=AddressState, name='slave AddressState')
}
old_ots_index = self.slave.ots_index
tx.sign(self.slave)
tx._apply_state_changes_for_PK(addr_state)
addr_state[self.slave.address].increase_nonce.assert_called_once()
addr_state[self.slave.address].set_ots_key.assert_called_once_with(old_ots_index)
addr_state[self.slave.address].transaction_hashes.append.assert_called_once()
def test_revert_state_changes(self, m_logger):
"""
Alice has sent 100 coins to Bob, using 1 as Transaction fee. Now we need to undo this.
"""
addresses_state = {
self.alice.address: Mock(autospec=AddressState, name='alice AddressState',
transaction_hashes=[self.tx.txhash],
balance=99),
self.bob.address: Mock(autospec=AddressState, name='bob AddressState', transaction_hashes=[self.tx.txhash],
balance=100),
self.slave.address: Mock(autospec=AddressState, name='slave AddressState', transaction_hashes=[], balance=0)
}
unused_chain_manager_mock = Mock(autospec=ChainManager, name='unused ChainManager')
self.tx._revert_state_changes_for_PK = Mock(autospec=TransferTransaction._revert_state_changes_for_PK)
self.tx.revert_state_changes(addresses_state, unused_chain_manager_mock)
self.assertEqual(200, addresses_state[self.alice.address].balance)
self.assertEqual(0, addresses_state[self.bob.address].balance)
self.assertEqual([], addresses_state[self.alice.address].transaction_hashes)
self.assertEqual([], addresses_state[self.bob.address].transaction_hashes)
self.tx._revert_state_changes_for_PK.assert_called_once()
# If there are no AddressStates related to the Addresses in this transaction, do nothing.
self.tx._revert_state_changes_for_PK.reset_mock()
addresses_state_dummy = {
b'a': 'ABC',
b'b': 'DEF'
}
self.tx.revert_state_changes(addresses_state_dummy, unused_chain_manager_mock)
self.assertEqual(addresses_state_dummy, {b'a': 'ABC', b'b': 'DEF'})
self.tx._revert_state_changes_for_PK.assert_called_once()
def test_revert_state_changes_multi_send(self, m_logger):
"""
Alice has sent 20 coins to Bob and Slave each, using 1 as Transaction fee. Now we need to undo this.
"""
addresses_state = {
self.alice.address: Mock(autospec=AddressState, name='alice AddressState',
transaction_hashes=[self.tx.txhash],
balance=159),
self.bob.address: Mock(autospec=AddressState, name='bob AddressState', transaction_hashes=[self.tx.txhash],
balance=20),
self.slave.address: Mock(autospec=AddressState, name='slave AddressState',
transaction_hashes=[self.tx.txhash], balance=20)
}
unused_chain_manager_mock = Mock(autospec=ChainManager, name='unused ChainManager')
tx_multisend = TransferTransaction.create(
addrs_to=[self.bob.address, self.slave.address],
amounts=[20, 20],
fee=1,
xmss_pk=self.alice.pk
)
tx_multisend._revert_state_changes_for_PK = Mock(autospec=TransferTransaction._revert_state_changes_for_PK)
tx_multisend.revert_state_changes(addresses_state, unused_chain_manager_mock)
self.assertEqual(200, addresses_state[self.alice.address].balance)
self.assertEqual(0, addresses_state[self.bob.address].balance)
self.assertEqual(0, addresses_state[self.slave.address].balance)
self.assertEqual([], addresses_state[self.alice.address].transaction_hashes)
self.assertEqual([], addresses_state[self.bob.address].transaction_hashes)
self.assertEqual([], addresses_state[self.slave.address].transaction_hashes)
tx_multisend._revert_state_changes_for_PK.assert_called_once()
def test_revert_state_changes_tx_sends_to_self(self, m_logger):
"""
Alice sent coins to herself, but she still lost the Transaction fee. Undo this.
"""
addresses_state = {
self.alice.address: Mock(autospec=AddressState, name='alice AddressState',
transaction_hashes=[self.tx.txhash],
balance=199),
self.bob.address: Mock(autospec=AddressState, name='bob AddressState', transaction_hashes=[],
balance=0),
self.slave.address: Mock(autospec=AddressState, name='slave AddressState', transaction_hashes=[], balance=0)
}
unused_chain_manager_mock = Mock(autospec=ChainManager, name='unused ChainManager')
tx = TransferTransaction.create(
addrs_to=[self.alice.address],
amounts=[100],
fee=1,
xmss_pk=self.alice.pk
)
tx._revert_state_changes_for_PK = Mock(autospec=TransferTransaction._revert_state_changes_for_PK)
tx.revert_state_changes(addresses_state, unused_chain_manager_mock)
self.assertEqual(200, addresses_state[self.alice.address].balance)
self.assertEqual(0, addresses_state[self.bob.address].balance)
self.assertEqual([], addresses_state[self.alice.address].transaction_hashes)
self.assertEqual([], addresses_state[self.bob.address].transaction_hashes)
tx._revert_state_changes_for_PK.assert_called_once()
def test_revert_state_changes_for_PK(self, m_logger):
"""
This is just an undo function.
:return:
"""
tx = TransferTransaction.create(
addrs_to=[self.bob.address],
amounts=[100],
fee=1,
xmss_pk=self.alice.pk
)
addr_state = {
self.alice.address: Mock(autospec=AddressState)
}
tx.sign(self.alice)
tx._revert_state_changes_for_PK(addr_state, Mock(name='unused State Mock'))
addr_state[self.alice.address].decrease_nonce.assert_called_once()
addr_state[self.alice.address].unset_ots_key.assert_called_once()
def test_revert_state_changes_for_PK_master_slave_XMSS(self, m_logger):
tx = TransferTransaction.create(
addrs_to=[self.bob.address],
amounts=[100],
fee=1,
xmss_pk=self.slave.pk,
master_addr=self.alice.address
)
addr_state = {
self.alice.address: Mock(autospec=AddressState, name='alice AddressState'),
self.slave.address: Mock(autospec=AddressState, name='slave AddressState')
}
tx.sign(self.slave)
tx._revert_state_changes_for_PK(addr_state, Mock(name='unused State Mock'))
addr_state[self.slave.address].decrease_nonce.assert_called_once()
addr_state[self.slave.address].unset_ots_key.assert_called_once()
addr_state[self.slave.address].transaction_hashes.remove.assert_called_once()
def test_affected_address(self, m_logger):
# The default transaction params involve only two addresses.
affected_addresses = set()
self.tx.set_affected_address(affected_addresses)
self.assertEqual(2, len(affected_addresses))
# This transaction should involve 3 addresses.
affected_addresses = set()
tx = TransferTransaction.create(
addrs_to=[self.bob.address, self.slave.address],
amounts=[100, 100],
fee=1,
xmss_pk=self.alice.pk
)
tx.set_affected_address(affected_addresses)
self.assertEqual(3, len(affected_addresses))
| en | 0.926692 | # Alice sending coins to Bob # Test that common Transaction components were copied over. # Test that specific content was copied over. # If we change amount, fee, addr_from, addr_to, (maybe include xmss stuff) txhash should change. # Here we use the tx already defined in setUp() for convenience. # We must sign the tx before validation will work. # We have not touched the tx: validation should pass. # Should fail, as we have modified with invalid transaction_hash # Test all the things that could make a TransferTransaction invalid # Validation in creation, Protobuf, type conversion etc. gets in our way all the time! # So to get dirty data to the validate() function, we need PropertyMocks # TX amount of 0 shouldn't be allowed. # Validation could fail because len(m_addrs_to) != len(m_amounts), # or if len(m_addrs_to) > transaction_multi_output_limit. # This second patch level is to make sure the only the latter case happens. # len(addrs_to) must equal len(amounts) validate_extended() handles these parts of the validation: 1. Master/slave 2. balance, amount + fee from AddressState 3. OTS key reuse from AddressState :return: # Suppose there was ots key reuse. The function should then return false. # Reset conditions from above # Suppose the slave XMSS address does not have permission for this type of Transaction. It should return False. # Reset conditions from above # Suppose the address doesn't have enough coins. Two TransferTransactions. Although they're the same, they are signed with different OTS indexes. Therefore they should not conflict when they are both in the TransactionPool. :return: Two different TransferTransactions. They are signed with the same OTS indexe, from the same public key. Therefore they should conflict. :return: # alice_clone's OTS index is still at 10, while self.alice will be at 11 after signing. Two TransferTransactions. They are signed with the same OTS indexes, but from different public keys. Therefore they should NOT conflict. :return: apply_state_changes() is the part that actually updates everybody's balances. Then it forwards the addresses_state to _apply_state_changes_for_PK(), which updates everybody's addresses's nonce, OTS key index, and associated TX hashes If there is no AddressState for a particular Address, nothing is done. # Now Alice should have 99 coins left (200 - 100 - 1) and Bob should have 100 coins. # If there are no AddressStates related to the Addresses in this transaction, do nothing. If you send coins to yourself, you should only lose the fee for the Transaction. Test that apply_state_changes() also works with multiple recipients. # Now Alice should have 159 coins left (200 - 20 - 20 - 1) and Bob should have 100 coins. This updates the node's AddressState database with which OTS index a particular address should be on, and what tx hashes is this address associated with. Curiously enough, if the TX was signed by a master XMSS tree, it doesn't add this tx's txhash to the list of txs that address is associated with. :return: If the TX was signed by a slave XMSS, the slave XMSS's AddressState should be updated (not the master's). :return: Alice has sent 100 coins to Bob, using 1 as Transaction fee. Now we need to undo this. # If there are no AddressStates related to the Addresses in this transaction, do nothing. Alice has sent 20 coins to Bob and Slave each, using 1 as Transaction fee. Now we need to undo this. Alice sent coins to herself, but she still lost the Transaction fee. Undo this. This is just an undo function. :return: # The default transaction params involve only two addresses. # This transaction should involve 3 addresses. | 2.311695 | 2 |
Sawtooth/families/suse/tests/suse_tests.py | ishtjot/susereumutep | 2 | 6623066 | <filename>Sawtooth/families/suse/tests/suse_tests.py
import unittest
import os
import sys
import getpass
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.realpath(__file__))))
from client.suse_client import SuseClient #pylint: disable=import-error
from client.suse_exceptions import SuseException #pylint: disable=import-error
class SimpleTest(unittest.TestCase):
def setUp(self):
#get default values
DISTRIBUTION_NAME = 'suserum-suse'
HOME = os.getenv('SAWTOOTH_HOME')
DEFAULT_URL = 'http://127.0.0.1:8008'
#get user key
username = getpass.getuser()
home = os.path.expanduser("~")
key_dir = os.path.join(home, ".sawtooth", "keys")
keyfile = '{}/{}.priv'.format(key_dir, username)
self.client = SuseClient(base_url=DEFAULT_URL, keyfile=keyfile, work_path=HOME)
#get test txn_id
self.txn = self.client.list()
for entry in self.txn.keys():
self.txn_id = entry
break
def test_suse(self):
response = self.client.suse(new_health=99, github_id="1234")
self.assertNotEqual(response, None)
def test_list(self):
response = self.client.list()
self.assertNotEqual(response, None)
def test_list_incorrect_type(self):
response = self.client.list("noType")
self.assertEqual(len(response), 0)
def test_bad_suse(self):
self.assertRaises(SuseException, self.client.code_analysis, "health")
if __name__ == '__main__':
unittest.main()
| <filename>Sawtooth/families/suse/tests/suse_tests.py
import unittest
import os
import sys
import getpass
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.realpath(__file__))))
from client.suse_client import SuseClient #pylint: disable=import-error
from client.suse_exceptions import SuseException #pylint: disable=import-error
class SimpleTest(unittest.TestCase):
def setUp(self):
#get default values
DISTRIBUTION_NAME = 'suserum-suse'
HOME = os.getenv('SAWTOOTH_HOME')
DEFAULT_URL = 'http://127.0.0.1:8008'
#get user key
username = getpass.getuser()
home = os.path.expanduser("~")
key_dir = os.path.join(home, ".sawtooth", "keys")
keyfile = '{}/{}.priv'.format(key_dir, username)
self.client = SuseClient(base_url=DEFAULT_URL, keyfile=keyfile, work_path=HOME)
#get test txn_id
self.txn = self.client.list()
for entry in self.txn.keys():
self.txn_id = entry
break
def test_suse(self):
response = self.client.suse(new_health=99, github_id="1234")
self.assertNotEqual(response, None)
def test_list(self):
response = self.client.list()
self.assertNotEqual(response, None)
def test_list_incorrect_type(self):
response = self.client.list("noType")
self.assertEqual(len(response), 0)
def test_bad_suse(self):
self.assertRaises(SuseException, self.client.code_analysis, "health")
if __name__ == '__main__':
unittest.main()
| en | 0.162343 | #pylint: disable=import-error #pylint: disable=import-error #get default values #get user key #get test txn_id | 2.473741 | 2 |
zdiscord/service/integration/chat/discord/macros/General.py | xxdunedainxx/zdiscord | 0 | 6623067 | <filename>zdiscord/service/integration/chat/discord/macros/General.py
from zdiscord.service.messaging.Events import IEvent
async def help_msg(help_msg: str,event: IEvent):
await event.context['message_object'].channel.send(help_msg) | <filename>zdiscord/service/integration/chat/discord/macros/General.py
from zdiscord.service.messaging.Events import IEvent
async def help_msg(help_msg: str,event: IEvent):
await event.context['message_object'].channel.send(help_msg) | none | 1 | 1.599779 | 2 | |
btest1/cudatest.py | originlab/Noho-Training | 0 | 6623068 | import originpro as op
from numba import cuda
import numpy as np
@cuda.jit
def cudakernel0(array):
for i in range(array.size):
array[i] += 0.5
array = np.array([0, 1], np.float32)
print('Initial array:', array)
print('Kernel launch: cudakernel0[1, 1](array)')
cudakernel0[1, 1](array)
print('Updated array:',array)
print('hello') | import originpro as op
from numba import cuda
import numpy as np
@cuda.jit
def cudakernel0(array):
for i in range(array.size):
array[i] += 0.5
array = np.array([0, 1], np.float32)
print('Initial array:', array)
print('Kernel launch: cudakernel0[1, 1](array)')
cudakernel0[1, 1](array)
print('Updated array:',array)
print('hello') | none | 1 | 2.466458 | 2 | |
submissions/abc146/c.py | m-star18/atcoder | 1 | 6623069 | <gh_stars>1-10
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
sys.setrecursionlimit(10 ** 7)
a, b, x = map(int, readline().split())
ans = 0
for d in range(1, 20):
c = (x - b * d) // a
if c >= 0:
ans = max(ans, min(c, 10 ** d - 1))
print(min(ans, 10 ** 9))
| import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
sys.setrecursionlimit(10 ** 7)
a, b, x = map(int, readline().split())
ans = 0
for d in range(1, 20):
c = (x - b * d) // a
if c >= 0:
ans = max(ans, min(c, 10 ** d - 1))
print(min(ans, 10 ** 9)) | none | 1 | 2.514071 | 3 | |
Instrumentos/Codigos/deprecated/Q4/src/models/Repo.py | aylton-almeida/TIS6 | 0 | 6623070 | from __future__ import annotations
import time
from datetime import datetime
from pandas.core import series
from src.models.AuthToken import AuthToken
from src.models.Issue import Issue
from src.models.Pr import Pr
from src.utils.BundlePhobia import measure_pkg
from src.utils.Graphql import Graphql
from src.utils.Node import search_package
from src.utils.TimeCountdown import sleep
class Repo:
cursor: str
name_with_owner: str
url: str
stargazer_count: str
topic: str
created_at: datetime
dependencies: int
weight: float
gzipped: float
issue_ratio: float
prs_ratio: float
def __init__(self, data: dict) -> None:
self.cursor = data.get('cursor')
self.name_with_owner = data.get('nameWithOwner')
self.url = data.get('url')
self.stargazer_count = data.get('stargazerCount')
self.topic = data.get('topic')
self.create_at = data.get('createdAt')
def get_owner_and_name(self) -> tuple[str, str]:
return self.name_with_owner.split('/')
def set_bug_issues(self, graphql: Graphql, token: AuthToken):
owner, name = self.get_owner_and_name()
# get bug or error labels
labels_query = graphql.get_labels_query(owner, name)
labels = graphql.get_labels_data(labels_query, token.get_token())
# get issues
issues: list[Issue] = []
has_next_page = True
while has_next_page:
try:
# get query
issue_query = graphql.get_issues_query(owner, name, labels)
# fetch issues
new_issues, has_next_page = graphql.get_issues_data(
issue_query, token.get_token())
# add issues to list
issues += [Issue.from_github(issue) for issue in new_issues]
# sleep a bit
time.sleep(1)
except Exception as err:
print(err)
sleep(600)
token.next_token()
# calculate issue ratio
if issues:
self.issue_ratio = len(
[issue for issue in issues if issue.state == 'OPEN']) / len(issues)
else:
self.issue_ratio = 0
def set_bug_prs(self, graphql: Graphql, token: AuthToken):
owner, name = self.get_owner_and_name()
# get bug or error labels
labels_query = graphql.get_labels_query(owner, name)
labels = graphql.get_labels_data(labels_query, token.get_token())
# get prs
prs: list[Pr] = []
has_next_page = True
while has_next_page:
try:
# get query
pr_query = graphql.get_prs_query(owner, name, labels)
# fetch prs
new_prs, has_next_page = graphql.get_prs_data(
pr_query, token.get_token())
# add prs to list
for new_pr in new_prs:
pr = Pr.from_github(new_pr)
has_any_label = False
for label in pr.labels:
if label in labels:
has_any_label = True
if 'bug' in pr.body or 'error' in pr.body or 'fix' in pr.body or has_any_label:
prs.append(pr)
# sleep a bit
time.sleep(1)
except Exception as err:
print(err)
sleep(600)
token.next_token()
# calculate prs ratio
if prs:
self.prs_ratio = len(
[pr for pr in prs if pr.state == 'MERGED']) / len(prs)
else:
self.prs_ratio = 0
def set_weight(self, graphql: Graphql, token: str):
# get npm package name
owner, name = self.get_owner_and_name()
pkg_name = search_package(name)
if not pkg_name:
pkg_name = name.lower()
dependencies, weight, gzipped = measure_pkg(pkg_name)
if not dependencies and not weight and not gzipped:
query = graphql.get_disk_usage_query(owner, name)
usage = graphql.get_disk_usage_data(query, token)
weight = usage
dependencies = -1
gzipped = -1
self.dependencies = int(dependencies)
self.weight = float(weight)
self.gzipped = float(gzipped)
@staticmethod
def from_dataframe(data: series) -> Repo:
return Repo({
'cursor': data['cursor'],
'nameWithOwner': data['name_with_owner'],
'url': data['url'],
'stargazerCount': data['stargazer_count'],
'topic': data['topic'],
'createdAt': datetime.fromisoformat(data['createdAt'])
})
| from __future__ import annotations
import time
from datetime import datetime
from pandas.core import series
from src.models.AuthToken import AuthToken
from src.models.Issue import Issue
from src.models.Pr import Pr
from src.utils.BundlePhobia import measure_pkg
from src.utils.Graphql import Graphql
from src.utils.Node import search_package
from src.utils.TimeCountdown import sleep
class Repo:
cursor: str
name_with_owner: str
url: str
stargazer_count: str
topic: str
created_at: datetime
dependencies: int
weight: float
gzipped: float
issue_ratio: float
prs_ratio: float
def __init__(self, data: dict) -> None:
self.cursor = data.get('cursor')
self.name_with_owner = data.get('nameWithOwner')
self.url = data.get('url')
self.stargazer_count = data.get('stargazerCount')
self.topic = data.get('topic')
self.create_at = data.get('createdAt')
def get_owner_and_name(self) -> tuple[str, str]:
return self.name_with_owner.split('/')
def set_bug_issues(self, graphql: Graphql, token: AuthToken):
owner, name = self.get_owner_and_name()
# get bug or error labels
labels_query = graphql.get_labels_query(owner, name)
labels = graphql.get_labels_data(labels_query, token.get_token())
# get issues
issues: list[Issue] = []
has_next_page = True
while has_next_page:
try:
# get query
issue_query = graphql.get_issues_query(owner, name, labels)
# fetch issues
new_issues, has_next_page = graphql.get_issues_data(
issue_query, token.get_token())
# add issues to list
issues += [Issue.from_github(issue) for issue in new_issues]
# sleep a bit
time.sleep(1)
except Exception as err:
print(err)
sleep(600)
token.next_token()
# calculate issue ratio
if issues:
self.issue_ratio = len(
[issue for issue in issues if issue.state == 'OPEN']) / len(issues)
else:
self.issue_ratio = 0
def set_bug_prs(self, graphql: Graphql, token: AuthToken):
owner, name = self.get_owner_and_name()
# get bug or error labels
labels_query = graphql.get_labels_query(owner, name)
labels = graphql.get_labels_data(labels_query, token.get_token())
# get prs
prs: list[Pr] = []
has_next_page = True
while has_next_page:
try:
# get query
pr_query = graphql.get_prs_query(owner, name, labels)
# fetch prs
new_prs, has_next_page = graphql.get_prs_data(
pr_query, token.get_token())
# add prs to list
for new_pr in new_prs:
pr = Pr.from_github(new_pr)
has_any_label = False
for label in pr.labels:
if label in labels:
has_any_label = True
if 'bug' in pr.body or 'error' in pr.body or 'fix' in pr.body or has_any_label:
prs.append(pr)
# sleep a bit
time.sleep(1)
except Exception as err:
print(err)
sleep(600)
token.next_token()
# calculate prs ratio
if prs:
self.prs_ratio = len(
[pr for pr in prs if pr.state == 'MERGED']) / len(prs)
else:
self.prs_ratio = 0
def set_weight(self, graphql: Graphql, token: str):
# get npm package name
owner, name = self.get_owner_and_name()
pkg_name = search_package(name)
if not pkg_name:
pkg_name = name.lower()
dependencies, weight, gzipped = measure_pkg(pkg_name)
if not dependencies and not weight and not gzipped:
query = graphql.get_disk_usage_query(owner, name)
usage = graphql.get_disk_usage_data(query, token)
weight = usage
dependencies = -1
gzipped = -1
self.dependencies = int(dependencies)
self.weight = float(weight)
self.gzipped = float(gzipped)
@staticmethod
def from_dataframe(data: series) -> Repo:
return Repo({
'cursor': data['cursor'],
'nameWithOwner': data['name_with_owner'],
'url': data['url'],
'stargazerCount': data['stargazer_count'],
'topic': data['topic'],
'createdAt': datetime.fromisoformat(data['createdAt'])
})
| en | 0.649648 | # get bug or error labels # get issues # get query # fetch issues # add issues to list # sleep a bit # calculate issue ratio # get bug or error labels # get prs # get query # fetch prs # add prs to list # sleep a bit # calculate prs ratio # get npm package name | 2.191609 | 2 |
ymir/backend/src/ymir_app/app/db/base.py | Zhang-SJ930104/ymir | 64 | 6623071 | # Import all the models, so that Base has them before being
# imported by Alembic
from app.db.base_class import Base # noqa
from app.models.dataset import Dataset # noqa
from app.models.model import Model # noqa
from app.models.task import Task # noqa
from app.models.user import User # noqa
| # Import all the models, so that Base has them before being
# imported by Alembic
from app.db.base_class import Base # noqa
from app.models.dataset import Dataset # noqa
from app.models.model import Model # noqa
from app.models.task import Task # noqa
from app.models.user import User # noqa
| en | 0.875407 | # Import all the models, so that Base has them before being # imported by Alembic # noqa # noqa # noqa # noqa # noqa | 1.443677 | 1 |
tests/test_tftp_client.py | AstralPresence/pyTFTP | 10 | 6623072 | <reponame>AstralPresence/pyTFTP<filename>tests/test_tftp_client.py
from typing import List, Tuple
from unittest.mock import patch, call, _Call
import tftp
from tests.tftp_test_case import TFTPTestCase
class TestTFTPClient(TFTPTestCase):
def setUp(self):
super(TestTFTPClient, self).setUp()
self.client = tftp.TFTPClient(*self.srv_addr)
self.client.__enter__()
def tearDown(self):
self.client.__exit__(None, None, None)
super(TestTFTPClient, self).tearDown()
def test_setup(self):
self.socket.socket.assert_called_with(
self.socket.AF_INET, self.socket.SOCK_DGRAM)
def __simple_test(
self, recv_values: List[tftp.Packet], func: str, args: Tuple,
expected_sendto: List[_Call], expected_data: bytes = None) -> None:
"""Test GET/PUT operation without expecting any errors.
:param recv_values: list of values that should be returned by recvfrom()
:param func: function to use: 'get' or 'put'
:param args: arguments for the function
:param expected_sendto: expected packets sent (as a list of arguments
for the sendto() function)
:param expected_data: expected data to be returned by GET
"""
self.socket_instance.recvfrom.side_effect = recv_values
assert func in ['get', 'put']
data = None
if func == 'get':
data = self.client.get_file(*args)
elif func == 'put':
self.client.put_file(*args)
self.assertEqual(
expected_sendto, self.socket_instance.sendto.call_args_list)
if func == 'get':
self.assertEqual(expected_data, data)
def test_get_empty_file(self):
expected_sendto = [
call(b'\x00\x01test !@#\x00octet\x00', self.srv_addr),
call(b'\x00\x04\x00\x01', self.addr)]
self.__simple_test(
[(b'\x00\x03\x00\x01', self.addr)], 'get', ('test !@#',),
expected_sendto, b'')
def test_get_empty_file_random_blockid(self):
recv_values = [
(b'\x00\x03\xca\xfe', self.addr),
(b'\x00\x03\x00\x01', self.addr)]
expected_sendto = [
call(b'\x00\x01test\x00octet\x00', self.srv_addr),
call(b'\x00\x04\x00\x00', self.addr),
call(b'\x00\x04\x00\x01', self.addr)]
self.__simple_test(
recv_values, 'get', ('test',),
expected_sendto, b'')
def test_get_short_file(self):
expected_sendto = [
call(b'\x00\x01test\x00octet\x00', self.srv_addr),
call(b'\x00\x04\x00\x01', self.addr)]
self.__simple_test(
[(b'\x00\x03\x00\x01test contents', self.addr)], 'get', ('test',),
expected_sendto, b'test contents')
def test_get_long_file(self):
recv_values = [
(b'\x00\x03\x00\x01' + b'a' * 512, self.addr),
(b'\x00\x03\x00\x02' + b'a' * 511, self.addr)]
expected_sendto = [
call(b'\x00\x01test\x00octet\x00', self.srv_addr),
call(b'\x00\x04\x00\x01', self.addr),
call(b'\x00\x04\x00\x02', self.addr)]
self.__simple_test(
recv_values, 'get', ('test',),
expected_sendto, b'a' * 1023)
def test_get_huge_file(self):
recv_values = []
expected_sendto = [
call(b'\x00\x01test\x00octet\x00', self.srv_addr)]
for i in range(1, 65537):
block_id = (i % 65536).to_bytes(2, byteorder='big')
recv_values.append(
(b'\x00\x03' + block_id +
b'a' * (0 if i == 65536 else 512), self.addr))
expected_sendto.append(call(b'\x00\x04' + block_id, self.addr))
self.__simple_test(recv_values, 'get', ('test',),
expected_sendto, b'a' * (65535 * 512))
def test_get_with_blksize_option(self):
self.client = tftp.TFTPClient(*self.srv_addr, 8192)
recv_values = [
(b'\x00\x06blksize\x008192\x00', self.addr),
(b'\x00\x03\x00\x01' + b'a' * 8192, self.addr),
(b'\x00\x03\x00\x02' + b'a' * 8191, self.addr)]
expected_sendto = [
call(b'\x00\x01test\x00octet\x00blksize\x008192\x00',
self.srv_addr),
call(b'\x00\x04\x00\x00', self.addr),
call(b'\x00\x04\x00\x01', self.addr),
call(b'\x00\x04\x00\x02', self.addr)]
self.__simple_test(recv_values, 'get', ('test',),
expected_sendto, b'a' * 16383)
def test_get_with_windowsize(self):
self.client = tftp.TFTPClient(*self.srv_addr, window_size=2)
recv_values = [
(b'\x00\x06windowsize\x002\x00', self.addr),
(b'\x00\x03\x00\x01' + b'a' * 512, self.addr),
(b'\x00\x03\x00\x02' + b'a' * 511, self.addr)]
expected_sendto = [
call(b'\x00\x01test\x00octet\x00windowsize\x002\x00',
self.srv_addr),
call(b'\x00\x04\x00\x00', self.addr),
call(b'\x00\x04\x00\x02', self.addr)]
self.__simple_test(recv_values, 'get', ('test',),
expected_sendto, b'a' * 1023)
@patch('tftp.socket.timeout', Exception)
def test_get_with_windowsize_timeout(self):
self.client = tftp.TFTPClient(*self.srv_addr, window_size=2)
recv_values = [
(b'\x00\x06windowsize\x002\x00', self.addr),
(b'\x00\x03\x00\x01' + b'a' * 512, self.addr),
tftp.socket.timeout(),
(b'\x00\x03\x00\x02' + b'a' * 512, self.addr),
(b'\x00\x03\x00\x03' + b'a' * 511, self.addr)]
expected_sendto = [
call(b'\x00\x01test\x00octet\x00windowsize\x002\x00',
self.srv_addr),
call(b'\x00\x04\x00\x00', self.addr),
call(b'\x00\x04\x00\x01', self.addr),
call(b'\x00\x04\x00\x03', self.addr)]
self.__simple_test(recv_values, 'get', ('test',),
expected_sendto, b'a' * 1535)
def test_put_empty_file(self):
recv_values = [
(b'\x00\x04\x00\x00', self.srv_addr),
(b'\x00\x04\x00\x01', self.srv_addr)]
expected_sendto = [
call(b'\x00\x02test !@#\x00octet\x00', self.srv_addr),
call(b'\x00\x03\x00\x01', self.srv_addr)]
self.__simple_test(
recv_values, 'put', ('test !@#', b''), expected_sendto)
def test_put_short_file(self):
recv_values = [
(b'\x00\x04\x00\x00', self.srv_addr),
(b'\x00\x04\x00\x01', self.srv_addr)]
expected_sendto = [
call(b'\x00\x02test !@#\x00octet\x00', self.srv_addr),
call(b'\x00\x03\x00\x01test contents', self.srv_addr)]
self.__simple_test(
recv_values, 'put', ('test !@#', b'test contents'),
expected_sendto)
def test_put_long_file(self):
recv_values = [
(b'\x00\x04\x00\x00', self.srv_addr),
(b'\x00\x04\x00\x01', self.srv_addr),
(b'\x00\x04\x00\x02', self.srv_addr)]
expected_sendto = [
call(b'\x00\x02test !@#\x00octet\x00', self.srv_addr),
call(b'\x00\x03\x00\x01' + b'a' * 512, self.srv_addr),
call(b'\x00\x03\x00\x02' + b'a' * 511, self.srv_addr)]
self.__simple_test(
recv_values, 'put', ('test !@#', b'a' * 1023), expected_sendto)
def test_put_with_blksize_option(self):
self.client = tftp.TFTPClient(*self.srv_addr, 8192)
recv_values = [
(b'\x00\x06blksize\x008192\x00', self.srv_addr),
(b'\x00\x04\x00\x01', self.srv_addr),
(b'\x00\x04\x00\x02', self.srv_addr)]
expected_sendto = [
call(b'\x00\x02test\x00octet\x00blksize\x008192\x00',
self.srv_addr),
call(b'\x00\x03\x00\x01' + b'a' * 8192, self.srv_addr),
call(b'\x00\x03\x00\x02' + b'a' * 8191, self.srv_addr)]
self.__simple_test(
recv_values, 'put', ('test', b'a' * 16383), expected_sendto)
def test_tftp_error(self):
self.socket_instance.recvfrom.return_value = (
b'\x00\x05\x00\x01File not found\x00', self.addr)
with self.assertRaises(tftp.TFTPError) as cm:
self.client.get_file('test')
self.assertEqual(1, cm.exception.error_id)
self.assertEqual('File not found', cm.exception.message)
def test_invalid_opcode(self):
self.socket_instance.recvfrom.return_value = (
b'\x00\xff\x00\x01', self.srv_addr)
with self.assertRaises(tftp.TFTPTerminatedError):
self.client.get_file('test')
self.socket_instance.sendto.assert_called_with(
b'\x00\x05\x00\x04Illegal TFTP operation\x00', self.srv_addr)
self.socket_instance.close.assert_called()
@patch('tftp.socket.timeout', type('timeout', (Exception,), {}))
def test_invalid_packet_format(self):
self.socket_instance.recvfrom.return_value = (
b'\x00\x03\x00', self.srv_addr)
with self.assertRaises(tftp.TFTPTerminatedError):
self.client.get_file('test')
self.socket_instance.sendto.assert_called_with(
b'\x00\x05\x00\x04Illegal TFTP operation\x00', self.srv_addr)
self.socket_instance.close.assert_called()
def test_invalid_tid(self):
evil_addr = ('evil.addr.com', 666)
recv_values = [
(b'\x00\x03\x00\x01' + b'a' * 512, self.addr),
(b'\x00\x03\x00\x02' + b'b' * 511, evil_addr),
(b'\x00\x03\x00\x02' + b'a' * 511, self.addr)]
expected_sendto = [
call(b'\x00\x01test\x00octet\x00', self.srv_addr),
call(b'\x00\x04\x00\x01', self.addr),
call(b'\x00\x05\x00\x05Unknown transfer ID\x00', evil_addr),
call(b'\x00\x04\x00\x02', self.addr)]
self.__simple_test(
recv_values, 'get', ('test',), expected_sendto, b'a' * 1023)
@patch('tftp.socket.timeout', Exception)
def test_retry(self):
recv_values = [
tftp.socket.timeout(),
(b'\x00\x03\x00\x01' + b'a' * 512, self.addr),
tftp.socket.timeout(),
(b'\x00\x03\x00\x02', self.addr)]
expected_sendto = [
call(b'\x00\x01test !@#\x00octet\x00', self.srv_addr),
call(b'\x00\x01test !@#\x00octet\x00', self.srv_addr),
call(b'\x00\x04\x00\x01', self.addr),
call(b'\x00\x04\x00\x01', self.addr),
call(b'\x00\x04\x00\x02', self.addr)]
self.__simple_test(
recv_values, 'get', ('test !@#',), expected_sendto, b'a' * 512)
@patch('tftp.socket.timeout', Exception)
def test_timeout(self):
self.socket_instance.recvfrom.side_effect = tftp.socket.timeout()
with self.assertRaises(tftp.TFTPException):
self.client.get_file('test')
self.assertEqual(tftp.MAX_RETRIES + 1,
self.socket_instance.sendto.call_count)
@patch('tftp.socket.timeout', Exception)
def test_timeout_after_valid_data(self):
recv_values = [
tftp.socket.timeout(),
(b'\x00\x03\x00\x01' + b'a' * 512, self.addr)] + [
tftp.socket.timeout()] * (tftp.MAX_RETRIES + 1)
expected_sendto = [
call(b'\x00\x01test\x00octet\x00', self.srv_addr),
call(b'\x00\x01test\x00octet\x00', self.srv_addr)] + [
call(b'\x00\x04\x00\x01', self.addr)] * (tftp.MAX_RETRIES + 1)
self.socket_instance.recvfrom.side_effect = recv_values
with self.assertRaises(tftp.TFTPException):
self.client.get_file('test')
self.assertEqual(
expected_sendto, self.socket_instance.sendto.call_args_list)
| from typing import List, Tuple
from unittest.mock import patch, call, _Call
import tftp
from tests.tftp_test_case import TFTPTestCase
class TestTFTPClient(TFTPTestCase):
def setUp(self):
super(TestTFTPClient, self).setUp()
self.client = tftp.TFTPClient(*self.srv_addr)
self.client.__enter__()
def tearDown(self):
self.client.__exit__(None, None, None)
super(TestTFTPClient, self).tearDown()
def test_setup(self):
self.socket.socket.assert_called_with(
self.socket.AF_INET, self.socket.SOCK_DGRAM)
def __simple_test(
self, recv_values: List[tftp.Packet], func: str, args: Tuple,
expected_sendto: List[_Call], expected_data: bytes = None) -> None:
"""Test GET/PUT operation without expecting any errors.
:param recv_values: list of values that should be returned by recvfrom()
:param func: function to use: 'get' or 'put'
:param args: arguments for the function
:param expected_sendto: expected packets sent (as a list of arguments
for the sendto() function)
:param expected_data: expected data to be returned by GET
"""
self.socket_instance.recvfrom.side_effect = recv_values
assert func in ['get', 'put']
data = None
if func == 'get':
data = self.client.get_file(*args)
elif func == 'put':
self.client.put_file(*args)
self.assertEqual(
expected_sendto, self.socket_instance.sendto.call_args_list)
if func == 'get':
self.assertEqual(expected_data, data)
def test_get_empty_file(self):
expected_sendto = [
call(b'\x00\x01test !@#\x00octet\x00', self.srv_addr),
call(b'\x00\x04\x00\x01', self.addr)]
self.__simple_test(
[(b'\x00\x03\x00\x01', self.addr)], 'get', ('test !@#',),
expected_sendto, b'')
def test_get_empty_file_random_blockid(self):
recv_values = [
(b'\x00\x03\xca\xfe', self.addr),
(b'\x00\x03\x00\x01', self.addr)]
expected_sendto = [
call(b'\x00\x01test\x00octet\x00', self.srv_addr),
call(b'\x00\x04\x00\x00', self.addr),
call(b'\x00\x04\x00\x01', self.addr)]
self.__simple_test(
recv_values, 'get', ('test',),
expected_sendto, b'')
def test_get_short_file(self):
expected_sendto = [
call(b'\x00\x01test\x00octet\x00', self.srv_addr),
call(b'\x00\x04\x00\x01', self.addr)]
self.__simple_test(
[(b'\x00\x03\x00\x01test contents', self.addr)], 'get', ('test',),
expected_sendto, b'test contents')
def test_get_long_file(self):
recv_values = [
(b'\x00\x03\x00\x01' + b'a' * 512, self.addr),
(b'\x00\x03\x00\x02' + b'a' * 511, self.addr)]
expected_sendto = [
call(b'\x00\x01test\x00octet\x00', self.srv_addr),
call(b'\x00\x04\x00\x01', self.addr),
call(b'\x00\x04\x00\x02', self.addr)]
self.__simple_test(
recv_values, 'get', ('test',),
expected_sendto, b'a' * 1023)
def test_get_huge_file(self):
recv_values = []
expected_sendto = [
call(b'\x00\x01test\x00octet\x00', self.srv_addr)]
for i in range(1, 65537):
block_id = (i % 65536).to_bytes(2, byteorder='big')
recv_values.append(
(b'\x00\x03' + block_id +
b'a' * (0 if i == 65536 else 512), self.addr))
expected_sendto.append(call(b'\x00\x04' + block_id, self.addr))
self.__simple_test(recv_values, 'get', ('test',),
expected_sendto, b'a' * (65535 * 512))
def test_get_with_blksize_option(self):
self.client = tftp.TFTPClient(*self.srv_addr, 8192)
recv_values = [
(b'\x00\x06blksize\x008192\x00', self.addr),
(b'\x00\x03\x00\x01' + b'a' * 8192, self.addr),
(b'\x00\x03\x00\x02' + b'a' * 8191, self.addr)]
expected_sendto = [
call(b'\x00\x01test\x00octet\x00blksize\x008192\x00',
self.srv_addr),
call(b'\x00\x04\x00\x00', self.addr),
call(b'\x00\x04\x00\x01', self.addr),
call(b'\x00\x04\x00\x02', self.addr)]
self.__simple_test(recv_values, 'get', ('test',),
expected_sendto, b'a' * 16383)
def test_get_with_windowsize(self):
self.client = tftp.TFTPClient(*self.srv_addr, window_size=2)
recv_values = [
(b'\x00\x06windowsize\x002\x00', self.addr),
(b'\x00\x03\x00\x01' + b'a' * 512, self.addr),
(b'\x00\x03\x00\x02' + b'a' * 511, self.addr)]
expected_sendto = [
call(b'\x00\x01test\x00octet\x00windowsize\x002\x00',
self.srv_addr),
call(b'\x00\x04\x00\x00', self.addr),
call(b'\x00\x04\x00\x02', self.addr)]
self.__simple_test(recv_values, 'get', ('test',),
expected_sendto, b'a' * 1023)
@patch('tftp.socket.timeout', Exception)
def test_get_with_windowsize_timeout(self):
self.client = tftp.TFTPClient(*self.srv_addr, window_size=2)
recv_values = [
(b'\x00\x06windowsize\x002\x00', self.addr),
(b'\x00\x03\x00\x01' + b'a' * 512, self.addr),
tftp.socket.timeout(),
(b'\x00\x03\x00\x02' + b'a' * 512, self.addr),
(b'\x00\x03\x00\x03' + b'a' * 511, self.addr)]
expected_sendto = [
call(b'\x00\x01test\x00octet\x00windowsize\x002\x00',
self.srv_addr),
call(b'\x00\x04\x00\x00', self.addr),
call(b'\x00\x04\x00\x01', self.addr),
call(b'\x00\x04\x00\x03', self.addr)]
self.__simple_test(recv_values, 'get', ('test',),
expected_sendto, b'a' * 1535)
def test_put_empty_file(self):
recv_values = [
(b'\x00\x04\x00\x00', self.srv_addr),
(b'\x00\x04\x00\x01', self.srv_addr)]
expected_sendto = [
call(b'\x00\x02test !@#\x00octet\x00', self.srv_addr),
call(b'\x00\x03\x00\x01', self.srv_addr)]
self.__simple_test(
recv_values, 'put', ('test !@#', b''), expected_sendto)
def test_put_short_file(self):
recv_values = [
(b'\x00\x04\x00\x00', self.srv_addr),
(b'\x00\x04\x00\x01', self.srv_addr)]
expected_sendto = [
call(b'\x00\x02test !@#\x00octet\x00', self.srv_addr),
call(b'\x00\x03\x00\x01test contents', self.srv_addr)]
self.__simple_test(
recv_values, 'put', ('test !@#', b'test contents'),
expected_sendto)
def test_put_long_file(self):
recv_values = [
(b'\x00\x04\x00\x00', self.srv_addr),
(b'\x00\x04\x00\x01', self.srv_addr),
(b'\x00\x04\x00\x02', self.srv_addr)]
expected_sendto = [
call(b'\x00\x02test !@#\x00octet\x00', self.srv_addr),
call(b'\x00\x03\x00\x01' + b'a' * 512, self.srv_addr),
call(b'\x00\x03\x00\x02' + b'a' * 511, self.srv_addr)]
self.__simple_test(
recv_values, 'put', ('test !@#', b'a' * 1023), expected_sendto)
def test_put_with_blksize_option(self):
self.client = tftp.TFTPClient(*self.srv_addr, 8192)
recv_values = [
(b'\x00\x06blksize\x008192\x00', self.srv_addr),
(b'\x00\x04\x00\x01', self.srv_addr),
(b'\x00\x04\x00\x02', self.srv_addr)]
expected_sendto = [
call(b'\x00\x02test\x00octet\x00blksize\x008192\x00',
self.srv_addr),
call(b'\x00\x03\x00\x01' + b'a' * 8192, self.srv_addr),
call(b'\x00\x03\x00\x02' + b'a' * 8191, self.srv_addr)]
self.__simple_test(
recv_values, 'put', ('test', b'a' * 16383), expected_sendto)
def test_tftp_error(self):
self.socket_instance.recvfrom.return_value = (
b'\x00\x05\x00\x01File not found\x00', self.addr)
with self.assertRaises(tftp.TFTPError) as cm:
self.client.get_file('test')
self.assertEqual(1, cm.exception.error_id)
self.assertEqual('File not found', cm.exception.message)
def test_invalid_opcode(self):
self.socket_instance.recvfrom.return_value = (
b'\x00\xff\x00\x01', self.srv_addr)
with self.assertRaises(tftp.TFTPTerminatedError):
self.client.get_file('test')
self.socket_instance.sendto.assert_called_with(
b'\x00\x05\x00\x04Illegal TFTP operation\x00', self.srv_addr)
self.socket_instance.close.assert_called()
@patch('tftp.socket.timeout', type('timeout', (Exception,), {}))
def test_invalid_packet_format(self):
self.socket_instance.recvfrom.return_value = (
b'\x00\x03\x00', self.srv_addr)
with self.assertRaises(tftp.TFTPTerminatedError):
self.client.get_file('test')
self.socket_instance.sendto.assert_called_with(
b'\x00\x05\x00\x04Illegal TFTP operation\x00', self.srv_addr)
self.socket_instance.close.assert_called()
def test_invalid_tid(self):
evil_addr = ('evil.addr.com', 666)
recv_values = [
(b'\x00\x03\x00\x01' + b'a' * 512, self.addr),
(b'\x00\x03\x00\x02' + b'b' * 511, evil_addr),
(b'\x00\x03\x00\x02' + b'a' * 511, self.addr)]
expected_sendto = [
call(b'\x00\x01test\x00octet\x00', self.srv_addr),
call(b'\x00\x04\x00\x01', self.addr),
call(b'\x00\x05\x00\x05Unknown transfer ID\x00', evil_addr),
call(b'\x00\x04\x00\x02', self.addr)]
self.__simple_test(
recv_values, 'get', ('test',), expected_sendto, b'a' * 1023)
@patch('tftp.socket.timeout', Exception)
def test_retry(self):
recv_values = [
tftp.socket.timeout(),
(b'\x00\x03\x00\x01' + b'a' * 512, self.addr),
tftp.socket.timeout(),
(b'\x00\x03\x00\x02', self.addr)]
expected_sendto = [
call(b'\x00\x01test !@#\x00octet\x00', self.srv_addr),
call(b'\x00\x01test !@#\x00octet\x00', self.srv_addr),
call(b'\x00\x04\x00\x01', self.addr),
call(b'\x00\x04\x00\x01', self.addr),
call(b'\x00\x04\x00\x02', self.addr)]
self.__simple_test(
recv_values, 'get', ('test !@#',), expected_sendto, b'a' * 512)
@patch('tftp.socket.timeout', Exception)
def test_timeout(self):
self.socket_instance.recvfrom.side_effect = tftp.socket.timeout()
with self.assertRaises(tftp.TFTPException):
self.client.get_file('test')
self.assertEqual(tftp.MAX_RETRIES + 1,
self.socket_instance.sendto.call_count)
@patch('tftp.socket.timeout', Exception)
def test_timeout_after_valid_data(self):
recv_values = [
tftp.socket.timeout(),
(b'\x00\x03\x00\x01' + b'a' * 512, self.addr)] + [
tftp.socket.timeout()] * (tftp.MAX_RETRIES + 1)
expected_sendto = [
call(b'\x00\x01test\x00octet\x00', self.srv_addr),
call(b'\x00\x01test\x00octet\x00', self.srv_addr)] + [
call(b'\x00\x04\x00\x01', self.addr)] * (tftp.MAX_RETRIES + 1)
self.socket_instance.recvfrom.side_effect = recv_values
with self.assertRaises(tftp.TFTPException):
self.client.get_file('test')
self.assertEqual(
expected_sendto, self.socket_instance.sendto.call_args_list) | en | 0.261543 | Test GET/PUT operation without expecting any errors. :param recv_values: list of values that should be returned by recvfrom() :param func: function to use: 'get' or 'put' :param args: arguments for the function :param expected_sendto: expected packets sent (as a list of arguments for the sendto() function) :param expected_data: expected data to be returned by GET #\x00octet\x00', self.srv_addr), #',), #\x00octet\x00', self.srv_addr), #', b''), expected_sendto) #\x00octet\x00', self.srv_addr), #', b'test contents'), #\x00octet\x00', self.srv_addr), #', b'a' * 1023), expected_sendto) #\x00octet\x00', self.srv_addr), #\x00octet\x00', self.srv_addr), #',), expected_sendto, b'a' * 512) | 2.847775 | 3 |
ps2_newton.py | nadaav/python_projects- | 0 | 6623073 | # 6.00 Problem Set 2
# Successive Approximation
def evaluate_poly(poly, x):
##assert type(poly)== tuple and len(poly)>0
##assert type(x) == float and type(epsilon) == float
result = 0
for i in range(len(poly)):
result += x**float(i)*poly[i]
return result
def compute_eval_deriv(poly, x):
##assert type(poly)== tuple and len(poly)>0
poly_computed = ()
for i in range(1, len(poly)):
poly_computed += (poly[i]*i,)
return evaluate_poly(poly_computed, x)
def compute_root(poly, x, epsilon):
num_iter=1
result = evaluate_poly(poly, x)
while result < -epsilon or result > 1.1*epsilon:
num_iter += 1
x -= result/compute_eval_deriv(poly, x)
result = evaluate_poly(poly, x)
return (x, num_iter)
##poly = (-13.39, 0.0, 17.5, 3.0, 1.0)
##x = 0.1
##poly = (4, 4, 1)
##x = -1.89
poly = (0.0625, -0.5, 1)
x = 0.20
epsilon = 0.0001
print(compute_root(poly, x, epsilon))
"""
Uses Newton's method to find and return a root of a polynomial function.
Returns a tuple containing the root and the number of iterations required
to get to the root.
Example:
>>> poly = (-13.39, 0.0, 17.5, 3.0, 1.0) #x^4 + 3x^3 + 17.5x^2 - 13.39
>>> x_0 = 0.1
>>> epsilon = .0001
>>> print compute_root(poly, x_0, epsilon)
(0.80679075379635201, 8.0)
poly: tuple of numbers, length > 1.
Represents a polynomial function containing at least one real root.
The derivative of this polynomial function at x_0 is not 0.
x_0: float
epsilon: float > 0
returns: tuple (float, int)
"""
##multiplication function without using "*"
##def rec_multiplication(m, n):
## if n == 0 or m == 0:
## return 0
## elif n>0:
## m, n = m, n
## elif n < 0:
## m, n = -m, -n
## return m + rec_multiplication(m, n-1)
| # 6.00 Problem Set 2
# Successive Approximation
def evaluate_poly(poly, x):
##assert type(poly)== tuple and len(poly)>0
##assert type(x) == float and type(epsilon) == float
result = 0
for i in range(len(poly)):
result += x**float(i)*poly[i]
return result
def compute_eval_deriv(poly, x):
##assert type(poly)== tuple and len(poly)>0
poly_computed = ()
for i in range(1, len(poly)):
poly_computed += (poly[i]*i,)
return evaluate_poly(poly_computed, x)
def compute_root(poly, x, epsilon):
num_iter=1
result = evaluate_poly(poly, x)
while result < -epsilon or result > 1.1*epsilon:
num_iter += 1
x -= result/compute_eval_deriv(poly, x)
result = evaluate_poly(poly, x)
return (x, num_iter)
##poly = (-13.39, 0.0, 17.5, 3.0, 1.0)
##x = 0.1
##poly = (4, 4, 1)
##x = -1.89
poly = (0.0625, -0.5, 1)
x = 0.20
epsilon = 0.0001
print(compute_root(poly, x, epsilon))
"""
Uses Newton's method to find and return a root of a polynomial function.
Returns a tuple containing the root and the number of iterations required
to get to the root.
Example:
>>> poly = (-13.39, 0.0, 17.5, 3.0, 1.0) #x^4 + 3x^3 + 17.5x^2 - 13.39
>>> x_0 = 0.1
>>> epsilon = .0001
>>> print compute_root(poly, x_0, epsilon)
(0.80679075379635201, 8.0)
poly: tuple of numbers, length > 1.
Represents a polynomial function containing at least one real root.
The derivative of this polynomial function at x_0 is not 0.
x_0: float
epsilon: float > 0
returns: tuple (float, int)
"""
##multiplication function without using "*"
##def rec_multiplication(m, n):
## if n == 0 or m == 0:
## return 0
## elif n>0:
## m, n = m, n
## elif n < 0:
## m, n = -m, -n
## return m + rec_multiplication(m, n-1)
| en | 0.550622 | # 6.00 Problem Set 2 # Successive Approximation ##assert type(poly)== tuple and len(poly)>0 ##assert type(x) == float and type(epsilon) == float ##assert type(poly)== tuple and len(poly)>0 ##poly = (-13.39, 0.0, 17.5, 3.0, 1.0) ##x = 0.1 ##poly = (4, 4, 1) ##x = -1.89 Uses Newton's method to find and return a root of a polynomial function. Returns a tuple containing the root and the number of iterations required to get to the root. Example: >>> poly = (-13.39, 0.0, 17.5, 3.0, 1.0) #x^4 + 3x^3 + 17.5x^2 - 13.39 >>> x_0 = 0.1 >>> epsilon = .0001 >>> print compute_root(poly, x_0, epsilon) (0.80679075379635201, 8.0) poly: tuple of numbers, length > 1. Represents a polynomial function containing at least one real root. The derivative of this polynomial function at x_0 is not 0. x_0: float epsilon: float > 0 returns: tuple (float, int) ##multiplication function without using "*" ##def rec_multiplication(m, n): ## if n == 0 or m == 0: ## return 0 ## elif n>0: ## m, n = m, n ## elif n < 0: ## m, n = -m, -n ## return m + rec_multiplication(m, n-1) | 3.87719 | 4 |
devbench/wikidot.py | pxdnbluesoul/Pixeltasim-Alexandra | 1 | 6623074 | from whiffle import wikidotapi
api = wikidotapi.connection()
pages = api.Pages
total = 0
for page in pages:
total += 1
print total
@hook.command
def author(inp):
".author <Author Name> -- Will return details regarding the author"
authpages = []
item for item in pagecache:
if item["created_by"] == inp:
authpages.append(item)
total = 0
pagetotal = 0
for page in authpages:
total += page["rating"]
pagetotal += 1
return inp +" has created " + pagetotal + " pages. With an average rating of "+ total/pagetotal+ ". Their most recently created page is " + authpages[-1]["title"]
pagecache = []
def refresh_cache():
api = wikidotapi.connection()
pages = api.refresh_pages()
for page in pages:
pagecache.append(api.server.pages.get_meta({"site": api.Site, "pages": [page]}))
print "\n" + time.ctime()
#threading.Timer(3600, refresh_cache).start()
#refresh_cache()
| from whiffle import wikidotapi
api = wikidotapi.connection()
pages = api.Pages
total = 0
for page in pages:
total += 1
print total
@hook.command
def author(inp):
".author <Author Name> -- Will return details regarding the author"
authpages = []
item for item in pagecache:
if item["created_by"] == inp:
authpages.append(item)
total = 0
pagetotal = 0
for page in authpages:
total += page["rating"]
pagetotal += 1
return inp +" has created " + pagetotal + " pages. With an average rating of "+ total/pagetotal+ ". Their most recently created page is " + authpages[-1]["title"]
pagecache = []
def refresh_cache():
api = wikidotapi.connection()
pages = api.refresh_pages()
for page in pages:
pagecache.append(api.server.pages.get_meta({"site": api.Site, "pages": [page]}))
print "\n" + time.ctime()
#threading.Timer(3600, refresh_cache).start()
#refresh_cache()
| en | 0.297196 | #threading.Timer(3600, refresh_cache).start() #refresh_cache() | 3.018477 | 3 |
appengine/src/greenday_api/tests/test_user_api.py | meedan/montage | 6 | 6623075 | <reponame>meedan/montage
"""
Tests for :mod:`greenday_api.user.user_api <greenday_api.user.user_api>`
"""
# LIBRARIES
import mock
from milkman.dairy import milkman
# FRAMEWORK
from protorpc import message_types
from django.contrib.auth import get_user_model
# GREENDAY
from greenday_core.api_exceptions import ForbiddenException
from greenday_core.models import (
Project,
UserVideoDetail,
GlobalTag,
ProjectTag,
VideoTag,
VideoTagInstance,
)
from greenday_core.constants import EventKind
from .base import ApiTestCase, TestEventBusMixin
from ..user.messages import (
UserListResponse, UserResponseMessage)
from ..user.user_api import UserAPI
from ..user.containers import (
UserFilterContainer,
UserCreateContainer,
UserUpdateContainer,
CurrentUserUpdateContainer,
)
class UserAPITests(TestEventBusMixin, ApiTestCase):
"""
Tests for :class:`greenday_api.user.UserAPI <greenday_api.user.UserAPI>`
"""
api_type = UserAPI
def create_test_users(self):
"""
Override creation of test users
"""
User = get_user_model()
# override
self.admin = milkman.deliver(
User, email="<EMAIL>", is_superuser=True)
self.user = milkman.deliver(User, email="<EMAIL>")
self.user2 = milkman.deliver(User, email="<EMAIL>")
def test_filter_users(self):
""" Test that the correct users are returned when doing partial filters
on the first_name, last_name and email fields
"""
User = get_user_model()
# Users with some overlapping details
charlie_brown = milkman.deliver(
User, first_name="Charlie", last_name="Brown",
email="<EMAIL>")
charlie_brooker = milkman.deliver(
User, first_name="Charlie", last_name="Brooker",
email="<EMAIL>")
someone_brooker = milkman.deliver(
User, first_name="Someone", last_name="Brooker",
email="<EMAIL>")
def _check_filtered_users(q, *users):
self._sign_in(self.admin)
response = self.api.users_filter(
UserFilterContainer.combined_message_class(q=q))
self.assertIsInstance(response, UserListResponse)
items_pks = [item.id for item in response.items]
self.assertEqual(len(users), len(items_pks))
for user in users:
self.assertTrue(user.pk in items_pks)
# Filter on 'example.com' first, it should return all 5 users
with self.assertNumQueries(2):
_check_filtered_users(
'example', charlie_brown, charlie_brooker,
someone_brooker, self.user, self.user2)
# Test some more restrictive filters
with self.assertNumQueries(2):
_check_filtered_users('charlie', charlie_brown, charlie_brooker)
# partial matches work as well
with self.assertNumQueries(2):
_check_filtered_users('charl', charlie_brown, charlie_brooker)
with self.assertNumQueries(2):
_check_filtered_users('brooker', charlie_brooker, someone_brooker)
with self.assertNumQueries(2):
_check_filtered_users('someone', someone_brooker)
with self.assertNumQueries(3):
_check_filtered_users('<NAME>', charlie_brooker)
with self.assertNumQueries(3):
_check_filtered_users('<NAME>', charlie_brown)
# no results
with self.assertNumQueries(3):
_check_filtered_users('<NAME>')
# no search term and not admin user - should raise forbidden.
self._sign_out()
self._sign_in(self.user)
self.assertRaises(
ForbiddenException,
self.api.users_filter,
UserFilterContainer.combined_message_class(q=None)
)
def test_create_user(self):
"""
Create a new user
"""
# Check that a normal user can't create other users
self._sign_in(self.user)
self.assertRaises(
ForbiddenException,
self.api.users_create, UserCreateContainer.combined_message_class(
email="<EMAIL>")
)
# But a superuser can
self._sign_in(self.admin)
with self.assertEventRecorded(
EventKind.USERCREATED,
object_id=True), self.assertNumQueries(6):
response = self.api.users_create(
UserCreateContainer.combined_message_class(
email="<EMAIL>"))
self.assertIsInstance(response, UserResponseMessage)
new_user = get_user_model().objects.get(email="<EMAIL>")
self.assertEqual(new_user.pk, response.id)
# Admins of projects can't
project = milkman.deliver(Project)
project.set_owner(self.user)
project.add_admin(self.user2, pending=False)
self._sign_in(self.user)
self.assertRaises(
ForbiddenException,
self.api.users_create, UserCreateContainer.combined_message_class(
email="<EMAIL>")
)
def test_update_user(self):
"""
Update a user's profile
"""
user = get_user_model().objects.create(
username="123",
email="<EMAIL>",
is_active=False
)
request = UserUpdateContainer.combined_message_class(
id=user.id,
first_name="foo",
last_name="bar",
email="<EMAIL>",
is_superuser=True,
is_staff=True,
profile_img_url="http://example.com/a.jpg",
google_plus_profile="http://plus.google.com/foobar",
accepted_nda=True,
is_active=True
)
# normal user can't update users - even themselves
self._sign_in(user)
self.assertRaises(
ForbiddenException,
self.api.users_update, request
)
# But a superuser can
self._sign_in(self.admin)
with self.assertEventRecorded(
EventKind.USERUPDATED,
object_id=user.pk), self.assertNumQueries(4):
response = self.api.users_update(request)
self.assertIsInstance(response, UserResponseMessage)
user = get_user_model().objects.get(pk=user.pk)
self.assertEqual(user.pk, response.id)
self.assertEqual(user.email, request.email)
self.assertEqual(user.first_name, response.first_name)
self.assertEqual(user.last_name, response.last_name)
self.assertEqual(user.is_superuser, response.is_superuser)
self.assertEqual(user.is_staff, response.is_staff)
self.assertEqual(user.profile_img_url, response.profile_img_url)
self.assertEqual(
user.google_plus_profile, response.google_plus_profile)
self.assertEqual(user.accepted_nda, response.accepted_nda)
self.assertEqual(user.is_active, response.is_active)
def test_update_current_user(self):
"""
Update the currently logged in user's profile
"""
User = get_user_model()
user = User.objects.create(
username="123",
email="<EMAIL>",
is_active=False
)
self._sign_in(user)
request = CurrentUserUpdateContainer.combined_message_class(
first_name="foo",
last_name="bar",
email="<EMAIL>",
profile_img_url="http://example.com/a.jpg",
google_plus_profile="http://plus.google.com/foobar",
accepted_nda=True
)
with self.assertNumQueries(2):
response = self.api.update_current_user(request)
self.assertIsInstance(response, UserResponseMessage)
user = User.objects.get(pk=user.pk)
self.assertEqual(user.pk, response.id)
self.assertEqual(user.email, request.email)
self.assertEqual(user.first_name, response.first_name)
self.assertEqual(user.last_name, response.last_name)
self.assertEqual(user.profile_img_url, response.profile_img_url)
self.assertEqual(
user.google_plus_profile, response.google_plus_profile)
self.assertEqual(user.accepted_nda, response.accepted_nda)
@mock.patch("greenday_api.user.user_api.defer_delete_user")
def test_delete_self(self, mock_defer_delete_user):
"""
User deleting themselves
"""
self._sign_in(self.user)
self.api.delete_current_user(message_types.VoidMessage())
mock_defer_delete_user.called_once_with(self.user, self.user)
def test_get_current_user(self):
"""
Get the current logged in user
"""
self._sign_in(self.user)
request = message_types.VoidMessage()
with self.assertNumQueries(1):
response = self.api.get_current_user(request)
self.assertIsInstance(response, UserResponseMessage)
self.assertEqual(self.user.pk, response.id)
class UserAPIStatsTests(ApiTestCase):
"""
Tests for :func:`greenday_api.user.UserAPI.get_current_user_stats <greenday_api.user.UserAPI.get_current_user_stats>`
"""
api_type = UserAPI
def setUp(self):
"""
Bootstrap test data
"""
super(UserAPIStatsTests, self).setUp()
self.project = milkman.deliver(Project)
self.project.set_owner(self.admin)
self.project.add_assigned(self.user, pending=False)
self.video = self.create_video(owner=self.admin)
self.globaltag = milkman.deliver(
GlobalTag, name="tag2", description="buzz", image_url="img.jpg")
self.projecttag = ProjectTag.add_root(
project=self.project, global_tag=self.globaltag)
self.videotag = VideoTag.objects.create(
project=self.project,
project_tag=self.projecttag,
video=self.video)
self.videotaginstance = VideoTagInstance.objects.create(
video_tag=self.videotag,
user=self.user
)
def test_get_self_stats(self):
"""
Get current user's statistics
"""
self._sign_in(self.user)
UserVideoDetail.objects.create(
user=self.user,
video=self.video,
watched=True
)
with self.assertNumQueries(3):
response = self.api.get_current_user_stats(
message_types.VoidMessage())
self.assertEqual(response.id, self.user.pk)
self.assertEqual(response.videos_watched, 1)
self.assertEqual(response.tags_added, 1)
def test_get_self_stats_no_data(self):
"""
Get current user's statistics - no stats available
"""
self._sign_in(self.user2)
with self.assertNumQueries(3):
response = self.api.get_current_user_stats(
message_types.VoidMessage())
self.assertEqual(response.id, self.user2.pk)
self.assertEqual(response.videos_watched, 0)
self.assertEqual(response.tags_added, 0)
| """
Tests for :mod:`greenday_api.user.user_api <greenday_api.user.user_api>`
"""
# LIBRARIES
import mock
from milkman.dairy import milkman
# FRAMEWORK
from protorpc import message_types
from django.contrib.auth import get_user_model
# GREENDAY
from greenday_core.api_exceptions import ForbiddenException
from greenday_core.models import (
Project,
UserVideoDetail,
GlobalTag,
ProjectTag,
VideoTag,
VideoTagInstance,
)
from greenday_core.constants import EventKind
from .base import ApiTestCase, TestEventBusMixin
from ..user.messages import (
UserListResponse, UserResponseMessage)
from ..user.user_api import UserAPI
from ..user.containers import (
UserFilterContainer,
UserCreateContainer,
UserUpdateContainer,
CurrentUserUpdateContainer,
)
class UserAPITests(TestEventBusMixin, ApiTestCase):
"""
Tests for :class:`greenday_api.user.UserAPI <greenday_api.user.UserAPI>`
"""
api_type = UserAPI
def create_test_users(self):
"""
Override creation of test users
"""
User = get_user_model()
# override
self.admin = milkman.deliver(
User, email="<EMAIL>", is_superuser=True)
self.user = milkman.deliver(User, email="<EMAIL>")
self.user2 = milkman.deliver(User, email="<EMAIL>")
def test_filter_users(self):
""" Test that the correct users are returned when doing partial filters
on the first_name, last_name and email fields
"""
User = get_user_model()
# Users with some overlapping details
charlie_brown = milkman.deliver(
User, first_name="Charlie", last_name="Brown",
email="<EMAIL>")
charlie_brooker = milkman.deliver(
User, first_name="Charlie", last_name="Brooker",
email="<EMAIL>")
someone_brooker = milkman.deliver(
User, first_name="Someone", last_name="Brooker",
email="<EMAIL>")
def _check_filtered_users(q, *users):
self._sign_in(self.admin)
response = self.api.users_filter(
UserFilterContainer.combined_message_class(q=q))
self.assertIsInstance(response, UserListResponse)
items_pks = [item.id for item in response.items]
self.assertEqual(len(users), len(items_pks))
for user in users:
self.assertTrue(user.pk in items_pks)
# Filter on 'example.com' first, it should return all 5 users
with self.assertNumQueries(2):
_check_filtered_users(
'example', charlie_brown, charlie_brooker,
someone_brooker, self.user, self.user2)
# Test some more restrictive filters
with self.assertNumQueries(2):
_check_filtered_users('charlie', charlie_brown, charlie_brooker)
# partial matches work as well
with self.assertNumQueries(2):
_check_filtered_users('charl', charlie_brown, charlie_brooker)
with self.assertNumQueries(2):
_check_filtered_users('brooker', charlie_brooker, someone_brooker)
with self.assertNumQueries(2):
_check_filtered_users('someone', someone_brooker)
with self.assertNumQueries(3):
_check_filtered_users('<NAME>', charlie_brooker)
with self.assertNumQueries(3):
_check_filtered_users('<NAME>', charlie_brown)
# no results
with self.assertNumQueries(3):
_check_filtered_users('<NAME>')
# no search term and not admin user - should raise forbidden.
self._sign_out()
self._sign_in(self.user)
self.assertRaises(
ForbiddenException,
self.api.users_filter,
UserFilterContainer.combined_message_class(q=None)
)
def test_create_user(self):
"""
Create a new user
"""
# Check that a normal user can't create other users
self._sign_in(self.user)
self.assertRaises(
ForbiddenException,
self.api.users_create, UserCreateContainer.combined_message_class(
email="<EMAIL>")
)
# But a superuser can
self._sign_in(self.admin)
with self.assertEventRecorded(
EventKind.USERCREATED,
object_id=True), self.assertNumQueries(6):
response = self.api.users_create(
UserCreateContainer.combined_message_class(
email="<EMAIL>"))
self.assertIsInstance(response, UserResponseMessage)
new_user = get_user_model().objects.get(email="<EMAIL>")
self.assertEqual(new_user.pk, response.id)
# Admins of projects can't
project = milkman.deliver(Project)
project.set_owner(self.user)
project.add_admin(self.user2, pending=False)
self._sign_in(self.user)
self.assertRaises(
ForbiddenException,
self.api.users_create, UserCreateContainer.combined_message_class(
email="<EMAIL>")
)
def test_update_user(self):
"""
Update a user's profile
"""
user = get_user_model().objects.create(
username="123",
email="<EMAIL>",
is_active=False
)
request = UserUpdateContainer.combined_message_class(
id=user.id,
first_name="foo",
last_name="bar",
email="<EMAIL>",
is_superuser=True,
is_staff=True,
profile_img_url="http://example.com/a.jpg",
google_plus_profile="http://plus.google.com/foobar",
accepted_nda=True,
is_active=True
)
# normal user can't update users - even themselves
self._sign_in(user)
self.assertRaises(
ForbiddenException,
self.api.users_update, request
)
# But a superuser can
self._sign_in(self.admin)
with self.assertEventRecorded(
EventKind.USERUPDATED,
object_id=user.pk), self.assertNumQueries(4):
response = self.api.users_update(request)
self.assertIsInstance(response, UserResponseMessage)
user = get_user_model().objects.get(pk=user.pk)
self.assertEqual(user.pk, response.id)
self.assertEqual(user.email, request.email)
self.assertEqual(user.first_name, response.first_name)
self.assertEqual(user.last_name, response.last_name)
self.assertEqual(user.is_superuser, response.is_superuser)
self.assertEqual(user.is_staff, response.is_staff)
self.assertEqual(user.profile_img_url, response.profile_img_url)
self.assertEqual(
user.google_plus_profile, response.google_plus_profile)
self.assertEqual(user.accepted_nda, response.accepted_nda)
self.assertEqual(user.is_active, response.is_active)
def test_update_current_user(self):
"""
Update the currently logged in user's profile
"""
User = get_user_model()
user = User.objects.create(
username="123",
email="<EMAIL>",
is_active=False
)
self._sign_in(user)
request = CurrentUserUpdateContainer.combined_message_class(
first_name="foo",
last_name="bar",
email="<EMAIL>",
profile_img_url="http://example.com/a.jpg",
google_plus_profile="http://plus.google.com/foobar",
accepted_nda=True
)
with self.assertNumQueries(2):
response = self.api.update_current_user(request)
self.assertIsInstance(response, UserResponseMessage)
user = User.objects.get(pk=user.pk)
self.assertEqual(user.pk, response.id)
self.assertEqual(user.email, request.email)
self.assertEqual(user.first_name, response.first_name)
self.assertEqual(user.last_name, response.last_name)
self.assertEqual(user.profile_img_url, response.profile_img_url)
self.assertEqual(
user.google_plus_profile, response.google_plus_profile)
self.assertEqual(user.accepted_nda, response.accepted_nda)
@mock.patch("greenday_api.user.user_api.defer_delete_user")
def test_delete_self(self, mock_defer_delete_user):
"""
User deleting themselves
"""
self._sign_in(self.user)
self.api.delete_current_user(message_types.VoidMessage())
mock_defer_delete_user.called_once_with(self.user, self.user)
def test_get_current_user(self):
"""
Get the current logged in user
"""
self._sign_in(self.user)
request = message_types.VoidMessage()
with self.assertNumQueries(1):
response = self.api.get_current_user(request)
self.assertIsInstance(response, UserResponseMessage)
self.assertEqual(self.user.pk, response.id)
class UserAPIStatsTests(ApiTestCase):
"""
Tests for :func:`greenday_api.user.UserAPI.get_current_user_stats <greenday_api.user.UserAPI.get_current_user_stats>`
"""
api_type = UserAPI
def setUp(self):
"""
Bootstrap test data
"""
super(UserAPIStatsTests, self).setUp()
self.project = milkman.deliver(Project)
self.project.set_owner(self.admin)
self.project.add_assigned(self.user, pending=False)
self.video = self.create_video(owner=self.admin)
self.globaltag = milkman.deliver(
GlobalTag, name="tag2", description="buzz", image_url="img.jpg")
self.projecttag = ProjectTag.add_root(
project=self.project, global_tag=self.globaltag)
self.videotag = VideoTag.objects.create(
project=self.project,
project_tag=self.projecttag,
video=self.video)
self.videotaginstance = VideoTagInstance.objects.create(
video_tag=self.videotag,
user=self.user
)
def test_get_self_stats(self):
"""
Get current user's statistics
"""
self._sign_in(self.user)
UserVideoDetail.objects.create(
user=self.user,
video=self.video,
watched=True
)
with self.assertNumQueries(3):
response = self.api.get_current_user_stats(
message_types.VoidMessage())
self.assertEqual(response.id, self.user.pk)
self.assertEqual(response.videos_watched, 1)
self.assertEqual(response.tags_added, 1)
def test_get_self_stats_no_data(self):
"""
Get current user's statistics - no stats available
"""
self._sign_in(self.user2)
with self.assertNumQueries(3):
response = self.api.get_current_user_stats(
message_types.VoidMessage())
self.assertEqual(response.id, self.user2.pk)
self.assertEqual(response.videos_watched, 0)
self.assertEqual(response.tags_added, 0) | en | 0.751673 | Tests for :mod:`greenday_api.user.user_api <greenday_api.user.user_api>` # LIBRARIES # FRAMEWORK # GREENDAY Tests for :class:`greenday_api.user.UserAPI <greenday_api.user.UserAPI>` Override creation of test users # override Test that the correct users are returned when doing partial filters on the first_name, last_name and email fields # Users with some overlapping details # Filter on 'example.com' first, it should return all 5 users # Test some more restrictive filters # partial matches work as well # no results # no search term and not admin user - should raise forbidden. Create a new user # Check that a normal user can't create other users # But a superuser can # Admins of projects can't Update a user's profile # normal user can't update users - even themselves # But a superuser can Update the currently logged in user's profile User deleting themselves Get the current logged in user Tests for :func:`greenday_api.user.UserAPI.get_current_user_stats <greenday_api.user.UserAPI.get_current_user_stats>` Bootstrap test data Get current user's statistics Get current user's statistics - no stats available | 2.201894 | 2 |
tests/integration/fileTypeTests.py | chambers-brian/SIG_Digital-Strategy_SI_ODP_Backend | 0 | 6623076 | from __future__ import print_function
import os
import unittest
from sqlalchemy import not_
from dataactcore.interfaces.db import GlobalDB
from dataactcore.models.domainModels import TASLookup
from dataactcore.models.jobModels import Job
from dataactcore.models.lookups import JOB_STATUS_DICT, JOB_TYPE_DICT, FILE_TYPE_DICT
from dataactcore.models.validationModels import RuleSql
from dataactcore.config import CONFIG_BROKER
from dataactvalidator.app import createApp
from dataactvalidator.filestreaming.sqlLoader import SQLLoader
from dataactvalidator.filestreaming.schemaLoader import SchemaLoader
from dataactvalidator.scripts.loadFile import loadDomainValues
from dataactvalidator.scripts.loadTas import loadTas
from dataactvalidator.scripts.load_sf133 import load_all_sf133
from tests.integration.baseTestValidator import BaseTestValidator
class FileTypeTests(BaseTestValidator):
@classmethod
def setUpClass(cls):
"""Set up class-wide resources."""
super(FileTypeTests, cls).setUpClass()
#TODO: refactor into a pytest fixture
user = cls.userId
# TODO: get rid of this flag once we're using a tempdb for test fixtures
force_tas_load = False
with createApp().app_context():
sess = GlobalDB.db().session
# Create submissions and jobs, also uploading
# the files needed for each job.
statusReadyId = JOB_STATUS_DICT['ready']
jobTypeCsvId = JOB_TYPE_DICT['csv_record_validation']
jobDict = {}
submissionId = cls.insertSubmission(sess, user)
job_info = Job(
filename=cls.uploadFile("appropValid.csv", user),
job_status_id=statusReadyId,
job_type_id=jobTypeCsvId,
file_type_id=FILE_TYPE_DICT['appropriations'],
submission_id=submissionId)
sess.add(job_info)
sess.flush()
jobDict['valid'] = job_info.job_id
submissionId = cls.insertSubmission(sess, user)
job_info = Job(
filename=cls.uploadFile("programActivityValid.csv", user),
job_status_id=statusReadyId,
job_type_id=jobTypeCsvId,
file_type_id=FILE_TYPE_DICT['program_activity'],
submission_id=submissionId)
sess.add(job_info)
sess.flush()
jobDict['programValid'] = job_info.job_id
submissionId = cls.insertSubmission(sess, user)
job_info = Job(
filename=cls.uploadFile("awardFinancialValid.csv", user),
job_status_id=statusReadyId,
job_type_id=jobTypeCsvId,
file_type_id=FILE_TYPE_DICT['award_financial'],
submission_id=submissionId)
sess.add(job_info)
sess.flush()
jobDict['awardFinValid'] = job_info.job_id
# next two jobs have the same submission id
submissionId = cls.insertSubmission(sess, user)
job_info = Job(
filename=cls.uploadFile("awardValid.csv", user),
job_status_id=statusReadyId,
job_type_id=jobTypeCsvId,
file_type_id=FILE_TYPE_DICT['award'],
submission_id=submissionId)
sess.add(job_info)
sess.flush()
jobDict['awardValid'] = job_info.job_id
job_info = Job(
filename=cls.uploadFile("awardProcValid.csv", user),
job_status_id=statusReadyId,
job_type_id=jobTypeCsvId,
file_type_id=FILE_TYPE_DICT['award_procurement'],
submission_id=submissionId)
sess.add(job_info)
sess.flush()
jobDict['awardProcValid'] = job_info.job_id
# commit submissions/jobs and output IDs
sess.commit()
for job_type, job_id in jobDict.items():
print('{}: {}'.format(job_type, job_id))
# Load fields and rules
FileTypeTests.load_definitions(sess, force_tas_load)
cls.jobDict = jobDict
@staticmethod
def load_definitions(sess, force_tas_load, ruleList=None):
"""Load file definitions."""
validator_config_path = os.path.join(CONFIG_BROKER["path"], "dataactvalidator", "config")
integration_test_data_path = os.path.join(CONFIG_BROKER["path"], "tests", "integration", "data")
SchemaLoader.loadAllFromPath(validator_config_path)
SQLLoader.loadSql("sqlRules.csv")
if ruleList is not None:
# If rule list provided, drop all other rules
sess.query(RuleSql).filter(not_(
RuleSql.rule_label.in_(ruleList))).delete(synchronize_session='fetch')
sess.commit()
# Load domain values tables
loadDomainValues(
validator_config_path,
os.path.join(integration_test_data_path, "program_activity.csv"))
if sess.query(TASLookup).count() == 0 or force_tas_load:
# TAS table is empty, load it
loadTas(tasFile=os.path.join(integration_test_data_path, "cars_tas.csv"))
# Load test SF-133
load_all_sf133(integration_test_data_path)
def test_approp_valid(self):
"""Test valid job."""
jobId = self.jobDict["valid"]
self.passed = self.run_test(
jobId, 200, "finished", 63, 10, "complete", 0, numWarnings=10)
def test_program_valid(self):
"""Test valid job."""
jobId = self.jobDict["programValid"]
self.passed = self.run_test(
jobId, 200, "finished", 63, 10, "complete", 0)
def test_award_fin_valid(self):
"""Test valid job."""
jobId = self.jobDict["awardFinValid"]
self.passed = self.run_test(
jobId, 200, "finished", 63, 10, "complete", 0, numWarnings=3)
def test_award_valid(self):
"""Test valid job."""
jobId = self.jobDict["awardValid"]
self.passed = self.run_test(
jobId, 200, "finished", 63, 10, "complete", 0)
def test_award_proc_valid(self):
"""Test valid job."""
jobId = self.jobDict["awardProcValid"]
self.passed = self.run_test(
jobId, 200, "finished", 63, 10, "complete", 0, False)
if __name__ == '__main__':
unittest.main()
| from __future__ import print_function
import os
import unittest
from sqlalchemy import not_
from dataactcore.interfaces.db import GlobalDB
from dataactcore.models.domainModels import TASLookup
from dataactcore.models.jobModels import Job
from dataactcore.models.lookups import JOB_STATUS_DICT, JOB_TYPE_DICT, FILE_TYPE_DICT
from dataactcore.models.validationModels import RuleSql
from dataactcore.config import CONFIG_BROKER
from dataactvalidator.app import createApp
from dataactvalidator.filestreaming.sqlLoader import SQLLoader
from dataactvalidator.filestreaming.schemaLoader import SchemaLoader
from dataactvalidator.scripts.loadFile import loadDomainValues
from dataactvalidator.scripts.loadTas import loadTas
from dataactvalidator.scripts.load_sf133 import load_all_sf133
from tests.integration.baseTestValidator import BaseTestValidator
class FileTypeTests(BaseTestValidator):
@classmethod
def setUpClass(cls):
"""Set up class-wide resources."""
super(FileTypeTests, cls).setUpClass()
#TODO: refactor into a pytest fixture
user = cls.userId
# TODO: get rid of this flag once we're using a tempdb for test fixtures
force_tas_load = False
with createApp().app_context():
sess = GlobalDB.db().session
# Create submissions and jobs, also uploading
# the files needed for each job.
statusReadyId = JOB_STATUS_DICT['ready']
jobTypeCsvId = JOB_TYPE_DICT['csv_record_validation']
jobDict = {}
submissionId = cls.insertSubmission(sess, user)
job_info = Job(
filename=cls.uploadFile("appropValid.csv", user),
job_status_id=statusReadyId,
job_type_id=jobTypeCsvId,
file_type_id=FILE_TYPE_DICT['appropriations'],
submission_id=submissionId)
sess.add(job_info)
sess.flush()
jobDict['valid'] = job_info.job_id
submissionId = cls.insertSubmission(sess, user)
job_info = Job(
filename=cls.uploadFile("programActivityValid.csv", user),
job_status_id=statusReadyId,
job_type_id=jobTypeCsvId,
file_type_id=FILE_TYPE_DICT['program_activity'],
submission_id=submissionId)
sess.add(job_info)
sess.flush()
jobDict['programValid'] = job_info.job_id
submissionId = cls.insertSubmission(sess, user)
job_info = Job(
filename=cls.uploadFile("awardFinancialValid.csv", user),
job_status_id=statusReadyId,
job_type_id=jobTypeCsvId,
file_type_id=FILE_TYPE_DICT['award_financial'],
submission_id=submissionId)
sess.add(job_info)
sess.flush()
jobDict['awardFinValid'] = job_info.job_id
# next two jobs have the same submission id
submissionId = cls.insertSubmission(sess, user)
job_info = Job(
filename=cls.uploadFile("awardValid.csv", user),
job_status_id=statusReadyId,
job_type_id=jobTypeCsvId,
file_type_id=FILE_TYPE_DICT['award'],
submission_id=submissionId)
sess.add(job_info)
sess.flush()
jobDict['awardValid'] = job_info.job_id
job_info = Job(
filename=cls.uploadFile("awardProcValid.csv", user),
job_status_id=statusReadyId,
job_type_id=jobTypeCsvId,
file_type_id=FILE_TYPE_DICT['award_procurement'],
submission_id=submissionId)
sess.add(job_info)
sess.flush()
jobDict['awardProcValid'] = job_info.job_id
# commit submissions/jobs and output IDs
sess.commit()
for job_type, job_id in jobDict.items():
print('{}: {}'.format(job_type, job_id))
# Load fields and rules
FileTypeTests.load_definitions(sess, force_tas_load)
cls.jobDict = jobDict
@staticmethod
def load_definitions(sess, force_tas_load, ruleList=None):
"""Load file definitions."""
validator_config_path = os.path.join(CONFIG_BROKER["path"], "dataactvalidator", "config")
integration_test_data_path = os.path.join(CONFIG_BROKER["path"], "tests", "integration", "data")
SchemaLoader.loadAllFromPath(validator_config_path)
SQLLoader.loadSql("sqlRules.csv")
if ruleList is not None:
# If rule list provided, drop all other rules
sess.query(RuleSql).filter(not_(
RuleSql.rule_label.in_(ruleList))).delete(synchronize_session='fetch')
sess.commit()
# Load domain values tables
loadDomainValues(
validator_config_path,
os.path.join(integration_test_data_path, "program_activity.csv"))
if sess.query(TASLookup).count() == 0 or force_tas_load:
# TAS table is empty, load it
loadTas(tasFile=os.path.join(integration_test_data_path, "cars_tas.csv"))
# Load test SF-133
load_all_sf133(integration_test_data_path)
def test_approp_valid(self):
"""Test valid job."""
jobId = self.jobDict["valid"]
self.passed = self.run_test(
jobId, 200, "finished", 63, 10, "complete", 0, numWarnings=10)
def test_program_valid(self):
"""Test valid job."""
jobId = self.jobDict["programValid"]
self.passed = self.run_test(
jobId, 200, "finished", 63, 10, "complete", 0)
def test_award_fin_valid(self):
"""Test valid job."""
jobId = self.jobDict["awardFinValid"]
self.passed = self.run_test(
jobId, 200, "finished", 63, 10, "complete", 0, numWarnings=3)
def test_award_valid(self):
"""Test valid job."""
jobId = self.jobDict["awardValid"]
self.passed = self.run_test(
jobId, 200, "finished", 63, 10, "complete", 0)
def test_award_proc_valid(self):
"""Test valid job."""
jobId = self.jobDict["awardProcValid"]
self.passed = self.run_test(
jobId, 200, "finished", 63, 10, "complete", 0, False)
if __name__ == '__main__':
unittest.main()
| en | 0.807824 | Set up class-wide resources. #TODO: refactor into a pytest fixture # TODO: get rid of this flag once we're using a tempdb for test fixtures # Create submissions and jobs, also uploading # the files needed for each job. # next two jobs have the same submission id # commit submissions/jobs and output IDs # Load fields and rules Load file definitions. # If rule list provided, drop all other rules # Load domain values tables # TAS table is empty, load it # Load test SF-133 Test valid job. Test valid job. Test valid job. Test valid job. Test valid job. | 1.82377 | 2 |
Tianchi2017IMQP-TeamExcited/preprocessing/string_data.py | polossk/DSML-Logs | 2 | 6623077 | import sys
sys.path.append('../')
from utils.csv_helper import *
from utils.xslx_helper import *
from utils.pickle_helper import *
def main():
idics_ABC = [
'A', 'B', 'HY', 'ABY', 'ACU', 'AJJ', 'BMM', 'CMQ',
'ELC', 'ESU', 'FDJ', 'HUY', 'IDE', 'IRX', 'KVU'
]
works = ['raw_data.bin', 'test_a.bin', 'test_b.bin']
idics = list(map(abc2dec, idics_ABC))
for _ in works:
if _ != 'raw_data.bin': idx = idics[:-1]
raw_data = read_pickle(_)
load = lambda a, x: a[x]
string_data = []
for sample in raw_data:
def load_help(x): return load(sample, x - 1)
string_data.append(list(map(load_help, idx)))
print(string_data[-1])
print(len(string_data[-1]))
pickled = pickle.dumps(string_data)
write_pickle('string_'+_, pickled)
write_csv('string_{0}.csv'.format(_), string_data)
if __name__ == '__main__':
main()
| import sys
sys.path.append('../')
from utils.csv_helper import *
from utils.xslx_helper import *
from utils.pickle_helper import *
def main():
idics_ABC = [
'A', 'B', 'HY', 'ABY', 'ACU', 'AJJ', 'BMM', 'CMQ',
'ELC', 'ESU', 'FDJ', 'HUY', 'IDE', 'IRX', 'KVU'
]
works = ['raw_data.bin', 'test_a.bin', 'test_b.bin']
idics = list(map(abc2dec, idics_ABC))
for _ in works:
if _ != 'raw_data.bin': idx = idics[:-1]
raw_data = read_pickle(_)
load = lambda a, x: a[x]
string_data = []
for sample in raw_data:
def load_help(x): return load(sample, x - 1)
string_data.append(list(map(load_help, idx)))
print(string_data[-1])
print(len(string_data[-1]))
pickled = pickle.dumps(string_data)
write_pickle('string_'+_, pickled)
write_csv('string_{0}.csv'.format(_), string_data)
if __name__ == '__main__':
main()
| none | 1 | 2.478613 | 2 | |
backend/tests/links/test_models.py | apirobot/linkanywhere-back | 0 | 6623078 | from unittest import mock
import pytest
from nose.tools import eq_
from django_nose.tools import assert_queryset_equal
from .. import factories as f
pytestmark = pytest.mark.django_db
class TestLinkModel:
def test__str__(self):
user = f.LinkFactory()
eq_(user.__str__(), '{0}: {1}'.format(user.title, user.url))
def test_relation_with_category(self):
category_1 = f.CategoryFactory()
link_1 = f.LinkFactory(category=category_1)
link_2 = f.LinkFactory(category=category_1)
eq_(link_1.category, category_1)
eq_(link_2.category, category_1)
def test_relation_with_tags(self):
tag_1 = f.TagFactory()
tag_2 = f.TagFactory()
link_1 = f.LinkFactory(tags=[tag_1, tag_2])
link_2 = f.LinkFactory(tags=[tag_1])
assert_queryset_equal(
link_1.tags.all(),
[repr(tag_1), repr(tag_2)],
ordered=False
)
assert_queryset_equal(
link_2.tags.all(),
[repr(tag_1)],
ordered=False
)
def test_total_likes(self):
link_1 = f.LinkFactory()
with mock.patch('linkanywhere.apps.links.models.Link.likes') as likes_mock:
link_1.total_likes
likes_mock.count.assert_called()
def test_get_url_domain(self):
link_1 = f.LinkFactory(url='http://stackoverflow.com/questions/17/blah-blah')
link_2 = f.LinkFactory(url='http://www.google.com/blah-blah')
link_3 = f.LinkFactory(url='http://news.cnn.com/blah-blah')
eq_(link_1.get_url_domain(), 'stackoverflow.com')
eq_(link_2.get_url_domain(), 'google.com')
eq_(link_3.get_url_domain(), 'cnn.<EMAIL>')
| from unittest import mock
import pytest
from nose.tools import eq_
from django_nose.tools import assert_queryset_equal
from .. import factories as f
pytestmark = pytest.mark.django_db
class TestLinkModel:
def test__str__(self):
user = f.LinkFactory()
eq_(user.__str__(), '{0}: {1}'.format(user.title, user.url))
def test_relation_with_category(self):
category_1 = f.CategoryFactory()
link_1 = f.LinkFactory(category=category_1)
link_2 = f.LinkFactory(category=category_1)
eq_(link_1.category, category_1)
eq_(link_2.category, category_1)
def test_relation_with_tags(self):
tag_1 = f.TagFactory()
tag_2 = f.TagFactory()
link_1 = f.LinkFactory(tags=[tag_1, tag_2])
link_2 = f.LinkFactory(tags=[tag_1])
assert_queryset_equal(
link_1.tags.all(),
[repr(tag_1), repr(tag_2)],
ordered=False
)
assert_queryset_equal(
link_2.tags.all(),
[repr(tag_1)],
ordered=False
)
def test_total_likes(self):
link_1 = f.LinkFactory()
with mock.patch('linkanywhere.apps.links.models.Link.likes') as likes_mock:
link_1.total_likes
likes_mock.count.assert_called()
def test_get_url_domain(self):
link_1 = f.LinkFactory(url='http://stackoverflow.com/questions/17/blah-blah')
link_2 = f.LinkFactory(url='http://www.google.com/blah-blah')
link_3 = f.LinkFactory(url='http://news.cnn.com/blah-blah')
eq_(link_1.get_url_domain(), 'stackoverflow.com')
eq_(link_2.get_url_domain(), 'google.com')
eq_(link_3.get_url_domain(), 'cnn.<EMAIL>')
| none | 1 | 2.268169 | 2 | |
hypernets/tests/tabular/tb_cuml/feature_importance_test.py | Enpen/Hypernets | 3 | 6623079 | # -*- coding:utf-8 -*-
__author__ = 'yangjian'
"""
"""
from ..feature_importance_test import TestPermutationImportance as _TestPermutationImportance
from . import if_cuml_ready, is_cuml_installed
if is_cuml_installed:
import cudf
@if_cuml_ready
class TestCumlPermutationImportance(_TestPermutationImportance):
@staticmethod
def load_data():
df = _TestPermutationImportance.load_data()
df = cudf.from_pandas(df)
return df
| # -*- coding:utf-8 -*-
__author__ = 'yangjian'
"""
"""
from ..feature_importance_test import TestPermutationImportance as _TestPermutationImportance
from . import if_cuml_ready, is_cuml_installed
if is_cuml_installed:
import cudf
@if_cuml_ready
class TestCumlPermutationImportance(_TestPermutationImportance):
@staticmethod
def load_data():
df = _TestPermutationImportance.load_data()
df = cudf.from_pandas(df)
return df
| en | 0.736017 | # -*- coding:utf-8 -*- | 2.00859 | 2 |
sqlcell/db.py | tmthyjames/SQLCell | 162 | 6623080 | from sqlalchemy import create_engine
from sqlalchemy.engine.url import make_url
from sqlalchemy.ext.automap import automap_base
from sqlalchemy.orm import Session, sessionmaker
from sqlalchemy import create_engine
from sqlalchemy import desc, asc
from sqlalchemy.engine.base import Engine
import pandas as pd
import re
class DBSessionHandler(object):
def __init__(self):
Base = automap_base()
engine = create_engine("sqlite:///sqlcell.db")
Base.prepare(engine, reflect=True)
self.classes = Base.classes
self.tables = Base.metadata.tables.keys()
self.Sqlcell = Base.classes.sqlcell
self.Engines = Base.classes.engines
self.Hooks = Base.classes.hooks
Session = sessionmaker(autoflush=False)
Session.configure(bind=engine)
self.session = Session()
dbs = self.session.query(self.Engines).all()
self.db_info = {}
for row in dbs:
engine = row.engine
if row.db:
self.db_info[row.db] = engine
if row.alias:
self.db_info[row.alias] = engine
self.db_info[engine] = engine
self.db_info[row.host] = engine
def recycle(self):
pass
def create(self):
pass
def dispose(self):
pass
class EngineHandler(DBSessionHandler):
"""remove all engines from sqlcell.db:
%%sql refresh
may have to use @cell_line_magic.
add multiple new engines:
%%sql add
foo=<engine str>
bar=<another engine str>
baz=<another engine str>"""
def __init__(self, *args, **kwargs):
super(EngineHandler, self).__init__()
def list(self):
"show all alias/engines"
engines = []
for row in self.session.query(self.Engines):
engine = {
'Alias': row.alias,
'Engine': row.engine
}
engines.append(engine)
return pd.DataFrame(engines)
@property
def latest_engine(self) -> Engine:
record = self.session.query(self.Engines).order_by(desc(self.Engines.dt)).limit(1).first()
if record:
engine = record.engine
return create_engine(engine)
def get_engine(self, engine_var: str, session_engine: bool or Engine=False, as_binary: bool=False):
if engine_var:
if engine_var not in self.db_info:
engine = create_engine(engine_var) #new engines
self.add_engine(engine)
else:
engine = create_engine(self.db_info[engine_var]) #engine lookup
else:
engine = session_engine or self.latest_engine
return engine
def add_engine(self, engine: Engine, alias: str=None) -> None:
if isinstance(engine, str):
engine = make_url(engine)
else:
engine = engine.url
host = engine.host
db = engine.database
engine_str = str(engine)
engine_exists_check = self.session.query(self.Engines).filter_by(db=db, host=host, engine=engine_str).first()
if engine_exists_check: return None
self.session.add(self.Engines(db=db, host=host, engine=engine_str, alias=alias))
self.session.commit()
def add_alias(self, cell):
for i in re.split('\n{1,}', cell):
row = i.replace(' ', '').split('=', 1)
if row[1:]:
alias, engine = row
self.add_engine(engine, alias=alias)
return ('Engines successfully registered')
def refresh(self, cell):
self.session.query(self.Engines).delete()
self.session.commit()
| from sqlalchemy import create_engine
from sqlalchemy.engine.url import make_url
from sqlalchemy.ext.automap import automap_base
from sqlalchemy.orm import Session, sessionmaker
from sqlalchemy import create_engine
from sqlalchemy import desc, asc
from sqlalchemy.engine.base import Engine
import pandas as pd
import re
class DBSessionHandler(object):
def __init__(self):
Base = automap_base()
engine = create_engine("sqlite:///sqlcell.db")
Base.prepare(engine, reflect=True)
self.classes = Base.classes
self.tables = Base.metadata.tables.keys()
self.Sqlcell = Base.classes.sqlcell
self.Engines = Base.classes.engines
self.Hooks = Base.classes.hooks
Session = sessionmaker(autoflush=False)
Session.configure(bind=engine)
self.session = Session()
dbs = self.session.query(self.Engines).all()
self.db_info = {}
for row in dbs:
engine = row.engine
if row.db:
self.db_info[row.db] = engine
if row.alias:
self.db_info[row.alias] = engine
self.db_info[engine] = engine
self.db_info[row.host] = engine
def recycle(self):
pass
def create(self):
pass
def dispose(self):
pass
class EngineHandler(DBSessionHandler):
"""remove all engines from sqlcell.db:
%%sql refresh
may have to use @cell_line_magic.
add multiple new engines:
%%sql add
foo=<engine str>
bar=<another engine str>
baz=<another engine str>"""
def __init__(self, *args, **kwargs):
super(EngineHandler, self).__init__()
def list(self):
"show all alias/engines"
engines = []
for row in self.session.query(self.Engines):
engine = {
'Alias': row.alias,
'Engine': row.engine
}
engines.append(engine)
return pd.DataFrame(engines)
@property
def latest_engine(self) -> Engine:
record = self.session.query(self.Engines).order_by(desc(self.Engines.dt)).limit(1).first()
if record:
engine = record.engine
return create_engine(engine)
def get_engine(self, engine_var: str, session_engine: bool or Engine=False, as_binary: bool=False):
if engine_var:
if engine_var not in self.db_info:
engine = create_engine(engine_var) #new engines
self.add_engine(engine)
else:
engine = create_engine(self.db_info[engine_var]) #engine lookup
else:
engine = session_engine or self.latest_engine
return engine
def add_engine(self, engine: Engine, alias: str=None) -> None:
if isinstance(engine, str):
engine = make_url(engine)
else:
engine = engine.url
host = engine.host
db = engine.database
engine_str = str(engine)
engine_exists_check = self.session.query(self.Engines).filter_by(db=db, host=host, engine=engine_str).first()
if engine_exists_check: return None
self.session.add(self.Engines(db=db, host=host, engine=engine_str, alias=alias))
self.session.commit()
def add_alias(self, cell):
for i in re.split('\n{1,}', cell):
row = i.replace(' ', '').split('=', 1)
if row[1:]:
alias, engine = row
self.add_engine(engine, alias=alias)
return ('Engines successfully registered')
def refresh(self, cell):
self.session.query(self.Engines).delete()
self.session.commit()
| en | 0.624827 | remove all engines from sqlcell.db: %%sql refresh may have to use @cell_line_magic. add multiple new engines: %%sql add foo=<engine str> bar=<another engine str> baz=<another engine str> #new engines #engine lookup | 2.482173 | 2 |
GUI/AdminUI/Admin_UI.py | BrendanCheong/BT2102-OSHES-Group16 | 5 | 6623081 | <reponame>BrendanCheong/BT2102-OSHES-Group16
import resources_rc
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(1914, 1077)
MainWindow.setMinimumSize(QtCore.QSize(1000, 500))
MainWindow.setStyleSheet("background-color: rgb(45, 45, 45);")
self.centralwidget = QtWidgets.QWidget(MainWindow)
sizePolicy = QtWidgets.QSizePolicy(
QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.centralwidget.sizePolicy().hasHeightForWidth())
self.centralwidget.setSizePolicy(sizePolicy)
self.centralwidget.setObjectName("centralwidget")
self.verticalLayout = QtWidgets.QVBoxLayout(self.centralwidget)
self.verticalLayout.setContentsMargins(0, 0, 0, 0)
self.verticalLayout.setSpacing(0)
self.verticalLayout.setObjectName("verticalLayout")
self.Top_Bar = QtWidgets.QFrame(self.centralwidget)
self.Top_Bar.setEnabled(True)
self.Top_Bar.setMaximumSize(QtCore.QSize(16777215, 70))
self.Top_Bar.setStyleSheet("background-color: rgb(35, 35, 35);")
self.Top_Bar.setFrameShape(QtWidgets.QFrame.NoFrame)
self.Top_Bar.setFrameShadow(QtWidgets.QFrame.Raised)
self.Top_Bar.setObjectName("Top_Bar")
self.horizontalLayout = QtWidgets.QHBoxLayout(self.Top_Bar)
self.horizontalLayout.setContentsMargins(0, 0, 0, 0)
self.horizontalLayout.setSpacing(0)
self.horizontalLayout.setObjectName("horizontalLayout")
self.frame_toggle = QtWidgets.QFrame(self.Top_Bar)
self.frame_toggle.setMaximumSize(QtCore.QSize(70, 40))
self.frame_toggle.setStyleSheet("")
self.frame_toggle.setFrameShape(QtWidgets.QFrame.StyledPanel)
self.frame_toggle.setFrameShadow(QtWidgets.QFrame.Raised)
self.frame_toggle.setObjectName("frame_toggle")
self.verticalLayout_2 = QtWidgets.QVBoxLayout(self.frame_toggle)
self.verticalLayout_2.setContentsMargins(0, 0, 0, 0)
self.verticalLayout_2.setObjectName("verticalLayout_2")
self.Btn_Toggle = QtWidgets.QPushButton(self.frame_toggle)
sizePolicy = QtWidgets.QSizePolicy(
QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.Btn_Toggle.sizePolicy().hasHeightForWidth())
self.Btn_Toggle.setSizePolicy(sizePolicy)
self.Btn_Toggle.setMaximumSize(QtCore.QSize(16777215, 16777215))
self.Btn_Toggle.setSizeIncrement(QtCore.QSize(0, 0))
self.Btn_Toggle.setBaseSize(QtCore.QSize(0, 0))
font = QtGui.QFont()
font.setPointSize(14)
self.Btn_Toggle.setFont(font)
self.Btn_Toggle.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))
self.Btn_Toggle.setStyleSheet("image: url(:/menuBurger/icons8-menu-48.png);\n"
"color: rgb(255, 255, 255);\n"
"border: 0px solid;\n"
"background-color: rgb(35, 35, 25);\n"
"padding-left: 25px;")
self.Btn_Toggle.setText("")
self.Btn_Toggle.setObjectName("Btn_Toggle")
self.verticalLayout_2.addWidget(self.Btn_Toggle)
self.horizontalLayout.addWidget(self.frame_toggle)
self.frame_top = QtWidgets.QFrame(self.Top_Bar)
self.frame_top.setMaximumSize(QtCore.QSize(16777215, 16777215))
self.frame_top.setFrameShape(QtWidgets.QFrame.StyledPanel)
self.frame_top.setFrameShadow(QtWidgets.QFrame.Raised)
self.frame_top.setObjectName("frame_top")
self.title = QtWidgets.QLabel(self.frame_top)
self.title.setGeometry(QtCore.QRect(640, 10, 641, 51))
self.title.setMaximumSize(QtCore.QSize(641, 16777215))
font = QtGui.QFont()
font.setFamily("8514oem")
font.setPointSize(32)
font.setBold(True)
font.setWeight(75)
self.title.setFont(font)
self.title.setStyleSheet("color: #C7D2FE;")
self.title.setAlignment(QtCore.Qt.AlignCenter)
self.title.setObjectName("title")
self.horizontalLayout.addWidget(self.frame_top)
self.verticalLayout.addWidget(self.Top_Bar)
self.Content = QtWidgets.QFrame(self.centralwidget)
self.Content.setFrameShape(QtWidgets.QFrame.NoFrame)
self.Content.setFrameShadow(QtWidgets.QFrame.Raised)
self.Content.setObjectName("Content")
self.horizontalLayout_2 = QtWidgets.QHBoxLayout(self.Content)
self.horizontalLayout_2.setContentsMargins(0, 0, 0, 0)
self.horizontalLayout_2.setSpacing(0)
self.horizontalLayout_2.setObjectName("horizontalLayout_2")
self.frame_left_menu = QtWidgets.QFrame(self.Content)
self.frame_left_menu.setMinimumSize(QtCore.QSize(0, 0))
self.frame_left_menu.setMaximumSize(QtCore.QSize(100, 16777215))
self.frame_left_menu.setStyleSheet("background-color: rgb(35, 35, 35);\n"
"padding:1px;")
self.frame_left_menu.setFrameShape(QtWidgets.QFrame.StyledPanel)
self.frame_left_menu.setFrameShadow(QtWidgets.QFrame.Raised)
self.frame_left_menu.setObjectName("frame_left_menu")
self.verticalLayout_3 = QtWidgets.QVBoxLayout(self.frame_left_menu)
self.verticalLayout_3.setObjectName("verticalLayout_3")
self.btn_page_1 = QtWidgets.QPushButton(self.frame_left_menu)
self.btn_page_1.setMinimumSize(QtCore.QSize(0, 100))
font = QtGui.QFont()
font.setFamily("8514oem")
font.setPointSize(20)
self.btn_page_1.setFont(font)
self.btn_page_1.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))
self.btn_page_1.setStyleSheet("QPushButton {\n"
" \n"
" image: url(:/adminSideBar/icons8-home-48.png);\n"
" color: rgb(255, 255, 255);\n"
" background-color: rgb(35, 35, 35);\n"
" border: 0px solid;\n"
" padding-right: 0px;\n"
"}\n"
"QPushButton:hover {\n"
" \n"
" background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 #2DD4BF, stop:1 #0EA5E9);\n"
" border-radius: 20px;\n"
"}")
self.btn_page_1.setObjectName("btn_page_1")
self.verticalLayout_3.addWidget(self.btn_page_1)
self.btn_page_2 = QtWidgets.QPushButton(self.frame_left_menu)
self.btn_page_2.setMinimumSize(QtCore.QSize(0, 100))
font = QtGui.QFont()
font.setFamily("8514oem")
font.setPointSize(20)
self.btn_page_2.setFont(font)
self.btn_page_2.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))
self.btn_page_2.setStyleSheet("QPushButton {\n"
" \n"
" image: url(:/adminSideBar/icons8-products-49.png);\n"
" color: rgb(255, 255, 255);\n"
" background-color: rgb(35, 35, 35);\n"
" border: 0px solid;\n"
" padding-right: 0px;\n"
"}\n"
"QPushButton:hover {\n"
" background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 #2DD4BF, stop:1 #0EA5E9);\n"
" border-radius: 20px;\n"
"}")
self.btn_page_2.setObjectName("btn_page_2")
self.verticalLayout_3.addWidget(self.btn_page_2)
self.btn_page_3 = QtWidgets.QPushButton(self.frame_left_menu)
self.btn_page_3.setMinimumSize(QtCore.QSize(0, 100))
font = QtGui.QFont()
font.setFamily("8514oem")
font.setPointSize(20)
self.btn_page_3.setFont(font)
self.btn_page_3.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))
self.btn_page_3.setStyleSheet("QPushButton {\n"
" \n"
" \n"
" image: url(:/adminSideBar/icons8-product-management-48.png);\n"
" color: rgb(255, 255, 255);\n"
" background-color: rgb(35, 35, 35);\n"
" border: 0px solid;\n"
" padding-right: 0px;\n"
"}\n"
"QPushButton:hover {\n"
" background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 #2DD4BF, stop:1 #0EA5E9);\n"
" border-radius: 20px;\n"
"}")
self.btn_page_3.setObjectName("btn_page_3")
self.verticalLayout_3.addWidget(self.btn_page_3)
self.btn_page_5 = QtWidgets.QPushButton(self.frame_left_menu)
self.btn_page_5.setMinimumSize(QtCore.QSize(0, 100))
font = QtGui.QFont()
font.setFamily("8514oem")
font.setPointSize(20)
self.btn_page_5.setFont(font)
self.btn_page_5.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))
self.btn_page_5.setStyleSheet("QPushButton {\n"
" \n"
" \n"
" image: url(:/adminSideBar/icons8-attract-customers-48.png);\n"
" color: rgb(255, 255, 255);\n"
" background-color: rgb(35, 35, 35);\n"
" border: 0px solid;\n"
" padding-right: 0px;\n"
"}\n"
"QPushButton:hover {\n"
" \n"
" background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 #2DD4BF, stop:1 #0EA5E9);\n"
" border-radius: 20px;\n"
"}")
self.btn_page_5.setObjectName("btn_page_5")
self.verticalLayout_3.addWidget(self.btn_page_5)
self.btn_page_6 = QtWidgets.QPushButton(self.frame_left_menu)
self.btn_page_6.setMinimumSize(QtCore.QSize(0, 100))
font = QtGui.QFont()
font.setFamily("8514oem")
font.setPointSize(20)
self.btn_page_6.setFont(font)
self.btn_page_6.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))
self.btn_page_6.setStyleSheet("QPushButton {\n"
" \n"
" \n"
" image: url(:/adminSideBar/icons8-service-48.png);\n"
" color: rgb(255, 255, 255);\n"
" background-color: rgb(35, 35, 35);\n"
" border: 0px solid;\n"
" padding-right: 0px;\n"
"}\n"
"QPushButton:hover {\n"
" \n"
" background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 #2DD4BF, stop:1 #0EA5E9);\n"
" border-radius: 20px;\n"
"}")
self.btn_page_6.setObjectName("btn_page_6")
self.verticalLayout_3.addWidget(self.btn_page_6)
self.btn_page_4 = QtWidgets.QPushButton(self.frame_left_menu)
sizePolicy = QtWidgets.QSizePolicy(
QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.btn_page_4.sizePolicy().hasHeightForWidth())
self.btn_page_4.setSizePolicy(sizePolicy)
self.btn_page_4.setMinimumSize(QtCore.QSize(0, 100))
font = QtGui.QFont()
font.setFamily("8514oem")
font.setPointSize(20)
self.btn_page_4.setFont(font)
self.btn_page_4.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))
self.btn_page_4.setStyleSheet("QPushButton {\n"
" image: url(:/SideBar/icons8-exit-48.png);\n"
" color: rgb(255, 255, 255);\n"
" background-color: rgb(35, 35, 35);\n"
" border: 0px solid;\n"
" padding-right: 0px;\n"
"}\n"
"QPushButton:hover {\n"
" background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 #2DD4BF, stop:1 #0EA5E9);\n"
" border-radius: 20px;\n"
"}")
self.btn_page_4.setObjectName("btn_page_4")
self.verticalLayout_3.addWidget(self.btn_page_4)
self.frame_top_menus = QtWidgets.QFrame(self.frame_left_menu)
self.frame_top_menus.setMinimumSize(QtCore.QSize(0, 0))
self.frame_top_menus.setFrameShape(QtWidgets.QFrame.NoFrame)
self.frame_top_menus.setFrameShadow(QtWidgets.QFrame.Raised)
self.frame_top_menus.setObjectName("frame_top_menus")
self.verticalLayout_3.addWidget(self.frame_top_menus)
self.horizontalLayout_2.addWidget(self.frame_left_menu)
self.frame_pages = QtWidgets.QFrame(self.Content)
self.frame_pages.setFrameShape(QtWidgets.QFrame.StyledPanel)
self.frame_pages.setFrameShadow(QtWidgets.QFrame.Raised)
self.frame_pages.setObjectName("frame_pages")
self.verticalLayout_5 = QtWidgets.QVBoxLayout(self.frame_pages)
self.verticalLayout_5.setSizeConstraint(
QtWidgets.QLayout.SetNoConstraint)
self.verticalLayout_5.setObjectName("verticalLayout_5")
self.stackedWidget = QtWidgets.QStackedWidget(self.frame_pages)
palette = QtGui.QPalette()
brush = QtGui.QBrush(QtGui.QColor(45, 45, 45))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Button, brush)
brush = QtGui.QBrush(QtGui.QColor(45, 45, 45))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Base, brush)
brush = QtGui.QBrush(QtGui.QColor(45, 45, 45))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Window, brush)
brush = QtGui.QBrush(QtGui.QColor(45, 45, 45))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Button, brush)
brush = QtGui.QBrush(QtGui.QColor(45, 45, 45))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Base, brush)
brush = QtGui.QBrush(QtGui.QColor(45, 45, 45))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Window, brush)
brush = QtGui.QBrush(QtGui.QColor(45, 45, 45))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Button, brush)
brush = QtGui.QBrush(QtGui.QColor(45, 45, 45))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Base, brush)
brush = QtGui.QBrush(QtGui.QColor(45, 45, 45))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Window, brush)
self.stackedWidget.setPalette(palette)
self.stackedWidget.setStyleSheet("")
self.stackedWidget.setFrameShape(QtWidgets.QFrame.NoFrame)
self.stackedWidget.setObjectName("stackedWidget")
self.page_1 = QtWidgets.QWidget()
self.page_1.setObjectName("page_1")
self.welcome_admin_label = QtWidgets.QLabel(self.page_1)
self.welcome_admin_label.setGeometry(QtCore.QRect(670, 0, 461, 91))
font = QtGui.QFont()
font.setFamily("8514oem")
font.setPointSize(25)
self.welcome_admin_label.setFont(font)
self.welcome_admin_label.setStyleSheet("color: rgb(255, 255, 255);\n"
"image: url(:/adminSideBar/icons8-home-48.png);\n"
"padding-right:50px;")
self.welcome_admin_label.setAlignment(
QtCore.Qt.AlignRight | QtCore.Qt.AlignTrailing | QtCore.Qt.AlignVCenter)
self.welcome_admin_label.setObjectName("welcome_admin_label")
self.admin_table = QtWidgets.QTableWidget(self.page_1)
self.admin_table.setGeometry(QtCore.QRect(20, 325, 1761, 561))
self.admin_table.setSizeIncrement(QtCore.QSize(0, 0))
font = QtGui.QFont()
font.setFamily("8514oem")
font.setPointSize(10)
font.setBold(False)
font.setItalic(False)
font.setWeight(50)
self.admin_table.setFont(font)
self.admin_table.setLayoutDirection(QtCore.Qt.LeftToRight)
self.admin_table.setAutoFillBackground(False)
self.admin_table.setStyleSheet("QWidget {\n"
" background-color: rgb(255, 255, 255);\n"
" alternate-background-color: rgb(241, 245, 249);\n"
" font: 10pt \"8514oem\";\n"
"}\n"
"QScrollBar:vertical {\n"
" border: none;\n"
" background: #94A3B8;\n"
" width: 14px;\n"
" margin: 15px 0 15px 0;\n"
" border-radius: 0px;\n"
" }\n"
"\n"
"/* HANDLE BAR VERTICAL */\n"
"QScrollBar::handle:vertical { \n"
" background-color: #E5E7EB;\n"
" min-height: 30px;\n"
" border-radius: 7px;\n"
"}\n"
"QScrollBar::handle:vertical:hover{ \n"
" background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 #6366F1, stop:1 #7C3AED);\n"
"}\n"
"QScrollBar::handle:vertical:pressed { \n"
" background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 #4338CA, stop:1 #5B21B6);\n"
"}\n"
"\n"
"/* BTN TOP - SCROLLBAR */\n"
"QScrollBar::sub-line:vertical {\n"
" border: none;\n"
" background-color: #94A3B8;\n"
" height: 15px;\n"
" border-top-left-radius: 7px;\n"
" border-top-right-radius: 7px;\n"
" subcontrol-position: top;\n"
" subcontrol-origin: margin;\n"
"}\n"
"QScrollBar::sub-line:vertical:hover { \n"
" background-color: rgb(255, 0, 127);\n"
"}\n"
"QScrollBar::sub-line:vertical:pressed { \n"
" background-color: rgb(185, 0, 92);\n"
"}\n"
"\n"
"/* BTN BOTTOM - SCROLLBAR */\n"
"QScrollBar::add-line:vertical {\n"
" border: none;\n"
" background-color:#94A3B8;\n"
" height: 15px;\n"
" border-bottom-left-radius: 7px;\n"
" border-bottom-right-radius: 7px;\n"
" subcontrol-position: bottom;\n"
" subcontrol-origin: margin;\n"
"}\n"
"QScrollBar::add-line:vertical:hover { \n"
" background-color: rgb(255, 0, 127);\n"
"}\n"
"QScrollBar::add-line:vertical:pressed { \n"
" background-color: rgb(185, 0, 92);\n"
"}\n"
"\n"
"/* RESET ARROW */\n"
"QScrollBar::up-arrow:vertical, QScrollBar::down-arrow:vertical {\n"
" background: none;\n"
"}\n"
"QScrollBar::add-page:vertical, QScrollBar::sub-page:vertical {\n"
" background: none;\n"
"}\n"
"")
self.admin_table.setFrameShape(QtWidgets.QFrame.Box)
self.admin_table.setFrameShadow(QtWidgets.QFrame.Raised)
self.admin_table.setLineWidth(10)
self.admin_table.setSizeAdjustPolicy(
QtWidgets.QAbstractScrollArea.AdjustToContents)
self.admin_table.setAlternatingRowColors(True)
self.admin_table.setSelectionMode(
QtWidgets.QAbstractItemView.SingleSelection)
self.admin_table.setSelectionBehavior(
QtWidgets.QAbstractItemView.SelectRows)
self.admin_table.setIconSize(QtCore.QSize(0, 0))
self.admin_table.setTextElideMode(QtCore.Qt.ElideLeft)
self.admin_table.setRowCount(7)
self.admin_table.setColumnCount(3)
self.admin_table.setObjectName("admin_table")
item = QtWidgets.QTableWidgetItem()
self.admin_table.setHorizontalHeaderItem(0, item)
item = QtWidgets.QTableWidgetItem()
self.admin_table.setHorizontalHeaderItem(1, item)
item = QtWidgets.QTableWidgetItem()
self.admin_table.setHorizontalHeaderItem(2, item)
self.admin_table.horizontalHeader().setCascadingSectionResizes(False)
self.admin_table.horizontalHeader().setDefaultSectionSize(550)
self.admin_table.horizontalHeader().setMinimumSectionSize(26)
self.admin_table.horizontalHeader().setStretchLastSection(True)
self.admin_table.verticalHeader().setDefaultSectionSize(87)
self.admin_table.verticalHeader().setSortIndicatorShown(True)
self.admin_table.verticalHeader().setStretchLastSection(False)
self.refresh_button_admin = QtWidgets.QPushButton(self.page_1)
self.refresh_button_admin.setGeometry(QtCore.QRect(1390, 250, 391, 51))
font = QtGui.QFont()
font.setPointSize(1)
font.setBold(False)
font.setItalic(False)
font.setWeight(50)
self.refresh_button_admin.setFont(font)
self.refresh_button_admin.setToolTipDuration(0)
self.refresh_button_admin.setStyleSheet("QPushButton {\n"
" border-top-right-radius: 10px;\n"
" border-top-left-radius: 10px;\n"
" border-bottom-right-radius: 10px;\n"
" border-bottom-left-radius: 10px;\n"
" background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 rgba(45, 212, 191, 1), stop:1 rgba(6, 182, 212, 1));\n"
" font: 22px;\n"
" color: rgb(255, 255, 255);\n"
"}\n"
"\n"
"QPushButton:hover {\n"
" background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 #0F766E\n"
", stop:1 #0E7490);\n"
"}\n"
"\n"
"QPushButton:pressed {\n"
" background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 #0F766E\n"
", stop:1 #0E7490);\n"
" padding-left: 5px;\n"
" padding-top: 5px;\n"
"}")
self.refresh_button_admin.setObjectName("refresh_button_admin")
self.view_customers_button = QtWidgets.QPushButton(self.page_1)
self.view_customers_button.setGeometry(QtCore.QRect(20, 250, 481, 51))
font = QtGui.QFont()
font.setPointSize(1)
font.setBold(False)
font.setItalic(False)
font.setWeight(50)
self.view_customers_button.setFont(font)
self.view_customers_button.setToolTipDuration(0)
self.view_customers_button.setStyleSheet("QPushButton {\n"
" border-radius: 10px;\n"
" font: 22px;\n"
" color: rgb(255, 255, 255);\n"
" border: 5px solid;\n"
" border-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 #6366F1, stop:1#7C3AED);\n"
"}\n"
"\n"
"QPushButton:hover {\n"
" border: 5px solid;\n"
" border-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 #3730A3, stop:1 #5B21B6);\n"
"}\n"
"\n"
"QPushButton:pressed {\n"
" border: 5px solid;\n"
" border-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 #3730A3\n"
", stop:1 #5B21B6);\n"
" padding-left: 5px;\n"
" padding-top: 5px;\n"
"}")
self.view_customers_button.setObjectName("view_customers_button")
self.view_items_category_model_button = QtWidgets.QPushButton(
self.page_1)
self.view_items_category_model_button.setGeometry(
QtCore.QRect(20, 170, 481, 51))
font = QtGui.QFont()
font.setPointSize(1)
font.setBold(False)
font.setItalic(False)
font.setWeight(50)
self.view_items_category_model_button.setFont(font)
self.view_items_category_model_button.setToolTipDuration(0)
self.view_items_category_model_button.setStyleSheet("QPushButton {\n"
" border-radius: 10px;\n"
" font: 22px;\n"
" color: rgb(255, 255, 255);\n"
" border: 5px solid;\n"
" border-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 #6366F1, stop:1#7C3AED);\n"
"}\n"
"\n"
"QPushButton:hover {\n"
" border: 5px solid;\n"
" border-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 #3730A3, stop:1 #5B21B6);\n"
"}\n"
"\n"
"QPushButton:pressed {\n"
" border: 5px solid;\n"
" border-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 #3730A3\n"
", stop:1 #5B21B6);\n"
" padding-left: 5px;\n"
" padding-top: 5px;\n"
"}")
self.view_items_category_model_button.setObjectName(
"view_items_category_model_button")
self.initialise_database_button = QtWidgets.QPushButton(self.page_1)
self.initialise_database_button.setGeometry(
QtCore.QRect(1390, 180, 391, 51))
font = QtGui.QFont()
font.setPointSize(1)
font.setBold(False)
font.setItalic(False)
font.setWeight(50)
self.initialise_database_button.setFont(font)
self.initialise_database_button.setToolTipDuration(0)
self.initialise_database_button.setStyleSheet("QPushButton {\n"
" border-top-right-radius: 10px;\n"
" border-top-left-radius: 10px;\n"
" border-bottom-right-radius: 10px;\n"
" border-bottom-left-radius: 10px;\n"
" background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 #6366F1, stop:1#7C3AED);\n"
" font: 22px;\n"
" color: rgb(255, 255, 255);\n"
"}\n"
"\n"
"QPushButton:hover {\n"
" background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 #3730A3\n"
", stop:1 #5B21B6);\n"
"}\n"
"\n"
"QPushButton:pressed {\n"
" background-color:qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 #3730A3\n"
", stop:1 #5B21B6);\n"
" padding-left: 5px;\n"
" padding-top: 5px;\n"
"}")
self.initialise_database_button.setObjectName(
"initialise_database_button")
self.stackedWidget.addWidget(self.page_1)
self.page_2 = QtWidgets.QWidget()
self.page_2.setObjectName("page_2")
self.submit_query = QtWidgets.QPushButton(self.page_2)
self.submit_query.setGeometry(QtCore.QRect(1470, 250, 301, 51))
font = QtGui.QFont()
font.setPointSize(1)
font.setBold(False)
font.setItalic(False)
font.setWeight(50)
self.submit_query.setFont(font)
self.submit_query.setToolTipDuration(0)
self.submit_query.setStyleSheet("QPushButton {\n"
" border-top-right-radius: 10px;\n"
" border-top-left-radius: 10px;\n"
" border-bottom-right-radius: 10px;\n"
" border-bottom-left-radius: 10px;\n"
" background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 #F59E0B, stop:1#E11D48);\n"
" font: 22px;\n"
" color: rgb(255, 255, 255);\n"
"}\n"
"\n"
"QPushButton:hover {\n"
" background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 #B45309\n"
", stop:1 #9F1239);\n"
"}\n"
"\n"
"QPushButton:pressed {\n"
" background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 #B45309\n"
", stop:1 #9F1239);\n"
" padding-left: 5px;\n"
" padding-top: 5px;\n"
"}")
self.submit_query.setObjectName("submit_query")
self.Categories_label = QtWidgets.QLineEdit(self.page_2)
self.Categories_label.setGeometry(QtCore.QRect(20, 10, 131, 22))
font = QtGui.QFont()
font.setFamily("8514oem")
font.setPointSize(16)
self.Categories_label.setFont(font)
self.Categories_label.setStyleSheet("color: rgb(255, 255, 255);\n"
"background-color: rgba(255, 255, 255, 0);")
self.Categories_label.setFrame(False)
self.Categories_label.setObjectName("Categories_label")
self.category_comboBox = QtWidgets.QComboBox(self.page_2)
self.category_comboBox.setGeometry(QtCore.QRect(20, 37, 519, 51))
sizePolicy = QtWidgets.QSizePolicy(
QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Minimum)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.category_comboBox.sizePolicy().hasHeightForWidth())
self.category_comboBox.setSizePolicy(sizePolicy)
self.category_comboBox.setMinimumSize(QtCore.QSize(143, 2))
self.category_comboBox.setMaximumSize(QtCore.QSize(16777214, 16777215))
palette = QtGui.QPalette()
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active,
QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Button, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active,
QtGui.QPalette.ButtonText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Base, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Window, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive,
QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Button, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive,
QtGui.QPalette.ButtonText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Base, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Window, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled,
QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Button, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled,
QtGui.QPalette.ButtonText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Base, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Window, brush)
self.category_comboBox.setPalette(palette)
font = QtGui.QFont()
font.setFamily("8514oem")
font.setPointSize(16)
font.setBold(False)
font.setItalic(False)
font.setWeight(50)
self.category_comboBox.setFont(font)
self.category_comboBox.setCursor(
QtGui.QCursor(QtCore.Qt.PointingHandCursor))
self.category_comboBox.setStyleSheet("QComboBox {\n"
" border: 1px solid gray;\n"
" border-radius: 10px;\n"
" padding: 1px 18px 1px 3px;\n"
" min-width: 6em;\n"
" font: 16pt \"8514oem\";\n"
" background-color: rgb(255, 255, 255);\n"
" \n"
" color: rgb(0, 0, 0);\n"
"}\n"
"\n"
"QComboBox:on { /* shift the text when the popup opens */\n"
" padding-top: 3px;\n"
" padding-left: 4px;\n"
" background: white;\n"
" border-radius: 10px;\n"
"}\n"
"\n"
"QComboBox::drop-down {\n"
" subcontrol-origin: padding;\n"
" subcontrol-position: top right;\n"
" width: 15px;\n"
" background-color:white;\n"
" border-left-width: 1px;\n"
" border-left-color: darkgray;\n"
" border-left-style: solid; /* just a single line */\n"
" border-top-right-radius: 3px; /* same radius as the QComboBox */\n"
" border-bottom-right-radius: 3px;\n"
" border-radius: 10px;\n"
"}\n"
"\n"
"QComboBox::down-arrow:on { /* shift the arrow when popup is open */\n"
" top: 1px;\n"
" left: 1px;\n"
"}\n"
"QListView\n"
"{\n"
"background-color : #334155;\n"
"color: rgb(255, 255, 255);\n"
"}")
self.category_comboBox.setEditable(False)
self.category_comboBox.setFrame(True)
self.category_comboBox.setObjectName("category_comboBox")
self.category_comboBox.addItem("")
self.category_comboBox.addItem("")
self.category_comboBox.addItem("")
self.gradient_backdrop = QtWidgets.QLabel(self.page_2)
self.gradient_backdrop.setGeometry(QtCore.QRect(10, 0, 1781, 311))
self.gradient_backdrop.setStyleSheet("background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 #0D9488, stop:1 #0E7490);\n"
"border-radius: 20px;")
self.gradient_backdrop.setText("")
self.gradient_backdrop.setObjectName("gradient_backdrop")
self.Model_label = QtWidgets.QLineEdit(self.page_2)
self.Model_label.setGeometry(QtCore.QRect(20, 110, 131, 22))
font = QtGui.QFont()
font.setFamily("8514oem")
font.setPointSize(16)
self.Model_label.setFont(font)
self.Model_label.setStyleSheet("color: rgb(255, 255, 255);\n"
"background-color: rgba(255, 255, 255, 0);")
self.Model_label.setFrame(False)
self.Model_label.setObjectName("Model_label")
self.Price_label = QtWidgets.QLineEdit(self.page_2)
self.Price_label.setGeometry(QtCore.QRect(20, 210, 131, 22))
font = QtGui.QFont()
font.setFamily("8514oem")
font.setPointSize(16)
self.Price_label.setFont(font)
self.Price_label.setStyleSheet("color: rgb(255, 255, 255);\n"
"background-color: rgba(255, 255, 255, 0);")
self.Price_label.setFrame(False)
self.Price_label.setObjectName("Price_label")
self.model_comboBox = QtWidgets.QComboBox(self.page_2)
self.model_comboBox.setGeometry(QtCore.QRect(20, 140, 519, 51))
sizePolicy = QtWidgets.QSizePolicy(
QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Minimum)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.model_comboBox.sizePolicy().hasHeightForWidth())
self.model_comboBox.setSizePolicy(sizePolicy)
self.model_comboBox.setMinimumSize(QtCore.QSize(143, 2))
self.model_comboBox.setMaximumSize(QtCore.QSize(16777214, 16777215))
palette = QtGui.QPalette()
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active,
QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Button, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active,
QtGui.QPalette.ButtonText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Base, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Window, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive,
QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Button, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive,
QtGui.QPalette.ButtonText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Base, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Window, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled,
QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Button, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled,
QtGui.QPalette.ButtonText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Base, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Window, brush)
self.model_comboBox.setPalette(palette)
font = QtGui.QFont()
font.setFamily("8514oem")
font.setPointSize(16)
font.setBold(False)
font.setItalic(False)
font.setWeight(50)
self.model_comboBox.setFont(font)
self.model_comboBox.setCursor(
QtGui.QCursor(QtCore.Qt.PointingHandCursor))
self.model_comboBox.setStyleSheet("QComboBox {\n"
" border: 1px solid gray;\n"
" border-radius: 10px;\n"
" padding: 1px 18px 1px 3px;\n"
" min-width: 6em;\n"
" font: 16pt \"8514oem\";\n"
" background-color: rgb(255, 255, 255);\n"
" \n"
" color: rgb(0, 0, 0);\n"
"}\n"
"\n"
"QComboBox:on { /* shift the text when the popup opens */\n"
" padding-top: 3px;\n"
" padding-left: 4px;\n"
" background: white;\n"
" border-radius: 10px;\n"
"}\n"
"\n"
"QComboBox::drop-down {\n"
" subcontrol-origin: padding;\n"
" subcontrol-position: top right;\n"
" width: 15px;\n"
" background-color:white;\n"
" border-left-width: 1px;\n"
" border-left-color: darkgray;\n"
" border-left-style: solid; /* just a single line */\n"
" border-top-right-radius: 3px; /* same radius as the QComboBox */\n"
" border-bottom-right-radius: 3px;\n"
" border-radius: 10px;\n"
"}\n"
"\n"
"QComboBox::down-arrow:on { /* shift the arrow when popup is open */\n"
" top: 1px;\n"
" left: 1px;\n"
"}\n"
"QListView\n"
"{\n"
"background-color : #334155;\n"
"color: rgb(255, 255, 255);\n"
"}")
self.model_comboBox.setEditable(False)
self.model_comboBox.setFrame(True)
self.model_comboBox.setObjectName("model_comboBox")
self.model_comboBox.addItem("")
self.model_comboBox.addItem("")
self.model_comboBox.addItem("")
self.model_comboBox.addItem("")
self.model_comboBox.addItem("")
self.model_comboBox.addItem("")
self.price_comboBox = QtWidgets.QComboBox(self.page_2)
self.price_comboBox.setGeometry(QtCore.QRect(20, 240, 519, 51))
sizePolicy = QtWidgets.QSizePolicy(
QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Minimum)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.price_comboBox.sizePolicy().hasHeightForWidth())
self.price_comboBox.setSizePolicy(sizePolicy)
self.price_comboBox.setMinimumSize(QtCore.QSize(143, 2))
self.price_comboBox.setMaximumSize(QtCore.QSize(16777214, 16777215))
palette = QtGui.QPalette()
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active,
QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Button, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active,
QtGui.QPalette.ButtonText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Base, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Window, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive,
QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Button, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive,
QtGui.QPalette.ButtonText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Base, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Window, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled,
QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Button, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled,
QtGui.QPalette.ButtonText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Base, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Window, brush)
self.price_comboBox.setPalette(palette)
font = QtGui.QFont()
font.setFamily("8514oem")
font.setPointSize(16)
font.setBold(False)
font.setItalic(False)
font.setWeight(50)
self.price_comboBox.setFont(font)
self.price_comboBox.setCursor(
QtGui.QCursor(QtCore.Qt.PointingHandCursor))
self.price_comboBox.setStyleSheet("QComboBox {\n"
" border: 1px solid gray;\n"
" border-radius: 10px;\n"
" padding: 1px 18px 1px 3px;\n"
" min-width: 6em;\n"
" font: 16pt \"8514oem\";\n"
" background-color: rgb(255, 255, 255);\n"
" \n"
" color: rgb(0, 0, 0);\n"
"}\n"
"\n"
"QComboBox:on { /* shift the text when the popup opens */\n"
" padding-top: 3px;\n"
" padding-left: 4px;\n"
" background: white;\n"
" border-radius: 10px;\n"
"}\n"
"\n"
"QComboBox::drop-down {\n"
" subcontrol-origin: padding;\n"
" subcontrol-position: top right;\n"
" width: 15px;\n"
" background-color:white;\n"
" border-left-width: 1px;\n"
" border-left-color: darkgray;\n"
" border-left-style: solid; /* just a single line */\n"
" border-top-right-radius: 3px; /* same radius as the QComboBox */\n"
" border-bottom-right-radius: 3px;\n"
" border-radius: 10px;\n"
"}\n"
"\n"
"QComboBox::down-arrow:on { /* shift the arrow when popup is open */\n"
" top: 1px;\n"
" left: 1px;\n"
"}\n"
"QListView\n"
"{\n"
"background-color : #334155;\n"
"color: rgb(255, 255, 255);\n"
"}")
self.price_comboBox.setEditable(False)
self.price_comboBox.setFrame(True)
self.price_comboBox.setObjectName("price_comboBox")
self.price_comboBox.addItem("")
self.price_comboBox.addItem("")
self.price_comboBox.addItem("")
self.price_comboBox.addItem("")
self.price_comboBox.addItem("")
self.price_comboBox.addItem("")
self.price_comboBox.addItem("")
self.factory_comboBox = QtWidgets.QComboBox(self.page_2)
self.factory_comboBox.setGeometry(QtCore.QRect(630, 140, 519, 51))
sizePolicy = QtWidgets.QSizePolicy(
QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Minimum)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.factory_comboBox.sizePolicy().hasHeightForWidth())
self.factory_comboBox.setSizePolicy(sizePolicy)
self.factory_comboBox.setMinimumSize(QtCore.QSize(143, 2))
self.factory_comboBox.setMaximumSize(QtCore.QSize(16777214, 16777215))
palette = QtGui.QPalette()
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active,
QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Button, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active,
QtGui.QPalette.ButtonText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Base, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Window, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive,
QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Button, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive,
QtGui.QPalette.ButtonText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Base, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Window, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled,
QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Button, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled,
QtGui.QPalette.ButtonText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Base, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Window, brush)
self.factory_comboBox.setPalette(palette)
font = QtGui.QFont()
font.setFamily("8514oem")
font.setPointSize(16)
font.setBold(False)
font.setItalic(False)
font.setWeight(50)
self.factory_comboBox.setFont(font)
self.factory_comboBox.setCursor(
QtGui.QCursor(QtCore.Qt.PointingHandCursor))
self.factory_comboBox.setStyleSheet("QComboBox {\n"
" border: 1px solid gray;\n"
" border-radius: 10px;\n"
" padding: 1px 18px 1px 3px;\n"
" min-width: 6em;\n"
" font: 16pt \"8514oem\";\n"
" background-color: rgb(255, 255, 255);\n"
" \n"
" color: rgb(0, 0, 0);\n"
"}\n"
"\n"
"QComboBox:on { /* shift the text when the popup opens */\n"
" padding-top: 3px;\n"
" padding-left: 4px;\n"
" background: white;\n"
" border-radius: 10px;\n"
"}\n"
"\n"
"QComboBox::drop-down {\n"
" subcontrol-origin: padding;\n"
" subcontrol-position: top right;\n"
" width: 15px;\n"
" background-color:white;\n"
" border-left-width: 1px;\n"
" border-left-color: darkgray;\n"
" border-left-style: solid; /* just a single line */\n"
" border-top-right-radius: 3px; /* same radius as the QComboBox */\n"
" border-bottom-right-radius: 3px;\n"
" border-radius: 10px;\n"
"}\n"
"\n"
"QComboBox::down-arrow:on { /* shift the arrow when popup is open */\n"
" top: 1px;\n"
" left: 1px;\n"
"}\n"
"QListView\n"
"{\n"
"background-color : #334155;\n"
"color: rgb(255, 255, 255);\n"
"}")
self.factory_comboBox.setEditable(False)
self.factory_comboBox.setFrame(True)
self.factory_comboBox.setObjectName("factory_comboBox")
self.factory_comboBox.addItem("")
self.factory_comboBox.addItem("")
self.factory_comboBox.addItem("")
self.factory_comboBox.addItem("")
self.Factory_label = QtWidgets.QLineEdit(self.page_2)
self.Factory_label.setGeometry(QtCore.QRect(630, 110, 131, 22))
font = QtGui.QFont()
font.setFamily("8514oem")
font.setPointSize(16)
self.Factory_label.setFont(font)
self.Factory_label.setStyleSheet("color: rgb(255, 255, 255);\n"
"background-color: rgba(255, 255, 255, 0);")
self.Factory_label.setFrame(False)
self.Factory_label.setObjectName("Factory_label")
self.production_year_label = QtWidgets.QLineEdit(self.page_2)
self.production_year_label.setGeometry(QtCore.QRect(630, 210, 191, 22))
font = QtGui.QFont()
font.setFamily("8514oem")
font.setPointSize(16)
self.production_year_label.setFont(font)
self.production_year_label.setStyleSheet("color: rgb(255, 255, 255);\n"
"background-color: rgba(255, 255, 255, 0);")
self.production_year_label.setFrame(False)
self.production_year_label.setObjectName("production_year_label")
self.colour_comboBox = QtWidgets.QComboBox(self.page_2)
self.colour_comboBox.setGeometry(QtCore.QRect(630, 37, 519, 51))
sizePolicy = QtWidgets.QSizePolicy(
QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Minimum)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.colour_comboBox.sizePolicy().hasHeightForWidth())
self.colour_comboBox.setSizePolicy(sizePolicy)
self.colour_comboBox.setMinimumSize(QtCore.QSize(143, 2))
self.colour_comboBox.setMaximumSize(QtCore.QSize(16777214, 16777215))
palette = QtGui.QPalette()
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active,
QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Button, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active,
QtGui.QPalette.ButtonText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Base, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Window, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive,
QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Button, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive,
QtGui.QPalette.ButtonText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Base, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Window, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled,
QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Button, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled,
QtGui.QPalette.ButtonText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Base, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Window, brush)
self.colour_comboBox.setPalette(palette)
font = QtGui.QFont()
font.setFamily("8514oem")
font.setPointSize(16)
font.setBold(False)
font.setItalic(False)
font.setWeight(50)
self.colour_comboBox.setFont(font)
self.colour_comboBox.setCursor(
QtGui.QCursor(QtCore.Qt.PointingHandCursor))
self.colour_comboBox.setStyleSheet("QComboBox {\n"
" border: 1px solid gray;\n"
" border-radius: 10px;\n"
" padding: 1px 18px 1px 3px;\n"
" min-width: 6em;\n"
" font: 16pt \"8514oem\";\n"
" background-color: rgb(255, 255, 255);\n"
" \n"
" color: rgb(0, 0, 0);\n"
"}\n"
"\n"
"QComboBox:on { /* shift the text when the popup opens */\n"
" padding-top: 3px;\n"
" padding-left: 4px;\n"
" background: white;\n"
" border-radius: 10px;\n"
"}\n"
"\n"
"QComboBox::drop-down {\n"
" subcontrol-origin: padding;\n"
" subcontrol-position: top right;\n"
" width: 15px;\n"
" background-color:white;\n"
" border-left-width: 1px;\n"
" border-left-color: darkgray;\n"
" border-left-style: solid; /* just a single line */\n"
" border-top-right-radius: 3px; /* same radius as the QComboBox */\n"
" border-bottom-right-radius: 3px;\n"
" border-radius: 10px;\n"
"}\n"
"\n"
"QComboBox::down-arrow:on { /* shift the arrow when popup is open */\n"
" top: 1px;\n"
" left: 1px;\n"
"}\n"
"QListView\n"
"{\n"
"background-color : #334155;\n"
"color: rgb(255, 255, 255);\n"
"}")
self.colour_comboBox.setEditable(False)
self.colour_comboBox.setFrame(True)
self.colour_comboBox.setObjectName("colour_comboBox")
self.colour_comboBox.addItem("")
self.colour_comboBox.addItem("")
self.colour_comboBox.addItem("")
self.colour_comboBox.addItem("")
self.colour_comboBox.addItem("")
self.colour_comboBox.addItem("")
self.Colour_label = QtWidgets.QLineEdit(self.page_2)
self.Colour_label.setGeometry(QtCore.QRect(630, 10, 131, 22))
font = QtGui.QFont()
font.setFamily("8514oem")
font.setPointSize(16)
self.Colour_label.setFont(font)
self.Colour_label.setStyleSheet("color: rgb(255, 255, 255);\n"
"background-color: rgba(255, 255, 255, 0);")
self.Colour_label.setFrame(False)
self.Colour_label.setObjectName("Colour_label")
self.production_year_comboBox = QtWidgets.QComboBox(self.page_2)
self.production_year_comboBox.setGeometry(
QtCore.QRect(630, 240, 519, 51))
sizePolicy = QtWidgets.QSizePolicy(
QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Minimum)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.production_year_comboBox.sizePolicy().hasHeightForWidth())
self.production_year_comboBox.setSizePolicy(sizePolicy)
self.production_year_comboBox.setMinimumSize(QtCore.QSize(143, 2))
self.production_year_comboBox.setMaximumSize(
QtCore.QSize(16777214, 16777215))
palette = QtGui.QPalette()
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active,
QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Button, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active,
QtGui.QPalette.ButtonText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Base, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Window, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive,
QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Button, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive,
QtGui.QPalette.ButtonText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Base, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Window, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled,
QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Button, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled,
QtGui.QPalette.ButtonText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Base, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Window, brush)
self.production_year_comboBox.setPalette(palette)
font = QtGui.QFont()
font.setFamily("8514oem")
font.setPointSize(16)
font.setBold(False)
font.setItalic(False)
font.setWeight(50)
self.production_year_comboBox.setFont(font)
self.production_year_comboBox.setCursor(
QtGui.QCursor(QtCore.Qt.PointingHandCursor))
self.production_year_comboBox.setStyleSheet("QComboBox {\n"
" border: 1px solid gray;\n"
" border-radius: 10px;\n"
" padding: 1px 18px 1px 3px;\n"
" min-width: 6em;\n"
" font: 16pt \"8514oem\";\n"
" background-color: rgb(255, 255, 255);\n"
" \n"
" color: rgb(0, 0, 0);\n"
"}\n"
"\n"
"QComboBox:on { /* shift the text when the popup opens */\n"
" padding-top: 3px;\n"
" padding-left: 4px;\n"
" background: white;\n"
" border-radius: 10px;\n"
"}\n"
"\n"
"QComboBox::drop-down {\n"
" subcontrol-origin: padding;\n"
" subcontrol-position: top right;\n"
" width: 15px;\n"
" background-color:white;\n"
" border-left-width: 1px;\n"
" border-left-color: darkgray;\n"
" border-left-style: solid; /* just a single line */\n"
" border-top-right-radius: 3px; /* same radius as the QComboBox */\n"
" border-bottom-right-radius: 3px;\n"
" border-radius: 10px;\n"
"}\n"
"\n"
"QComboBox::down-arrow:on { /* shift the arrow when popup is open */\n"
" top: 1px;\n"
" left: 1px;\n"
"}\n"
"QListView\n"
"{\n"
"background-color : #334155;\n"
"color: rgb(255, 255, 255);\n"
"}")
self.production_year_comboBox.setEditable(False)
self.production_year_comboBox.setFrame(True)
self.production_year_comboBox.setObjectName("production_year_comboBox")
self.production_year_comboBox.addItem("")
self.production_year_comboBox.addItem("")
self.production_year_comboBox.addItem("")
self.production_year_comboBox.addItem("")
self.production_year_comboBox.addItem("")
self.production_year_comboBox.addItem("")
self.production_year_comboBox.addItem("")
self.Power_supply_label = QtWidgets.QLineEdit(self.page_2)
self.Power_supply_label.setGeometry(QtCore.QRect(1250, 10, 151, 22))
font = QtGui.QFont()
font.setFamily("8514oem")
font.setPointSize(16)
self.Power_supply_label.setFont(font)
self.Power_supply_label.setStyleSheet("color: rgb(255, 255, 255);\n"
"background-color: rgba(255, 255, 255, 0);")
self.Power_supply_label.setFrame(False)
self.Power_supply_label.setObjectName("Power_supply_label")
self.power_supply_comboBox = QtWidgets.QComboBox(self.page_2)
self.power_supply_comboBox.setGeometry(QtCore.QRect(1250, 37, 519, 51))
sizePolicy = QtWidgets.QSizePolicy(
QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Minimum)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.power_supply_comboBox.sizePolicy().hasHeightForWidth())
self.power_supply_comboBox.setSizePolicy(sizePolicy)
self.power_supply_comboBox.setMinimumSize(QtCore.QSize(143, 2))
self.power_supply_comboBox.setMaximumSize(
QtCore.QSize(16777214, 16777215))
palette = QtGui.QPalette()
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active,
QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Button, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active,
QtGui.QPalette.ButtonText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Base, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Window, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive,
QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Button, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive,
QtGui.QPalette.ButtonText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Base, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Window, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled,
QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Button, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled,
QtGui.QPalette.ButtonText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Base, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Window, brush)
self.power_supply_comboBox.setPalette(palette)
font = QtGui.QFont()
font.setFamily("8514oem")
font.setPointSize(16)
font.setBold(False)
font.setItalic(False)
font.setWeight(50)
self.power_supply_comboBox.setFont(font)
self.power_supply_comboBox.setCursor(
QtGui.QCursor(QtCore.Qt.PointingHandCursor))
self.power_supply_comboBox.setStyleSheet("QComboBox {\n"
" border: 1px solid gray;\n"
" border-radius: 10px;\n"
" padding: 1px 18px 1px 3px;\n"
" min-width: 6em;\n"
" font: 16pt \"8514oem\";\n"
" background-color: rgb(255, 255, 255);\n"
" \n"
" color: rgb(0, 0, 0);\n"
"}\n"
"\n"
"QComboBox:on { /* shift the text when the popup opens */\n"
" padding-top: 3px;\n"
" padding-left: 4px;\n"
" background: white;\n"
" border-radius: 10px;\n"
"}\n"
"\n"
"QComboBox::drop-down {\n"
" subcontrol-origin: padding;\n"
" subcontrol-position: top right;\n"
" width: 15px;\n"
" background-color:white;\n"
" border-left-width: 1px;\n"
" border-left-color: darkgray;\n"
" border-left-style: solid; /* just a single line */\n"
" border-top-right-radius: 3px; /* same radius as the QComboBox */\n"
" border-bottom-right-radius: 3px;\n"
" border-radius: 10px;\n"
"}\n"
"\n"
"QComboBox::down-arrow:on { /* shift the arrow when popup is open */\n"
" top: 1px;\n"
" left: 1px;\n"
"}\n"
"QListView\n"
"{\n"
"background-color : #334155;\n"
"color: rgb(255, 255, 255);\n"
"}")
self.power_supply_comboBox.setEditable(False)
self.power_supply_comboBox.setFrame(True)
self.power_supply_comboBox.setObjectName("power_supply_comboBox")
self.power_supply_comboBox.addItem("")
self.power_supply_comboBox.addItem("")
self.power_supply_comboBox.addItem("")
self.Warranty_label = QtWidgets.QLineEdit(self.page_2)
self.Warranty_label.setGeometry(QtCore.QRect(1250, 113, 131, 22))
font = QtGui.QFont()
font.setFamily("8514oem")
font.setPointSize(16)
self.Warranty_label.setFont(font)
self.Warranty_label.setStyleSheet("color: rgb(255, 255, 255);\n"
"background-color: rgba(255, 255, 255, 0);")
self.Warranty_label.setFrame(False)
self.Warranty_label.setObjectName("Warranty_label")
self.warranty_comboBox = QtWidgets.QComboBox(self.page_2)
self.warranty_comboBox.setGeometry(QtCore.QRect(1250, 140, 519, 51))
sizePolicy = QtWidgets.QSizePolicy(
QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Minimum)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.warranty_comboBox.sizePolicy().hasHeightForWidth())
self.warranty_comboBox.setSizePolicy(sizePolicy)
self.warranty_comboBox.setMinimumSize(QtCore.QSize(143, 2))
self.warranty_comboBox.setMaximumSize(QtCore.QSize(16777214, 16777215))
palette = QtGui.QPalette()
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active,
QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Button, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active,
QtGui.QPalette.ButtonText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Base, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Window, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive,
QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Button, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive,
QtGui.QPalette.ButtonText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Base, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Window, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled,
QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Button, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled,
QtGui.QPalette.ButtonText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Base, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Window, brush)
self.warranty_comboBox.setPalette(palette)
font = QtGui.QFont()
font.setFamily("8514oem")
font.setPointSize(16)
font.setBold(False)
font.setItalic(False)
font.setWeight(50)
self.warranty_comboBox.setFont(font)
self.warranty_comboBox.setCursor(
QtGui.QCursor(QtCore.Qt.PointingHandCursor))
self.warranty_comboBox.setStyleSheet("QComboBox {\n"
" border: 1px solid gray;\n"
" border-radius: 10px;\n"
" padding: 1px 18px 1px 3px;\n"
" min-width: 6em;\n"
" font: 16pt \"8514oem\";\n"
" background-color: rgb(255, 255, 255);\n"
" \n"
" color: rgb(0, 0, 0);\n"
"}\n"
"\n"
"QComboBox:on { /* shift the text when the popup opens */\n"
" padding-top: 3px;\n"
" padding-left: 4px;\n"
" background: white;\n"
" border-radius: 10px;\n"
"}\n"
"\n"
"QComboBox::drop-down {\n"
" subcontrol-origin: padding;\n"
" subcontrol-position: top right;\n"
" width: 15px;\n"
" background-color:white;\n"
" border-left-width: 1px;\n"
" border-left-color: darkgray;\n"
" border-left-style: solid; /* just a single line */\n"
" border-top-right-radius: 3px; /* same radius as the QComboBox */\n"
" border-bottom-right-radius: 3px;\n"
" border-radius: 10px;\n"
"}\n"
"\n"
"QComboBox::down-arrow:on { /* shift the arrow when popup is open */\n"
" top: 1px;\n"
" left: 1px;\n"
"}\n"
"QListView\n"
"{\n"
"background-color : #334155;\n"
"color: rgb(255, 255, 255);\n"
"}")
self.warranty_comboBox.setEditable(False)
self.warranty_comboBox.setFrame(True)
self.warranty_comboBox.setObjectName("warranty_comboBox")
self.warranty_comboBox.addItem("")
self.warranty_comboBox.addItem("")
self.warranty_comboBox.addItem("")
self.warranty_comboBox.addItem("")
self.warranty_comboBox.addItem("")
self.category_div = QtWidgets.QLabel(self.page_2)
self.category_div.setGeometry(QtCore.QRect(10, 340, 421, 541))
self.category_div.setStyleSheet("QWidget { \n"
"background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 #6D28D9 , stop:1 #4F46E5);\n"
"/**image: url(:/Choose_Item_div/light-bulb.png);*/\n"
"/**image: url(:/Choose_Item_div/padlock.png);*/\n"
"image: url(:/Choose_Item_div/box.png);\n"
"border-radius: 20px;\n"
"}")
self.category_div.setText("")
self.category_div.setObjectName("category_div")
self.price_div = QtWidgets.QLabel(self.page_2)
self.price_div.setGeometry(QtCore.QRect(460, 340, 971, 50))
self.price_div.setStyleSheet("background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 #6D28D9 , stop:1 #4F46E5);\n"
"border-radius: 20px;")
self.price_div.setText("")
self.price_div.setObjectName("price_div")
self.warranty_div = QtWidgets.QLabel(self.page_2)
self.warranty_div.setGeometry(QtCore.QRect(460, 420, 971, 50))
self.warranty_div.setStyleSheet("background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 #6D28D9 , stop:1 #4F46E5);\n"
"border-radius: 20px;")
self.warranty_div.setText("")
self.warranty_div.setObjectName("warranty_div")
self.model_div = QtWidgets.QLabel(self.page_2)
self.model_div.setGeometry(QtCore.QRect(460, 500, 971, 50))
self.model_div.setStyleSheet("background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 #6D28D9 , stop:1 #4F46E5);\n"
"border-radius: 20px;")
self.model_div.setText("")
self.model_div.setObjectName("model_div")
self.cost_div = QtWidgets.QLabel(self.page_2)
self.cost_div.setGeometry(QtCore.QRect(460, 580, 971, 50))
self.cost_div.setStyleSheet("background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 #6D28D9 , stop:1 #4F46E5);\n"
"border-radius: 20px;")
self.cost_div.setText("")
self.cost_div.setObjectName("cost_div")
self.inventory_div = QtWidgets.QLabel(self.page_2)
self.inventory_div.setGeometry(QtCore.QRect(1460, 340, 301, 241))
self.inventory_div.setStyleSheet("background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 #F59E0B, stop:1#E11D48);\n"
"border-radius: 20px;")
self.inventory_div.setText("")
self.inventory_div.setObjectName("inventory_div")
self.sold_items_div = QtWidgets.QLabel(self.page_2)
self.sold_items_div.setGeometry(QtCore.QRect(1460, 630, 301, 241))
self.sold_items_div.setStyleSheet("background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 #F59E0B, stop:1#E11D48);\n"
"border-radius: 20px;")
self.sold_items_div.setText("")
self.sold_items_div.setObjectName("sold_items_div")
self.category_amount_label = QtWidgets.QLabel(self.page_2)
self.category_amount_label.setGeometry(QtCore.QRect(20, 770, 401, 81))
font = QtGui.QFont()
font.setFamily("Segoe UI")
font.setPointSize(18)
font.setBold(False)
font.setItalic(True)
font.setWeight(9)
self.category_amount_label.setFont(font)
self.category_amount_label.setStyleSheet("background-color: transparent;\n"
"color: rgb(255, 255, 255);\n"
"font: 75 italic 18pt \"Segoe UI\";")
self.category_amount_label.setAlignment(QtCore.Qt.AlignCenter)
self.category_amount_label.setObjectName("category_amount_label")
self.choose_an_item_label = QtWidgets.QLabel(self.page_2)
self.choose_an_item_label.setGeometry(QtCore.QRect(20, 360, 411, 81))
font = QtGui.QFont()
font.setFamily("Yu Gothic UI")
font.setPointSize(20)
font.setBold(False)
font.setItalic(False)
font.setWeight(50)
self.choose_an_item_label.setFont(font)
self.choose_an_item_label.setStyleSheet("background-color: transparent;\n"
"color: rgb(255, 255, 255);\n"
"font: 20pt \"Yu Gothic UI\";")
self.choose_an_item_label.setAlignment(QtCore.Qt.AlignCenter)
self.choose_an_item_label.setObjectName("choose_an_item_label")
self.inventory_level_label = QtWidgets.QLabel(self.page_2)
self.inventory_level_label.setGeometry(
QtCore.QRect(1460, 350, 301, 81))
font = QtGui.QFont()
font.setFamily("Yu Gothic UI")
font.setPointSize(14)
font.setBold(False)
font.setItalic(False)
font.setWeight(50)
self.inventory_level_label.setFont(font)
self.inventory_level_label.setStyleSheet("background-color: transparent;\n"
"color: rgb(255, 255, 255);\n"
"font: 14pt \"Yu Gothic UI\";")
self.inventory_level_label.setAlignment(QtCore.Qt.AlignCenter)
self.inventory_level_label.setObjectName("inventory_level_label")
self.sold_items_label = QtWidgets.QLabel(self.page_2)
self.sold_items_label.setGeometry(QtCore.QRect(1460, 630, 301, 81))
font = QtGui.QFont()
font.setFamily("Yu Gothic UI")
font.setPointSize(14)
font.setBold(False)
font.setItalic(False)
font.setWeight(50)
self.sold_items_label.setFont(font)
self.sold_items_label.setStyleSheet("background-color: transparent;\n"
"color: rgb(255, 255, 255);\n"
"font: 14pt \"Yu Gothic UI\";")
self.sold_items_label.setAlignment(QtCore.Qt.AlignCenter)
self.sold_items_label.setObjectName("sold_items_label")
self.price_label = QtWidgets.QLabel(self.page_2)
self.price_label.setGeometry(QtCore.QRect(400, 350, 241, 31))
font = QtGui.QFont()
font.setFamily("Yu Gothic UI")
font.setPointSize(12)
font.setBold(False)
font.setItalic(False)
font.setWeight(50)
self.price_label.setFont(font)
self.price_label.setStyleSheet("background-color: transparent;\n"
"color: rgb(255, 255, 255);\n"
"font: 12pt \"Yu Gothic UI\";")
self.price_label.setAlignment(QtCore.Qt.AlignCenter)
self.price_label.setObjectName("price_label")
self.warranty_label = QtWidgets.QLabel(self.page_2)
self.warranty_label.setGeometry(QtCore.QRect(420, 420, 241, 51))
font = QtGui.QFont()
font.setFamily("Yu Gothic UI")
font.setPointSize(12)
font.setBold(False)
font.setItalic(False)
font.setWeight(50)
self.warranty_label.setFont(font)
self.warranty_label.setStyleSheet("background-color: transparent;\n"
"color: rgb(255, 255, 255);\n"
"font: 12pt \"Yu Gothic UI\";")
self.warranty_label.setAlignment(QtCore.Qt.AlignCenter)
self.warranty_label.setObjectName("warranty_label")
self.model_label = QtWidgets.QLabel(self.page_2)
self.model_label.setGeometry(QtCore.QRect(410, 500, 241, 51))
font = QtGui.QFont()
font.setFamily("Yu Gothic UI")
font.setPointSize(12)
font.setBold(False)
font.setItalic(False)
font.setWeight(50)
self.model_label.setFont(font)
self.model_label.setStyleSheet("background-color: transparent;\n"
"color: rgb(255, 255, 255);\n"
"font: 12pt \"Yu Gothic UI\";")
self.model_label.setAlignment(QtCore.Qt.AlignCenter)
self.model_label.setObjectName("model_label")
self.cost_label = QtWidgets.QLabel(self.page_2)
self.cost_label.setGeometry(QtCore.QRect(400, 580, 241, 51))
font = QtGui.QFont()
font.setFamily("Yu Gothic UI")
font.setPointSize(12)
font.setBold(False)
font.setItalic(False)
font.setWeight(50)
self.cost_label.setFont(font)
self.cost_label.setStyleSheet("background-color: transparent;\n"
"color: rgb(255, 255, 255);\n"
"font: 12pt \"Yu Gothic UI\";")
self.cost_label.setAlignment(QtCore.Qt.AlignCenter)
self.cost_label.setObjectName("cost_label")
self.price_amount_label = QtWidgets.QLabel(self.page_2)
self.price_amount_label.setGeometry(QtCore.QRect(1180, 340, 241, 51))
font = QtGui.QFont()
font.setFamily("Yu Gothic UI")
font.setPointSize(12)
font.setBold(False)
font.setItalic(True)
font.setWeight(50)
self.price_amount_label.setFont(font)
self.price_amount_label.setStyleSheet("background-color: transparent;\n"
"color: rgb(255, 255, 255);\n"
"font: italic 12pt \"Yu Gothic UI\";")
self.price_amount_label.setAlignment(QtCore.Qt.AlignCenter)
self.price_amount_label.setObjectName("price_amount_label")
self.warranty_amount_label = QtWidgets.QLabel(self.page_2)
self.warranty_amount_label.setGeometry(
QtCore.QRect(1180, 420, 241, 51))
font = QtGui.QFont()
font.setFamily("Yu Gothic UI")
font.setPointSize(12)
font.setBold(False)
font.setItalic(True)
font.setWeight(50)
self.warranty_amount_label.setFont(font)
self.warranty_amount_label.setStyleSheet("background-color: transparent;\n"
"color: rgb(255, 255, 255);\n"
"font: italic 12pt \"Yu Gothic UI\";")
self.warranty_amount_label.setAlignment(QtCore.Qt.AlignCenter)
self.warranty_amount_label.setObjectName("warranty_amount_label")
self.model_amount_label = QtWidgets.QLabel(self.page_2)
self.model_amount_label.setGeometry(QtCore.QRect(1180, 500, 241, 51))
font = QtGui.QFont()
font.setFamily("Yu Gothic UI")
font.setPointSize(12)
font.setBold(False)
font.setItalic(True)
font.setWeight(50)
self.model_amount_label.setFont(font)
self.model_amount_label.setStyleSheet("background-color: transparent;\n"
"color: rgb(255, 255, 255);\n"
"font: italic 12pt \"Yu Gothic UI\";")
self.model_amount_label.setAlignment(QtCore.Qt.AlignCenter)
self.model_amount_label.setObjectName("model_amount_label")
self.cost_amount_label = QtWidgets.QLabel(self.page_2)
self.cost_amount_label.setGeometry(QtCore.QRect(1180, 580, 241, 51))
font = QtGui.QFont()
font.setFamily("Yu Gothic UI")
font.setPointSize(12)
font.setBold(False)
font.setItalic(True)
font.setWeight(50)
self.cost_amount_label.setFont(font)
self.cost_amount_label.setStyleSheet("background-color: transparent;\n"
"color: rgb(255, 255, 255);\n"
"font: italic 12pt \"Yu Gothic UI\";")
self.cost_amount_label.setAlignment(QtCore.Qt.AlignCenter)
self.cost_amount_label.setObjectName("cost_amount_label")
self.inventory_amount_label = QtWidgets.QLabel(self.page_2)
self.inventory_amount_label.setGeometry(
QtCore.QRect(1460, 490, 301, 81))
font = QtGui.QFont()
font.setFamily("Yu Gothic UI")
font.setPointSize(16)
font.setBold(False)
font.setItalic(True)
font.setWeight(50)
self.inventory_amount_label.setFont(font)
self.inventory_amount_label.setStyleSheet("background-color: transparent;\n"
"color: rgb(255, 255, 255);\n"
"font: italic 16pt \"Yu Gothic UI\";")
self.inventory_amount_label.setAlignment(QtCore.Qt.AlignCenter)
self.inventory_amount_label.setObjectName("inventory_amount_label")
self.sold_items_amount_label = QtWidgets.QLabel(self.page_2)
self.sold_items_amount_label.setGeometry(
QtCore.QRect(1460, 780, 301, 91))
font = QtGui.QFont()
font.setFamily("Yu Gothic UI")
font.setPointSize(16)
font.setBold(False)
font.setItalic(True)
font.setWeight(50)
self.sold_items_amount_label.setFont(font)
self.sold_items_amount_label.setStyleSheet("background-color: transparent;\n"
"color: rgb(255, 255, 255);\n"
"font: italic 16pt \"Yu Gothic UI\";")
self.sold_items_amount_label.setAlignment(QtCore.Qt.AlignCenter)
self.sold_items_amount_label.setObjectName("sold_items_amount_label")
self.color_div = QtWidgets.QLabel(self.page_2)
self.color_div.setGeometry(QtCore.QRect(460, 660, 971, 50))
self.color_div.setStyleSheet("background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 #6D28D9 , stop:1 #4F46E5);\n"
"border-radius: 20px;")
self.color_div.setText("")
self.color_div.setObjectName("color_div")
self.production_year_div = QtWidgets.QLabel(self.page_2)
self.production_year_div.setGeometry(QtCore.QRect(460, 740, 971, 50))
self.production_year_div.setStyleSheet("background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 #6D28D9 , stop:1 #4F46E5);\n"
"border-radius: 20px;")
self.production_year_div.setText("")
self.production_year_div.setObjectName("production_year_div")
self.power_supply_div = QtWidgets.QLabel(self.page_2)
self.power_supply_div.setGeometry(QtCore.QRect(460, 820, 971, 50))
self.power_supply_div.setStyleSheet("background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 #6D28D9 , stop:1 #4F46E5);\n"
"border-radius: 20px;")
self.power_supply_div.setText("")
self.power_supply_div.setObjectName("power_supply_div")
self.color_label = QtWidgets.QLabel(self.page_2)
self.color_label.setGeometry(QtCore.QRect(400, 660, 241, 51))
font = QtGui.QFont()
font.setFamily("Yu Gothic UI")
font.setPointSize(12)
font.setBold(False)
font.setItalic(False)
font.setWeight(50)
self.color_label.setFont(font)
self.color_label.setStyleSheet("background-color: transparent;\n"
"color: rgb(255, 255, 255);\n"
"font: 12pt \"Yu Gothic UI\";")
self.color_label.setAlignment(QtCore.Qt.AlignCenter)
self.color_label.setObjectName("color_label")
self.product_year_label = QtWidgets.QLabel(self.page_2)
self.product_year_label.setGeometry(QtCore.QRect(460, 740, 241, 51))
font = QtGui.QFont()
font.setFamily("Yu Gothic UI")
font.setPointSize(12)
font.setBold(False)
font.setItalic(False)
font.setWeight(50)
self.product_year_label.setFont(font)
self.product_year_label.setStyleSheet("background-color: transparent;\n"
"color: rgb(255, 255, 255);\n"
"font: 12pt \"Yu Gothic UI\";")
self.product_year_label.setAlignment(QtCore.Qt.AlignCenter)
self.product_year_label.setObjectName("product_year_label")
self.power_supply_label = QtWidgets.QLabel(self.page_2)
self.power_supply_label.setGeometry(QtCore.QRect(450, 820, 241, 51))
font = QtGui.QFont()
font.setFamily("Yu Gothic UI")
font.setPointSize(12)
font.setBold(False)
font.setItalic(False)
font.setWeight(50)
self.power_supply_label.setFont(font)
self.power_supply_label.setStyleSheet("background-color: transparent;\n"
"color: rgb(255, 255, 255);\n"
"font: 12pt \"Yu Gothic UI\";")
self.power_supply_label.setAlignment(QtCore.Qt.AlignCenter)
self.power_supply_label.setObjectName("power_supply_label")
self.color_amount_label = QtWidgets.QLabel(self.page_2)
self.color_amount_label.setGeometry(QtCore.QRect(1180, 660, 241, 51))
font = QtGui.QFont()
font.setFamily("Yu Gothic UI")
font.setPointSize(12)
font.setBold(False)
font.setItalic(True)
font.setWeight(50)
self.color_amount_label.setFont(font)
self.color_amount_label.setStyleSheet("background-color: transparent;\n"
"color: rgb(255, 255, 255);\n"
"font: italic 12pt \"Yu Gothic UI\";")
self.color_amount_label.setAlignment(QtCore.Qt.AlignCenter)
self.color_amount_label.setObjectName("color_amount_label")
self.producti_year_amount_label = QtWidgets.QLabel(self.page_2)
self.producti_year_amount_label.setGeometry(
QtCore.QRect(1180, 740, 241, 51))
font = QtGui.QFont()
font.setFamily("Yu Gothic UI")
font.setPointSize(12)
font.setBold(False)
font.setItalic(True)
font.setWeight(50)
self.producti_year_amount_label.setFont(font)
self.producti_year_amount_label.setStyleSheet("background-color: transparent;\n"
"color: rgb(255, 255, 255);\n"
"font: italic 12pt \"Yu Gothic UI\";")
self.producti_year_amount_label.setAlignment(QtCore.Qt.AlignCenter)
self.producti_year_amount_label.setObjectName(
"producti_year_amount_label")
self.power_supply_amount_label = QtWidgets.QLabel(self.page_2)
self.power_supply_amount_label.setGeometry(
QtCore.QRect(1180, 820, 241, 51))
font = QtGui.QFont()
font.setFamily("Yu Gothic UI")
font.setPointSize(12)
font.setBold(False)
font.setItalic(True)
font.setWeight(50)
self.power_supply_amount_label.setFont(font)
self.power_supply_amount_label.setStyleSheet("background-color: transparent;\n"
"color: rgb(255, 255, 255);\n"
"font: italic 12pt \"Yu Gothic UI\";")
self.power_supply_amount_label.setAlignment(QtCore.Qt.AlignCenter)
self.power_supply_amount_label.setObjectName(
"power_supply_amount_label")
self.gradient_backdrop.raise_()
self.submit_query.raise_()
self.Categories_label.raise_()
self.category_comboBox.raise_()
self.Model_label.raise_()
self.Price_label.raise_()
self.model_comboBox.raise_()
self.price_comboBox.raise_()
self.factory_comboBox.raise_()
self.Factory_label.raise_()
self.production_year_label.raise_()
self.colour_comboBox.raise_()
self.Colour_label.raise_()
self.production_year_comboBox.raise_()
self.Power_supply_label.raise_()
self.power_supply_comboBox.raise_()
self.Warranty_label.raise_()
self.warranty_comboBox.raise_()
self.category_div.raise_()
self.price_div.raise_()
self.warranty_div.raise_()
self.model_div.raise_()
self.cost_div.raise_()
self.inventory_div.raise_()
self.sold_items_div.raise_()
self.category_amount_label.raise_()
self.choose_an_item_label.raise_()
self.inventory_level_label.raise_()
self.sold_items_label.raise_()
self.price_label.raise_()
self.warranty_label.raise_()
self.model_label.raise_()
self.cost_label.raise_()
self.price_amount_label.raise_()
self.warranty_amount_label.raise_()
self.model_amount_label.raise_()
self.cost_amount_label.raise_()
self.inventory_amount_label.raise_()
self.sold_items_amount_label.raise_()
self.color_div.raise_()
self.production_year_div.raise_()
self.power_supply_div.raise_()
self.color_label.raise_()
self.product_year_label.raise_()
self.power_supply_label.raise_()
self.color_amount_label.raise_()
self.producti_year_amount_label.raise_()
self.power_supply_amount_label.raise_()
self.stackedWidget.addWidget(self.page_2)
self.page_3 = QtWidgets.QWidget()
self.page_3.setObjectName("page_3")
self.item_search_label = QtWidgets.QLabel(self.page_3)
self.item_search_label.setGeometry(QtCore.QRect(690, 0, 401, 91))
font = QtGui.QFont()
font.setFamily("8514oem")
font.setPointSize(25)
self.item_search_label.setFont(font)
self.item_search_label.setStyleSheet("color: rgb(255, 255, 255);\n"
"image: url(:/adminSideBar/icons8-product-management-48.png);\n"
"padding-right:50px;")
self.item_search_label.setAlignment(
QtCore.Qt.AlignRight | QtCore.Qt.AlignTrailing | QtCore.Qt.AlignVCenter)
self.item_search_label.setObjectName("item_search_label")
self.item_table = QtWidgets.QTableWidget(self.page_3)
self.item_table.setGeometry(QtCore.QRect(20, 325, 1761, 561))
self.item_table.setSizeIncrement(QtCore.QSize(0, 0))
font = QtGui.QFont()
font.setFamily("8514oem")
font.setPointSize(10)
font.setBold(False)
font.setItalic(False)
font.setWeight(50)
self.item_table.setFont(font)
self.item_table.setLayoutDirection(QtCore.Qt.LeftToRight)
self.item_table.setAutoFillBackground(False)
self.item_table.setStyleSheet("QWidget {\n"
" background-color: rgb(255, 255, 255);\n"
" alternate-background-color: rgb(241, 245, 249);\n"
" font: 10pt \"8514oem\";\n"
"}\n"
"QScrollBar:vertical {\n"
" border: none;\n"
" background: #94A3B8;\n"
" width: 14px;\n"
" margin: 15px 0 15px 0;\n"
" border-radius: 0px;\n"
" }\n"
"\n"
"/* HANDLE BAR VERTICAL */\n"
"QScrollBar::handle:vertical { \n"
" background-color: #E5E7EB;\n"
" min-height: 30px;\n"
" border-radius: 7px;\n"
"}\n"
"QScrollBar::handle:vertical:hover{ \n"
" background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 #6366F1, stop:1 #7C3AED);\n"
"}\n"
"QScrollBar::handle:vertical:pressed { \n"
" background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 #4338CA, stop:1 #5B21B6);\n"
"}\n"
"\n"
"/* BTN TOP - SCROLLBAR */\n"
"QScrollBar::sub-line:vertical {\n"
" border: none;\n"
" background-color: #94A3B8;\n"
" height: 15px;\n"
" border-top-left-radius: 7px;\n"
" border-top-right-radius: 7px;\n"
" subcontrol-position: top;\n"
" subcontrol-origin: margin;\n"
"}\n"
"QScrollBar::sub-line:vertical:hover { \n"
" background-color: rgb(255, 0, 127);\n"
"}\n"
"QScrollBar::sub-line:vertical:pressed { \n"
" background-color: rgb(185, 0, 92);\n"
"}\n"
"\n"
"/* BTN BOTTOM - SCROLLBAR */\n"
"QScrollBar::add-line:vertical {\n"
" border: none;\n"
" background-color:#94A3B8;\n"
" height: 15px;\n"
" border-bottom-left-radius: 7px;\n"
" border-bottom-right-radius: 7px;\n"
" subcontrol-position: bottom;\n"
" subcontrol-origin: margin;\n"
"}\n"
"QScrollBar::add-line:vertical:hover { \n"
" background-color: rgb(255, 0, 127);\n"
"}\n"
"QScrollBar::add-line:vertical:pressed { \n"
" background-color: rgb(185, 0, 92);\n"
"}\n"
"\n"
"/* RESET ARROW */\n"
"QScrollBar::up-arrow:vertical, QScrollBar::down-arrow:vertical {\n"
" background: none;\n"
"}\n"
"QScrollBar::add-page:vertical, QScrollBar::sub-page:vertical {\n"
" background: none;\n"
"}\n"
"")
self.item_table.setFrameShape(QtWidgets.QFrame.Box)
self.item_table.setFrameShadow(QtWidgets.QFrame.Raised)
self.item_table.setLineWidth(10)
self.item_table.setSizeAdjustPolicy(
QtWidgets.QAbstractScrollArea.AdjustToContents)
self.item_table.setAlternatingRowColors(True)
self.item_table.setSelectionMode(
QtWidgets.QAbstractItemView.SingleSelection)
self.item_table.setSelectionBehavior(
QtWidgets.QAbstractItemView.SelectRows)
self.item_table.setIconSize(QtCore.QSize(0, 0))
self.item_table.setTextElideMode(QtCore.Qt.ElideLeft)
self.item_table.setRowCount(7)
self.item_table.setColumnCount(12)
self.item_table.setObjectName("item_table")
item = QtWidgets.QTableWidgetItem()
self.item_table.setHorizontalHeaderItem(0, item)
item = QtWidgets.QTableWidgetItem()
self.item_table.setHorizontalHeaderItem(1, item)
item = QtWidgets.QTableWidgetItem()
self.item_table.setHorizontalHeaderItem(2, item)
item = QtWidgets.QTableWidgetItem()
self.item_table.setHorizontalHeaderItem(3, item)
item = QtWidgets.QTableWidgetItem()
self.item_table.setHorizontalHeaderItem(4, item)
item = QtWidgets.QTableWidgetItem()
self.item_table.setHorizontalHeaderItem(5, item)
item = QtWidgets.QTableWidgetItem()
self.item_table.setHorizontalHeaderItem(6, item)
item = QtWidgets.QTableWidgetItem()
self.item_table.setHorizontalHeaderItem(7, item)
item = QtWidgets.QTableWidgetItem()
self.item_table.setHorizontalHeaderItem(8, item)
item = QtWidgets.QTableWidgetItem()
self.item_table.setHorizontalHeaderItem(9, item)
item = QtWidgets.QTableWidgetItem()
self.item_table.setHorizontalHeaderItem(10, item)
item = QtWidgets.QTableWidgetItem()
self.item_table.setHorizontalHeaderItem(11, item)
item = QtWidgets.QTableWidgetItem()
self.item_table.setItem(0, 1, item)
item = QtWidgets.QTableWidgetItem()
self.item_table.setItem(6, 6, item)
self.item_table.horizontalHeader().setCascadingSectionResizes(False)
self.item_table.horizontalHeader().setDefaultSectionSize(200)
self.item_table.horizontalHeader().setMinimumSectionSize(26)
self.item_table.horizontalHeader().setStretchLastSection(True)
self.item_table.verticalHeader().setDefaultSectionSize(87)
self.item_table.verticalHeader().setSortIndicatorShown(True)
self.item_table.verticalHeader().setStretchLastSection(False)
self.item_id_comboBox = QtWidgets.QComboBox(self.page_3)
self.item_id_comboBox.setGeometry(QtCore.QRect(20, 250, 519, 51))
sizePolicy = QtWidgets.QSizePolicy(
QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Minimum)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.item_id_comboBox.sizePolicy().hasHeightForWidth())
self.item_id_comboBox.setSizePolicy(sizePolicy)
self.item_id_comboBox.setMinimumSize(QtCore.QSize(143, 2))
self.item_id_comboBox.setMaximumSize(QtCore.QSize(16777214, 16777215))
palette = QtGui.QPalette()
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active,
QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Button, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active,
QtGui.QPalette.ButtonText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Base, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Window, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive,
QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Button, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive,
QtGui.QPalette.ButtonText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Base, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Window, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled,
QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Button, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled,
QtGui.QPalette.ButtonText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Base, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Window, brush)
self.item_id_comboBox.setPalette(palette)
font = QtGui.QFont()
font.setFamily("8514oem")
font.setPointSize(16)
font.setBold(False)
font.setItalic(False)
font.setWeight(50)
self.item_id_comboBox.setFont(font)
self.item_id_comboBox.setCursor(
QtGui.QCursor(QtCore.Qt.PointingHandCursor))
self.item_id_comboBox.setStyleSheet("QComboBox {\n"
" border: 1px solid gray;\n"
" border-radius: 10px;\n"
" padding: 1px 18px 1px 3px;\n"
" min-width: 6em;\n"
" font: 16pt \"8514oem\";\n"
" background-color: rgb(255, 255, 255);\n"
" \n"
" color: rgb(0, 0, 0);\n"
"}\n"
"\n"
"QComboBox:on { /* shift the text when the popup opens */\n"
" padding-top: 3px;\n"
" padding-left: 4px;\n"
" background: white;\n"
" border-radius: 10px;\n"
"}\n"
"\n"
"QComboBox::drop-down {\n"
" subcontrol-origin: padding;\n"
" subcontrol-position: top right;\n"
" width: 15px;\n"
" background-color:white;\n"
" border-left-width: 1px;\n"
" border-left-color: darkgray;\n"
" border-left-style: solid; /* just a single line */\n"
" border-top-right-radius: 3px; /* same radius as the QComboBox */\n"
" border-bottom-right-radius: 3px;\n"
" border-radius: 10px;\n"
"}\n"
"\n"
"QComboBox::down-arrow:on { /* shift the arrow when popup is open */\n"
" top: 1px;\n"
" left: 1px;\n"
"}\n"
"QListView\n"
"{\n"
"background-color : #334155;\n"
"color: rgb(255, 255, 255);\n"
"}")
self.item_id_comboBox.setEditable(True)
self.item_id_comboBox.setCurrentText("")
self.item_id_comboBox.setFrame(True)
self.item_id_comboBox.setObjectName("item_id_comboBox")
self.under_service_comboBox = QtWidgets.QComboBox(self.page_3)
self.under_service_comboBox.setGeometry(QtCore.QRect(20, 100, 519, 51))
sizePolicy = QtWidgets.QSizePolicy(
QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Minimum)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.under_service_comboBox.sizePolicy().hasHeightForWidth())
self.under_service_comboBox.setSizePolicy(sizePolicy)
self.under_service_comboBox.setMinimumSize(QtCore.QSize(143, 2))
self.under_service_comboBox.setMaximumSize(
QtCore.QSize(16777214, 16777215))
palette = QtGui.QPalette()
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active,
QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Button, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active,
QtGui.QPalette.ButtonText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Base, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Window, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive,
QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Button, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive,
QtGui.QPalette.ButtonText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Base, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Window, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled,
QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Button, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled,
QtGui.QPalette.ButtonText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Base, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Window, brush)
self.under_service_comboBox.setPalette(palette)
font = QtGui.QFont()
font.setFamily("8514oem")
font.setPointSize(16)
font.setBold(False)
font.setItalic(False)
font.setWeight(50)
self.under_service_comboBox.setFont(font)
self.under_service_comboBox.setCursor(
QtGui.QCursor(QtCore.Qt.PointingHandCursor))
self.under_service_comboBox.setStyleSheet("QComboBox {\n"
" border: 1px solid gray;\n"
" border-radius: 10px;\n"
" padding: 1px 18px 1px 3px;\n"
" min-width: 6em;\n"
" font: 16pt \"8514oem\";\n"
" background-color: rgb(255, 255, 255);\n"
" \n"
" color: rgb(0, 0, 0);\n"
"}\n"
"\n"
"QComboBox:on { /* shift the text when the popup opens */\n"
" padding-top: 3px;\n"
" padding-left: 4px;\n"
" background: white;\n"
" border-radius: 10px;\n"
"}\n"
"\n"
"QComboBox::drop-down {\n"
" subcontrol-origin: padding;\n"
" subcontrol-position: top right;\n"
" width: 15px;\n"
" background-color:white;\n"
" border-left-width: 1px;\n"
" border-left-color: darkgray;\n"
" border-left-style: solid; /* just a single line */\n"
" border-top-right-radius: 3px; /* same radius as the QComboBox */\n"
" border-bottom-right-radius: 3px;\n"
" border-radius: 10px;\n"
"}\n"
"\n"
"QComboBox::down-arrow:on { /* shift the arrow when popup is open */\n"
" top: 1px;\n"
" left: 1px;\n"
"}\n"
"QListView\n"
"{\n"
"background-color : #334155;\n"
"color: rgb(255, 255, 255);\n"
"}")
self.under_service_comboBox.setEditable(False)
self.under_service_comboBox.setFrame(True)
self.under_service_comboBox.setObjectName("under_service_comboBox")
self.under_service_comboBox.addItem("")
self.under_service_comboBox.addItem("")
self.under_service_label = QtWidgets.QLineEdit(self.page_3)
self.under_service_label.setGeometry(QtCore.QRect(20, 73, 241, 22))
font = QtGui.QFont()
font.setFamily("8514oem")
font.setPointSize(16)
self.under_service_label.setFont(font)
self.under_service_label.setStyleSheet("color: rgb(255, 255, 255);\n"
"background-color: rgba(255, 255, 255, 0);")
self.under_service_label.setFrame(False)
self.under_service_label.setObjectName("under_service_label")
self.item_id_label = QtWidgets.QLineEdit(self.page_3)
self.item_id_label.setGeometry(QtCore.QRect(20, 220, 131, 22))
font = QtGui.QFont()
font.setFamily("8514oem")
font.setPointSize(16)
self.item_id_label.setFont(font)
self.item_id_label.setStyleSheet("color: rgb(255, 255, 255);\n"
"background-color: rgba(255, 255, 255, 0);")
self.item_id_label.setFrame(False)
self.item_id_label.setObjectName("item_id_label")
self.item_search_button = QtWidgets.QPushButton(self.page_3)
self.item_search_button.setGeometry(QtCore.QRect(1470, 250, 301, 51))
font = QtGui.QFont()
font.setPointSize(1)
font.setBold(False)
font.setItalic(False)
font.setWeight(50)
self.item_search_button.setFont(font)
self.item_search_button.setToolTipDuration(0)
self.item_search_button.setStyleSheet("QPushButton {\n"
" border-top-right-radius: 10px;\n"
" border-top-left-radius: 10px;\n"
" border-bottom-right-radius: 10px;\n"
" border-bottom-left-radius: 10px;\n"
" background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 #6366F1, stop:1 #7C3AED);\n"
" font: 22px;\n"
" color: rgb(255, 255, 255);\n"
"}\n"
"\n"
"QPushButton:hover {\n"
" background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 #4338CA\n"
", stop:1 #5B21B6);\n"
"}\n"
"\n"
"QPushButton:pressed {\n"
" background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 #4338CA\n"
", stop:1 #5B21B6);\n"
" padding-left: 5px;\n"
" padding-top: 5px;\n"
"}")
self.item_search_button.setObjectName("item_search_button")
self.stackedWidget.addWidget(self.page_3)
self.page_4 = QtWidgets.QWidget()
self.page_4.setObjectName("page_4")
self.request_table = QtWidgets.QTableWidget(self.page_4)
self.request_table.setGeometry(QtCore.QRect(20, 215, 1761, 671))
self.request_table.setSizeIncrement(QtCore.QSize(0, 0))
font = QtGui.QFont()
font.setFamily("8514oem")
font.setPointSize(10)
font.setBold(False)
font.setItalic(False)
font.setWeight(50)
self.request_table.setFont(font)
self.request_table.setLayoutDirection(QtCore.Qt.LeftToRight)
self.request_table.setAutoFillBackground(False)
self.request_table.setStyleSheet("QWidget {\n"
" background-color: rgb(255, 255, 255);\n"
" alternate-background-color: rgb(241, 245, 249);\n"
" font: 10pt \"8514oem\";\n"
"}\n"
"QScrollBar:vertical {\n"
" border: none;\n"
" background: #94A3B8;\n"
" width: 14px;\n"
" margin: 15px 0 15px 0;\n"
" border-radius: 0px;\n"
" }\n"
"\n"
"/* HANDLE BAR VERTICAL */\n"
"QScrollBar::handle:vertical { \n"
" background-color: #E5E7EB;\n"
" min-height: 30px;\n"
" border-radius: 7px;\n"
"}\n"
"QScrollBar::handle:vertical:hover{ \n"
" background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 #6366F1, stop:1 #7C3AED);\n"
"}\n"
"QScrollBar::handle:vertical:pressed { \n"
" background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 #4338CA, stop:1 #5B21B6);\n"
"}\n"
"\n"
"/* BTN TOP - SCROLLBAR */\n"
"QScrollBar::sub-line:vertical {\n"
" border: none;\n"
" background-color: #94A3B8;\n"
" height: 15px;\n"
" border-top-left-radius: 7px;\n"
" border-top-right-radius: 7px;\n"
" subcontrol-position: top;\n"
" subcontrol-origin: margin;\n"
"}\n"
"QScrollBar::sub-line:vertical:hover { \n"
" background-color: rgb(255, 0, 127);\n"
"}\n"
"QScrollBar::sub-line:vertical:pressed { \n"
" background-color: rgb(185, 0, 92);\n"
"}\n"
"\n"
"/* BTN BOTTOM - SCROLLBAR */\n"
"QScrollBar::add-line:vertical {\n"
" border: none;\n"
" background-color:#94A3B8;\n"
" height: 15px;\n"
" border-bottom-left-radius: 7px;\n"
" border-bottom-right-radius: 7px;\n"
" subcontrol-position: bottom;\n"
" subcontrol-origin: margin;\n"
"}\n"
"QScrollBar::add-line:vertical:hover { \n"
" background-color: rgb(255, 0, 127);\n"
"}\n"
"QScrollBar::add-line:vertical:pressed { \n"
" background-color: rgb(185, 0, 92);\n"
"}\n"
"\n"
"/* RESET ARROW */\n"
"QScrollBar::up-arrow:vertical, QScrollBar::down-arrow:vertical {\n"
" background: none;\n"
"}\n"
"QScrollBar::add-page:vertical, QScrollBar::sub-page:vertical {\n"
" background: none;\n"
"}\n"
"")
self.request_table.setFrameShape(QtWidgets.QFrame.Box)
self.request_table.setFrameShadow(QtWidgets.QFrame.Raised)
self.request_table.setLineWidth(10)
self.request_table.setSizeAdjustPolicy(
QtWidgets.QAbstractScrollArea.AdjustToContents)
self.request_table.setAlternatingRowColors(True)
self.request_table.setSelectionMode(
QtWidgets.QAbstractItemView.SingleSelection)
self.request_table.setSelectionBehavior(
QtWidgets.QAbstractItemView.SelectRows)
self.request_table.setIconSize(QtCore.QSize(0, 0))
self.request_table.setTextElideMode(QtCore.Qt.ElideLeft)
self.request_table.setShowGrid(True)
self.request_table.setRowCount(10)
self.request_table.setColumnCount(7)
self.request_table.setObjectName("request_table")
item = QtWidgets.QTableWidgetItem()
self.request_table.setHorizontalHeaderItem(0, item)
item = QtWidgets.QTableWidgetItem()
self.request_table.setHorizontalHeaderItem(1, item)
item = QtWidgets.QTableWidgetItem()
self.request_table.setHorizontalHeaderItem(2, item)
item = QtWidgets.QTableWidgetItem()
self.request_table.setHorizontalHeaderItem(3, item)
item = QtWidgets.QTableWidgetItem()
self.request_table.setHorizontalHeaderItem(4, item)
item = QtWidgets.QTableWidgetItem()
self.request_table.setHorizontalHeaderItem(5, item)
item = QtWidgets.QTableWidgetItem()
self.request_table.setHorizontalHeaderItem(6, item)
self.request_table.horizontalHeader().setCascadingSectionResizes(False)
self.request_table.horizontalHeader().setDefaultSectionSize(239)
self.request_table.horizontalHeader().setMinimumSectionSize(26)
self.request_table.horizontalHeader().setSortIndicatorShown(True)
self.request_table.horizontalHeader().setStretchLastSection(True)
self.request_table.verticalHeader().setDefaultSectionSize(81)
self.request_table.verticalHeader().setSortIndicatorShown(True)
self.request_table.verticalHeader().setStretchLastSection(False)
self.fetch_requests_button = QtWidgets.QPushButton(self.page_4)
self.fetch_requests_button.setGeometry(QtCore.QRect(20, 150, 301, 51))
font = QtGui.QFont()
font.setPointSize(1)
font.setBold(False)
font.setItalic(False)
font.setWeight(50)
self.fetch_requests_button.setFont(font)
self.fetch_requests_button.setToolTipDuration(0)
self.fetch_requests_button.setStyleSheet("QPushButton {\n"
" border-top-right-radius: 10px;\n"
" border-top-left-radius: 10px;\n"
" border-bottom-right-radius: 10px;\n"
" border-bottom-left-radius: 10px;\n"
" background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 #F59E0B, stop:1#E11D48);\n"
" font: 22px;\n"
" color: rgb(255, 255, 255);\n"
"}\n"
"\n"
"QPushButton:hover {\n"
" background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 #B45309\n"
", stop:1 #9F1239);\n"
"}\n"
"\n"
"QPushButton:pressed {\n"
" background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 #B45309\n"
", stop:1 #9F1239);\n"
" padding-left: 5px;\n"
" padding-top: 5px;\n"
"}")
self.fetch_requests_button.setObjectName("fetch_requests_button")
self.all_requests_label = QtWidgets.QLabel(self.page_4)
self.all_requests_label.setGeometry(QtCore.QRect(670, 0, 411, 91))
font = QtGui.QFont()
font.setFamily("8514oem")
font.setPointSize(25)
self.all_requests_label.setFont(font)
self.all_requests_label.setStyleSheet("color: rgb(255, 255, 255);\n"
"image: url(:/adminSideBar/icons8-attract-customers-48.png);\n"
"padding-right:50px;")
self.all_requests_label.setAlignment(
QtCore.Qt.AlignRight | QtCore.Qt.AlignTrailing | QtCore.Qt.AlignVCenter)
self.all_requests_label.setObjectName("all_requests_label")
self.stackedWidget.addWidget(self.page_4)
self.page_5 = QtWidgets.QWidget()
self.page_5.setObjectName("page_5")
self.my_servicing_label = QtWidgets.QLabel(self.page_5)
self.my_servicing_label.setGeometry(QtCore.QRect(650, 0, 461, 91))
font = QtGui.QFont()
font.setFamily("8514oem")
font.setPointSize(25)
self.my_servicing_label.setFont(font)
self.my_servicing_label.setStyleSheet("color: rgb(255, 255, 255);\n"
"image: url(:/adminSideBar/icons8-service-48.png);\n"
"padding-right:50px;")
self.my_servicing_label.setAlignment(
QtCore.Qt.AlignRight | QtCore.Qt.AlignTrailing | QtCore.Qt.AlignVCenter)
self.my_servicing_label.setObjectName("my_servicing_label")
self.servicing_table = QtWidgets.QTableWidget(self.page_5)
self.servicing_table.setGeometry(QtCore.QRect(20, 215, 1761, 671))
self.servicing_table.setSizeIncrement(QtCore.QSize(0, 0))
font = QtGui.QFont()
font.setFamily("8514oem")
font.setPointSize(10)
font.setBold(False)
font.setItalic(False)
font.setWeight(50)
self.servicing_table.setFont(font)
self.servicing_table.setLayoutDirection(QtCore.Qt.LeftToRight)
self.servicing_table.setAutoFillBackground(False)
self.servicing_table.setStyleSheet("QWidget {\n"
" background-color: rgb(255, 255, 255);\n"
" alternate-background-color: rgb(241, 245, 249);\n"
" font: 10pt \"8514oem\";\n"
"}\n"
"QScrollBar:vertical {\n"
" border: none;\n"
" background: #94A3B8;\n"
" width: 14px;\n"
" margin: 15px 0 15px 0;\n"
" border-radius: 0px;\n"
" }\n"
"\n"
"/* HANDLE BAR VERTICAL */\n"
"QScrollBar::handle:vertical { \n"
" background-color: #E5E7EB;\n"
" min-height: 30px;\n"
" border-radius: 7px;\n"
"}\n"
"QScrollBar::handle:vertical:hover{ \n"
" background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 #6366F1, stop:1 #7C3AED);\n"
"}\n"
"QScrollBar::handle:vertical:pressed { \n"
" background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 #4338CA, stop:1 #5B21B6);\n"
"}\n"
"\n"
"/* BTN TOP - SCROLLBAR */\n"
"QScrollBar::sub-line:vertical {\n"
" border: none;\n"
" background-color: #94A3B8;\n"
" height: 15px;\n"
" border-top-left-radius: 7px;\n"
" border-top-right-radius: 7px;\n"
" subcontrol-position: top;\n"
" subcontrol-origin: margin;\n"
"}\n"
"QScrollBar::sub-line:vertical:hover { \n"
" background-color: rgb(255, 0, 127);\n"
"}\n"
"QScrollBar::sub-line:vertical:pressed { \n"
" background-color: rgb(185, 0, 92);\n"
"}\n"
"\n"
"/* BTN BOTTOM - SCROLLBAR */\n"
"QScrollBar::add-line:vertical {\n"
" border: none;\n"
" background-color:#94A3B8;\n"
" height: 15px;\n"
" border-bottom-left-radius: 7px;\n"
" border-bottom-right-radius: 7px;\n"
" subcontrol-position: bottom;\n"
" subcontrol-origin: margin;\n"
"}\n"
"QScrollBar::add-line:vertical:hover { \n"
" background-color: rgb(255, 0, 127);\n"
"}\n"
"QScrollBar::add-line:vertical:pressed { \n"
" background-color: rgb(185, 0, 92);\n"
"}\n"
"\n"
"/* RESET ARROW */\n"
"QScrollBar::up-arrow:vertical, QScrollBar::down-arrow:vertical {\n"
" background: none;\n"
"}\n"
"QScrollBar::add-page:vertical, QScrollBar::sub-page:vertical {\n"
" background: none;\n"
"}\n"
"")
self.servicing_table.setFrameShape(QtWidgets.QFrame.Box)
self.servicing_table.setFrameShadow(QtWidgets.QFrame.Raised)
self.servicing_table.setLineWidth(10)
self.servicing_table.setSizeAdjustPolicy(
QtWidgets.QAbstractScrollArea.AdjustToContents)
self.servicing_table.setAlternatingRowColors(True)
self.servicing_table.setSelectionMode(
QtWidgets.QAbstractItemView.SingleSelection)
self.servicing_table.setSelectionBehavior(
QtWidgets.QAbstractItemView.SelectRows)
self.servicing_table.setIconSize(QtCore.QSize(0, 0))
self.servicing_table.setTextElideMode(QtCore.Qt.ElideLeft)
self.servicing_table.setRowCount(10)
self.servicing_table.setColumnCount(5)
self.servicing_table.setObjectName("servicing_table")
item = QtWidgets.QTableWidgetItem()
self.servicing_table.setHorizontalHeaderItem(0, item)
item = QtWidgets.QTableWidgetItem()
self.servicing_table.setHorizontalHeaderItem(1, item)
item = QtWidgets.QTableWidgetItem()
self.servicing_table.setHorizontalHeaderItem(2, item)
item = QtWidgets.QTableWidgetItem()
self.servicing_table.setHorizontalHeaderItem(3, item)
item = QtWidgets.QTableWidgetItem()
self.servicing_table.setHorizontalHeaderItem(4, item)
self.servicing_table.horizontalHeader().setCascadingSectionResizes(False)
self.servicing_table.horizontalHeader().setDefaultSectionSize(335)
self.servicing_table.horizontalHeader().setMinimumSectionSize(26)
self.servicing_table.horizontalHeader().setSortIndicatorShown(True)
self.servicing_table.horizontalHeader().setStretchLastSection(False)
self.servicing_table.verticalHeader().setDefaultSectionSize(81)
self.servicing_table.verticalHeader().setSortIndicatorShown(True)
self.servicing_table.verticalHeader().setStretchLastSection(False)
self.refresh_servicing_button = QtWidgets.QPushButton(self.page_5)
self.refresh_servicing_button.setGeometry(
QtCore.QRect(20, 140, 241, 51))
font = QtGui.QFont()
font.setPointSize(1)
font.setBold(False)
font.setItalic(False)
font.setWeight(50)
self.refresh_servicing_button.setFont(font)
self.refresh_servicing_button.setToolTipDuration(0)
self.refresh_servicing_button.setStyleSheet("QPushButton {\n"
" border-top-right-radius: 10px;\n"
" border-top-left-radius: 10px;\n"
" border-bottom-right-radius: 10px;\n"
" border-bottom-left-radius: 10px;\n"
" background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 rgba(45, 212, 191, 1), stop:1 rgba(6, 182, 212, 1));\n"
" font: 22px;\n"
" color: rgb(255, 255, 255);\n"
"}\n"
"\n"
"QPushButton:hover {\n"
" background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 #0F766E\n"
", stop:1 #0E7490);\n"
"}\n"
"\n"
"QPushButton:pressed {\n"
" background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 #0F766E\n"
", stop:1 #0E7490);\n"
" padding-left: 5px;\n"
" padding-top: 5px;\n"
"}")
self.refresh_servicing_button.setObjectName("refresh_servicing_button")
self.stackedWidget.addWidget(self.page_5)
self.verticalLayout_5.addWidget(self.stackedWidget)
self.horizontalLayout_2.addWidget(self.frame_pages)
self.verticalLayout.addWidget(self.Content)
MainWindow.setCentralWidget(self.centralwidget)
self.retranslateUi(MainWindow)
self.stackedWidget.setCurrentIndex(0)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.title.setText(_translate("MainWindow", "Lights & Locks"))
self.btn_page_1.setText(_translate(
"MainWindow", " Home"))
self.btn_page_2.setText(_translate(
"MainWindow", " Products"))
self.btn_page_3.setText(_translate(
"MainWindow", " Items"))
self.btn_page_5.setText(_translate(
"MainWindow", " Requests"))
self.btn_page_6.setText(_translate(
"MainWindow", " Servicing"))
self.btn_page_4.setText(_translate(
"MainWindow", " Exit"))
self.welcome_admin_label.setText(
_translate("MainWindow", "Welcome Admin! "))
self.admin_table.setSortingEnabled(True)
item = self.admin_table.horizontalHeaderItem(0)
item.setText(_translate("MainWindow", "IID"))
item = self.admin_table.horizontalHeaderItem(1)
item.setText(_translate("MainWindow", "Number of \"SOLD\" Items"))
item = self.admin_table.horizontalHeaderItem(2)
item.setText(_translate("MainWindow", "Number of \"UNSOLD\" Items"))
self.refresh_button_admin.setText(_translate(
"MainWindow", "Display Sold && Unsold Items"))
self.view_customers_button.setText(_translate(
"MainWindow", "View Customers With Unpaid Fees"))
self.view_items_category_model_button.setText(
_translate("MainWindow", "Items Sold in Category && Model"))
self.initialise_database_button.setText(
_translate("MainWindow", "Initialise Database!"))
self.submit_query.setText(_translate("MainWindow", "Submit"))
self.Categories_label.setText(_translate("MainWindow", "Categories"))
self.category_comboBox.setCurrentText(_translate("MainWindow", "All"))
self.category_comboBox.setItemText(0, _translate("MainWindow", "All"))
self.category_comboBox.setItemText(
1, _translate("MainWindow", "Locks"))
self.category_comboBox.setItemText(
2, _translate("MainWindow", "Lights"))
self.Model_label.setText(_translate("MainWindow", "Models"))
self.Price_label.setText(_translate("MainWindow", "Price"))
self.model_comboBox.setCurrentText(_translate("MainWindow", "All"))
self.model_comboBox.setItemText(0, _translate("MainWindow", "All"))
self.model_comboBox.setItemText(1, _translate("MainWindow", "Light1"))
self.model_comboBox.setItemText(2, _translate("MainWindow", "Light2"))
self.model_comboBox.setItemText(
3, _translate("MainWindow", "SmartHome1"))
self.model_comboBox.setItemText(4, _translate("MainWindow", "Safe1"))
self.model_comboBox.setItemText(5, _translate("MainWindow", "Safe2"))
self.price_comboBox.setCurrentText(_translate("MainWindow", "All"))
self.price_comboBox.setItemText(0, _translate("MainWindow", "All"))
self.price_comboBox.setItemText(1, _translate("MainWindow", "$50"))
self.price_comboBox.setItemText(2, _translate("MainWindow", "$60"))
self.price_comboBox.setItemText(3, _translate("MainWindow", "$100"))
self.price_comboBox.setItemText(4, _translate("MainWindow", "$120"))
self.price_comboBox.setItemText(5, _translate("MainWindow", "$125"))
self.price_comboBox.setItemText(6, _translate("MainWindow", "$200"))
self.factory_comboBox.setCurrentText(_translate("MainWindow", "All"))
self.factory_comboBox.setItemText(0, _translate("MainWindow", "All"))
self.factory_comboBox.setItemText(1, _translate("MainWindow", "China"))
self.factory_comboBox.setItemText(
2, _translate("MainWindow", "Malaysia"))
self.factory_comboBox.setItemText(
3, _translate("MainWindow", "Philippines"))
self.Factory_label.setText(_translate("MainWindow", "Factory"))
self.production_year_label.setText(
_translate("MainWindow", "Production year"))
self.colour_comboBox.setCurrentText(_translate("MainWindow", "All"))
self.colour_comboBox.setItemText(0, _translate("MainWindow", "All"))
self.colour_comboBox.setItemText(1, _translate("MainWindow", "Blue"))
self.colour_comboBox.setItemText(2, _translate("MainWindow", "Black"))
self.colour_comboBox.setItemText(3, _translate("MainWindow", "Green"))
self.colour_comboBox.setItemText(4, _translate("MainWindow", "Yellow"))
self.colour_comboBox.setItemText(5, _translate("MainWindow", "White"))
self.Colour_label.setText(_translate("MainWindow", "Colour"))
self.production_year_comboBox.setCurrentText(
_translate("MainWindow", "All"))
self.production_year_comboBox.setItemText(
0, _translate("MainWindow", "All"))
self.production_year_comboBox.setItemText(
1, _translate("MainWindow", "2014"))
self.production_year_comboBox.setItemText(
2, _translate("MainWindow", "2015"))
self.production_year_comboBox.setItemText(
3, _translate("MainWindow", "2016"))
self.production_year_comboBox.setItemText(
4, _translate("MainWindow", "2017"))
self.production_year_comboBox.setItemText(
5, _translate("MainWindow", "2019"))
self.production_year_comboBox.setItemText(
6, _translate("MainWindow", "2020"))
self.Power_supply_label.setText(
_translate("MainWindow", "Power Supply"))
self.power_supply_comboBox.setCurrentText(
_translate("MainWindow", "All"))
self.power_supply_comboBox.setItemText(
0, _translate("MainWindow", "All"))
self.power_supply_comboBox.setItemText(
1, _translate("MainWindow", "Battery"))
self.power_supply_comboBox.setItemText(
2, _translate("MainWindow", "USB"))
self.Warranty_label.setText(_translate("MainWindow", "Warranty"))
self.warranty_comboBox.setCurrentText(_translate("MainWindow", "All"))
self.warranty_comboBox.setItemText(0, _translate("MainWindow", "All"))
self.warranty_comboBox.setItemText(1, _translate("MainWindow", "6"))
self.warranty_comboBox.setItemText(2, _translate("MainWindow", "8"))
self.warranty_comboBox.setItemText(3, _translate("MainWindow", "10"))
self.warranty_comboBox.setItemText(4, _translate("MainWindow", "12"))
self.category_amount_label.setText(_translate("MainWindow", "All"))
self.choose_an_item_label.setText(
_translate("MainWindow", "Choose An Item!"))
self.inventory_level_label.setText(
_translate("MainWindow", "Inventory Level"))
self.sold_items_label.setText(
_translate("MainWindow", "Sold Items Amount"))
self.price_label.setText(_translate("MainWindow", "Price"))
self.warranty_label.setText(_translate("MainWindow", "Warranty"))
self.model_label.setText(_translate("MainWindow", "Model"))
self.cost_label.setText(_translate("MainWindow", "Cost"))
self.price_amount_label.setText(_translate("MainWindow", "$ --"))
self.warranty_amount_label.setText(_translate("MainWindow", "--"))
self.model_amount_label.setText(_translate("MainWindow", "--"))
self.cost_amount_label.setText(_translate("MainWindow", "$ --"))
self.inventory_amount_label.setText(_translate("MainWindow", "--"))
self.sold_items_amount_label.setText(_translate("MainWindow", "--"))
self.color_label.setText(_translate("MainWindow", "Color"))
self.product_year_label.setText(
_translate("MainWindow", "Production Year"))
self.power_supply_label.setText(
_translate("MainWindow", "Power Supply"))
self.color_amount_label.setText(_translate("MainWindow", "--"))
self.producti_year_amount_label.setText(_translate("MainWindow", "--"))
self.power_supply_amount_label.setText(_translate("MainWindow", "--"))
self.item_search_label.setText(_translate("MainWindow", "Item Search"))
self.item_table.setSortingEnabled(True)
item = self.item_table.horizontalHeaderItem(0)
item.setText(_translate("MainWindow", "Product ID"))
item = self.item_table.horizontalHeaderItem(1)
item.setText(_translate("MainWindow", "Item ID"))
item = self.item_table.horizontalHeaderItem(2)
item.setText(_translate("MainWindow", "Production Year"))
item = self.item_table.horizontalHeaderItem(3)
item.setText(_translate("MainWindow", "Power Supply"))
item = self.item_table.horizontalHeaderItem(4)
item.setText(_translate("MainWindow", "Color"))
item = self.item_table.horizontalHeaderItem(5)
item.setText(_translate("MainWindow", "Factory"))
item = self.item_table.horizontalHeaderItem(6)
item.setText(_translate("MainWindow", "Purchase Status"))
item = self.item_table.horizontalHeaderItem(7)
item.setText(_translate("MainWindow", "Model"))
item = self.item_table.horizontalHeaderItem(8)
item.setText(_translate("MainWindow", "Category"))
item = self.item_table.horizontalHeaderItem(9)
item.setText(_translate("MainWindow", "Warranty"))
item = self.item_table.horizontalHeaderItem(10)
item.setText(_translate("MainWindow", "Price"))
item = self.item_table.horizontalHeaderItem(11)
item.setText(_translate("MainWindow", "Cost"))
__sortingEnabled = self.item_table.isSortingEnabled()
self.item_table.setSortingEnabled(False)
self.item_table.setSortingEnabled(__sortingEnabled)
self.under_service_comboBox.setCurrentText(
_translate("MainWindow", "Yes"))
self.under_service_comboBox.setItemText(
0, _translate("MainWindow", "Yes"))
self.under_service_comboBox.setItemText(
1, _translate("MainWindow", "All Items Search"))
self.under_service_label.setText(
_translate("MainWindow", "Under Service?"))
self.item_id_label.setText(_translate("MainWindow", "Item ID"))
self.item_search_button.setText(_translate("MainWindow", "Search"))
self.request_table.setSortingEnabled(True)
item = self.request_table.horizontalHeaderItem(0)
item.setText(_translate("MainWindow", "Request ID"))
item = self.request_table.horizontalHeaderItem(1)
item.setText(_translate("MainWindow", "Service ID"))
item = self.request_table.horizontalHeaderItem(2)
item.setText(_translate("MainWindow", "Customer ID"))
item = self.request_table.horizontalHeaderItem(3)
item.setText(_translate("MainWindow", "Admin ID"))
item = self.request_table.horizontalHeaderItem(4)
item.setText(_translate("MainWindow", "Item ID"))
item = self.request_table.horizontalHeaderItem(5)
item.setText(_translate("MainWindow", "Request Date"))
item = self.request_table.horizontalHeaderItem(6)
item.setText(_translate("MainWindow", "Approve Request"))
self.fetch_requests_button.setText(
_translate("MainWindow", "Fetch Requests"))
self.all_requests_label.setText(_translate("MainWindow", "Requests"))
self.my_servicing_label.setText(_translate("MainWindow", "Servicing"))
self.servicing_table.setSortingEnabled(True)
item = self.servicing_table.horizontalHeaderItem(0)
item.setText(_translate("MainWindow", "Admin ID"))
item = self.servicing_table.horizontalHeaderItem(1)
item.setText(_translate("MainWindow", "Request ID"))
item = self.servicing_table.horizontalHeaderItem(2)
item.setText(_translate("MainWindow", "Service ID"))
item = self.servicing_table.horizontalHeaderItem(3)
item.setText(_translate("MainWindow", "Service Status"))
item = self.servicing_table.horizontalHeaderItem(4)
item.setText(_translate("MainWindow", "Complete Service"))
self.refresh_servicing_button.setText(
_translate("MainWindow", "Refresh"))
| import resources_rc
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(1914, 1077)
MainWindow.setMinimumSize(QtCore.QSize(1000, 500))
MainWindow.setStyleSheet("background-color: rgb(45, 45, 45);")
self.centralwidget = QtWidgets.QWidget(MainWindow)
sizePolicy = QtWidgets.QSizePolicy(
QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.centralwidget.sizePolicy().hasHeightForWidth())
self.centralwidget.setSizePolicy(sizePolicy)
self.centralwidget.setObjectName("centralwidget")
self.verticalLayout = QtWidgets.QVBoxLayout(self.centralwidget)
self.verticalLayout.setContentsMargins(0, 0, 0, 0)
self.verticalLayout.setSpacing(0)
self.verticalLayout.setObjectName("verticalLayout")
self.Top_Bar = QtWidgets.QFrame(self.centralwidget)
self.Top_Bar.setEnabled(True)
self.Top_Bar.setMaximumSize(QtCore.QSize(16777215, 70))
self.Top_Bar.setStyleSheet("background-color: rgb(35, 35, 35);")
self.Top_Bar.setFrameShape(QtWidgets.QFrame.NoFrame)
self.Top_Bar.setFrameShadow(QtWidgets.QFrame.Raised)
self.Top_Bar.setObjectName("Top_Bar")
self.horizontalLayout = QtWidgets.QHBoxLayout(self.Top_Bar)
self.horizontalLayout.setContentsMargins(0, 0, 0, 0)
self.horizontalLayout.setSpacing(0)
self.horizontalLayout.setObjectName("horizontalLayout")
self.frame_toggle = QtWidgets.QFrame(self.Top_Bar)
self.frame_toggle.setMaximumSize(QtCore.QSize(70, 40))
self.frame_toggle.setStyleSheet("")
self.frame_toggle.setFrameShape(QtWidgets.QFrame.StyledPanel)
self.frame_toggle.setFrameShadow(QtWidgets.QFrame.Raised)
self.frame_toggle.setObjectName("frame_toggle")
self.verticalLayout_2 = QtWidgets.QVBoxLayout(self.frame_toggle)
self.verticalLayout_2.setContentsMargins(0, 0, 0, 0)
self.verticalLayout_2.setObjectName("verticalLayout_2")
self.Btn_Toggle = QtWidgets.QPushButton(self.frame_toggle)
sizePolicy = QtWidgets.QSizePolicy(
QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.Btn_Toggle.sizePolicy().hasHeightForWidth())
self.Btn_Toggle.setSizePolicy(sizePolicy)
self.Btn_Toggle.setMaximumSize(QtCore.QSize(16777215, 16777215))
self.Btn_Toggle.setSizeIncrement(QtCore.QSize(0, 0))
self.Btn_Toggle.setBaseSize(QtCore.QSize(0, 0))
font = QtGui.QFont()
font.setPointSize(14)
self.Btn_Toggle.setFont(font)
self.Btn_Toggle.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))
self.Btn_Toggle.setStyleSheet("image: url(:/menuBurger/icons8-menu-48.png);\n"
"color: rgb(255, 255, 255);\n"
"border: 0px solid;\n"
"background-color: rgb(35, 35, 25);\n"
"padding-left: 25px;")
self.Btn_Toggle.setText("")
self.Btn_Toggle.setObjectName("Btn_Toggle")
self.verticalLayout_2.addWidget(self.Btn_Toggle)
self.horizontalLayout.addWidget(self.frame_toggle)
self.frame_top = QtWidgets.QFrame(self.Top_Bar)
self.frame_top.setMaximumSize(QtCore.QSize(16777215, 16777215))
self.frame_top.setFrameShape(QtWidgets.QFrame.StyledPanel)
self.frame_top.setFrameShadow(QtWidgets.QFrame.Raised)
self.frame_top.setObjectName("frame_top")
self.title = QtWidgets.QLabel(self.frame_top)
self.title.setGeometry(QtCore.QRect(640, 10, 641, 51))
self.title.setMaximumSize(QtCore.QSize(641, 16777215))
font = QtGui.QFont()
font.setFamily("8514oem")
font.setPointSize(32)
font.setBold(True)
font.setWeight(75)
self.title.setFont(font)
self.title.setStyleSheet("color: #C7D2FE;")
self.title.setAlignment(QtCore.Qt.AlignCenter)
self.title.setObjectName("title")
self.horizontalLayout.addWidget(self.frame_top)
self.verticalLayout.addWidget(self.Top_Bar)
self.Content = QtWidgets.QFrame(self.centralwidget)
self.Content.setFrameShape(QtWidgets.QFrame.NoFrame)
self.Content.setFrameShadow(QtWidgets.QFrame.Raised)
self.Content.setObjectName("Content")
self.horizontalLayout_2 = QtWidgets.QHBoxLayout(self.Content)
self.horizontalLayout_2.setContentsMargins(0, 0, 0, 0)
self.horizontalLayout_2.setSpacing(0)
self.horizontalLayout_2.setObjectName("horizontalLayout_2")
self.frame_left_menu = QtWidgets.QFrame(self.Content)
self.frame_left_menu.setMinimumSize(QtCore.QSize(0, 0))
self.frame_left_menu.setMaximumSize(QtCore.QSize(100, 16777215))
self.frame_left_menu.setStyleSheet("background-color: rgb(35, 35, 35);\n"
"padding:1px;")
self.frame_left_menu.setFrameShape(QtWidgets.QFrame.StyledPanel)
self.frame_left_menu.setFrameShadow(QtWidgets.QFrame.Raised)
self.frame_left_menu.setObjectName("frame_left_menu")
self.verticalLayout_3 = QtWidgets.QVBoxLayout(self.frame_left_menu)
self.verticalLayout_3.setObjectName("verticalLayout_3")
self.btn_page_1 = QtWidgets.QPushButton(self.frame_left_menu)
self.btn_page_1.setMinimumSize(QtCore.QSize(0, 100))
font = QtGui.QFont()
font.setFamily("8514oem")
font.setPointSize(20)
self.btn_page_1.setFont(font)
self.btn_page_1.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))
self.btn_page_1.setStyleSheet("QPushButton {\n"
" \n"
" image: url(:/adminSideBar/icons8-home-48.png);\n"
" color: rgb(255, 255, 255);\n"
" background-color: rgb(35, 35, 35);\n"
" border: 0px solid;\n"
" padding-right: 0px;\n"
"}\n"
"QPushButton:hover {\n"
" \n"
" background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 #2DD4BF, stop:1 #0EA5E9);\n"
" border-radius: 20px;\n"
"}")
self.btn_page_1.setObjectName("btn_page_1")
self.verticalLayout_3.addWidget(self.btn_page_1)
self.btn_page_2 = QtWidgets.QPushButton(self.frame_left_menu)
self.btn_page_2.setMinimumSize(QtCore.QSize(0, 100))
font = QtGui.QFont()
font.setFamily("8514oem")
font.setPointSize(20)
self.btn_page_2.setFont(font)
self.btn_page_2.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))
self.btn_page_2.setStyleSheet("QPushButton {\n"
" \n"
" image: url(:/adminSideBar/icons8-products-49.png);\n"
" color: rgb(255, 255, 255);\n"
" background-color: rgb(35, 35, 35);\n"
" border: 0px solid;\n"
" padding-right: 0px;\n"
"}\n"
"QPushButton:hover {\n"
" background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 #2DD4BF, stop:1 #0EA5E9);\n"
" border-radius: 20px;\n"
"}")
self.btn_page_2.setObjectName("btn_page_2")
self.verticalLayout_3.addWidget(self.btn_page_2)
self.btn_page_3 = QtWidgets.QPushButton(self.frame_left_menu)
self.btn_page_3.setMinimumSize(QtCore.QSize(0, 100))
font = QtGui.QFont()
font.setFamily("8514oem")
font.setPointSize(20)
self.btn_page_3.setFont(font)
self.btn_page_3.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))
self.btn_page_3.setStyleSheet("QPushButton {\n"
" \n"
" \n"
" image: url(:/adminSideBar/icons8-product-management-48.png);\n"
" color: rgb(255, 255, 255);\n"
" background-color: rgb(35, 35, 35);\n"
" border: 0px solid;\n"
" padding-right: 0px;\n"
"}\n"
"QPushButton:hover {\n"
" background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 #2DD4BF, stop:1 #0EA5E9);\n"
" border-radius: 20px;\n"
"}")
self.btn_page_3.setObjectName("btn_page_3")
self.verticalLayout_3.addWidget(self.btn_page_3)
self.btn_page_5 = QtWidgets.QPushButton(self.frame_left_menu)
self.btn_page_5.setMinimumSize(QtCore.QSize(0, 100))
font = QtGui.QFont()
font.setFamily("8514oem")
font.setPointSize(20)
self.btn_page_5.setFont(font)
self.btn_page_5.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))
self.btn_page_5.setStyleSheet("QPushButton {\n"
" \n"
" \n"
" image: url(:/adminSideBar/icons8-attract-customers-48.png);\n"
" color: rgb(255, 255, 255);\n"
" background-color: rgb(35, 35, 35);\n"
" border: 0px solid;\n"
" padding-right: 0px;\n"
"}\n"
"QPushButton:hover {\n"
" \n"
" background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 #2DD4BF, stop:1 #0EA5E9);\n"
" border-radius: 20px;\n"
"}")
self.btn_page_5.setObjectName("btn_page_5")
self.verticalLayout_3.addWidget(self.btn_page_5)
self.btn_page_6 = QtWidgets.QPushButton(self.frame_left_menu)
self.btn_page_6.setMinimumSize(QtCore.QSize(0, 100))
font = QtGui.QFont()
font.setFamily("8514oem")
font.setPointSize(20)
self.btn_page_6.setFont(font)
self.btn_page_6.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))
self.btn_page_6.setStyleSheet("QPushButton {\n"
" \n"
" \n"
" image: url(:/adminSideBar/icons8-service-48.png);\n"
" color: rgb(255, 255, 255);\n"
" background-color: rgb(35, 35, 35);\n"
" border: 0px solid;\n"
" padding-right: 0px;\n"
"}\n"
"QPushButton:hover {\n"
" \n"
" background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 #2DD4BF, stop:1 #0EA5E9);\n"
" border-radius: 20px;\n"
"}")
self.btn_page_6.setObjectName("btn_page_6")
self.verticalLayout_3.addWidget(self.btn_page_6)
self.btn_page_4 = QtWidgets.QPushButton(self.frame_left_menu)
sizePolicy = QtWidgets.QSizePolicy(
QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.btn_page_4.sizePolicy().hasHeightForWidth())
self.btn_page_4.setSizePolicy(sizePolicy)
self.btn_page_4.setMinimumSize(QtCore.QSize(0, 100))
font = QtGui.QFont()
font.setFamily("8514oem")
font.setPointSize(20)
self.btn_page_4.setFont(font)
self.btn_page_4.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))
self.btn_page_4.setStyleSheet("QPushButton {\n"
" image: url(:/SideBar/icons8-exit-48.png);\n"
" color: rgb(255, 255, 255);\n"
" background-color: rgb(35, 35, 35);\n"
" border: 0px solid;\n"
" padding-right: 0px;\n"
"}\n"
"QPushButton:hover {\n"
" background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 #2DD4BF, stop:1 #0EA5E9);\n"
" border-radius: 20px;\n"
"}")
self.btn_page_4.setObjectName("btn_page_4")
self.verticalLayout_3.addWidget(self.btn_page_4)
self.frame_top_menus = QtWidgets.QFrame(self.frame_left_menu)
self.frame_top_menus.setMinimumSize(QtCore.QSize(0, 0))
self.frame_top_menus.setFrameShape(QtWidgets.QFrame.NoFrame)
self.frame_top_menus.setFrameShadow(QtWidgets.QFrame.Raised)
self.frame_top_menus.setObjectName("frame_top_menus")
self.verticalLayout_3.addWidget(self.frame_top_menus)
self.horizontalLayout_2.addWidget(self.frame_left_menu)
self.frame_pages = QtWidgets.QFrame(self.Content)
self.frame_pages.setFrameShape(QtWidgets.QFrame.StyledPanel)
self.frame_pages.setFrameShadow(QtWidgets.QFrame.Raised)
self.frame_pages.setObjectName("frame_pages")
self.verticalLayout_5 = QtWidgets.QVBoxLayout(self.frame_pages)
self.verticalLayout_5.setSizeConstraint(
QtWidgets.QLayout.SetNoConstraint)
self.verticalLayout_5.setObjectName("verticalLayout_5")
self.stackedWidget = QtWidgets.QStackedWidget(self.frame_pages)
palette = QtGui.QPalette()
brush = QtGui.QBrush(QtGui.QColor(45, 45, 45))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Button, brush)
brush = QtGui.QBrush(QtGui.QColor(45, 45, 45))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Base, brush)
brush = QtGui.QBrush(QtGui.QColor(45, 45, 45))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Window, brush)
brush = QtGui.QBrush(QtGui.QColor(45, 45, 45))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Button, brush)
brush = QtGui.QBrush(QtGui.QColor(45, 45, 45))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Base, brush)
brush = QtGui.QBrush(QtGui.QColor(45, 45, 45))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Window, brush)
brush = QtGui.QBrush(QtGui.QColor(45, 45, 45))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Button, brush)
brush = QtGui.QBrush(QtGui.QColor(45, 45, 45))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Base, brush)
brush = QtGui.QBrush(QtGui.QColor(45, 45, 45))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Window, brush)
self.stackedWidget.setPalette(palette)
self.stackedWidget.setStyleSheet("")
self.stackedWidget.setFrameShape(QtWidgets.QFrame.NoFrame)
self.stackedWidget.setObjectName("stackedWidget")
self.page_1 = QtWidgets.QWidget()
self.page_1.setObjectName("page_1")
self.welcome_admin_label = QtWidgets.QLabel(self.page_1)
self.welcome_admin_label.setGeometry(QtCore.QRect(670, 0, 461, 91))
font = QtGui.QFont()
font.setFamily("8514oem")
font.setPointSize(25)
self.welcome_admin_label.setFont(font)
self.welcome_admin_label.setStyleSheet("color: rgb(255, 255, 255);\n"
"image: url(:/adminSideBar/icons8-home-48.png);\n"
"padding-right:50px;")
self.welcome_admin_label.setAlignment(
QtCore.Qt.AlignRight | QtCore.Qt.AlignTrailing | QtCore.Qt.AlignVCenter)
self.welcome_admin_label.setObjectName("welcome_admin_label")
self.admin_table = QtWidgets.QTableWidget(self.page_1)
self.admin_table.setGeometry(QtCore.QRect(20, 325, 1761, 561))
self.admin_table.setSizeIncrement(QtCore.QSize(0, 0))
font = QtGui.QFont()
font.setFamily("8514oem")
font.setPointSize(10)
font.setBold(False)
font.setItalic(False)
font.setWeight(50)
self.admin_table.setFont(font)
self.admin_table.setLayoutDirection(QtCore.Qt.LeftToRight)
self.admin_table.setAutoFillBackground(False)
self.admin_table.setStyleSheet("QWidget {\n"
" background-color: rgb(255, 255, 255);\n"
" alternate-background-color: rgb(241, 245, 249);\n"
" font: 10pt \"8514oem\";\n"
"}\n"
"QScrollBar:vertical {\n"
" border: none;\n"
" background: #94A3B8;\n"
" width: 14px;\n"
" margin: 15px 0 15px 0;\n"
" border-radius: 0px;\n"
" }\n"
"\n"
"/* HANDLE BAR VERTICAL */\n"
"QScrollBar::handle:vertical { \n"
" background-color: #E5E7EB;\n"
" min-height: 30px;\n"
" border-radius: 7px;\n"
"}\n"
"QScrollBar::handle:vertical:hover{ \n"
" background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 #6366F1, stop:1 #7C3AED);\n"
"}\n"
"QScrollBar::handle:vertical:pressed { \n"
" background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 #4338CA, stop:1 #5B21B6);\n"
"}\n"
"\n"
"/* BTN TOP - SCROLLBAR */\n"
"QScrollBar::sub-line:vertical {\n"
" border: none;\n"
" background-color: #94A3B8;\n"
" height: 15px;\n"
" border-top-left-radius: 7px;\n"
" border-top-right-radius: 7px;\n"
" subcontrol-position: top;\n"
" subcontrol-origin: margin;\n"
"}\n"
"QScrollBar::sub-line:vertical:hover { \n"
" background-color: rgb(255, 0, 127);\n"
"}\n"
"QScrollBar::sub-line:vertical:pressed { \n"
" background-color: rgb(185, 0, 92);\n"
"}\n"
"\n"
"/* BTN BOTTOM - SCROLLBAR */\n"
"QScrollBar::add-line:vertical {\n"
" border: none;\n"
" background-color:#94A3B8;\n"
" height: 15px;\n"
" border-bottom-left-radius: 7px;\n"
" border-bottom-right-radius: 7px;\n"
" subcontrol-position: bottom;\n"
" subcontrol-origin: margin;\n"
"}\n"
"QScrollBar::add-line:vertical:hover { \n"
" background-color: rgb(255, 0, 127);\n"
"}\n"
"QScrollBar::add-line:vertical:pressed { \n"
" background-color: rgb(185, 0, 92);\n"
"}\n"
"\n"
"/* RESET ARROW */\n"
"QScrollBar::up-arrow:vertical, QScrollBar::down-arrow:vertical {\n"
" background: none;\n"
"}\n"
"QScrollBar::add-page:vertical, QScrollBar::sub-page:vertical {\n"
" background: none;\n"
"}\n"
"")
self.admin_table.setFrameShape(QtWidgets.QFrame.Box)
self.admin_table.setFrameShadow(QtWidgets.QFrame.Raised)
self.admin_table.setLineWidth(10)
self.admin_table.setSizeAdjustPolicy(
QtWidgets.QAbstractScrollArea.AdjustToContents)
self.admin_table.setAlternatingRowColors(True)
self.admin_table.setSelectionMode(
QtWidgets.QAbstractItemView.SingleSelection)
self.admin_table.setSelectionBehavior(
QtWidgets.QAbstractItemView.SelectRows)
self.admin_table.setIconSize(QtCore.QSize(0, 0))
self.admin_table.setTextElideMode(QtCore.Qt.ElideLeft)
self.admin_table.setRowCount(7)
self.admin_table.setColumnCount(3)
self.admin_table.setObjectName("admin_table")
item = QtWidgets.QTableWidgetItem()
self.admin_table.setHorizontalHeaderItem(0, item)
item = QtWidgets.QTableWidgetItem()
self.admin_table.setHorizontalHeaderItem(1, item)
item = QtWidgets.QTableWidgetItem()
self.admin_table.setHorizontalHeaderItem(2, item)
self.admin_table.horizontalHeader().setCascadingSectionResizes(False)
self.admin_table.horizontalHeader().setDefaultSectionSize(550)
self.admin_table.horizontalHeader().setMinimumSectionSize(26)
self.admin_table.horizontalHeader().setStretchLastSection(True)
self.admin_table.verticalHeader().setDefaultSectionSize(87)
self.admin_table.verticalHeader().setSortIndicatorShown(True)
self.admin_table.verticalHeader().setStretchLastSection(False)
self.refresh_button_admin = QtWidgets.QPushButton(self.page_1)
self.refresh_button_admin.setGeometry(QtCore.QRect(1390, 250, 391, 51))
font = QtGui.QFont()
font.setPointSize(1)
font.setBold(False)
font.setItalic(False)
font.setWeight(50)
self.refresh_button_admin.setFont(font)
self.refresh_button_admin.setToolTipDuration(0)
self.refresh_button_admin.setStyleSheet("QPushButton {\n"
" border-top-right-radius: 10px;\n"
" border-top-left-radius: 10px;\n"
" border-bottom-right-radius: 10px;\n"
" border-bottom-left-radius: 10px;\n"
" background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 rgba(45, 212, 191, 1), stop:1 rgba(6, 182, 212, 1));\n"
" font: 22px;\n"
" color: rgb(255, 255, 255);\n"
"}\n"
"\n"
"QPushButton:hover {\n"
" background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 #0F766E\n"
", stop:1 #0E7490);\n"
"}\n"
"\n"
"QPushButton:pressed {\n"
" background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 #0F766E\n"
", stop:1 #0E7490);\n"
" padding-left: 5px;\n"
" padding-top: 5px;\n"
"}")
self.refresh_button_admin.setObjectName("refresh_button_admin")
self.view_customers_button = QtWidgets.QPushButton(self.page_1)
self.view_customers_button.setGeometry(QtCore.QRect(20, 250, 481, 51))
font = QtGui.QFont()
font.setPointSize(1)
font.setBold(False)
font.setItalic(False)
font.setWeight(50)
self.view_customers_button.setFont(font)
self.view_customers_button.setToolTipDuration(0)
self.view_customers_button.setStyleSheet("QPushButton {\n"
" border-radius: 10px;\n"
" font: 22px;\n"
" color: rgb(255, 255, 255);\n"
" border: 5px solid;\n"
" border-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 #6366F1, stop:1#7C3AED);\n"
"}\n"
"\n"
"QPushButton:hover {\n"
" border: 5px solid;\n"
" border-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 #3730A3, stop:1 #5B21B6);\n"
"}\n"
"\n"
"QPushButton:pressed {\n"
" border: 5px solid;\n"
" border-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 #3730A3\n"
", stop:1 #5B21B6);\n"
" padding-left: 5px;\n"
" padding-top: 5px;\n"
"}")
self.view_customers_button.setObjectName("view_customers_button")
self.view_items_category_model_button = QtWidgets.QPushButton(
self.page_1)
self.view_items_category_model_button.setGeometry(
QtCore.QRect(20, 170, 481, 51))
font = QtGui.QFont()
font.setPointSize(1)
font.setBold(False)
font.setItalic(False)
font.setWeight(50)
self.view_items_category_model_button.setFont(font)
self.view_items_category_model_button.setToolTipDuration(0)
self.view_items_category_model_button.setStyleSheet("QPushButton {\n"
" border-radius: 10px;\n"
" font: 22px;\n"
" color: rgb(255, 255, 255);\n"
" border: 5px solid;\n"
" border-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 #6366F1, stop:1#7C3AED);\n"
"}\n"
"\n"
"QPushButton:hover {\n"
" border: 5px solid;\n"
" border-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 #3730A3, stop:1 #5B21B6);\n"
"}\n"
"\n"
"QPushButton:pressed {\n"
" border: 5px solid;\n"
" border-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 #3730A3\n"
", stop:1 #5B21B6);\n"
" padding-left: 5px;\n"
" padding-top: 5px;\n"
"}")
self.view_items_category_model_button.setObjectName(
"view_items_category_model_button")
self.initialise_database_button = QtWidgets.QPushButton(self.page_1)
self.initialise_database_button.setGeometry(
QtCore.QRect(1390, 180, 391, 51))
font = QtGui.QFont()
font.setPointSize(1)
font.setBold(False)
font.setItalic(False)
font.setWeight(50)
self.initialise_database_button.setFont(font)
self.initialise_database_button.setToolTipDuration(0)
self.initialise_database_button.setStyleSheet("QPushButton {\n"
" border-top-right-radius: 10px;\n"
" border-top-left-radius: 10px;\n"
" border-bottom-right-radius: 10px;\n"
" border-bottom-left-radius: 10px;\n"
" background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 #6366F1, stop:1#7C3AED);\n"
" font: 22px;\n"
" color: rgb(255, 255, 255);\n"
"}\n"
"\n"
"QPushButton:hover {\n"
" background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 #3730A3\n"
", stop:1 #5B21B6);\n"
"}\n"
"\n"
"QPushButton:pressed {\n"
" background-color:qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 #3730A3\n"
", stop:1 #5B21B6);\n"
" padding-left: 5px;\n"
" padding-top: 5px;\n"
"}")
self.initialise_database_button.setObjectName(
"initialise_database_button")
self.stackedWidget.addWidget(self.page_1)
self.page_2 = QtWidgets.QWidget()
self.page_2.setObjectName("page_2")
self.submit_query = QtWidgets.QPushButton(self.page_2)
self.submit_query.setGeometry(QtCore.QRect(1470, 250, 301, 51))
font = QtGui.QFont()
font.setPointSize(1)
font.setBold(False)
font.setItalic(False)
font.setWeight(50)
self.submit_query.setFont(font)
self.submit_query.setToolTipDuration(0)
self.submit_query.setStyleSheet("QPushButton {\n"
" border-top-right-radius: 10px;\n"
" border-top-left-radius: 10px;\n"
" border-bottom-right-radius: 10px;\n"
" border-bottom-left-radius: 10px;\n"
" background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 #F59E0B, stop:1#E11D48);\n"
" font: 22px;\n"
" color: rgb(255, 255, 255);\n"
"}\n"
"\n"
"QPushButton:hover {\n"
" background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 #B45309\n"
", stop:1 #9F1239);\n"
"}\n"
"\n"
"QPushButton:pressed {\n"
" background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 #B45309\n"
", stop:1 #9F1239);\n"
" padding-left: 5px;\n"
" padding-top: 5px;\n"
"}")
self.submit_query.setObjectName("submit_query")
self.Categories_label = QtWidgets.QLineEdit(self.page_2)
self.Categories_label.setGeometry(QtCore.QRect(20, 10, 131, 22))
font = QtGui.QFont()
font.setFamily("8514oem")
font.setPointSize(16)
self.Categories_label.setFont(font)
self.Categories_label.setStyleSheet("color: rgb(255, 255, 255);\n"
"background-color: rgba(255, 255, 255, 0);")
self.Categories_label.setFrame(False)
self.Categories_label.setObjectName("Categories_label")
self.category_comboBox = QtWidgets.QComboBox(self.page_2)
self.category_comboBox.setGeometry(QtCore.QRect(20, 37, 519, 51))
sizePolicy = QtWidgets.QSizePolicy(
QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Minimum)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.category_comboBox.sizePolicy().hasHeightForWidth())
self.category_comboBox.setSizePolicy(sizePolicy)
self.category_comboBox.setMinimumSize(QtCore.QSize(143, 2))
self.category_comboBox.setMaximumSize(QtCore.QSize(16777214, 16777215))
palette = QtGui.QPalette()
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active,
QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Button, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active,
QtGui.QPalette.ButtonText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Base, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Window, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive,
QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Button, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive,
QtGui.QPalette.ButtonText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Base, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Window, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled,
QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Button, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled,
QtGui.QPalette.ButtonText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Base, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Window, brush)
self.category_comboBox.setPalette(palette)
font = QtGui.QFont()
font.setFamily("8514oem")
font.setPointSize(16)
font.setBold(False)
font.setItalic(False)
font.setWeight(50)
self.category_comboBox.setFont(font)
self.category_comboBox.setCursor(
QtGui.QCursor(QtCore.Qt.PointingHandCursor))
self.category_comboBox.setStyleSheet("QComboBox {\n"
" border: 1px solid gray;\n"
" border-radius: 10px;\n"
" padding: 1px 18px 1px 3px;\n"
" min-width: 6em;\n"
" font: 16pt \"8514oem\";\n"
" background-color: rgb(255, 255, 255);\n"
" \n"
" color: rgb(0, 0, 0);\n"
"}\n"
"\n"
"QComboBox:on { /* shift the text when the popup opens */\n"
" padding-top: 3px;\n"
" padding-left: 4px;\n"
" background: white;\n"
" border-radius: 10px;\n"
"}\n"
"\n"
"QComboBox::drop-down {\n"
" subcontrol-origin: padding;\n"
" subcontrol-position: top right;\n"
" width: 15px;\n"
" background-color:white;\n"
" border-left-width: 1px;\n"
" border-left-color: darkgray;\n"
" border-left-style: solid; /* just a single line */\n"
" border-top-right-radius: 3px; /* same radius as the QComboBox */\n"
" border-bottom-right-radius: 3px;\n"
" border-radius: 10px;\n"
"}\n"
"\n"
"QComboBox::down-arrow:on { /* shift the arrow when popup is open */\n"
" top: 1px;\n"
" left: 1px;\n"
"}\n"
"QListView\n"
"{\n"
"background-color : #334155;\n"
"color: rgb(255, 255, 255);\n"
"}")
self.category_comboBox.setEditable(False)
self.category_comboBox.setFrame(True)
self.category_comboBox.setObjectName("category_comboBox")
self.category_comboBox.addItem("")
self.category_comboBox.addItem("")
self.category_comboBox.addItem("")
self.gradient_backdrop = QtWidgets.QLabel(self.page_2)
self.gradient_backdrop.setGeometry(QtCore.QRect(10, 0, 1781, 311))
self.gradient_backdrop.setStyleSheet("background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 #0D9488, stop:1 #0E7490);\n"
"border-radius: 20px;")
self.gradient_backdrop.setText("")
self.gradient_backdrop.setObjectName("gradient_backdrop")
self.Model_label = QtWidgets.QLineEdit(self.page_2)
self.Model_label.setGeometry(QtCore.QRect(20, 110, 131, 22))
font = QtGui.QFont()
font.setFamily("8514oem")
font.setPointSize(16)
self.Model_label.setFont(font)
self.Model_label.setStyleSheet("color: rgb(255, 255, 255);\n"
"background-color: rgba(255, 255, 255, 0);")
self.Model_label.setFrame(False)
self.Model_label.setObjectName("Model_label")
self.Price_label = QtWidgets.QLineEdit(self.page_2)
self.Price_label.setGeometry(QtCore.QRect(20, 210, 131, 22))
font = QtGui.QFont()
font.setFamily("8514oem")
font.setPointSize(16)
self.Price_label.setFont(font)
self.Price_label.setStyleSheet("color: rgb(255, 255, 255);\n"
"background-color: rgba(255, 255, 255, 0);")
self.Price_label.setFrame(False)
self.Price_label.setObjectName("Price_label")
self.model_comboBox = QtWidgets.QComboBox(self.page_2)
self.model_comboBox.setGeometry(QtCore.QRect(20, 140, 519, 51))
sizePolicy = QtWidgets.QSizePolicy(
QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Minimum)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.model_comboBox.sizePolicy().hasHeightForWidth())
self.model_comboBox.setSizePolicy(sizePolicy)
self.model_comboBox.setMinimumSize(QtCore.QSize(143, 2))
self.model_comboBox.setMaximumSize(QtCore.QSize(16777214, 16777215))
palette = QtGui.QPalette()
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active,
QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Button, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active,
QtGui.QPalette.ButtonText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Base, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Window, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive,
QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Button, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive,
QtGui.QPalette.ButtonText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Base, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Window, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled,
QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Button, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled,
QtGui.QPalette.ButtonText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Base, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Window, brush)
self.model_comboBox.setPalette(palette)
font = QtGui.QFont()
font.setFamily("8514oem")
font.setPointSize(16)
font.setBold(False)
font.setItalic(False)
font.setWeight(50)
self.model_comboBox.setFont(font)
self.model_comboBox.setCursor(
QtGui.QCursor(QtCore.Qt.PointingHandCursor))
self.model_comboBox.setStyleSheet("QComboBox {\n"
" border: 1px solid gray;\n"
" border-radius: 10px;\n"
" padding: 1px 18px 1px 3px;\n"
" min-width: 6em;\n"
" font: 16pt \"8514oem\";\n"
" background-color: rgb(255, 255, 255);\n"
" \n"
" color: rgb(0, 0, 0);\n"
"}\n"
"\n"
"QComboBox:on { /* shift the text when the popup opens */\n"
" padding-top: 3px;\n"
" padding-left: 4px;\n"
" background: white;\n"
" border-radius: 10px;\n"
"}\n"
"\n"
"QComboBox::drop-down {\n"
" subcontrol-origin: padding;\n"
" subcontrol-position: top right;\n"
" width: 15px;\n"
" background-color:white;\n"
" border-left-width: 1px;\n"
" border-left-color: darkgray;\n"
" border-left-style: solid; /* just a single line */\n"
" border-top-right-radius: 3px; /* same radius as the QComboBox */\n"
" border-bottom-right-radius: 3px;\n"
" border-radius: 10px;\n"
"}\n"
"\n"
"QComboBox::down-arrow:on { /* shift the arrow when popup is open */\n"
" top: 1px;\n"
" left: 1px;\n"
"}\n"
"QListView\n"
"{\n"
"background-color : #334155;\n"
"color: rgb(255, 255, 255);\n"
"}")
self.model_comboBox.setEditable(False)
self.model_comboBox.setFrame(True)
self.model_comboBox.setObjectName("model_comboBox")
self.model_comboBox.addItem("")
self.model_comboBox.addItem("")
self.model_comboBox.addItem("")
self.model_comboBox.addItem("")
self.model_comboBox.addItem("")
self.model_comboBox.addItem("")
self.price_comboBox = QtWidgets.QComboBox(self.page_2)
self.price_comboBox.setGeometry(QtCore.QRect(20, 240, 519, 51))
sizePolicy = QtWidgets.QSizePolicy(
QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Minimum)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.price_comboBox.sizePolicy().hasHeightForWidth())
self.price_comboBox.setSizePolicy(sizePolicy)
self.price_comboBox.setMinimumSize(QtCore.QSize(143, 2))
self.price_comboBox.setMaximumSize(QtCore.QSize(16777214, 16777215))
palette = QtGui.QPalette()
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active,
QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Button, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active,
QtGui.QPalette.ButtonText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Base, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Window, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive,
QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Button, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive,
QtGui.QPalette.ButtonText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Base, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Window, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled,
QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Button, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled,
QtGui.QPalette.ButtonText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Base, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Window, brush)
self.price_comboBox.setPalette(palette)
font = QtGui.QFont()
font.setFamily("8514oem")
font.setPointSize(16)
font.setBold(False)
font.setItalic(False)
font.setWeight(50)
self.price_comboBox.setFont(font)
self.price_comboBox.setCursor(
QtGui.QCursor(QtCore.Qt.PointingHandCursor))
self.price_comboBox.setStyleSheet("QComboBox {\n"
" border: 1px solid gray;\n"
" border-radius: 10px;\n"
" padding: 1px 18px 1px 3px;\n"
" min-width: 6em;\n"
" font: 16pt \"8514oem\";\n"
" background-color: rgb(255, 255, 255);\n"
" \n"
" color: rgb(0, 0, 0);\n"
"}\n"
"\n"
"QComboBox:on { /* shift the text when the popup opens */\n"
" padding-top: 3px;\n"
" padding-left: 4px;\n"
" background: white;\n"
" border-radius: 10px;\n"
"}\n"
"\n"
"QComboBox::drop-down {\n"
" subcontrol-origin: padding;\n"
" subcontrol-position: top right;\n"
" width: 15px;\n"
" background-color:white;\n"
" border-left-width: 1px;\n"
" border-left-color: darkgray;\n"
" border-left-style: solid; /* just a single line */\n"
" border-top-right-radius: 3px; /* same radius as the QComboBox */\n"
" border-bottom-right-radius: 3px;\n"
" border-radius: 10px;\n"
"}\n"
"\n"
"QComboBox::down-arrow:on { /* shift the arrow when popup is open */\n"
" top: 1px;\n"
" left: 1px;\n"
"}\n"
"QListView\n"
"{\n"
"background-color : #334155;\n"
"color: rgb(255, 255, 255);\n"
"}")
self.price_comboBox.setEditable(False)
self.price_comboBox.setFrame(True)
self.price_comboBox.setObjectName("price_comboBox")
self.price_comboBox.addItem("")
self.price_comboBox.addItem("")
self.price_comboBox.addItem("")
self.price_comboBox.addItem("")
self.price_comboBox.addItem("")
self.price_comboBox.addItem("")
self.price_comboBox.addItem("")
self.factory_comboBox = QtWidgets.QComboBox(self.page_2)
self.factory_comboBox.setGeometry(QtCore.QRect(630, 140, 519, 51))
sizePolicy = QtWidgets.QSizePolicy(
QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Minimum)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.factory_comboBox.sizePolicy().hasHeightForWidth())
self.factory_comboBox.setSizePolicy(sizePolicy)
self.factory_comboBox.setMinimumSize(QtCore.QSize(143, 2))
self.factory_comboBox.setMaximumSize(QtCore.QSize(16777214, 16777215))
palette = QtGui.QPalette()
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active,
QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Button, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active,
QtGui.QPalette.ButtonText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Base, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Window, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive,
QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Button, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive,
QtGui.QPalette.ButtonText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Base, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Window, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled,
QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Button, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled,
QtGui.QPalette.ButtonText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Base, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Window, brush)
self.factory_comboBox.setPalette(palette)
font = QtGui.QFont()
font.setFamily("8514oem")
font.setPointSize(16)
font.setBold(False)
font.setItalic(False)
font.setWeight(50)
self.factory_comboBox.setFont(font)
self.factory_comboBox.setCursor(
QtGui.QCursor(QtCore.Qt.PointingHandCursor))
self.factory_comboBox.setStyleSheet("QComboBox {\n"
" border: 1px solid gray;\n"
" border-radius: 10px;\n"
" padding: 1px 18px 1px 3px;\n"
" min-width: 6em;\n"
" font: 16pt \"8514oem\";\n"
" background-color: rgb(255, 255, 255);\n"
" \n"
" color: rgb(0, 0, 0);\n"
"}\n"
"\n"
"QComboBox:on { /* shift the text when the popup opens */\n"
" padding-top: 3px;\n"
" padding-left: 4px;\n"
" background: white;\n"
" border-radius: 10px;\n"
"}\n"
"\n"
"QComboBox::drop-down {\n"
" subcontrol-origin: padding;\n"
" subcontrol-position: top right;\n"
" width: 15px;\n"
" background-color:white;\n"
" border-left-width: 1px;\n"
" border-left-color: darkgray;\n"
" border-left-style: solid; /* just a single line */\n"
" border-top-right-radius: 3px; /* same radius as the QComboBox */\n"
" border-bottom-right-radius: 3px;\n"
" border-radius: 10px;\n"
"}\n"
"\n"
"QComboBox::down-arrow:on { /* shift the arrow when popup is open */\n"
" top: 1px;\n"
" left: 1px;\n"
"}\n"
"QListView\n"
"{\n"
"background-color : #334155;\n"
"color: rgb(255, 255, 255);\n"
"}")
self.factory_comboBox.setEditable(False)
self.factory_comboBox.setFrame(True)
self.factory_comboBox.setObjectName("factory_comboBox")
self.factory_comboBox.addItem("")
self.factory_comboBox.addItem("")
self.factory_comboBox.addItem("")
self.factory_comboBox.addItem("")
self.Factory_label = QtWidgets.QLineEdit(self.page_2)
self.Factory_label.setGeometry(QtCore.QRect(630, 110, 131, 22))
font = QtGui.QFont()
font.setFamily("8514oem")
font.setPointSize(16)
self.Factory_label.setFont(font)
self.Factory_label.setStyleSheet("color: rgb(255, 255, 255);\n"
"background-color: rgba(255, 255, 255, 0);")
self.Factory_label.setFrame(False)
self.Factory_label.setObjectName("Factory_label")
self.production_year_label = QtWidgets.QLineEdit(self.page_2)
self.production_year_label.setGeometry(QtCore.QRect(630, 210, 191, 22))
font = QtGui.QFont()
font.setFamily("8514oem")
font.setPointSize(16)
self.production_year_label.setFont(font)
self.production_year_label.setStyleSheet("color: rgb(255, 255, 255);\n"
"background-color: rgba(255, 255, 255, 0);")
self.production_year_label.setFrame(False)
self.production_year_label.setObjectName("production_year_label")
self.colour_comboBox = QtWidgets.QComboBox(self.page_2)
self.colour_comboBox.setGeometry(QtCore.QRect(630, 37, 519, 51))
sizePolicy = QtWidgets.QSizePolicy(
QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Minimum)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.colour_comboBox.sizePolicy().hasHeightForWidth())
self.colour_comboBox.setSizePolicy(sizePolicy)
self.colour_comboBox.setMinimumSize(QtCore.QSize(143, 2))
self.colour_comboBox.setMaximumSize(QtCore.QSize(16777214, 16777215))
palette = QtGui.QPalette()
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active,
QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Button, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active,
QtGui.QPalette.ButtonText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Base, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Window, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive,
QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Button, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive,
QtGui.QPalette.ButtonText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Base, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Window, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled,
QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Button, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled,
QtGui.QPalette.ButtonText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Base, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Window, brush)
self.colour_comboBox.setPalette(palette)
font = QtGui.QFont()
font.setFamily("8514oem")
font.setPointSize(16)
font.setBold(False)
font.setItalic(False)
font.setWeight(50)
self.colour_comboBox.setFont(font)
self.colour_comboBox.setCursor(
QtGui.QCursor(QtCore.Qt.PointingHandCursor))
self.colour_comboBox.setStyleSheet("QComboBox {\n"
" border: 1px solid gray;\n"
" border-radius: 10px;\n"
" padding: 1px 18px 1px 3px;\n"
" min-width: 6em;\n"
" font: 16pt \"8514oem\";\n"
" background-color: rgb(255, 255, 255);\n"
" \n"
" color: rgb(0, 0, 0);\n"
"}\n"
"\n"
"QComboBox:on { /* shift the text when the popup opens */\n"
" padding-top: 3px;\n"
" padding-left: 4px;\n"
" background: white;\n"
" border-radius: 10px;\n"
"}\n"
"\n"
"QComboBox::drop-down {\n"
" subcontrol-origin: padding;\n"
" subcontrol-position: top right;\n"
" width: 15px;\n"
" background-color:white;\n"
" border-left-width: 1px;\n"
" border-left-color: darkgray;\n"
" border-left-style: solid; /* just a single line */\n"
" border-top-right-radius: 3px; /* same radius as the QComboBox */\n"
" border-bottom-right-radius: 3px;\n"
" border-radius: 10px;\n"
"}\n"
"\n"
"QComboBox::down-arrow:on { /* shift the arrow when popup is open */\n"
" top: 1px;\n"
" left: 1px;\n"
"}\n"
"QListView\n"
"{\n"
"background-color : #334155;\n"
"color: rgb(255, 255, 255);\n"
"}")
self.colour_comboBox.setEditable(False)
self.colour_comboBox.setFrame(True)
self.colour_comboBox.setObjectName("colour_comboBox")
self.colour_comboBox.addItem("")
self.colour_comboBox.addItem("")
self.colour_comboBox.addItem("")
self.colour_comboBox.addItem("")
self.colour_comboBox.addItem("")
self.colour_comboBox.addItem("")
self.Colour_label = QtWidgets.QLineEdit(self.page_2)
self.Colour_label.setGeometry(QtCore.QRect(630, 10, 131, 22))
font = QtGui.QFont()
font.setFamily("8514oem")
font.setPointSize(16)
self.Colour_label.setFont(font)
self.Colour_label.setStyleSheet("color: rgb(255, 255, 255);\n"
"background-color: rgba(255, 255, 255, 0);")
self.Colour_label.setFrame(False)
self.Colour_label.setObjectName("Colour_label")
self.production_year_comboBox = QtWidgets.QComboBox(self.page_2)
self.production_year_comboBox.setGeometry(
QtCore.QRect(630, 240, 519, 51))
sizePolicy = QtWidgets.QSizePolicy(
QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Minimum)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.production_year_comboBox.sizePolicy().hasHeightForWidth())
self.production_year_comboBox.setSizePolicy(sizePolicy)
self.production_year_comboBox.setMinimumSize(QtCore.QSize(143, 2))
self.production_year_comboBox.setMaximumSize(
QtCore.QSize(16777214, 16777215))
palette = QtGui.QPalette()
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active,
QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Button, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active,
QtGui.QPalette.ButtonText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Base, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Window, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive,
QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Button, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive,
QtGui.QPalette.ButtonText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Base, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Window, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled,
QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Button, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled,
QtGui.QPalette.ButtonText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Base, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Window, brush)
self.production_year_comboBox.setPalette(palette)
font = QtGui.QFont()
font.setFamily("8514oem")
font.setPointSize(16)
font.setBold(False)
font.setItalic(False)
font.setWeight(50)
self.production_year_comboBox.setFont(font)
self.production_year_comboBox.setCursor(
QtGui.QCursor(QtCore.Qt.PointingHandCursor))
self.production_year_comboBox.setStyleSheet("QComboBox {\n"
" border: 1px solid gray;\n"
" border-radius: 10px;\n"
" padding: 1px 18px 1px 3px;\n"
" min-width: 6em;\n"
" font: 16pt \"8514oem\";\n"
" background-color: rgb(255, 255, 255);\n"
" \n"
" color: rgb(0, 0, 0);\n"
"}\n"
"\n"
"QComboBox:on { /* shift the text when the popup opens */\n"
" padding-top: 3px;\n"
" padding-left: 4px;\n"
" background: white;\n"
" border-radius: 10px;\n"
"}\n"
"\n"
"QComboBox::drop-down {\n"
" subcontrol-origin: padding;\n"
" subcontrol-position: top right;\n"
" width: 15px;\n"
" background-color:white;\n"
" border-left-width: 1px;\n"
" border-left-color: darkgray;\n"
" border-left-style: solid; /* just a single line */\n"
" border-top-right-radius: 3px; /* same radius as the QComboBox */\n"
" border-bottom-right-radius: 3px;\n"
" border-radius: 10px;\n"
"}\n"
"\n"
"QComboBox::down-arrow:on { /* shift the arrow when popup is open */\n"
" top: 1px;\n"
" left: 1px;\n"
"}\n"
"QListView\n"
"{\n"
"background-color : #334155;\n"
"color: rgb(255, 255, 255);\n"
"}")
self.production_year_comboBox.setEditable(False)
self.production_year_comboBox.setFrame(True)
self.production_year_comboBox.setObjectName("production_year_comboBox")
self.production_year_comboBox.addItem("")
self.production_year_comboBox.addItem("")
self.production_year_comboBox.addItem("")
self.production_year_comboBox.addItem("")
self.production_year_comboBox.addItem("")
self.production_year_comboBox.addItem("")
self.production_year_comboBox.addItem("")
self.Power_supply_label = QtWidgets.QLineEdit(self.page_2)
self.Power_supply_label.setGeometry(QtCore.QRect(1250, 10, 151, 22))
font = QtGui.QFont()
font.setFamily("8514oem")
font.setPointSize(16)
self.Power_supply_label.setFont(font)
self.Power_supply_label.setStyleSheet("color: rgb(255, 255, 255);\n"
"background-color: rgba(255, 255, 255, 0);")
self.Power_supply_label.setFrame(False)
self.Power_supply_label.setObjectName("Power_supply_label")
self.power_supply_comboBox = QtWidgets.QComboBox(self.page_2)
self.power_supply_comboBox.setGeometry(QtCore.QRect(1250, 37, 519, 51))
sizePolicy = QtWidgets.QSizePolicy(
QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Minimum)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.power_supply_comboBox.sizePolicy().hasHeightForWidth())
self.power_supply_comboBox.setSizePolicy(sizePolicy)
self.power_supply_comboBox.setMinimumSize(QtCore.QSize(143, 2))
self.power_supply_comboBox.setMaximumSize(
QtCore.QSize(16777214, 16777215))
palette = QtGui.QPalette()
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active,
QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Button, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active,
QtGui.QPalette.ButtonText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Base, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Window, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive,
QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Button, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive,
QtGui.QPalette.ButtonText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Base, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Window, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled,
QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Button, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled,
QtGui.QPalette.ButtonText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Base, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Window, brush)
self.power_supply_comboBox.setPalette(palette)
font = QtGui.QFont()
font.setFamily("8514oem")
font.setPointSize(16)
font.setBold(False)
font.setItalic(False)
font.setWeight(50)
self.power_supply_comboBox.setFont(font)
self.power_supply_comboBox.setCursor(
QtGui.QCursor(QtCore.Qt.PointingHandCursor))
self.power_supply_comboBox.setStyleSheet("QComboBox {\n"
" border: 1px solid gray;\n"
" border-radius: 10px;\n"
" padding: 1px 18px 1px 3px;\n"
" min-width: 6em;\n"
" font: 16pt \"8514oem\";\n"
" background-color: rgb(255, 255, 255);\n"
" \n"
" color: rgb(0, 0, 0);\n"
"}\n"
"\n"
"QComboBox:on { /* shift the text when the popup opens */\n"
" padding-top: 3px;\n"
" padding-left: 4px;\n"
" background: white;\n"
" border-radius: 10px;\n"
"}\n"
"\n"
"QComboBox::drop-down {\n"
" subcontrol-origin: padding;\n"
" subcontrol-position: top right;\n"
" width: 15px;\n"
" background-color:white;\n"
" border-left-width: 1px;\n"
" border-left-color: darkgray;\n"
" border-left-style: solid; /* just a single line */\n"
" border-top-right-radius: 3px; /* same radius as the QComboBox */\n"
" border-bottom-right-radius: 3px;\n"
" border-radius: 10px;\n"
"}\n"
"\n"
"QComboBox::down-arrow:on { /* shift the arrow when popup is open */\n"
" top: 1px;\n"
" left: 1px;\n"
"}\n"
"QListView\n"
"{\n"
"background-color : #334155;\n"
"color: rgb(255, 255, 255);\n"
"}")
self.power_supply_comboBox.setEditable(False)
self.power_supply_comboBox.setFrame(True)
self.power_supply_comboBox.setObjectName("power_supply_comboBox")
self.power_supply_comboBox.addItem("")
self.power_supply_comboBox.addItem("")
self.power_supply_comboBox.addItem("")
self.Warranty_label = QtWidgets.QLineEdit(self.page_2)
self.Warranty_label.setGeometry(QtCore.QRect(1250, 113, 131, 22))
font = QtGui.QFont()
font.setFamily("8514oem")
font.setPointSize(16)
self.Warranty_label.setFont(font)
self.Warranty_label.setStyleSheet("color: rgb(255, 255, 255);\n"
"background-color: rgba(255, 255, 255, 0);")
self.Warranty_label.setFrame(False)
self.Warranty_label.setObjectName("Warranty_label")
self.warranty_comboBox = QtWidgets.QComboBox(self.page_2)
self.warranty_comboBox.setGeometry(QtCore.QRect(1250, 140, 519, 51))
sizePolicy = QtWidgets.QSizePolicy(
QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Minimum)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.warranty_comboBox.sizePolicy().hasHeightForWidth())
self.warranty_comboBox.setSizePolicy(sizePolicy)
self.warranty_comboBox.setMinimumSize(QtCore.QSize(143, 2))
self.warranty_comboBox.setMaximumSize(QtCore.QSize(16777214, 16777215))
palette = QtGui.QPalette()
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active,
QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Button, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active,
QtGui.QPalette.ButtonText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Base, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Window, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive,
QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Button, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive,
QtGui.QPalette.ButtonText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Base, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Window, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled,
QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Button, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled,
QtGui.QPalette.ButtonText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Base, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Window, brush)
self.warranty_comboBox.setPalette(palette)
font = QtGui.QFont()
font.setFamily("8514oem")
font.setPointSize(16)
font.setBold(False)
font.setItalic(False)
font.setWeight(50)
self.warranty_comboBox.setFont(font)
self.warranty_comboBox.setCursor(
QtGui.QCursor(QtCore.Qt.PointingHandCursor))
self.warranty_comboBox.setStyleSheet("QComboBox {\n"
" border: 1px solid gray;\n"
" border-radius: 10px;\n"
" padding: 1px 18px 1px 3px;\n"
" min-width: 6em;\n"
" font: 16pt \"8514oem\";\n"
" background-color: rgb(255, 255, 255);\n"
" \n"
" color: rgb(0, 0, 0);\n"
"}\n"
"\n"
"QComboBox:on { /* shift the text when the popup opens */\n"
" padding-top: 3px;\n"
" padding-left: 4px;\n"
" background: white;\n"
" border-radius: 10px;\n"
"}\n"
"\n"
"QComboBox::drop-down {\n"
" subcontrol-origin: padding;\n"
" subcontrol-position: top right;\n"
" width: 15px;\n"
" background-color:white;\n"
" border-left-width: 1px;\n"
" border-left-color: darkgray;\n"
" border-left-style: solid; /* just a single line */\n"
" border-top-right-radius: 3px; /* same radius as the QComboBox */\n"
" border-bottom-right-radius: 3px;\n"
" border-radius: 10px;\n"
"}\n"
"\n"
"QComboBox::down-arrow:on { /* shift the arrow when popup is open */\n"
" top: 1px;\n"
" left: 1px;\n"
"}\n"
"QListView\n"
"{\n"
"background-color : #334155;\n"
"color: rgb(255, 255, 255);\n"
"}")
self.warranty_comboBox.setEditable(False)
self.warranty_comboBox.setFrame(True)
self.warranty_comboBox.setObjectName("warranty_comboBox")
self.warranty_comboBox.addItem("")
self.warranty_comboBox.addItem("")
self.warranty_comboBox.addItem("")
self.warranty_comboBox.addItem("")
self.warranty_comboBox.addItem("")
self.category_div = QtWidgets.QLabel(self.page_2)
self.category_div.setGeometry(QtCore.QRect(10, 340, 421, 541))
self.category_div.setStyleSheet("QWidget { \n"
"background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 #6D28D9 , stop:1 #4F46E5);\n"
"/**image: url(:/Choose_Item_div/light-bulb.png);*/\n"
"/**image: url(:/Choose_Item_div/padlock.png);*/\n"
"image: url(:/Choose_Item_div/box.png);\n"
"border-radius: 20px;\n"
"}")
self.category_div.setText("")
self.category_div.setObjectName("category_div")
self.price_div = QtWidgets.QLabel(self.page_2)
self.price_div.setGeometry(QtCore.QRect(460, 340, 971, 50))
self.price_div.setStyleSheet("background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 #6D28D9 , stop:1 #4F46E5);\n"
"border-radius: 20px;")
self.price_div.setText("")
self.price_div.setObjectName("price_div")
self.warranty_div = QtWidgets.QLabel(self.page_2)
self.warranty_div.setGeometry(QtCore.QRect(460, 420, 971, 50))
self.warranty_div.setStyleSheet("background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 #6D28D9 , stop:1 #4F46E5);\n"
"border-radius: 20px;")
self.warranty_div.setText("")
self.warranty_div.setObjectName("warranty_div")
self.model_div = QtWidgets.QLabel(self.page_2)
self.model_div.setGeometry(QtCore.QRect(460, 500, 971, 50))
self.model_div.setStyleSheet("background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 #6D28D9 , stop:1 #4F46E5);\n"
"border-radius: 20px;")
self.model_div.setText("")
self.model_div.setObjectName("model_div")
self.cost_div = QtWidgets.QLabel(self.page_2)
self.cost_div.setGeometry(QtCore.QRect(460, 580, 971, 50))
self.cost_div.setStyleSheet("background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 #6D28D9 , stop:1 #4F46E5);\n"
"border-radius: 20px;")
self.cost_div.setText("")
self.cost_div.setObjectName("cost_div")
self.inventory_div = QtWidgets.QLabel(self.page_2)
self.inventory_div.setGeometry(QtCore.QRect(1460, 340, 301, 241))
self.inventory_div.setStyleSheet("background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 #F59E0B, stop:1#E11D48);\n"
"border-radius: 20px;")
self.inventory_div.setText("")
self.inventory_div.setObjectName("inventory_div")
self.sold_items_div = QtWidgets.QLabel(self.page_2)
self.sold_items_div.setGeometry(QtCore.QRect(1460, 630, 301, 241))
self.sold_items_div.setStyleSheet("background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 #F59E0B, stop:1#E11D48);\n"
"border-radius: 20px;")
self.sold_items_div.setText("")
self.sold_items_div.setObjectName("sold_items_div")
self.category_amount_label = QtWidgets.QLabel(self.page_2)
self.category_amount_label.setGeometry(QtCore.QRect(20, 770, 401, 81))
font = QtGui.QFont()
font.setFamily("Segoe UI")
font.setPointSize(18)
font.setBold(False)
font.setItalic(True)
font.setWeight(9)
self.category_amount_label.setFont(font)
self.category_amount_label.setStyleSheet("background-color: transparent;\n"
"color: rgb(255, 255, 255);\n"
"font: 75 italic 18pt \"Segoe UI\";")
self.category_amount_label.setAlignment(QtCore.Qt.AlignCenter)
self.category_amount_label.setObjectName("category_amount_label")
self.choose_an_item_label = QtWidgets.QLabel(self.page_2)
self.choose_an_item_label.setGeometry(QtCore.QRect(20, 360, 411, 81))
font = QtGui.QFont()
font.setFamily("Yu Gothic UI")
font.setPointSize(20)
font.setBold(False)
font.setItalic(False)
font.setWeight(50)
self.choose_an_item_label.setFont(font)
self.choose_an_item_label.setStyleSheet("background-color: transparent;\n"
"color: rgb(255, 255, 255);\n"
"font: 20pt \"Yu Gothic UI\";")
self.choose_an_item_label.setAlignment(QtCore.Qt.AlignCenter)
self.choose_an_item_label.setObjectName("choose_an_item_label")
self.inventory_level_label = QtWidgets.QLabel(self.page_2)
self.inventory_level_label.setGeometry(
QtCore.QRect(1460, 350, 301, 81))
font = QtGui.QFont()
font.setFamily("Yu Gothic UI")
font.setPointSize(14)
font.setBold(False)
font.setItalic(False)
font.setWeight(50)
self.inventory_level_label.setFont(font)
self.inventory_level_label.setStyleSheet("background-color: transparent;\n"
"color: rgb(255, 255, 255);\n"
"font: 14pt \"Yu Gothic UI\";")
self.inventory_level_label.setAlignment(QtCore.Qt.AlignCenter)
self.inventory_level_label.setObjectName("inventory_level_label")
self.sold_items_label = QtWidgets.QLabel(self.page_2)
self.sold_items_label.setGeometry(QtCore.QRect(1460, 630, 301, 81))
font = QtGui.QFont()
font.setFamily("Yu Gothic UI")
font.setPointSize(14)
font.setBold(False)
font.setItalic(False)
font.setWeight(50)
self.sold_items_label.setFont(font)
self.sold_items_label.setStyleSheet("background-color: transparent;\n"
"color: rgb(255, 255, 255);\n"
"font: 14pt \"Yu Gothic UI\";")
self.sold_items_label.setAlignment(QtCore.Qt.AlignCenter)
self.sold_items_label.setObjectName("sold_items_label")
self.price_label = QtWidgets.QLabel(self.page_2)
self.price_label.setGeometry(QtCore.QRect(400, 350, 241, 31))
font = QtGui.QFont()
font.setFamily("Yu Gothic UI")
font.setPointSize(12)
font.setBold(False)
font.setItalic(False)
font.setWeight(50)
self.price_label.setFont(font)
self.price_label.setStyleSheet("background-color: transparent;\n"
"color: rgb(255, 255, 255);\n"
"font: 12pt \"Yu Gothic UI\";")
self.price_label.setAlignment(QtCore.Qt.AlignCenter)
self.price_label.setObjectName("price_label")
self.warranty_label = QtWidgets.QLabel(self.page_2)
self.warranty_label.setGeometry(QtCore.QRect(420, 420, 241, 51))
font = QtGui.QFont()
font.setFamily("Yu Gothic UI")
font.setPointSize(12)
font.setBold(False)
font.setItalic(False)
font.setWeight(50)
self.warranty_label.setFont(font)
self.warranty_label.setStyleSheet("background-color: transparent;\n"
"color: rgb(255, 255, 255);\n"
"font: 12pt \"Yu Gothic UI\";")
self.warranty_label.setAlignment(QtCore.Qt.AlignCenter)
self.warranty_label.setObjectName("warranty_label")
self.model_label = QtWidgets.QLabel(self.page_2)
self.model_label.setGeometry(QtCore.QRect(410, 500, 241, 51))
font = QtGui.QFont()
font.setFamily("Yu Gothic UI")
font.setPointSize(12)
font.setBold(False)
font.setItalic(False)
font.setWeight(50)
self.model_label.setFont(font)
self.model_label.setStyleSheet("background-color: transparent;\n"
"color: rgb(255, 255, 255);\n"
"font: 12pt \"Yu Gothic UI\";")
self.model_label.setAlignment(QtCore.Qt.AlignCenter)
self.model_label.setObjectName("model_label")
self.cost_label = QtWidgets.QLabel(self.page_2)
self.cost_label.setGeometry(QtCore.QRect(400, 580, 241, 51))
font = QtGui.QFont()
font.setFamily("Yu Gothic UI")
font.setPointSize(12)
font.setBold(False)
font.setItalic(False)
font.setWeight(50)
self.cost_label.setFont(font)
self.cost_label.setStyleSheet("background-color: transparent;\n"
"color: rgb(255, 255, 255);\n"
"font: 12pt \"Yu Gothic UI\";")
self.cost_label.setAlignment(QtCore.Qt.AlignCenter)
self.cost_label.setObjectName("cost_label")
self.price_amount_label = QtWidgets.QLabel(self.page_2)
self.price_amount_label.setGeometry(QtCore.QRect(1180, 340, 241, 51))
font = QtGui.QFont()
font.setFamily("Yu Gothic UI")
font.setPointSize(12)
font.setBold(False)
font.setItalic(True)
font.setWeight(50)
self.price_amount_label.setFont(font)
self.price_amount_label.setStyleSheet("background-color: transparent;\n"
"color: rgb(255, 255, 255);\n"
"font: italic 12pt \"Yu Gothic UI\";")
self.price_amount_label.setAlignment(QtCore.Qt.AlignCenter)
self.price_amount_label.setObjectName("price_amount_label")
self.warranty_amount_label = QtWidgets.QLabel(self.page_2)
self.warranty_amount_label.setGeometry(
QtCore.QRect(1180, 420, 241, 51))
font = QtGui.QFont()
font.setFamily("Yu Gothic UI")
font.setPointSize(12)
font.setBold(False)
font.setItalic(True)
font.setWeight(50)
self.warranty_amount_label.setFont(font)
self.warranty_amount_label.setStyleSheet("background-color: transparent;\n"
"color: rgb(255, 255, 255);\n"
"font: italic 12pt \"Yu Gothic UI\";")
self.warranty_amount_label.setAlignment(QtCore.Qt.AlignCenter)
self.warranty_amount_label.setObjectName("warranty_amount_label")
self.model_amount_label = QtWidgets.QLabel(self.page_2)
self.model_amount_label.setGeometry(QtCore.QRect(1180, 500, 241, 51))
font = QtGui.QFont()
font.setFamily("Yu Gothic UI")
font.setPointSize(12)
font.setBold(False)
font.setItalic(True)
font.setWeight(50)
self.model_amount_label.setFont(font)
self.model_amount_label.setStyleSheet("background-color: transparent;\n"
"color: rgb(255, 255, 255);\n"
"font: italic 12pt \"Yu Gothic UI\";")
self.model_amount_label.setAlignment(QtCore.Qt.AlignCenter)
self.model_amount_label.setObjectName("model_amount_label")
self.cost_amount_label = QtWidgets.QLabel(self.page_2)
self.cost_amount_label.setGeometry(QtCore.QRect(1180, 580, 241, 51))
font = QtGui.QFont()
font.setFamily("Yu Gothic UI")
font.setPointSize(12)
font.setBold(False)
font.setItalic(True)
font.setWeight(50)
self.cost_amount_label.setFont(font)
self.cost_amount_label.setStyleSheet("background-color: transparent;\n"
"color: rgb(255, 255, 255);\n"
"font: italic 12pt \"Yu Gothic UI\";")
self.cost_amount_label.setAlignment(QtCore.Qt.AlignCenter)
self.cost_amount_label.setObjectName("cost_amount_label")
self.inventory_amount_label = QtWidgets.QLabel(self.page_2)
self.inventory_amount_label.setGeometry(
QtCore.QRect(1460, 490, 301, 81))
font = QtGui.QFont()
font.setFamily("Yu Gothic UI")
font.setPointSize(16)
font.setBold(False)
font.setItalic(True)
font.setWeight(50)
self.inventory_amount_label.setFont(font)
self.inventory_amount_label.setStyleSheet("background-color: transparent;\n"
"color: rgb(255, 255, 255);\n"
"font: italic 16pt \"Yu Gothic UI\";")
self.inventory_amount_label.setAlignment(QtCore.Qt.AlignCenter)
self.inventory_amount_label.setObjectName("inventory_amount_label")
self.sold_items_amount_label = QtWidgets.QLabel(self.page_2)
self.sold_items_amount_label.setGeometry(
QtCore.QRect(1460, 780, 301, 91))
font = QtGui.QFont()
font.setFamily("Yu Gothic UI")
font.setPointSize(16)
font.setBold(False)
font.setItalic(True)
font.setWeight(50)
self.sold_items_amount_label.setFont(font)
self.sold_items_amount_label.setStyleSheet("background-color: transparent;\n"
"color: rgb(255, 255, 255);\n"
"font: italic 16pt \"Yu Gothic UI\";")
self.sold_items_amount_label.setAlignment(QtCore.Qt.AlignCenter)
self.sold_items_amount_label.setObjectName("sold_items_amount_label")
self.color_div = QtWidgets.QLabel(self.page_2)
self.color_div.setGeometry(QtCore.QRect(460, 660, 971, 50))
self.color_div.setStyleSheet("background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 #6D28D9 , stop:1 #4F46E5);\n"
"border-radius: 20px;")
self.color_div.setText("")
self.color_div.setObjectName("color_div")
self.production_year_div = QtWidgets.QLabel(self.page_2)
self.production_year_div.setGeometry(QtCore.QRect(460, 740, 971, 50))
self.production_year_div.setStyleSheet("background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 #6D28D9 , stop:1 #4F46E5);\n"
"border-radius: 20px;")
self.production_year_div.setText("")
self.production_year_div.setObjectName("production_year_div")
self.power_supply_div = QtWidgets.QLabel(self.page_2)
self.power_supply_div.setGeometry(QtCore.QRect(460, 820, 971, 50))
self.power_supply_div.setStyleSheet("background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 #6D28D9 , stop:1 #4F46E5);\n"
"border-radius: 20px;")
self.power_supply_div.setText("")
self.power_supply_div.setObjectName("power_supply_div")
self.color_label = QtWidgets.QLabel(self.page_2)
self.color_label.setGeometry(QtCore.QRect(400, 660, 241, 51))
font = QtGui.QFont()
font.setFamily("Yu Gothic UI")
font.setPointSize(12)
font.setBold(False)
font.setItalic(False)
font.setWeight(50)
self.color_label.setFont(font)
self.color_label.setStyleSheet("background-color: transparent;\n"
"color: rgb(255, 255, 255);\n"
"font: 12pt \"Yu Gothic UI\";")
self.color_label.setAlignment(QtCore.Qt.AlignCenter)
self.color_label.setObjectName("color_label")
self.product_year_label = QtWidgets.QLabel(self.page_2)
self.product_year_label.setGeometry(QtCore.QRect(460, 740, 241, 51))
font = QtGui.QFont()
font.setFamily("Yu Gothic UI")
font.setPointSize(12)
font.setBold(False)
font.setItalic(False)
font.setWeight(50)
self.product_year_label.setFont(font)
self.product_year_label.setStyleSheet("background-color: transparent;\n"
"color: rgb(255, 255, 255);\n"
"font: 12pt \"Yu Gothic UI\";")
self.product_year_label.setAlignment(QtCore.Qt.AlignCenter)
self.product_year_label.setObjectName("product_year_label")
self.power_supply_label = QtWidgets.QLabel(self.page_2)
self.power_supply_label.setGeometry(QtCore.QRect(450, 820, 241, 51))
font = QtGui.QFont()
font.setFamily("Yu Gothic UI")
font.setPointSize(12)
font.setBold(False)
font.setItalic(False)
font.setWeight(50)
self.power_supply_label.setFont(font)
self.power_supply_label.setStyleSheet("background-color: transparent;\n"
"color: rgb(255, 255, 255);\n"
"font: 12pt \"Yu Gothic UI\";")
self.power_supply_label.setAlignment(QtCore.Qt.AlignCenter)
self.power_supply_label.setObjectName("power_supply_label")
self.color_amount_label = QtWidgets.QLabel(self.page_2)
self.color_amount_label.setGeometry(QtCore.QRect(1180, 660, 241, 51))
font = QtGui.QFont()
font.setFamily("Yu Gothic UI")
font.setPointSize(12)
font.setBold(False)
font.setItalic(True)
font.setWeight(50)
self.color_amount_label.setFont(font)
self.color_amount_label.setStyleSheet("background-color: transparent;\n"
"color: rgb(255, 255, 255);\n"
"font: italic 12pt \"Yu Gothic UI\";")
self.color_amount_label.setAlignment(QtCore.Qt.AlignCenter)
self.color_amount_label.setObjectName("color_amount_label")
self.producti_year_amount_label = QtWidgets.QLabel(self.page_2)
self.producti_year_amount_label.setGeometry(
QtCore.QRect(1180, 740, 241, 51))
font = QtGui.QFont()
font.setFamily("Yu Gothic UI")
font.setPointSize(12)
font.setBold(False)
font.setItalic(True)
font.setWeight(50)
self.producti_year_amount_label.setFont(font)
self.producti_year_amount_label.setStyleSheet("background-color: transparent;\n"
"color: rgb(255, 255, 255);\n"
"font: italic 12pt \"Yu Gothic UI\";")
self.producti_year_amount_label.setAlignment(QtCore.Qt.AlignCenter)
self.producti_year_amount_label.setObjectName(
"producti_year_amount_label")
self.power_supply_amount_label = QtWidgets.QLabel(self.page_2)
self.power_supply_amount_label.setGeometry(
QtCore.QRect(1180, 820, 241, 51))
font = QtGui.QFont()
font.setFamily("Yu Gothic UI")
font.setPointSize(12)
font.setBold(False)
font.setItalic(True)
font.setWeight(50)
self.power_supply_amount_label.setFont(font)
self.power_supply_amount_label.setStyleSheet("background-color: transparent;\n"
"color: rgb(255, 255, 255);\n"
"font: italic 12pt \"Yu Gothic UI\";")
self.power_supply_amount_label.setAlignment(QtCore.Qt.AlignCenter)
self.power_supply_amount_label.setObjectName(
"power_supply_amount_label")
self.gradient_backdrop.raise_()
self.submit_query.raise_()
self.Categories_label.raise_()
self.category_comboBox.raise_()
self.Model_label.raise_()
self.Price_label.raise_()
self.model_comboBox.raise_()
self.price_comboBox.raise_()
self.factory_comboBox.raise_()
self.Factory_label.raise_()
self.production_year_label.raise_()
self.colour_comboBox.raise_()
self.Colour_label.raise_()
self.production_year_comboBox.raise_()
self.Power_supply_label.raise_()
self.power_supply_comboBox.raise_()
self.Warranty_label.raise_()
self.warranty_comboBox.raise_()
self.category_div.raise_()
self.price_div.raise_()
self.warranty_div.raise_()
self.model_div.raise_()
self.cost_div.raise_()
self.inventory_div.raise_()
self.sold_items_div.raise_()
self.category_amount_label.raise_()
self.choose_an_item_label.raise_()
self.inventory_level_label.raise_()
self.sold_items_label.raise_()
self.price_label.raise_()
self.warranty_label.raise_()
self.model_label.raise_()
self.cost_label.raise_()
self.price_amount_label.raise_()
self.warranty_amount_label.raise_()
self.model_amount_label.raise_()
self.cost_amount_label.raise_()
self.inventory_amount_label.raise_()
self.sold_items_amount_label.raise_()
self.color_div.raise_()
self.production_year_div.raise_()
self.power_supply_div.raise_()
self.color_label.raise_()
self.product_year_label.raise_()
self.power_supply_label.raise_()
self.color_amount_label.raise_()
self.producti_year_amount_label.raise_()
self.power_supply_amount_label.raise_()
self.stackedWidget.addWidget(self.page_2)
self.page_3 = QtWidgets.QWidget()
self.page_3.setObjectName("page_3")
self.item_search_label = QtWidgets.QLabel(self.page_3)
self.item_search_label.setGeometry(QtCore.QRect(690, 0, 401, 91))
font = QtGui.QFont()
font.setFamily("8514oem")
font.setPointSize(25)
self.item_search_label.setFont(font)
self.item_search_label.setStyleSheet("color: rgb(255, 255, 255);\n"
"image: url(:/adminSideBar/icons8-product-management-48.png);\n"
"padding-right:50px;")
self.item_search_label.setAlignment(
QtCore.Qt.AlignRight | QtCore.Qt.AlignTrailing | QtCore.Qt.AlignVCenter)
self.item_search_label.setObjectName("item_search_label")
self.item_table = QtWidgets.QTableWidget(self.page_3)
self.item_table.setGeometry(QtCore.QRect(20, 325, 1761, 561))
self.item_table.setSizeIncrement(QtCore.QSize(0, 0))
font = QtGui.QFont()
font.setFamily("8514oem")
font.setPointSize(10)
font.setBold(False)
font.setItalic(False)
font.setWeight(50)
self.item_table.setFont(font)
self.item_table.setLayoutDirection(QtCore.Qt.LeftToRight)
self.item_table.setAutoFillBackground(False)
self.item_table.setStyleSheet("QWidget {\n"
" background-color: rgb(255, 255, 255);\n"
" alternate-background-color: rgb(241, 245, 249);\n"
" font: 10pt \"8514oem\";\n"
"}\n"
"QScrollBar:vertical {\n"
" border: none;\n"
" background: #94A3B8;\n"
" width: 14px;\n"
" margin: 15px 0 15px 0;\n"
" border-radius: 0px;\n"
" }\n"
"\n"
"/* HANDLE BAR VERTICAL */\n"
"QScrollBar::handle:vertical { \n"
" background-color: #E5E7EB;\n"
" min-height: 30px;\n"
" border-radius: 7px;\n"
"}\n"
"QScrollBar::handle:vertical:hover{ \n"
" background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 #6366F1, stop:1 #7C3AED);\n"
"}\n"
"QScrollBar::handle:vertical:pressed { \n"
" background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 #4338CA, stop:1 #5B21B6);\n"
"}\n"
"\n"
"/* BTN TOP - SCROLLBAR */\n"
"QScrollBar::sub-line:vertical {\n"
" border: none;\n"
" background-color: #94A3B8;\n"
" height: 15px;\n"
" border-top-left-radius: 7px;\n"
" border-top-right-radius: 7px;\n"
" subcontrol-position: top;\n"
" subcontrol-origin: margin;\n"
"}\n"
"QScrollBar::sub-line:vertical:hover { \n"
" background-color: rgb(255, 0, 127);\n"
"}\n"
"QScrollBar::sub-line:vertical:pressed { \n"
" background-color: rgb(185, 0, 92);\n"
"}\n"
"\n"
"/* BTN BOTTOM - SCROLLBAR */\n"
"QScrollBar::add-line:vertical {\n"
" border: none;\n"
" background-color:#94A3B8;\n"
" height: 15px;\n"
" border-bottom-left-radius: 7px;\n"
" border-bottom-right-radius: 7px;\n"
" subcontrol-position: bottom;\n"
" subcontrol-origin: margin;\n"
"}\n"
"QScrollBar::add-line:vertical:hover { \n"
" background-color: rgb(255, 0, 127);\n"
"}\n"
"QScrollBar::add-line:vertical:pressed { \n"
" background-color: rgb(185, 0, 92);\n"
"}\n"
"\n"
"/* RESET ARROW */\n"
"QScrollBar::up-arrow:vertical, QScrollBar::down-arrow:vertical {\n"
" background: none;\n"
"}\n"
"QScrollBar::add-page:vertical, QScrollBar::sub-page:vertical {\n"
" background: none;\n"
"}\n"
"")
self.item_table.setFrameShape(QtWidgets.QFrame.Box)
self.item_table.setFrameShadow(QtWidgets.QFrame.Raised)
self.item_table.setLineWidth(10)
self.item_table.setSizeAdjustPolicy(
QtWidgets.QAbstractScrollArea.AdjustToContents)
self.item_table.setAlternatingRowColors(True)
self.item_table.setSelectionMode(
QtWidgets.QAbstractItemView.SingleSelection)
self.item_table.setSelectionBehavior(
QtWidgets.QAbstractItemView.SelectRows)
self.item_table.setIconSize(QtCore.QSize(0, 0))
self.item_table.setTextElideMode(QtCore.Qt.ElideLeft)
self.item_table.setRowCount(7)
self.item_table.setColumnCount(12)
self.item_table.setObjectName("item_table")
item = QtWidgets.QTableWidgetItem()
self.item_table.setHorizontalHeaderItem(0, item)
item = QtWidgets.QTableWidgetItem()
self.item_table.setHorizontalHeaderItem(1, item)
item = QtWidgets.QTableWidgetItem()
self.item_table.setHorizontalHeaderItem(2, item)
item = QtWidgets.QTableWidgetItem()
self.item_table.setHorizontalHeaderItem(3, item)
item = QtWidgets.QTableWidgetItem()
self.item_table.setHorizontalHeaderItem(4, item)
item = QtWidgets.QTableWidgetItem()
self.item_table.setHorizontalHeaderItem(5, item)
item = QtWidgets.QTableWidgetItem()
self.item_table.setHorizontalHeaderItem(6, item)
item = QtWidgets.QTableWidgetItem()
self.item_table.setHorizontalHeaderItem(7, item)
item = QtWidgets.QTableWidgetItem()
self.item_table.setHorizontalHeaderItem(8, item)
item = QtWidgets.QTableWidgetItem()
self.item_table.setHorizontalHeaderItem(9, item)
item = QtWidgets.QTableWidgetItem()
self.item_table.setHorizontalHeaderItem(10, item)
item = QtWidgets.QTableWidgetItem()
self.item_table.setHorizontalHeaderItem(11, item)
item = QtWidgets.QTableWidgetItem()
self.item_table.setItem(0, 1, item)
item = QtWidgets.QTableWidgetItem()
self.item_table.setItem(6, 6, item)
self.item_table.horizontalHeader().setCascadingSectionResizes(False)
self.item_table.horizontalHeader().setDefaultSectionSize(200)
self.item_table.horizontalHeader().setMinimumSectionSize(26)
self.item_table.horizontalHeader().setStretchLastSection(True)
self.item_table.verticalHeader().setDefaultSectionSize(87)
self.item_table.verticalHeader().setSortIndicatorShown(True)
self.item_table.verticalHeader().setStretchLastSection(False)
self.item_id_comboBox = QtWidgets.QComboBox(self.page_3)
self.item_id_comboBox.setGeometry(QtCore.QRect(20, 250, 519, 51))
sizePolicy = QtWidgets.QSizePolicy(
QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Minimum)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.item_id_comboBox.sizePolicy().hasHeightForWidth())
self.item_id_comboBox.setSizePolicy(sizePolicy)
self.item_id_comboBox.setMinimumSize(QtCore.QSize(143, 2))
self.item_id_comboBox.setMaximumSize(QtCore.QSize(16777214, 16777215))
palette = QtGui.QPalette()
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active,
QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Button, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active,
QtGui.QPalette.ButtonText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Base, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Window, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive,
QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Button, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive,
QtGui.QPalette.ButtonText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Base, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Window, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled,
QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Button, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled,
QtGui.QPalette.ButtonText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Base, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Window, brush)
self.item_id_comboBox.setPalette(palette)
font = QtGui.QFont()
font.setFamily("8514oem")
font.setPointSize(16)
font.setBold(False)
font.setItalic(False)
font.setWeight(50)
self.item_id_comboBox.setFont(font)
self.item_id_comboBox.setCursor(
QtGui.QCursor(QtCore.Qt.PointingHandCursor))
self.item_id_comboBox.setStyleSheet("QComboBox {\n"
" border: 1px solid gray;\n"
" border-radius: 10px;\n"
" padding: 1px 18px 1px 3px;\n"
" min-width: 6em;\n"
" font: 16pt \"8514oem\";\n"
" background-color: rgb(255, 255, 255);\n"
" \n"
" color: rgb(0, 0, 0);\n"
"}\n"
"\n"
"QComboBox:on { /* shift the text when the popup opens */\n"
" padding-top: 3px;\n"
" padding-left: 4px;\n"
" background: white;\n"
" border-radius: 10px;\n"
"}\n"
"\n"
"QComboBox::drop-down {\n"
" subcontrol-origin: padding;\n"
" subcontrol-position: top right;\n"
" width: 15px;\n"
" background-color:white;\n"
" border-left-width: 1px;\n"
" border-left-color: darkgray;\n"
" border-left-style: solid; /* just a single line */\n"
" border-top-right-radius: 3px; /* same radius as the QComboBox */\n"
" border-bottom-right-radius: 3px;\n"
" border-radius: 10px;\n"
"}\n"
"\n"
"QComboBox::down-arrow:on { /* shift the arrow when popup is open */\n"
" top: 1px;\n"
" left: 1px;\n"
"}\n"
"QListView\n"
"{\n"
"background-color : #334155;\n"
"color: rgb(255, 255, 255);\n"
"}")
self.item_id_comboBox.setEditable(True)
self.item_id_comboBox.setCurrentText("")
self.item_id_comboBox.setFrame(True)
self.item_id_comboBox.setObjectName("item_id_comboBox")
self.under_service_comboBox = QtWidgets.QComboBox(self.page_3)
self.under_service_comboBox.setGeometry(QtCore.QRect(20, 100, 519, 51))
sizePolicy = QtWidgets.QSizePolicy(
QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Minimum)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.under_service_comboBox.sizePolicy().hasHeightForWidth())
self.under_service_comboBox.setSizePolicy(sizePolicy)
self.under_service_comboBox.setMinimumSize(QtCore.QSize(143, 2))
self.under_service_comboBox.setMaximumSize(
QtCore.QSize(16777214, 16777215))
palette = QtGui.QPalette()
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active,
QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Button, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active,
QtGui.QPalette.ButtonText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Base, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Window, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive,
QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Button, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive,
QtGui.QPalette.ButtonText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Base, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Window, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled,
QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Button, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled,
QtGui.QPalette.ButtonText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Base, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Window, brush)
self.under_service_comboBox.setPalette(palette)
font = QtGui.QFont()
font.setFamily("8514oem")
font.setPointSize(16)
font.setBold(False)
font.setItalic(False)
font.setWeight(50)
self.under_service_comboBox.setFont(font)
self.under_service_comboBox.setCursor(
QtGui.QCursor(QtCore.Qt.PointingHandCursor))
self.under_service_comboBox.setStyleSheet("QComboBox {\n"
" border: 1px solid gray;\n"
" border-radius: 10px;\n"
" padding: 1px 18px 1px 3px;\n"
" min-width: 6em;\n"
" font: 16pt \"8514oem\";\n"
" background-color: rgb(255, 255, 255);\n"
" \n"
" color: rgb(0, 0, 0);\n"
"}\n"
"\n"
"QComboBox:on { /* shift the text when the popup opens */\n"
" padding-top: 3px;\n"
" padding-left: 4px;\n"
" background: white;\n"
" border-radius: 10px;\n"
"}\n"
"\n"
"QComboBox::drop-down {\n"
" subcontrol-origin: padding;\n"
" subcontrol-position: top right;\n"
" width: 15px;\n"
" background-color:white;\n"
" border-left-width: 1px;\n"
" border-left-color: darkgray;\n"
" border-left-style: solid; /* just a single line */\n"
" border-top-right-radius: 3px; /* same radius as the QComboBox */\n"
" border-bottom-right-radius: 3px;\n"
" border-radius: 10px;\n"
"}\n"
"\n"
"QComboBox::down-arrow:on { /* shift the arrow when popup is open */\n"
" top: 1px;\n"
" left: 1px;\n"
"}\n"
"QListView\n"
"{\n"
"background-color : #334155;\n"
"color: rgb(255, 255, 255);\n"
"}")
self.under_service_comboBox.setEditable(False)
self.under_service_comboBox.setFrame(True)
self.under_service_comboBox.setObjectName("under_service_comboBox")
self.under_service_comboBox.addItem("")
self.under_service_comboBox.addItem("")
self.under_service_label = QtWidgets.QLineEdit(self.page_3)
self.under_service_label.setGeometry(QtCore.QRect(20, 73, 241, 22))
font = QtGui.QFont()
font.setFamily("8514oem")
font.setPointSize(16)
self.under_service_label.setFont(font)
self.under_service_label.setStyleSheet("color: rgb(255, 255, 255);\n"
"background-color: rgba(255, 255, 255, 0);")
self.under_service_label.setFrame(False)
self.under_service_label.setObjectName("under_service_label")
self.item_id_label = QtWidgets.QLineEdit(self.page_3)
self.item_id_label.setGeometry(QtCore.QRect(20, 220, 131, 22))
font = QtGui.QFont()
font.setFamily("8514oem")
font.setPointSize(16)
self.item_id_label.setFont(font)
self.item_id_label.setStyleSheet("color: rgb(255, 255, 255);\n"
"background-color: rgba(255, 255, 255, 0);")
self.item_id_label.setFrame(False)
self.item_id_label.setObjectName("item_id_label")
self.item_search_button = QtWidgets.QPushButton(self.page_3)
self.item_search_button.setGeometry(QtCore.QRect(1470, 250, 301, 51))
font = QtGui.QFont()
font.setPointSize(1)
font.setBold(False)
font.setItalic(False)
font.setWeight(50)
self.item_search_button.setFont(font)
self.item_search_button.setToolTipDuration(0)
self.item_search_button.setStyleSheet("QPushButton {\n"
" border-top-right-radius: 10px;\n"
" border-top-left-radius: 10px;\n"
" border-bottom-right-radius: 10px;\n"
" border-bottom-left-radius: 10px;\n"
" background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 #6366F1, stop:1 #7C3AED);\n"
" font: 22px;\n"
" color: rgb(255, 255, 255);\n"
"}\n"
"\n"
"QPushButton:hover {\n"
" background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 #4338CA\n"
", stop:1 #5B21B6);\n"
"}\n"
"\n"
"QPushButton:pressed {\n"
" background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 #4338CA\n"
", stop:1 #5B21B6);\n"
" padding-left: 5px;\n"
" padding-top: 5px;\n"
"}")
self.item_search_button.setObjectName("item_search_button")
self.stackedWidget.addWidget(self.page_3)
self.page_4 = QtWidgets.QWidget()
self.page_4.setObjectName("page_4")
self.request_table = QtWidgets.QTableWidget(self.page_4)
self.request_table.setGeometry(QtCore.QRect(20, 215, 1761, 671))
self.request_table.setSizeIncrement(QtCore.QSize(0, 0))
font = QtGui.QFont()
font.setFamily("8514oem")
font.setPointSize(10)
font.setBold(False)
font.setItalic(False)
font.setWeight(50)
self.request_table.setFont(font)
self.request_table.setLayoutDirection(QtCore.Qt.LeftToRight)
self.request_table.setAutoFillBackground(False)
self.request_table.setStyleSheet("QWidget {\n"
" background-color: rgb(255, 255, 255);\n"
" alternate-background-color: rgb(241, 245, 249);\n"
" font: 10pt \"8514oem\";\n"
"}\n"
"QScrollBar:vertical {\n"
" border: none;\n"
" background: #94A3B8;\n"
" width: 14px;\n"
" margin: 15px 0 15px 0;\n"
" border-radius: 0px;\n"
" }\n"
"\n"
"/* HANDLE BAR VERTICAL */\n"
"QScrollBar::handle:vertical { \n"
" background-color: #E5E7EB;\n"
" min-height: 30px;\n"
" border-radius: 7px;\n"
"}\n"
"QScrollBar::handle:vertical:hover{ \n"
" background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 #6366F1, stop:1 #7C3AED);\n"
"}\n"
"QScrollBar::handle:vertical:pressed { \n"
" background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 #4338CA, stop:1 #5B21B6);\n"
"}\n"
"\n"
"/* BTN TOP - SCROLLBAR */\n"
"QScrollBar::sub-line:vertical {\n"
" border: none;\n"
" background-color: #94A3B8;\n"
" height: 15px;\n"
" border-top-left-radius: 7px;\n"
" border-top-right-radius: 7px;\n"
" subcontrol-position: top;\n"
" subcontrol-origin: margin;\n"
"}\n"
"QScrollBar::sub-line:vertical:hover { \n"
" background-color: rgb(255, 0, 127);\n"
"}\n"
"QScrollBar::sub-line:vertical:pressed { \n"
" background-color: rgb(185, 0, 92);\n"
"}\n"
"\n"
"/* BTN BOTTOM - SCROLLBAR */\n"
"QScrollBar::add-line:vertical {\n"
" border: none;\n"
" background-color:#94A3B8;\n"
" height: 15px;\n"
" border-bottom-left-radius: 7px;\n"
" border-bottom-right-radius: 7px;\n"
" subcontrol-position: bottom;\n"
" subcontrol-origin: margin;\n"
"}\n"
"QScrollBar::add-line:vertical:hover { \n"
" background-color: rgb(255, 0, 127);\n"
"}\n"
"QScrollBar::add-line:vertical:pressed { \n"
" background-color: rgb(185, 0, 92);\n"
"}\n"
"\n"
"/* RESET ARROW */\n"
"QScrollBar::up-arrow:vertical, QScrollBar::down-arrow:vertical {\n"
" background: none;\n"
"}\n"
"QScrollBar::add-page:vertical, QScrollBar::sub-page:vertical {\n"
" background: none;\n"
"}\n"
"")
self.request_table.setFrameShape(QtWidgets.QFrame.Box)
self.request_table.setFrameShadow(QtWidgets.QFrame.Raised)
self.request_table.setLineWidth(10)
self.request_table.setSizeAdjustPolicy(
QtWidgets.QAbstractScrollArea.AdjustToContents)
self.request_table.setAlternatingRowColors(True)
self.request_table.setSelectionMode(
QtWidgets.QAbstractItemView.SingleSelection)
self.request_table.setSelectionBehavior(
QtWidgets.QAbstractItemView.SelectRows)
self.request_table.setIconSize(QtCore.QSize(0, 0))
self.request_table.setTextElideMode(QtCore.Qt.ElideLeft)
self.request_table.setShowGrid(True)
self.request_table.setRowCount(10)
self.request_table.setColumnCount(7)
self.request_table.setObjectName("request_table")
item = QtWidgets.QTableWidgetItem()
self.request_table.setHorizontalHeaderItem(0, item)
item = QtWidgets.QTableWidgetItem()
self.request_table.setHorizontalHeaderItem(1, item)
item = QtWidgets.QTableWidgetItem()
self.request_table.setHorizontalHeaderItem(2, item)
item = QtWidgets.QTableWidgetItem()
self.request_table.setHorizontalHeaderItem(3, item)
item = QtWidgets.QTableWidgetItem()
self.request_table.setHorizontalHeaderItem(4, item)
item = QtWidgets.QTableWidgetItem()
self.request_table.setHorizontalHeaderItem(5, item)
item = QtWidgets.QTableWidgetItem()
self.request_table.setHorizontalHeaderItem(6, item)
self.request_table.horizontalHeader().setCascadingSectionResizes(False)
self.request_table.horizontalHeader().setDefaultSectionSize(239)
self.request_table.horizontalHeader().setMinimumSectionSize(26)
self.request_table.horizontalHeader().setSortIndicatorShown(True)
self.request_table.horizontalHeader().setStretchLastSection(True)
self.request_table.verticalHeader().setDefaultSectionSize(81)
self.request_table.verticalHeader().setSortIndicatorShown(True)
self.request_table.verticalHeader().setStretchLastSection(False)
self.fetch_requests_button = QtWidgets.QPushButton(self.page_4)
self.fetch_requests_button.setGeometry(QtCore.QRect(20, 150, 301, 51))
font = QtGui.QFont()
font.setPointSize(1)
font.setBold(False)
font.setItalic(False)
font.setWeight(50)
self.fetch_requests_button.setFont(font)
self.fetch_requests_button.setToolTipDuration(0)
self.fetch_requests_button.setStyleSheet("QPushButton {\n"
" border-top-right-radius: 10px;\n"
" border-top-left-radius: 10px;\n"
" border-bottom-right-radius: 10px;\n"
" border-bottom-left-radius: 10px;\n"
" background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 #F59E0B, stop:1#E11D48);\n"
" font: 22px;\n"
" color: rgb(255, 255, 255);\n"
"}\n"
"\n"
"QPushButton:hover {\n"
" background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 #B45309\n"
", stop:1 #9F1239);\n"
"}\n"
"\n"
"QPushButton:pressed {\n"
" background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 #B45309\n"
", stop:1 #9F1239);\n"
" padding-left: 5px;\n"
" padding-top: 5px;\n"
"}")
self.fetch_requests_button.setObjectName("fetch_requests_button")
self.all_requests_label = QtWidgets.QLabel(self.page_4)
self.all_requests_label.setGeometry(QtCore.QRect(670, 0, 411, 91))
font = QtGui.QFont()
font.setFamily("8514oem")
font.setPointSize(25)
self.all_requests_label.setFont(font)
self.all_requests_label.setStyleSheet("color: rgb(255, 255, 255);\n"
"image: url(:/adminSideBar/icons8-attract-customers-48.png);\n"
"padding-right:50px;")
self.all_requests_label.setAlignment(
QtCore.Qt.AlignRight | QtCore.Qt.AlignTrailing | QtCore.Qt.AlignVCenter)
self.all_requests_label.setObjectName("all_requests_label")
self.stackedWidget.addWidget(self.page_4)
self.page_5 = QtWidgets.QWidget()
self.page_5.setObjectName("page_5")
self.my_servicing_label = QtWidgets.QLabel(self.page_5)
self.my_servicing_label.setGeometry(QtCore.QRect(650, 0, 461, 91))
font = QtGui.QFont()
font.setFamily("8514oem")
font.setPointSize(25)
self.my_servicing_label.setFont(font)
self.my_servicing_label.setStyleSheet("color: rgb(255, 255, 255);\n"
"image: url(:/adminSideBar/icons8-service-48.png);\n"
"padding-right:50px;")
self.my_servicing_label.setAlignment(
QtCore.Qt.AlignRight | QtCore.Qt.AlignTrailing | QtCore.Qt.AlignVCenter)
self.my_servicing_label.setObjectName("my_servicing_label")
self.servicing_table = QtWidgets.QTableWidget(self.page_5)
self.servicing_table.setGeometry(QtCore.QRect(20, 215, 1761, 671))
self.servicing_table.setSizeIncrement(QtCore.QSize(0, 0))
font = QtGui.QFont()
font.setFamily("8514oem")
font.setPointSize(10)
font.setBold(False)
font.setItalic(False)
font.setWeight(50)
self.servicing_table.setFont(font)
self.servicing_table.setLayoutDirection(QtCore.Qt.LeftToRight)
self.servicing_table.setAutoFillBackground(False)
self.servicing_table.setStyleSheet("QWidget {\n"
" background-color: rgb(255, 255, 255);\n"
" alternate-background-color: rgb(241, 245, 249);\n"
" font: 10pt \"8514oem\";\n"
"}\n"
"QScrollBar:vertical {\n"
" border: none;\n"
" background: #94A3B8;\n"
" width: 14px;\n"
" margin: 15px 0 15px 0;\n"
" border-radius: 0px;\n"
" }\n"
"\n"
"/* HANDLE BAR VERTICAL */\n"
"QScrollBar::handle:vertical { \n"
" background-color: #E5E7EB;\n"
" min-height: 30px;\n"
" border-radius: 7px;\n"
"}\n"
"QScrollBar::handle:vertical:hover{ \n"
" background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 #6366F1, stop:1 #7C3AED);\n"
"}\n"
"QScrollBar::handle:vertical:pressed { \n"
" background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 #4338CA, stop:1 #5B21B6);\n"
"}\n"
"\n"
"/* BTN TOP - SCROLLBAR */\n"
"QScrollBar::sub-line:vertical {\n"
" border: none;\n"
" background-color: #94A3B8;\n"
" height: 15px;\n"
" border-top-left-radius: 7px;\n"
" border-top-right-radius: 7px;\n"
" subcontrol-position: top;\n"
" subcontrol-origin: margin;\n"
"}\n"
"QScrollBar::sub-line:vertical:hover { \n"
" background-color: rgb(255, 0, 127);\n"
"}\n"
"QScrollBar::sub-line:vertical:pressed { \n"
" background-color: rgb(185, 0, 92);\n"
"}\n"
"\n"
"/* BTN BOTTOM - SCROLLBAR */\n"
"QScrollBar::add-line:vertical {\n"
" border: none;\n"
" background-color:#94A3B8;\n"
" height: 15px;\n"
" border-bottom-left-radius: 7px;\n"
" border-bottom-right-radius: 7px;\n"
" subcontrol-position: bottom;\n"
" subcontrol-origin: margin;\n"
"}\n"
"QScrollBar::add-line:vertical:hover { \n"
" background-color: rgb(255, 0, 127);\n"
"}\n"
"QScrollBar::add-line:vertical:pressed { \n"
" background-color: rgb(185, 0, 92);\n"
"}\n"
"\n"
"/* RESET ARROW */\n"
"QScrollBar::up-arrow:vertical, QScrollBar::down-arrow:vertical {\n"
" background: none;\n"
"}\n"
"QScrollBar::add-page:vertical, QScrollBar::sub-page:vertical {\n"
" background: none;\n"
"}\n"
"")
self.servicing_table.setFrameShape(QtWidgets.QFrame.Box)
self.servicing_table.setFrameShadow(QtWidgets.QFrame.Raised)
self.servicing_table.setLineWidth(10)
self.servicing_table.setSizeAdjustPolicy(
QtWidgets.QAbstractScrollArea.AdjustToContents)
self.servicing_table.setAlternatingRowColors(True)
self.servicing_table.setSelectionMode(
QtWidgets.QAbstractItemView.SingleSelection)
self.servicing_table.setSelectionBehavior(
QtWidgets.QAbstractItemView.SelectRows)
self.servicing_table.setIconSize(QtCore.QSize(0, 0))
self.servicing_table.setTextElideMode(QtCore.Qt.ElideLeft)
self.servicing_table.setRowCount(10)
self.servicing_table.setColumnCount(5)
self.servicing_table.setObjectName("servicing_table")
item = QtWidgets.QTableWidgetItem()
self.servicing_table.setHorizontalHeaderItem(0, item)
item = QtWidgets.QTableWidgetItem()
self.servicing_table.setHorizontalHeaderItem(1, item)
item = QtWidgets.QTableWidgetItem()
self.servicing_table.setHorizontalHeaderItem(2, item)
item = QtWidgets.QTableWidgetItem()
self.servicing_table.setHorizontalHeaderItem(3, item)
item = QtWidgets.QTableWidgetItem()
self.servicing_table.setHorizontalHeaderItem(4, item)
self.servicing_table.horizontalHeader().setCascadingSectionResizes(False)
self.servicing_table.horizontalHeader().setDefaultSectionSize(335)
self.servicing_table.horizontalHeader().setMinimumSectionSize(26)
self.servicing_table.horizontalHeader().setSortIndicatorShown(True)
self.servicing_table.horizontalHeader().setStretchLastSection(False)
self.servicing_table.verticalHeader().setDefaultSectionSize(81)
self.servicing_table.verticalHeader().setSortIndicatorShown(True)
self.servicing_table.verticalHeader().setStretchLastSection(False)
self.refresh_servicing_button = QtWidgets.QPushButton(self.page_5)
self.refresh_servicing_button.setGeometry(
QtCore.QRect(20, 140, 241, 51))
font = QtGui.QFont()
font.setPointSize(1)
font.setBold(False)
font.setItalic(False)
font.setWeight(50)
self.refresh_servicing_button.setFont(font)
self.refresh_servicing_button.setToolTipDuration(0)
self.refresh_servicing_button.setStyleSheet("QPushButton {\n"
" border-top-right-radius: 10px;\n"
" border-top-left-radius: 10px;\n"
" border-bottom-right-radius: 10px;\n"
" border-bottom-left-radius: 10px;\n"
" background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 rgba(45, 212, 191, 1), stop:1 rgba(6, 182, 212, 1));\n"
" font: 22px;\n"
" color: rgb(255, 255, 255);\n"
"}\n"
"\n"
"QPushButton:hover {\n"
" background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 #0F766E\n"
", stop:1 #0E7490);\n"
"}\n"
"\n"
"QPushButton:pressed {\n"
" background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 #0F766E\n"
", stop:1 #0E7490);\n"
" padding-left: 5px;\n"
" padding-top: 5px;\n"
"}")
self.refresh_servicing_button.setObjectName("refresh_servicing_button")
self.stackedWidget.addWidget(self.page_5)
self.verticalLayout_5.addWidget(self.stackedWidget)
self.horizontalLayout_2.addWidget(self.frame_pages)
self.verticalLayout.addWidget(self.Content)
MainWindow.setCentralWidget(self.centralwidget)
self.retranslateUi(MainWindow)
self.stackedWidget.setCurrentIndex(0)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.title.setText(_translate("MainWindow", "Lights & Locks"))
self.btn_page_1.setText(_translate(
"MainWindow", " Home"))
self.btn_page_2.setText(_translate(
"MainWindow", " Products"))
self.btn_page_3.setText(_translate(
"MainWindow", " Items"))
self.btn_page_5.setText(_translate(
"MainWindow", " Requests"))
self.btn_page_6.setText(_translate(
"MainWindow", " Servicing"))
self.btn_page_4.setText(_translate(
"MainWindow", " Exit"))
self.welcome_admin_label.setText(
_translate("MainWindow", "Welcome Admin! "))
self.admin_table.setSortingEnabled(True)
item = self.admin_table.horizontalHeaderItem(0)
item.setText(_translate("MainWindow", "IID"))
item = self.admin_table.horizontalHeaderItem(1)
item.setText(_translate("MainWindow", "Number of \"SOLD\" Items"))
item = self.admin_table.horizontalHeaderItem(2)
item.setText(_translate("MainWindow", "Number of \"UNSOLD\" Items"))
self.refresh_button_admin.setText(_translate(
"MainWindow", "Display Sold && Unsold Items"))
self.view_customers_button.setText(_translate(
"MainWindow", "View Customers With Unpaid Fees"))
self.view_items_category_model_button.setText(
_translate("MainWindow", "Items Sold in Category && Model"))
self.initialise_database_button.setText(
_translate("MainWindow", "Initialise Database!"))
self.submit_query.setText(_translate("MainWindow", "Submit"))
self.Categories_label.setText(_translate("MainWindow", "Categories"))
self.category_comboBox.setCurrentText(_translate("MainWindow", "All"))
self.category_comboBox.setItemText(0, _translate("MainWindow", "All"))
self.category_comboBox.setItemText(
1, _translate("MainWindow", "Locks"))
self.category_comboBox.setItemText(
2, _translate("MainWindow", "Lights"))
self.Model_label.setText(_translate("MainWindow", "Models"))
self.Price_label.setText(_translate("MainWindow", "Price"))
self.model_comboBox.setCurrentText(_translate("MainWindow", "All"))
self.model_comboBox.setItemText(0, _translate("MainWindow", "All"))
self.model_comboBox.setItemText(1, _translate("MainWindow", "Light1"))
self.model_comboBox.setItemText(2, _translate("MainWindow", "Light2"))
self.model_comboBox.setItemText(
3, _translate("MainWindow", "SmartHome1"))
self.model_comboBox.setItemText(4, _translate("MainWindow", "Safe1"))
self.model_comboBox.setItemText(5, _translate("MainWindow", "Safe2"))
self.price_comboBox.setCurrentText(_translate("MainWindow", "All"))
self.price_comboBox.setItemText(0, _translate("MainWindow", "All"))
self.price_comboBox.setItemText(1, _translate("MainWindow", "$50"))
self.price_comboBox.setItemText(2, _translate("MainWindow", "$60"))
self.price_comboBox.setItemText(3, _translate("MainWindow", "$100"))
self.price_comboBox.setItemText(4, _translate("MainWindow", "$120"))
self.price_comboBox.setItemText(5, _translate("MainWindow", "$125"))
self.price_comboBox.setItemText(6, _translate("MainWindow", "$200"))
self.factory_comboBox.setCurrentText(_translate("MainWindow", "All"))
self.factory_comboBox.setItemText(0, _translate("MainWindow", "All"))
self.factory_comboBox.setItemText(1, _translate("MainWindow", "China"))
self.factory_comboBox.setItemText(
2, _translate("MainWindow", "Malaysia"))
self.factory_comboBox.setItemText(
3, _translate("MainWindow", "Philippines"))
self.Factory_label.setText(_translate("MainWindow", "Factory"))
self.production_year_label.setText(
_translate("MainWindow", "Production year"))
self.colour_comboBox.setCurrentText(_translate("MainWindow", "All"))
self.colour_comboBox.setItemText(0, _translate("MainWindow", "All"))
self.colour_comboBox.setItemText(1, _translate("MainWindow", "Blue"))
self.colour_comboBox.setItemText(2, _translate("MainWindow", "Black"))
self.colour_comboBox.setItemText(3, _translate("MainWindow", "Green"))
self.colour_comboBox.setItemText(4, _translate("MainWindow", "Yellow"))
self.colour_comboBox.setItemText(5, _translate("MainWindow", "White"))
self.Colour_label.setText(_translate("MainWindow", "Colour"))
self.production_year_comboBox.setCurrentText(
_translate("MainWindow", "All"))
self.production_year_comboBox.setItemText(
0, _translate("MainWindow", "All"))
self.production_year_comboBox.setItemText(
1, _translate("MainWindow", "2014"))
self.production_year_comboBox.setItemText(
2, _translate("MainWindow", "2015"))
self.production_year_comboBox.setItemText(
3, _translate("MainWindow", "2016"))
self.production_year_comboBox.setItemText(
4, _translate("MainWindow", "2017"))
self.production_year_comboBox.setItemText(
5, _translate("MainWindow", "2019"))
self.production_year_comboBox.setItemText(
6, _translate("MainWindow", "2020"))
self.Power_supply_label.setText(
_translate("MainWindow", "Power Supply"))
self.power_supply_comboBox.setCurrentText(
_translate("MainWindow", "All"))
self.power_supply_comboBox.setItemText(
0, _translate("MainWindow", "All"))
self.power_supply_comboBox.setItemText(
1, _translate("MainWindow", "Battery"))
self.power_supply_comboBox.setItemText(
2, _translate("MainWindow", "USB"))
self.Warranty_label.setText(_translate("MainWindow", "Warranty"))
self.warranty_comboBox.setCurrentText(_translate("MainWindow", "All"))
self.warranty_comboBox.setItemText(0, _translate("MainWindow", "All"))
self.warranty_comboBox.setItemText(1, _translate("MainWindow", "6"))
self.warranty_comboBox.setItemText(2, _translate("MainWindow", "8"))
self.warranty_comboBox.setItemText(3, _translate("MainWindow", "10"))
self.warranty_comboBox.setItemText(4, _translate("MainWindow", "12"))
self.category_amount_label.setText(_translate("MainWindow", "All"))
self.choose_an_item_label.setText(
_translate("MainWindow", "Choose An Item!"))
self.inventory_level_label.setText(
_translate("MainWindow", "Inventory Level"))
self.sold_items_label.setText(
_translate("MainWindow", "Sold Items Amount"))
self.price_label.setText(_translate("MainWindow", "Price"))
self.warranty_label.setText(_translate("MainWindow", "Warranty"))
self.model_label.setText(_translate("MainWindow", "Model"))
self.cost_label.setText(_translate("MainWindow", "Cost"))
self.price_amount_label.setText(_translate("MainWindow", "$ --"))
self.warranty_amount_label.setText(_translate("MainWindow", "--"))
self.model_amount_label.setText(_translate("MainWindow", "--"))
self.cost_amount_label.setText(_translate("MainWindow", "$ --"))
self.inventory_amount_label.setText(_translate("MainWindow", "--"))
self.sold_items_amount_label.setText(_translate("MainWindow", "--"))
self.color_label.setText(_translate("MainWindow", "Color"))
self.product_year_label.setText(
_translate("MainWindow", "Production Year"))
self.power_supply_label.setText(
_translate("MainWindow", "Power Supply"))
self.color_amount_label.setText(_translate("MainWindow", "--"))
self.producti_year_amount_label.setText(_translate("MainWindow", "--"))
self.power_supply_amount_label.setText(_translate("MainWindow", "--"))
self.item_search_label.setText(_translate("MainWindow", "Item Search"))
self.item_table.setSortingEnabled(True)
item = self.item_table.horizontalHeaderItem(0)
item.setText(_translate("MainWindow", "Product ID"))
item = self.item_table.horizontalHeaderItem(1)
item.setText(_translate("MainWindow", "Item ID"))
item = self.item_table.horizontalHeaderItem(2)
item.setText(_translate("MainWindow", "Production Year"))
item = self.item_table.horizontalHeaderItem(3)
item.setText(_translate("MainWindow", "Power Supply"))
item = self.item_table.horizontalHeaderItem(4)
item.setText(_translate("MainWindow", "Color"))
item = self.item_table.horizontalHeaderItem(5)
item.setText(_translate("MainWindow", "Factory"))
item = self.item_table.horizontalHeaderItem(6)
item.setText(_translate("MainWindow", "Purchase Status"))
item = self.item_table.horizontalHeaderItem(7)
item.setText(_translate("MainWindow", "Model"))
item = self.item_table.horizontalHeaderItem(8)
item.setText(_translate("MainWindow", "Category"))
item = self.item_table.horizontalHeaderItem(9)
item.setText(_translate("MainWindow", "Warranty"))
item = self.item_table.horizontalHeaderItem(10)
item.setText(_translate("MainWindow", "Price"))
item = self.item_table.horizontalHeaderItem(11)
item.setText(_translate("MainWindow", "Cost"))
__sortingEnabled = self.item_table.isSortingEnabled()
self.item_table.setSortingEnabled(False)
self.item_table.setSortingEnabled(__sortingEnabled)
self.under_service_comboBox.setCurrentText(
_translate("MainWindow", "Yes"))
self.under_service_comboBox.setItemText(
0, _translate("MainWindow", "Yes"))
self.under_service_comboBox.setItemText(
1, _translate("MainWindow", "All Items Search"))
self.under_service_label.setText(
_translate("MainWindow", "Under Service?"))
self.item_id_label.setText(_translate("MainWindow", "Item ID"))
self.item_search_button.setText(_translate("MainWindow", "Search"))
self.request_table.setSortingEnabled(True)
item = self.request_table.horizontalHeaderItem(0)
item.setText(_translate("MainWindow", "Request ID"))
item = self.request_table.horizontalHeaderItem(1)
item.setText(_translate("MainWindow", "Service ID"))
item = self.request_table.horizontalHeaderItem(2)
item.setText(_translate("MainWindow", "Customer ID"))
item = self.request_table.horizontalHeaderItem(3)
item.setText(_translate("MainWindow", "Admin ID"))
item = self.request_table.horizontalHeaderItem(4)
item.setText(_translate("MainWindow", "Item ID"))
item = self.request_table.horizontalHeaderItem(5)
item.setText(_translate("MainWindow", "Request Date"))
item = self.request_table.horizontalHeaderItem(6)
item.setText(_translate("MainWindow", "Approve Request"))
self.fetch_requests_button.setText(
_translate("MainWindow", "Fetch Requests"))
self.all_requests_label.setText(_translate("MainWindow", "Requests"))
self.my_servicing_label.setText(_translate("MainWindow", "Servicing"))
self.servicing_table.setSortingEnabled(True)
item = self.servicing_table.horizontalHeaderItem(0)
item.setText(_translate("MainWindow", "Admin ID"))
item = self.servicing_table.horizontalHeaderItem(1)
item.setText(_translate("MainWindow", "Request ID"))
item = self.servicing_table.horizontalHeaderItem(2)
item.setText(_translate("MainWindow", "Service ID"))
item = self.servicing_table.horizontalHeaderItem(3)
item.setText(_translate("MainWindow", "Service Status"))
item = self.servicing_table.horizontalHeaderItem(4)
item.setText(_translate("MainWindow", "Complete Service"))
self.refresh_servicing_button.setText(
_translate("MainWindow", "Refresh")) | en | 0.245059 | #C7D2FE;") #2DD4BF, stop:1 #0EA5E9);\n" #2DD4BF, stop:1 #0EA5E9);\n" #2DD4BF, stop:1 #0EA5E9);\n" #2DD4BF, stop:1 #0EA5E9);\n" #2DD4BF, stop:1 #0EA5E9);\n" #2DD4BF, stop:1 #0EA5E9);\n" #94A3B8;\n" #E5E7EB;\n" #6366F1, stop:1 #7C3AED);\n" #4338CA, stop:1 #5B21B6);\n" #94A3B8;\n" #94A3B8;\n" #0F766E\n" #0E7490);\n" #0F766E\n" #0E7490);\n" #6366F1, stop:1#7C3AED);\n" #3730A3, stop:1 #5B21B6);\n" #3730A3\n" #5B21B6);\n" #6366F1, stop:1#7C3AED);\n" #3730A3, stop:1 #5B21B6);\n" #3730A3\n" #5B21B6);\n" #6366F1, stop:1#7C3AED);\n" #3730A3\n" #5B21B6);\n" #3730A3\n" #5B21B6);\n" #F59E0B, stop:1#E11D48);\n" #B45309\n" #9F1239);\n" #B45309\n" #9F1239);\n" #334155;\n" #0D9488, stop:1 #0E7490);\n" #334155;\n" #334155;\n" #334155;\n" #334155;\n" #334155;\n" #334155;\n" #334155;\n" #6D28D9 , stop:1 #4F46E5);\n" #6D28D9 , stop:1 #4F46E5);\n" #6D28D9 , stop:1 #4F46E5);\n" #6D28D9 , stop:1 #4F46E5);\n" #6D28D9 , stop:1 #4F46E5);\n" #F59E0B, stop:1#E11D48);\n" #F59E0B, stop:1#E11D48);\n" #6D28D9 , stop:1 #4F46E5);\n" #6D28D9 , stop:1 #4F46E5);\n" #6D28D9 , stop:1 #4F46E5);\n" #94A3B8;\n" #E5E7EB;\n" #6366F1, stop:1 #7C3AED);\n" #4338CA, stop:1 #5B21B6);\n" #94A3B8;\n" #94A3B8;\n" #334155;\n" #334155;\n" #6366F1, stop:1 #7C3AED);\n" #4338CA\n" #5B21B6);\n" #4338CA\n" #5B21B6);\n" #94A3B8;\n" #E5E7EB;\n" #6366F1, stop:1 #7C3AED);\n" #4338CA, stop:1 #5B21B6);\n" #94A3B8;\n" #94A3B8;\n" #F59E0B, stop:1#E11D48);\n" #B45309\n" #9F1239);\n" #B45309\n" #9F1239);\n" #94A3B8;\n" #E5E7EB;\n" #6366F1, stop:1 #7C3AED);\n" #4338CA, stop:1 #5B21B6);\n" #94A3B8;\n" #94A3B8;\n" #0F766E\n" #0E7490);\n" #0F766E\n" #0E7490);\n" | 2.242481 | 2 |
src/exams/doctor_time.py | Jakob-Daugherty/ftlengine | 1 | 6623082 | import ntplib
import time
from ..plugins.base import BasePlugin
from ..plugins.doctor import BaseExamination
class DoctorTimePlugin(BasePlugin):
"""
Examinations to check the time on the docker server is roughly correct
"""
requires = ["doctor"]
def load(self):
self.add_catalog_item("doctor-exam", "time", TimeExamination)
class TimeExamination(BaseExamination):
"""
Checks the datetime on the docker server is not too out of drift
"""
warning_limit = 10
error_limit = 120
description = "Time checks"
def check_docker_time(self):
"""Testing docker clock sync"""
# Check to see if the docker server agrees with our clock
self.host.client.pull("alpine", "3.5")
container = self.host.client.create_container(
"alpine:3.5",
command=["/bin/date", "+%s"],
detach=True,
tty=False,
)
self.host.client.start(container)
while self.host.container_running(container['Id']):
time.sleep(0.1)
docker_time = self.host.client.logs(container['Id']).strip()
delta = abs(int(docker_time) - time.time())
if delta > self.error_limit:
raise self.Failure("%i seconds out of sync" % delta)
elif delta > self.warning_limit:
raise self.Warning("%i seconds out of sync" % delta)
def check_local_time(self):
"""Testing local clock sync"""
# Query an NTP server for the time
c = ntplib.NTPClient()
response = c.request('pool.ntp.org', version=3)
delta = abs(response.offset)
if delta > self.error_limit:
raise self.Failure("%i seconds out of sync" % delta)
elif delta > self.warning_limit:
raise self.Warning("%i seconds out of sync" % delta)
| import ntplib
import time
from ..plugins.base import BasePlugin
from ..plugins.doctor import BaseExamination
class DoctorTimePlugin(BasePlugin):
"""
Examinations to check the time on the docker server is roughly correct
"""
requires = ["doctor"]
def load(self):
self.add_catalog_item("doctor-exam", "time", TimeExamination)
class TimeExamination(BaseExamination):
"""
Checks the datetime on the docker server is not too out of drift
"""
warning_limit = 10
error_limit = 120
description = "Time checks"
def check_docker_time(self):
"""Testing docker clock sync"""
# Check to see if the docker server agrees with our clock
self.host.client.pull("alpine", "3.5")
container = self.host.client.create_container(
"alpine:3.5",
command=["/bin/date", "+%s"],
detach=True,
tty=False,
)
self.host.client.start(container)
while self.host.container_running(container['Id']):
time.sleep(0.1)
docker_time = self.host.client.logs(container['Id']).strip()
delta = abs(int(docker_time) - time.time())
if delta > self.error_limit:
raise self.Failure("%i seconds out of sync" % delta)
elif delta > self.warning_limit:
raise self.Warning("%i seconds out of sync" % delta)
def check_local_time(self):
"""Testing local clock sync"""
# Query an NTP server for the time
c = ntplib.NTPClient()
response = c.request('pool.ntp.org', version=3)
delta = abs(response.offset)
if delta > self.error_limit:
raise self.Failure("%i seconds out of sync" % delta)
elif delta > self.warning_limit:
raise self.Warning("%i seconds out of sync" % delta)
| en | 0.829351 | Examinations to check the time on the docker server is roughly correct Checks the datetime on the docker server is not too out of drift Testing docker clock sync # Check to see if the docker server agrees with our clock Testing local clock sync # Query an NTP server for the time | 2.698454 | 3 |
PI/Renderer/Camera/PerspectiveCamera.py | HotShot0901/PI | 0 | 6623083 | <gh_stars>0
from .Camera import Camera
from ..RenderCommand import RenderCommand
import pyrr
class PerspectiveCamera(Camera):
__slots__ = "__Fov", "__Near", "__Far"
def __init__(self, fov: float, aspectRatio: float, near: float=0.01, far: float=1000) -> None:
self.__Fov = fov
self._AspectRatio = aspectRatio
self.__Near = near
self.__Far = far
viewMatrix = pyrr.matrix44.create_identity()
projectionMatrix = pyrr.matrix44.create_perspective_projection_matrix(
fov, aspectRatio, near, far
)
super().__init__(viewMatrix, projectionMatrix)
RenderCommand.EnableDepth()
def SetAspectRatio(self, newRatio: float) -> None:
self._AspectRatio = newRatio
self._ProjectionMatrix = pyrr.matrix44.create_perspective_projection_matrix(
self.__Fov, self._AspectRatio, self.__Near, self.__Far
)
self._RecalculateViewMatrix()
@property
def FOV(self) -> float:
return self.__Fov
def GetSpeed(self) -> float:
return self.__Fov / 15
def SetFOV(self, fov: float) -> None:
self.__Fov = fov + 0.001
self._ProjectionMatrix = pyrr.matrix44.create_perspective_projection_matrix(
fov, self._AspectRatio, self.__Near, self.__Far
)
self._RecalculateViewMatrix()
| from .Camera import Camera
from ..RenderCommand import RenderCommand
import pyrr
class PerspectiveCamera(Camera):
__slots__ = "__Fov", "__Near", "__Far"
def __init__(self, fov: float, aspectRatio: float, near: float=0.01, far: float=1000) -> None:
self.__Fov = fov
self._AspectRatio = aspectRatio
self.__Near = near
self.__Far = far
viewMatrix = pyrr.matrix44.create_identity()
projectionMatrix = pyrr.matrix44.create_perspective_projection_matrix(
fov, aspectRatio, near, far
)
super().__init__(viewMatrix, projectionMatrix)
RenderCommand.EnableDepth()
def SetAspectRatio(self, newRatio: float) -> None:
self._AspectRatio = newRatio
self._ProjectionMatrix = pyrr.matrix44.create_perspective_projection_matrix(
self.__Fov, self._AspectRatio, self.__Near, self.__Far
)
self._RecalculateViewMatrix()
@property
def FOV(self) -> float:
return self.__Fov
def GetSpeed(self) -> float:
return self.__Fov / 15
def SetFOV(self, fov: float) -> None:
self.__Fov = fov + 0.001
self._ProjectionMatrix = pyrr.matrix44.create_perspective_projection_matrix(
fov, self._AspectRatio, self.__Near, self.__Far
)
self._RecalculateViewMatrix() | none | 1 | 2.402431 | 2 | |
scripts/src/build_sources/__main__.py | APotyomkin/awesome-bugs | 1 | 6623084 | <reponame>APotyomkin/awesome-bugs
import os
import sys
# Here we generate a CMakeLists file based on the CPP sources
# and make a build using it
# As an input it takes:
# - a path to a folder with source files
# - a path to a resulting build folder
CMAKE_TEMPLATE = """
cmake_minimum_required(VERSION 3.20)
project(AwesomeBugs)
set(CMAKE_CXX_STANDARD 14)
add_executable(AwesomeBugs
{files}
)
"""
def generate_cmakelists(sources_folder_path):
paths = []
# Collect CPP sources
for root, dirs, files in os.walk(sources_folder_path):
if len(dirs) == 0:
for file in files:
if file.endswith(".cpp"):
paths.append(os.path.join(root, file))
# Insert into CMakeLists file template
with open("CMakeLists.txt", "w") as f:
f.write(CMAKE_TEMPLATE.format(files="\n\t".join(sorted(paths))))
def run_cmake(build_folder_path):
# Create a build folder if not exist
if not os.path.exists(build_folder_path):
os.mkdir(build_folder_path)
# Run building process.
# DCMAKE_EXPORT_COMPILE_COMMANDS=ON is important because
# the exported DB will be used by CSA
os.system("cmake -DCMAKE_EXPORT_COMPILE_COMMANDS=ON -S . -B build")
def main():
# Read arguments
if len(sys.argv) == 3:
sources_folder_path = sys.argv[1]
build_folder_path = sys.argv[2]
else:
print("Wrong number of arguments")
return
# Generation CMakeList from CPP source files
generate_cmakelists(sources_folder_path)
print("Cmake file generated")
# Build based on CMakeList file
run_cmake(build_folder_path)
print("Cmake build completed")
if __name__ == "__main__":
main()
| import os
import sys
# Here we generate a CMakeLists file based on the CPP sources
# and make a build using it
# As an input it takes:
# - a path to a folder with source files
# - a path to a resulting build folder
CMAKE_TEMPLATE = """
cmake_minimum_required(VERSION 3.20)
project(AwesomeBugs)
set(CMAKE_CXX_STANDARD 14)
add_executable(AwesomeBugs
{files}
)
"""
def generate_cmakelists(sources_folder_path):
paths = []
# Collect CPP sources
for root, dirs, files in os.walk(sources_folder_path):
if len(dirs) == 0:
for file in files:
if file.endswith(".cpp"):
paths.append(os.path.join(root, file))
# Insert into CMakeLists file template
with open("CMakeLists.txt", "w") as f:
f.write(CMAKE_TEMPLATE.format(files="\n\t".join(sorted(paths))))
def run_cmake(build_folder_path):
# Create a build folder if not exist
if not os.path.exists(build_folder_path):
os.mkdir(build_folder_path)
# Run building process.
# DCMAKE_EXPORT_COMPILE_COMMANDS=ON is important because
# the exported DB will be used by CSA
os.system("cmake -DCMAKE_EXPORT_COMPILE_COMMANDS=ON -S . -B build")
def main():
# Read arguments
if len(sys.argv) == 3:
sources_folder_path = sys.argv[1]
build_folder_path = sys.argv[2]
else:
print("Wrong number of arguments")
return
# Generation CMakeList from CPP source files
generate_cmakelists(sources_folder_path)
print("Cmake file generated")
# Build based on CMakeList file
run_cmake(build_folder_path)
print("Cmake build completed")
if __name__ == "__main__":
main() | en | 0.723381 | # Here we generate a CMakeLists file based on the CPP sources # and make a build using it # As an input it takes: # - a path to a folder with source files # - a path to a resulting build folder cmake_minimum_required(VERSION 3.20) project(AwesomeBugs) set(CMAKE_CXX_STANDARD 14) add_executable(AwesomeBugs {files} ) # Collect CPP sources # Insert into CMakeLists file template # Create a build folder if not exist # Run building process. # DCMAKE_EXPORT_COMPILE_COMMANDS=ON is important because # the exported DB will be used by CSA # Read arguments # Generation CMakeList from CPP source files # Build based on CMakeList file | 2.884973 | 3 |
heartbridge/data.py | mm/heartbridge | 11 | 6623085 | <gh_stars>10-100
"""Entity definitions (data classes) for Heartbridge. Each
class is a different record type from the Health app.
"""
from dataclasses import dataclass, fields, InitVar
from typing import ClassVar
from datetime import datetime
@dataclass(order=True)
class BaseHealthReading:
timestamp: datetime
value: InitVar[str] = None
@property
def field_names(self):
return [x.name for x in fields(self)]
@property
def timestamp_string(self) -> str:
return datetime.strftime(self.timestamp, "%Y-%m-%d %H:%M:%S")
def get_value(self):
"""Gets the value of a health reading, determined by the `value_attribute`
class variable.
"""
if self.__annotations__.get("value_attribute"):
value_key = getattr(self, "value_attribute")
return self.__getattribute__(value_key)
return None
def to_dict(self):
"""Converts the data object to a dictionary. Call only
on a subclass of BaseHealthReading.
"""
if self.__annotations__.get("value_attribute"):
value_key = getattr(self, "value_attribute")
return {
"timestamp": self.timestamp_string,
value_key: self.__getattribute__(value_key),
}
@dataclass(order=True)
class GenericHealthReading(BaseHealthReading):
reading: str = None
value_attribute: ClassVar[str] = "reading"
def __post_init__(self, value):
self.reading = value
@dataclass(order=True)
class HeartRateReading(BaseHealthReading):
heart_rate: float = None
value_attribute: ClassVar[str] = "heart_rate"
def __post_init__(self, value):
self.heart_rate = int(value)
@dataclass(order=True)
class RestingHeartRateReading(BaseHealthReading):
resting_heart_rate: int = None
value_attribute: ClassVar[str] = "resting_heart_rate"
def __post_init__(self, value):
self.resting_heart_rate = int(value)
@dataclass(order=True)
class HeartRateVariabilityReading(BaseHealthReading):
heart_rate_variability: float = None
value_attribute: ClassVar[str] = "heart_rate_variability"
def __post_init__(self, value):
self.heart_rate_variability = round(float(value), 2)
@dataclass(order=True)
class StepsReading(BaseHealthReading):
step_count: int = None
value_attribute: ClassVar[str] = "step_count"
def __post_init__(self, value):
self.step_count = int(value)
@dataclass(order=True)
class FlightsClimbedReading(BaseHealthReading):
climbed: int = None
value_attribute: ClassVar[str] = "climbed"
def __post_init__(self, value):
self.climbed = int(value)
@dataclass(order=True)
class CyclingDistanceReading(BaseHealthReading):
distance_cycled: float = None
value_attribute: ClassVar[str] = "distance_cycled"
def __post_init__(self, value):
self.distance_cycled = float(value)
| """Entity definitions (data classes) for Heartbridge. Each
class is a different record type from the Health app.
"""
from dataclasses import dataclass, fields, InitVar
from typing import ClassVar
from datetime import datetime
@dataclass(order=True)
class BaseHealthReading:
timestamp: datetime
value: InitVar[str] = None
@property
def field_names(self):
return [x.name for x in fields(self)]
@property
def timestamp_string(self) -> str:
return datetime.strftime(self.timestamp, "%Y-%m-%d %H:%M:%S")
def get_value(self):
"""Gets the value of a health reading, determined by the `value_attribute`
class variable.
"""
if self.__annotations__.get("value_attribute"):
value_key = getattr(self, "value_attribute")
return self.__getattribute__(value_key)
return None
def to_dict(self):
"""Converts the data object to a dictionary. Call only
on a subclass of BaseHealthReading.
"""
if self.__annotations__.get("value_attribute"):
value_key = getattr(self, "value_attribute")
return {
"timestamp": self.timestamp_string,
value_key: self.__getattribute__(value_key),
}
@dataclass(order=True)
class GenericHealthReading(BaseHealthReading):
reading: str = None
value_attribute: ClassVar[str] = "reading"
def __post_init__(self, value):
self.reading = value
@dataclass(order=True)
class HeartRateReading(BaseHealthReading):
heart_rate: float = None
value_attribute: ClassVar[str] = "heart_rate"
def __post_init__(self, value):
self.heart_rate = int(value)
@dataclass(order=True)
class RestingHeartRateReading(BaseHealthReading):
resting_heart_rate: int = None
value_attribute: ClassVar[str] = "resting_heart_rate"
def __post_init__(self, value):
self.resting_heart_rate = int(value)
@dataclass(order=True)
class HeartRateVariabilityReading(BaseHealthReading):
heart_rate_variability: float = None
value_attribute: ClassVar[str] = "heart_rate_variability"
def __post_init__(self, value):
self.heart_rate_variability = round(float(value), 2)
@dataclass(order=True)
class StepsReading(BaseHealthReading):
step_count: int = None
value_attribute: ClassVar[str] = "step_count"
def __post_init__(self, value):
self.step_count = int(value)
@dataclass(order=True)
class FlightsClimbedReading(BaseHealthReading):
climbed: int = None
value_attribute: ClassVar[str] = "climbed"
def __post_init__(self, value):
self.climbed = int(value)
@dataclass(order=True)
class CyclingDistanceReading(BaseHealthReading):
distance_cycled: float = None
value_attribute: ClassVar[str] = "distance_cycled"
def __post_init__(self, value):
self.distance_cycled = float(value) | en | 0.79126 | Entity definitions (data classes) for Heartbridge. Each class is a different record type from the Health app. Gets the value of a health reading, determined by the `value_attribute` class variable. Converts the data object to a dictionary. Call only on a subclass of BaseHealthReading. | 3.44401 | 3 |
wxviews/__init__.py | eumis/wxviews | 6 | 6623086 | <gh_stars>1-10
"""Package adapts pyviews for using with wxpython"""
from pyviews.setters import import_global, inject_global, set_global, call, call_args
from pyviews.code import Code
from pyviews.containers import Container, View, For, If
from pyviews.presenter import Presenter, PresenterNode, add_reference
from wxviews.sizers import GrowableCol, GrowableRow, set_sizer
from wxviews.widgets import get_root, bind
from wxviews.styles import Style, StylesView, style
__version__ = '0.6.0'
| """Package adapts pyviews for using with wxpython"""
from pyviews.setters import import_global, inject_global, set_global, call, call_args
from pyviews.code import Code
from pyviews.containers import Container, View, For, If
from pyviews.presenter import Presenter, PresenterNode, add_reference
from wxviews.sizers import GrowableCol, GrowableRow, set_sizer
from wxviews.widgets import get_root, bind
from wxviews.styles import Style, StylesView, style
__version__ = '0.6.0' | en | 0.858433 | Package adapts pyviews for using with wxpython | 1.933195 | 2 |
amazonPriceTracker/app/templatetags/colorize.py | younesaitmha/amazon-price-tracker | 12 | 6623087 | <filename>amazonPriceTracker/app/templatetags/colorize.py
from django import template
from django.utils.safestring import mark_safe
register = template.Library()
@register.filter
def colorize(value):
mark = str(value)[:1]
if mark == "-":
html_str = f"<span style='color:green'>${value}</span>"
elif value == 0:
html_str = f"<span style='color:blue'>${value}</span>"
else:
html_str = f"<span style='color:red'>${value}</span>"
return mark_safe(html_str)
| <filename>amazonPriceTracker/app/templatetags/colorize.py
from django import template
from django.utils.safestring import mark_safe
register = template.Library()
@register.filter
def colorize(value):
mark = str(value)[:1]
if mark == "-":
html_str = f"<span style='color:green'>${value}</span>"
elif value == 0:
html_str = f"<span style='color:blue'>${value}</span>"
else:
html_str = f"<span style='color:red'>${value}</span>"
return mark_safe(html_str)
| none | 1 | 2.593407 | 3 | |
likes/api/views.py | BattleWoLFz99/Twitchain | 0 | 6623088 | <gh_stars>0
from django.utils.decorators import method_decorator
from inbox.services import NotificationService
from likes.api.serializers import (
LikeSerializer,
LikeSerializerForCancel,
LikeSerializerForCreate,
)
from likes.models import Like
from ratelimit.decorators import ratelimit
from rest_framework import viewsets, status
from rest_framework.decorators import action
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from utils.decorators import required_params
class LikeViewSet(viewsets.GenericViewSet):
queryset = Like.objects.all()
permission_classes = [IsAuthenticated]
serializer_class = LikeSerializerForCreate
@required_params(method='POST', params=['content_type', 'object_id'])
@method_decorator(ratelimit(key='user', rate='10/s', method='POST', block=True))
def create(self, request, *args, **kwargs):
serializer = LikeSerializerForCreate(
data=request.data,
context={'request': request},
)
if not serializer.is_valid():
return Response({
'message': 'Please check input',
'errors': serializer.errors,
}, status=status.HTTP_400_BAD_REQUEST)
instance, created = serializer.get_or_create()
if created:
NotificationService.send_like_notification(instance)
return Response(
LikeSerializer(instance).data,
status=status.HTTP_201_CREATED,
)
@action(methods=['POST'], detail=False)
@required_params(method='POST', params=['content_type', 'object_id'])
@method_decorator(ratelimit(key='user', rate='10/s', method='POST', block=True))
def cancel(self, request, *args, **kwargs):
serializer = LikeSerializerForCancel(
data=request.data,
context={'request': request},
)
if not serializer.is_valid():
return Response({
'message': 'Please check input',
'errors': serializer.errors,
}, status=status.HTTP_400_BAD_REQUEST)
serializer.cancel()
return Response({'success': True}, status=status.HTTP_200_OK)
| from django.utils.decorators import method_decorator
from inbox.services import NotificationService
from likes.api.serializers import (
LikeSerializer,
LikeSerializerForCancel,
LikeSerializerForCreate,
)
from likes.models import Like
from ratelimit.decorators import ratelimit
from rest_framework import viewsets, status
from rest_framework.decorators import action
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from utils.decorators import required_params
class LikeViewSet(viewsets.GenericViewSet):
queryset = Like.objects.all()
permission_classes = [IsAuthenticated]
serializer_class = LikeSerializerForCreate
@required_params(method='POST', params=['content_type', 'object_id'])
@method_decorator(ratelimit(key='user', rate='10/s', method='POST', block=True))
def create(self, request, *args, **kwargs):
serializer = LikeSerializerForCreate(
data=request.data,
context={'request': request},
)
if not serializer.is_valid():
return Response({
'message': 'Please check input',
'errors': serializer.errors,
}, status=status.HTTP_400_BAD_REQUEST)
instance, created = serializer.get_or_create()
if created:
NotificationService.send_like_notification(instance)
return Response(
LikeSerializer(instance).data,
status=status.HTTP_201_CREATED,
)
@action(methods=['POST'], detail=False)
@required_params(method='POST', params=['content_type', 'object_id'])
@method_decorator(ratelimit(key='user', rate='10/s', method='POST', block=True))
def cancel(self, request, *args, **kwargs):
serializer = LikeSerializerForCancel(
data=request.data,
context={'request': request},
)
if not serializer.is_valid():
return Response({
'message': 'Please check input',
'errors': serializer.errors,
}, status=status.HTTP_400_BAD_REQUEST)
serializer.cancel()
return Response({'success': True}, status=status.HTTP_200_OK) | none | 1 | 1.930623 | 2 | |
CorpusCleaner.py | teaholic/NLP | 0 | 6623089 | """
Created on Sun Mar 22 14:57:00 2015
@author: bigiei
"""
# Opening my csv file
dataset = open("Dataset.txt", "w")
# Opening text and isolating every word
text = open("Corpus.txt", "r")
for line in text :
for word in line.split() :
word = (word)
# generating and classificating tokens
# finding existing tags
#
# TAG CODEBOOK:
# LSP = language for specific purpose
#
try:
cleaning = word.split("/")
token = cleaning[0]
tag = cleaning[1]
except IndexError:
token = word
# tagging non LSP as NA
tag = "NON"
# rimming punctuation
if token[len(token)-1:] in char :
token = token[:len(token)-1]
# tagging non LSP as NA
result = [token, tag]
print result
# defining result
result = str(token + "," + tag + "\n")
# printing token and relevant tag
dataset.write(result)
#closing files
text.close()
dataset.close()
| """
Created on Sun Mar 22 14:57:00 2015
@author: bigiei
"""
# Opening my csv file
dataset = open("Dataset.txt", "w")
# Opening text and isolating every word
text = open("Corpus.txt", "r")
for line in text :
for word in line.split() :
word = (word)
# generating and classificating tokens
# finding existing tags
#
# TAG CODEBOOK:
# LSP = language for specific purpose
#
try:
cleaning = word.split("/")
token = cleaning[0]
tag = cleaning[1]
except IndexError:
token = word
# tagging non LSP as NA
tag = "NON"
# rimming punctuation
if token[len(token)-1:] in char :
token = token[:len(token)-1]
# tagging non LSP as NA
result = [token, tag]
print result
# defining result
result = str(token + "," + tag + "\n")
# printing token and relevant tag
dataset.write(result)
#closing files
text.close()
dataset.close()
| en | 0.749395 | Created on Sun Mar 22 14:57:00 2015 @author: bigiei # Opening my csv file # Opening text and isolating every word # generating and classificating tokens # finding existing tags # # TAG CODEBOOK: # LSP = language for specific purpose # # tagging non LSP as NA # rimming punctuation # tagging non LSP as NA # defining result # printing token and relevant tag #closing files | 3.046551 | 3 |
Gallery/migrations/0008_imagesclient_column.py | CiganOliviu/InfiniteShoot | 1 | 6623090 | # Generated by Django 3.0.8 on 2021-02-20 12:56
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('Gallery', '0007_platformpresentationimage_column'),
]
operations = [
migrations.AddField(
model_name='imagesclient',
name='column',
field=models.CharField(choices=[('First Column', 'First Column'), ('Second Column', 'Second Column'), ('Third Column', 'Third Column'), ('Fourth Column', 'Fourth Column')], default='First Column', max_length=255),
),
]
| # Generated by Django 3.0.8 on 2021-02-20 12:56
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('Gallery', '0007_platformpresentationimage_column'),
]
operations = [
migrations.AddField(
model_name='imagesclient',
name='column',
field=models.CharField(choices=[('First Column', 'First Column'), ('Second Column', 'Second Column'), ('Third Column', 'Third Column'), ('Fourth Column', 'Fourth Column')], default='First Column', max_length=255),
),
]
| en | 0.803852 | # Generated by Django 3.0.8 on 2021-02-20 12:56 | 1.955355 | 2 |
Util.py | landicefu/OKExDailyReport | 1 | 6623091 |
def read_all(path: str, strip: bool = True) -> str:
with open(path, 'r') as file:
content = file.read()
if strip:
return content.strip()
else:
return content
|
def read_all(path: str, strip: bool = True) -> str:
with open(path, 'r') as file:
content = file.read()
if strip:
return content.strip()
else:
return content
| none | 1 | 3.190564 | 3 | |
bot/__init__.py | yiannisha/UrbanDictionaryBot | 0 | 6623092 | """ A module to handle running the bot. """
| """ A module to handle running the bot. """
| en | 0.456491 | A module to handle running the bot. | 0.971533 | 1 |
openapi_schema_to_json_schema/to_jsonschema.py | pglass/py-openapi-jsonschema-converter | 12 | 6623093 | <filename>openapi_schema_to_json_schema/to_jsonschema.py<gh_stars>10-100
import json
class InvalidTypeError(ValueError):
def __init__(self, msg):
super(InvalidTypeError, self).__init__(msg)
def _prepare(schema, options=None):
notSupported = [
'nullable', 'discriminator', 'readOnly',
'writeOnly', 'xml', 'externalDocs',
'example', 'deprecated',
]
options = options or {}
options['dateToDateTime'] = options.get('dateToDateTime', False)
options['cloneSchema'] = options.get('cloneSchema', True)
options['supportPatternProperties'] = options.get(
'supportPatternProperties', False
)
options['keepNotSupported'] = options.get('keepNotSupported', [])
if not callable(options.get('patternPropertiesHandler')):
options['patternPropertiesHandler'] = patternPropertiesHandler
options['_removeProps'] = []
if options.get('removeReadOnly'):
options['_removeProps'].append('readOnly')
if options.get('removeWriteOnly'):
options['_removeProps'].append('writeOnly')
options['_structs'] = [
'allOf', 'anyOf', 'oneOf', 'not', 'items', 'additionalProperties',
]
options['_notSupported'] = resolveNotSupported(
notSupported, options['keepNotSupported'],
)
if options['cloneSchema']:
schema = json.loads(json.dumps(schema))
return schema, options
def convert(schema, options=None):
schema, options = _prepare(schema, options)
schema = convertSchema(schema, options)
schema['$schema'] = 'http://json-schema.org/draft-04/schema#'
return schema
def _recurse(tree, options):
for key, subtree in list(tree.items()):
if isinstance(subtree, dict):
if key == 'schema':
tree[key] = convertSchema(subtree, options)
else:
tree[key] = _recurse(subtree, options)
elif isinstance(subtree, list):
tree[key] = [
_recurse(item, options) if isinstance(item, dict) else item
for item in subtree
]
return tree
def convertDoc(doc, options):
doc, options = _prepare(doc, options)
components_schemas = doc.get('components', {}).get('schemas')
if components_schemas:
for name, struct in list(components_schemas.items()):
components_schemas[name] = convertSchema(struct, options)
paths = doc.get('paths')
if paths:
doc['paths'] = dict((path, _recurse(tree, options))
for path, tree in paths.items())
doc['$schema'] = 'http://json-schema.org/draft-04/schema#'
return doc
def convertSchema(schema, options):
structs = options['_structs']
notSupported = options['_notSupported']
for i, struct in enumerate(structs):
if isinstance(schema.get(struct), list):
for j in range(len(schema[struct])):
schema[struct][j] = convertSchema(schema[struct][j], options)
elif isinstance(schema.get(struct), dict):
schema[struct] = convertSchema(schema[struct], options)
if isinstance(schema.get('properties'), dict):
schema['properties'] = convertProperties(schema['properties'], options)
if isinstance(schema.get('required'), list):
schema['required'] = cleanRequired(schema['required'],
schema['properties'])
if len(schema['required']) == 0:
del schema['required']
if len(schema['properties']) == 0:
del schema['properties']
validateType(schema.get('type'))
schema = convertTypes(schema, options)
if (isinstance(schema.get('x-patternProperties'), dict)
and options['supportPatternProperties']):
schema = convertPatternProperties(schema,
options['patternPropertiesHandler'])
for unsupported in notSupported:
try:
del schema[unsupported]
except KeyError:
pass
return schema
def convertProperties(properties, options):
props = {}
for key in properties:
removeProp = False
# note: don't shadow the `property` built-in
pproperty = properties[key]
for prop in options['_removeProps']:
if pproperty.get(prop) is True:
removeProp = True
if removeProp:
continue
props[key] = convertSchema(pproperty, options)
return props
def validateType(ttype):
validTypes = ['integer', 'number', 'string', 'boolean', 'object', 'array']
if ttype is not None and ttype not in validTypes:
raise InvalidTypeError('Type "%s" is not a valid type' % ttype)
def convertTypes(schema, options):
toDateTime = options['dateToDateTime']
if schema.get('type') is None:
# https://github.com/pglass/py-openapi-schema-to-json-schema/issues/10
if schema.get('nullable') is True:
for struct in ['oneOf', 'anyOf']:
if struct in schema:
schema[struct].append({'type': 'null'})
return schema
if (schema.get('type') == 'string' and schema.get('format') == 'date'
and toDateTime):
schema['format'] = 'date-time'
if not schema.get('format'):
try:
del schema['format']
except KeyError:
pass
if schema.get('nullable') is True:
schema['type'] = [schema['type'], 'null']
return schema
def convertPatternProperties(schema, handler):
schema['patternProperties'] = schema['x-patternProperties']
del schema['x-patternProperties']
return handler(schema)
def patternPropertiesHandler(schema):
patternsObj = schema['patternProperties']
additProps = schema.get('additionalProperties')
if not isinstance(additProps, dict):
return schema
for pattern, value in patternsObj.items():
if value == additProps:
schema['additionalProperties'] = False
break
return schema
def resolveNotSupported(notSupported, toRetain):
return [x for x in notSupported if x not in toRetain]
def cleanRequired(required, properties):
required = required or []
properties = properties or {}
return [x for x in required if properties.get(x) is not None]
| <filename>openapi_schema_to_json_schema/to_jsonschema.py<gh_stars>10-100
import json
class InvalidTypeError(ValueError):
def __init__(self, msg):
super(InvalidTypeError, self).__init__(msg)
def _prepare(schema, options=None):
notSupported = [
'nullable', 'discriminator', 'readOnly',
'writeOnly', 'xml', 'externalDocs',
'example', 'deprecated',
]
options = options or {}
options['dateToDateTime'] = options.get('dateToDateTime', False)
options['cloneSchema'] = options.get('cloneSchema', True)
options['supportPatternProperties'] = options.get(
'supportPatternProperties', False
)
options['keepNotSupported'] = options.get('keepNotSupported', [])
if not callable(options.get('patternPropertiesHandler')):
options['patternPropertiesHandler'] = patternPropertiesHandler
options['_removeProps'] = []
if options.get('removeReadOnly'):
options['_removeProps'].append('readOnly')
if options.get('removeWriteOnly'):
options['_removeProps'].append('writeOnly')
options['_structs'] = [
'allOf', 'anyOf', 'oneOf', 'not', 'items', 'additionalProperties',
]
options['_notSupported'] = resolveNotSupported(
notSupported, options['keepNotSupported'],
)
if options['cloneSchema']:
schema = json.loads(json.dumps(schema))
return schema, options
def convert(schema, options=None):
schema, options = _prepare(schema, options)
schema = convertSchema(schema, options)
schema['$schema'] = 'http://json-schema.org/draft-04/schema#'
return schema
def _recurse(tree, options):
for key, subtree in list(tree.items()):
if isinstance(subtree, dict):
if key == 'schema':
tree[key] = convertSchema(subtree, options)
else:
tree[key] = _recurse(subtree, options)
elif isinstance(subtree, list):
tree[key] = [
_recurse(item, options) if isinstance(item, dict) else item
for item in subtree
]
return tree
def convertDoc(doc, options):
doc, options = _prepare(doc, options)
components_schemas = doc.get('components', {}).get('schemas')
if components_schemas:
for name, struct in list(components_schemas.items()):
components_schemas[name] = convertSchema(struct, options)
paths = doc.get('paths')
if paths:
doc['paths'] = dict((path, _recurse(tree, options))
for path, tree in paths.items())
doc['$schema'] = 'http://json-schema.org/draft-04/schema#'
return doc
def convertSchema(schema, options):
structs = options['_structs']
notSupported = options['_notSupported']
for i, struct in enumerate(structs):
if isinstance(schema.get(struct), list):
for j in range(len(schema[struct])):
schema[struct][j] = convertSchema(schema[struct][j], options)
elif isinstance(schema.get(struct), dict):
schema[struct] = convertSchema(schema[struct], options)
if isinstance(schema.get('properties'), dict):
schema['properties'] = convertProperties(schema['properties'], options)
if isinstance(schema.get('required'), list):
schema['required'] = cleanRequired(schema['required'],
schema['properties'])
if len(schema['required']) == 0:
del schema['required']
if len(schema['properties']) == 0:
del schema['properties']
validateType(schema.get('type'))
schema = convertTypes(schema, options)
if (isinstance(schema.get('x-patternProperties'), dict)
and options['supportPatternProperties']):
schema = convertPatternProperties(schema,
options['patternPropertiesHandler'])
for unsupported in notSupported:
try:
del schema[unsupported]
except KeyError:
pass
return schema
def convertProperties(properties, options):
props = {}
for key in properties:
removeProp = False
# note: don't shadow the `property` built-in
pproperty = properties[key]
for prop in options['_removeProps']:
if pproperty.get(prop) is True:
removeProp = True
if removeProp:
continue
props[key] = convertSchema(pproperty, options)
return props
def validateType(ttype):
validTypes = ['integer', 'number', 'string', 'boolean', 'object', 'array']
if ttype is not None and ttype not in validTypes:
raise InvalidTypeError('Type "%s" is not a valid type' % ttype)
def convertTypes(schema, options):
toDateTime = options['dateToDateTime']
if schema.get('type') is None:
# https://github.com/pglass/py-openapi-schema-to-json-schema/issues/10
if schema.get('nullable') is True:
for struct in ['oneOf', 'anyOf']:
if struct in schema:
schema[struct].append({'type': 'null'})
return schema
if (schema.get('type') == 'string' and schema.get('format') == 'date'
and toDateTime):
schema['format'] = 'date-time'
if not schema.get('format'):
try:
del schema['format']
except KeyError:
pass
if schema.get('nullable') is True:
schema['type'] = [schema['type'], 'null']
return schema
def convertPatternProperties(schema, handler):
schema['patternProperties'] = schema['x-patternProperties']
del schema['x-patternProperties']
return handler(schema)
def patternPropertiesHandler(schema):
patternsObj = schema['patternProperties']
additProps = schema.get('additionalProperties')
if not isinstance(additProps, dict):
return schema
for pattern, value in patternsObj.items():
if value == additProps:
schema['additionalProperties'] = False
break
return schema
def resolveNotSupported(notSupported, toRetain):
return [x for x in notSupported if x not in toRetain]
def cleanRequired(required, properties):
required = required or []
properties = properties or {}
return [x for x in required if properties.get(x) is not None]
| en | 0.75973 | #' #' # note: don't shadow the `property` built-in # https://github.com/pglass/py-openapi-schema-to-json-schema/issues/10 | 2.282441 | 2 |
xixiang/services.py | LKI/xixiang | 15 | 6623094 | <gh_stars>10-100
import datetime
import http
import uuid
from urllib.parse import urlencode
import requests
import xixiang
class XiXiang:
MENU_TYPE_LUNCH = "2"
MENU_TYPE_DINNER = "4"
ORDER_SUCCESS = "2"
@classmethod
def login(cls, phone, password, openid=None):
"""
:rtype: XiXiang
"""
openid = openid or uuid.uuid4().hex
response = requests.post(xixiang.urls.login_url, data={"phone": phone, "password": password, "openid": openid})
if response.status_code == http.HTTPStatus.OK.value:
data = response.json()
if data["code"] == 1:
return cls(data["data"]["api_token"])
else:
raise xixiang.XiXiangLoginFail("{} 登录失败:{}".format(phone, data["message"]))
elif response.status_code == http.HTTPStatus.UNPROCESSABLE_ENTITY.value:
raise xixiang.XiXiangLoginFail("{} 登录失败:密码错误".format(phone))
raise xixiang.XiXiangLoginFail("{} 登录失败:服务器返回码 {}".format(phone, response.status_code))
def __init__(self, api_token):
self.api_token = api_token
self.company_id = None
self.menu_date = None
def get_companies(self):
companies = self.get(xixiang.urls.list_company_url)
self.company_id = companies[0]["company_id"]
return companies
def get_menus(self):
self.menu_date = str(datetime.date.today())
if not self.company_id:
self.get_companies()
return xixiang.Menu.load(self.get(xixiang.urls.list_menu_url))
def get_businesses(self, menu):
return xixiang.Business.load(self.get(xixiang.urls.list_url, {"mt": menu.menu_type}))
def get_items(self, business, menu):
"""
:type business: xixiang.models.Business
:type menu: xixiang.models.Menu
"""
return xixiang.Item.load(
self.get(xixiang.urls.cookbook_url, {"busid": business.business_id, "mt": menu.menu_type})
)
def add_item(self, item, num=1):
"""
:type item: xixiang.models.Item
:type num: int
"""
return self.post(
xixiang.urls.cart_add_url,
json={
"id": item.item_id,
"menu_id": item.menu_id,
"mt": item.menu_type,
"num": num,
"reserve_date": str(datetime.date.today()),
},
)
def get_addresses(self):
return xixiang.Address.load(self.get(xixiang.urls.user_address_url))
def add_order(self, address, menu):
return self.post(
xixiang.urls.order_add_url,
params={
"menuType": menu.menu_type,
"reserveDate": str(datetime.date.today()),
"companyId": self.company_id,
},
data={"address_id": address.address_id},
)
def get_orders(self, status="", page=1):
return self.get(xixiang.urls.order_list_url, params={"orderStatus": status, "page": page})
def get(self, url, params=None):
"""
:rtype: dict
"""
url = self._prepare_url(url, params)
response = requests.get(url)
data = response.json()
if data["code"] == 1:
return data["data"]
raise xixiang.XiXiangRequestError("请求失败:{}".format(data["message"]))
def post(self, url, *, params=None, data=None, json=None):
"""
:rtype: dict
"""
url = self._prepare_url(url, params)
response = requests.post(url, data=data, json=json)
data = response.json()
if data["code"] == 1:
return data["data"]
raise xixiang.XiXiangRequestError("请求失败:{}".format(data["message"]))
def _prepare_url(self, url, params):
if params is None:
params = {}
if self.company_id:
params.setdefault("companyId", self.company_id)
if self.menu_date:
params.setdefault("menu_date", self.menu_date)
params["api_token"] = self.api_token
return "{}?{}".format(url, urlencode(sorted(params.items())))
| import datetime
import http
import uuid
from urllib.parse import urlencode
import requests
import xixiang
class XiXiang:
MENU_TYPE_LUNCH = "2"
MENU_TYPE_DINNER = "4"
ORDER_SUCCESS = "2"
@classmethod
def login(cls, phone, password, openid=None):
"""
:rtype: XiXiang
"""
openid = openid or uuid.uuid4().hex
response = requests.post(xixiang.urls.login_url, data={"phone": phone, "password": password, "openid": openid})
if response.status_code == http.HTTPStatus.OK.value:
data = response.json()
if data["code"] == 1:
return cls(data["data"]["api_token"])
else:
raise xixiang.XiXiangLoginFail("{} 登录失败:{}".format(phone, data["message"]))
elif response.status_code == http.HTTPStatus.UNPROCESSABLE_ENTITY.value:
raise xixiang.XiXiangLoginFail("{} 登录失败:密码错误".format(phone))
raise xixiang.XiXiangLoginFail("{} 登录失败:服务器返回码 {}".format(phone, response.status_code))
def __init__(self, api_token):
self.api_token = api_token
self.company_id = None
self.menu_date = None
def get_companies(self):
companies = self.get(xixiang.urls.list_company_url)
self.company_id = companies[0]["company_id"]
return companies
def get_menus(self):
self.menu_date = str(datetime.date.today())
if not self.company_id:
self.get_companies()
return xixiang.Menu.load(self.get(xixiang.urls.list_menu_url))
def get_businesses(self, menu):
return xixiang.Business.load(self.get(xixiang.urls.list_url, {"mt": menu.menu_type}))
def get_items(self, business, menu):
"""
:type business: xixiang.models.Business
:type menu: xixiang.models.Menu
"""
return xixiang.Item.load(
self.get(xixiang.urls.cookbook_url, {"busid": business.business_id, "mt": menu.menu_type})
)
def add_item(self, item, num=1):
"""
:type item: xixiang.models.Item
:type num: int
"""
return self.post(
xixiang.urls.cart_add_url,
json={
"id": item.item_id,
"menu_id": item.menu_id,
"mt": item.menu_type,
"num": num,
"reserve_date": str(datetime.date.today()),
},
)
def get_addresses(self):
return xixiang.Address.load(self.get(xixiang.urls.user_address_url))
def add_order(self, address, menu):
return self.post(
xixiang.urls.order_add_url,
params={
"menuType": menu.menu_type,
"reserveDate": str(datetime.date.today()),
"companyId": self.company_id,
},
data={"address_id": address.address_id},
)
def get_orders(self, status="", page=1):
return self.get(xixiang.urls.order_list_url, params={"orderStatus": status, "page": page})
def get(self, url, params=None):
"""
:rtype: dict
"""
url = self._prepare_url(url, params)
response = requests.get(url)
data = response.json()
if data["code"] == 1:
return data["data"]
raise xixiang.XiXiangRequestError("请求失败:{}".format(data["message"]))
def post(self, url, *, params=None, data=None, json=None):
"""
:rtype: dict
"""
url = self._prepare_url(url, params)
response = requests.post(url, data=data, json=json)
data = response.json()
if data["code"] == 1:
return data["data"]
raise xixiang.XiXiangRequestError("请求失败:{}".format(data["message"]))
def _prepare_url(self, url, params):
if params is None:
params = {}
if self.company_id:
params.setdefault("companyId", self.company_id)
if self.menu_date:
params.setdefault("menu_date", self.menu_date)
params["api_token"] = self.api_token
return "{}?{}".format(url, urlencode(sorted(params.items()))) | en | 0.190398 | :rtype: XiXiang :type business: xixiang.models.Business :type menu: xixiang.models.Menu :type item: xixiang.models.Item :type num: int :rtype: dict :rtype: dict | 2.964294 | 3 |
tools/linked_list.py | niki4/leetcode_py3 | 0 | 6623095 | <reponame>niki4/leetcode_py3<gh_stars>0
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def get_linked_list_representation(node: ListNode) -> str:
list_values = list()
while node:
list_values.append(str(node.val))
node = node.next
return ' -> '.join(list_values)
def make_circulated_linked_list(seq):
""" Makes circulated linked list so that last item (tail) linked to the first item (head) """
head = make_linked_list_from_iterable(seq)
if not head:
return
node = head
while node and node.next:
node = node.next
node.next = head
return head
def make_linked_list_from_iterable(seq):
head = prev = None
for v in seq:
n = ListNode(v)
if not head:
head = prev = n
else:
prev.next = n
prev = n
return head
def traverse(head: ListNode):
values = []
seen = set()
node = head
while node:
if node in seen:
break
seen.add(node)
values.append(node.val)
node = node.next
return values
| # Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def get_linked_list_representation(node: ListNode) -> str:
list_values = list()
while node:
list_values.append(str(node.val))
node = node.next
return ' -> '.join(list_values)
def make_circulated_linked_list(seq):
""" Makes circulated linked list so that last item (tail) linked to the first item (head) """
head = make_linked_list_from_iterable(seq)
if not head:
return
node = head
while node and node.next:
node = node.next
node.next = head
return head
def make_linked_list_from_iterable(seq):
head = prev = None
for v in seq:
n = ListNode(v)
if not head:
head = prev = n
else:
prev.next = n
prev = n
return head
def traverse(head: ListNode):
values = []
seen = set()
node = head
while node:
if node in seen:
break
seen.add(node)
values.append(node.val)
node = node.next
return values | en | 0.713049 | # Definition for singly-linked list. Makes circulated linked list so that last item (tail) linked to the first item (head) | 3.932898 | 4 |
loader/loader.py | jeremyagray/django-loader | 0 | 6623096 | # ******************************************************************************
#
# django-loader, a configuration and secret loader for Django
#
# loader.py: main loader functions
#
# Copyright (C) 2021 <NAME> <<EMAIL>>.
#
# SPDX-License-Identifier: MIT
#
# ******************************************************************************
#
"""Load Django settings.
Load Django settings from defaults, files, or the environment, in that
order.
"""
import json
import os
import sys
import types
from pathlib import Path
import bespon
import toml
from django.core.exceptions import ImproperlyConfigured
from ruamel.yaml import YAML
from ruamel.yaml.error import YAMLError
def generate_secret_key():
"""Generate a secret key for a Django app.
Generate a secret key for a Django app, using
``django.core.management.utils.get_random_secret_key``.
Returns
-------
string
A random secret key.
"""
from django.core.management.utils import get_random_secret_key
return get_random_secret_key()
def load_secrets(fn=".env", prefix="DJANGO_ENV_", **kwargs):
"""Load a list of configuration variables.
Return a dictionary of configuration variables, as loaded from a
configuration file or the environment. Values passed in as
``args`` or as the value in ``kwargs`` will be used as the
configuration variable's default value if one is not found in the
configuration file or environment.
Parameters
----------
fn : string, default=".env"
Configuration filename, defaults to ``.env``. May be in TOML,
JSON, YAML, or BespON formats. Formats will be attempted in this
order.
prefix : string, default="DJANGO_ENV_"
Prefix for environment variables. This prefix will be
prepended to all variable names before searching for them in
the environment.
kwargs : dict, optional
Dictionary with configuration variables as keys and default
values as values.
Returns
-------
dict
A dictionary of configuration variables and their values.
"""
return merge(kwargs, load_file(fn), load_environment(prefix))
def merge(defaults, file, env):
"""Merge configuration from defaults, file, and environment."""
config = defaults
# Merge in file options, if they exist in the defaults.
for (k, v) in file.items():
if k in config:
config[k] = v
# Merge in environment options, if they exist in the defaults.
for (k, v) in env.items():
if k in config:
config[k] = v
return config
def load_file(fn, raise_bad_format=False):
"""Attempt to load configuration variables from ``fn``.
Attempt to load configuration variables from ``fn``. If ``fn``
does not exist or is not a recognized format, return an empty dict
unless ``raise_bad_format`` is ``True``.
Parameters
----------
fn : string
Filename from which to load configuration values.
raise_bad_format : boolean, default=False
Determine whether to raise
``django.core.exceptions.ImproperlyConfigured`` if the file
format is not recognized. Default is ``False``.
Returns
-------
dict
A dictionary, possibly empty, of configuration variables and
values.
Raises
------
django.core.exceptions.ImproperlyConfigured
Raises an ``ImproperlyConfigured`` exception if the file
format is not recognized and ``raise_bad_format`` is ``True``.
"""
# Determine if the file actually exists, and bail if not.
secrets = {}
if not Path(fn).is_file():
return secrets
# Attempt to load TOML, since python.
with open(fn, "r") as f:
try:
secrets = toml.load(f)
except (toml.TomlDecodeError):
pass
# Attempt to load JSON.
with open(fn, "r") as f:
try:
secrets = json.load(f)
except (json.JSONDecodeError):
pass
# Attempt to load YAML, with ruamel.yaml and YAML 1.2.
# Overachiever.
with open(fn, "r") as f:
try:
yaml = YAML(typ="safe")
secrets = yaml.load(f)
except (YAMLError):
pass
# Attempt to load BespON. Geek.
with open(fn, "r") as f:
try:
secrets = bespon.load(f)
except (bespon.erring.DecodingException):
# Everything failed, so raise.
if raise_bad_format:
raise ImproperlyConfigured(
f"Configuration file {fn} is not a recognized format."
)
return secrets
def _keys_are_indices(d):
"""Determine if the keys of a dict are list indices."""
# All integers?
keys = []
for k in d.keys():
try:
keys.append(int(k))
except (ValueError):
return False
keys = sorted(keys)
# Zero start?
if min(keys) != 0:
return False
# Consecutive?
if keys != list(range(0, max(keys) + 1)):
return False
return True
def _convert_dict_to_list(d):
"""Convert a list-style dict to a list."""
keys = sorted(d.keys())
the_list = []
for k in keys:
the_list.append(d[k])
return the_list
def _convert_listdict_to_list(ds):
"""Convert lists as dicts to lists in a data structure."""
for (k, v) in ds.items():
if isinstance(ds[k], dict):
# If the item points a dict, descend.
ds[k] = _convert_listdict_to_list(ds[k])
# We're back. Now check if the dict is a list-style dict
# and maybe convert to a list.
if _keys_are_indices(ds[k]):
ds[k] = _convert_dict_to_list(ds[k])
return ds
def load_environment(prefix="DJANGO_ENV_"):
"""Load Django configuration variables from the enviroment.
This function searches the environment for variables prepended
with ``prefix``. Currently, this function only reliably works for
string variables, but hopefully will work for other types,
dictionaries, and lists in the future.
Parameters
----------
prefix : string, default="DJANGO_ENV_"
Prefix for environment variables. This prefix should be
prepended to all valid variable names in the environment.
Returns
-------
dict
A dictionary, possibly empty, of configuration variables and
values.
"""
config = {}
for (key, value) in os.environ.items():
if key.startswith(prefix):
# Find the prefixed values and strip the prefix.
if sys.version_info >= (3, 6) and sys.version_info < (3, 9):
name = key[len(prefix) :]
else:
name = key.removeprefix(prefix)
if "__" not in name:
# Find the non-dict and non-list pairs and add them to
# the dict.
config[name] = value
else:
# Handle the flattened data structures, treating the
# list type variables as dicts.
# Based on:
# https://gist.github.com/fmder/494aaa2dd6f8c428cede
keys = name.split("__")
sub_config = config
for k in keys[:-1]:
try:
if not isinstance(sub_config[k], dict):
raise ImproperlyConfigured(
f"{k} is defined multiple times in the environment."
)
sub_config = sub_config[k]
except (KeyError):
sub_config[k] = {}
sub_config = sub_config[k]
sub_config[keys[-1]] = value
config = _convert_listdict_to_list(config)
return config
def dump_environment(config, prefix="DJANGO_ENV_", export=True):
"""Dump configuration as an environment variable string.
Parameters
----------
config : dict
The configuration dict.
prefix : string, default="DJANGO_ENV_"
Prefix for environment variables. This prefix should be
prepended to all valid variable names in the environment.
export : boolean, default=True
Prepend each environment variable string with "export ", or
not.
Returns
-------
string
The current configuration as a string setting environment
variables.
"""
stack = []
dumps = []
if export:
exp = "export "
else:
exp = ""
# Convert the config dict into a list (stack).
for (k, v) in config.items():
stack.append((k, v))
while stack:
(k, v) = stack.pop(0)
if isinstance(v, list):
for (i, sv) in enumerate(v):
stack.append((f"{k}_{i}", sv))
elif isinstance(v, dict):
for (sk, sv) in v.items():
stack.append((f"{k}_{sk}", sv))
else:
dumps.append(f"{str(k)}='{str(v)}'")
return "\n".join(f"{exp}{prefix}{line}" for line in dumps)
def validate_not_empty_string(name, val):
"""Validate that ``val`` is not an empty string.
Validate that ``val`` is not an empty string.
Parameters
----------
val : any
Configuration variable to validate.
Returns
-------
boolean
``True`` if ``val`` is not an empty string.
Raises
------
django.core.exceptions.ImproperlyConfigured
Raises an ``ImproperlyConfigured`` exception on empty strings,
with an error message.
"""
if val == "":
raise ImproperlyConfigured(f"{name} is an empty string and should not be")
return True
def validate_falsy(name, val):
"""Validate that ``val`` is falsy.
Validate that ``val`` is falsy according to
https://docs.python.org/3/library/stdtypes.html#truth-value-testing.
Parameters
----------
val : any
Configuration variable to validate.
Returns
-------
boolean
``True`` if ``val`` is falsy.
Raises
------
django.core.exceptions.ImproperlyConfigured
Raises an ``ImproperlyConfigured`` exception on truthy values,
with an error message.
"""
if val:
raise ImproperlyConfigured(
f"{name} has value {val} which is truthy, but should be falsy"
)
return True
def validate_truthy(name, val):
"""Validate that ``val`` is truthy.
Validate that ``val`` is truthy according to
https://docs.python.org/3/library/stdtypes.html#truth-value-testing.
Parameters
----------
val : any
Configuration variable to validate.
Returns
-------
boolean
``True`` if ``val`` is truthy.
Raises
------
django.core.exceptions.ImproperlyConfigured
Raises an ``ImproperlyConfigured`` exception on falsy values,
with an error message.
"""
if not val:
raise ImproperlyConfigured(
f"{name} has value {val} which is falsy, but should be truthy"
)
return True
# def set_or_fail_on_unset(val):
# """Raise ``ImproperlyConfigured()`` if ``val`` is not set.
# Return the configuration value if set, otherwise raise
# ``django.core.exceptions.ImproperlyConfigured()`` to abort.
# Parameters
# ----------
# val : string
# Configuration variable that should be set to a value.
# Returns
# -------
# string
# The variable value, if set.
# """
# if not val:
# raise ImproperlyConfigured("A required configuration variable is not set.")
# return val
# def _validate(name, val, validation=[]):
# """Validate a django configuration variable."""
# env_name = "DJANGO_" + name
# if isinstance(validation, types.FunctionType):
# try:
# return validation(val)
# except ImproperlyConfigured:
# raise
# else:
# if len(validation) > 0:
# if not (val in validation):
# raise ImproperlyConfigured(
# f"{name} can not have value {val};"
# f" must be one of [{', '.join(validation)}]."
# )
# return
# print(f"{name} loaded from {env_name}.")
# return val
def dump_secrets(fmt="TOML", **kwargs):
"""Dump a secrets dictionary to the specified format.
Dump a secrets dictionary to the specified format, defaulting to
TOML.
Parameters
----------
fmt : string, default="TOML"
The dump format, one of ``TOML``, ``JSON``, ``YAML``,
``BespON``, or ``ENV``.
kwargs : dict
A dictionary of configuration variables.
"""
if fmt == "TOML":
return toml.dumps(kwargs)
elif fmt == "JSON":
return json.dumps(kwargs)
elif fmt == "YAML":
# Let's jump through some hoops for the sake of streams.
# https://yaml.readthedocs.io/en/latest/example.html#output-of-dump-as-a-string
from ruamel.yaml.compat import StringIO
stream = StringIO()
yaml = YAML(typ="safe")
yaml.dump(kwargs, stream)
return stream.getvalue()
elif fmt == "BespON":
return bespon.dumps(kwargs)
else:
return dump_environment(kwargs)
def main():
"""Run as script, to access ``dump()`` functions."""
# Desired functions:
# create SECRET_KEY
# load and dump environment
# cli help
# cli copyright/license
print(dump_secrets(**load_secrets(**{"ALLOWED_HOSTS": ["bob is your uncle"]})))
if __name__ == "__main__":
main()
| # ******************************************************************************
#
# django-loader, a configuration and secret loader for Django
#
# loader.py: main loader functions
#
# Copyright (C) 2021 <NAME> <<EMAIL>>.
#
# SPDX-License-Identifier: MIT
#
# ******************************************************************************
#
"""Load Django settings.
Load Django settings from defaults, files, or the environment, in that
order.
"""
import json
import os
import sys
import types
from pathlib import Path
import bespon
import toml
from django.core.exceptions import ImproperlyConfigured
from ruamel.yaml import YAML
from ruamel.yaml.error import YAMLError
def generate_secret_key():
"""Generate a secret key for a Django app.
Generate a secret key for a Django app, using
``django.core.management.utils.get_random_secret_key``.
Returns
-------
string
A random secret key.
"""
from django.core.management.utils import get_random_secret_key
return get_random_secret_key()
def load_secrets(fn=".env", prefix="DJANGO_ENV_", **kwargs):
"""Load a list of configuration variables.
Return a dictionary of configuration variables, as loaded from a
configuration file or the environment. Values passed in as
``args`` or as the value in ``kwargs`` will be used as the
configuration variable's default value if one is not found in the
configuration file or environment.
Parameters
----------
fn : string, default=".env"
Configuration filename, defaults to ``.env``. May be in TOML,
JSON, YAML, or BespON formats. Formats will be attempted in this
order.
prefix : string, default="DJANGO_ENV_"
Prefix for environment variables. This prefix will be
prepended to all variable names before searching for them in
the environment.
kwargs : dict, optional
Dictionary with configuration variables as keys and default
values as values.
Returns
-------
dict
A dictionary of configuration variables and their values.
"""
return merge(kwargs, load_file(fn), load_environment(prefix))
def merge(defaults, file, env):
"""Merge configuration from defaults, file, and environment."""
config = defaults
# Merge in file options, if they exist in the defaults.
for (k, v) in file.items():
if k in config:
config[k] = v
# Merge in environment options, if they exist in the defaults.
for (k, v) in env.items():
if k in config:
config[k] = v
return config
def load_file(fn, raise_bad_format=False):
"""Attempt to load configuration variables from ``fn``.
Attempt to load configuration variables from ``fn``. If ``fn``
does not exist or is not a recognized format, return an empty dict
unless ``raise_bad_format`` is ``True``.
Parameters
----------
fn : string
Filename from which to load configuration values.
raise_bad_format : boolean, default=False
Determine whether to raise
``django.core.exceptions.ImproperlyConfigured`` if the file
format is not recognized. Default is ``False``.
Returns
-------
dict
A dictionary, possibly empty, of configuration variables and
values.
Raises
------
django.core.exceptions.ImproperlyConfigured
Raises an ``ImproperlyConfigured`` exception if the file
format is not recognized and ``raise_bad_format`` is ``True``.
"""
# Determine if the file actually exists, and bail if not.
secrets = {}
if not Path(fn).is_file():
return secrets
# Attempt to load TOML, since python.
with open(fn, "r") as f:
try:
secrets = toml.load(f)
except (toml.TomlDecodeError):
pass
# Attempt to load JSON.
with open(fn, "r") as f:
try:
secrets = json.load(f)
except (json.JSONDecodeError):
pass
# Attempt to load YAML, with ruamel.yaml and YAML 1.2.
# Overachiever.
with open(fn, "r") as f:
try:
yaml = YAML(typ="safe")
secrets = yaml.load(f)
except (YAMLError):
pass
# Attempt to load BespON. Geek.
with open(fn, "r") as f:
try:
secrets = bespon.load(f)
except (bespon.erring.DecodingException):
# Everything failed, so raise.
if raise_bad_format:
raise ImproperlyConfigured(
f"Configuration file {fn} is not a recognized format."
)
return secrets
def _keys_are_indices(d):
"""Determine if the keys of a dict are list indices."""
# All integers?
keys = []
for k in d.keys():
try:
keys.append(int(k))
except (ValueError):
return False
keys = sorted(keys)
# Zero start?
if min(keys) != 0:
return False
# Consecutive?
if keys != list(range(0, max(keys) + 1)):
return False
return True
def _convert_dict_to_list(d):
"""Convert a list-style dict to a list."""
keys = sorted(d.keys())
the_list = []
for k in keys:
the_list.append(d[k])
return the_list
def _convert_listdict_to_list(ds):
"""Convert lists as dicts to lists in a data structure."""
for (k, v) in ds.items():
if isinstance(ds[k], dict):
# If the item points a dict, descend.
ds[k] = _convert_listdict_to_list(ds[k])
# We're back. Now check if the dict is a list-style dict
# and maybe convert to a list.
if _keys_are_indices(ds[k]):
ds[k] = _convert_dict_to_list(ds[k])
return ds
def load_environment(prefix="DJANGO_ENV_"):
"""Load Django configuration variables from the enviroment.
This function searches the environment for variables prepended
with ``prefix``. Currently, this function only reliably works for
string variables, but hopefully will work for other types,
dictionaries, and lists in the future.
Parameters
----------
prefix : string, default="DJANGO_ENV_"
Prefix for environment variables. This prefix should be
prepended to all valid variable names in the environment.
Returns
-------
dict
A dictionary, possibly empty, of configuration variables and
values.
"""
config = {}
for (key, value) in os.environ.items():
if key.startswith(prefix):
# Find the prefixed values and strip the prefix.
if sys.version_info >= (3, 6) and sys.version_info < (3, 9):
name = key[len(prefix) :]
else:
name = key.removeprefix(prefix)
if "__" not in name:
# Find the non-dict and non-list pairs and add them to
# the dict.
config[name] = value
else:
# Handle the flattened data structures, treating the
# list type variables as dicts.
# Based on:
# https://gist.github.com/fmder/494aaa2dd6f8c428cede
keys = name.split("__")
sub_config = config
for k in keys[:-1]:
try:
if not isinstance(sub_config[k], dict):
raise ImproperlyConfigured(
f"{k} is defined multiple times in the environment."
)
sub_config = sub_config[k]
except (KeyError):
sub_config[k] = {}
sub_config = sub_config[k]
sub_config[keys[-1]] = value
config = _convert_listdict_to_list(config)
return config
def dump_environment(config, prefix="DJANGO_ENV_", export=True):
"""Dump configuration as an environment variable string.
Parameters
----------
config : dict
The configuration dict.
prefix : string, default="DJANGO_ENV_"
Prefix for environment variables. This prefix should be
prepended to all valid variable names in the environment.
export : boolean, default=True
Prepend each environment variable string with "export ", or
not.
Returns
-------
string
The current configuration as a string setting environment
variables.
"""
stack = []
dumps = []
if export:
exp = "export "
else:
exp = ""
# Convert the config dict into a list (stack).
for (k, v) in config.items():
stack.append((k, v))
while stack:
(k, v) = stack.pop(0)
if isinstance(v, list):
for (i, sv) in enumerate(v):
stack.append((f"{k}_{i}", sv))
elif isinstance(v, dict):
for (sk, sv) in v.items():
stack.append((f"{k}_{sk}", sv))
else:
dumps.append(f"{str(k)}='{str(v)}'")
return "\n".join(f"{exp}{prefix}{line}" for line in dumps)
def validate_not_empty_string(name, val):
"""Validate that ``val`` is not an empty string.
Validate that ``val`` is not an empty string.
Parameters
----------
val : any
Configuration variable to validate.
Returns
-------
boolean
``True`` if ``val`` is not an empty string.
Raises
------
django.core.exceptions.ImproperlyConfigured
Raises an ``ImproperlyConfigured`` exception on empty strings,
with an error message.
"""
if val == "":
raise ImproperlyConfigured(f"{name} is an empty string and should not be")
return True
def validate_falsy(name, val):
"""Validate that ``val`` is falsy.
Validate that ``val`` is falsy according to
https://docs.python.org/3/library/stdtypes.html#truth-value-testing.
Parameters
----------
val : any
Configuration variable to validate.
Returns
-------
boolean
``True`` if ``val`` is falsy.
Raises
------
django.core.exceptions.ImproperlyConfigured
Raises an ``ImproperlyConfigured`` exception on truthy values,
with an error message.
"""
if val:
raise ImproperlyConfigured(
f"{name} has value {val} which is truthy, but should be falsy"
)
return True
def validate_truthy(name, val):
"""Validate that ``val`` is truthy.
Validate that ``val`` is truthy according to
https://docs.python.org/3/library/stdtypes.html#truth-value-testing.
Parameters
----------
val : any
Configuration variable to validate.
Returns
-------
boolean
``True`` if ``val`` is truthy.
Raises
------
django.core.exceptions.ImproperlyConfigured
Raises an ``ImproperlyConfigured`` exception on falsy values,
with an error message.
"""
if not val:
raise ImproperlyConfigured(
f"{name} has value {val} which is falsy, but should be truthy"
)
return True
# def set_or_fail_on_unset(val):
# """Raise ``ImproperlyConfigured()`` if ``val`` is not set.
# Return the configuration value if set, otherwise raise
# ``django.core.exceptions.ImproperlyConfigured()`` to abort.
# Parameters
# ----------
# val : string
# Configuration variable that should be set to a value.
# Returns
# -------
# string
# The variable value, if set.
# """
# if not val:
# raise ImproperlyConfigured("A required configuration variable is not set.")
# return val
# def _validate(name, val, validation=[]):
# """Validate a django configuration variable."""
# env_name = "DJANGO_" + name
# if isinstance(validation, types.FunctionType):
# try:
# return validation(val)
# except ImproperlyConfigured:
# raise
# else:
# if len(validation) > 0:
# if not (val in validation):
# raise ImproperlyConfigured(
# f"{name} can not have value {val};"
# f" must be one of [{', '.join(validation)}]."
# )
# return
# print(f"{name} loaded from {env_name}.")
# return val
def dump_secrets(fmt="TOML", **kwargs):
"""Dump a secrets dictionary to the specified format.
Dump a secrets dictionary to the specified format, defaulting to
TOML.
Parameters
----------
fmt : string, default="TOML"
The dump format, one of ``TOML``, ``JSON``, ``YAML``,
``BespON``, or ``ENV``.
kwargs : dict
A dictionary of configuration variables.
"""
if fmt == "TOML":
return toml.dumps(kwargs)
elif fmt == "JSON":
return json.dumps(kwargs)
elif fmt == "YAML":
# Let's jump through some hoops for the sake of streams.
# https://yaml.readthedocs.io/en/latest/example.html#output-of-dump-as-a-string
from ruamel.yaml.compat import StringIO
stream = StringIO()
yaml = YAML(typ="safe")
yaml.dump(kwargs, stream)
return stream.getvalue()
elif fmt == "BespON":
return bespon.dumps(kwargs)
else:
return dump_environment(kwargs)
def main():
"""Run as script, to access ``dump()`` functions."""
# Desired functions:
# create SECRET_KEY
# load and dump environment
# cli help
# cli copyright/license
print(dump_secrets(**load_secrets(**{"ALLOWED_HOSTS": ["bob is your uncle"]})))
if __name__ == "__main__":
main()
| en | 0.638884 | # ****************************************************************************** # # django-loader, a configuration and secret loader for Django # # loader.py: main loader functions # # Copyright (C) 2021 <NAME> <<EMAIL>>. # # SPDX-License-Identifier: MIT # # ****************************************************************************** # Load Django settings. Load Django settings from defaults, files, or the environment, in that order. Generate a secret key for a Django app. Generate a secret key for a Django app, using ``django.core.management.utils.get_random_secret_key``. Returns ------- string A random secret key. Load a list of configuration variables. Return a dictionary of configuration variables, as loaded from a configuration file or the environment. Values passed in as ``args`` or as the value in ``kwargs`` will be used as the configuration variable's default value if one is not found in the configuration file or environment. Parameters ---------- fn : string, default=".env" Configuration filename, defaults to ``.env``. May be in TOML, JSON, YAML, or BespON formats. Formats will be attempted in this order. prefix : string, default="DJANGO_ENV_" Prefix for environment variables. This prefix will be prepended to all variable names before searching for them in the environment. kwargs : dict, optional Dictionary with configuration variables as keys and default values as values. Returns ------- dict A dictionary of configuration variables and their values. Merge configuration from defaults, file, and environment. # Merge in file options, if they exist in the defaults. # Merge in environment options, if they exist in the defaults. Attempt to load configuration variables from ``fn``. Attempt to load configuration variables from ``fn``. If ``fn`` does not exist or is not a recognized format, return an empty dict unless ``raise_bad_format`` is ``True``. Parameters ---------- fn : string Filename from which to load configuration values. raise_bad_format : boolean, default=False Determine whether to raise ``django.core.exceptions.ImproperlyConfigured`` if the file format is not recognized. Default is ``False``. Returns ------- dict A dictionary, possibly empty, of configuration variables and values. Raises ------ django.core.exceptions.ImproperlyConfigured Raises an ``ImproperlyConfigured`` exception if the file format is not recognized and ``raise_bad_format`` is ``True``. # Determine if the file actually exists, and bail if not. # Attempt to load TOML, since python. # Attempt to load JSON. # Attempt to load YAML, with ruamel.yaml and YAML 1.2. # Overachiever. # Attempt to load BespON. Geek. # Everything failed, so raise. Determine if the keys of a dict are list indices. # All integers? # Zero start? # Consecutive? Convert a list-style dict to a list. Convert lists as dicts to lists in a data structure. # If the item points a dict, descend. # We're back. Now check if the dict is a list-style dict # and maybe convert to a list. Load Django configuration variables from the enviroment. This function searches the environment for variables prepended with ``prefix``. Currently, this function only reliably works for string variables, but hopefully will work for other types, dictionaries, and lists in the future. Parameters ---------- prefix : string, default="DJANGO_ENV_" Prefix for environment variables. This prefix should be prepended to all valid variable names in the environment. Returns ------- dict A dictionary, possibly empty, of configuration variables and values. # Find the prefixed values and strip the prefix. # Find the non-dict and non-list pairs and add them to # the dict. # Handle the flattened data structures, treating the # list type variables as dicts. # Based on: # https://gist.github.com/fmder/494aaa2dd6f8c428cede Dump configuration as an environment variable string. Parameters ---------- config : dict The configuration dict. prefix : string, default="DJANGO_ENV_" Prefix for environment variables. This prefix should be prepended to all valid variable names in the environment. export : boolean, default=True Prepend each environment variable string with "export ", or not. Returns ------- string The current configuration as a string setting environment variables. # Convert the config dict into a list (stack). Validate that ``val`` is not an empty string. Validate that ``val`` is not an empty string. Parameters ---------- val : any Configuration variable to validate. Returns ------- boolean ``True`` if ``val`` is not an empty string. Raises ------ django.core.exceptions.ImproperlyConfigured Raises an ``ImproperlyConfigured`` exception on empty strings, with an error message. Validate that ``val`` is falsy. Validate that ``val`` is falsy according to https://docs.python.org/3/library/stdtypes.html#truth-value-testing. Parameters ---------- val : any Configuration variable to validate. Returns ------- boolean ``True`` if ``val`` is falsy. Raises ------ django.core.exceptions.ImproperlyConfigured Raises an ``ImproperlyConfigured`` exception on truthy values, with an error message. Validate that ``val`` is truthy. Validate that ``val`` is truthy according to https://docs.python.org/3/library/stdtypes.html#truth-value-testing. Parameters ---------- val : any Configuration variable to validate. Returns ------- boolean ``True`` if ``val`` is truthy. Raises ------ django.core.exceptions.ImproperlyConfigured Raises an ``ImproperlyConfigured`` exception on falsy values, with an error message. # def set_or_fail_on_unset(val): # """Raise ``ImproperlyConfigured()`` if ``val`` is not set. # Return the configuration value if set, otherwise raise # ``django.core.exceptions.ImproperlyConfigured()`` to abort. # Parameters # ---------- # val : string # Configuration variable that should be set to a value. # Returns # ------- # string # The variable value, if set. # """ # if not val: # raise ImproperlyConfigured("A required configuration variable is not set.") # return val # def _validate(name, val, validation=[]): # """Validate a django configuration variable.""" # env_name = "DJANGO_" + name # if isinstance(validation, types.FunctionType): # try: # return validation(val) # except ImproperlyConfigured: # raise # else: # if len(validation) > 0: # if not (val in validation): # raise ImproperlyConfigured( # f"{name} can not have value {val};" # f" must be one of [{', '.join(validation)}]." # ) # return # print(f"{name} loaded from {env_name}.") # return val Dump a secrets dictionary to the specified format. Dump a secrets dictionary to the specified format, defaulting to TOML. Parameters ---------- fmt : string, default="TOML" The dump format, one of ``TOML``, ``JSON``, ``YAML``, ``BespON``, or ``ENV``. kwargs : dict A dictionary of configuration variables. # Let's jump through some hoops for the sake of streams. # https://yaml.readthedocs.io/en/latest/example.html#output-of-dump-as-a-string Run as script, to access ``dump()`` functions. # Desired functions: # create SECRET_KEY # load and dump environment # cli help # cli copyright/license | 2.496598 | 2 |
examples/trials/cifar10_grad_match/cords/selectionstrategies/supervisedlearning/__init__.py | savan77/nni | 0 | 6623097 | from .craigstrategy import CRAIGStrategy
from .dataselectionstrategy import DataSelectionStrategy
from .glisterstrategy import GLISTERStrategy
from .randomstrategy import RandomStrategy
from .submodularselectionstrategy import SubmodularSelectionStrategy
from .ompgradmatchstrategy import OMPGradMatchStrategy
__version__ = '0.0.4' | from .craigstrategy import CRAIGStrategy
from .dataselectionstrategy import DataSelectionStrategy
from .glisterstrategy import GLISTERStrategy
from .randomstrategy import RandomStrategy
from .submodularselectionstrategy import SubmodularSelectionStrategy
from .ompgradmatchstrategy import OMPGradMatchStrategy
__version__ = '0.0.4' | none | 1 | 1.048148 | 1 | |
Observability/logging-example.py | kraluc/DevCore | 0 | 6623098 | <filename>Observability/logging-example.py
#!/bin/env python
import logging
# Set logging level
logging.basicConfig(level=logging.INFO)
logging.info('This will get logged')
logging.error('This will get logged too')
logging.debug('This will NOT get logged')
def doSomething():
raise
try:
doSomething()
except:
logging.critical('This will be logged in case of an error') | <filename>Observability/logging-example.py
#!/bin/env python
import logging
# Set logging level
logging.basicConfig(level=logging.INFO)
logging.info('This will get logged')
logging.error('This will get logged too')
logging.debug('This will NOT get logged')
def doSomething():
raise
try:
doSomething()
except:
logging.critical('This will be logged in case of an error') | en | 0.351013 | #!/bin/env python # Set logging level | 2.959316 | 3 |
21_Classes_Objects/01_Classes.py | jmmedel/Python-Reference | 0 | 6623099 | """
Author: <NAME>
Tutorial 21 : Classes Objects
"""
"""
Python Classes/Objects
Python is an object oriented programming language.
Almost everything in Python is an object, with its properties and methods.
A Class is like an object constructor, or a "blueprint" for creating objects.
Create a Class
To create a class, use the keyword class:
"""
class MyClass:
x = 5
print(MyClass)
| """
Author: <NAME>
Tutorial 21 : Classes Objects
"""
"""
Python Classes/Objects
Python is an object oriented programming language.
Almost everything in Python is an object, with its properties and methods.
A Class is like an object constructor, or a "blueprint" for creating objects.
Create a Class
To create a class, use the keyword class:
"""
class MyClass:
x = 5
print(MyClass)
| en | 0.863824 | Author: <NAME> Tutorial 21 : Classes Objects Python Classes/Objects Python is an object oriented programming language. Almost everything in Python is an object, with its properties and methods. A Class is like an object constructor, or a "blueprint" for creating objects. Create a Class To create a class, use the keyword class: | 4.052357 | 4 |
organiser/log.py | Tauseef-Hilal/DesktopOrganiser | 3 | 6623100 | import os
import logging
from logging.handlers import RotatingFileHandler
from datetime import date
usr_dir = os.path.join(os.getcwd().split(os.getlogin())[0], os.getlogin())
desktop = os.path.join(usr_dir, "Desktop")
target = os.path.join(desktop, "Target")
log_folder = os.path.join(target, "Log")
if not os.path.isdir(target):
os.mkdir(target)
if not os.path.isdir(log_folder):
os.mkdir(log_folder)
logger = logging.getLogger(__name__)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(message)s')
handler = RotatingFileHandler(os.path.join(log_folder, f"{date.today()}.log"))
logger.addHandler(handler)
logger.setLevel(logging.INFO)
handler.setFormatter(formatter)
| import os
import logging
from logging.handlers import RotatingFileHandler
from datetime import date
usr_dir = os.path.join(os.getcwd().split(os.getlogin())[0], os.getlogin())
desktop = os.path.join(usr_dir, "Desktop")
target = os.path.join(desktop, "Target")
log_folder = os.path.join(target, "Log")
if not os.path.isdir(target):
os.mkdir(target)
if not os.path.isdir(log_folder):
os.mkdir(log_folder)
logger = logging.getLogger(__name__)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(message)s')
handler = RotatingFileHandler(os.path.join(log_folder, f"{date.today()}.log"))
logger.addHandler(handler)
logger.setLevel(logging.INFO)
handler.setFormatter(formatter)
| none | 1 | 2.727565 | 3 | |
python/src/stacks_and_queues.py | marvincolgin/data-structures-and-algorythms | 5 | 6623101 | import sys
sys.path.insert(0, '../linked_list')
from link_list import LinkList
# ********************************
class Stack():
_data = None
def __init__(self):
self._data = LinkList()
def count(self) -> int:
return self._data.count()
def pop(self) -> object:
b, val = self._data.peekHead()
if b:
self._data.remove(val)
return val
def push(self, val: object) -> bool:
self._data.insert(val)
return True
def peek(self) -> [bool, object]:
return self._data.peekHead()
# *********************************
class Queue():
def __init__(self):
self._data = LinkList()
def count(self) -> int:
return self._data.count()
def toStr(self) -> str:
return self._data.toStr()
def enqueue(self, val) -> bool:
# Add a value to the queue
return self._data.append(val)
def dequeue(self, val) -> bool:
# Remove entry from queue with a given value
# NOTE: will only remove the first element found with val
return self._data.remove(val)
def peek(self) -> [bool, object]:
# Get value from the head of the queue (without removing it)
return self._data.peekHead()
| import sys
sys.path.insert(0, '../linked_list')
from link_list import LinkList
# ********************************
class Stack():
_data = None
def __init__(self):
self._data = LinkList()
def count(self) -> int:
return self._data.count()
def pop(self) -> object:
b, val = self._data.peekHead()
if b:
self._data.remove(val)
return val
def push(self, val: object) -> bool:
self._data.insert(val)
return True
def peek(self) -> [bool, object]:
return self._data.peekHead()
# *********************************
class Queue():
def __init__(self):
self._data = LinkList()
def count(self) -> int:
return self._data.count()
def toStr(self) -> str:
return self._data.toStr()
def enqueue(self, val) -> bool:
# Add a value to the queue
return self._data.append(val)
def dequeue(self, val) -> bool:
# Remove entry from queue with a given value
# NOTE: will only remove the first element found with val
return self._data.remove(val)
def peek(self) -> [bool, object]:
# Get value from the head of the queue (without removing it)
return self._data.peekHead()
| en | 0.706292 | # ******************************** # ********************************* # Add a value to the queue # Remove entry from queue with a given value # NOTE: will only remove the first element found with val # Get value from the head of the queue (without removing it) | 3.574613 | 4 |
2020/day10_sol.py | vladan-stojnic/AdventOfCode | 0 | 6623102 | <reponame>vladan-stojnic/AdventOfCode
from collections import Counter
from functools import lru_cache
def read_input(path):
with open(path, 'r') as f:
data = f.read()
data = data.splitlines()
data = [int(d) for d in data]
return data
@lru_cache
def weight(val, m):
global data_sorted_set
if val == m:
return 1
w = 0
for i in range(1, 4):
if (val + i) in data_sorted_set:
w += weight(val+i, m)
return w
data = read_input('day10')
# Part 1
data_sorted = sorted(data)
diffs = [data_sorted[i]-data_sorted[i-1] for i in range(1, len(data_sorted))]
diffs.insert(0, data_sorted[0])
counts = Counter(diffs)
print(counts[1]*(counts[3]+1))
# Part 2
data_sorted_set = set(data_sorted)
ww = 0
for ds in data_sorted[:3]:
if ds <= 3:
ww += weight(ds, data_sorted[-1])
print(ww) | from collections import Counter
from functools import lru_cache
def read_input(path):
with open(path, 'r') as f:
data = f.read()
data = data.splitlines()
data = [int(d) for d in data]
return data
@lru_cache
def weight(val, m):
global data_sorted_set
if val == m:
return 1
w = 0
for i in range(1, 4):
if (val + i) in data_sorted_set:
w += weight(val+i, m)
return w
data = read_input('day10')
# Part 1
data_sorted = sorted(data)
diffs = [data_sorted[i]-data_sorted[i-1] for i in range(1, len(data_sorted))]
diffs.insert(0, data_sorted[0])
counts = Counter(diffs)
print(counts[1]*(counts[3]+1))
# Part 2
data_sorted_set = set(data_sorted)
ww = 0
for ds in data_sorted[:3]:
if ds <= 3:
ww += weight(ds, data_sorted[-1])
print(ww) | en | 0.538791 | # Part 1 # Part 2 | 3.507862 | 4 |
backend/api/models.py | TChi91/drf-reactjs | 0 | 6623103 | <gh_stars>0
from django.db import models
from rest_framework import serializers
class Message(models.Model):
subject = models.CharField(max_length=200)
body = models.TextField()
| from django.db import models
from rest_framework import serializers
class Message(models.Model):
subject = models.CharField(max_length=200)
body = models.TextField() | none | 1 | 2.038357 | 2 | |
examples/quadratic.py | seba-1511/randopt | 115 | 6623104 | #!/usr/bin/env python3
import randopt as ro
from random import random
def loss(x, y):
return [(x**2 + y**2 + random()) / i for i in range(1, 51)]
if __name__ == '__main__':
exp = ro.Experiment('quadratic', params={
'x': ro.Gaussian(),
'y': ro.Uniform(-0.5, 0.5)
})
for _ in range(20):
exp.sample_all_params()
conv = loss(exp.x, exp.y)
exp.add_result(conv[-1], data={
'convergence': conv
})
| #!/usr/bin/env python3
import randopt as ro
from random import random
def loss(x, y):
return [(x**2 + y**2 + random()) / i for i in range(1, 51)]
if __name__ == '__main__':
exp = ro.Experiment('quadratic', params={
'x': ro.Gaussian(),
'y': ro.Uniform(-0.5, 0.5)
})
for _ in range(20):
exp.sample_all_params()
conv = loss(exp.x, exp.y)
exp.add_result(conv[-1], data={
'convergence': conv
})
| fr | 0.221828 | #!/usr/bin/env python3 | 3.1776 | 3 |
py_tdlib/constructors/authorization_state_ready.py | Mr-TelegramBot/python-tdlib | 24 | 6623105 | from ..factory import Type
class authorizationStateReady(Type):
pass
| from ..factory import Type
class authorizationStateReady(Type):
pass
| none | 1 | 1.224905 | 1 | |
kdap/converter/wiki_clean.py | AayushSabharwal/kdap | 9 | 6623106 | <filename>kdap/converter/wiki_clean.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed May 20 23:02:43 2020
@author: descentis
"""
import re
from urllib.parse import quote
from html.entities import name2codepoint
def dropSpans(spans, text):
"""
Drop from text the blocks identified in :param spans:, possibly nested.
"""
spans.sort()
res = ''
offset = 0
for s, e in spans:
if offset <= s: # handle nesting
if offset < s:
res += text[offset:s]
offset = e
res += text[offset:]
return res
def dropNested(text, openDelim, closeDelim):
"""
A matching function for nested expressions, e.g. namespaces and tables.
"""
openRE = re.compile(openDelim, re.IGNORECASE)
closeRE = re.compile(closeDelim, re.IGNORECASE)
# partition text in separate blocks { } { }
spans = [] # pairs (s, e) for each partition
nest = 0 # nesting level
start = openRE.search(text, 0)
if not start:
return text
end = closeRE.search(text, start.end())
next = start
while end:
next = openRE.search(text, next.end())
if not next: # termination
while nest: # close all pending
nest -= 1
end0 = closeRE.search(text, end.end())
if end0:
end = end0
else:
break
spans.append((start.start(), end.end()))
break
while end.end() < next.start():
# { } {
if nest:
nest -= 1
# try closing more
last = end.end()
end = closeRE.search(text, end.end())
if not end: # unbalanced
if spans:
span = (spans[0][0], last)
else:
span = (start.start(), last)
spans = [span]
break
else:
spans.append((start.start(), end.end()))
# advance start, find next close
start = next
end = closeRE.search(text, next.end())
break # { }
if next != start:
# { { }
nest += 1
# collect text outside partitions
return dropSpans(spans, text)
def transform(wikitext):
"""
Transforms wiki markup.
@see https://www.mediawiki.org/wiki/Help:Formatting
"""
# look for matching <nowiki>...</nowiki>
nowiki = re.compile(r'<nowiki>.*?</nowiki>')
res = ''
cur = 0
for m in nowiki.finditer(wikitext, cur):
res += transform1(wikitext[cur:m.start()]) + wikitext[m.start():m.end()]
cur = m.end()
# leftover
res += transform1(wikitext[cur:])
return res
def transform1(text):
"""Transform text not containing <nowiki>"""
return dropNested(text, r'{{', r'}}')
def makeExternalImage(url, alt=''):
return alt
def replaceExternalLinks(text):
"""
https://www.mediawiki.org/wiki/Help:Links#External_links
[URL anchor text]
"""
wgUrlProtocols = [
'bitcoin:', 'ftp://', 'ftps://', 'geo:', 'git://', 'gopher://', 'http://',
'https://', 'irc://', 'ircs://', 'magnet:', 'mailto:', 'mms://', 'news:',
'nntp://', 'redis://', 'sftp://', 'sip:', 'sips:', 'sms:', 'ssh://',
'svn://', 'tel:', 'telnet://', 'urn:', 'worldwind://', 'xmpp:', '//'
]
EXT_LINK_URL_CLASS = r'[^][<>"\x00-\x20\x7F\s]'
ANCHOR_CLASS = r'[^][\x00-\x08\x0a-\x1F]'
ExtLinkBracketedRegex = re.compile('\[(((?i)' + '|'.join(wgUrlProtocols) + ')' + EXT_LINK_URL_CLASS + r'+)' + r'\s*((?:' + ANCHOR_CLASS + r'|\[\[' + ANCHOR_CLASS + r'+\]\])' + r'*?)\]',
re.S | re.U)
EXT_IMAGE_REGEX = re.compile(
r"""^(http://|https://)([^][<>"\x00-\x20\x7F\s]+)
/([A-Za-z0-9_.,~%\-+&;#*?!=()@\x80-\xFF]+)\.((?i)gif|png|jpg|jpeg)$""",
re.X | re.S | re.U)
s = ''
cur = 0
for m in ExtLinkBracketedRegex.finditer(text):
s += text[cur:m.start()]
cur = m.end()
url = m.group(1)
label = m.group(3)
# # The characters '<' and '>' (which were escaped by
# # removeHTMLtags()) should not be included in
# # URLs, per RFC 2396.
# m2 = re.search('&(lt|gt);', url)
# if m2:
# link = url[m2.end():] + ' ' + link
# url = url[0:m2.end()]
# If the link text is an image URL, replace it with an <img> tag
# This happened by accident in the original parser, but some people used it extensively
m = EXT_IMAGE_REGEX.match(label)
if m:
label = makeExternalImage(label)
# Use the encoded URL
# This means that users can paste URLs directly into the text
# Funny characters like ö aren't valid in URLs anyway
# This was changed in August 2004
s += label # + trail
return s + text[cur:]
def unescape(text):
"""
Removes HTML or XML character references and entities from a text string.
:param text The HTML (or XML) source text.
:return The plain text, as a Unicode string, if necessary.
"""
def fixup(m):
text = m.group(0)
code = m.group(1)
try:
if text[1] == "#": # character reference
if text[2] == "x":
return chr(int(code[1:], 16))
else:
return chr(int(code))
else: # named entity
return chr(name2codepoint[code])
except:
return text # leave as is
return re.sub("&#?(\w+);", fixup, text)
def wiki2text(text):
#
# final part of internalParse().)
#
# $text = $this->doTableStuff( $text );
# $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
# $text = $this->doDoubleUnderscore( $text );
# $text = $this->doHeadings( $text );
# $text = $this->replaceInternalLinks( $text );
# $text = $this->doAllQuotes( $text );
# $text = $this->replaceExternalLinks( $text );
# $text = str_replace( self::MARKER_PREFIX . 'NOPARSE', '', $text );
# $text = $this->doMagicLinks( $text );
# $text = $this->formatHeadings( $text, $origText, $isMain );
syntaxhighlight = re.compile('<syntaxhighlight .*?>(.*?)</syntaxhighlight>', re.DOTALL)
# Drop tables
# first drop residual templates, or else empty parameter |} might look like end of table.
text = dropNested(text, r'{{', r'}}')
text = dropNested(text, r'{\|', r'\|}')
switches = (
'__NOTOC__',
'__FORCETOC__',
'__TOC__',
'__TOC__',
'__NEWSECTIONLINK__',
'__NONEWSECTIONLINK__',
'__NOGALLERY__',
'__HIDDENCAT__',
'__NOCONTENTCONVERT__',
'__NOCC__',
'__NOTITLECONVERT__',
'__NOTC__',
'__START__',
'__END__',
'__INDEX__',
'__NOINDEX__',
'__STATICREDIRECT__',
'__DISAMBIG__'
)
# Handle bold/italic/quote
bold_italic = re.compile(r"'''''(.*?)'''''")
bold = re.compile(r"'''(.*?)'''")
italic_quote = re.compile(r"''\"([^\"]*?)\"''")
italic = re.compile(r"''(.*?)''")
quote_quote = re.compile(r'""([^"]*?)""')
magicWordsRE = re.compile('|'.join(switches))
text = bold_italic.sub(r'\1', text)
text = bold.sub(r'\1', text)
text = italic_quote.sub(r'"\1"', text)
text = italic.sub(r'"\1"', text)
text = quote_quote.sub(r'"\1"', text)
# residuals of unbalanced quotes
text = text.replace("'''", '').replace("''", '"')
# replace internal links
text = replaceInternalLinks(text)
# replace external links
text = replaceExternalLinks(text)
# drop MagicWords behavioral switches
text = magicWordsRE.sub('', text)
# ############### Process HTML ###############
# turn into HTML, except for the content of <syntaxhighlight>
res = ''
cur = 0
for m in syntaxhighlight.finditer(text):
res += unescape(text[cur:m.start()]) + m.group(1)
cur = m.end()
text = res + unescape(text[cur:])
return text
def clean(text):
"""
Removes irrelevant parts from :param: text.
"""
selfClosingTags = ('br', 'hr', 'nobr', 'ref', 'references', 'nowiki')
comment = re.compile(r'<!--.*?-->', re.DOTALL)
selfClosing_tag_patterns = [
re.compile(r'<\s*%s\b[^>]*/\s*>' % tag, re.DOTALL | re.IGNORECASE) for tag in selfClosingTags
]
discardElements = [
'gallery', 'timeline', 'noinclude', 'pre',
'table', 'tr', 'td', 'th', 'caption', 'div',
'form', 'input', 'select', 'option', 'textarea',
'ul', 'li', 'ol', 'dl', 'dt', 'dd', 'menu', 'dir',
'ref', 'references', 'img', 'imagemap', 'source', 'small',
'sub', 'sup', 'indicator'
]
spaces = re.compile(r' {2,}')
dots = re.compile(r'\.{4,}')
placeholder_tags = {'math': 'formula', 'code': 'codice'}
placeholder_tag_patterns = [
(re.compile(r'<\s*%s(\s*| [^>]+?)>.*?<\s*/\s*%s\s*>' % (tag, tag), re.DOTALL | re.IGNORECASE),
repl) for tag, repl in placeholder_tags.items()
]
# Collect spans
spans = []
# Drop HTML comments
for m in comment.finditer(text):
spans.append((m.start(), m.end()))
# Drop self-closing tags
for pattern in selfClosing_tag_patterns:
for m in pattern.finditer(text):
spans.append((m.start(), m.end()))
'''
# Drop ignored tags
for left, right in options.ignored_tag_patterns:
for m in left.finditer(text):
spans.append((m.start(), m.end()))
for m in right.finditer(text):
spans.append((m.start(), m.end()))
'''
# Bulk remove all spans
text = dropSpans(spans, text)
# Drop discarded elements
for tag in discardElements:
text = dropNested(text, r'<\s*%s\b[^>/]*>' % tag, r'<\s*/\s*%s>' % tag)
text = unescape(text)
# Expand placeholders
for pattern, placeholder in placeholder_tag_patterns:
index = 1
for match in pattern.finditer(text):
text = text.replace(match.group(), '%s_%d' % (placeholder, index))
index += 1
text = text.replace('<<', '«').replace('>>', '»')
#############################################
# Cleanup text
text = text.replace('\t', ' ')
text = spaces.sub(' ', text)
text = dots.sub('...', text)
text = re.sub(' (,:\.\)\]»)', r'\1', text)
text = re.sub('(\[\(«) ', r'\1', text)
text = re.sub(r'\n\W+?\n', '\n', text, flags=re.U) # lines with only punctuations
text = text.replace(',,', ',').replace(',.', '.')
keep_tables = True
if keep_tables:
# the following regular expressions are used to remove the wikiml chartacters around table strucutures
# yet keep the content. The order here is imporant so we remove certain markup like {| and then
# then the future html attributes such as 'style'. Finally we drop the remaining '|-' that delimits cells.
text = re.sub(r'!(?:\s)?style=\"[a-z]+:(?:\d+)%;\"', r'', text)
text = re.sub(r'!(?:\s)?style="[a-z]+:(?:\d+)%;[a-z]+:(?:#)?(?:[0-9a-z]+)?"', r'', text)
text = text.replace('|-', '')
text = text.replace('|', '')
'''
if options.toHTML:
text = cgi.escape(text)
'''
return text
def getCleanText(text):
text = transform(text)
text = wiki2text(text)
text = clean(text)
return text
def findBalanced(text, openDelim=['[['], closeDelim=[']]']):
"""
Assuming that text contains a properly balanced expression using
:param openDelim: as opening delimiters and
:param closeDelim: as closing delimiters.
:return: an iterator producing pairs (start, end) of start and end
positions in text containing a balanced expression.
"""
openPat = '|'.join([re.escape(x) for x in openDelim])
# pattern for delimiters expected after each opening delimiter
afterPat = {o: re.compile(openPat + '|' + c, re.DOTALL) for o, c in zip(openDelim, closeDelim)}
stack = []
start = 0
cur = 0
# end = len(text)
startSet = False
startPat = re.compile(openPat)
nextPat = startPat
while True:
next = nextPat.search(text, cur)
if not next:
return
if not startSet:
start = next.start()
startSet = True
delim = next.group(0)
if delim in openDelim:
stack.append(delim)
nextPat = afterPat[delim]
else:
opening = stack.pop()
# assert opening == openDelim[closeDelim.index(next.group(0))]
if stack:
nextPat = afterPat[stack[-1]]
else:
yield start, next.end()
nextPat = startPat
start = next.end()
startSet = False
cur = next.end()
def makeInternalLink(title, label):
colon = title.find(':')
keepLinks = False
acceptedNamespaces = ['w', 'wiktionary', 'wikt']
if colon > 0 and title[:colon] not in acceptedNamespaces:
return ''
if colon == 0:
# drop also :File:
colon2 = title.find(':', colon + 1)
if colon2 > 1 and title[colon + 1:colon2] not in acceptedNamespaces:
return ''
if keepLinks:
return '<a href="%s">%s</a>' % (quote(title.encode('utf-8')), label)
else:
return label
def replaceInternalLinks(text):
"""
Replaces internal links of the form:
[[title |...|label]]trail
with title concatenated with trail, when present, e.g. 's' for plural.
See https://www.mediawiki.org/wiki/Help:Links#Internal_links
"""
# call this after removal of external links, so we need not worry about
# triple closing ]]].
tailRE = re.compile('\w+')
cur = 0
res = ''
for s, e in findBalanced(text):
m = tailRE.match(text, e)
if m:
trail = m.group(0)
end = m.end()
else:
trail = ''
end = e
inner = text[s + 2:e - 2]
# find first |
pipe = inner.find('|')
if pipe < 0:
title = inner
label = title
else:
title = inner[:pipe].rstrip()
# find last |
curp = pipe + 1
for s1, e1 in findBalanced(inner):
last = inner.rfind('|', curp, s1)
if last >= 0:
pipe = last # advance
curp = e1
label = inner[pipe + 1:].strip()
res += text[cur:s] + makeInternalLink(title, label) + trail
cur = end
return res + text[cur:] | <filename>kdap/converter/wiki_clean.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed May 20 23:02:43 2020
@author: descentis
"""
import re
from urllib.parse import quote
from html.entities import name2codepoint
def dropSpans(spans, text):
"""
Drop from text the blocks identified in :param spans:, possibly nested.
"""
spans.sort()
res = ''
offset = 0
for s, e in spans:
if offset <= s: # handle nesting
if offset < s:
res += text[offset:s]
offset = e
res += text[offset:]
return res
def dropNested(text, openDelim, closeDelim):
"""
A matching function for nested expressions, e.g. namespaces and tables.
"""
openRE = re.compile(openDelim, re.IGNORECASE)
closeRE = re.compile(closeDelim, re.IGNORECASE)
# partition text in separate blocks { } { }
spans = [] # pairs (s, e) for each partition
nest = 0 # nesting level
start = openRE.search(text, 0)
if not start:
return text
end = closeRE.search(text, start.end())
next = start
while end:
next = openRE.search(text, next.end())
if not next: # termination
while nest: # close all pending
nest -= 1
end0 = closeRE.search(text, end.end())
if end0:
end = end0
else:
break
spans.append((start.start(), end.end()))
break
while end.end() < next.start():
# { } {
if nest:
nest -= 1
# try closing more
last = end.end()
end = closeRE.search(text, end.end())
if not end: # unbalanced
if spans:
span = (spans[0][0], last)
else:
span = (start.start(), last)
spans = [span]
break
else:
spans.append((start.start(), end.end()))
# advance start, find next close
start = next
end = closeRE.search(text, next.end())
break # { }
if next != start:
# { { }
nest += 1
# collect text outside partitions
return dropSpans(spans, text)
def transform(wikitext):
"""
Transforms wiki markup.
@see https://www.mediawiki.org/wiki/Help:Formatting
"""
# look for matching <nowiki>...</nowiki>
nowiki = re.compile(r'<nowiki>.*?</nowiki>')
res = ''
cur = 0
for m in nowiki.finditer(wikitext, cur):
res += transform1(wikitext[cur:m.start()]) + wikitext[m.start():m.end()]
cur = m.end()
# leftover
res += transform1(wikitext[cur:])
return res
def transform1(text):
"""Transform text not containing <nowiki>"""
return dropNested(text, r'{{', r'}}')
def makeExternalImage(url, alt=''):
return alt
def replaceExternalLinks(text):
"""
https://www.mediawiki.org/wiki/Help:Links#External_links
[URL anchor text]
"""
wgUrlProtocols = [
'bitcoin:', 'ftp://', 'ftps://', 'geo:', 'git://', 'gopher://', 'http://',
'https://', 'irc://', 'ircs://', 'magnet:', 'mailto:', 'mms://', 'news:',
'nntp://', 'redis://', 'sftp://', 'sip:', 'sips:', 'sms:', 'ssh://',
'svn://', 'tel:', 'telnet://', 'urn:', 'worldwind://', 'xmpp:', '//'
]
EXT_LINK_URL_CLASS = r'[^][<>"\x00-\x20\x7F\s]'
ANCHOR_CLASS = r'[^][\x00-\x08\x0a-\x1F]'
ExtLinkBracketedRegex = re.compile('\[(((?i)' + '|'.join(wgUrlProtocols) + ')' + EXT_LINK_URL_CLASS + r'+)' + r'\s*((?:' + ANCHOR_CLASS + r'|\[\[' + ANCHOR_CLASS + r'+\]\])' + r'*?)\]',
re.S | re.U)
EXT_IMAGE_REGEX = re.compile(
r"""^(http://|https://)([^][<>"\x00-\x20\x7F\s]+)
/([A-Za-z0-9_.,~%\-+&;#*?!=()@\x80-\xFF]+)\.((?i)gif|png|jpg|jpeg)$""",
re.X | re.S | re.U)
s = ''
cur = 0
for m in ExtLinkBracketedRegex.finditer(text):
s += text[cur:m.start()]
cur = m.end()
url = m.group(1)
label = m.group(3)
# # The characters '<' and '>' (which were escaped by
# # removeHTMLtags()) should not be included in
# # URLs, per RFC 2396.
# m2 = re.search('&(lt|gt);', url)
# if m2:
# link = url[m2.end():] + ' ' + link
# url = url[0:m2.end()]
# If the link text is an image URL, replace it with an <img> tag
# This happened by accident in the original parser, but some people used it extensively
m = EXT_IMAGE_REGEX.match(label)
if m:
label = makeExternalImage(label)
# Use the encoded URL
# This means that users can paste URLs directly into the text
# Funny characters like ö aren't valid in URLs anyway
# This was changed in August 2004
s += label # + trail
return s + text[cur:]
def unescape(text):
"""
Removes HTML or XML character references and entities from a text string.
:param text The HTML (or XML) source text.
:return The plain text, as a Unicode string, if necessary.
"""
def fixup(m):
text = m.group(0)
code = m.group(1)
try:
if text[1] == "#": # character reference
if text[2] == "x":
return chr(int(code[1:], 16))
else:
return chr(int(code))
else: # named entity
return chr(name2codepoint[code])
except:
return text # leave as is
return re.sub("&#?(\w+);", fixup, text)
def wiki2text(text):
#
# final part of internalParse().)
#
# $text = $this->doTableStuff( $text );
# $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
# $text = $this->doDoubleUnderscore( $text );
# $text = $this->doHeadings( $text );
# $text = $this->replaceInternalLinks( $text );
# $text = $this->doAllQuotes( $text );
# $text = $this->replaceExternalLinks( $text );
# $text = str_replace( self::MARKER_PREFIX . 'NOPARSE', '', $text );
# $text = $this->doMagicLinks( $text );
# $text = $this->formatHeadings( $text, $origText, $isMain );
syntaxhighlight = re.compile('<syntaxhighlight .*?>(.*?)</syntaxhighlight>', re.DOTALL)
# Drop tables
# first drop residual templates, or else empty parameter |} might look like end of table.
text = dropNested(text, r'{{', r'}}')
text = dropNested(text, r'{\|', r'\|}')
switches = (
'__NOTOC__',
'__FORCETOC__',
'__TOC__',
'__TOC__',
'__NEWSECTIONLINK__',
'__NONEWSECTIONLINK__',
'__NOGALLERY__',
'__HIDDENCAT__',
'__NOCONTENTCONVERT__',
'__NOCC__',
'__NOTITLECONVERT__',
'__NOTC__',
'__START__',
'__END__',
'__INDEX__',
'__NOINDEX__',
'__STATICREDIRECT__',
'__DISAMBIG__'
)
# Handle bold/italic/quote
bold_italic = re.compile(r"'''''(.*?)'''''")
bold = re.compile(r"'''(.*?)'''")
italic_quote = re.compile(r"''\"([^\"]*?)\"''")
italic = re.compile(r"''(.*?)''")
quote_quote = re.compile(r'""([^"]*?)""')
magicWordsRE = re.compile('|'.join(switches))
text = bold_italic.sub(r'\1', text)
text = bold.sub(r'\1', text)
text = italic_quote.sub(r'"\1"', text)
text = italic.sub(r'"\1"', text)
text = quote_quote.sub(r'"\1"', text)
# residuals of unbalanced quotes
text = text.replace("'''", '').replace("''", '"')
# replace internal links
text = replaceInternalLinks(text)
# replace external links
text = replaceExternalLinks(text)
# drop MagicWords behavioral switches
text = magicWordsRE.sub('', text)
# ############### Process HTML ###############
# turn into HTML, except for the content of <syntaxhighlight>
res = ''
cur = 0
for m in syntaxhighlight.finditer(text):
res += unescape(text[cur:m.start()]) + m.group(1)
cur = m.end()
text = res + unescape(text[cur:])
return text
def clean(text):
"""
Removes irrelevant parts from :param: text.
"""
selfClosingTags = ('br', 'hr', 'nobr', 'ref', 'references', 'nowiki')
comment = re.compile(r'<!--.*?-->', re.DOTALL)
selfClosing_tag_patterns = [
re.compile(r'<\s*%s\b[^>]*/\s*>' % tag, re.DOTALL | re.IGNORECASE) for tag in selfClosingTags
]
discardElements = [
'gallery', 'timeline', 'noinclude', 'pre',
'table', 'tr', 'td', 'th', 'caption', 'div',
'form', 'input', 'select', 'option', 'textarea',
'ul', 'li', 'ol', 'dl', 'dt', 'dd', 'menu', 'dir',
'ref', 'references', 'img', 'imagemap', 'source', 'small',
'sub', 'sup', 'indicator'
]
spaces = re.compile(r' {2,}')
dots = re.compile(r'\.{4,}')
placeholder_tags = {'math': 'formula', 'code': 'codice'}
placeholder_tag_patterns = [
(re.compile(r'<\s*%s(\s*| [^>]+?)>.*?<\s*/\s*%s\s*>' % (tag, tag), re.DOTALL | re.IGNORECASE),
repl) for tag, repl in placeholder_tags.items()
]
# Collect spans
spans = []
# Drop HTML comments
for m in comment.finditer(text):
spans.append((m.start(), m.end()))
# Drop self-closing tags
for pattern in selfClosing_tag_patterns:
for m in pattern.finditer(text):
spans.append((m.start(), m.end()))
'''
# Drop ignored tags
for left, right in options.ignored_tag_patterns:
for m in left.finditer(text):
spans.append((m.start(), m.end()))
for m in right.finditer(text):
spans.append((m.start(), m.end()))
'''
# Bulk remove all spans
text = dropSpans(spans, text)
# Drop discarded elements
for tag in discardElements:
text = dropNested(text, r'<\s*%s\b[^>/]*>' % tag, r'<\s*/\s*%s>' % tag)
text = unescape(text)
# Expand placeholders
for pattern, placeholder in placeholder_tag_patterns:
index = 1
for match in pattern.finditer(text):
text = text.replace(match.group(), '%s_%d' % (placeholder, index))
index += 1
text = text.replace('<<', '«').replace('>>', '»')
#############################################
# Cleanup text
text = text.replace('\t', ' ')
text = spaces.sub(' ', text)
text = dots.sub('...', text)
text = re.sub(' (,:\.\)\]»)', r'\1', text)
text = re.sub('(\[\(«) ', r'\1', text)
text = re.sub(r'\n\W+?\n', '\n', text, flags=re.U) # lines with only punctuations
text = text.replace(',,', ',').replace(',.', '.')
keep_tables = True
if keep_tables:
# the following regular expressions are used to remove the wikiml chartacters around table strucutures
# yet keep the content. The order here is imporant so we remove certain markup like {| and then
# then the future html attributes such as 'style'. Finally we drop the remaining '|-' that delimits cells.
text = re.sub(r'!(?:\s)?style=\"[a-z]+:(?:\d+)%;\"', r'', text)
text = re.sub(r'!(?:\s)?style="[a-z]+:(?:\d+)%;[a-z]+:(?:#)?(?:[0-9a-z]+)?"', r'', text)
text = text.replace('|-', '')
text = text.replace('|', '')
'''
if options.toHTML:
text = cgi.escape(text)
'''
return text
def getCleanText(text):
text = transform(text)
text = wiki2text(text)
text = clean(text)
return text
def findBalanced(text, openDelim=['[['], closeDelim=[']]']):
"""
Assuming that text contains a properly balanced expression using
:param openDelim: as opening delimiters and
:param closeDelim: as closing delimiters.
:return: an iterator producing pairs (start, end) of start and end
positions in text containing a balanced expression.
"""
openPat = '|'.join([re.escape(x) for x in openDelim])
# pattern for delimiters expected after each opening delimiter
afterPat = {o: re.compile(openPat + '|' + c, re.DOTALL) for o, c in zip(openDelim, closeDelim)}
stack = []
start = 0
cur = 0
# end = len(text)
startSet = False
startPat = re.compile(openPat)
nextPat = startPat
while True:
next = nextPat.search(text, cur)
if not next:
return
if not startSet:
start = next.start()
startSet = True
delim = next.group(0)
if delim in openDelim:
stack.append(delim)
nextPat = afterPat[delim]
else:
opening = stack.pop()
# assert opening == openDelim[closeDelim.index(next.group(0))]
if stack:
nextPat = afterPat[stack[-1]]
else:
yield start, next.end()
nextPat = startPat
start = next.end()
startSet = False
cur = next.end()
def makeInternalLink(title, label):
colon = title.find(':')
keepLinks = False
acceptedNamespaces = ['w', 'wiktionary', 'wikt']
if colon > 0 and title[:colon] not in acceptedNamespaces:
return ''
if colon == 0:
# drop also :File:
colon2 = title.find(':', colon + 1)
if colon2 > 1 and title[colon + 1:colon2] not in acceptedNamespaces:
return ''
if keepLinks:
return '<a href="%s">%s</a>' % (quote(title.encode('utf-8')), label)
else:
return label
def replaceInternalLinks(text):
"""
Replaces internal links of the form:
[[title |...|label]]trail
with title concatenated with trail, when present, e.g. 's' for plural.
See https://www.mediawiki.org/wiki/Help:Links#Internal_links
"""
# call this after removal of external links, so we need not worry about
# triple closing ]]].
tailRE = re.compile('\w+')
cur = 0
res = ''
for s, e in findBalanced(text):
m = tailRE.match(text, e)
if m:
trail = m.group(0)
end = m.end()
else:
trail = ''
end = e
inner = text[s + 2:e - 2]
# find first |
pipe = inner.find('|')
if pipe < 0:
title = inner
label = title
else:
title = inner[:pipe].rstrip()
# find last |
curp = pipe + 1
for s1, e1 in findBalanced(inner):
last = inner.rfind('|', curp, s1)
if last >= 0:
pipe = last # advance
curp = e1
label = inner[pipe + 1:].strip()
res += text[cur:s] + makeInternalLink(title, label) + trail
cur = end
return res + text[cur:] | en | 0.441166 | #!/usr/bin/env python3 # -*- coding: utf-8 -*- Created on Wed May 20 23:02:43 2020 @author: descentis Drop from text the blocks identified in :param spans:, possibly nested. # handle nesting A matching function for nested expressions, e.g. namespaces and tables. # partition text in separate blocks { } { } # pairs (s, e) for each partition # nesting level # termination # close all pending # { } { # try closing more # unbalanced # advance start, find next close # { } # { { } # collect text outside partitions Transforms wiki markup. @see https://www.mediawiki.org/wiki/Help:Formatting # look for matching <nowiki>...</nowiki> # leftover Transform text not containing <nowiki> https://www.mediawiki.org/wiki/Help:Links#External_links [URL anchor text] ^(http://|https://)([^][<>"\x00-\x20\x7F\s]+) /([A-Za-z0-9_.,~%\-+&;#*?!=()@\x80-\xFF]+)\.((?i)gif|png|jpg|jpeg)$ # # The characters '<' and '>' (which were escaped by # # removeHTMLtags()) should not be included in # # URLs, per RFC 2396. # m2 = re.search('&(lt|gt);', url) # if m2: # link = url[m2.end():] + ' ' + link # url = url[0:m2.end()] # If the link text is an image URL, replace it with an <img> tag # This happened by accident in the original parser, but some people used it extensively # Use the encoded URL # This means that users can paste URLs directly into the text # Funny characters like ö aren't valid in URLs anyway # This was changed in August 2004 # + trail Removes HTML or XML character references and entities from a text string. :param text The HTML (or XML) source text. :return The plain text, as a Unicode string, if necessary. # character reference # named entity # leave as is #?(\w+);", fixup, text) # # final part of internalParse().) # # $text = $this->doTableStuff( $text ); # $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text ); # $text = $this->doDoubleUnderscore( $text ); # $text = $this->doHeadings( $text ); # $text = $this->replaceInternalLinks( $text ); # $text = $this->doAllQuotes( $text ); # $text = $this->replaceExternalLinks( $text ); # $text = str_replace( self::MARKER_PREFIX . 'NOPARSE', '', $text ); # $text = $this->doMagicLinks( $text ); # $text = $this->formatHeadings( $text, $origText, $isMain ); # Drop tables # first drop residual templates, or else empty parameter |} might look like end of table. # Handle bold/italic/quote ''(.*?) (.*?) # residuals of unbalanced quotes ", '').replace("''", '"') # replace internal links text = replaceInternalLinks(text) # replace external links text = replaceExternalLinks(text) # drop MagicWords behavioral switches text = magicWordsRE.sub('', text) # ############### Process HTML ############### # turn into HTML, except for the content of <syntaxhighlight> res = '' cur = 0 for m in syntaxhighlight.finditer(text): res += unescape(text[cur:m.start()]) + m.group(1) cur = m.end() text = res + unescape(text[cur:]) return text def clean(text): """ Removes irrelevant parts from :param: text. """ selfClosingTags = ('br', 'hr', 'nobr', 'ref', 'references', 'nowiki') comment = re.compile(r'<!--.*?-->', re.DOTALL) selfClosing_tag_patterns = [ re.compile(r'<\s*%s\b[^>]*/\s*>' % tag, re.DOTALL | re.IGNORECASE) for tag in selfClosingTags ] discardElements = [ 'gallery', 'timeline', 'noinclude', 'pre', 'table', 'tr', 'td', 'th', 'caption', 'div', 'form', 'input', 'select', 'option', 'textarea', 'ul', 'li', 'ol', 'dl', 'dt', 'dd', 'menu', 'dir', 'ref', 'references', 'img', 'imagemap', 'source', 'small', 'sub', 'sup', 'indicator' ] spaces = re.compile(r' {2,}') dots = re.compile(r'\.{4,}') placeholder_tags = {'math': 'formula', 'code': 'codice'} placeholder_tag_patterns = [ (re.compile(r'<\s*%s(\s*| [^>]+?)>.*?<\s*/\s*%s\s*>' % (tag, tag), re.DOTALL | re.IGNORECASE), repl) for tag, repl in placeholder_tags.items() ] # Collect spans spans = [] # Drop HTML comments for m in comment.finditer(text): spans.append((m.start(), m.end())) # Drop self-closing tags for pattern in selfClosing_tag_patterns: for m in pattern.finditer(text): spans.append((m.start(), m.end())) # Drop ignored tags # Bulk remove all spans text = dropSpans(spans, text) # Drop discarded elements for tag in discardElements: text = dropNested(text, r'<\s*%s\b[^>/]*>' % tag, r'<\s*/\s*%s>' % tag) text = unescape(text) # Expand placeholders for pattern, placeholder in placeholder_tag_patterns: index = 1 for match in pattern.finditer(text): text = text.replace(match.group(), '%s_%d' % (placeholder, index)) index += 1 text = text.replace('<<', '«').replace('>>', '»') ############################################# # Cleanup text text = text.replace('\t', ' ') text = spaces.sub(' ', text) text = dots.sub('...', text) text = re.sub(' (,:\.\)\]»)', r'\1', text) text = re.sub('(\[\(«) ', r'\1', text) text = re.sub(r'\n\W+?\n', '\n', text, flags=re.U) # lines with only punctuations text = text.replace(',,', ',').replace(',.', '.') keep_tables = True if keep_tables: # the following regular expressions are used to remove the wikiml chartacters around table strucutures # yet keep the content. The order here is imporant so we remove certain markup like {| and then # then the future html attributes such as 'style'. Finally we drop the remaining '|-' that delimits cells. text = re.sub(r'!(?:\s)?style=\"[a-z]+:(?:\d+)%;\"', r'', text) text = re.sub(r'!(?:\s)?style="[a-z]+:(?:\d+)%;[a-z]+:(?:#)?(?:[0-9a-z]+)?"', r'', text) text = text.replace('|-', '') text = text.replace('|', '') Assuming that text contains a properly balanced expression using :param openDelim: as opening delimiters and :param closeDelim: as closing delimiters. :return: an iterator producing pairs (start, end) of start and end positions in text containing a balanced expression. # pattern for delimiters expected after each opening delimiter # end = len(text) # assert opening == openDelim[closeDelim.index(next.group(0))] # drop also :File: Replaces internal links of the form: [[title |...|label]]trail with title concatenated with trail, when present, e.g. 's' for plural. See https://www.mediawiki.org/wiki/Help:Links#Internal_links # call this after removal of external links, so we need not worry about # triple closing ]]]. # find first | # find last | # advance | 3.195527 | 3 |
hackulus/utils.py | jungkumseok/hackulus | 0 | 6623107 | <filename>hackulus/utils.py
import sys, code, re
from jokes.core.console import Console as jokesConsole
from io import StringIO
from contextlib import contextmanager
@contextmanager
def std_redirector(stdin=sys.stdin, stdout=sys.stdin, stderr=sys.stderr):
tmp_fds = stdin, stdout, stderr
orig_fds = sys.stdin, sys.stdout, sys.stderr
sys.stdin, sys.stdout, sys.stderr = tmp_fds
yield
sys.stdin, sys.stdout, sys.stderr = orig_fds
class PyShell(code.InteractiveConsole):
def __init__(self, locals=None):
code.InteractiveConsole.__init__(self, locals=locals)
self.output = StringIO()
self.ps1 = getattr(sys, "ps1", ">>> ")
self.ps2 = getattr(sys, "ps2", "... ")
self.banner = ("Python %s\n%s\n" % (sys.version, sys.platform) +
'Type "help", "copyright", "credits" or "license" '
'for more information.\n')
def push(self, command):
if not (True in [ bool(re.match(pattern, command)) for pattern in ['exit\(\)', ] ]): #Check for forbidden command regex patterns
self.output = StringIO()
with std_redirector(stdout=self.output, stderr=self.output):
try:
more = code.InteractiveConsole.push(self, command)
result = self.output.getvalue()
except (SyntaxError, OverflowError):
pass
return more, result
else:
return False, '"'+command+'" is a forbidden command in this version of the python interpreter'
INTERPRETER_LANGUAGES = ['python', 'javascript', 'jokes']
class Interpreter():
def __init__(self, language='python'):
self.set_language(language)
def set_language(self, language):
if language in INTERPRETER_LANGUAGES:
self.language = language
self.set_interpreter(language)
def set_interpreter(self, language):
""" Called within self.set_language() method """
if language == 'python':
self.interpreter = PyShell()
elif language == 'jokes':
self.interpreter = jokesConsole()
def input(self, inputstring):
""" Do something and return a dict {'concat': bool, 'print': str} """
return getattr(self, 'input_'+self.language)(inputstring)
def input_python(self, inputstring):
""" Run inputstring as shell command and return a dict {'concat': bool, 'print': str} """
result = self.interpreter.push(inputstring)
return {'concat':result[0], 'print':result[1]}
def input_jokes(self, inputstring):
""" Run inputstring as shell command and return a dict {'concat': bool, 'print': str} """
result = self.interpreter.push(inputstring)
return {'concat':result[0], 'print':result[1]} | <filename>hackulus/utils.py
import sys, code, re
from jokes.core.console import Console as jokesConsole
from io import StringIO
from contextlib import contextmanager
@contextmanager
def std_redirector(stdin=sys.stdin, stdout=sys.stdin, stderr=sys.stderr):
tmp_fds = stdin, stdout, stderr
orig_fds = sys.stdin, sys.stdout, sys.stderr
sys.stdin, sys.stdout, sys.stderr = tmp_fds
yield
sys.stdin, sys.stdout, sys.stderr = orig_fds
class PyShell(code.InteractiveConsole):
def __init__(self, locals=None):
code.InteractiveConsole.__init__(self, locals=locals)
self.output = StringIO()
self.ps1 = getattr(sys, "ps1", ">>> ")
self.ps2 = getattr(sys, "ps2", "... ")
self.banner = ("Python %s\n%s\n" % (sys.version, sys.platform) +
'Type "help", "copyright", "credits" or "license" '
'for more information.\n')
def push(self, command):
if not (True in [ bool(re.match(pattern, command)) for pattern in ['exit\(\)', ] ]): #Check for forbidden command regex patterns
self.output = StringIO()
with std_redirector(stdout=self.output, stderr=self.output):
try:
more = code.InteractiveConsole.push(self, command)
result = self.output.getvalue()
except (SyntaxError, OverflowError):
pass
return more, result
else:
return False, '"'+command+'" is a forbidden command in this version of the python interpreter'
INTERPRETER_LANGUAGES = ['python', 'javascript', 'jokes']
class Interpreter():
def __init__(self, language='python'):
self.set_language(language)
def set_language(self, language):
if language in INTERPRETER_LANGUAGES:
self.language = language
self.set_interpreter(language)
def set_interpreter(self, language):
""" Called within self.set_language() method """
if language == 'python':
self.interpreter = PyShell()
elif language == 'jokes':
self.interpreter = jokesConsole()
def input(self, inputstring):
""" Do something and return a dict {'concat': bool, 'print': str} """
return getattr(self, 'input_'+self.language)(inputstring)
def input_python(self, inputstring):
""" Run inputstring as shell command and return a dict {'concat': bool, 'print': str} """
result = self.interpreter.push(inputstring)
return {'concat':result[0], 'print':result[1]}
def input_jokes(self, inputstring):
""" Run inputstring as shell command and return a dict {'concat': bool, 'print': str} """
result = self.interpreter.push(inputstring)
return {'concat':result[0], 'print':result[1]} | en | 0.61085 | #Check for forbidden command regex patterns Called within self.set_language() method Do something and return a dict {'concat': bool, 'print': str} Run inputstring as shell command and return a dict {'concat': bool, 'print': str} Run inputstring as shell command and return a dict {'concat': bool, 'print': str} | 2.384011 | 2 |
functions/types_of_arguments_in_function/variabel_scope.py | Mr-Sunglasses/Function-OOPS-PY | 0 | 6623108 | <reponame>Mr-Sunglasses/Function-OOPS-PY
# Local Variable
a = 22
def myfunction():
a = 22
a+=1
print(a)
def see():
global a
a+=1
print("modified = ",a)
x = 10
def app():
global x
x+=20
print(x)
def work():
x = 22
z = globals()['x']
print(z)
work() | # Local Variable
a = 22
def myfunction():
a = 22
a+=1
print(a)
def see():
global a
a+=1
print("modified = ",a)
x = 10
def app():
global x
x+=20
print(x)
def work():
x = 22
z = globals()['x']
print(z)
work() | en | 0.792356 | # Local Variable | 3.53058 | 4 |
bot/plugins/upload_servers/__init__.py | grahamtito/TelegramFiletoCloud | 0 | 6623109 | <reponame>grahamtito/TelegramFiletoCloud
from .fileio_upload import fileIO
from .gofileio import gofileIO
from .transfersh import transferSH
from .anonymfiles import anonymFiles
from .aparat import aparatUPPer
from .splus import splusUPPer
| from .fileio_upload import fileIO
from .gofileio import gofileIO
from .transfersh import transferSH
from .anonymfiles import anonymFiles
from .aparat import aparatUPPer
from .splus import splusUPPer | none | 1 | 1.070129 | 1 | |
nomadgram2/images/migrations/0002_auto_20180527_2229.py | tonky0110/NomadGram2 | 0 | 6623110 | # Generated by Django 2.0.5 on 2018-05-27 13:29
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('images', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='comment',
name='creator',
field=models.ForeignKey(null=True, on_delete=True, to=settings.AUTH_USER_MODEL),
),
migrations.AlterField(
model_name='comment',
name='image',
field=models.ForeignKey(null=True, on_delete=True, to='images.Image'),
),
migrations.AlterField(
model_name='image',
name='creator',
field=models.ForeignKey(null=True, on_delete=True, to=settings.AUTH_USER_MODEL),
),
migrations.AlterField(
model_name='like',
name='creator',
field=models.ForeignKey(null=True, on_delete=True, to=settings.AUTH_USER_MODEL),
),
migrations.AlterField(
model_name='like',
name='image',
field=models.ForeignKey(null=True, on_delete=True, to='images.Image'),
),
]
| # Generated by Django 2.0.5 on 2018-05-27 13:29
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('images', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='comment',
name='creator',
field=models.ForeignKey(null=True, on_delete=True, to=settings.AUTH_USER_MODEL),
),
migrations.AlterField(
model_name='comment',
name='image',
field=models.ForeignKey(null=True, on_delete=True, to='images.Image'),
),
migrations.AlterField(
model_name='image',
name='creator',
field=models.ForeignKey(null=True, on_delete=True, to=settings.AUTH_USER_MODEL),
),
migrations.AlterField(
model_name='like',
name='creator',
field=models.ForeignKey(null=True, on_delete=True, to=settings.AUTH_USER_MODEL),
),
migrations.AlterField(
model_name='like',
name='image',
field=models.ForeignKey(null=True, on_delete=True, to='images.Image'),
),
]
| en | 0.793437 | # Generated by Django 2.0.5 on 2018-05-27 13:29 | 1.714998 | 2 |
src/analytics/migrations/0003_auto_20200410_0153.py | ResearchHub/ResearchHub-Backend-Open | 18 | 6623111 | <gh_stars>10-100
# Generated by Django 2.2.11 on 2020-04-10 01:53
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('analytics', '0002_websitevisits_saw_signup_banner'),
]
operations = [
migrations.AlterField(
model_name='websitevisits',
name='uuid',
field=models.CharField(max_length=32),
),
]
| # Generated by Django 2.2.11 on 2020-04-10 01:53
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('analytics', '0002_websitevisits_saw_signup_banner'),
]
operations = [
migrations.AlterField(
model_name='websitevisits',
name='uuid',
field=models.CharField(max_length=32),
),
] | en | 0.793744 | # Generated by Django 2.2.11 on 2020-04-10 01:53 | 1.490583 | 1 |
telegram/admin.py | aquametalabs/django-telegram | 10 | 6623112 | <gh_stars>1-10
from django.contrib import admin
from telegram.models import *
class SubscriptionPlatformInline(admin.TabularInline):
model = SubscriptionPlatform
extra = 1
class SubscriptionAdmin(admin.ModelAdmin):
fields = ('channel', 'level', 'disabled',)
inlines = (SubscriptionPlatformInline,)
def save_model(self, request, obj, form, change):
obj.user = request.user
obj.save()
class PlatformAdmin(admin.ModelAdmin):
pass
admin.site.register(Telegram)
admin.site.register(Subscription, SubscriptionAdmin)
admin.site.register(Platform, PlatformAdmin)
admin.site.register(SubscriptionMeta)
admin.site.register(Channel)
admin.site.register(SubscriptionPlatform)
admin.site.register(SendLog)
| from django.contrib import admin
from telegram.models import *
class SubscriptionPlatformInline(admin.TabularInline):
model = SubscriptionPlatform
extra = 1
class SubscriptionAdmin(admin.ModelAdmin):
fields = ('channel', 'level', 'disabled',)
inlines = (SubscriptionPlatformInline,)
def save_model(self, request, obj, form, change):
obj.user = request.user
obj.save()
class PlatformAdmin(admin.ModelAdmin):
pass
admin.site.register(Telegram)
admin.site.register(Subscription, SubscriptionAdmin)
admin.site.register(Platform, PlatformAdmin)
admin.site.register(SubscriptionMeta)
admin.site.register(Channel)
admin.site.register(SubscriptionPlatform)
admin.site.register(SendLog) | none | 1 | 1.93968 | 2 | |
backend/apps/dorm/urls.py | YernarT/dormitory_management_system | 1 | 6623113 | <filename>backend/apps/dorm/urls.py<gh_stars>1-10
from django.conf.urls import url
from dorm.views import CityView, CitySingleView, DormView, DormSingleView, OrganizationView, OrganizationCategoryView, RoomView, RoomSingleView, BedView, BedSingleView
urlpatterns = [
url(r'^dorm/city/$', CityView.as_view()),
url(r'^dorm/city/(?P<id>\d+)/$', CitySingleView.as_view()),
url(r'^dorm/$', DormView.as_view()),
url(r'^dorm/(?P<id>\d+)/$', DormSingleView.as_view()),
url(r'^dorm/organization/$', OrganizationView.as_view()),
url(r'^dorm/organization/category/$', OrganizationCategoryView.as_view()),
url(r'^dorm/room/$', RoomView.as_view()),
url(r'^dorm/room/(?P<id>\d+)/$$', RoomSingleView.as_view()),
url(r'^dorm/bed/$', BedView.as_view()),
url(r'^dorm/bed/(?P<id>\d+)/$$', BedSingleView.as_view()),
]
app_name = 'dorm'
| <filename>backend/apps/dorm/urls.py<gh_stars>1-10
from django.conf.urls import url
from dorm.views import CityView, CitySingleView, DormView, DormSingleView, OrganizationView, OrganizationCategoryView, RoomView, RoomSingleView, BedView, BedSingleView
urlpatterns = [
url(r'^dorm/city/$', CityView.as_view()),
url(r'^dorm/city/(?P<id>\d+)/$', CitySingleView.as_view()),
url(r'^dorm/$', DormView.as_view()),
url(r'^dorm/(?P<id>\d+)/$', DormSingleView.as_view()),
url(r'^dorm/organization/$', OrganizationView.as_view()),
url(r'^dorm/organization/category/$', OrganizationCategoryView.as_view()),
url(r'^dorm/room/$', RoomView.as_view()),
url(r'^dorm/room/(?P<id>\d+)/$$', RoomSingleView.as_view()),
url(r'^dorm/bed/$', BedView.as_view()),
url(r'^dorm/bed/(?P<id>\d+)/$$', BedSingleView.as_view()),
]
app_name = 'dorm'
| none | 1 | 1.99098 | 2 | |
tact/fastmrca.py | jonchang/tact | 2 | 6623114 | """Singleton object that helps speed up MRCA lookups."""
from __future__ import division
from .tree_util import get_tip_labels
global tree
def initialize(phy):
"""
Initialize the fastmrca singleton with a tree.
"""
global tree
tree = phy
def bitmask(labels):
"""
Gets a bitmask for the taxa in `labels`, potentially in parallel.
"""
global tree
tn = tree.taxon_namespace
return tn.taxa_bitmask(labels=labels)
def get(labels):
"""Pulls a MRCA node out for the taxa in `labels`."""
global tree
labels = set(labels)
mrca = tree.mrca(leafset_bitmask=bitmask(labels))
if mrca and labels.issuperset(get_tip_labels(mrca)):
return mrca
return None
def fastmrca_getter(tn, x):
"""Helper function for submitting stuff."""
taxa = tn.get_taxa(labels=x)
mask = 0
for taxon in taxa:
mask |= tn.taxon_bitmask(taxon)
return mask
| """Singleton object that helps speed up MRCA lookups."""
from __future__ import division
from .tree_util import get_tip_labels
global tree
def initialize(phy):
"""
Initialize the fastmrca singleton with a tree.
"""
global tree
tree = phy
def bitmask(labels):
"""
Gets a bitmask for the taxa in `labels`, potentially in parallel.
"""
global tree
tn = tree.taxon_namespace
return tn.taxa_bitmask(labels=labels)
def get(labels):
"""Pulls a MRCA node out for the taxa in `labels`."""
global tree
labels = set(labels)
mrca = tree.mrca(leafset_bitmask=bitmask(labels))
if mrca and labels.issuperset(get_tip_labels(mrca)):
return mrca
return None
def fastmrca_getter(tn, x):
"""Helper function for submitting stuff."""
taxa = tn.get_taxa(labels=x)
mask = 0
for taxon in taxa:
mask |= tn.taxon_bitmask(taxon)
return mask
| en | 0.834152 | Singleton object that helps speed up MRCA lookups. Initialize the fastmrca singleton with a tree. Gets a bitmask for the taxa in `labels`, potentially in parallel. Pulls a MRCA node out for the taxa in `labels`. Helper function for submitting stuff. | 2.467895 | 2 |
sktime/utils/testing.py | TonyBagnall/sktime | 2 | 6623115 | <filename>sktime/utils/testing.py
import pandas as pd
def generate_df_from_array(array, n_rows=10, n_cols=1):
return pd.DataFrame([[pd.Series(array) for _ in range(n_cols)] for _ in range(n_rows)],
columns=[f'col{c}' for c in range(n_cols)])
| <filename>sktime/utils/testing.py
import pandas as pd
def generate_df_from_array(array, n_rows=10, n_cols=1):
return pd.DataFrame([[pd.Series(array) for _ in range(n_cols)] for _ in range(n_rows)],
columns=[f'col{c}' for c in range(n_cols)])
| none | 1 | 3.023628 | 3 | |
challenges/local_exceptions.py | architv/chcli | 337 | 6623116 | <reponame>architv/chcli
class IncorrectParametersException(Exception):
pass | class IncorrectParametersException(Exception):
pass | none | 1 | 1.101368 | 1 | |
instructors/course-2015/oop/lab/deck_o_cards.py | mgadagin/PythonClass | 46 | 6623117 | <reponame>mgadagin/PythonClass
import random
from collections import deque
class PlayingCard(object):
'''A classic 'Playing Card' for traditional games such as poker, war and go fish.
each PlayingCard has a rank, suit, and color
'''
def __init__(self, rank, suit): #every single instance needs a rank and suit!
self.rank = rank
self.suit = suit
def __repr__(self):
return "{0} of {1}".format(self.rank, self.suit)
#unneccesary example of a color of a card, however good illustration of an @property
#color should be a data attribute but it needs calculation, thus it belongs as a property
@property
def color(self):
if "diamonds" == self.suit or "hearts" == self.suit:
self._color = "red"
return self._color
elif "spades" == self.suit or "clubs" == self.suit:
self._color = "black"
return self._color
else:
self._color = None
return self._color
class PlayingDeck(object):
'''A Deck of 'Playing Cards'
initialized with classic the 52 cards, no jokers
'''
ranks = ["two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "jack", "queen", "king", "ace"]
suits = ["spades", "clubs", "hearts", "diamonds"]
def __init__(self, type_of_card):
#double-ended queue is going to be used to emulate a real-world Deck of Cards
#the left side of the deque is the bottom of a Deck and the right side is the top
self.deck_container = deque()
for rank in self.ranks:
for suit in self.suits:
self.deck_container.append(PlayingCard(rank, suit))
def __repr__(self):
return "deck of length: {0}\n all cards: {1}".format(len(self.deck_container), self.deck_container)
def cut(self):
'''cut the deck using a generated psuedo random integer
'''
randint = random.randint(0, len(self.deck_container) )
self.deck_container.rotate(randint)
def shuffle(self, x_times):
'''shuffle the deck in place according to a psuedo random number algorithm within python,
x_times is entered to ensure quality of shuffle, however beware psuedo random patterns!
'''
for x_time in range(x_times):
#print 'running shuffle for the {}'.format(x_time)
random.shuffle(self.deck_container)
def pass_n_cards(self, num_to_deal):
'''take n amount of cards from top of PlayingDeck instance,
that is from the right side of the deck_container
'''
holder = deque() #need ability to hold each 'popped' card until passed and received by another Deck like object
for num in range(num_to_deal):
holder.append(self.deck_container.pop())
return holder
def receive_n_cards(self, cards):
'''receive n amount of cards and put on bottom of PlayingDeck instance,
that is the left side of the deck_container
'''
#designed to receive another deque object
#needs to take each element of the deque and append it to self.deck_container
for card in cards:
self.deck_container.appendleft(card)
'''
pd = PlayingDeck(PlayingCard)
another_playing_deck = PlayingDeck(PlayingCard)
another_playing_deck.receive_n_cards( pd.pass_n_cards(22) )
print len(another_playing_deck.deck_container)
print(another_playing_deck)
print pd.deck_container[0]
print pd.deck_container[0].color
print pd.deck_container[1]
print pd.deck_container[1].color
'''
#unnecessary list "dead-end" code alley below
#self.deck_container.insert( self.deck_container[randint], self.deck_container[randint:] )
| import random
from collections import deque
class PlayingCard(object):
'''A classic 'Playing Card' for traditional games such as poker, war and go fish.
each PlayingCard has a rank, suit, and color
'''
def __init__(self, rank, suit): #every single instance needs a rank and suit!
self.rank = rank
self.suit = suit
def __repr__(self):
return "{0} of {1}".format(self.rank, self.suit)
#unneccesary example of a color of a card, however good illustration of an @property
#color should be a data attribute but it needs calculation, thus it belongs as a property
@property
def color(self):
if "diamonds" == self.suit or "hearts" == self.suit:
self._color = "red"
return self._color
elif "spades" == self.suit or "clubs" == self.suit:
self._color = "black"
return self._color
else:
self._color = None
return self._color
class PlayingDeck(object):
'''A Deck of 'Playing Cards'
initialized with classic the 52 cards, no jokers
'''
ranks = ["two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "jack", "queen", "king", "ace"]
suits = ["spades", "clubs", "hearts", "diamonds"]
def __init__(self, type_of_card):
#double-ended queue is going to be used to emulate a real-world Deck of Cards
#the left side of the deque is the bottom of a Deck and the right side is the top
self.deck_container = deque()
for rank in self.ranks:
for suit in self.suits:
self.deck_container.append(PlayingCard(rank, suit))
def __repr__(self):
return "deck of length: {0}\n all cards: {1}".format(len(self.deck_container), self.deck_container)
def cut(self):
'''cut the deck using a generated psuedo random integer
'''
randint = random.randint(0, len(self.deck_container) )
self.deck_container.rotate(randint)
def shuffle(self, x_times):
'''shuffle the deck in place according to a psuedo random number algorithm within python,
x_times is entered to ensure quality of shuffle, however beware psuedo random patterns!
'''
for x_time in range(x_times):
#print 'running shuffle for the {}'.format(x_time)
random.shuffle(self.deck_container)
def pass_n_cards(self, num_to_deal):
'''take n amount of cards from top of PlayingDeck instance,
that is from the right side of the deck_container
'''
holder = deque() #need ability to hold each 'popped' card until passed and received by another Deck like object
for num in range(num_to_deal):
holder.append(self.deck_container.pop())
return holder
def receive_n_cards(self, cards):
'''receive n amount of cards and put on bottom of PlayingDeck instance,
that is the left side of the deck_container
'''
#designed to receive another deque object
#needs to take each element of the deque and append it to self.deck_container
for card in cards:
self.deck_container.appendleft(card)
'''
pd = PlayingDeck(PlayingCard)
another_playing_deck = PlayingDeck(PlayingCard)
another_playing_deck.receive_n_cards( pd.pass_n_cards(22) )
print len(another_playing_deck.deck_container)
print(another_playing_deck)
print pd.deck_container[0]
print pd.deck_container[0].color
print pd.deck_container[1]
print pd.deck_container[1].color
'''
#unnecessary list "dead-end" code alley below
#self.deck_container.insert( self.deck_container[randint], self.deck_container[randint:] ) | en | 0.840605 | A classic 'Playing Card' for traditional games such as poker, war and go fish. each PlayingCard has a rank, suit, and color #every single instance needs a rank and suit! #unneccesary example of a color of a card, however good illustration of an @property #color should be a data attribute but it needs calculation, thus it belongs as a property A Deck of 'Playing Cards' initialized with classic the 52 cards, no jokers #double-ended queue is going to be used to emulate a real-world Deck of Cards #the left side of the deque is the bottom of a Deck and the right side is the top cut the deck using a generated psuedo random integer shuffle the deck in place according to a psuedo random number algorithm within python, x_times is entered to ensure quality of shuffle, however beware psuedo random patterns! #print 'running shuffle for the {}'.format(x_time) take n amount of cards from top of PlayingDeck instance, that is from the right side of the deck_container #need ability to hold each 'popped' card until passed and received by another Deck like object receive n amount of cards and put on bottom of PlayingDeck instance, that is the left side of the deck_container #designed to receive another deque object #needs to take each element of the deque and append it to self.deck_container pd = PlayingDeck(PlayingCard) another_playing_deck = PlayingDeck(PlayingCard) another_playing_deck.receive_n_cards( pd.pass_n_cards(22) ) print len(another_playing_deck.deck_container) print(another_playing_deck) print pd.deck_container[0] print pd.deck_container[0].color print pd.deck_container[1] print pd.deck_container[1].color #unnecessary list "dead-end" code alley below #self.deck_container.insert( self.deck_container[randint], self.deck_container[randint:] ) | 3.95139 | 4 |
loldib/getratings/models/NA/na_veigar/na_veigar_top.py | koliupy/loldib | 0 | 6623118 | <filename>loldib/getratings/models/NA/na_veigar/na_veigar_top.py
from getratings.models.ratings import Ratings
class NA_Veigar_Top_Aatrox(Ratings):
pass
class NA_Veigar_Top_Ahri(Ratings):
pass
class NA_Veigar_Top_Akali(Ratings):
pass
class NA_Veigar_Top_Alistar(Ratings):
pass
class NA_Veigar_Top_Amumu(Ratings):
pass
class NA_Veigar_Top_Anivia(Ratings):
pass
class NA_Veigar_Top_Annie(Ratings):
pass
class NA_Veigar_Top_Ashe(Ratings):
pass
class NA_Veigar_Top_AurelionSol(Ratings):
pass
class NA_Veigar_Top_Azir(Ratings):
pass
class NA_Veigar_Top_Bard(Ratings):
pass
class NA_Veigar_Top_Blitzcrank(Ratings):
pass
class NA_Veigar_Top_Brand(Ratings):
pass
class NA_Veigar_Top_Braum(Ratings):
pass
class NA_Veigar_Top_Caitlyn(Ratings):
pass
class NA_Veigar_Top_Camille(Ratings):
pass
class NA_Veigar_Top_Cassiopeia(Ratings):
pass
class NA_Veigar_Top_Chogath(Ratings):
pass
class NA_Veigar_Top_Corki(Ratings):
pass
class NA_Veigar_Top_Darius(Ratings):
pass
class NA_Veigar_Top_Diana(Ratings):
pass
class NA_Veigar_Top_Draven(Ratings):
pass
class NA_Veigar_Top_DrMundo(Ratings):
pass
class NA_Veigar_Top_Ekko(Ratings):
pass
class NA_Veigar_Top_Elise(Ratings):
pass
class NA_Veigar_Top_Evelynn(Ratings):
pass
class NA_Veigar_Top_Ezreal(Ratings):
pass
class NA_Veigar_Top_Fiddlesticks(Ratings):
pass
class NA_Veigar_Top_Fiora(Ratings):
pass
class NA_Veigar_Top_Fizz(Ratings):
pass
class NA_Veigar_Top_Galio(Ratings):
pass
class NA_Veigar_Top_Gangplank(Ratings):
pass
class NA_Veigar_Top_Garen(Ratings):
pass
class NA_Veigar_Top_Gnar(Ratings):
pass
class NA_Veigar_Top_Gragas(Ratings):
pass
class NA_Veigar_Top_Graves(Ratings):
pass
class NA_Veigar_Top_Hecarim(Ratings):
pass
class NA_Veigar_Top_Heimerdinger(Ratings):
pass
class NA_Veigar_Top_Illaoi(Ratings):
pass
class NA_Veigar_Top_Irelia(Ratings):
pass
class NA_Veigar_Top_Ivern(Ratings):
pass
class NA_Veigar_Top_Janna(Ratings):
pass
class NA_Veigar_Top_JarvanIV(Ratings):
pass
class NA_Veigar_Top_Jax(Ratings):
pass
class NA_Veigar_Top_Jayce(Ratings):
pass
class NA_Veigar_Top_Jhin(Ratings):
pass
class NA_Veigar_Top_Jinx(Ratings):
pass
class NA_Veigar_Top_Kalista(Ratings):
pass
class NA_Veigar_Top_Karma(Ratings):
pass
class NA_Veigar_Top_Karthus(Ratings):
pass
class NA_Veigar_Top_Kassadin(Ratings):
pass
class NA_Veigar_Top_Katarina(Ratings):
pass
class NA_Veigar_Top_Kayle(Ratings):
pass
class NA_Veigar_Top_Kayn(Ratings):
pass
class NA_Veigar_Top_Kennen(Ratings):
pass
class NA_Veigar_Top_Khazix(Ratings):
pass
class NA_Veigar_Top_Kindred(Ratings):
pass
class NA_Veigar_Top_Kled(Ratings):
pass
class NA_Veigar_Top_KogMaw(Ratings):
pass
class NA_Veigar_Top_Leblanc(Ratings):
pass
class NA_Veigar_Top_LeeSin(Ratings):
pass
class NA_Veigar_Top_Leona(Ratings):
pass
class NA_Veigar_Top_Lissandra(Ratings):
pass
class NA_Veigar_Top_Lucian(Ratings):
pass
class NA_Veigar_Top_Lulu(Ratings):
pass
class NA_Veigar_Top_Lux(Ratings):
pass
class NA_Veigar_Top_Malphite(Ratings):
pass
class NA_Veigar_Top_Malzahar(Ratings):
pass
class NA_Veigar_Top_Maokai(Ratings):
pass
class NA_Veigar_Top_MasterYi(Ratings):
pass
class NA_Veigar_Top_MissFortune(Ratings):
pass
class NA_Veigar_Top_MonkeyKing(Ratings):
pass
class NA_Veigar_Top_Mordekaiser(Ratings):
pass
class NA_Veigar_Top_Morgana(Ratings):
pass
class NA_Veigar_Top_Nami(Ratings):
pass
class NA_Veigar_Top_Nasus(Ratings):
pass
class NA_Veigar_Top_Nautilus(Ratings):
pass
class NA_Veigar_Top_Nidalee(Ratings):
pass
class NA_Veigar_Top_Nocturne(Ratings):
pass
class NA_Veigar_Top_Nunu(Ratings):
pass
class NA_Veigar_Top_Olaf(Ratings):
pass
class NA_Veigar_Top_Orianna(Ratings):
pass
class NA_Veigar_Top_Ornn(Ratings):
pass
class NA_Veigar_Top_Pantheon(Ratings):
pass
class NA_Veigar_Top_Poppy(Ratings):
pass
class NA_Veigar_Top_Quinn(Ratings):
pass
class NA_Veigar_Top_Rakan(Ratings):
pass
class NA_Veigar_Top_Rammus(Ratings):
pass
class NA_Veigar_Top_RekSai(Ratings):
pass
class NA_Veigar_Top_Renekton(Ratings):
pass
class NA_Veigar_Top_Rengar(Ratings):
pass
class NA_Veigar_Top_Riven(Ratings):
pass
class NA_Veigar_Top_Rumble(Ratings):
pass
class NA_Veigar_Top_Ryze(Ratings):
pass
class NA_Veigar_Top_Sejuani(Ratings):
pass
class NA_Veigar_Top_Shaco(Ratings):
pass
class NA_Veigar_Top_Shen(Ratings):
pass
class NA_Veigar_Top_Shyvana(Ratings):
pass
class NA_Veigar_Top_Singed(Ratings):
pass
class NA_Veigar_Top_Sion(Ratings):
pass
class NA_Veigar_Top_Sivir(Ratings):
pass
class NA_Veigar_Top_Skarner(Ratings):
pass
class NA_Veigar_Top_Sona(Ratings):
pass
class NA_Veigar_Top_Soraka(Ratings):
pass
class NA_Veigar_Top_Swain(Ratings):
pass
class NA_Veigar_Top_Syndra(Ratings):
pass
class NA_Veigar_Top_TahmKench(Ratings):
pass
class NA_Veigar_Top_Taliyah(Ratings):
pass
class NA_Veigar_Top_Talon(Ratings):
pass
class NA_Veigar_Top_Taric(Ratings):
pass
class NA_Veigar_Top_Teemo(Ratings):
pass
class NA_Veigar_Top_Thresh(Ratings):
pass
class NA_Veigar_Top_Tristana(Ratings):
pass
class NA_Veigar_Top_Trundle(Ratings):
pass
class NA_Veigar_Top_Tryndamere(Ratings):
pass
class NA_Veigar_Top_TwistedFate(Ratings):
pass
class NA_Veigar_Top_Twitch(Ratings):
pass
class NA_Veigar_Top_Udyr(Ratings):
pass
class NA_Veigar_Top_Urgot(Ratings):
pass
class NA_Veigar_Top_Varus(Ratings):
pass
class NA_Veigar_Top_Vayne(Ratings):
pass
class NA_Veigar_Top_Veigar(Ratings):
pass
class NA_Veigar_Top_Velkoz(Ratings):
pass
class NA_Veigar_Top_Vi(Ratings):
pass
class NA_Veigar_Top_Viktor(Ratings):
pass
class NA_Veigar_Top_Vladimir(Ratings):
pass
class NA_Veigar_Top_Volibear(Ratings):
pass
class NA_Veigar_Top_Warwick(Ratings):
pass
class NA_Veigar_Top_Xayah(Ratings):
pass
class NA_Veigar_Top_Xerath(Ratings):
pass
class NA_Veigar_Top_XinZhao(Ratings):
pass
class NA_Veigar_Top_Yasuo(Ratings):
pass
class NA_Veigar_Top_Yorick(Ratings):
pass
class NA_Veigar_Top_Zac(Ratings):
pass
class NA_Veigar_Top_Zed(Ratings):
pass
class NA_Veigar_Top_Ziggs(Ratings):
pass
class NA_Veigar_Top_Zilean(Ratings):
pass
class NA_Veigar_Top_Zyra(Ratings):
pass
| <filename>loldib/getratings/models/NA/na_veigar/na_veigar_top.py
from getratings.models.ratings import Ratings
class NA_Veigar_Top_Aatrox(Ratings):
pass
class NA_Veigar_Top_Ahri(Ratings):
pass
class NA_Veigar_Top_Akali(Ratings):
pass
class NA_Veigar_Top_Alistar(Ratings):
pass
class NA_Veigar_Top_Amumu(Ratings):
pass
class NA_Veigar_Top_Anivia(Ratings):
pass
class NA_Veigar_Top_Annie(Ratings):
pass
class NA_Veigar_Top_Ashe(Ratings):
pass
class NA_Veigar_Top_AurelionSol(Ratings):
pass
class NA_Veigar_Top_Azir(Ratings):
pass
class NA_Veigar_Top_Bard(Ratings):
pass
class NA_Veigar_Top_Blitzcrank(Ratings):
pass
class NA_Veigar_Top_Brand(Ratings):
pass
class NA_Veigar_Top_Braum(Ratings):
pass
class NA_Veigar_Top_Caitlyn(Ratings):
pass
class NA_Veigar_Top_Camille(Ratings):
pass
class NA_Veigar_Top_Cassiopeia(Ratings):
pass
class NA_Veigar_Top_Chogath(Ratings):
pass
class NA_Veigar_Top_Corki(Ratings):
pass
class NA_Veigar_Top_Darius(Ratings):
pass
class NA_Veigar_Top_Diana(Ratings):
pass
class NA_Veigar_Top_Draven(Ratings):
pass
class NA_Veigar_Top_DrMundo(Ratings):
pass
class NA_Veigar_Top_Ekko(Ratings):
pass
class NA_Veigar_Top_Elise(Ratings):
pass
class NA_Veigar_Top_Evelynn(Ratings):
pass
class NA_Veigar_Top_Ezreal(Ratings):
pass
class NA_Veigar_Top_Fiddlesticks(Ratings):
pass
class NA_Veigar_Top_Fiora(Ratings):
pass
class NA_Veigar_Top_Fizz(Ratings):
pass
class NA_Veigar_Top_Galio(Ratings):
pass
class NA_Veigar_Top_Gangplank(Ratings):
pass
class NA_Veigar_Top_Garen(Ratings):
pass
class NA_Veigar_Top_Gnar(Ratings):
pass
class NA_Veigar_Top_Gragas(Ratings):
pass
class NA_Veigar_Top_Graves(Ratings):
pass
class NA_Veigar_Top_Hecarim(Ratings):
pass
class NA_Veigar_Top_Heimerdinger(Ratings):
pass
class NA_Veigar_Top_Illaoi(Ratings):
pass
class NA_Veigar_Top_Irelia(Ratings):
pass
class NA_Veigar_Top_Ivern(Ratings):
pass
class NA_Veigar_Top_Janna(Ratings):
pass
class NA_Veigar_Top_JarvanIV(Ratings):
pass
class NA_Veigar_Top_Jax(Ratings):
pass
class NA_Veigar_Top_Jayce(Ratings):
pass
class NA_Veigar_Top_Jhin(Ratings):
pass
class NA_Veigar_Top_Jinx(Ratings):
pass
class NA_Veigar_Top_Kalista(Ratings):
pass
class NA_Veigar_Top_Karma(Ratings):
pass
class NA_Veigar_Top_Karthus(Ratings):
pass
class NA_Veigar_Top_Kassadin(Ratings):
pass
class NA_Veigar_Top_Katarina(Ratings):
pass
class NA_Veigar_Top_Kayle(Ratings):
pass
class NA_Veigar_Top_Kayn(Ratings):
pass
class NA_Veigar_Top_Kennen(Ratings):
pass
class NA_Veigar_Top_Khazix(Ratings):
pass
class NA_Veigar_Top_Kindred(Ratings):
pass
class NA_Veigar_Top_Kled(Ratings):
pass
class NA_Veigar_Top_KogMaw(Ratings):
pass
class NA_Veigar_Top_Leblanc(Ratings):
pass
class NA_Veigar_Top_LeeSin(Ratings):
pass
class NA_Veigar_Top_Leona(Ratings):
pass
class NA_Veigar_Top_Lissandra(Ratings):
pass
class NA_Veigar_Top_Lucian(Ratings):
pass
class NA_Veigar_Top_Lulu(Ratings):
pass
class NA_Veigar_Top_Lux(Ratings):
pass
class NA_Veigar_Top_Malphite(Ratings):
pass
class NA_Veigar_Top_Malzahar(Ratings):
pass
class NA_Veigar_Top_Maokai(Ratings):
pass
class NA_Veigar_Top_MasterYi(Ratings):
pass
class NA_Veigar_Top_MissFortune(Ratings):
pass
class NA_Veigar_Top_MonkeyKing(Ratings):
pass
class NA_Veigar_Top_Mordekaiser(Ratings):
pass
class NA_Veigar_Top_Morgana(Ratings):
pass
class NA_Veigar_Top_Nami(Ratings):
pass
class NA_Veigar_Top_Nasus(Ratings):
pass
class NA_Veigar_Top_Nautilus(Ratings):
pass
class NA_Veigar_Top_Nidalee(Ratings):
pass
class NA_Veigar_Top_Nocturne(Ratings):
pass
class NA_Veigar_Top_Nunu(Ratings):
pass
class NA_Veigar_Top_Olaf(Ratings):
pass
class NA_Veigar_Top_Orianna(Ratings):
pass
class NA_Veigar_Top_Ornn(Ratings):
pass
class NA_Veigar_Top_Pantheon(Ratings):
pass
class NA_Veigar_Top_Poppy(Ratings):
pass
class NA_Veigar_Top_Quinn(Ratings):
pass
class NA_Veigar_Top_Rakan(Ratings):
pass
class NA_Veigar_Top_Rammus(Ratings):
pass
class NA_Veigar_Top_RekSai(Ratings):
pass
class NA_Veigar_Top_Renekton(Ratings):
pass
class NA_Veigar_Top_Rengar(Ratings):
pass
class NA_Veigar_Top_Riven(Ratings):
pass
class NA_Veigar_Top_Rumble(Ratings):
pass
class NA_Veigar_Top_Ryze(Ratings):
pass
class NA_Veigar_Top_Sejuani(Ratings):
pass
class NA_Veigar_Top_Shaco(Ratings):
pass
class NA_Veigar_Top_Shen(Ratings):
pass
class NA_Veigar_Top_Shyvana(Ratings):
pass
class NA_Veigar_Top_Singed(Ratings):
pass
class NA_Veigar_Top_Sion(Ratings):
pass
class NA_Veigar_Top_Sivir(Ratings):
pass
class NA_Veigar_Top_Skarner(Ratings):
pass
class NA_Veigar_Top_Sona(Ratings):
pass
class NA_Veigar_Top_Soraka(Ratings):
pass
class NA_Veigar_Top_Swain(Ratings):
pass
class NA_Veigar_Top_Syndra(Ratings):
pass
class NA_Veigar_Top_TahmKench(Ratings):
pass
class NA_Veigar_Top_Taliyah(Ratings):
pass
class NA_Veigar_Top_Talon(Ratings):
pass
class NA_Veigar_Top_Taric(Ratings):
pass
class NA_Veigar_Top_Teemo(Ratings):
pass
class NA_Veigar_Top_Thresh(Ratings):
pass
class NA_Veigar_Top_Tristana(Ratings):
pass
class NA_Veigar_Top_Trundle(Ratings):
pass
class NA_Veigar_Top_Tryndamere(Ratings):
pass
class NA_Veigar_Top_TwistedFate(Ratings):
pass
class NA_Veigar_Top_Twitch(Ratings):
pass
class NA_Veigar_Top_Udyr(Ratings):
pass
class NA_Veigar_Top_Urgot(Ratings):
pass
class NA_Veigar_Top_Varus(Ratings):
pass
class NA_Veigar_Top_Vayne(Ratings):
pass
class NA_Veigar_Top_Veigar(Ratings):
pass
class NA_Veigar_Top_Velkoz(Ratings):
pass
class NA_Veigar_Top_Vi(Ratings):
pass
class NA_Veigar_Top_Viktor(Ratings):
pass
class NA_Veigar_Top_Vladimir(Ratings):
pass
class NA_Veigar_Top_Volibear(Ratings):
pass
class NA_Veigar_Top_Warwick(Ratings):
pass
class NA_Veigar_Top_Xayah(Ratings):
pass
class NA_Veigar_Top_Xerath(Ratings):
pass
class NA_Veigar_Top_XinZhao(Ratings):
pass
class NA_Veigar_Top_Yasuo(Ratings):
pass
class NA_Veigar_Top_Yorick(Ratings):
pass
class NA_Veigar_Top_Zac(Ratings):
pass
class NA_Veigar_Top_Zed(Ratings):
pass
class NA_Veigar_Top_Ziggs(Ratings):
pass
class NA_Veigar_Top_Zilean(Ratings):
pass
class NA_Veigar_Top_Zyra(Ratings):
pass
| none | 1 | 1.493826 | 1 | |
core/utilities/__init__.py | yellowbyte/zero-footprint-opaque-predicates | 6 | 6623119 | """Contains general utilities functions and global configs."""
import logging
import argparse
import subprocess # noqa
from .framac_engineer import * # noqa
# Configurations
######################
__CONFIGS = {
'metadata_dir': '/tmp', # noqa
'delete_metadata': True,
'srcfolder': None,
# Obfuscation for the inserted opaque predicates
# We purposely make it deterministic so we can detect our
# opaque predicates for evaluation with other deobfuscation tools.
# Also in practice, the obfuscation shouldn't always be the same sequence.
# Or else it can be easily detected from the obfuscation.
'obfuscation': '__asm__ __volatile__(\"xor %eax, %eax;xor %esp, %esp;xor %ebp, %ebp; add %eax, %esp;\");', # noqa
# NOTE: python can only hold so many values in-memory.
# Higher "value_set_limit" allows you to possibly generate
# more opaque predicates but will also slow down program or
# worst-case, prematurely terminate it.
'value_set_limit': 100000000, # we found this value to work well for our
# benchmark. Can choose a larger value.
# However, if program terminates prematurely, choose a smaller value (10000)
# Specific to running Frama-C
'framac_macro': 'Frama_C_show_each_',
'framac_vars': ['__retres', 'Frama_C_entropy_source',
'__fc_', '__realloc_', '__malloc_'],
# stubs to analyze frama-c
'ignored_files': ['fc_stubs.c', 'fc_stubs.h'],
# function specific to the frama-c value analysis
'ignored_functions': ['eva_main'],
}
def parse_args():
"""
"""
parser = argparse.ArgumentParser()
parser.add_argument('-m',
'--metadatadir',
type=str,
required=False,
help=('path to directory where metadata will be stored.'
'Default to /tmp'))
parser.add_argument('-l',
'--limits',
type=int,
required=False,
help=('the max value set length to consider.'
'Too small may lead to few synthesized opaque'
'predicates. Too large may lead to crash.'
'Default to 100000000'))
parser.add_argument('srcfolder',
type=str,
help='folder containing source code to obfuscate')
parser.add_argument('--delmetadata',
action=argparse.BooleanOptionalAction,
required=False,
help=('set to either True or False. Decides whether to'
'delete the metadata folder. Default to True'))
args = parser.parse_args()
# Set configurations
set_configs(args)
def get_configs():
"""
"""
global __CONFIGS
return __CONFIGS
def set_configs(args):
"""Set `configs` based on commandline arguments `args`.
Args:
args: commandline arguments
Return:
None
"""
global __CONFIGS
__CONFIGS['srcfolder'] = args.srcfolder
if args.metadatadir:
__CONFIGS['metadata_dir'] = args.metadatadir
if args.delmetadata is False:
# by default True
__CONFIGS['delete_metadata'] = False
if args.limits:
__CONFIGS['value_set_limit'] = args.limits
def shell_exec(cmd):
"""Run `cmd` in shell.
Args:
cmd: command to run by the shell
Returns:
output from running cmd in the shell
"""
logging.debug(cmd)
# Capture_output argument is only available in Python >= 3.7
result = subprocess.run(cmd.split(), capture_output=True) # noqa
logging.debug('SHELL_EXEC: '+result.stdout.decode('utf-8').rstrip('\n'))
return result.stdout.decode('utf-8').rstrip('\n')
def get_file_content(filepath, return_type='list'):
"""Bring content of file at `filepath` to memory.
Args:
filepath: file to read content of
return_type: data structure to represent content in
"""
with open(filepath, 'r') as f:
if return_type == 'list':
content = [line.rstrip('\n') for line in f.readlines()]
else:
content = f.read()
return content
| """Contains general utilities functions and global configs."""
import logging
import argparse
import subprocess # noqa
from .framac_engineer import * # noqa
# Configurations
######################
__CONFIGS = {
'metadata_dir': '/tmp', # noqa
'delete_metadata': True,
'srcfolder': None,
# Obfuscation for the inserted opaque predicates
# We purposely make it deterministic so we can detect our
# opaque predicates for evaluation with other deobfuscation tools.
# Also in practice, the obfuscation shouldn't always be the same sequence.
# Or else it can be easily detected from the obfuscation.
'obfuscation': '__asm__ __volatile__(\"xor %eax, %eax;xor %esp, %esp;xor %ebp, %ebp; add %eax, %esp;\");', # noqa
# NOTE: python can only hold so many values in-memory.
# Higher "value_set_limit" allows you to possibly generate
# more opaque predicates but will also slow down program or
# worst-case, prematurely terminate it.
'value_set_limit': 100000000, # we found this value to work well for our
# benchmark. Can choose a larger value.
# However, if program terminates prematurely, choose a smaller value (10000)
# Specific to running Frama-C
'framac_macro': 'Frama_C_show_each_',
'framac_vars': ['__retres', 'Frama_C_entropy_source',
'__fc_', '__realloc_', '__malloc_'],
# stubs to analyze frama-c
'ignored_files': ['fc_stubs.c', 'fc_stubs.h'],
# function specific to the frama-c value analysis
'ignored_functions': ['eva_main'],
}
def parse_args():
"""
"""
parser = argparse.ArgumentParser()
parser.add_argument('-m',
'--metadatadir',
type=str,
required=False,
help=('path to directory where metadata will be stored.'
'Default to /tmp'))
parser.add_argument('-l',
'--limits',
type=int,
required=False,
help=('the max value set length to consider.'
'Too small may lead to few synthesized opaque'
'predicates. Too large may lead to crash.'
'Default to 100000000'))
parser.add_argument('srcfolder',
type=str,
help='folder containing source code to obfuscate')
parser.add_argument('--delmetadata',
action=argparse.BooleanOptionalAction,
required=False,
help=('set to either True or False. Decides whether to'
'delete the metadata folder. Default to True'))
args = parser.parse_args()
# Set configurations
set_configs(args)
def get_configs():
"""
"""
global __CONFIGS
return __CONFIGS
def set_configs(args):
"""Set `configs` based on commandline arguments `args`.
Args:
args: commandline arguments
Return:
None
"""
global __CONFIGS
__CONFIGS['srcfolder'] = args.srcfolder
if args.metadatadir:
__CONFIGS['metadata_dir'] = args.metadatadir
if args.delmetadata is False:
# by default True
__CONFIGS['delete_metadata'] = False
if args.limits:
__CONFIGS['value_set_limit'] = args.limits
def shell_exec(cmd):
"""Run `cmd` in shell.
Args:
cmd: command to run by the shell
Returns:
output from running cmd in the shell
"""
logging.debug(cmd)
# Capture_output argument is only available in Python >= 3.7
result = subprocess.run(cmd.split(), capture_output=True) # noqa
logging.debug('SHELL_EXEC: '+result.stdout.decode('utf-8').rstrip('\n'))
return result.stdout.decode('utf-8').rstrip('\n')
def get_file_content(filepath, return_type='list'):
"""Bring content of file at `filepath` to memory.
Args:
filepath: file to read content of
return_type: data structure to represent content in
"""
with open(filepath, 'r') as f:
if return_type == 'list':
content = [line.rstrip('\n') for line in f.readlines()]
else:
content = f.read()
return content
| en | 0.763789 | Contains general utilities functions and global configs. # noqa # noqa # Configurations ###################### # noqa # Obfuscation for the inserted opaque predicates # We purposely make it deterministic so we can detect our # opaque predicates for evaluation with other deobfuscation tools. # Also in practice, the obfuscation shouldn't always be the same sequence. # Or else it can be easily detected from the obfuscation. # noqa # NOTE: python can only hold so many values in-memory. # Higher "value_set_limit" allows you to possibly generate # more opaque predicates but will also slow down program or # worst-case, prematurely terminate it. # we found this value to work well for our # benchmark. Can choose a larger value. # However, if program terminates prematurely, choose a smaller value (10000) # Specific to running Frama-C # stubs to analyze frama-c # function specific to the frama-c value analysis # Set configurations Set `configs` based on commandline arguments `args`. Args: args: commandline arguments Return: None # by default True Run `cmd` in shell. Args: cmd: command to run by the shell Returns: output from running cmd in the shell # Capture_output argument is only available in Python >= 3.7 # noqa Bring content of file at `filepath` to memory. Args: filepath: file to read content of return_type: data structure to represent content in | 2.443652 | 2 |
dcbench/common/table.py | data-centric-ai/dcbench | 40 | 6623120 | <reponame>data-centric-ai/dcbench
import copy
from dataclasses import dataclass
from itertools import chain
from typing import Dict, Iterator, Mapping, Optional, Sequence, Union
import pandas as pd
Attribute = Union[int, float, str, bool]
@dataclass
class AttributeSpec:
description: str
attribute_type: type
optional: bool = False
class RowMixin:
attribute_specs: Mapping[str, AttributeSpec]
def __init__(self, id: str, attributes: Mapping[str, Attribute] = None):
self.id = id
self._attributes = attributes
@property
def attributes(self) -> Optional[Mapping[str, Attribute]]:
return self._attributes
@attributes.setter
def attributes(self, value: Mapping[str, Attribute]):
self._check_attribute_specs(value)
self._attributes = value
@classmethod
def _check_attribute_specs(cls, attributes: Mapping[str, Attribute]):
for name, attribute in attributes.items():
if name not in cls.attribute_specs:
raise ValueError(
f"Passed attribute name '{name}', but the specification for"
f" {cls.__name__} doesn't include it."
)
if not isinstance(attribute, cls.attribute_specs[name].attribute_type):
raise ValueError(
f"Passed an attribute of type {type(attribute)} to {cls.__name__}"
f" for the attribute named '{name}'. The specification for"
f" {cls.__name__} expects an attribute of type"
f" {cls.attribute_specs[name].attribute_type}."
)
for name, attribute_spec in cls.attribute_specs.items():
if attribute_spec.optional:
continue
if name not in attributes:
raise ValueError(
f"Must pass required attribute with key {name} to {cls.__name__}."
)
class RowUnion(RowMixin):
def __init__(self, id: str, elements: Sequence[RowMixin]):
self._elements = elements
attributes: Dict[str, Attribute] = {}
for element in reversed(elements):
attributes.update(element.attributes)
super().__init__(id, attributes=attributes)
def predicate(a: Attribute, b: Union[Attribute, slice, Sequence[Attribute]]) -> bool:
if isinstance(b, slice):
return (b.start is not None and a >= b.start) and (
b.stop is not None and a < b.stop
)
elif isinstance(b, Sequence):
return a in b
else:
return a == b
class Table(Mapping[str, RowMixin]):
def __init__(self, data: Sequence[RowMixin]):
self._data = {item.id: item for item in data}
def __getitem__(self, k: str) -> RowMixin:
result = self._data.get(k, None)
if result is None:
raise KeyError()
return result
def __iter__(self) -> Iterator[str]:
return self._data.__iter__()
def __len__(self) -> int:
return self._data.__len__()
def _add_row(self, row: RowMixin) -> None:
self._data[row.id] = row
@property
def df(self):
return pd.DataFrame.from_dict(
{k: v.attributes for k, v in self._data.items()}, orient="index"
)
def where(self, **kwargs: Union[Attribute, slice, Sequence[Attribute]]) -> "Table":
result_data = [
item
for item in self._data.values()
if all(
predicate(item.attributes.get(k, None), v) for (k, v) in kwargs.items()
)
]
return type(self)(result_data)
def average(
self, *targets: str, groupby: Optional[Sequence[str]] = None, std: bool = False
) -> "Table":
groupby = groupby or []
df = self.df[chain(targets, groupby)]
if groupby is not None and len(groupby) > 0:
df = df.groupby(groupby)
df_result = df.mean()
if isinstance(df_result, pd.Series):
df_result = df_result.to_frame().T
if std:
df_std = df.std()
if isinstance(df_std, pd.Series):
df_std = df_std.to_frame().T
df_result = pd.merge(
df_result,
df_std,
left_index=True,
right_index=True,
suffixes=("", ":std"),
)
df_result = df_result.reset_index()
result_rows = [
RowMixin(id=str(id), attributes=row) for id, row in df_result.iterrows()
]
return Table(result_rows)
def __repr__(self) -> str:
return self.df.__repr__()
def _repr_html_(self) -> Optional[str]:
return self.df._repr_html_()
def __add__(self, other: RowMixin) -> "Table":
result = copy.deepcopy(self)
result._add_row(other)
return result
def __iadd__(self, other: RowMixin) -> "Table":
self._add_row(other)
return self
| import copy
from dataclasses import dataclass
from itertools import chain
from typing import Dict, Iterator, Mapping, Optional, Sequence, Union
import pandas as pd
Attribute = Union[int, float, str, bool]
@dataclass
class AttributeSpec:
description: str
attribute_type: type
optional: bool = False
class RowMixin:
attribute_specs: Mapping[str, AttributeSpec]
def __init__(self, id: str, attributes: Mapping[str, Attribute] = None):
self.id = id
self._attributes = attributes
@property
def attributes(self) -> Optional[Mapping[str, Attribute]]:
return self._attributes
@attributes.setter
def attributes(self, value: Mapping[str, Attribute]):
self._check_attribute_specs(value)
self._attributes = value
@classmethod
def _check_attribute_specs(cls, attributes: Mapping[str, Attribute]):
for name, attribute in attributes.items():
if name not in cls.attribute_specs:
raise ValueError(
f"Passed attribute name '{name}', but the specification for"
f" {cls.__name__} doesn't include it."
)
if not isinstance(attribute, cls.attribute_specs[name].attribute_type):
raise ValueError(
f"Passed an attribute of type {type(attribute)} to {cls.__name__}"
f" for the attribute named '{name}'. The specification for"
f" {cls.__name__} expects an attribute of type"
f" {cls.attribute_specs[name].attribute_type}."
)
for name, attribute_spec in cls.attribute_specs.items():
if attribute_spec.optional:
continue
if name not in attributes:
raise ValueError(
f"Must pass required attribute with key {name} to {cls.__name__}."
)
class RowUnion(RowMixin):
def __init__(self, id: str, elements: Sequence[RowMixin]):
self._elements = elements
attributes: Dict[str, Attribute] = {}
for element in reversed(elements):
attributes.update(element.attributes)
super().__init__(id, attributes=attributes)
def predicate(a: Attribute, b: Union[Attribute, slice, Sequence[Attribute]]) -> bool:
if isinstance(b, slice):
return (b.start is not None and a >= b.start) and (
b.stop is not None and a < b.stop
)
elif isinstance(b, Sequence):
return a in b
else:
return a == b
class Table(Mapping[str, RowMixin]):
def __init__(self, data: Sequence[RowMixin]):
self._data = {item.id: item for item in data}
def __getitem__(self, k: str) -> RowMixin:
result = self._data.get(k, None)
if result is None:
raise KeyError()
return result
def __iter__(self) -> Iterator[str]:
return self._data.__iter__()
def __len__(self) -> int:
return self._data.__len__()
def _add_row(self, row: RowMixin) -> None:
self._data[row.id] = row
@property
def df(self):
return pd.DataFrame.from_dict(
{k: v.attributes for k, v in self._data.items()}, orient="index"
)
def where(self, **kwargs: Union[Attribute, slice, Sequence[Attribute]]) -> "Table":
result_data = [
item
for item in self._data.values()
if all(
predicate(item.attributes.get(k, None), v) for (k, v) in kwargs.items()
)
]
return type(self)(result_data)
def average(
self, *targets: str, groupby: Optional[Sequence[str]] = None, std: bool = False
) -> "Table":
groupby = groupby or []
df = self.df[chain(targets, groupby)]
if groupby is not None and len(groupby) > 0:
df = df.groupby(groupby)
df_result = df.mean()
if isinstance(df_result, pd.Series):
df_result = df_result.to_frame().T
if std:
df_std = df.std()
if isinstance(df_std, pd.Series):
df_std = df_std.to_frame().T
df_result = pd.merge(
df_result,
df_std,
left_index=True,
right_index=True,
suffixes=("", ":std"),
)
df_result = df_result.reset_index()
result_rows = [
RowMixin(id=str(id), attributes=row) for id, row in df_result.iterrows()
]
return Table(result_rows)
def __repr__(self) -> str:
return self.df.__repr__()
def _repr_html_(self) -> Optional[str]:
return self.df._repr_html_()
def __add__(self, other: RowMixin) -> "Table":
result = copy.deepcopy(self)
result._add_row(other)
return result
def __iadd__(self, other: RowMixin) -> "Table":
self._add_row(other)
return self | none | 1 | 2.541132 | 3 | |
cate/ops/plot_helpers.py | strawpants/cate | 34 | 6623121 | <reponame>strawpants/cate
# The MIT License (MIT)
# Copyright (c) 2016, 2017 by the ESA CCI Toolbox development team and contributors
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of
# this software and associated documentation files (the "Software"), to deal in
# the Software without restriction, including without limitation the rights to
# use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
# of the Software, and to permit persons to whom the Software is furnished to do
# so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
"""
Description
===========
Helpers for data visualization operations (plot and animate).
Components
==========
"""
from cate.core.types import PolygonLike, ValidationError
from cate.core.opimpl import get_extents
from cate.util.im import ensure_cmaps_loaded
def handle_plot_polygon(region: PolygonLike.TYPE = None):
"""
Return extents of the given PolygonLike.
:param region: PolygonLike to introspect
:return: extents
"""
if region is None:
return None
extents, explicit_coords = get_extents(region)
lon_min, lat_min, lon_max, lat_max = extents
if not check_bounding_box(lat_min, lat_max, lon_min, lon_max):
raise ValidationError('Provided plot extents do not form a valid bounding box '
'within [-180.0,+180.0,-90.0,+90.0]')
return extents
def check_bounding_box(lat_min: float,
lat_max: float,
lon_min: float,
lon_max: float) -> bool:
"""
Check if the provided [lat_min, lat_max, lon_min, lon_max] extents
are sane.
"""
if lat_min >= lat_max:
return False
if lon_min >= lon_max:
return False
if lat_min < -90.0:
return False
if lat_max > 90.0:
return False
if lon_min < -180.0:
return False
if lon_max > 180.0:
return False
return True
def in_notebook():
"""
Return ``True`` if the module is running in IPython kernel,
``False`` if in IPython shell or other Python shell.
"""
import sys
ipykernel_in_sys_modules = 'ipykernel' in sys.modules
# print('###########################################', ipykernel_in_sys_modules)
return ipykernel_in_sys_modules
def get_var_data(var, indexers: dict, remaining_dims=None):
"""Select an arbitrary piece of an xarray dataset by using indexers."""
if indexers:
if remaining_dims:
for dim in remaining_dims:
if dim not in var.dims:
raise ValidationError(f'The specified dataset does not have a dimension called \'{dim}\'.')
if dim in indexers:
raise ValidationError(f'Dimension \'{dim}\' is also specified as indexers. Please ensure that a '
f'dimension is used exclusively either as indexers or as the selected '
f'dimension.')
for dim in indexers:
if dim not in var.dims:
raise ValidationError(f'The specified dataset does not have a dimension called \'{dim}\'.')
var = var.sel(method='nearest', **indexers)
if remaining_dims:
isel_indexers = {dim_name: 0 for dim_name in var.dims if dim_name not in remaining_dims}
var = var.isel(**isel_indexers)
return var
def get_vars_data(ds, indexers: dict, remaining_dims=None):
"""Select an arbitrary piece of an xarray dataset by using indexers."""
# to avoid the original dataset being affected (especially useful in unit tests)
ds = ds.copy()
if indexers:
invalid_indexers = list(indexers)
for var_name in ds:
if ds[var_name].name in ds[var_name].dims:
continue
var_indexers = {}
if remaining_dims:
for dim in remaining_dims:
if dim not in ds[var_name].dims:
raise ValidationError(f'The specified dataset does not have a dimension called \'{dim}\'.')
if dim in indexers:
raise ValidationError(
f'Dimension \'{dim}\' is also specified as indexers. Please ensure that a '
f'dimension is used exclusively either as indexers or as the selected '
f'dimension.')
for dim in ds[var_name].dims:
if dim in indexers:
var_indexers[dim] = indexers[dim]
for dim in invalid_indexers:
if dim in ds[var_name].dims:
invalid_indexers.remove(dim)
ds[var_name] = ds[var_name].sel(method='nearest', **var_indexers)
if remaining_dims:
isel_indexers = {dim_name: 0 for dim_name in ds[var_name].dims if dim_name not in remaining_dims}
ds[var_name] = ds[var_name].isel(**isel_indexers)
if len(invalid_indexers) > 0:
raise ValidationError(f'There are dimensions specified in indexers but do not match dimensions in '
f'any variables: {invalid_indexers}')
return ds
# determine_cmap_params is adapted from Xarray through Seaborn:
# https://github.com/pydata/xarray/blob/master/xarray/plot/utils.py#L151
# https://github.com/mwaskom/seaborn/blob/v0.6/seaborn/matrix.py#L158
# Used under the terms of Seaborn's license:
# https://github.com/mwaskom/seaborn/blob/v0.8.1/LICENSE
#
# _determine_extend, _build_discrete_cmap, _color_palette, _is_scalar are
# adapted from Xarray and used under Xarray license:
# https://github.com/pydata/xarray/blob/v0.10.0/LICENSE
ROBUST_QUANTILE = 0.02
def determine_cmap_params(data_min, data_max, vmin=None, vmax=None, cmap=None,
center=None, robust=False, extend=None,
levels=None, filled=True, norm=None):
"""
Use some heuristics to set good defaults for colorbar and range.
:param plot_data: Data to use to determine colormap parameters
:return: A dictionary containing calculated parameters
"""
import matplotlib as mpl
import numpy as np
# Setting center=False prevents a divergent cmap
possibly_divergent = center is not False
# Set center to 0 so math below makes sense but remember its state
center_is_none = False
if center is None:
center = 0
center_is_none = True
# Setting both vmin and vmax prevents a divergent cmap
if (vmin is not None) and (vmax is not None):
possibly_divergent = False
# Setting vmin or vmax implies linspaced levels
user_minmax = (vmin is not None) or (vmax is not None)
# vlim might be computed below
vlim = None
if vmin is None:
vmin = data_min
elif possibly_divergent:
vlim = abs(vmin - center)
if vmax is None:
vmax = data_max
elif possibly_divergent:
vlim = abs(vmax - center)
if possibly_divergent:
# kwargs not specific about divergent or not: infer defaults from data
divergent = ((vmin < 0) and (vmax > 0)) or not center_is_none
else:
divergent = False
# A divergent map should be symmetric around the center value
if divergent:
if vlim is None:
vlim = max(abs(vmin - center), abs(vmax - center))
vmin, vmax = -vlim, vlim
# Now add in the centering value and set the limits
vmin += center
vmax += center
# Choose default colormaps if not provided
if cmap is None:
if divergent:
cmap = "RdBu_r"
else:
cmap = "viridis"
# Handle discrete levels
if levels is not None:
if _is_scalar(levels):
if user_minmax or levels == 1:
levels = np.linspace(vmin, vmax, levels)
else:
# N in MaxNLocator refers to bins, not ticks
ticker = mpl.ticker.MaxNLocator(levels - 1)
levels = ticker.tick_values(vmin, vmax)
vmin, vmax = levels[0], levels[-1]
if extend is None:
extend = _determine_extend(data_min, data_max, vmin, vmax)
if levels is not None:
cmap, norm = _build_discrete_cmap(cmap, levels, extend, filled)
return dict(vmin=vmin, vmax=vmax, cmap=cmap, extend=extend,
levels=levels, norm=norm)
def _determine_extend(data_min, data_max, vmin, vmax):
extend_min = data_min < vmin
extend_max = data_max > vmax
if extend_min and extend_max:
extend = 'both'
elif extend_min:
extend = 'min'
elif extend_max:
extend = 'max'
else:
extend = 'neither'
return extend
def _build_discrete_cmap(cmap, levels, extend, filled):
"""Build a discrete colormap and normalization of the data."""
import matplotlib as mpl
if not filled:
# non-filled contour plots
extend = 'max'
if extend == 'both':
ext_n = 2
elif extend in ['min', 'max']:
ext_n = 1
else:
ext_n = 0
n_colors = len(levels) + ext_n - 1
pal = _color_palette(cmap, n_colors)
new_cmap, cnorm = mpl.colors.from_levels_and_colors(
levels, pal, extend=extend)
# copy the old cmap name, for easier testing
new_cmap.name = getattr(cmap, 'name', cmap)
return new_cmap, cnorm
def _color_palette(cmap, n_colors):
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
import numpy as np
colors_i = np.linspace(0, 1., n_colors)
if isinstance(cmap, (list, tuple)):
# we have a list of colors
cmap = ListedColormap(cmap, N=n_colors)
pal = cmap(colors_i)
elif isinstance(cmap, str):
# we have some sort of named palette
try:
# is this a matplotlib cmap?
ensure_cmaps_loaded()
cmap = plt.get_cmap(cmap)
except ValueError:
# or maybe we just got a single color as a string
cmap = ListedColormap([cmap], N=n_colors)
pal = cmap(colors_i)
else:
# cmap better be a LinearSegmentedColormap (e.g. viridis)
pal = cmap(colors_i)
return pal
def _is_scalar(value):
"""Whether to treat a value as a scalar.
Any non-iterable, string, or 0-D array
"""
from collections import Iterable
return (getattr(value, 'ndim', None) == 0
or isinstance(value, (str, bytes))
or not isinstance(value, (Iterable,)))
| # The MIT License (MIT)
# Copyright (c) 2016, 2017 by the ESA CCI Toolbox development team and contributors
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of
# this software and associated documentation files (the "Software"), to deal in
# the Software without restriction, including without limitation the rights to
# use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
# of the Software, and to permit persons to whom the Software is furnished to do
# so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
"""
Description
===========
Helpers for data visualization operations (plot and animate).
Components
==========
"""
from cate.core.types import PolygonLike, ValidationError
from cate.core.opimpl import get_extents
from cate.util.im import ensure_cmaps_loaded
def handle_plot_polygon(region: PolygonLike.TYPE = None):
"""
Return extents of the given PolygonLike.
:param region: PolygonLike to introspect
:return: extents
"""
if region is None:
return None
extents, explicit_coords = get_extents(region)
lon_min, lat_min, lon_max, lat_max = extents
if not check_bounding_box(lat_min, lat_max, lon_min, lon_max):
raise ValidationError('Provided plot extents do not form a valid bounding box '
'within [-180.0,+180.0,-90.0,+90.0]')
return extents
def check_bounding_box(lat_min: float,
lat_max: float,
lon_min: float,
lon_max: float) -> bool:
"""
Check if the provided [lat_min, lat_max, lon_min, lon_max] extents
are sane.
"""
if lat_min >= lat_max:
return False
if lon_min >= lon_max:
return False
if lat_min < -90.0:
return False
if lat_max > 90.0:
return False
if lon_min < -180.0:
return False
if lon_max > 180.0:
return False
return True
def in_notebook():
"""
Return ``True`` if the module is running in IPython kernel,
``False`` if in IPython shell or other Python shell.
"""
import sys
ipykernel_in_sys_modules = 'ipykernel' in sys.modules
# print('###########################################', ipykernel_in_sys_modules)
return ipykernel_in_sys_modules
def get_var_data(var, indexers: dict, remaining_dims=None):
"""Select an arbitrary piece of an xarray dataset by using indexers."""
if indexers:
if remaining_dims:
for dim in remaining_dims:
if dim not in var.dims:
raise ValidationError(f'The specified dataset does not have a dimension called \'{dim}\'.')
if dim in indexers:
raise ValidationError(f'Dimension \'{dim}\' is also specified as indexers. Please ensure that a '
f'dimension is used exclusively either as indexers or as the selected '
f'dimension.')
for dim in indexers:
if dim not in var.dims:
raise ValidationError(f'The specified dataset does not have a dimension called \'{dim}\'.')
var = var.sel(method='nearest', **indexers)
if remaining_dims:
isel_indexers = {dim_name: 0 for dim_name in var.dims if dim_name not in remaining_dims}
var = var.isel(**isel_indexers)
return var
def get_vars_data(ds, indexers: dict, remaining_dims=None):
"""Select an arbitrary piece of an xarray dataset by using indexers."""
# to avoid the original dataset being affected (especially useful in unit tests)
ds = ds.copy()
if indexers:
invalid_indexers = list(indexers)
for var_name in ds:
if ds[var_name].name in ds[var_name].dims:
continue
var_indexers = {}
if remaining_dims:
for dim in remaining_dims:
if dim not in ds[var_name].dims:
raise ValidationError(f'The specified dataset does not have a dimension called \'{dim}\'.')
if dim in indexers:
raise ValidationError(
f'Dimension \'{dim}\' is also specified as indexers. Please ensure that a '
f'dimension is used exclusively either as indexers or as the selected '
f'dimension.')
for dim in ds[var_name].dims:
if dim in indexers:
var_indexers[dim] = indexers[dim]
for dim in invalid_indexers:
if dim in ds[var_name].dims:
invalid_indexers.remove(dim)
ds[var_name] = ds[var_name].sel(method='nearest', **var_indexers)
if remaining_dims:
isel_indexers = {dim_name: 0 for dim_name in ds[var_name].dims if dim_name not in remaining_dims}
ds[var_name] = ds[var_name].isel(**isel_indexers)
if len(invalid_indexers) > 0:
raise ValidationError(f'There are dimensions specified in indexers but do not match dimensions in '
f'any variables: {invalid_indexers}')
return ds
# determine_cmap_params is adapted from Xarray through Seaborn:
# https://github.com/pydata/xarray/blob/master/xarray/plot/utils.py#L151
# https://github.com/mwaskom/seaborn/blob/v0.6/seaborn/matrix.py#L158
# Used under the terms of Seaborn's license:
# https://github.com/mwaskom/seaborn/blob/v0.8.1/LICENSE
#
# _determine_extend, _build_discrete_cmap, _color_palette, _is_scalar are
# adapted from Xarray and used under Xarray license:
# https://github.com/pydata/xarray/blob/v0.10.0/LICENSE
ROBUST_QUANTILE = 0.02
def determine_cmap_params(data_min, data_max, vmin=None, vmax=None, cmap=None,
center=None, robust=False, extend=None,
levels=None, filled=True, norm=None):
"""
Use some heuristics to set good defaults for colorbar and range.
:param plot_data: Data to use to determine colormap parameters
:return: A dictionary containing calculated parameters
"""
import matplotlib as mpl
import numpy as np
# Setting center=False prevents a divergent cmap
possibly_divergent = center is not False
# Set center to 0 so math below makes sense but remember its state
center_is_none = False
if center is None:
center = 0
center_is_none = True
# Setting both vmin and vmax prevents a divergent cmap
if (vmin is not None) and (vmax is not None):
possibly_divergent = False
# Setting vmin or vmax implies linspaced levels
user_minmax = (vmin is not None) or (vmax is not None)
# vlim might be computed below
vlim = None
if vmin is None:
vmin = data_min
elif possibly_divergent:
vlim = abs(vmin - center)
if vmax is None:
vmax = data_max
elif possibly_divergent:
vlim = abs(vmax - center)
if possibly_divergent:
# kwargs not specific about divergent or not: infer defaults from data
divergent = ((vmin < 0) and (vmax > 0)) or not center_is_none
else:
divergent = False
# A divergent map should be symmetric around the center value
if divergent:
if vlim is None:
vlim = max(abs(vmin - center), abs(vmax - center))
vmin, vmax = -vlim, vlim
# Now add in the centering value and set the limits
vmin += center
vmax += center
# Choose default colormaps if not provided
if cmap is None:
if divergent:
cmap = "RdBu_r"
else:
cmap = "viridis"
# Handle discrete levels
if levels is not None:
if _is_scalar(levels):
if user_minmax or levels == 1:
levels = np.linspace(vmin, vmax, levels)
else:
# N in MaxNLocator refers to bins, not ticks
ticker = mpl.ticker.MaxNLocator(levels - 1)
levels = ticker.tick_values(vmin, vmax)
vmin, vmax = levels[0], levels[-1]
if extend is None:
extend = _determine_extend(data_min, data_max, vmin, vmax)
if levels is not None:
cmap, norm = _build_discrete_cmap(cmap, levels, extend, filled)
return dict(vmin=vmin, vmax=vmax, cmap=cmap, extend=extend,
levels=levels, norm=norm)
def _determine_extend(data_min, data_max, vmin, vmax):
extend_min = data_min < vmin
extend_max = data_max > vmax
if extend_min and extend_max:
extend = 'both'
elif extend_min:
extend = 'min'
elif extend_max:
extend = 'max'
else:
extend = 'neither'
return extend
def _build_discrete_cmap(cmap, levels, extend, filled):
"""Build a discrete colormap and normalization of the data."""
import matplotlib as mpl
if not filled:
# non-filled contour plots
extend = 'max'
if extend == 'both':
ext_n = 2
elif extend in ['min', 'max']:
ext_n = 1
else:
ext_n = 0
n_colors = len(levels) + ext_n - 1
pal = _color_palette(cmap, n_colors)
new_cmap, cnorm = mpl.colors.from_levels_and_colors(
levels, pal, extend=extend)
# copy the old cmap name, for easier testing
new_cmap.name = getattr(cmap, 'name', cmap)
return new_cmap, cnorm
def _color_palette(cmap, n_colors):
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
import numpy as np
colors_i = np.linspace(0, 1., n_colors)
if isinstance(cmap, (list, tuple)):
# we have a list of colors
cmap = ListedColormap(cmap, N=n_colors)
pal = cmap(colors_i)
elif isinstance(cmap, str):
# we have some sort of named palette
try:
# is this a matplotlib cmap?
ensure_cmaps_loaded()
cmap = plt.get_cmap(cmap)
except ValueError:
# or maybe we just got a single color as a string
cmap = ListedColormap([cmap], N=n_colors)
pal = cmap(colors_i)
else:
# cmap better be a LinearSegmentedColormap (e.g. viridis)
pal = cmap(colors_i)
return pal
def _is_scalar(value):
"""Whether to treat a value as a scalar.
Any non-iterable, string, or 0-D array
"""
from collections import Iterable
return (getattr(value, 'ndim', None) == 0
or isinstance(value, (str, bytes))
or not isinstance(value, (Iterable,))) | en | 0.702714 | # The MIT License (MIT) # Copyright (c) 2016, 2017 by the ESA CCI Toolbox development team and contributors # # Permission is hereby granted, free of charge, to any person obtaining a copy of # this software and associated documentation files (the "Software"), to deal in # the Software without restriction, including without limitation the rights to # use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies # of the Software, and to permit persons to whom the Software is furnished to do # so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. Description =========== Helpers for data visualization operations (plot and animate). Components ========== Return extents of the given PolygonLike. :param region: PolygonLike to introspect :return: extents Check if the provided [lat_min, lat_max, lon_min, lon_max] extents are sane. Return ``True`` if the module is running in IPython kernel, ``False`` if in IPython shell or other Python shell. # print('###########################################', ipykernel_in_sys_modules) Select an arbitrary piece of an xarray dataset by using indexers. Select an arbitrary piece of an xarray dataset by using indexers. # to avoid the original dataset being affected (especially useful in unit tests) # determine_cmap_params is adapted from Xarray through Seaborn: # https://github.com/pydata/xarray/blob/master/xarray/plot/utils.py#L151 # https://github.com/mwaskom/seaborn/blob/v0.6/seaborn/matrix.py#L158 # Used under the terms of Seaborn's license: # https://github.com/mwaskom/seaborn/blob/v0.8.1/LICENSE # # _determine_extend, _build_discrete_cmap, _color_palette, _is_scalar are # adapted from Xarray and used under Xarray license: # https://github.com/pydata/xarray/blob/v0.10.0/LICENSE Use some heuristics to set good defaults for colorbar and range. :param plot_data: Data to use to determine colormap parameters :return: A dictionary containing calculated parameters # Setting center=False prevents a divergent cmap # Set center to 0 so math below makes sense but remember its state # Setting both vmin and vmax prevents a divergent cmap # Setting vmin or vmax implies linspaced levels # vlim might be computed below # kwargs not specific about divergent or not: infer defaults from data # A divergent map should be symmetric around the center value # Now add in the centering value and set the limits # Choose default colormaps if not provided # Handle discrete levels # N in MaxNLocator refers to bins, not ticks Build a discrete colormap and normalization of the data. # non-filled contour plots # copy the old cmap name, for easier testing # we have a list of colors # we have some sort of named palette # is this a matplotlib cmap? # or maybe we just got a single color as a string # cmap better be a LinearSegmentedColormap (e.g. viridis) Whether to treat a value as a scalar. Any non-iterable, string, or 0-D array | 1.560701 | 2 |
nipyper/interfaces/__init__.py | jyotishkabiswas/nipyper | 0 | 6623122 | from flask.ext.restful import reqparse, abort, Resource, marshal
from nipyper.app import api
from .registry import registry, interface_spec, module_spec
from .tasks import resolve
from traceback import format_exception
import sys
interfaceParser = reqparse.RequestParser()
interfaceParser.add_argument('inputs', type=dict, location='json', help='specify inputs to the interface')
class Interface(Resource):
# decorators = [auth.login_required]
def get(self, query = ""):
if query == "all":
result = {
'interfaces': {},
'modules': {}
}
for name, face in registry.interfaces.iteritems():
result['interfaces'][name] = marshal(face, interface_spec)
for name, mod in interfaces.modules.iteritems():
result['modules'][name] = marshal(mod, module_spec)
return result
query = query.replace("/", ".")
message = ""
try:
# faster to resolve synchronously rather than go through Celery
result, isInterface = resolve(query)
if result is None:
message = "There is no interface or module at path '/" + query.replace(".", "/") + "'."
abort(404, message)
res = {}
if isInterface:
res['apiVersion'] = '1.0'
res['type'] = 'interface'
res['data'] = marshal(result, interface_spec)
return res
else:
res['apiVersion'] = '1.0'
res['type'] = 'module'
res['data'] = marshal(result, module_spec)
return res
except:
abort(400, message = message)
def post(self, query = ""):
from nipyper.workflows.tasks import parse
args = interfaceParser.parse_args()
query = query.replace("/", ".")
message = ""
if query not in registry.interfaces:
abort(404, message = "There is no interface named " + query)
normalized = {
'type': 'Interface',
'interface': query
}
if 'inputs' in parser:
normalized['inputs'] = parser['inputs']
result = parse.delay(normalized)
return result.id
from nipyper.util import memoize
@memoize
def create_route():
api.add_resource(Interface, '/interfaces/', endpoint = 'module')
api.add_resource(Interface, '/interfaces/<string:query>/', endpoint = 'interface')
api.add_resource(Interface, '/interfaces/<path:query>', endpoint = 'path')
create_route() | from flask.ext.restful import reqparse, abort, Resource, marshal
from nipyper.app import api
from .registry import registry, interface_spec, module_spec
from .tasks import resolve
from traceback import format_exception
import sys
interfaceParser = reqparse.RequestParser()
interfaceParser.add_argument('inputs', type=dict, location='json', help='specify inputs to the interface')
class Interface(Resource):
# decorators = [auth.login_required]
def get(self, query = ""):
if query == "all":
result = {
'interfaces': {},
'modules': {}
}
for name, face in registry.interfaces.iteritems():
result['interfaces'][name] = marshal(face, interface_spec)
for name, mod in interfaces.modules.iteritems():
result['modules'][name] = marshal(mod, module_spec)
return result
query = query.replace("/", ".")
message = ""
try:
# faster to resolve synchronously rather than go through Celery
result, isInterface = resolve(query)
if result is None:
message = "There is no interface or module at path '/" + query.replace(".", "/") + "'."
abort(404, message)
res = {}
if isInterface:
res['apiVersion'] = '1.0'
res['type'] = 'interface'
res['data'] = marshal(result, interface_spec)
return res
else:
res['apiVersion'] = '1.0'
res['type'] = 'module'
res['data'] = marshal(result, module_spec)
return res
except:
abort(400, message = message)
def post(self, query = ""):
from nipyper.workflows.tasks import parse
args = interfaceParser.parse_args()
query = query.replace("/", ".")
message = ""
if query not in registry.interfaces:
abort(404, message = "There is no interface named " + query)
normalized = {
'type': 'Interface',
'interface': query
}
if 'inputs' in parser:
normalized['inputs'] = parser['inputs']
result = parse.delay(normalized)
return result.id
from nipyper.util import memoize
@memoize
def create_route():
api.add_resource(Interface, '/interfaces/', endpoint = 'module')
api.add_resource(Interface, '/interfaces/<string:query>/', endpoint = 'interface')
api.add_resource(Interface, '/interfaces/<path:query>', endpoint = 'path')
create_route() | en | 0.928934 | # decorators = [auth.login_required] # faster to resolve synchronously rather than go through Celery | 2.010434 | 2 |
models/database.py | Mmx233/blivechat | 1 | 6623123 | # -*- coding: utf-8 -*-
from typing import *
import sqlalchemy.ext.declarative
import sqlalchemy.orm
import config
OrmBase = sqlalchemy.ext.declarative.declarative_base()
_engine = None
_DbSession: Optional[Type[sqlalchemy.orm.Session]] = None
def init(_debug):
cfg = config.get_config()
global _engine, _DbSession
# engine = sqlalchemy.create_engine(cfg.database_url, echo=debug)
_engine = sqlalchemy.create_engine(cfg.database_url)
_DbSession = sqlalchemy.orm.sessionmaker(bind=_engine)
OrmBase.metadata.create_all(_engine)
def get_session():
return _DbSession()
| # -*- coding: utf-8 -*-
from typing import *
import sqlalchemy.ext.declarative
import sqlalchemy.orm
import config
OrmBase = sqlalchemy.ext.declarative.declarative_base()
_engine = None
_DbSession: Optional[Type[sqlalchemy.orm.Session]] = None
def init(_debug):
cfg = config.get_config()
global _engine, _DbSession
# engine = sqlalchemy.create_engine(cfg.database_url, echo=debug)
_engine = sqlalchemy.create_engine(cfg.database_url)
_DbSession = sqlalchemy.orm.sessionmaker(bind=_engine)
OrmBase.metadata.create_all(_engine)
def get_session():
return _DbSession()
| en | 0.300423 | # -*- coding: utf-8 -*- # engine = sqlalchemy.create_engine(cfg.database_url, echo=debug) | 2.460249 | 2 |
databind.json/src/databind/json/modules/collection.py | NiklasRosenstein/databind | 2 | 6623124 |
import typing as t
from databind.core import Context, Direction, Converter, CollectionType
class CollectionConverter(Converter):
def __init__(self, json_type: t.Type[t.Collection] = list) -> None:
self.json_type = json_type
def convert(self, ctx: Context) -> t.Any:
assert isinstance(ctx.type, CollectionType)
if ctx.direction == Direction.serialize:
if not isinstance(ctx.value, ctx.type.python_type):
raise ctx.type_error(expected=ctx.type.python_type)
python_type = self.json_type
elif ctx.direction == Direction.deserialize:
if not isinstance(ctx.value, t.Collection) or isinstance(ctx.value, (str, bytes, bytearray, memoryview)):
raise ctx.type_error(expected=t.Collection)
python_type = ctx.type.python_type
else:
assert False, ctx.direction
return python_type( # type: ignore
ctx.push(ctx.type.item_type, val, idx, ctx.field).convert()
for idx, val in enumerate(ctx.value))
|
import typing as t
from databind.core import Context, Direction, Converter, CollectionType
class CollectionConverter(Converter):
def __init__(self, json_type: t.Type[t.Collection] = list) -> None:
self.json_type = json_type
def convert(self, ctx: Context) -> t.Any:
assert isinstance(ctx.type, CollectionType)
if ctx.direction == Direction.serialize:
if not isinstance(ctx.value, ctx.type.python_type):
raise ctx.type_error(expected=ctx.type.python_type)
python_type = self.json_type
elif ctx.direction == Direction.deserialize:
if not isinstance(ctx.value, t.Collection) or isinstance(ctx.value, (str, bytes, bytearray, memoryview)):
raise ctx.type_error(expected=t.Collection)
python_type = ctx.type.python_type
else:
assert False, ctx.direction
return python_type( # type: ignore
ctx.push(ctx.type.item_type, val, idx, ctx.field).convert()
for idx, val in enumerate(ctx.value))
| it | 0.190853 | # type: ignore | 2.458035 | 2 |
test_app/tests/conftest.py | pehala/cached-markdown-field | 0 | 6623125 | <filename>test_app/tests/conftest.py<gh_stars>0
import pytest
@pytest.fixture(scope="function")
def use_runtime_cache(settings):
settings.MARKDOWN_CACHE_RUNTIME = True
@pytest.fixture(scope="function")
def no_cache(settings):
settings.MARKDOWN_CACHE = False
| <filename>test_app/tests/conftest.py<gh_stars>0
import pytest
@pytest.fixture(scope="function")
def use_runtime_cache(settings):
settings.MARKDOWN_CACHE_RUNTIME = True
@pytest.fixture(scope="function")
def no_cache(settings):
settings.MARKDOWN_CACHE = False
| none | 1 | 1.459633 | 1 | |
lib/model/ops/pcl_losses/pcl_losses.py | StillWaterRUN/D-MIL.pytorch | 10 | 6623126 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Sep 21 19:48:44 2019
@author: vasgaoweithu
"""
import torch
import torch.nn as nn
from torch.autograd import Function
from torch.autograd.function import once_differentiable
from torch.nn.modules.utils import _pair
from torch.nn.modules.module import Module
from . import pcl_losses_cpu
from . import pcl_losses_cuda
class PCLLosses(Function):
@staticmethod
def forward(ctx, pcl_probs, labels, cls_loss_weights, gt_assignment,
pc_labels, pc_probs, pc_count, img_cls_loss_weights,
im_labels):
device_id = pcl_probs.get_device()
output = pcl_probs.new(1, pcl_probs.shape[1]).zero_()
if not pcl_probs.is_cuda:
ctx.save_for_backward(pcl_probs, labels, cls_loss_weights,
gt_assignment, pc_labels, pc_probs,
pc_count, img_cls_loss_weights, im_labels,
torch.tensor(device_id))
pcl_losses_cpu.forward(pcl_probs, labels, cls_loss_weights,
pc_labels, pc_probs, img_cls_loss_weights,
im_labels, output)
else:
ctx.save_for_backward(pcl_probs, labels, cls_loss_weights,
gt_assignment, pc_labels, pc_probs,
pc_count, img_cls_loss_weights, im_labels,
torch.tensor(device_id))
pcl_losses_cuda.forward(pcl_probs, labels, cls_loss_weights,
pc_labels, pc_probs, img_cls_loss_weights,
im_labels, output)
return output.sum() / pcl_probs.size(0)
@staticmethod
def backward(ctx, grad_output):
pcl_probs, labels, cls_loss_weights, gt_assignment, pc_labels, pc_probs, \
pc_count, img_cls_loss_weights, im_labels, device_id = ctx.saved_tensors
grad_input = grad_output.new(pcl_probs.size()).zero_()
if not grad_output.is_cuda:
pcl_losses_cpu.backward(pcl_probs, labels, cls_loss_weights,
gt_assignment, pc_labels, pc_probs,
pc_count, img_cls_loss_weights, im_labels,
grad_output, grad_input)
else:
pcl_losses_cuda.backward(pcl_probs, labels, cls_loss_weights,
gt_assignment, pc_labels, pc_probs,
pc_count, img_cls_loss_weights, im_labels,
grad_output, grad_input)
grad_input /= pcl_probs.size(0)
return grad_input, None, None, None, None, None, None, None, None
pcl_losses = PCLLosses.apply
class _PCL_Losses(Module):
def forward(self, pcl_prob, labels, cls_loss_weights, gt_assignment,
pc_labels, pc_probs, pc_count, img_cls_loss_weights,
im_labels_real):
return pcl_losses(pcl_prob, labels, cls_loss_weights, gt_assignment,
pc_labels, pc_probs, pc_count, img_cls_loss_weights, im_labels_real) | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Sep 21 19:48:44 2019
@author: vasgaoweithu
"""
import torch
import torch.nn as nn
from torch.autograd import Function
from torch.autograd.function import once_differentiable
from torch.nn.modules.utils import _pair
from torch.nn.modules.module import Module
from . import pcl_losses_cpu
from . import pcl_losses_cuda
class PCLLosses(Function):
@staticmethod
def forward(ctx, pcl_probs, labels, cls_loss_weights, gt_assignment,
pc_labels, pc_probs, pc_count, img_cls_loss_weights,
im_labels):
device_id = pcl_probs.get_device()
output = pcl_probs.new(1, pcl_probs.shape[1]).zero_()
if not pcl_probs.is_cuda:
ctx.save_for_backward(pcl_probs, labels, cls_loss_weights,
gt_assignment, pc_labels, pc_probs,
pc_count, img_cls_loss_weights, im_labels,
torch.tensor(device_id))
pcl_losses_cpu.forward(pcl_probs, labels, cls_loss_weights,
pc_labels, pc_probs, img_cls_loss_weights,
im_labels, output)
else:
ctx.save_for_backward(pcl_probs, labels, cls_loss_weights,
gt_assignment, pc_labels, pc_probs,
pc_count, img_cls_loss_weights, im_labels,
torch.tensor(device_id))
pcl_losses_cuda.forward(pcl_probs, labels, cls_loss_weights,
pc_labels, pc_probs, img_cls_loss_weights,
im_labels, output)
return output.sum() / pcl_probs.size(0)
@staticmethod
def backward(ctx, grad_output):
pcl_probs, labels, cls_loss_weights, gt_assignment, pc_labels, pc_probs, \
pc_count, img_cls_loss_weights, im_labels, device_id = ctx.saved_tensors
grad_input = grad_output.new(pcl_probs.size()).zero_()
if not grad_output.is_cuda:
pcl_losses_cpu.backward(pcl_probs, labels, cls_loss_weights,
gt_assignment, pc_labels, pc_probs,
pc_count, img_cls_loss_weights, im_labels,
grad_output, grad_input)
else:
pcl_losses_cuda.backward(pcl_probs, labels, cls_loss_weights,
gt_assignment, pc_labels, pc_probs,
pc_count, img_cls_loss_weights, im_labels,
grad_output, grad_input)
grad_input /= pcl_probs.size(0)
return grad_input, None, None, None, None, None, None, None, None
pcl_losses = PCLLosses.apply
class _PCL_Losses(Module):
def forward(self, pcl_prob, labels, cls_loss_weights, gt_assignment,
pc_labels, pc_probs, pc_count, img_cls_loss_weights,
im_labels_real):
return pcl_losses(pcl_prob, labels, cls_loss_weights, gt_assignment,
pc_labels, pc_probs, pc_count, img_cls_loss_weights, im_labels_real) | en | 0.425406 | #!/usr/bin/env python3 # -*- coding: utf-8 -*- Created on Sat Sep 21 19:48:44 2019 @author: vasgaoweithu | 2.164633 | 2 |
utils/augmentation/smpl_augmentation.py | yuepengzhan/HierarchicalProbabilistic3DHuman | 1 | 6623127 | <gh_stars>1-10
import torch
from smplx.lbs import batch_rodrigues
def uniform_sample_shape(batch_size, mean_shape, delta_betas_range):
"""
Uniform sampling of shape parameter deviations from the mean.
"""
l, h = delta_betas_range
delta_betas = (h-l)*torch.rand(batch_size, mean_shape.shape[0], device= mean_shape.device) + l
shape = delta_betas + mean_shape
return shape # (bs, num_smpl_betas)
def normal_sample_shape(batch_size, mean_shape, std_vector):
"""
Gaussian sampling of shape parameter deviations from the mean.
"""
shape = mean_shape + torch.randn(batch_size, mean_shape.shape[0], device=mean_shape.device)*std_vector
return shape # (bs, num_smpl_betas)
def uniform_random_rot_matrix(num_matrices, std=0.01):
"""
Uniform sampling of random 3D rotation matrices using QR decomposition.
Source: https://arxiv.org/pdf/math-ph/0609050.pdf
"""
Z = torch.randn(num_matrices, 3, 3) * std
Q, R = torch.qr(Z)
d = torch.diagonal(R)
ph = d/torch.abs(d)
# matmul with diagonal matrix L equivalent to element-wise mul with broad-casted vector l
Q = torch.mul(Q, ph)
return Q # (num_matrices, 3, 3)
def uniform_random_unit_vector(num_vectors):
"""
Uniform sampling random 3D unit-vectors, i.e. points on surface of unit sphere.
"""
e = torch.randn(num_vectors, 3)
e = torch.div(e, torch.norm(e, dim=-1, keepdim=True))
return e # (num_vectors, 3)
| import torch
from smplx.lbs import batch_rodrigues
def uniform_sample_shape(batch_size, mean_shape, delta_betas_range):
"""
Uniform sampling of shape parameter deviations from the mean.
"""
l, h = delta_betas_range
delta_betas = (h-l)*torch.rand(batch_size, mean_shape.shape[0], device= mean_shape.device) + l
shape = delta_betas + mean_shape
return shape # (bs, num_smpl_betas)
def normal_sample_shape(batch_size, mean_shape, std_vector):
"""
Gaussian sampling of shape parameter deviations from the mean.
"""
shape = mean_shape + torch.randn(batch_size, mean_shape.shape[0], device=mean_shape.device)*std_vector
return shape # (bs, num_smpl_betas)
def uniform_random_rot_matrix(num_matrices, std=0.01):
"""
Uniform sampling of random 3D rotation matrices using QR decomposition.
Source: https://arxiv.org/pdf/math-ph/0609050.pdf
"""
Z = torch.randn(num_matrices, 3, 3) * std
Q, R = torch.qr(Z)
d = torch.diagonal(R)
ph = d/torch.abs(d)
# matmul with diagonal matrix L equivalent to element-wise mul with broad-casted vector l
Q = torch.mul(Q, ph)
return Q # (num_matrices, 3, 3)
def uniform_random_unit_vector(num_vectors):
"""
Uniform sampling random 3D unit-vectors, i.e. points on surface of unit sphere.
"""
e = torch.randn(num_vectors, 3)
e = torch.div(e, torch.norm(e, dim=-1, keepdim=True))
return e # (num_vectors, 3) | en | 0.658951 | Uniform sampling of shape parameter deviations from the mean. # (bs, num_smpl_betas) Gaussian sampling of shape parameter deviations from the mean. # (bs, num_smpl_betas) Uniform sampling of random 3D rotation matrices using QR decomposition. Source: https://arxiv.org/pdf/math-ph/0609050.pdf # matmul with diagonal matrix L equivalent to element-wise mul with broad-casted vector l # (num_matrices, 3, 3) Uniform sampling random 3D unit-vectors, i.e. points on surface of unit sphere. # (num_vectors, 3) | 2.846479 | 3 |
install/core/python/tank/folder/folder_types/__init__.py | JoanAzpeitia/lp_sg | 0 | 6623128 | # Copyright (c) 2013 Shotgun Software Inc.
#
# CONFIDENTIAL AND PROPRIETARY
#
# This work is provided "AS IS" and subject to the Shotgun Pipeline Toolkit
# Source Code License included in this distribution package. See LICENSE.
# By accessing, using, copying or modifying this work you indicate your
# agreement to the Shotgun Pipeline Toolkit Source Code License. All rights
# not expressly granted therein are reserved by Shotgun Software Inc.
"""
This module contains all the implementations for the different
folder types that can be created.
"""
from .errors import EntityLinkTypeMismatch
from .static import Static
from .listfield import ListField
from .entity import Entity
from .project import Project
from .user import UserWorkspace
from .step import ShotgunStep
from .task import ShotgunTask
| # Copyright (c) 2013 Shotgun Software Inc.
#
# CONFIDENTIAL AND PROPRIETARY
#
# This work is provided "AS IS" and subject to the Shotgun Pipeline Toolkit
# Source Code License included in this distribution package. See LICENSE.
# By accessing, using, copying or modifying this work you indicate your
# agreement to the Shotgun Pipeline Toolkit Source Code License. All rights
# not expressly granted therein are reserved by Shotgun Software Inc.
"""
This module contains all the implementations for the different
folder types that can be created.
"""
from .errors import EntityLinkTypeMismatch
from .static import Static
from .listfield import ListField
from .entity import Entity
from .project import Project
from .user import UserWorkspace
from .step import ShotgunStep
from .task import ShotgunTask
| en | 0.848096 | # Copyright (c) 2013 Shotgun Software Inc. # # CONFIDENTIAL AND PROPRIETARY # # This work is provided "AS IS" and subject to the Shotgun Pipeline Toolkit # Source Code License included in this distribution package. See LICENSE. # By accessing, using, copying or modifying this work you indicate your # agreement to the Shotgun Pipeline Toolkit Source Code License. All rights # not expressly granted therein are reserved by Shotgun Software Inc. This module contains all the implementations for the different folder types that can be created. | 1.169287 | 1 |
projects/models.py | tungr/Django-Site | 0 | 6623129 | from django.db import models
from django.core.files.storage import FileSystemStorage
# Create your models here.
# Uses an Object-Relational Mapper (ORM). Similar to a SQL database, but without having to learn another language
# Creates database in SQLite format by default (Can use others as well)
fs = FileSystemStorage(location='projects/static')
class Project(models.Model):
title = models.CharField(max_length=100)
description = models.TextField()
technology = models.CharField(max_length=20)
image = models.FileField(storage=fs)
def __str__(self):
return 'Project: {}'.format(self.title) | from django.db import models
from django.core.files.storage import FileSystemStorage
# Create your models here.
# Uses an Object-Relational Mapper (ORM). Similar to a SQL database, but without having to learn another language
# Creates database in SQLite format by default (Can use others as well)
fs = FileSystemStorage(location='projects/static')
class Project(models.Model):
title = models.CharField(max_length=100)
description = models.TextField()
technology = models.CharField(max_length=20)
image = models.FileField(storage=fs)
def __str__(self):
return 'Project: {}'.format(self.title) | en | 0.884765 | # Create your models here. # Uses an Object-Relational Mapper (ORM). Similar to a SQL database, but without having to learn another language # Creates database in SQLite format by default (Can use others as well) | 2.755938 | 3 |
backend/apps/listings/migrations/0011_auto_20210902_1847.py | hovedstyret/indok-web | 3 | 6623130 | <reponame>hovedstyret/indok-web<filename>backend/apps/listings/migrations/0011_auto_20210902_1847.py<gh_stars>1-10
# Generated by Django 3.1.8 on 2021-09-02 16:47
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
("listings", "0010_listing_view_count"),
]
operations = [
migrations.RenameField(
model_name="listing",
old_name="url",
new_name="application_url",
),
migrations.RenameField(
model_name="listing",
old_name="read_more",
new_name="read_more_url",
),
]
| # Generated by Django 3.1.8 on 2021-09-02 16:47
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
("listings", "0010_listing_view_count"),
]
operations = [
migrations.RenameField(
model_name="listing",
old_name="url",
new_name="application_url",
),
migrations.RenameField(
model_name="listing",
old_name="read_more",
new_name="read_more_url",
),
] | en | 0.78876 | # Generated by Django 3.1.8 on 2021-09-02 16:47 | 1.691612 | 2 |
train.py | tipt0p/periodic_behavior_bn_wd | 1 | 6623131 | import math
import torch
import torch.nn.functional as F
import numpy as np
import os, sys
import time
import tabulate
import data
import training_utils
import nets as models
from parser_train import parser
columns = ["ep", "lr", "tr_loss", "tr_acc", "te_loss", "te_acc", "time"]
def cross_entropy(model, input, target, reduction="mean"):
"standard cross-entropy loss function"
output = model(input)
loss = F.cross_entropy(output, target, reduction=reduction)
return loss, output
def check_si_name(n, model_name='ResNet18'):
if model_name == 'ResNet18':
return "conv1" in n or "1.bn1" in n or "1.0.bn1" in n or (("conv2" in n or "short" in n) and "4" not in n)
elif model_name == 'ResNet18SI':
return 'linear' not in n
elif model_name == 'ResNet18SIAf':
return ('linear' not in n and 'bn' not in n and 'shortcut.0' not in n)
elif 'ConvNet' in model_name:
return 'conv_layers.0.' in n or 'conv_layers.3.' in n or 'conv_layers.7.' in n or 'conv_layers.11.' in n
return False
def main():
args = parser()
args.device = None
os.environ['CUDA_DEVICE_ORDER']='PCI_BUS_ID'
os.environ['CUDA_VISIBLE_DEVICES']=args.gpu
if torch.cuda.is_available():
args.device = torch.device("cuda")
args.cuda = True
else:
args.device = torch.device("cpu")
args.cuda = False
torch.backends.cudnn.benchmark = True
torch.manual_seed(args.seed)
torch.cuda.manual_seed(args.seed)
# n_trials = 1
print("Preparing base directory %s" % args.dir)
os.makedirs(args.dir, exist_ok=True)
# for trial in range(n_trials):
trial = args.trial
output_dir = args.dir + f"/trial_{trial}"
### resuming is modified!!!
if args.resume_epoch > -1:
resume_dir = output_dir
output_dir = output_dir + f"/from_{args.resume_epoch}_for_{args.epochs}"
if args.save_freq_int > 0:
output_dir = output_dir + f"_save_int_{args.save_freq_int}"
if args.noninvlr >= 0:
output_dir = output_dir + f"_noninvlr_{args.noninvlr}"
### resuming is modified!!!
print("Preparing directory %s" % output_dir)
os.makedirs(output_dir, exist_ok=True)
with open(os.path.join(output_dir, "command.sh"), "w") as f:
f.write(" ".join(sys.argv))
f.write("\n")
print("Using model %s" % args.model)
model_cfg = getattr(models, args.model)
print("Loading dataset %s from %s" % (args.dataset, args.data_path))
transform_train = model_cfg.transform_test if args.no_aug else model_cfg.transform_train
loaders, num_classes = data.loaders(
args.dataset,
args.data_path,
args.batch_size,
args.num_workers,
transform_train,
model_cfg.transform_test,
use_validation=not args.use_test,
use_data_size = args.use_data_size,
split_classes=args.split_classes,
corrupt_train=args.corrupt_train
)
print("Preparing model")
print(*model_cfg.args)
# add extra args for varying names
if 'ResNet18' in args.model:
extra_args = {'init_channels':args.num_channels}
if "SI" in args.model:
extra_args.update({'linear_norm':args.init_scale})
elif 'ConvNet' in args.model:
extra_args = {'init_channels':args.num_channels, 'max_depth':args.depth,'init_scale':args.init_scale}
elif args.model == 'LeNet':
extra_args = {'scale':args.scale}
else:
extra_args = {}
model = model_cfg.base(*model_cfg.args, num_classes=num_classes, **model_cfg.kwargs,
**extra_args)
model.to(args.device)
param_groups = model.parameters()
if args.noninvlr >= 0:
param_groups = [
{'params': [p for n, p in model.named_parameters() if check_si_name(n, args.model)]}, # SI params are convolutions
{'params': [p for n, p in model.named_parameters() if not check_si_name(n, args.model)],'lr':args.noninvlr}, # other params
]
optimizer = torch.optim.SGD(param_groups,
lr=args.lr_init,
momentum=args.momentum,
weight_decay=args.wd)
if args.cosan_schedule:
scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=args.epochs)
epoch_from = args.resume_epoch + 1
epoch_to = epoch_from + args.epochs
print(f"Training from {epoch_from} to {epoch_to - 1} epochs")
if epoch_from > 0:
# Warning: due to specific lr schedule, resuming is generally not recommended!
print(f"Loading checkpoint from the {args.resume_epoch} epoch")
state = training_utils.load_checkpoint(resume_dir, args.resume_epoch)
model.load_state_dict(state['state_dict'])
optimizer.load_state_dict(state['optimizer'])
if args.noninvlr >= 0:
optimizer.param_groups[1]["lr"] = args.noninvlr
si_pnorm_0 = None
if args.fix_si_pnorm:
if args.fix_si_pnorm_value > 0:
# No lr schedule, plz...
si_pnorm_0 = args.fix_si_pnorm_value
else:
si_pnorm_0 = np.sqrt(sum((p ** 2).sum().item() for n, p in model.named_parameters() if check_si_name(n, args.model)))
print(f"Fixing SI-pnorm to value {si_pnorm_0:.4f}")
for epoch in range(epoch_from, epoch_to):
train_epoch(model, loaders, cross_entropy, optimizer,
epoch=epoch,
end_epoch=epoch_to,
eval_freq=args.eval_freq,
save_freq=args.save_freq,
save_freq_int=args.save_freq_int,
output_dir=output_dir,
lr_init=args.lr_init,
lr_schedule=not args.no_schedule,
noninvlr=args.noninvlr,
c_schedule=args.c_schedule,
d_schedule=args.d_schedule,
si_pnorm_0=si_pnorm_0,
fbgd=args.fbgd,
cosan_schedule = args.cosan_schedule)
if args.cosan_schedule:
scheduler.step()
print("model ", trial, " done")
def train_epoch(model, loaders, criterion, optimizer, epoch, end_epoch,
eval_freq=1, save_freq=10, save_freq_int=0, output_dir='./', lr_init=0.01,
lr_schedule=True, noninvlr = -1, c_schedule=None, d_schedule=None, si_pnorm_0=None,fbgd=False,
cosan_schedule = False):
time_ep = time.time()
if not cosan_schedule:
if not lr_schedule:
lr = lr_init
elif c_schedule > 0:
lr = training_utils.c_schedule(epoch, lr_init, end_epoch, c_schedule)
elif d_schedule > 0:
lr = training_utils.d_schedule(epoch, lr_init, end_epoch, d_schedule)
else:
lr = training_utils.schedule(epoch, lr_init, end_epoch, swa=False)
if noninvlr >= 0:
training_utils.adjust_learning_rate_only_conv(optimizer, lr)
else:
training_utils.adjust_learning_rate(optimizer, lr)
else:
for param_group in optimizer.param_groups:
lr = param_group["lr"]
break
train_res = training_utils.train_epoch(loaders["train"], model, criterion, optimizer, fbgd=fbgd,si_pnorm_0=si_pnorm_0,
save_freq_int=save_freq_int,epoch = epoch,output_dir = output_dir)
if (
epoch == 0
or epoch % eval_freq == eval_freq - 1
or epoch == end_epoch - 1
):
test_res = training_utils.eval(loaders["test"], model, criterion)
else:
test_res = {"loss": None, "accuracy": None}
def save_epoch(epoch):
training_utils.save_checkpoint(
output_dir,
epoch,
state_dict=model.state_dict(),
optimizer=optimizer.state_dict(),
train_res=train_res,
test_res=test_res
)
if save_freq is None:
if training_utils.do_report(epoch):
save_epoch(epoch)
elif epoch % save_freq == 0:
save_epoch(epoch)
time_ep = time.time() - time_ep
values = [
epoch,
lr,
train_res["loss"],
train_res["accuracy"],
test_res["loss"],
test_res["accuracy"],
time_ep,
]
table = tabulate.tabulate([values], columns, tablefmt="simple", floatfmt="8.4f")
if epoch % 40 == 0:
table = table.split("\n")
table = "\n".join([table[1]] + table)
else:
table = table.split("\n")[2]
print(table)
if __name__ == '__main__':
main()
| import math
import torch
import torch.nn.functional as F
import numpy as np
import os, sys
import time
import tabulate
import data
import training_utils
import nets as models
from parser_train import parser
columns = ["ep", "lr", "tr_loss", "tr_acc", "te_loss", "te_acc", "time"]
def cross_entropy(model, input, target, reduction="mean"):
"standard cross-entropy loss function"
output = model(input)
loss = F.cross_entropy(output, target, reduction=reduction)
return loss, output
def check_si_name(n, model_name='ResNet18'):
if model_name == 'ResNet18':
return "conv1" in n or "1.bn1" in n or "1.0.bn1" in n or (("conv2" in n or "short" in n) and "4" not in n)
elif model_name == 'ResNet18SI':
return 'linear' not in n
elif model_name == 'ResNet18SIAf':
return ('linear' not in n and 'bn' not in n and 'shortcut.0' not in n)
elif 'ConvNet' in model_name:
return 'conv_layers.0.' in n or 'conv_layers.3.' in n or 'conv_layers.7.' in n or 'conv_layers.11.' in n
return False
def main():
args = parser()
args.device = None
os.environ['CUDA_DEVICE_ORDER']='PCI_BUS_ID'
os.environ['CUDA_VISIBLE_DEVICES']=args.gpu
if torch.cuda.is_available():
args.device = torch.device("cuda")
args.cuda = True
else:
args.device = torch.device("cpu")
args.cuda = False
torch.backends.cudnn.benchmark = True
torch.manual_seed(args.seed)
torch.cuda.manual_seed(args.seed)
# n_trials = 1
print("Preparing base directory %s" % args.dir)
os.makedirs(args.dir, exist_ok=True)
# for trial in range(n_trials):
trial = args.trial
output_dir = args.dir + f"/trial_{trial}"
### resuming is modified!!!
if args.resume_epoch > -1:
resume_dir = output_dir
output_dir = output_dir + f"/from_{args.resume_epoch}_for_{args.epochs}"
if args.save_freq_int > 0:
output_dir = output_dir + f"_save_int_{args.save_freq_int}"
if args.noninvlr >= 0:
output_dir = output_dir + f"_noninvlr_{args.noninvlr}"
### resuming is modified!!!
print("Preparing directory %s" % output_dir)
os.makedirs(output_dir, exist_ok=True)
with open(os.path.join(output_dir, "command.sh"), "w") as f:
f.write(" ".join(sys.argv))
f.write("\n")
print("Using model %s" % args.model)
model_cfg = getattr(models, args.model)
print("Loading dataset %s from %s" % (args.dataset, args.data_path))
transform_train = model_cfg.transform_test if args.no_aug else model_cfg.transform_train
loaders, num_classes = data.loaders(
args.dataset,
args.data_path,
args.batch_size,
args.num_workers,
transform_train,
model_cfg.transform_test,
use_validation=not args.use_test,
use_data_size = args.use_data_size,
split_classes=args.split_classes,
corrupt_train=args.corrupt_train
)
print("Preparing model")
print(*model_cfg.args)
# add extra args for varying names
if 'ResNet18' in args.model:
extra_args = {'init_channels':args.num_channels}
if "SI" in args.model:
extra_args.update({'linear_norm':args.init_scale})
elif 'ConvNet' in args.model:
extra_args = {'init_channels':args.num_channels, 'max_depth':args.depth,'init_scale':args.init_scale}
elif args.model == 'LeNet':
extra_args = {'scale':args.scale}
else:
extra_args = {}
model = model_cfg.base(*model_cfg.args, num_classes=num_classes, **model_cfg.kwargs,
**extra_args)
model.to(args.device)
param_groups = model.parameters()
if args.noninvlr >= 0:
param_groups = [
{'params': [p for n, p in model.named_parameters() if check_si_name(n, args.model)]}, # SI params are convolutions
{'params': [p for n, p in model.named_parameters() if not check_si_name(n, args.model)],'lr':args.noninvlr}, # other params
]
optimizer = torch.optim.SGD(param_groups,
lr=args.lr_init,
momentum=args.momentum,
weight_decay=args.wd)
if args.cosan_schedule:
scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=args.epochs)
epoch_from = args.resume_epoch + 1
epoch_to = epoch_from + args.epochs
print(f"Training from {epoch_from} to {epoch_to - 1} epochs")
if epoch_from > 0:
# Warning: due to specific lr schedule, resuming is generally not recommended!
print(f"Loading checkpoint from the {args.resume_epoch} epoch")
state = training_utils.load_checkpoint(resume_dir, args.resume_epoch)
model.load_state_dict(state['state_dict'])
optimizer.load_state_dict(state['optimizer'])
if args.noninvlr >= 0:
optimizer.param_groups[1]["lr"] = args.noninvlr
si_pnorm_0 = None
if args.fix_si_pnorm:
if args.fix_si_pnorm_value > 0:
# No lr schedule, plz...
si_pnorm_0 = args.fix_si_pnorm_value
else:
si_pnorm_0 = np.sqrt(sum((p ** 2).sum().item() for n, p in model.named_parameters() if check_si_name(n, args.model)))
print(f"Fixing SI-pnorm to value {si_pnorm_0:.4f}")
for epoch in range(epoch_from, epoch_to):
train_epoch(model, loaders, cross_entropy, optimizer,
epoch=epoch,
end_epoch=epoch_to,
eval_freq=args.eval_freq,
save_freq=args.save_freq,
save_freq_int=args.save_freq_int,
output_dir=output_dir,
lr_init=args.lr_init,
lr_schedule=not args.no_schedule,
noninvlr=args.noninvlr,
c_schedule=args.c_schedule,
d_schedule=args.d_schedule,
si_pnorm_0=si_pnorm_0,
fbgd=args.fbgd,
cosan_schedule = args.cosan_schedule)
if args.cosan_schedule:
scheduler.step()
print("model ", trial, " done")
def train_epoch(model, loaders, criterion, optimizer, epoch, end_epoch,
eval_freq=1, save_freq=10, save_freq_int=0, output_dir='./', lr_init=0.01,
lr_schedule=True, noninvlr = -1, c_schedule=None, d_schedule=None, si_pnorm_0=None,fbgd=False,
cosan_schedule = False):
time_ep = time.time()
if not cosan_schedule:
if not lr_schedule:
lr = lr_init
elif c_schedule > 0:
lr = training_utils.c_schedule(epoch, lr_init, end_epoch, c_schedule)
elif d_schedule > 0:
lr = training_utils.d_schedule(epoch, lr_init, end_epoch, d_schedule)
else:
lr = training_utils.schedule(epoch, lr_init, end_epoch, swa=False)
if noninvlr >= 0:
training_utils.adjust_learning_rate_only_conv(optimizer, lr)
else:
training_utils.adjust_learning_rate(optimizer, lr)
else:
for param_group in optimizer.param_groups:
lr = param_group["lr"]
break
train_res = training_utils.train_epoch(loaders["train"], model, criterion, optimizer, fbgd=fbgd,si_pnorm_0=si_pnorm_0,
save_freq_int=save_freq_int,epoch = epoch,output_dir = output_dir)
if (
epoch == 0
or epoch % eval_freq == eval_freq - 1
or epoch == end_epoch - 1
):
test_res = training_utils.eval(loaders["test"], model, criterion)
else:
test_res = {"loss": None, "accuracy": None}
def save_epoch(epoch):
training_utils.save_checkpoint(
output_dir,
epoch,
state_dict=model.state_dict(),
optimizer=optimizer.state_dict(),
train_res=train_res,
test_res=test_res
)
if save_freq is None:
if training_utils.do_report(epoch):
save_epoch(epoch)
elif epoch % save_freq == 0:
save_epoch(epoch)
time_ep = time.time() - time_ep
values = [
epoch,
lr,
train_res["loss"],
train_res["accuracy"],
test_res["loss"],
test_res["accuracy"],
time_ep,
]
table = tabulate.tabulate([values], columns, tablefmt="simple", floatfmt="8.4f")
if epoch % 40 == 0:
table = table.split("\n")
table = "\n".join([table[1]] + table)
else:
table = table.split("\n")[2]
print(table)
if __name__ == '__main__':
main()
| en | 0.799565 | # n_trials = 1 # for trial in range(n_trials): ### resuming is modified!!! ### resuming is modified!!! # add extra args for varying names # SI params are convolutions # other params # Warning: due to specific lr schedule, resuming is generally not recommended! # No lr schedule, plz... | 2.43262 | 2 |
simulation/utils_env.py | liaojh1998/cross-modal-concept2robot | 4 | 6623132 | import numpy as np
import pybullet as p
#import matplotlib.pyplot as plt
import os
import torch
import shutil
import torch.autograd as Variable
#import matplotlib as mpl
#from mpl_toolkits.mplot3d import Axes3D
def get_view(opt):
def getview (width=600, height=600, look=[-0.05, -0.3, 0.0], dist=0.25, direct=[0.0, 0.0, 0.0]):
cameraRandom = 0.0
pitch = direct[0] + cameraRandom * np.random.uniform (-3, 3)
yaw = direct[1] + cameraRandom * np.random.uniform (-3, 3)
roll = direct[2] + cameraRandom * np.random.uniform (-3, 3)
viewmatrix = p.computeViewMatrixFromYawPitchRoll (look, dist, yaw, pitch, roll, 2)
fov = 40. + cameraRandom * np.random.uniform (-2, 2)
aspect = float (width) / float (height)
near = 0.01
far = 10
projmatrix = p.computeProjectionMatrixFOV (fov, aspect, near, far)
return viewmatrix, projmatrix
width = 640
height = 480
# TODO: Use config
params_file = os.path.join("../configs/camera_parameters/params.npy")
params = np.load(params_file)
if opt.view_point == 'third':
dist = params[5] + 0.3
look = [params[3] - 0.4, -params[4], 0.0]
direct = [params[0] + 90, params[2] + 180, params[1]]
else:
dist = params[5]
look = [params[3], params[4], 0.0]
direct = [params[0]+90,params[2],params[1]]
view_matrix,proj_matrix = getview(width,height,look,dist,direct)
return view_matrix,proj_matrix
def get_view_sim():
def getview (width=600, height=600, look=[-0.05, -0.3, 0.0], dist=0.25, direct=[0.0, 0.0, 0.0]):
cameraRandom = 0.0
pitch = direct[0] + cameraRandom * np.random.uniform (-3, 3)
yaw = direct[1] + cameraRandom * np.random.uniform (-3, 3)
roll = direct[2] + cameraRandom * np.random.uniform (-3, 3)
viewmatrix = p.computeViewMatrixFromYawPitchRoll (look, dist, yaw, pitch, roll, 2)
fov = 40. + cameraRandom * np.random.uniform (-2, 2)
aspect = float (width) / float (height)
near = 0.01
far = 10
projmatrix = p.computeProjectionMatrixFOV (fov, aspect, near, far)
return viewmatrix, projmatrix
width = 640
height = 480
params = np.load('../../configs/camera_parameters/params.npy')
# dist = params[5]
dist = params[5]+0.3
look = [params[3]-0.4, -params[4], 0.0]
direct = [params[0]+90,params[2]+180,params[1]]
view_matrix,proj_matrix = getview(width,height,look,dist,direct)
return view_matrix,proj_matrix
def safe_path(path):
if not os.path.exists(path):
os.mkdir(path)
return path
def point2traj(points=None,delta=0.01):
traj = []
last = points[0]
for i in range(len(points)-1):
now = points[i+1]
diff = [x-y for x,y in zip(now,last)]
dist = sum([x**2 for x in diff])**0.5
n = int(dist/delta)
for step in range(n):
x = last[0] + step*delta*diff[0]/dist
y = last[1] + step*delta*diff[1]/dist
z = last[2] + step*delta*diff[2]/dist
traj.append([x,y,z])
last = now
return traj
def get_gripper_pos(gripperOpen=1):
"""
:param gripperOpen: 1 represents open, 0 represents close
:return: the gripperPos
"""
gripperLowerLimitList = [0] * 6
gripperUpperLimitList = [0.81, -0.8, 0.81, -0.8, 0.8757, 0.8757]
gripperPos = np.array (gripperUpperLimitList) * (1 - gripperOpen) + np.array (gripperLowerLimitList) * gripperOpen
return gripperPos
def cut_frame(video_name,output_path):
if not os.path.exists(output_path):
os.mkdir(output_path)
cmd = 'ffmpeg -i {} -vf scale=640:480 '.format(video_name)+'{}/%06d.jpg'.format(output_path)
os.system(cmd)
return output_path
def soft_update(target, source, tau):
"""
Copies the parameters from source network (x) to target network (y) using the below update
y = TAU*x + (1 - TAU)*y
:param target: Target network (PyTorch)
:param source: Source network (PyTorch)
:return:
"""
for target_param, param in zip(target.parameters(), source.parameters()):
target_param.data.copy_(
target_param.data * (1.0 - tau) + param.data * tau
)
def hard_update(target, source):
"""
Copies the parameters from source network to target network
:param target: Target network (PyTorch)
:param source: Source network (PyTorch)
:return:
"""
for target_param, param in zip(target.parameters(), source.parameters()):
target_param.data.copy_(param.data)
def save_training_checkpoint(state, is_best, episode_count):
"""
Saves the models, with all training parameters intact
:param state:
:param is_best:
:param filename:
:return:
"""
filename = str(episode_count) + 'checkpoint.path.rar'
torch.save(state, filename)
if is_best:
shutil.copyfile(filename, 'model_best.pth.tar')
# Based on http://math.stackexchange.com/questions/1287634/implementing-ornstein-uhlenbeck-in-matlab
class OrnsteinUhlenbeckActionNoise:
def __init__(self, action_dim, mu = 0, theta = 0.15, sigma = 0.2):
self.action_dim = action_dim
self.mu = mu
self.theta = theta
self.sigma = sigma
self.X = np.ones(self.action_dim) * self.mu
def reset(self):
self.X = np.ones(self.action_dim) * self.mu
def sample(self):
dx = self.theta * (self.mu - self.X)
dx = dx + self.sigma * np.random.randn(len(self.X))
self.X = self.X + dx
return self.X
# use this to plot Ornstein Uhlenbeck random motion
def test_orn():
ou = OrnsteinUhlenbeckActionNoise(1)
states = []
for i in range(1000):
states.append(ou.sample())
import matplotlib.pyplot as plt
plt.plot(states)
plt.show()
class Visual:
def __init__(self,test_id=0,epoch_id=0):
self.test_id = test_id
self.epoch_id = epoch_id
self.log_file = '../../dataset/ddpg_log/test{}/epoch-{}.txt'\
.format(self.test_id,self.epoch_id)
self.traj_folder = safe_path('../../dataset/ddpg_log/test{}/traj/'.format(self.test_id))
def update(self,epoch_id):
self.epoch_id = epoch_id
self.log_file = '../../dataset/ddpg_log/test{}/epoch-{}.txt' \
.format (self.test_id, self.epoch_id)
def get_xyz(self):
self.points = []
with open(self.log_file,'r') as reader:
for line in reader.readlines():
line = line.strip().split(':')
if line[0]=='executed pos':
self.points.append(eval(line[1]))
self.points = np.array(self.points)
def show_xyz(self):
self.get_xyz ()
mpl.rcParams['legend.fontsize'] = 10
fig = plt.figure ()
ax = fig.gca (projection='3d')
x = self.points[:,0]
y = self.points[:,1]
z = self.points[:,2]
ax.plot (x, y, z, label='parametric curve')
ax.legend ()
plt.savefig(os.path.join(self.traj_folder,'trajectory-{}.jpg'.format(self.epoch_id)))
plt.cla()
def backup_code(script_path,log_path):
log_path = os.path.join(log_path,'script_backup')
if os.path.exists(log_path):
shutil.rmtree(log_path)
shutil.copytree(script_path,log_path)
def get_next_test_id():
num = 0
for file in os.listdir('../../dataset/ddpg_log/'):
if 'test' in file:
file = file.strip().replace('test','')
num = max(num,int(file))
return num+1
if __name__ == '__main__':
agent = Visual(test_id=3)
for epoch in range(300):
agent.update(epoch+1)
agent.show_xyz()
| import numpy as np
import pybullet as p
#import matplotlib.pyplot as plt
import os
import torch
import shutil
import torch.autograd as Variable
#import matplotlib as mpl
#from mpl_toolkits.mplot3d import Axes3D
def get_view(opt):
def getview (width=600, height=600, look=[-0.05, -0.3, 0.0], dist=0.25, direct=[0.0, 0.0, 0.0]):
cameraRandom = 0.0
pitch = direct[0] + cameraRandom * np.random.uniform (-3, 3)
yaw = direct[1] + cameraRandom * np.random.uniform (-3, 3)
roll = direct[2] + cameraRandom * np.random.uniform (-3, 3)
viewmatrix = p.computeViewMatrixFromYawPitchRoll (look, dist, yaw, pitch, roll, 2)
fov = 40. + cameraRandom * np.random.uniform (-2, 2)
aspect = float (width) / float (height)
near = 0.01
far = 10
projmatrix = p.computeProjectionMatrixFOV (fov, aspect, near, far)
return viewmatrix, projmatrix
width = 640
height = 480
# TODO: Use config
params_file = os.path.join("../configs/camera_parameters/params.npy")
params = np.load(params_file)
if opt.view_point == 'third':
dist = params[5] + 0.3
look = [params[3] - 0.4, -params[4], 0.0]
direct = [params[0] + 90, params[2] + 180, params[1]]
else:
dist = params[5]
look = [params[3], params[4], 0.0]
direct = [params[0]+90,params[2],params[1]]
view_matrix,proj_matrix = getview(width,height,look,dist,direct)
return view_matrix,proj_matrix
def get_view_sim():
def getview (width=600, height=600, look=[-0.05, -0.3, 0.0], dist=0.25, direct=[0.0, 0.0, 0.0]):
cameraRandom = 0.0
pitch = direct[0] + cameraRandom * np.random.uniform (-3, 3)
yaw = direct[1] + cameraRandom * np.random.uniform (-3, 3)
roll = direct[2] + cameraRandom * np.random.uniform (-3, 3)
viewmatrix = p.computeViewMatrixFromYawPitchRoll (look, dist, yaw, pitch, roll, 2)
fov = 40. + cameraRandom * np.random.uniform (-2, 2)
aspect = float (width) / float (height)
near = 0.01
far = 10
projmatrix = p.computeProjectionMatrixFOV (fov, aspect, near, far)
return viewmatrix, projmatrix
width = 640
height = 480
params = np.load('../../configs/camera_parameters/params.npy')
# dist = params[5]
dist = params[5]+0.3
look = [params[3]-0.4, -params[4], 0.0]
direct = [params[0]+90,params[2]+180,params[1]]
view_matrix,proj_matrix = getview(width,height,look,dist,direct)
return view_matrix,proj_matrix
def safe_path(path):
if not os.path.exists(path):
os.mkdir(path)
return path
def point2traj(points=None,delta=0.01):
traj = []
last = points[0]
for i in range(len(points)-1):
now = points[i+1]
diff = [x-y for x,y in zip(now,last)]
dist = sum([x**2 for x in diff])**0.5
n = int(dist/delta)
for step in range(n):
x = last[0] + step*delta*diff[0]/dist
y = last[1] + step*delta*diff[1]/dist
z = last[2] + step*delta*diff[2]/dist
traj.append([x,y,z])
last = now
return traj
def get_gripper_pos(gripperOpen=1):
"""
:param gripperOpen: 1 represents open, 0 represents close
:return: the gripperPos
"""
gripperLowerLimitList = [0] * 6
gripperUpperLimitList = [0.81, -0.8, 0.81, -0.8, 0.8757, 0.8757]
gripperPos = np.array (gripperUpperLimitList) * (1 - gripperOpen) + np.array (gripperLowerLimitList) * gripperOpen
return gripperPos
def cut_frame(video_name,output_path):
if not os.path.exists(output_path):
os.mkdir(output_path)
cmd = 'ffmpeg -i {} -vf scale=640:480 '.format(video_name)+'{}/%06d.jpg'.format(output_path)
os.system(cmd)
return output_path
def soft_update(target, source, tau):
"""
Copies the parameters from source network (x) to target network (y) using the below update
y = TAU*x + (1 - TAU)*y
:param target: Target network (PyTorch)
:param source: Source network (PyTorch)
:return:
"""
for target_param, param in zip(target.parameters(), source.parameters()):
target_param.data.copy_(
target_param.data * (1.0 - tau) + param.data * tau
)
def hard_update(target, source):
"""
Copies the parameters from source network to target network
:param target: Target network (PyTorch)
:param source: Source network (PyTorch)
:return:
"""
for target_param, param in zip(target.parameters(), source.parameters()):
target_param.data.copy_(param.data)
def save_training_checkpoint(state, is_best, episode_count):
"""
Saves the models, with all training parameters intact
:param state:
:param is_best:
:param filename:
:return:
"""
filename = str(episode_count) + 'checkpoint.path.rar'
torch.save(state, filename)
if is_best:
shutil.copyfile(filename, 'model_best.pth.tar')
# Based on http://math.stackexchange.com/questions/1287634/implementing-ornstein-uhlenbeck-in-matlab
class OrnsteinUhlenbeckActionNoise:
def __init__(self, action_dim, mu = 0, theta = 0.15, sigma = 0.2):
self.action_dim = action_dim
self.mu = mu
self.theta = theta
self.sigma = sigma
self.X = np.ones(self.action_dim) * self.mu
def reset(self):
self.X = np.ones(self.action_dim) * self.mu
def sample(self):
dx = self.theta * (self.mu - self.X)
dx = dx + self.sigma * np.random.randn(len(self.X))
self.X = self.X + dx
return self.X
# use this to plot Ornstein Uhlenbeck random motion
def test_orn():
ou = OrnsteinUhlenbeckActionNoise(1)
states = []
for i in range(1000):
states.append(ou.sample())
import matplotlib.pyplot as plt
plt.plot(states)
plt.show()
class Visual:
def __init__(self,test_id=0,epoch_id=0):
self.test_id = test_id
self.epoch_id = epoch_id
self.log_file = '../../dataset/ddpg_log/test{}/epoch-{}.txt'\
.format(self.test_id,self.epoch_id)
self.traj_folder = safe_path('../../dataset/ddpg_log/test{}/traj/'.format(self.test_id))
def update(self,epoch_id):
self.epoch_id = epoch_id
self.log_file = '../../dataset/ddpg_log/test{}/epoch-{}.txt' \
.format (self.test_id, self.epoch_id)
def get_xyz(self):
self.points = []
with open(self.log_file,'r') as reader:
for line in reader.readlines():
line = line.strip().split(':')
if line[0]=='executed pos':
self.points.append(eval(line[1]))
self.points = np.array(self.points)
def show_xyz(self):
self.get_xyz ()
mpl.rcParams['legend.fontsize'] = 10
fig = plt.figure ()
ax = fig.gca (projection='3d')
x = self.points[:,0]
y = self.points[:,1]
z = self.points[:,2]
ax.plot (x, y, z, label='parametric curve')
ax.legend ()
plt.savefig(os.path.join(self.traj_folder,'trajectory-{}.jpg'.format(self.epoch_id)))
plt.cla()
def backup_code(script_path,log_path):
log_path = os.path.join(log_path,'script_backup')
if os.path.exists(log_path):
shutil.rmtree(log_path)
shutil.copytree(script_path,log_path)
def get_next_test_id():
num = 0
for file in os.listdir('../../dataset/ddpg_log/'):
if 'test' in file:
file = file.strip().replace('test','')
num = max(num,int(file))
return num+1
if __name__ == '__main__':
agent = Visual(test_id=3)
for epoch in range(300):
agent.update(epoch+1)
agent.show_xyz()
| en | 0.556801 | #import matplotlib.pyplot as plt #import matplotlib as mpl #from mpl_toolkits.mplot3d import Axes3D # TODO: Use config # dist = params[5] :param gripperOpen: 1 represents open, 0 represents close :return: the gripperPos Copies the parameters from source network (x) to target network (y) using the below update y = TAU*x + (1 - TAU)*y :param target: Target network (PyTorch) :param source: Source network (PyTorch) :return: Copies the parameters from source network to target network :param target: Target network (PyTorch) :param source: Source network (PyTorch) :return: Saves the models, with all training parameters intact :param state: :param is_best: :param filename: :return: # Based on http://math.stackexchange.com/questions/1287634/implementing-ornstein-uhlenbeck-in-matlab # use this to plot Ornstein Uhlenbeck random motion | 2.19006 | 2 |
order/migrations/0002_auto_20210311_1913.py | Habeebhassan/zarawa_express | 0 | 6623133 | # Generated by Django 3.1.7 on 2021-03-11 19:13
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('order', '0001_initial'),
]
operations = [
migrations.RenameField(
model_name='order',
old_name='drop_add',
new_name='dropoff_address',
),
migrations.RenameField(
model_name='order',
old_name='pickup_add',
new_name='pickup_address',
),
migrations.RemoveField(
model_name='order',
name='email',
),
migrations.AddField(
model_name='order',
name='name',
field=models.CharField(blank=True, max_length=100),
),
migrations.AddField(
model_name='order',
name='phone_number',
field=models.CharField(blank=True, max_length=11),
),
migrations.AddField(
model_name='order',
name='submitted',
field=models.DateField(auto_now_add=True, default=django.utils.timezone.now),
preserve_default=False,
),
migrations.AlterField(
model_name='order',
name='pickup_name',
field=models.CharField(blank=True, max_length=100),
),
migrations.AlterField(
model_name='order',
name='recipient_name',
field=models.CharField(blank=True, max_length=100),
),
]
| # Generated by Django 3.1.7 on 2021-03-11 19:13
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('order', '0001_initial'),
]
operations = [
migrations.RenameField(
model_name='order',
old_name='drop_add',
new_name='dropoff_address',
),
migrations.RenameField(
model_name='order',
old_name='pickup_add',
new_name='pickup_address',
),
migrations.RemoveField(
model_name='order',
name='email',
),
migrations.AddField(
model_name='order',
name='name',
field=models.CharField(blank=True, max_length=100),
),
migrations.AddField(
model_name='order',
name='phone_number',
field=models.CharField(blank=True, max_length=11),
),
migrations.AddField(
model_name='order',
name='submitted',
field=models.DateField(auto_now_add=True, default=django.utils.timezone.now),
preserve_default=False,
),
migrations.AlterField(
model_name='order',
name='pickup_name',
field=models.CharField(blank=True, max_length=100),
),
migrations.AlterField(
model_name='order',
name='recipient_name',
field=models.CharField(blank=True, max_length=100),
),
]
| en | 0.761021 | # Generated by Django 3.1.7 on 2021-03-11 19:13 | 1.745815 | 2 |
scripts/test_api.py | sergeyt/pandora | 28 | 6623134 | <filename>scripts/test_api.py
#!/usr/bin/env python
import os
import api
# todo check bad auth cases as separate test cases
def crud(resource):
api.login("system", os.getenv("SYSTEM_PWD"))
data = {
'name': "bob",
'age': 39,
}
print('CREATE')
base = '/api/data/' + resource
resp = api.post(base, data)
id = resp['uid']
data = {
'name': "joe",
'age': 40,
}
resp = api.post(base, data)
id2 = resp['uid']
print('GET LIST')
resp = api.get(f'{base}/list')
print('GET BY ID')
resp = api.get(f'{base}/{id}')
print('QUERY')
query = """{{
data(func: eq(name, "bob")) @filter(has({0})) {{
uid
name
age
}}
}}""".format(resource.capitalize())
resp = api.post('/api/query', query, raw=True)
print('search terms')
resp = api.search_terms('abc', 'en', no_links=True)
print('UPDATE')
data = {
'name': 'rob',
'age': 42,
}
resp = api.put(f"{base}/{id}", data)
print('GET BY ID')
resp = api.get(f'{base}/{id}')
print('DELETE')
api.delete(f'{base}/{id}')
api.delete(f'{base}/{id2}')
def test_crud_user():
crud('user')
def test_crud_term():
crud('term')
def test_crud_document():
crud('document')
def test_graph_update():
api.login("system", os.getenv("SYSTEM_PWD"))
data = {
'name': "bob",
'age': 39,
}
resp = api.post('/api/data/user', data)
id = resp['uid']
user_url = f'/api/data/user/{id}'
nquads = '\n'.join([f'<{id}> <first_lang> "ru" .'])
api.post('/api/nquads', nquads, content_type='application/n-quads')
resp = api.get(user_url)
assert resp['first_lang'] == 'ru'
mutation = {
'set': '\n'.join([f'<{id}> <age> "38"^^<xs:int> .']),
'delete': '\n'.join([f'<{id}> <first_lang> * .']),
}
api.post('/api/nquads', mutation)
resp = api.get(user_url)
assert resp['age'] == 38
assert 'first_lang' not in resp
api.delete(user_url)
| <filename>scripts/test_api.py
#!/usr/bin/env python
import os
import api
# todo check bad auth cases as separate test cases
def crud(resource):
api.login("system", os.getenv("SYSTEM_PWD"))
data = {
'name': "bob",
'age': 39,
}
print('CREATE')
base = '/api/data/' + resource
resp = api.post(base, data)
id = resp['uid']
data = {
'name': "joe",
'age': 40,
}
resp = api.post(base, data)
id2 = resp['uid']
print('GET LIST')
resp = api.get(f'{base}/list')
print('GET BY ID')
resp = api.get(f'{base}/{id}')
print('QUERY')
query = """{{
data(func: eq(name, "bob")) @filter(has({0})) {{
uid
name
age
}}
}}""".format(resource.capitalize())
resp = api.post('/api/query', query, raw=True)
print('search terms')
resp = api.search_terms('abc', 'en', no_links=True)
print('UPDATE')
data = {
'name': 'rob',
'age': 42,
}
resp = api.put(f"{base}/{id}", data)
print('GET BY ID')
resp = api.get(f'{base}/{id}')
print('DELETE')
api.delete(f'{base}/{id}')
api.delete(f'{base}/{id2}')
def test_crud_user():
crud('user')
def test_crud_term():
crud('term')
def test_crud_document():
crud('document')
def test_graph_update():
api.login("system", os.getenv("SYSTEM_PWD"))
data = {
'name': "bob",
'age': 39,
}
resp = api.post('/api/data/user', data)
id = resp['uid']
user_url = f'/api/data/user/{id}'
nquads = '\n'.join([f'<{id}> <first_lang> "ru" .'])
api.post('/api/nquads', nquads, content_type='application/n-quads')
resp = api.get(user_url)
assert resp['first_lang'] == 'ru'
mutation = {
'set': '\n'.join([f'<{id}> <age> "38"^^<xs:int> .']),
'delete': '\n'.join([f'<{id}> <first_lang> * .']),
}
api.post('/api/nquads', mutation)
resp = api.get(user_url)
assert resp['age'] == 38
assert 'first_lang' not in resp
api.delete(user_url)
| en | 0.407662 | #!/usr/bin/env python # todo check bad auth cases as separate test cases {{ data(func: eq(name, "bob")) @filter(has({0})) {{ uid name age }} }} | 2.596708 | 3 |
src/ds/01_array.py | burhanuddinbhopalwala/py-ds-algo | 0 | 6623135 | # * Mathematical Algorithm - Lucky number
| # * Mathematical Algorithm - Lucky number
| en | 0.453034 | # * Mathematical Algorithm - Lucky number | 1.2719 | 1 |
protoseg/filters/torch_cade.py | chriamue/protoseg | 0 | 6623136 | <filename>protoseg/filters/torch_cade.py
import numpy as np
import cv2
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.multiprocessing as multiprocessing
from torch.utils import data
cade = None
def torch_cade(img, num_angles=8, distance=5, epochs=2, background_min=0, background_max=100, learn_rate=1, reinit=False):
global cade
if cade is None:
cade = CADE(img, num_angles=num_angles, distance=distance,
epochs=epochs, learn_rate=learn_rate, reinit=reinit)
return cade(img)
class Model(nn.Module):
def __init__(self, cols, rows):
super(Model, self).__init__()
self.cols = cols
self.rows = rows
self.layer1 = nn.Sequential(
nn.Conv1d(2, 2, kernel_size=1, stride=1, padding=0),
nn.BatchNorm1d(2),
nn.ReLU())
self.layer2 = nn.Sequential(
nn.Conv1d(2, 4, kernel_size=1, stride=1, padding=0),
nn.BatchNorm1d(4),
nn.ReLU())
self.layer3 = nn.Conv1d(4, 2, kernel_size=1, stride=1, padding=0)
self.layer5 = nn.Conv1d(4, 1, kernel_size=1, stride=1, padding=0)
def forward(self, x):
out = self.layer1(x)
out = self.layer2(out)
#out = self.layer3(out)
out = self.layer5(out)
out = out.view(-1)
return out
def weights_init(self, m):
if isinstance(m, nn.Conv2d) or isinstance(m, nn.BatchNorm2d):
torch.nn.init.uniform_(m.weight.data)
torch.nn.init.uniform_(m.bias.data)
class Dataset(data.Dataset):
def __init__(self, x, y):
self.x = x
self.y = y
def __len__(self):
return len(self.x)
def __getitem__(self, idx):
return self.x[idx], self.y[idx]
class CADE():
torch.multiprocessing.set_start_method('forkserver', force=True)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
def __init__(self, img, num_angles=8, distance=5, epochs=2, background_min=0, background_max=1, learn_rate=1, reinit=False):
self.img = img
if len(img.shape) == 3:
self.img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
self.rows = img.shape[0]
self.cols = img.shape[1]
self.num_angles = num_angles
self.distance = distance
self.epochs = epochs
self.background_min = background_min
self.background_max = background_max
self.reinit = reinit
self.angles = np.linspace(
0, (360.0 - 360.0 / self.num_angles), self.num_angles)
self.model = Model(self.cols, self.rows)
self.model = self.model.to(self.device)
self.criterion = nn.BCEWithLogitsLoss()
self.optimizer = torch.optim.Adam(
self.model.parameters(), lr=learn_rate)
def rotationFilter(self, angle, distance):
rows = 2*distance+1
cols = 2*distance+1
filt = np.zeros((rows, cols))
filt[2*distance] = 0.5
filt[distance] = -0.5
M = cv2.getRotationMatrix2D((cols, rows), angle, 1)
return cv2.warpAffine(filt, M, (cols, rows))
def neighbourhood(self, img, angle, distance):
return cv2.filter2D(img, -1, kernel=self.rotationFilter(angle, distance))
def dataset(self, x, y):
for i in range(len(x)):
yield (x[i], y[i])
def cade(self, img, neighbours):
preds = []
for neighbour in neighbours:
if self.reinit is True:
self.model.apply(self.model.weights_init)
distr = list(map(list, zip(img.ravel(), neighbour.ravel())))
distr = np.atleast_3d(distr)
x = np.array(distr)
y = np.zeros(len(x))
x_fake = np.random.uniform(
self.background_min, self.background_max, x.shape)
y_fake = np.ones(y.shape)
x_full = np.concatenate((x, x_fake), axis=0)
y_full = np.concatenate((y, y_fake), axis=0)
dataloader = data.DataLoader(
Dataset(x_full, y_full), batch_size=25000, shuffle=True
)
for _ in range(self.epochs):
for (x_,y_) in dataloader:
self.train_img(x_, y_)
self.model.eval()
x = torch.from_numpy(x).float().to(self.device)
prob = self.model(x)
prob = prob.cpu().detach().numpy()
prob = prob.reshape(img.shape)
preds.append(prob)
return preds
def train_img(self, x, y):
x = x.float().to(self.device)
y = y.float().to(self.device)
# Forward pass
outputs = self.model(x)
loss = self.criterion(outputs, y)
# Backward and optimize
self.optimizer.zero_grad()
loss.backward()
self.optimizer.step()
def batchify(self, imgs):
img_batch = np.array(imgs)
img_batch = np.expand_dims(img_batch, axis=3)
img_batch = np.transpose(img_batch, axes=[0, 3, 1, 2])
return img_batch
def __call__(self, img=None):
if img is None:
img = self.img
if len(img.shape) == 3:
img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
if self.reinit is True:
self.model.apply(self.model.weights_init)
neighbours = []
for angle in self.angles:
neighbourhood_ = self.neighbourhood(img, angle, self.distance)
neighbours.append(neighbourhood_)
preds = self.cade(img, neighbours)
pred = np.sum(np.array(preds), axis=0)
pred = pred / (0.0001+pred.max())
pred = pred * 255
return pred.astype(np.uint8)
| <filename>protoseg/filters/torch_cade.py
import numpy as np
import cv2
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.multiprocessing as multiprocessing
from torch.utils import data
cade = None
def torch_cade(img, num_angles=8, distance=5, epochs=2, background_min=0, background_max=100, learn_rate=1, reinit=False):
global cade
if cade is None:
cade = CADE(img, num_angles=num_angles, distance=distance,
epochs=epochs, learn_rate=learn_rate, reinit=reinit)
return cade(img)
class Model(nn.Module):
def __init__(self, cols, rows):
super(Model, self).__init__()
self.cols = cols
self.rows = rows
self.layer1 = nn.Sequential(
nn.Conv1d(2, 2, kernel_size=1, stride=1, padding=0),
nn.BatchNorm1d(2),
nn.ReLU())
self.layer2 = nn.Sequential(
nn.Conv1d(2, 4, kernel_size=1, stride=1, padding=0),
nn.BatchNorm1d(4),
nn.ReLU())
self.layer3 = nn.Conv1d(4, 2, kernel_size=1, stride=1, padding=0)
self.layer5 = nn.Conv1d(4, 1, kernel_size=1, stride=1, padding=0)
def forward(self, x):
out = self.layer1(x)
out = self.layer2(out)
#out = self.layer3(out)
out = self.layer5(out)
out = out.view(-1)
return out
def weights_init(self, m):
if isinstance(m, nn.Conv2d) or isinstance(m, nn.BatchNorm2d):
torch.nn.init.uniform_(m.weight.data)
torch.nn.init.uniform_(m.bias.data)
class Dataset(data.Dataset):
def __init__(self, x, y):
self.x = x
self.y = y
def __len__(self):
return len(self.x)
def __getitem__(self, idx):
return self.x[idx], self.y[idx]
class CADE():
torch.multiprocessing.set_start_method('forkserver', force=True)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
def __init__(self, img, num_angles=8, distance=5, epochs=2, background_min=0, background_max=1, learn_rate=1, reinit=False):
self.img = img
if len(img.shape) == 3:
self.img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
self.rows = img.shape[0]
self.cols = img.shape[1]
self.num_angles = num_angles
self.distance = distance
self.epochs = epochs
self.background_min = background_min
self.background_max = background_max
self.reinit = reinit
self.angles = np.linspace(
0, (360.0 - 360.0 / self.num_angles), self.num_angles)
self.model = Model(self.cols, self.rows)
self.model = self.model.to(self.device)
self.criterion = nn.BCEWithLogitsLoss()
self.optimizer = torch.optim.Adam(
self.model.parameters(), lr=learn_rate)
def rotationFilter(self, angle, distance):
rows = 2*distance+1
cols = 2*distance+1
filt = np.zeros((rows, cols))
filt[2*distance] = 0.5
filt[distance] = -0.5
M = cv2.getRotationMatrix2D((cols, rows), angle, 1)
return cv2.warpAffine(filt, M, (cols, rows))
def neighbourhood(self, img, angle, distance):
return cv2.filter2D(img, -1, kernel=self.rotationFilter(angle, distance))
def dataset(self, x, y):
for i in range(len(x)):
yield (x[i], y[i])
def cade(self, img, neighbours):
preds = []
for neighbour in neighbours:
if self.reinit is True:
self.model.apply(self.model.weights_init)
distr = list(map(list, zip(img.ravel(), neighbour.ravel())))
distr = np.atleast_3d(distr)
x = np.array(distr)
y = np.zeros(len(x))
x_fake = np.random.uniform(
self.background_min, self.background_max, x.shape)
y_fake = np.ones(y.shape)
x_full = np.concatenate((x, x_fake), axis=0)
y_full = np.concatenate((y, y_fake), axis=0)
dataloader = data.DataLoader(
Dataset(x_full, y_full), batch_size=25000, shuffle=True
)
for _ in range(self.epochs):
for (x_,y_) in dataloader:
self.train_img(x_, y_)
self.model.eval()
x = torch.from_numpy(x).float().to(self.device)
prob = self.model(x)
prob = prob.cpu().detach().numpy()
prob = prob.reshape(img.shape)
preds.append(prob)
return preds
def train_img(self, x, y):
x = x.float().to(self.device)
y = y.float().to(self.device)
# Forward pass
outputs = self.model(x)
loss = self.criterion(outputs, y)
# Backward and optimize
self.optimizer.zero_grad()
loss.backward()
self.optimizer.step()
def batchify(self, imgs):
img_batch = np.array(imgs)
img_batch = np.expand_dims(img_batch, axis=3)
img_batch = np.transpose(img_batch, axes=[0, 3, 1, 2])
return img_batch
def __call__(self, img=None):
if img is None:
img = self.img
if len(img.shape) == 3:
img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
if self.reinit is True:
self.model.apply(self.model.weights_init)
neighbours = []
for angle in self.angles:
neighbourhood_ = self.neighbourhood(img, angle, self.distance)
neighbours.append(neighbourhood_)
preds = self.cade(img, neighbours)
pred = np.sum(np.array(preds), axis=0)
pred = pred / (0.0001+pred.max())
pred = pred * 255
return pred.astype(np.uint8)
| en | 0.556009 | #out = self.layer3(out) # Forward pass # Backward and optimize | 2.720548 | 3 |
modules/model_alignment.py | HHeracles/SEGR | 0 | 6623137 | import torch
import torch.nn as nn
from fastai.vision import *
from modules.model import Model, _default_tfmer_cfg
class BaseAlignment(Model):
def __init__(self, config):
super().__init__(config)
d_model = ifnone(config.model_alignment_d_model, _default_tfmer_cfg['d_model'])
self.loss_weight = ifnone(config.model_alignment_loss_weight, 1.0)
self.max_length = config.dataset_max_length + 1 # additional stop token
self.w_att = nn.Linear(2 * d_model, d_model)
self.cls = nn.Linear(d_model, self.charset.num_classes)
def forward(self, l_feature, v_feature):
"""
Args:
l_feature: (N, T, E) where T is length, N is batch size and d is dim of model
v_feature: (N, T, E) shape the same as l_feature
l_lengths: (N,)
v_lengths: (N,)
"""
f = torch.cat((l_feature, v_feature), dim=2)
f_att = torch.sigmoid(self.w_att(f))
output = f_att * v_feature + (1 - f_att) * l_feature
logits = self.cls(output) # (N, T, C)
pt_lengths = self._get_length(logits)
return {'feature': output, 'logits': logits, 'pt_lengths': pt_lengths, 'loss_weight':self.loss_weight,
'name': 'alignment'}
class SEFusionBlock(nn.Module):
#def __init__(self, in_planes, planes, stride=1):
def __init__(self, planes, stride=1):
super(SEFusionBlock, self).__init__()
# SE layers
self.planes = planes
self.fc1 = nn.Conv2d(planes, planes//16, kernel_size=1) # Use nn.Conv2d instead of nn.Linear
self.fc2 = nn.Conv2d(planes//16, planes, kernel_size=1)
def forward(self, x):
#def forward(self, l_feature, v_feature):
dim = x.dim()
#if dim==3:
# x = x.permute(1, 0, 2)
# x=x.unsqueeze(-1)
x=x.unsqueeze(-1)
out = x
w = F.avg_pool2d(out, (out.size(2), out.size(3)))
w = F.relu(self.fc1(w))
w = F.sigmoid(self.fc2(w))
# Excitation
out = out * w # New broadcasting feature from v0.2!
output = out + x
output = F.relu(output)#.contiguous()
if dim==3:
output = output.squeeze(-1)
return w, out, output,
class SEFusion(Model):
def __init__(self, config):
super().__init__(config)
d_model = ifnone(config.model_alignment_d_model, _default_tfmer_cfg['d_model'])
self.loss_weight = ifnone(config.model_alignment_loss_weight, 1.0)
self.max_length = config.dataset_max_length + 1 # additional stop token
self.w_att = nn.Linear(2 * d_model, d_model)
self.cls = nn.Linear(d_model, self.charset.num_classes)
self.SEBlock_V = SEFusionBlock(self.max_length)
self.SEBlock_L = SEFusionBlock(self.max_length)
def forward(self, l_feature, v_feature):
"""
Args:
l_feature: (N, T, E) where T is length, N is batch size and d is dim of model
v_feature: (N, T, E) shape the same as l_feature
l_lengths: (N,)
v_lengths: (N,)
"""
weight_l, sum_oput_v, l_feature = self.SEBlock_L(l_feature)
weight_v, sum_out_v, v_feature = self.SEBlock_V(v_feature)
f = torch.cat((l_feature, v_feature), dim=2)
f_att = torch.sigmoid(self.w_att(f))
output = f_att * v_feature + (1 - f_att) * l_feature
logits = self.cls(output) # (N, T, C)
pt_lengths = self._get_length(logits)
return {'feature': output, 'logits': logits, 'pt_lengths': pt_lengths, 'loss_weight':self.loss_weight,
'name': 'alignment'}
class SEGateCrossFusion(Model):
def __init__(self, config):
super().__init__(config)
d_model = ifnone(config.model_alignment_d_model, _default_tfmer_cfg['d_model'])
self.loss_weight = ifnone(config.model_alignment_loss_weight, 1.0)
self.max_length = config.dataset_max_length + 1 # additional stop token
self.w_att = nn.Linear(2 * d_model, d_model)
self.cls = nn.Linear(d_model, self.charset.num_classes)
self.SEBlock_V = SEFusionBlock(self.max_length)
self.SEBlock_L = SEFusionBlock(self.max_length)
def forward(self, l_feature, v_feature):
"""
Args:
l_feature: (N, T, E) where T is length, N is batch size and d is dim of model
v_feature: (N, T, E) shape the same as l_feature
l_lengths: (N,)
v_lengths: (N,)
"""
dim = l_feature.dim()
weight_l, sum_oput_v, l_SeFeature = self.SEBlock_L(l_feature)
weight_v, sum_out_v, v_SeFeature = self.SEBlock_V(v_feature)
l_feature, v_feature = l_feature.unsqueeze(-1), v_feature.unsqueeze(-1)
l_feature_ori, v_feature_ori = l_feature, v_feature
l_feature = l_feature * weight_v
l_feature = l_feature_ori + l_feature
l_feature = F.relu(l_feature)#.contiguous()
if dim==3:
l_feature = l_feature.squeeze(-1)
v_feature = v_feature * weight_l
v_feature = v_feature_ori + v_feature
v_feature = F.relu(v_feature)#.contiguous()
if dim==3:
v_feature = v_feature.squeeze(-1)
f = torch.cat((l_feature, v_feature), dim=2)
f_att = torch.sigmoid(self.w_att(f))
output = f_att * v_feature + (1 - f_att) * l_feature
logits = self.cls(output) # (N, T, C)
pt_lengths = self._get_length(logits)
return {'feature': output, 'logits': logits, 'pt_lengths': pt_lengths, 'loss_weight':self.loss_weight,
'name': 'alignment'}
class SemanticFusionAlignment(Model):
def __init__(self, config):
super().__init__(config)
d_model = ifnone(config.model_alignment_d_model, _default_tfmer_cfg['d_model'])
self.loss_weight = ifnone(config.model_alignment_loss_weight, 1.0)
self.max_length = config.dataset_max_length + 1 # additional stop token
self.w_att = nn.Linear(2 * d_model, d_model)
self.cls = nn.Linear(d_model, self.charset.num_classes)
self.w_f = nn.Linear(2 * d_model, d_model)
self.w_i = nn.Linear(2 * d_model, d_model)
self.w_c = nn.Linear(2 * d_model, d_model)
self.w_o = nn.Linear(2 * d_model, d_model)
def forward(self, l_feature, v_feature):
"""
Args:
l_feature: (N, T, E) where T is length, N is batch size and d is dim of model
v_feature: (N, T, E) shape the same as l_feature
l_lengths: (N,)
v_lengths: (N,)
l_featrue as input and cell, v_feaature as hinden
"""
i , c, h = l_featrue, l_featrue, v_feaature
# forgate gate
t = self.w_f(torch.cat((l_feature, v_feature), dim=2))
ft = torch.sigmoid(t)
#input gate
it = torch.sigmoid(self.w_i(torch.cat((l_feature, v_feature), dim=2)))
ct_ = torch.tanh(self.w_c(torch.cat((l_feature, v_feature), dim=2)))
ct = ft * c + it * ct_
#output gate
ot = torch.sigmoid(self.w_o(torch.cat((l_feature, v_feature), dim=2)))
ht = ot * torch.tanh(ct)
f = torch.cat((l_feature, v_feature), dim=2)
f_att = torch.sigmoid(self.w_att(f))
output = f_att * v_feature + (1 - f_att) * l_feature
logits = self.cls(output) # (N, T, C)
pt_lengths = self._get_length(logits)
return {'feature': output, 'logits': logits, 'pt_lengths': pt_lengths, 'loss_weight':self.loss_weight,
'name': 'alignment'}
class VotingFusion(Model):
def __init__(self, config):
super().__init__(config)
d_model = ifnone(config.model_alignment_d_model, _default_tfmer_cfg['d_model'])
self.loss_weight = ifnone(config.model_alignment_loss_weight, 1.0)
self.max_length = config.dataset_max_length + 1 # additional stop token
self.w_att = nn.Linear(2 * d_model, d_model)
self.cls = nn.Linear(d_model, self.charset.num_classes)
def forward(self, res):
vot_res = res
cls_1 = F.softmax(vot_res[0]['logits'], dim=2)
cls_2 = F.softmax(vot_res[1]['logits'], dim=2)
cls_3 = F.softmax(vot_res[2]['logits'], dim=2)
fusion_logits = vot_res[0]['logits']
for i, cl in enumerate(cls_1):
score_1 = cl.max(dim=1)[0]
score_2 = cls_2[i].max(dim=1)[0]
score_3 = cls_3[i].max(dim=1)[0]
for j in range(score_1.shape[0]):
if score_1[j] < score_2[j]:
fusion_logits[i,j,:] = vot_res[1]['logits'][i,j,:]
if score_2[j] < score_3[j]:
fusion_logits[i,j,:] = vot_res[2]['logits'][i,j,:]
else:
fusion_logits[i,j,:] = vot_res[0]['logits'][i,j,:]
if score_1[j] < score_3[j]:
fusion_logits[i,j,:] = vot_res[2]['logits'][i,j,:]
pt_lengths = self._get_length(fusion_logits)
res = {'logits': fusion_logits, 'pt_lengths': pt_lengths, 'loss_weight':1.0,'name': 'voting'}
return res
| import torch
import torch.nn as nn
from fastai.vision import *
from modules.model import Model, _default_tfmer_cfg
class BaseAlignment(Model):
def __init__(self, config):
super().__init__(config)
d_model = ifnone(config.model_alignment_d_model, _default_tfmer_cfg['d_model'])
self.loss_weight = ifnone(config.model_alignment_loss_weight, 1.0)
self.max_length = config.dataset_max_length + 1 # additional stop token
self.w_att = nn.Linear(2 * d_model, d_model)
self.cls = nn.Linear(d_model, self.charset.num_classes)
def forward(self, l_feature, v_feature):
"""
Args:
l_feature: (N, T, E) where T is length, N is batch size and d is dim of model
v_feature: (N, T, E) shape the same as l_feature
l_lengths: (N,)
v_lengths: (N,)
"""
f = torch.cat((l_feature, v_feature), dim=2)
f_att = torch.sigmoid(self.w_att(f))
output = f_att * v_feature + (1 - f_att) * l_feature
logits = self.cls(output) # (N, T, C)
pt_lengths = self._get_length(logits)
return {'feature': output, 'logits': logits, 'pt_lengths': pt_lengths, 'loss_weight':self.loss_weight,
'name': 'alignment'}
class SEFusionBlock(nn.Module):
#def __init__(self, in_planes, planes, stride=1):
def __init__(self, planes, stride=1):
super(SEFusionBlock, self).__init__()
# SE layers
self.planes = planes
self.fc1 = nn.Conv2d(planes, planes//16, kernel_size=1) # Use nn.Conv2d instead of nn.Linear
self.fc2 = nn.Conv2d(planes//16, planes, kernel_size=1)
def forward(self, x):
#def forward(self, l_feature, v_feature):
dim = x.dim()
#if dim==3:
# x = x.permute(1, 0, 2)
# x=x.unsqueeze(-1)
x=x.unsqueeze(-1)
out = x
w = F.avg_pool2d(out, (out.size(2), out.size(3)))
w = F.relu(self.fc1(w))
w = F.sigmoid(self.fc2(w))
# Excitation
out = out * w # New broadcasting feature from v0.2!
output = out + x
output = F.relu(output)#.contiguous()
if dim==3:
output = output.squeeze(-1)
return w, out, output,
class SEFusion(Model):
def __init__(self, config):
super().__init__(config)
d_model = ifnone(config.model_alignment_d_model, _default_tfmer_cfg['d_model'])
self.loss_weight = ifnone(config.model_alignment_loss_weight, 1.0)
self.max_length = config.dataset_max_length + 1 # additional stop token
self.w_att = nn.Linear(2 * d_model, d_model)
self.cls = nn.Linear(d_model, self.charset.num_classes)
self.SEBlock_V = SEFusionBlock(self.max_length)
self.SEBlock_L = SEFusionBlock(self.max_length)
def forward(self, l_feature, v_feature):
"""
Args:
l_feature: (N, T, E) where T is length, N is batch size and d is dim of model
v_feature: (N, T, E) shape the same as l_feature
l_lengths: (N,)
v_lengths: (N,)
"""
weight_l, sum_oput_v, l_feature = self.SEBlock_L(l_feature)
weight_v, sum_out_v, v_feature = self.SEBlock_V(v_feature)
f = torch.cat((l_feature, v_feature), dim=2)
f_att = torch.sigmoid(self.w_att(f))
output = f_att * v_feature + (1 - f_att) * l_feature
logits = self.cls(output) # (N, T, C)
pt_lengths = self._get_length(logits)
return {'feature': output, 'logits': logits, 'pt_lengths': pt_lengths, 'loss_weight':self.loss_weight,
'name': 'alignment'}
class SEGateCrossFusion(Model):
def __init__(self, config):
super().__init__(config)
d_model = ifnone(config.model_alignment_d_model, _default_tfmer_cfg['d_model'])
self.loss_weight = ifnone(config.model_alignment_loss_weight, 1.0)
self.max_length = config.dataset_max_length + 1 # additional stop token
self.w_att = nn.Linear(2 * d_model, d_model)
self.cls = nn.Linear(d_model, self.charset.num_classes)
self.SEBlock_V = SEFusionBlock(self.max_length)
self.SEBlock_L = SEFusionBlock(self.max_length)
def forward(self, l_feature, v_feature):
"""
Args:
l_feature: (N, T, E) where T is length, N is batch size and d is dim of model
v_feature: (N, T, E) shape the same as l_feature
l_lengths: (N,)
v_lengths: (N,)
"""
dim = l_feature.dim()
weight_l, sum_oput_v, l_SeFeature = self.SEBlock_L(l_feature)
weight_v, sum_out_v, v_SeFeature = self.SEBlock_V(v_feature)
l_feature, v_feature = l_feature.unsqueeze(-1), v_feature.unsqueeze(-1)
l_feature_ori, v_feature_ori = l_feature, v_feature
l_feature = l_feature * weight_v
l_feature = l_feature_ori + l_feature
l_feature = F.relu(l_feature)#.contiguous()
if dim==3:
l_feature = l_feature.squeeze(-1)
v_feature = v_feature * weight_l
v_feature = v_feature_ori + v_feature
v_feature = F.relu(v_feature)#.contiguous()
if dim==3:
v_feature = v_feature.squeeze(-1)
f = torch.cat((l_feature, v_feature), dim=2)
f_att = torch.sigmoid(self.w_att(f))
output = f_att * v_feature + (1 - f_att) * l_feature
logits = self.cls(output) # (N, T, C)
pt_lengths = self._get_length(logits)
return {'feature': output, 'logits': logits, 'pt_lengths': pt_lengths, 'loss_weight':self.loss_weight,
'name': 'alignment'}
class SemanticFusionAlignment(Model):
def __init__(self, config):
super().__init__(config)
d_model = ifnone(config.model_alignment_d_model, _default_tfmer_cfg['d_model'])
self.loss_weight = ifnone(config.model_alignment_loss_weight, 1.0)
self.max_length = config.dataset_max_length + 1 # additional stop token
self.w_att = nn.Linear(2 * d_model, d_model)
self.cls = nn.Linear(d_model, self.charset.num_classes)
self.w_f = nn.Linear(2 * d_model, d_model)
self.w_i = nn.Linear(2 * d_model, d_model)
self.w_c = nn.Linear(2 * d_model, d_model)
self.w_o = nn.Linear(2 * d_model, d_model)
def forward(self, l_feature, v_feature):
"""
Args:
l_feature: (N, T, E) where T is length, N is batch size and d is dim of model
v_feature: (N, T, E) shape the same as l_feature
l_lengths: (N,)
v_lengths: (N,)
l_featrue as input and cell, v_feaature as hinden
"""
i , c, h = l_featrue, l_featrue, v_feaature
# forgate gate
t = self.w_f(torch.cat((l_feature, v_feature), dim=2))
ft = torch.sigmoid(t)
#input gate
it = torch.sigmoid(self.w_i(torch.cat((l_feature, v_feature), dim=2)))
ct_ = torch.tanh(self.w_c(torch.cat((l_feature, v_feature), dim=2)))
ct = ft * c + it * ct_
#output gate
ot = torch.sigmoid(self.w_o(torch.cat((l_feature, v_feature), dim=2)))
ht = ot * torch.tanh(ct)
f = torch.cat((l_feature, v_feature), dim=2)
f_att = torch.sigmoid(self.w_att(f))
output = f_att * v_feature + (1 - f_att) * l_feature
logits = self.cls(output) # (N, T, C)
pt_lengths = self._get_length(logits)
return {'feature': output, 'logits': logits, 'pt_lengths': pt_lengths, 'loss_weight':self.loss_weight,
'name': 'alignment'}
class VotingFusion(Model):
def __init__(self, config):
super().__init__(config)
d_model = ifnone(config.model_alignment_d_model, _default_tfmer_cfg['d_model'])
self.loss_weight = ifnone(config.model_alignment_loss_weight, 1.0)
self.max_length = config.dataset_max_length + 1 # additional stop token
self.w_att = nn.Linear(2 * d_model, d_model)
self.cls = nn.Linear(d_model, self.charset.num_classes)
def forward(self, res):
vot_res = res
cls_1 = F.softmax(vot_res[0]['logits'], dim=2)
cls_2 = F.softmax(vot_res[1]['logits'], dim=2)
cls_3 = F.softmax(vot_res[2]['logits'], dim=2)
fusion_logits = vot_res[0]['logits']
for i, cl in enumerate(cls_1):
score_1 = cl.max(dim=1)[0]
score_2 = cls_2[i].max(dim=1)[0]
score_3 = cls_3[i].max(dim=1)[0]
for j in range(score_1.shape[0]):
if score_1[j] < score_2[j]:
fusion_logits[i,j,:] = vot_res[1]['logits'][i,j,:]
if score_2[j] < score_3[j]:
fusion_logits[i,j,:] = vot_res[2]['logits'][i,j,:]
else:
fusion_logits[i,j,:] = vot_res[0]['logits'][i,j,:]
if score_1[j] < score_3[j]:
fusion_logits[i,j,:] = vot_res[2]['logits'][i,j,:]
pt_lengths = self._get_length(fusion_logits)
res = {'logits': fusion_logits, 'pt_lengths': pt_lengths, 'loss_weight':1.0,'name': 'voting'}
return res
| en | 0.868694 | # additional stop token Args: l_feature: (N, T, E) where T is length, N is batch size and d is dim of model v_feature: (N, T, E) shape the same as l_feature l_lengths: (N,) v_lengths: (N,) # (N, T, C) #def __init__(self, in_planes, planes, stride=1): # SE layers # Use nn.Conv2d instead of nn.Linear #def forward(self, l_feature, v_feature): #if dim==3: # x = x.permute(1, 0, 2) # x=x.unsqueeze(-1) # Excitation # New broadcasting feature from v0.2! #.contiguous() # additional stop token Args: l_feature: (N, T, E) where T is length, N is batch size and d is dim of model v_feature: (N, T, E) shape the same as l_feature l_lengths: (N,) v_lengths: (N,) # (N, T, C) # additional stop token Args: l_feature: (N, T, E) where T is length, N is batch size and d is dim of model v_feature: (N, T, E) shape the same as l_feature l_lengths: (N,) v_lengths: (N,) #.contiguous() #.contiguous() # (N, T, C) # additional stop token Args: l_feature: (N, T, E) where T is length, N is batch size and d is dim of model v_feature: (N, T, E) shape the same as l_feature l_lengths: (N,) v_lengths: (N,) l_featrue as input and cell, v_feaature as hinden # forgate gate #input gate #output gate # (N, T, C) # additional stop token | 2.459755 | 2 |
openexplorer_old/tools/quench/__init__.py | uibcdf/PELE-OpenMM | 0 | 6623138 | from .l_bfgs import L_BFGS
from .fire import FIRE
from .gradient_descent import GradientDescent
| from .l_bfgs import L_BFGS
from .fire import FIRE
from .gradient_descent import GradientDescent
| none | 1 | 0.995036 | 1 | |
Python/042.py | joonion/Project-Euler | 0 | 6623139 | <reponame>joonion/Project-Euler
from math import floor, sqrt
def is_triangle(word):
s = 0
for i in range(len(word)):
s += ord(word[i]) - ord('A') + 1
n = 8 * s + 1
if n == floor(sqrt(n)) ** 2:
return True
else:
return False
def solve(words):
count = 0
for i in range(len(words)):
if is_triangle(words[i]):
count += 1
return count
def trim(s):
return s.replace("\"", "")
words = list(map(trim, input().split(",")))
answer = solve(words)
print(answer)
| from math import floor, sqrt
def is_triangle(word):
s = 0
for i in range(len(word)):
s += ord(word[i]) - ord('A') + 1
n = 8 * s + 1
if n == floor(sqrt(n)) ** 2:
return True
else:
return False
def solve(words):
count = 0
for i in range(len(words)):
if is_triangle(words[i]):
count += 1
return count
def trim(s):
return s.replace("\"", "")
words = list(map(trim, input().split(",")))
answer = solve(words)
print(answer) | none | 1 | 3.66104 | 4 | |
pci_reset.py | RightHandRobotics/linux-bus-reset-tools | 1 | 6623140 | #!/usr/bin/python
"""pci_reset - does an unbind/bind of an entire device"""
import sys
import argparse
import os
from os.path import realpath
from systools import sleep_with_countdown, lspci, lspci_lookup, bind, unbind
if __name__ == "__main__":
## let's restrict ourselves to USB controllers for now...
# 00:14.0 USB controller: Intel Corporation Wildcat Point-LP USB xHCI Controller (rev 03)
# 00:1d.0 USB controller: Intel Corporation Wildcat Point-LP USB EHCI Controller (rev 03)
# UHCI: USB 1.x
# EHCI: USB 2.0
# XHCI: USB 3.x
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("--pci-bus", default="0000")
parser.add_argument("--pci-id", "-s", help="raw PCI id (no checking)")
parser.add_argument("--usb2", "-2", action="store_true", help="Find one usb2(ehci) controller and whack it")
parser.add_argument("--usb3", "-3", action="store_true", help="Find one usb3(xhci) controller and whack it")
args = parser.parse_args()
if args.pci_id:
if args.usb2 or args.usb3:
sys.exit("id *or* controller, not both")
pci_id = args.pci_id
slots = lspci().keys()
if pci_id not in slots:
sys.exit("{} not found in {!r}".format(pci_id, slots))
elif args.usb2:
if args.usb3:
sys.exit("only reset one controller at a time")
pci_id = lspci_lookup("USB controller", "EHCI") # class 0x0c03
elif args.usb3:
if args.usb2:
sys.exit("only reset one controller at a time")
pci_id = lspci_lookup("USB controller", "xHCI") # class 0x0c03
else:
sys.exit("specify some pci slot")
full_pci_id = "{}:{}".format(args.pci_bus, pci_id)
print "id:", full_pci_id
driver = realpath("/sys/bus/pci/devices/{}/driver".format(full_pci_id))
print "driver:", driver
assert os.path.exists(driver), "{} not found".format(driver)
raw_input("Press RETURN to unbind, sleep 5, and rebind: ")
print "Unbinding", full_pci_id
unbind(driver, full_pci_id)
sleep_with_countdown(5)
print "Rebinding", full_pci_id
bind(driver, full_pci_id)
sleep_with_countdown(3)
print lspci().get(pci_id, "{} not found after rebind!".format(pci_id))
# TODO: catch any added lines in kern.log for signs of activity
| #!/usr/bin/python
"""pci_reset - does an unbind/bind of an entire device"""
import sys
import argparse
import os
from os.path import realpath
from systools import sleep_with_countdown, lspci, lspci_lookup, bind, unbind
if __name__ == "__main__":
## let's restrict ourselves to USB controllers for now...
# 00:14.0 USB controller: Intel Corporation Wildcat Point-LP USB xHCI Controller (rev 03)
# 00:1d.0 USB controller: Intel Corporation Wildcat Point-LP USB EHCI Controller (rev 03)
# UHCI: USB 1.x
# EHCI: USB 2.0
# XHCI: USB 3.x
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("--pci-bus", default="0000")
parser.add_argument("--pci-id", "-s", help="raw PCI id (no checking)")
parser.add_argument("--usb2", "-2", action="store_true", help="Find one usb2(ehci) controller and whack it")
parser.add_argument("--usb3", "-3", action="store_true", help="Find one usb3(xhci) controller and whack it")
args = parser.parse_args()
if args.pci_id:
if args.usb2 or args.usb3:
sys.exit("id *or* controller, not both")
pci_id = args.pci_id
slots = lspci().keys()
if pci_id not in slots:
sys.exit("{} not found in {!r}".format(pci_id, slots))
elif args.usb2:
if args.usb3:
sys.exit("only reset one controller at a time")
pci_id = lspci_lookup("USB controller", "EHCI") # class 0x0c03
elif args.usb3:
if args.usb2:
sys.exit("only reset one controller at a time")
pci_id = lspci_lookup("USB controller", "xHCI") # class 0x0c03
else:
sys.exit("specify some pci slot")
full_pci_id = "{}:{}".format(args.pci_bus, pci_id)
print "id:", full_pci_id
driver = realpath("/sys/bus/pci/devices/{}/driver".format(full_pci_id))
print "driver:", driver
assert os.path.exists(driver), "{} not found".format(driver)
raw_input("Press RETURN to unbind, sleep 5, and rebind: ")
print "Unbinding", full_pci_id
unbind(driver, full_pci_id)
sleep_with_countdown(5)
print "Rebinding", full_pci_id
bind(driver, full_pci_id)
sleep_with_countdown(3)
print lspci().get(pci_id, "{} not found after rebind!".format(pci_id))
# TODO: catch any added lines in kern.log for signs of activity
| en | 0.657759 | #!/usr/bin/python pci_reset - does an unbind/bind of an entire device ## let's restrict ourselves to USB controllers for now... # 00:14.0 USB controller: Intel Corporation Wildcat Point-LP USB xHCI Controller (rev 03) # 00:1d.0 USB controller: Intel Corporation Wildcat Point-LP USB EHCI Controller (rev 03) # UHCI: USB 1.x # EHCI: USB 2.0 # XHCI: USB 3.x # class 0x0c03 # class 0x0c03 # TODO: catch any added lines in kern.log for signs of activity | 2.568166 | 3 |
python/src/wslink/wslinktypes.py | yasushi-saito/wslink | 0 | 6623141 | from typing import Dict, List, Optional, TypedDict
from wslink.websocket import ServerProtocol
class ServerConfig(TypedDict, total=False):
# The network interface to bind to. If None,
# bind to all interfaces.
host: Optional[str]
# HTTP port to listen to.
port: int
# Idle shutdown timeout, in seconds.
timeout: float
# websocket routes.
ws: Dict[str, ServerProtocol]
# static file serving routes
static: Dict[str, str]
logging_level: Optional[int]
handle_signals: bool
| from typing import Dict, List, Optional, TypedDict
from wslink.websocket import ServerProtocol
class ServerConfig(TypedDict, total=False):
# The network interface to bind to. If None,
# bind to all interfaces.
host: Optional[str]
# HTTP port to listen to.
port: int
# Idle shutdown timeout, in seconds.
timeout: float
# websocket routes.
ws: Dict[str, ServerProtocol]
# static file serving routes
static: Dict[str, str]
logging_level: Optional[int]
handle_signals: bool
| en | 0.780991 | # The network interface to bind to. If None, # bind to all interfaces. # HTTP port to listen to. # Idle shutdown timeout, in seconds. # websocket routes. # static file serving routes | 2.497462 | 2 |
03_For/Step10/yj.py | StudyForCoding/BEAKJOON | 0 | 6623142 | a = int(input())
for i in range(1,a+1):
print(' '*(a-i)+'*'*i) | a = int(input())
for i in range(1,a+1):
print(' '*(a-i)+'*'*i) | none | 1 | 3.397409 | 3 | |
applications/mupio/migrations/0004_auto_20210721_0338.py | PEM-Humboldt/visor-geografico-I2d-backend | 0 | 6623143 | <filename>applications/mupio/migrations/0004_auto_20210721_0338.py
# Generated by Django 3.1.7 on 2021-07-21 03:38
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('mupio', '0003_delete_mpiopolitico'),
]
operations = [
migrations.CreateModel(
name='MpioAmenazas',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('codigo', models.CharField(blank=True, max_length=5, null=True)),
('tipo', models.CharField(blank=True, max_length=1, null=True)),
('amenazadas', models.BigIntegerField(blank=True, null=True)),
('geom', models.TextField(blank=True, null=True)),
('nombre', models.CharField(blank=True, max_length=254, null=True)),
],
options={
'db_table': 'mpio_amenazas',
'managed': False,
},
),
migrations.CreateModel(
name='MpioQueries',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('codigo', models.CharField(blank=True, max_length=5, null=True)),
('tipo', models.TextField(blank=True, null=True)),
('registers', models.BigIntegerField(blank=True, null=True)),
('species', models.BigIntegerField(blank=True, null=True)),
('exoticas', models.BigIntegerField(blank=True, null=True)),
('endemicas', models.BigIntegerField(blank=True, null=True)),
('geom', models.TextField(blank=True, null=True)),
('nombre', models.CharField(blank=True, max_length=254, null=True)),
],
options={
'db_table': 'mpio_queries',
'managed': False,
},
),
migrations.DeleteModel(
name='MpioTipo',
),
]
| <filename>applications/mupio/migrations/0004_auto_20210721_0338.py
# Generated by Django 3.1.7 on 2021-07-21 03:38
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('mupio', '0003_delete_mpiopolitico'),
]
operations = [
migrations.CreateModel(
name='MpioAmenazas',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('codigo', models.CharField(blank=True, max_length=5, null=True)),
('tipo', models.CharField(blank=True, max_length=1, null=True)),
('amenazadas', models.BigIntegerField(blank=True, null=True)),
('geom', models.TextField(blank=True, null=True)),
('nombre', models.CharField(blank=True, max_length=254, null=True)),
],
options={
'db_table': 'mpio_amenazas',
'managed': False,
},
),
migrations.CreateModel(
name='MpioQueries',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('codigo', models.CharField(blank=True, max_length=5, null=True)),
('tipo', models.TextField(blank=True, null=True)),
('registers', models.BigIntegerField(blank=True, null=True)),
('species', models.BigIntegerField(blank=True, null=True)),
('exoticas', models.BigIntegerField(blank=True, null=True)),
('endemicas', models.BigIntegerField(blank=True, null=True)),
('geom', models.TextField(blank=True, null=True)),
('nombre', models.CharField(blank=True, max_length=254, null=True)),
],
options={
'db_table': 'mpio_queries',
'managed': False,
},
),
migrations.DeleteModel(
name='MpioTipo',
),
]
| en | 0.802675 | # Generated by Django 3.1.7 on 2021-07-21 03:38 | 1.648416 | 2 |
hw1/generate_dagger_comparison_plot.py | Khodeir/homework | 0 | 6623144 | <reponame>Khodeir/homework
import matplotlib
matplotlib.use('Agg')
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from glob import glob
import pickle
import numpy as np
import re
num_re = re.compile(r'(\d+)[^0-9]*$')
def get_last_num_in_str(path):
match = num_re.search(path)
return int(match.group(1)) if match else None
data = []
runs = sorted([(get_last_num_in_str(run_dir), run_dir) for run_dir in glob('dagger_runs/*') if get_last_num_in_str(run_dir)])
run_num, run_dir = runs[-1]
rollout_data = sorted([(get_last_num_in_str(path), path) for path in glob('%s/rollouts*' % run_dir)])
for (step, rollout_path) in rollout_data:
with open(rollout_path, 'rb') as open_file:
rollout = pickle.load(open_file)
for reward in rollout['rewards']:
data.append(dict(step=step, reward=np.sum(reward)))
max_step = rollout_data[-1][0]
with open('expert_data/RoboschoolHumanoid-v1.py-100.pkl', 'rb') as expert_file:
expert_rollouts = pickle.load(expert_file)
expert_data = []
for i in range (max_step):
for reward in expert_rollouts['returns']:
expert_data.append(dict(step=i, reward=reward))
expert_df = pd.DataFrame(expert_data)
with open('models/humanoid/test_rollouts.pkl', 'rb') as clone_file:
bc_agent_rollouts = pickle.load(clone_file)
bc_agent_data = []
for i in range (max_step):
for reward in bc_agent_rollouts['rewards']:
bc_agent_data.append(dict(step=i, reward=np.sum(reward)))
bc_agent_df = pd.DataFrame(bc_agent_data)
df = pd.DataFrame(data)
plt.figure(figsize=(10,6))
sns.lineplot(data=df, x='step', y='reward', ci='sd', label='dagger')
sns.lineplot(data=expert_df, x='step', y='reward', ci='sd', label='expert')
sns.lineplot(data=bc_agent_df, x='step', y='reward', ci='sd', label='bc agent')
plt.savefig('3.2 - Dagger Comparison.png') | import matplotlib
matplotlib.use('Agg')
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from glob import glob
import pickle
import numpy as np
import re
num_re = re.compile(r'(\d+)[^0-9]*$')
def get_last_num_in_str(path):
match = num_re.search(path)
return int(match.group(1)) if match else None
data = []
runs = sorted([(get_last_num_in_str(run_dir), run_dir) for run_dir in glob('dagger_runs/*') if get_last_num_in_str(run_dir)])
run_num, run_dir = runs[-1]
rollout_data = sorted([(get_last_num_in_str(path), path) for path in glob('%s/rollouts*' % run_dir)])
for (step, rollout_path) in rollout_data:
with open(rollout_path, 'rb') as open_file:
rollout = pickle.load(open_file)
for reward in rollout['rewards']:
data.append(dict(step=step, reward=np.sum(reward)))
max_step = rollout_data[-1][0]
with open('expert_data/RoboschoolHumanoid-v1.py-100.pkl', 'rb') as expert_file:
expert_rollouts = pickle.load(expert_file)
expert_data = []
for i in range (max_step):
for reward in expert_rollouts['returns']:
expert_data.append(dict(step=i, reward=reward))
expert_df = pd.DataFrame(expert_data)
with open('models/humanoid/test_rollouts.pkl', 'rb') as clone_file:
bc_agent_rollouts = pickle.load(clone_file)
bc_agent_data = []
for i in range (max_step):
for reward in bc_agent_rollouts['rewards']:
bc_agent_data.append(dict(step=i, reward=np.sum(reward)))
bc_agent_df = pd.DataFrame(bc_agent_data)
df = pd.DataFrame(data)
plt.figure(figsize=(10,6))
sns.lineplot(data=df, x='step', y='reward', ci='sd', label='dagger')
sns.lineplot(data=expert_df, x='step', y='reward', ci='sd', label='expert')
sns.lineplot(data=bc_agent_df, x='step', y='reward', ci='sd', label='bc agent')
plt.savefig('3.2 - Dagger Comparison.png') | none | 1 | 2.153113 | 2 | |
src/utils/program3/values/value_getter.py | amasiukevich/InterpreterNew | 0 | 6623145 | from .value import Value
class ValueGetter(Value):
def __init__(self, base_getters=[]):
self.base_getters = base_getters
def __str__(self):
if self.get_num_base_getters() == 1:
return f"{self.base_getters[0]}"
else:
try:
return ".".join([str(base_getter) for base_getter in self.base_getters])
except:
breakpoint()
def __repr__(self):
return self.__str__()
def is_empty(self):
return self.base_getters == []
def get_num_base_getters(self):
return len(self.base_getters) | from .value import Value
class ValueGetter(Value):
def __init__(self, base_getters=[]):
self.base_getters = base_getters
def __str__(self):
if self.get_num_base_getters() == 1:
return f"{self.base_getters[0]}"
else:
try:
return ".".join([str(base_getter) for base_getter in self.base_getters])
except:
breakpoint()
def __repr__(self):
return self.__str__()
def is_empty(self):
return self.base_getters == []
def get_num_base_getters(self):
return len(self.base_getters) | none | 1 | 3.025864 | 3 | |
Python_3/Jupyter/test_signals.py | waynegm/OpendTect-External-Attributes | 22 | 6623146 | #
# Python Test Signal Library
#
# Copyright (C) 2018 <NAME> All rights reserved.
#
# This file may be used under the terms of the MIT License
#
# Author: <NAME>
# Date: March, 2018
#
import numpy as np
import scipy.signal as sig
def make_random_signal(nsamp):
"""Make a single trace with random reflectivity
A random reflectivity trace is convolved with a zero phase ricker wavelet
Args:
nsamp: the number of samples in the output trace
Returns:
A 1D array with the signal
"""
ref = np.random.rand(nsamp)*2-1
wav = sig.ricker(80,5)
filtered = np.convolve(ref, wav,'same')
return filtered
def make_delayed_signal_pair(nsamp, delay):
"""Make a pair of identical traces with specified delay
A random reflectivity trace is convolved with a zero phase ricker wavelet
and the created trace and a delayed version are returned
Args:
nsamp: the number of samples in the output trace
delay: the number of samples to delay the second trace
Returns:
Two 1D arrays with the undelayed and delayed signal
"""
ref = np.random.rand(nsamp+abs(delay))*2-1
wav = sig.ricker(80,5)
filtered = np.convolve(ref, wav,'same')
if delay < 0 :
return filtered[0:nsamp], filtered[-delay:nsamp-delay]
else:
return filtered[delay:nsamp+delay], filtered[0:nsamp]
class SphericalSignal(object):
"""Make a 3D spherical test signal
Provides a 3D sinusoidal, hemisperical test signal and its spatial derivatives
Args:
factor: a parameter controlling the frequency content of the signal.
Default is 5000.
xsize: the size of the 3D signal in the 1st dimension. Default is 301.
ysize: the size of the 3D signal in the 2nd dimension. Default is 301.
zsize: the size of the 3D signal in the last dimension. Default is 301.
deriv: what derivative of the test signal to create. Default is None.
"""
def __init__(self,factor=5000, xsize=301, ysize=301, zsize=301, deriv=None):
self.xs = xsize
self.ys = ysize
self.zs = zsize
self.factor = factor
f0=.01
k=.001
xtmp = np.linspace(-xsize,xsize,xsize)
ytmp = np.linspace(-ysize,ysize,ysize)
ztmp = np.linspace(-2*zsize,0,zsize)
self.x,self.y,self.z = np.meshgrid(xtmp,ytmp,ztmp, indexing='ij')
t = (self.x**2+self.y**2+self.z**2)/factor
if deriv == 'dx':
self.data = 2/factor * self.x * np.cos(t)
elif deriv == 'dy':
self.data = 2/factor * self.y * np.cos(t)
elif deriv == 'dz':
self.data = 2/factor * self.z * np.cos(t)
elif deriv == 'dxx':
self.data = 2/factor * np.cos(t) - 4/(factor*factor) * np.square(self.x) * np.sin(t)
elif deriv == 'dyy':
self.data = 2/factor * np.cos(t) - 4/(factor*factor) * np.square(self.y) * np.sin(t)
elif deriv == 'dzz':
self.data = 2/factor * np.cos(t) - 4/(factor*factor) * np.square(self.z) * np.sin(t)
elif deriv in ['dxy', 'dyx']:
self.data = -4/(factor*factor) * self.x * self.y * np.sin(t)
elif deriv in ['dxz', 'dzx']:
self.data = -4/(factor*factor) * self.x * self.z * np.sin(t)
elif deriv in ['dyz', 'dzy']:
self.data = -4/(factor*factor) * self.y * self.z * np.sin(t)
else:
self.data = np.sin(t)
def xSlice(self, x):
"""Return an y-z plane at location x
Args:
x: the x value of the required y-z plane
Returns:
A 2D array with the y-z plane if x is a valid index
otherwise returns a plane of zeros.
"""
if (x<=self.xs):
return np.transpose(self.data[x,:,:])
else:
return np.zeros((self.data[0,:,:].shape))
def ySlice(self, y):
"""Return an x-z plane at location y
Args:
y: the y value of the required x-z plane
Returns:
A 2D array with the x-z plane if y is a valid index
otherwise returns a plane of zeros.
"""
if (y<=self.ys):
return np.transpose(self.data[:,y,:])
else:
return np.zeros((self.data[:,0,:].shape))
def zSlice(self, z):
"""Return an x- plane at location z
Args:
z: the z value of the required x-y plane
Returns:
A 2D array with the x-y plane if z is a valid index
otherwise returns a plane of zeros.
"""
if (z<=self.zs):
return self.data[:,:,z]
else:
return np.zeros((self.data[:,:,0].shape))
def getXslice(self, x, xstep, ystep):
"""A generator for a series of data cubes along a y-z plane at location x
Allows iteration along a y-z plane where at each interation a data cube
of shape (2*xstep+1, 2*ystep+1, zsize) is returned. Cubes around the edge
of the test signal volume are padded with the edge value.
Args:
x: the x value of the required y-z plane
xstep: number of traces either side of the current location to include
ystep: number of traces either side of the current location to indlude
Returns:
A series of data cubes along the specified y-z plane
"""
tmp = np.pad( self.data, ((xstep,xstep),(ystep,ystep),(0,0)), mode='edge')
for y in range(self.ys):
yield tmp[x:x+2*xstep+1,y:y+2*ystep+1,:]
def getYslice(self, y, xstep, ystep):
"""A generator for a series of data cubes along a x-z plane at location y
Allows iteration along a x-z plane where at each interation a data cube
of shape (2*xstep+1, 2*ystep+1, zsize) is returned. Cubes around the edge
of the test signal volume are padded with the edge value.
Args:
y: the y value of the required x-z plane
xstep: number of traces either side of the current location to include
ystep: number of traces either side of the current location to indlude
Returns:
A series of data cubes along the specified x-z plane
"""
tmp = np.pad( self.data, ((xstep,xstep),(ystep,ystep),(0,0)), mode='edge')
for x in range(self.xs):
yield tmp[x:x+2*xstep+1,y:y+2*ystep+1,:]
def getZslice(self, z, xstep, ystep, zstep):
"""A generator for a series of data cubes on an x-y plane at location z
Allows iteration over an x-y plane where at each interation a data cube
of shape (2*xstep+1, 2*ystep+1, 2*zsize+1) is returned. Cubes around the edge
of the test signal volume are padded with the edge value.The iteration
proceeds along the xSlice direction.
Args:
z: the z value of the required x-y plane
xstep: number of traces either side of the current location to include
ystep: number of traces either side of the current location to indlude
zstep: number of traces either side of the current location to indlude
Returns:
A series of data cubes on the specified x-y plane
"""
tmp = np.pad( self.data, ((xstep,xstep),(ystep,ystep),(zstep,zstep)), mode='edge')
for x in range(self.xs):
for y in range(self.ys):
yield tmp[x:x+2*xstep+1,y:y+2*ystep+1,z:z+2*zstep+1]
| #
# Python Test Signal Library
#
# Copyright (C) 2018 <NAME> All rights reserved.
#
# This file may be used under the terms of the MIT License
#
# Author: <NAME>
# Date: March, 2018
#
import numpy as np
import scipy.signal as sig
def make_random_signal(nsamp):
"""Make a single trace with random reflectivity
A random reflectivity trace is convolved with a zero phase ricker wavelet
Args:
nsamp: the number of samples in the output trace
Returns:
A 1D array with the signal
"""
ref = np.random.rand(nsamp)*2-1
wav = sig.ricker(80,5)
filtered = np.convolve(ref, wav,'same')
return filtered
def make_delayed_signal_pair(nsamp, delay):
"""Make a pair of identical traces with specified delay
A random reflectivity trace is convolved with a zero phase ricker wavelet
and the created trace and a delayed version are returned
Args:
nsamp: the number of samples in the output trace
delay: the number of samples to delay the second trace
Returns:
Two 1D arrays with the undelayed and delayed signal
"""
ref = np.random.rand(nsamp+abs(delay))*2-1
wav = sig.ricker(80,5)
filtered = np.convolve(ref, wav,'same')
if delay < 0 :
return filtered[0:nsamp], filtered[-delay:nsamp-delay]
else:
return filtered[delay:nsamp+delay], filtered[0:nsamp]
class SphericalSignal(object):
"""Make a 3D spherical test signal
Provides a 3D sinusoidal, hemisperical test signal and its spatial derivatives
Args:
factor: a parameter controlling the frequency content of the signal.
Default is 5000.
xsize: the size of the 3D signal in the 1st dimension. Default is 301.
ysize: the size of the 3D signal in the 2nd dimension. Default is 301.
zsize: the size of the 3D signal in the last dimension. Default is 301.
deriv: what derivative of the test signal to create. Default is None.
"""
def __init__(self,factor=5000, xsize=301, ysize=301, zsize=301, deriv=None):
self.xs = xsize
self.ys = ysize
self.zs = zsize
self.factor = factor
f0=.01
k=.001
xtmp = np.linspace(-xsize,xsize,xsize)
ytmp = np.linspace(-ysize,ysize,ysize)
ztmp = np.linspace(-2*zsize,0,zsize)
self.x,self.y,self.z = np.meshgrid(xtmp,ytmp,ztmp, indexing='ij')
t = (self.x**2+self.y**2+self.z**2)/factor
if deriv == 'dx':
self.data = 2/factor * self.x * np.cos(t)
elif deriv == 'dy':
self.data = 2/factor * self.y * np.cos(t)
elif deriv == 'dz':
self.data = 2/factor * self.z * np.cos(t)
elif deriv == 'dxx':
self.data = 2/factor * np.cos(t) - 4/(factor*factor) * np.square(self.x) * np.sin(t)
elif deriv == 'dyy':
self.data = 2/factor * np.cos(t) - 4/(factor*factor) * np.square(self.y) * np.sin(t)
elif deriv == 'dzz':
self.data = 2/factor * np.cos(t) - 4/(factor*factor) * np.square(self.z) * np.sin(t)
elif deriv in ['dxy', 'dyx']:
self.data = -4/(factor*factor) * self.x * self.y * np.sin(t)
elif deriv in ['dxz', 'dzx']:
self.data = -4/(factor*factor) * self.x * self.z * np.sin(t)
elif deriv in ['dyz', 'dzy']:
self.data = -4/(factor*factor) * self.y * self.z * np.sin(t)
else:
self.data = np.sin(t)
def xSlice(self, x):
"""Return an y-z plane at location x
Args:
x: the x value of the required y-z plane
Returns:
A 2D array with the y-z plane if x is a valid index
otherwise returns a plane of zeros.
"""
if (x<=self.xs):
return np.transpose(self.data[x,:,:])
else:
return np.zeros((self.data[0,:,:].shape))
def ySlice(self, y):
"""Return an x-z plane at location y
Args:
y: the y value of the required x-z plane
Returns:
A 2D array with the x-z plane if y is a valid index
otherwise returns a plane of zeros.
"""
if (y<=self.ys):
return np.transpose(self.data[:,y,:])
else:
return np.zeros((self.data[:,0,:].shape))
def zSlice(self, z):
"""Return an x- plane at location z
Args:
z: the z value of the required x-y plane
Returns:
A 2D array with the x-y plane if z is a valid index
otherwise returns a plane of zeros.
"""
if (z<=self.zs):
return self.data[:,:,z]
else:
return np.zeros((self.data[:,:,0].shape))
def getXslice(self, x, xstep, ystep):
"""A generator for a series of data cubes along a y-z plane at location x
Allows iteration along a y-z plane where at each interation a data cube
of shape (2*xstep+1, 2*ystep+1, zsize) is returned. Cubes around the edge
of the test signal volume are padded with the edge value.
Args:
x: the x value of the required y-z plane
xstep: number of traces either side of the current location to include
ystep: number of traces either side of the current location to indlude
Returns:
A series of data cubes along the specified y-z plane
"""
tmp = np.pad( self.data, ((xstep,xstep),(ystep,ystep),(0,0)), mode='edge')
for y in range(self.ys):
yield tmp[x:x+2*xstep+1,y:y+2*ystep+1,:]
def getYslice(self, y, xstep, ystep):
"""A generator for a series of data cubes along a x-z plane at location y
Allows iteration along a x-z plane where at each interation a data cube
of shape (2*xstep+1, 2*ystep+1, zsize) is returned. Cubes around the edge
of the test signal volume are padded with the edge value.
Args:
y: the y value of the required x-z plane
xstep: number of traces either side of the current location to include
ystep: number of traces either side of the current location to indlude
Returns:
A series of data cubes along the specified x-z plane
"""
tmp = np.pad( self.data, ((xstep,xstep),(ystep,ystep),(0,0)), mode='edge')
for x in range(self.xs):
yield tmp[x:x+2*xstep+1,y:y+2*ystep+1,:]
def getZslice(self, z, xstep, ystep, zstep):
"""A generator for a series of data cubes on an x-y plane at location z
Allows iteration over an x-y plane where at each interation a data cube
of shape (2*xstep+1, 2*ystep+1, 2*zsize+1) is returned. Cubes around the edge
of the test signal volume are padded with the edge value.The iteration
proceeds along the xSlice direction.
Args:
z: the z value of the required x-y plane
xstep: number of traces either side of the current location to include
ystep: number of traces either side of the current location to indlude
zstep: number of traces either side of the current location to indlude
Returns:
A series of data cubes on the specified x-y plane
"""
tmp = np.pad( self.data, ((xstep,xstep),(ystep,ystep),(zstep,zstep)), mode='edge')
for x in range(self.xs):
for y in range(self.ys):
yield tmp[x:x+2*xstep+1,y:y+2*ystep+1,z:z+2*zstep+1]
| en | 0.838556 | # # Python Test Signal Library # # Copyright (C) 2018 <NAME> All rights reserved. # # This file may be used under the terms of the MIT License # # Author: <NAME> # Date: March, 2018 # Make a single trace with random reflectivity A random reflectivity trace is convolved with a zero phase ricker wavelet Args: nsamp: the number of samples in the output trace Returns: A 1D array with the signal Make a pair of identical traces with specified delay A random reflectivity trace is convolved with a zero phase ricker wavelet and the created trace and a delayed version are returned Args: nsamp: the number of samples in the output trace delay: the number of samples to delay the second trace Returns: Two 1D arrays with the undelayed and delayed signal Make a 3D spherical test signal Provides a 3D sinusoidal, hemisperical test signal and its spatial derivatives Args: factor: a parameter controlling the frequency content of the signal. Default is 5000. xsize: the size of the 3D signal in the 1st dimension. Default is 301. ysize: the size of the 3D signal in the 2nd dimension. Default is 301. zsize: the size of the 3D signal in the last dimension. Default is 301. deriv: what derivative of the test signal to create. Default is None. Return an y-z plane at location x Args: x: the x value of the required y-z plane Returns: A 2D array with the y-z plane if x is a valid index otherwise returns a plane of zeros. Return an x-z plane at location y Args: y: the y value of the required x-z plane Returns: A 2D array with the x-z plane if y is a valid index otherwise returns a plane of zeros. Return an x- plane at location z Args: z: the z value of the required x-y plane Returns: A 2D array with the x-y plane if z is a valid index otherwise returns a plane of zeros. A generator for a series of data cubes along a y-z plane at location x Allows iteration along a y-z plane where at each interation a data cube of shape (2*xstep+1, 2*ystep+1, zsize) is returned. Cubes around the edge of the test signal volume are padded with the edge value. Args: x: the x value of the required y-z plane xstep: number of traces either side of the current location to include ystep: number of traces either side of the current location to indlude Returns: A series of data cubes along the specified y-z plane A generator for a series of data cubes along a x-z plane at location y Allows iteration along a x-z plane where at each interation a data cube of shape (2*xstep+1, 2*ystep+1, zsize) is returned. Cubes around the edge of the test signal volume are padded with the edge value. Args: y: the y value of the required x-z plane xstep: number of traces either side of the current location to include ystep: number of traces either side of the current location to indlude Returns: A series of data cubes along the specified x-z plane A generator for a series of data cubes on an x-y plane at location z Allows iteration over an x-y plane where at each interation a data cube of shape (2*xstep+1, 2*ystep+1, 2*zsize+1) is returned. Cubes around the edge of the test signal volume are padded with the edge value.The iteration proceeds along the xSlice direction. Args: z: the z value of the required x-y plane xstep: number of traces either side of the current location to include ystep: number of traces either side of the current location to indlude zstep: number of traces either side of the current location to indlude Returns: A series of data cubes on the specified x-y plane | 2.984926 | 3 |
index.py | the-dean7/python001 | 1 | 6623147 | num=1
num=2
num=30
num=4
num=5
| num=1
num=2
num=30
num=4
num=5
| none | 1 | 1.518163 | 2 | |
bimmer_connected/vehicle/vehicle_status.py | m1n3rva/bimmer_connected | 39 | 6623148 | """Models the state of a vehicle."""
import datetime
import logging
from typing import TYPE_CHECKING, Dict, List, Optional
from bimmer_connected.utils import deprecated
from bimmer_connected.vehicle.models import GPSPosition, ValueWithUnit
if TYPE_CHECKING:
from bimmer_connected.vehicle import MyBMWVehicle
from bimmer_connected.vehicle.doors_windows import Lid, LockState, Window
from bimmer_connected.vehicle.fuel_and_battery import ChargingState
from bimmer_connected.vehicle.reports import CheckControlMessage, ConditionBasedService
_LOGGER = logging.getLogger(__name__)
class VehicleStatus: # pylint: disable=too-many-public-methods
"""Models the status of a vehicle."""
# pylint: disable=unused-argument
def __init__(self, vehicle: "MyBMWVehicle", status_dict: Dict = None):
"""Constructor."""
self.vehicle = vehicle
@property # type: ignore[misc]
@deprecated("vehicle.timestamp")
def timestamp(self) -> Optional[datetime.datetime]:
# pylint:disable=missing-function-docstring
return self.vehicle.timestamp
@property # type: ignore[misc]
@deprecated("vehicle.vehicle_location.location")
def gps_position(self) -> GPSPosition:
# pylint:disable=missing-function-docstring
return self.vehicle.vehicle_location.location
@property # type: ignore[misc]
@deprecated("vehicle.vehicle_location.heading")
def gps_heading(self) -> Optional[int]:
# pylint:disable=missing-function-docstring
return self.vehicle.vehicle_location.heading
@property # type: ignore[misc]
@deprecated("vehicle.is_vehicle_active")
def is_vehicle_active(self) -> bool:
# pylint:disable=missing-function-docstring
return self.vehicle.is_vehicle_active
@property # type: ignore[misc]
@deprecated("vehicle.mileage")
def mileage(self) -> ValueWithUnit:
# pylint:disable=missing-function-docstring
return self.vehicle.mileage
@property # type: ignore[misc]
@deprecated("vehicle.fuel_and_battery.remaining_range_fuel")
def remaining_range_fuel(self) -> Optional[ValueWithUnit]:
# pylint:disable=missing-function-docstring
return self.vehicle.fuel_and_battery.remaining_range_fuel
@property # type: ignore[misc]
@deprecated("vehicle.fuel_and_battery.remaining_fuel")
def remaining_fuel(self) -> Optional[ValueWithUnit]:
# pylint:disable=missing-function-docstring
return self.vehicle.fuel_and_battery.remaining_fuel
@property # type: ignore[misc]
@deprecated("vehicle.fuel_indicator_count")
def fuel_indicator_count(self) -> Optional[int]:
# pylint:disable=missing-function-docstring
return self.vehicle.fuel_indicator_count
@property # type: ignore[misc]
@deprecated("vehicle.doors_and_windows.lids")
def lids(self) -> List["Lid"]:
# pylint:disable=missing-function-docstring
return self.vehicle.doors_and_windows.lids
@property # type: ignore[misc]
@deprecated("vehicle.doors_and_windows.open_lids")
def open_lids(self) -> List["Lid"]:
# pylint:disable=missing-function-docstring
return self.vehicle.doors_and_windows.open_lids
@property # type: ignore[misc]
@deprecated("vehicle.doors_and_windows.all_lids_closed")
def all_lids_closed(self) -> bool:
# pylint:disable=missing-function-docstring
return self.vehicle.doors_and_windows.all_lids_closed
@property # type: ignore[misc]
@deprecated("vehicle.doors_and_windows.windows")
def windows(self) -> List["Window"]:
# pylint:disable=missing-function-docstring
return self.vehicle.doors_and_windows.windows
@property # type: ignore[misc]
@deprecated("vehicle.doors_and_windows.open_windows")
def open_windows(self) -> List["Window"]:
# pylint:disable=missing-function-docstring
return self.vehicle.doors_and_windows.open_windows
@property # type: ignore[misc]
@deprecated("vehicle.doors_and_windows.all_lids_closed")
def all_windows_closed(self) -> bool:
# pylint:disable=missing-function-docstring
return self.vehicle.doors_and_windows.all_lids_closed
@property # type: ignore[misc]
@deprecated("vehicle.doors_and_windows.door_lock_state")
def door_lock_state(self) -> "LockState":
# pylint:disable=missing-function-docstring
return self.vehicle.doors_and_windows.door_lock_state
@property # type: ignore[misc]
@deprecated("vehicle.last_update_reason")
def last_update_reason(self) -> str:
# pylint:disable=missing-function-docstring
return self.vehicle.last_update_reason
@property # type: ignore[misc]
@deprecated()
def last_charging_end_result(self) -> None:
# pylint:disable=missing-function-docstring
return None # Not available in My BMW
@property # type: ignore[misc]
@deprecated("vehicle.fuel_and_battery.is_charger_connected")
def connection_status(self) -> str:
# pylint:disable=missing-function-docstring
return "CONNECTED" if self.vehicle.fuel_and_battery.is_charger_connected else "DISCONNECTED"
@property # type: ignore[misc]
@deprecated("vehicle.condition_based_services.messages")
def condition_based_services(self) -> List["ConditionBasedService"]:
# pylint:disable=missing-function-docstring
return self.vehicle.condition_based_services.messages
@property # type: ignore[misc]
@deprecated("vehicle.condition_based_services.is_service_required")
def are_all_cbs_ok(self) -> bool:
# pylint:disable=missing-function-docstring
return not self.vehicle.condition_based_services.is_service_required
@property # type: ignore[misc]
@deprecated()
def parking_lights(self) -> None:
# pylint:disable=missing-function-docstring
return None # Not available in My BMW
@property # type: ignore[misc]
@deprecated()
def has_parking_light_state(self) -> bool:
# pylint:disable=missing-function-docstring
return False # Not available in My BMW
@property # type: ignore[misc]
@deprecated()
def are_parking_lights_on(self) -> None:
# pylint:disable=missing-function-docstring
return None # Not available in My BMW
@property # type: ignore[misc]
@deprecated("vehicle.fuel_and_battery.remaining_range_electric")
def remaining_range_electric(self) -> Optional[ValueWithUnit]:
# pylint:disable=missing-function-docstring
return self.vehicle.fuel_and_battery.remaining_range_electric
@property # type: ignore[misc]
@deprecated("vehicle.fuel_and_battery.remaining_range_total")
def remaining_range_total(self) -> Optional[ValueWithUnit]:
# pylint:disable=missing-function-docstring
return self.vehicle.fuel_and_battery.remaining_range_total
@property # type: ignore[misc]
@deprecated()
def max_range_electric(self) -> Optional[int]:
# pylint:disable=missing-function-docstring
return None # Not available in My BMW
@property # type: ignore[misc]
@deprecated("vehicle.fuel_and_battery.charging_status")
def charging_status(self) -> Optional["ChargingState"]:
# pylint:disable=missing-function-docstring
return self.vehicle.fuel_and_battery.charging_status
@property # type: ignore[misc]
@deprecated()
def charging_time_remaining(self) -> None:
# pylint:disable=missing-function-docstring
return None
@property # type: ignore[misc]
@deprecated("vehicle.fuel_and_battery.charging_start_time")
def charging_start_time(self) -> Optional[datetime.datetime]:
# pylint:disable=missing-function-docstring
return self.vehicle.fuel_and_battery.charging_start_time
@property # type: ignore[misc]
@deprecated("vehicle.fuel_and_battery.charging_end_time")
def charging_end_time(self) -> Optional[datetime.datetime]:
# pylint:disable=missing-function-docstring
return self.vehicle.fuel_and_battery.charging_end_time
@property # type: ignore[misc]
@deprecated("vehicle.fuel_and_battery.charging_time_label")
def charging_time_label(self) -> Optional[str]:
# pylint:disable=missing-function-docstring
return self.vehicle.fuel_and_battery.charging_time_label
@property # type: ignore[misc]
@deprecated("vehicle.fuel_and_battery.remaining_battery_percent")
def charging_level_hv(self) -> Optional[int]:
# pylint:disable=missing-function-docstring
return self.vehicle.fuel_and_battery.remaining_battery_percent
@property # type: ignore[misc]
@deprecated("vehicle.fuel_and_battery.remaining_fuel_percent")
def fuel_percent(self) -> Optional[int]:
# pylint:disable=missing-function-docstring
return self.vehicle.fuel_and_battery.remaining_fuel_percent
@property # type: ignore[misc]
@deprecated("vehicle.check_control_messages.messages")
def check_control_messages(self) -> List["CheckControlMessage"]:
# pylint:disable=missing-function-docstring
return self.vehicle.check_control_messages.messages
@property # type: ignore[misc]
@deprecated("vehicle.check_control_messages.has_check_control_messages")
def has_check_control_messages(self) -> bool:
# pylint:disable=missing-function-docstring
return self.vehicle.check_control_messages.has_check_control_messages
| """Models the state of a vehicle."""
import datetime
import logging
from typing import TYPE_CHECKING, Dict, List, Optional
from bimmer_connected.utils import deprecated
from bimmer_connected.vehicle.models import GPSPosition, ValueWithUnit
if TYPE_CHECKING:
from bimmer_connected.vehicle import MyBMWVehicle
from bimmer_connected.vehicle.doors_windows import Lid, LockState, Window
from bimmer_connected.vehicle.fuel_and_battery import ChargingState
from bimmer_connected.vehicle.reports import CheckControlMessage, ConditionBasedService
_LOGGER = logging.getLogger(__name__)
class VehicleStatus: # pylint: disable=too-many-public-methods
"""Models the status of a vehicle."""
# pylint: disable=unused-argument
def __init__(self, vehicle: "MyBMWVehicle", status_dict: Dict = None):
"""Constructor."""
self.vehicle = vehicle
@property # type: ignore[misc]
@deprecated("vehicle.timestamp")
def timestamp(self) -> Optional[datetime.datetime]:
# pylint:disable=missing-function-docstring
return self.vehicle.timestamp
@property # type: ignore[misc]
@deprecated("vehicle.vehicle_location.location")
def gps_position(self) -> GPSPosition:
# pylint:disable=missing-function-docstring
return self.vehicle.vehicle_location.location
@property # type: ignore[misc]
@deprecated("vehicle.vehicle_location.heading")
def gps_heading(self) -> Optional[int]:
# pylint:disable=missing-function-docstring
return self.vehicle.vehicle_location.heading
@property # type: ignore[misc]
@deprecated("vehicle.is_vehicle_active")
def is_vehicle_active(self) -> bool:
# pylint:disable=missing-function-docstring
return self.vehicle.is_vehicle_active
@property # type: ignore[misc]
@deprecated("vehicle.mileage")
def mileage(self) -> ValueWithUnit:
# pylint:disable=missing-function-docstring
return self.vehicle.mileage
@property # type: ignore[misc]
@deprecated("vehicle.fuel_and_battery.remaining_range_fuel")
def remaining_range_fuel(self) -> Optional[ValueWithUnit]:
# pylint:disable=missing-function-docstring
return self.vehicle.fuel_and_battery.remaining_range_fuel
@property # type: ignore[misc]
@deprecated("vehicle.fuel_and_battery.remaining_fuel")
def remaining_fuel(self) -> Optional[ValueWithUnit]:
# pylint:disable=missing-function-docstring
return self.vehicle.fuel_and_battery.remaining_fuel
@property # type: ignore[misc]
@deprecated("vehicle.fuel_indicator_count")
def fuel_indicator_count(self) -> Optional[int]:
# pylint:disable=missing-function-docstring
return self.vehicle.fuel_indicator_count
@property # type: ignore[misc]
@deprecated("vehicle.doors_and_windows.lids")
def lids(self) -> List["Lid"]:
# pylint:disable=missing-function-docstring
return self.vehicle.doors_and_windows.lids
@property # type: ignore[misc]
@deprecated("vehicle.doors_and_windows.open_lids")
def open_lids(self) -> List["Lid"]:
# pylint:disable=missing-function-docstring
return self.vehicle.doors_and_windows.open_lids
@property # type: ignore[misc]
@deprecated("vehicle.doors_and_windows.all_lids_closed")
def all_lids_closed(self) -> bool:
# pylint:disable=missing-function-docstring
return self.vehicle.doors_and_windows.all_lids_closed
@property # type: ignore[misc]
@deprecated("vehicle.doors_and_windows.windows")
def windows(self) -> List["Window"]:
# pylint:disable=missing-function-docstring
return self.vehicle.doors_and_windows.windows
@property # type: ignore[misc]
@deprecated("vehicle.doors_and_windows.open_windows")
def open_windows(self) -> List["Window"]:
# pylint:disable=missing-function-docstring
return self.vehicle.doors_and_windows.open_windows
@property # type: ignore[misc]
@deprecated("vehicle.doors_and_windows.all_lids_closed")
def all_windows_closed(self) -> bool:
# pylint:disable=missing-function-docstring
return self.vehicle.doors_and_windows.all_lids_closed
@property # type: ignore[misc]
@deprecated("vehicle.doors_and_windows.door_lock_state")
def door_lock_state(self) -> "LockState":
# pylint:disable=missing-function-docstring
return self.vehicle.doors_and_windows.door_lock_state
@property # type: ignore[misc]
@deprecated("vehicle.last_update_reason")
def last_update_reason(self) -> str:
# pylint:disable=missing-function-docstring
return self.vehicle.last_update_reason
@property # type: ignore[misc]
@deprecated()
def last_charging_end_result(self) -> None:
# pylint:disable=missing-function-docstring
return None # Not available in My BMW
@property # type: ignore[misc]
@deprecated("vehicle.fuel_and_battery.is_charger_connected")
def connection_status(self) -> str:
# pylint:disable=missing-function-docstring
return "CONNECTED" if self.vehicle.fuel_and_battery.is_charger_connected else "DISCONNECTED"
@property # type: ignore[misc]
@deprecated("vehicle.condition_based_services.messages")
def condition_based_services(self) -> List["ConditionBasedService"]:
# pylint:disable=missing-function-docstring
return self.vehicle.condition_based_services.messages
@property # type: ignore[misc]
@deprecated("vehicle.condition_based_services.is_service_required")
def are_all_cbs_ok(self) -> bool:
# pylint:disable=missing-function-docstring
return not self.vehicle.condition_based_services.is_service_required
@property # type: ignore[misc]
@deprecated()
def parking_lights(self) -> None:
# pylint:disable=missing-function-docstring
return None # Not available in My BMW
@property # type: ignore[misc]
@deprecated()
def has_parking_light_state(self) -> bool:
# pylint:disable=missing-function-docstring
return False # Not available in My BMW
@property # type: ignore[misc]
@deprecated()
def are_parking_lights_on(self) -> None:
# pylint:disable=missing-function-docstring
return None # Not available in My BMW
@property # type: ignore[misc]
@deprecated("vehicle.fuel_and_battery.remaining_range_electric")
def remaining_range_electric(self) -> Optional[ValueWithUnit]:
# pylint:disable=missing-function-docstring
return self.vehicle.fuel_and_battery.remaining_range_electric
@property # type: ignore[misc]
@deprecated("vehicle.fuel_and_battery.remaining_range_total")
def remaining_range_total(self) -> Optional[ValueWithUnit]:
# pylint:disable=missing-function-docstring
return self.vehicle.fuel_and_battery.remaining_range_total
@property # type: ignore[misc]
@deprecated()
def max_range_electric(self) -> Optional[int]:
# pylint:disable=missing-function-docstring
return None # Not available in My BMW
@property # type: ignore[misc]
@deprecated("vehicle.fuel_and_battery.charging_status")
def charging_status(self) -> Optional["ChargingState"]:
# pylint:disable=missing-function-docstring
return self.vehicle.fuel_and_battery.charging_status
@property # type: ignore[misc]
@deprecated()
def charging_time_remaining(self) -> None:
# pylint:disable=missing-function-docstring
return None
@property # type: ignore[misc]
@deprecated("vehicle.fuel_and_battery.charging_start_time")
def charging_start_time(self) -> Optional[datetime.datetime]:
# pylint:disable=missing-function-docstring
return self.vehicle.fuel_and_battery.charging_start_time
@property # type: ignore[misc]
@deprecated("vehicle.fuel_and_battery.charging_end_time")
def charging_end_time(self) -> Optional[datetime.datetime]:
# pylint:disable=missing-function-docstring
return self.vehicle.fuel_and_battery.charging_end_time
@property # type: ignore[misc]
@deprecated("vehicle.fuel_and_battery.charging_time_label")
def charging_time_label(self) -> Optional[str]:
# pylint:disable=missing-function-docstring
return self.vehicle.fuel_and_battery.charging_time_label
@property # type: ignore[misc]
@deprecated("vehicle.fuel_and_battery.remaining_battery_percent")
def charging_level_hv(self) -> Optional[int]:
# pylint:disable=missing-function-docstring
return self.vehicle.fuel_and_battery.remaining_battery_percent
@property # type: ignore[misc]
@deprecated("vehicle.fuel_and_battery.remaining_fuel_percent")
def fuel_percent(self) -> Optional[int]:
# pylint:disable=missing-function-docstring
return self.vehicle.fuel_and_battery.remaining_fuel_percent
@property # type: ignore[misc]
@deprecated("vehicle.check_control_messages.messages")
def check_control_messages(self) -> List["CheckControlMessage"]:
# pylint:disable=missing-function-docstring
return self.vehicle.check_control_messages.messages
@property # type: ignore[misc]
@deprecated("vehicle.check_control_messages.has_check_control_messages")
def has_check_control_messages(self) -> bool:
# pylint:disable=missing-function-docstring
return self.vehicle.check_control_messages.has_check_control_messages
| en | 0.467024 | Models the state of a vehicle. # pylint: disable=too-many-public-methods Models the status of a vehicle. # pylint: disable=unused-argument Constructor. # type: ignore[misc] # pylint:disable=missing-function-docstring # type: ignore[misc] # pylint:disable=missing-function-docstring # type: ignore[misc] # pylint:disable=missing-function-docstring # type: ignore[misc] # pylint:disable=missing-function-docstring # type: ignore[misc] # pylint:disable=missing-function-docstring # type: ignore[misc] # pylint:disable=missing-function-docstring # type: ignore[misc] # pylint:disable=missing-function-docstring # type: ignore[misc] # pylint:disable=missing-function-docstring # type: ignore[misc] # pylint:disable=missing-function-docstring # type: ignore[misc] # pylint:disable=missing-function-docstring # type: ignore[misc] # pylint:disable=missing-function-docstring # type: ignore[misc] # pylint:disable=missing-function-docstring # type: ignore[misc] # pylint:disable=missing-function-docstring # type: ignore[misc] # pylint:disable=missing-function-docstring # type: ignore[misc] # pylint:disable=missing-function-docstring # type: ignore[misc] # pylint:disable=missing-function-docstring # type: ignore[misc] # pylint:disable=missing-function-docstring # Not available in My BMW # type: ignore[misc] # pylint:disable=missing-function-docstring # type: ignore[misc] # pylint:disable=missing-function-docstring # type: ignore[misc] # pylint:disable=missing-function-docstring # type: ignore[misc] # pylint:disable=missing-function-docstring # Not available in My BMW # type: ignore[misc] # pylint:disable=missing-function-docstring # Not available in My BMW # type: ignore[misc] # pylint:disable=missing-function-docstring # Not available in My BMW # type: ignore[misc] # pylint:disable=missing-function-docstring # type: ignore[misc] # pylint:disable=missing-function-docstring # type: ignore[misc] # pylint:disable=missing-function-docstring # Not available in My BMW # type: ignore[misc] # pylint:disable=missing-function-docstring # type: ignore[misc] # pylint:disable=missing-function-docstring # type: ignore[misc] # pylint:disable=missing-function-docstring # type: ignore[misc] # pylint:disable=missing-function-docstring # type: ignore[misc] # pylint:disable=missing-function-docstring # type: ignore[misc] # pylint:disable=missing-function-docstring # type: ignore[misc] # pylint:disable=missing-function-docstring # type: ignore[misc] # pylint:disable=missing-function-docstring # type: ignore[misc] # pylint:disable=missing-function-docstring | 2.493999 | 2 |
ckanext/spatial/nongeos_plugin.py | geosolutions-it/ckanext-spatial-cerco | 1 | 6623149 | <reponame>geosolutions-it/ckanext-spatial-cerco<filename>ckanext/spatial/nongeos_plugin.py<gh_stars>1-10
import os
from logging import getLogger
from pylons.i18n import _
from genshi.input import HTML
from genshi.filters import Transformer
import ckan.lib.helpers as h
from ckan.lib.helpers import json
from ckan.plugins import implements, SingletonPlugin
from ckan.plugins import IRoutes, IConfigurer
from ckan.plugins import IGenshiStreamFilter
import html
log = getLogger(__name__)
class WMSPreview(SingletonPlugin):
implements(IGenshiStreamFilter)
implements(IRoutes, inherit=True)
implements(IConfigurer, inherit=True)
def filter(self, stream):
from pylons import request, tmpl_context as c
routes = request.environ.get('pylons.routes_dict')
if routes.get('controller') == 'package' and \
routes.get('action') == 'read' and c.pkg.id:
for res in c.pkg.resources:
if res.format == "WMS":
data = {'name': c.pkg.name}
stream = stream | Transformer('body//div[@class="resources subsection"]')\
.append(HTML(html.MAP_VIEW % data))
break
return stream
def before_map(self, map):
map.redirect('/package/{id}/map','/dataset/{id}/map')
map.connect('map_view', '/dataset/:id/map',
controller='ckanext.spatial.controllers.view:ViewController',
action='wms_preview')
map.connect('proxy', '/proxy',
controller='ckanext.spatial.controllers.view:ViewController',
action='proxy')
return map
def update_config(self, config):
here = os.path.dirname(__file__)
template_dir = os.path.join(here, 'templates')
public_dir = os.path.join(here, 'public')
if config.get('extra_template_paths'):
config['extra_template_paths'] += ','+template_dir
else:
config['extra_template_paths'] = template_dir
if config.get('extra_public_paths'):
config['extra_public_paths'] += ','+public_dir
else:
config['extra_public_paths'] = public_dir
| import os
from logging import getLogger
from pylons.i18n import _
from genshi.input import HTML
from genshi.filters import Transformer
import ckan.lib.helpers as h
from ckan.lib.helpers import json
from ckan.plugins import implements, SingletonPlugin
from ckan.plugins import IRoutes, IConfigurer
from ckan.plugins import IGenshiStreamFilter
import html
log = getLogger(__name__)
class WMSPreview(SingletonPlugin):
implements(IGenshiStreamFilter)
implements(IRoutes, inherit=True)
implements(IConfigurer, inherit=True)
def filter(self, stream):
from pylons import request, tmpl_context as c
routes = request.environ.get('pylons.routes_dict')
if routes.get('controller') == 'package' and \
routes.get('action') == 'read' and c.pkg.id:
for res in c.pkg.resources:
if res.format == "WMS":
data = {'name': c.pkg.name}
stream = stream | Transformer('body//div[@class="resources subsection"]')\
.append(HTML(html.MAP_VIEW % data))
break
return stream
def before_map(self, map):
map.redirect('/package/{id}/map','/dataset/{id}/map')
map.connect('map_view', '/dataset/:id/map',
controller='ckanext.spatial.controllers.view:ViewController',
action='wms_preview')
map.connect('proxy', '/proxy',
controller='ckanext.spatial.controllers.view:ViewController',
action='proxy')
return map
def update_config(self, config):
here = os.path.dirname(__file__)
template_dir = os.path.join(here, 'templates')
public_dir = os.path.join(here, 'public')
if config.get('extra_template_paths'):
config['extra_template_paths'] += ','+template_dir
else:
config['extra_template_paths'] = template_dir
if config.get('extra_public_paths'):
config['extra_public_paths'] += ','+public_dir
else:
config['extra_public_paths'] = public_dir | none | 1 | 1.85811 | 2 | |
tests/tools/add_regression_case.py | regardscitoyens/senapy | 6 | 6623150 | <gh_stars>1-10
import sys
import os
import requests
if len(sys.argv) != 3:
print('usage: python add_regression_case.py <dosleg_url> <new_regression_directory>')
sys.exit()
url = sys.argv[1]
output_directory = sys.argv[2]
if not os.path.exists(output_directory):
os.makedirs(output_directory)
with open(os.path.join(output_directory, 'input.html'), 'w') as f:
f.write(requests.get(url).text + '<!-- URL_SENAT=%s -->' % url)
with open(os.path.join(output_directory, 'anpy.json'), 'w') as f:
f.write('')
print('now you can run regen_regressions_output.py to generate the output of reference')
| import sys
import os
import requests
if len(sys.argv) != 3:
print('usage: python add_regression_case.py <dosleg_url> <new_regression_directory>')
sys.exit()
url = sys.argv[1]
output_directory = sys.argv[2]
if not os.path.exists(output_directory):
os.makedirs(output_directory)
with open(os.path.join(output_directory, 'input.html'), 'w') as f:
f.write(requests.get(url).text + '<!-- URL_SENAT=%s -->' % url)
with open(os.path.join(output_directory, 'anpy.json'), 'w') as f:
f.write('')
print('now you can run regen_regressions_output.py to generate the output of reference') | none | 1 | 2.746503 | 3 |