text stringlengths 38 1.54M |
|---|
import asyncio
from server.integrations import openexchangerates
from server.models.repository import Currency
async def start_refresh_rates_routine():
asyncio.create_task(_refresh_rates_routine())
async def _refresh_rates_routine(delay=False):
if delay:
await asyncio.sleep(60 * 60 * 24)
asyncio.create_task(_refresh_rates_routine(delay=True))
await refresh_rates()
async def refresh_rates():
currencies = await openexchangerates.decimals()
for currency_name, currency_rate in currencies.items():
cur = await Currency.query.where(Currency.exchange_code == currency_name).gino.first()
if cur:
await cur.update(rate=currency_rate).apply()
else:
await Currency.create(exchange_code=currency_name, rate=currency_rate)
|
#!/usr/bin/python
# _*_ coding:utf-8 _*_
__author__ = "dqz"
#引用函数getpass 实现密码输入的隐藏
import getpass
name = input("输入用户名:")
password = input("输入密码:")
no = 0
while True:
if name == 'tom' and password =='123':
print("登入成功")
break
else:
no += 1
print("登入失败%s次" %no)
name = input("用户输入错误,重新输入:")
password = input("密码输入错误,重新输入:")
if no == 2:
print("登入失败")
break |
class Solution:
def compressString(self, S: str) -> str:
compressed = []
n = len(S)
if n <= 1:
return S
count = 0
for i in range(n):
count += 1
if i + 1 >= n or S[i] != S[i + 1]:
compressed.append(S[i])
compressed.append(str(count))
count = 0
return "".join(compressed) if len(compressed) < n else S
|
__author__ = 'vikram'
import sys
import os
from os import listdir
from os.path import isfile, join
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
import matplotlib.lines as mlines
import argparse
plt.close("all")
parser = argparse.ArgumentParser(description="V vs C viz script to visualize rslt channel")
parser.add_argument('-v', '--Vfile', help='RTL result file name', required=True, type=str)
parser.add_argument('-c', '--Cfile', help='C result file name', required=True, type=str)
args = parser.parse_args()
'''Vfile = '/home/vikram/FG/algLogs/fgAlgTrkrDscWithGocEn.log'
Cfile = '/home/vikram/FG/algLogs/jITech3AhDscRsltRnd.log'
'''
def parseV(nibble, posn):
tempList = []
binaryList = []
with open(args.Vfile, mode='rt') as f:
f.readline()
for line in f:
tempList.append(line.split()[11])
for n in range(0, len(tempList)):
val = "{0:04b}".format(int(tempList[n][nibble], 16))
binaryList.append(val[posn])
return binaryList
def parseC(flagCol):
CbinList = []
with open(args.Cfile, mode='rt') as cf:
cf.readline()
for line in cf:
CbinList.append(line.split()[flagCol])
for n in range(len(CbinList)):
if CbinList[n] == 'false':
CbinList[n] = 0
else:
CbinList[n] = 1
return CbinList
def doPlot(figNum, listToPlot, label):
plt.figure(figNum)
plt.plot(listToPlot)
plt.ylabel(label)
def do2Plot(figNum, vArray, vLabel, cArray, cLabel):
"""
:rtype : no return value.
"""
plt.figure(figNum)
ax1 = plt.subplot(211)
ax1.plot(vArray)
plt.ylabel(vLabel)
ax2 = plt.subplot(212, sharex=ax1, sharey=ax1)
ax2.plot(cArray)
plt.ylabel(cLabel)
plt.xlabel("FG cycle")
bSocDeltaBin = parseV(7, 2)
CbSocDelta = parseC(20) #for 2.0
'''doPlot(1, bSocDeltaBin, "VbSocDelta")
doPlot(2, CbSocDelta, "CbSocDelta")'''
do2Plot(1, bSocDeltaBin, "VbSocDelta", CbSocDelta, "CbSocDelta")
'''-------------'''
mSocDeltaBin = parseV(7, 1)
CmSocDelta = parseC(21) #for 2.0
'''doPlot(3, mSocDeltaBin, "VmSocDelta")
doPlot(4, CmSocDelta, "CmSocDelta")'''
do2Plot(2, mSocDeltaBin, "VmSocDelta", CmSocDelta, "CmSocDelta")
'''-------------'''
mSocLowBin = parseV(7, 0)
CmSocLow = parseC(17)
'''doPlot(5, mSocLowBin, "mSocLow")
doPlot(6, CmSocLow, "CmSocLow")'''
do2Plot(3, mSocLowBin, "mSocLowBin", CmSocLow, "CmSocLow")
'''-------------'''
mSocEmptyBin = parseV(6, 3)
CmSocEmpty = parseC(16)
'''doPlot(7, mSocEmptyBin, "mSocEmpty")
doPlot(8, CmSocEmpty, "CmSocEmpty")'''
do2Plot(4, mSocEmptyBin,"mSocEmptyBin", CmSocEmpty, "CmSocEmpty")
plt.show()
|
from numpy import *
a = array(eval(input()))
d = ''
c = size(a)
b = 0
for j in a:
for i in a:
if j > i:
d = i
i = j
j = d
print(a) |
print(" Welcome to ABC shop ")
print("-----Please login-----")
username = input("username : ")
password = input("password : ")
u1 = "123456"
p1 = "987654"
if username == u1 and p1 == password:
print("Login complete")
print(" >>> Please select menu <<< ")
print("1.Fired rice = 35 Bth")
print("2.Fired chicken = 50 Bth")
print("3.Noodle soup = 45 Bth")
print("4.Papaya salad = 30 Bth")
print("5.Fired egg = 5 Bth")
food = input("Please fill number or food name : ")
if food == "1" or food == "Fired rice":
print(">>> Fired rice: 35 bth")
q1 = int(input("Order quantity: "))
tt1 = q1*30
print("Price is ", tt1, " Bth")
elif food == "2" or food == "Fired chicken":
print(">>> Fired chicken: 50 bth")
q2 = int(input("Order quantity: "))
tt2 = q2*50
print("Price is ", tt2, " Bth")
elif food == "3" or food == "Noodle soup":
print(">>> Noodle soup: 45 bth")
q3 = int(input("Order quantity: "))
tt3 = q3*45
print("Price is ", tt3, " Bth")
elif food == "4" or food == "Papaya salad":
print(">>> Papaya salad: 30 bth")
q4 = int(input("Order quantity: "))
tt4 = q4*30
print("Price is ", tt4, " Bth")
elif food == "5" or food == "Fired egg":
print(">>> Fired egg: 5 bth")
q5 = int(input("Order quantity: "))
tt5 = q5*5
print("Price is ", tt5, " Bth")
else:
print("Login incomplete ;( ")
|
#! /usr/bin/python
# coding = utf-8
print
import urllib2
import re
page = 1
url = 'http://news.baidu.com/?qq-pf-to=pcqq.group/page/' + str(page)
user_agent = "Mozi;;a/4.0 (compatible; MSIE 5.5; Windows NT)"
headers = { 'User-Agent' : user_agent}
try:
request = urllib2.Request(url, headers = headers)
response = urllib2.urlopen(request)
content = response.read()
#print content
# pattern = re.compile('<div class="author clearfix">.*?<img src.*?title=.*?<h2>(.*?)</h2>.*?<span>(.*?)</span>.*?<span class="stats-vote"><i class="number">(.*?)</i>.*?<i class="number">(.*?)</i>',re.S)
# pattern= re.compile('<ul class="ulist focuslistnews">.*?<li class="bold-item">(.*?)</a>',re.S)
pattern= re.compile('(<div id="channel-all" class="channel-all clearfix" >.*)<div id="body" alog-alias="b">',re.S)
items = re.search(pattern, content)
print items.group(1)
#for item in items:
# print item[0], item[1], item[2], '\n'
except urllib2.URLError, e:
if hasattr(e, "code"):
print e.code
if hasattr(e, "reason"):
print e.reason |
import unittest
class tree:
def __init__(self, root):
self.root = root
class tree_node:
def __init__(self, data, left, right):
self.data = data
self.left = left
self.right = right
#preorder, postorder and inorder prints
def print_tree(tr):
if tr.root is None:
return
if tr.root.left is not None:
print_tree(tree(tr.root.left))
print(tr.root.data)
print_tree(tree(tr.root.right))
def breadth_first_print(tr):
if tr.root is None:
return
print(tr.root.data)
breadth_first_print(tree(tr.root.left))
breadth_first_print(tree(tr.root.right))
def num_levels(tr):
if tr.root is None:
return 0
else:
return 1 + max(num_levels(tree(tr.root.left)), num_levels(tree(tr.root.right)))
def inorder_print(tr):
#traverse left subtree, then root, then right subtree
if tr.root is None:
return
inorder_print(tree(tr.root.left))
print(tr.root.data)
inorder_print(tree(tr.root.right))
def preorder_print(tr):
#traverse root, then left subtree, then right subtree
if tr.root is None:
return
print(tr.root.data)
preorder_print(tree(tr.root.left))
preorder_print(tree(tr.root.right))
def postorder_print(tr):
#traverse left subtree, then right subtree, then root
if tr.root is None:
return
postorder_print(tree(tr.root.left))
postorder_print(tree(tr.root.right))
print(tr.root.data)
class UnitTests(unittest.TestCase):
def test_print(self):
left_child = tree_node(6, None, None)
right_child = tree_node(3, None, None)
left = tree_node(7, None, None)
right = tree_node(17, left_child, right_child)
root = tree_node(1, left, right)
my_tree = tree(root)
print("left first starting")
print_tree(my_tree)
def test_breadth_print(self):
left_child = tree_node(6, None, None)
right_child = tree_node(3, None, None)
left = tree_node(7, None, None)
right = tree_node(17, left_child, right_child)
root = tree_node(1, left, right)
my_tree = tree(root)
print("breadth first starting")
breadth_first_print(my_tree)
def test_num_levels(self):
left_child = tree_node(6, None, None)
right_child = tree_node(3, None, None)
left = tree_node(7, None, None)
right = tree_node(17, left_child, right_child)
root = tree_node(1, left, right)
my_tree = tree(root)
second_tree = tree(right)
self.assertEqual(num_levels(my_tree),3)
self.assertEqual(num_levels(second_tree),2)
def test_preorder_print(self):
two = tree_node(2, None, None)
six_left = tree_node(5, None, None)
six_right = tree_node(11, None, None)
six = tree_node(6, six_left, six_right)
left = tree_node(7, two, six)
four = tree_node(4, None, None)
nine = tree_node(9, four, None)
right = tree_node(5, None, nine)
root = tree_node(2, left, right)
test_tree = tree(root)
print("preorder starting, should be 2 7 2 6 5 11 5 9 4")
preorder_print(test_tree)
def test_postorder_print(self):
two = tree_node(2, None, None)
six_left = tree_node(5, None, None)
six_right = tree_node(11, None, None)
six = tree_node(6, six_left, six_right)
left = tree_node(7, two, six)
four = tree_node(4, None, None)
nine = tree_node(9, four, None)
right = tree_node(5, None, nine)
root = tree_node(2, left, right)
test_tree = tree(root)
print("postorder starting, should be 2 5 11 6 7 4 9 5 2")
postorder_print(test_tree)
def test_inorder_print(self):
two = tree_node(2, None, None)
six_left = tree_node(5, None, None)
six_right = tree_node(11, None, None)
six = tree_node(6, six_left, six_right)
left = tree_node(7, two, six)
four = tree_node(4, None, None)
nine = tree_node(9, four, None)
right = tree_node(5, None, nine)
root = tree_node(2, left, right)
test_tree = tree(root)
print("inorder starting, should be 2 7 5 6 11 2 5 4 9")
inorder_print(test_tree)
if __name__ == '__main__':
unittest.main()
#Ex 1-3:
#TIMING (without retyping tree class and example case)
#print: 11 min
#breadth_first_print = 9 min
#levels = 6 min
# reflection: was able to use a lot of recursion which was super helpful! I was not sure whether we were supposed to use the tree class given in the spec or not, but it was how I would have implemented it as well, so I just studied and retyped it.
#extra practice: preorder, postorder and inorder prints (with test cases written first)
#example tree from: https://www.google.com/url?sa=i&url=https%3A%2F%2Ftech.paayi.com%2Fpython-tree-data-structures&psig=AOvVaw0F6fGCiTTjtPLLNFFLUzXX&ust=1623184834967000&source=images&cd=vfe&ved=0CA0QjhxqFwoTCICyzvGwhvECFQAAAAAdAAAAABAI
#TIMING: writing tests: 8 min, writing code: 13 min
|
#!/usr/bin/python env
# -*- coding: utf-8 -*-
import logging
import os
import re
import time
from Queue import Queue
import xlwt
from keystoneauth1 import loading, session
from novaclient import client
from xlrd import open_workbook
DEFAULT_TIMEOUT = 10 * 60
WAITING_QUEUE_MAX_SIZE = 10
LOGGER = None
MAX_COLUMNS = 2
COLUME_NAME = ["name", "tag"]
DEST = 'dest'
LIVE_MIGRATIBLE_STATES = ['active', 'puased']
MIGRATIBLE_STATES = ['active', 'shutoff']
ERROR_STATE = ['error']
TRANSITIONAL_STATE = 'migrating'
COMPLETED_STATES = MIGRATIBLE_STATES + LIVE_MIGRATIBLE_STATES
def setup_logging(debug=False):
logging_format = "%(asctime)s - %(name)10s.%(lineno)4s - %(levelname)5s - %(message)s"
level = logging.DEBUG if debug else logging.INFO
logging.basicConfig(level=level, format=logging_format)
def get_logger():
global LOGGER
if not LOGGER:
LOGGER = logging.getLogger(__name__)
return LOGGER
class Server(object):
available = "active"
def __init__(self, server_id, name, host, tag, vcpu=0, ram=0, service=None, az=None):
# this id will not be used if
# search name returns a list with more than 1 element
self.id = server_id
self.name = name
self.host = host
self.vcpus = vcpu
self.ram = ram
self.tag = tag
if service:
self.service = service.strip()
elif tag:
self.service = tag.strip()
else:
self.service = ''
self.az = az if az else "cn-north-3a"
self.aggregate = "%s_%s_%s" % (self.az, self.service.lower(), "general")
def __repr__(self):
return self.__str__()
def __str__(self):
return "%s_%s_%s_%s" % (self.id, self.aggregate, self.host, self.tag)
def tag_vm(self, nova_client):
"""
tag vm
:param nova_client:
:return:
"""
logger = get_logger()
server = nova_client.servers.get(self)
# quit if not tag provided
if not self.tag:
return
# tag this vm
tag_list = [i for i in nova_client.servers.tag_list(server)]
if self.tag not in tag_list:
logger.info('create tag %s for vm %s (%s)', self.tag, self.name, server.id)
nova_client.servers.add_tag(server, self.tag)
else:
logger.info('vm: %s(%s) already has tag: %s', self.name, server.id, self.tag)
def could_migrate(self, server):
if server.status.lower() in MIGRATIBLE_STATES:
return True
else:
return False
def could_live_migrate(self, server):
if server.status.lower() in LIVE_MIGRATIBLE_STATES:
return True
else:
return False
def migrate(self, nova_client):
server = nova_client.servers.get(self)
logger = get_logger()
if self.could_live_migrate(server):
logger.debug("live migrate server %s", server)
self.live_migrate(nova_client, False)
elif self.could_migrate(server):
logger.debug("cold migrate server %s", server)
self.cold_migrate(nova_client)
else:
logger.info("server %s is not in active/stopped state, cannot live migrate it", self.id)
raise ServerErrorStateException('server in non migrable state')
def cold_migrate(self, nova_client):
server = nova_client.servers.get(self)
try:
nova_client.servers.migrate(server)
tic = time.time()
while time.time() - tic < DEFAULT_TIMEOUT:
server = nova_client.servers.get(self)
if server.status == 'resize_confirm':
server.confirm_resize()
time.sleep(10)
else:
raise ColdMigrationFailedException('cold migration of %s timeout' % server)
except Exception:
raise ColdMigrationFailedException('cold migration of %s failed' % server)
def live_migrate(self, nova_client, block=False):
dest = getattr(self, DEST)
server = nova_client.servers.get(self)
logger = get_logger()
if not self.could_live_migrate(server):
logger.info("server %s is not in active/stopped state, cannot live migrate it", self.id)
raise ServerErrorStateException('server in non migrable state')
nova_client.servers.live_migrate(server, dest, False, True)
if block:
tic = time.time()
while True:
toc = time.time()
if toc - tic > DEFAULT_TIMEOUT:
raise ServerLiveMigrationTimeoutException('live migration timeout')
server = nova_client.servers.get(server)
logger.debug('server %s is %s', server.id, server.status)
if is_active(server):
return True
if is_error(server):
raise ServerErrorException("server is in error status")
time.sleep(30)
def get_status(self, nova_client):
return nova_client.servers.get(self).status
@classmethod
def create(cls, nova_client, name, tag):
logger = get_logger()
# fixme vm name duplication?
# instead it uses database style (mysql...)
servers = nova_client.servers.list(detailed=False, search_opts={"name": name, "all_tenants": True})
if len(servers) == 0:
# this trick utilizes the fact only id attribute is required for this get method
a = Server(name, None, None, None)
servers = [nova_client.servers.get(a)]
if len(servers) == 0:
# this method might be redundant, nova may support regex natively?
logger.info('searching through all existing vms, this could be heavy')
all_servers = get_all_servers(nova_client, name)
for one in all_servers:
if re.match(name, one.name):
servers.append(one)
ret = []
for server in servers:
detailed_server = nova_client.servers.get(server)
host = getattr(detailed_server, 'OS-EXT-SRV-ATTR:host')
vcpus = detailed_server.flavor['vcpus']
ram = detailed_server.flavor['ram']
ret.append(Server(server.id, server.name, host, tag, vcpus, ram))
return ret
def should_move(self):
dest = getattr(self, DEST, None)
if not dest:
return False
else:
return dest != self.host
class ServerErrorException(Exception):
def __init__(self, *args, **kwargs):
super(ServerErrorException, self).__init__(*args, **kwargs)
self.name = 'server error'
class ServerLiveMigrationTimeoutException(Exception):
def __init__(self, *args, **kwargs):
super(ServerLiveMigrationTimeoutException, self).__init__(*args, **kwargs)
self.name = 'live migration timeout'
class ServerErrorStateException(Exception):
def __init__(self, *args, **kwargs):
super(ServerErrorStateException, self).__init__(*args, **kwargs)
self.name = "server in mismatch state"
class ColdMigrationFailedException(Exception):
def __init__(self, *args, **kwargs):
super(ColdMigrationFailedException, self).__init__(*args, **kwargs)
self.name = 'cold migration failed exception'
def is_error(server):
status = getattr(server, "status")
if not status:
return True
else:
return status.lower() == 'error'
def is_active(server):
status = getattr(server, 'status')
if status:
return status.lower() == "active"
else:
return False
class Host(object):
def __init__(self, host_id, name, vcpus, ram, **kwargs):
self.id = host_id
self.name = name
self.vcpus = vcpus
self.ram = ram
self.hypervisor_type = kwargs.get('hypervisor_type', "QEMU")
def take_cpu(self, cpu):
self.vcpus -= cpu
def take_ram(self, ram):
self.ram -= ram
def assign_server(self, server):
self.take_cpu(server.vcpu)
self.take_ram(server.ram)
def __str__(self):
return "%s_%s_%s" % (self.name, self.vcpus, self.ram)
def __repr__(self):
return self.__str__()
def __lt__(self, other):
# __lt__ return true if self < other
# be careful: bool(-1) will give True
if self.vcpus == other.vcpus:
return self.ram < other.ram
else:
return self.vcpus < other.vcpus
def __eq__(self, other):
return self.name == other.name
class Aggregate(object):
def __init__(self, name, hosts=list()):
self.name = name
self.hosts = hosts
def add_host(self, host):
self.hosts.append(host)
def assemble_aggregates(nova_client):
"""
construct a aggregates map
:param nova_client:
:return:
"""
hosts = {i.service['host']: Host(i.id, i.service['host'], i.vcpus - i.vcpus_used, i.free_ram_mb)
for i in nova_client.hypervisors.list()}
aggregates = {i.name: Aggregate(i.name, [hosts.get(j) for j in i.hosts])
for i in nova_client.aggregates.list()}
return aggregates
def update_host(host, vm):
host.vcpus -= vm.vcpus
host.ram -= vm.ram
def schedule_vms(aggregates, vms):
"""
schedule vms
:param aggregates:
:param vms:
:return: vms
"""
logger = get_logger()
for vm in vms:
current_host = vm.host
correct_aggregate = vm.aggregate
if correct_aggregate not in aggregates.keys():
logger.warning("server %s does not have a correct aggregate configured", vm)
continue
# move vm if it's on a wrong host
if current_host not in [i.name for i in aggregates[correct_aggregate].hosts]:
# compute dest and assign to vm
hosts = aggregates[correct_aggregate].hosts
indices = sorted(range(len(hosts)), key=lambda j: hosts[j])
index = indices[-1]
logger.info("%s will be moved from %s to %s", vm.id, current_host, hosts[index])
setattr(vm, DEST, hosts[index].name)
logger.debug("updating host %s", hosts[index])
update_host(hosts[index], vm)
logger.debug("host %s updated", hosts[index])
# TODO should update current host as well?
return vms
def read_config(nova_client, config_path):
# fixme remove duplicate record and log
if not os.path.exists(config_path):
raise Exception("path: %s does not exist!", config_path)
logger = get_logger()
servers = []
logger.info("read configuration from %s", config_path)
wb = open_workbook(config_path)
# by default, there is only a single sheet
sheet = wb.sheets()[0]
# ignore the first row
for row in range(1, sheet.nrows):
args = {
"nova_client": nova_client
}
for col in range(sheet.ncols):
# there should not be more than defined
# number of columns
if col >= MAX_COLUMNS:
break
# value should not have letters like 'G'
val = sheet.cell(row, col).value
args[COLUME_NAME[col]] = val
logger.info("args: %s", str(args))
try:
servers.extend(Server.create(**args))
except Exception:
logger.exception("get server error..")
# it is hard to know where to find it in excel
names = {}
for i in range(len(servers)):
if not names.get(servers[i].id):
names[servers[i].id] = [i]
else:
names[servers[i].id].append(i)
dumplicated_index = []
dumplicated_names = []
for name in names.keys():
if len(names[name]) > 1:
dumplicated_index.extend(names[name])
dumplicated_names.append(name)
dumplicated_index = sorted(dumplicated_index, reverse=True)
# make sure traverse index from greater value to lesser
for i in dumplicated_index:
servers.pop(i)
return servers, dumplicated_names
def tag_and_move_vm(nova_client, vms, preview=False):
"""
add tag to virtual machines
:param nova_client:
:param vms:
:param preview
:return:
"""
ret = {
"success": [],
"error": [],
"ignored": [],
"preview": []
}
waiting_list = Queue()
server_queue = Queue()
for vm in vms:
server_queue.put(vm)
logger = get_logger()
while not server_queue.empty():
logger.debug('retrive server from queue')
vm = server_queue.get()
try:
# tag vm ignoring preview value
logger.info('start dealing with %s', vm.name)
vm.tag_vm(nova_client)
if vm.should_move():
logger.info('move mv: %s from %s to %s', vm, vm.host, getattr(vm, DEST))
if not preview:
try:
# stopped vm couold be resized?
vm.migrate(nova_client)
vm.start_time = time.time()
waiting_list.put(vm)
except ServerErrorStateException:
logger.exception("vm %s is in wrong state", vm.id)
ret['error'].append(vm)
except ServerLiveMigrationTimeoutException:
logger.exception("waiting for %s finish time out", vm.id)
ret['error'].append(vm)
except ServerErrorException:
logger.exception("server %s is error state", vm.id)
ret['error'].append(vm)
except Exception:
logger.exception("server %s migration failed", vm.id)
ret['error'].append(vm)
else:
ret['preview'].append(vm)
logger.debug("in preview mode, instance will not be actually moved")
else:
ret['ignored'].append(vm)
except Exception:
logger.exception("add tag to vm: %s failed", str(vm))
ret['error'].append(vm)
while waiting_list.qsize() == WAITING_QUEUE_MAX_SIZE:
# block here
vm = waiting_list.get()
status = check_migrating_vm(nova_client, vm)
if not status:
# requeue if not finished
waiting_list.put(vm)
time.sleep(10)
else:
ret.update(status)
# searching through waiting list
logger.info('waiting for live migrating finishes')
while not waiting_list.empty():
vm = waiting_list.get()
status = check_migrating_vm(vm, nova_client)
if not status:
# request if not finished
waiting_list.put(vm)
else:
ret.update(status)
return ret
def check_migrating_vm(nova_client, vm):
"""
check both cold/live migration
this makes things tricker since they share different
:param nova_client:
:param vm:
:return:
"""
ret = {}
logger = get_logger()
tic = getattr(vm, "start_time", time.time())
try:
status = vm.get_status(nova_client)
toc = time.time()
# https://docs.openstack.org/nova/pike/reference/vm-states.html
if status.lower() in COMPLETED_STATES:
ret['success'].append(vm)
elif status.lower() in ERROR_STATE:
ret['error'].append(vm)
elif toc - tic > DEFAULT_TIMEOUT:
ret['error'].append(vm)
else:
return None
except Exception:
logger.exception("server %s migration failed", vm.id)
ret['error'].append(vm)
return ret
def init_nova_client(credentials):
# get logger
logger = get_logger()
# relation between variable name & corresponding environment variable
required_fields = {'auth_url': 'OS_AUTH_URL',
'username': "OS_USERNAME",
'password': 'OS_PASSWORD',
'user_domain_name': "OS_USER_DOMAIN_NAME",
'project_name': "OS_PROJECT_NAME",
'project_domain_name': "OS_PROJECT_DOMAIN_NAME"
}
# check & pop values from environment variable
options = {}
for key in required_fields.keys():
if not credentials.get(key):
value = os.environ[required_fields[key]]
if not value:
raise Exception("%s(%s) is missing" % (key, required_fields[key]))
options.update({key: value})
else:
options.update({key: credentials.get(key)})
logger.info("begin initializing nova client")
loader = loading.get_plugin_loader('v3password')
auth = loader.load_from_options(**options)
sess = session.Session(auth=auth, verify=False)
endpoint_type = get(credentials, 'endpoin_type', os.environ['OS_ENDPOINT_TYPE'], 'public')
region_name = get(credentials, 'region_name', os.environ['OS_REGION_NAME'], 'RegionOne')
nova_client = client.Client('2.53', session=sess, endpoint_type=endpoint_type, region_name=region_name)
logger.info("initialzing nova client completed successfully")
# return a glance client
return nova_client
def get(obj, name, *args):
"""
extend get(obj, name, default=None) method
:param obj:
:param name:
:param args:
:return:
"""
if getattr(obj, name, None):
return get(obj, name)
try:
if isinstance(obj, dict) and obj[name]:
return obj[name]
except Exception:
pass
for i in args:
if i:
return i
def get_all_servers(nova_client, name=None, detailed=False, use_all=True):
all_servers = []
opts = {
"all_tenants": use_all,
}
if name:
opts.update({"name": name})
last = None
while True:
servers = nova_client.servers.list(detailed=detailed, search_opts=opts,
marker=last.id if last else None)
if len(servers) == 0:
break
all_servers.extend(servers)
last = all_servers[-1]
return all_servers
def write_vm_to_sheet(vms, sheet):
attrs = ['name', 'id', 'service', 'host', DEST]
for i in range(len(attrs)):
sheet.write(0, i, attrs[i])
for i in range(len(vms)):
for j in range(len(attrs)):
sheet.write(i + 1, j, getattr(vms[i], attrs[j], ''))
def write_to_excel(result, file_name):
workbook = xlwt.Workbook()
for key in result.keys():
sheet = workbook.add_sheet(key)
write_vm_to_sheet(result[key], sheet)
workbook.save(file_name)
def get_parser():
import argparse
parser = argparse.ArgumentParser(description='generate required flavors')
parser.add_argument('-f', '--config', dest='config_path', required=True,
help='path to the configuration file')
parser.add_argument('-d', '--debug', dest='debug', action='store_const', const=True,
default=False, help='enable debugging')
parser.add_argument('--no-preview', dest='preview', action='store_const', const=False,
default=True, help='preview changes')
parser.add_argument('-o', '--output', dest='output',
default='output.xls', help='display result in excel (xls)')
return parser.parse_args()
def main():
parser = get_parser()
setup_logging(parser.debug)
nova_client = init_nova_client({})
logger = get_logger()
servers, dup = read_config(nova_client, parser.config_path)
logger.info('%s', servers)
if len(dup) > 0:
logger.warning("These names %s are duplicated.", dup)
logger.info('assemble aggreates objects')
# aggreates construct relationship between HA -> hosts
# every HA could have multiple overlapping hosts associated
aggregates = assemble_aggregates(nova_client)
logger.info("schedule servers to proper hosts")
# assign a host to each servers retrieved from excel
servers = schedule_vms(aggregates, servers)
logger.info('migrate servers')
ret = tag_and_move_vm(nova_client, servers, parser.preview)
logger.info('result is %s', ret)
write_to_excel(ret, parser.output)
if __name__ == "__main__":
exit(main())
|
#/bin/python
import numpy as np
import random;
class Grid_Mdp_Id:
def __init__(self, initial_state = None):
self.states = [1,2,3,4,5,6,7,8]
self.terminal_states = dict()
self.terminal_states[6] = 1
self.terminal_states[7] = 1
self.terminal_states[8] = 1
self.current_state = 1
if None == initial_state:
self.current = int(random.random() * 5) + 1;
else:
if initial_state in self.terminal_states:
raise Exception("initial_state(%d) is a terminal state"%\
(initial_state));
self.current = initial_state;
#feature of states
self.feas = dict();
self.feas[1] = np.array([1,0,0,0,0,0,0,0]);
self.feas[2] = np.array([0,1,0,0,0,0,0,0]);
self.feas[3] = np.array([0,0,1,0,0,0,0,0]);
self.feas[4] = np.array([0,0,0,1,0,0,0,0]);
self.feas[5] = np.array([0,0,0,0,1,0,0,0]);
self.feas[6] = np.array([0,0,0,0,0,1,0,0]);
self.feas[7] = np.array([0,0,0,0,0,0,1,0]);
self.feas[8] = np.array([0,0,0,0,0,0,0,1]);
self.actions = ['n','e','s','w']
self.rewards = dict();
self.rewards['1_s'] = -1.0
self.rewards['3_s'] = 1.0
self.rewards['5_s'] = -1.0
self.t = dict();
self.t['1_s'] = 6
self.t['1_e'] = 2
self.t['2_w'] = 1
self.t['2_e'] = 3
self.t['3_s'] = 7
self.t['3_w'] = 2
self.t['3_e'] = 4
self.t['4_w'] = 3
self.t['4_e'] = 5
self.t['5_s'] = 8
self.t['5_w'] = 4
self.gamma = 0.8
def getGamma(self):
return self.gamma;
def getActions(self):
return self.actions
def start(self, initial_state = None):
self.current_state = 1
if None == initial_state:
self.current = int(random.random() * 5) + 1;
else:
if initial_state in self.terminal_states:
raise Exception("initial_state(%d) is a terminal state"%\
(initial_state));
self.current = initial_state;
return self.feas[self.current]
def receive(self, action): ##return is_terminal,state, reward
state = self.current;
if state in self.terminal_states:
return True, self.feas[state], 0
key = '%d_%s'%(state, action);
if key in self.t:
self.current = self.t[key];
else:
self.current = state;
is_terminal = False
if self.current in self.terminal_states:
is_terminal = True
if key not in self.rewards:
r = 0.0
else:
r = self.rewards[key];
return is_terminal, self.feas[self.current], r;
class Grid_Mdp:
def __init__(self, initial_state = None):
self.states = [1,2,3,4,5,6,7,8]
self.terminal_states = dict()
self.terminal_states[6] = 1
self.terminal_states[7] = 1
self.terminal_states[8] = 1
self.current_state = 1
if None == initial_state:
self.current = int(random.random() * 5) + 1;
else:
if initial_state in self.terminal_states:
raise Exception("initial_state(%d) is a terminal state"%\
(initial_state));
self.current = initial_state;
#feature of states
self.feas = dict();
self.feas[1] = np.array([1,0,0,1]);
self.feas[2] = np.array([1,0,1,0]);
self.feas[3] = np.array([1,0,0,0]);
self.feas[4] = np.array([1,0,1,0]);
self.feas[5] = np.array([1,1,0,0]);
self.feas[6] = np.array([0,1,1,1]);
self.feas[7] = np.array([0,1,1,1]);
self.feas[8] = np.array([0,1,1,1]);
self.actions = ['n','e','s','w']
self.rewards = dict();
self.rewards['1_s'] = -1.0
self.rewards['3_s'] = 1.0
self.rewards['5_s'] = -1.0
self.t = dict();
self.t['1_s'] = 6
self.t['1_e'] = 2
self.t['2_w'] = 1
self.t['2_e'] = 3
self.t['3_s'] = 7
self.t['3_w'] = 2
self.t['3_e'] = 4
self.t['4_w'] = 3
self.t['4_e'] = 5
self.t['5_s'] = 8
self.t['5_w'] = 4
self.gamma = 0.8
def getGamma(self):
return self.gamma;
def getActions(self):
return self.actions
def start(self, initial_state = None):
self.current_state = 1
if None == initial_state:
self.current = int(random.random() * 5) + 1;
else:
if initial_state in self.terminal_states:
raise Exception("initial_state(%d) is a terminal state"%\
(initial_state));
self.current = initial_state;
return self.feas[self.current]
def receive(self, action): ##return is_terminal,state, reward
state = self.current;
if state in self.terminal_states:
return True, self.feas[state], 0
key = '%d_%s'%(state, action);
if key in self.t:
self.current = self.t[key];
else:
self.current = state;
is_terminal = False
if self.current in self.terminal_states:
is_terminal = True
if key not in self.rewards:
r = 0.0
else:
r = self.rewards[key];
return is_terminal, self.feas[self.current], r;
|
from __future__ import absolute_import
# Version 4.0
import logging as logger
import copy
import splunk.clilib.cli_common as comm
from splunk.clilib.control_exceptions import ArgError
import splunk.clilib._internal as _internal
import splunk.clilib.info_gather as info_gather
import splunk.clilib.apps as apps
import splunk.clilib.bundle as bundle
import splunk.clilib.bundle_paths as bundle_paths
import splunk.clilib.deploy as deploy
import splunk.clilib.exports as exports
import splunk.clilib.index as index
import splunk.clilib.migration as migration
import splunk.clilib.module as module
import splunk.clilib.manage_search as ms
import splunk.clilib.clilib_tst_artifact as test
import splunk.clilib.train as train
import splunk.clilib.i18n as i18n
def newFunc(func):
def wrapperFunc(args, fromCLI = False):
if not isinstance(args, dict):
raise ArgError("Parameter 'args' should be a dict (was %s)." % type(args))
dictCopy = copy.deepcopy(args)
return func(dictCopy, fromCLI)
return wrapperFunc
#### ----- MANAGE_SEARCH -----
getUIVersion = newFunc(ms.getUIVersion)
setUIVersion = newFunc(ms.setUIVersion)
get_servername = newFunc(ms.getInstanceName)
setServerName = newFunc(ms.setInstanceName)
### ----- TEST -----
testDates = newFunc(test.testDates)
testFields = newFunc(test.testFields)
testStypes = newFunc(test.testSourcetypes)
### ----- TRAIN -----
trainDates = newFunc(train.trainDates)
trainFields = newFunc(train.trainFields)
### ----- INDEXES -----
get_defIndex = newFunc(index.getDef)
set_defIndex = newFunc(index.setDef)
### ----- DEPLOYMENT CLIENT SETTINGS -----
deplClient_disable = newFunc(module.deplClientDisable)
deplClient_enable = newFunc(module.deplClientEnable)
deplClient_status = newFunc(module.deplClientStatus)
deplClient_edit = newFunc(deploy.editClient)
get_depPoll = newFunc(deploy.getPoll)
set_depPoll = newFunc(deploy.setPoll)
### ----- BUNDLE MANAGEMENT -----
bundle_migrate = newFunc(bundle_paths.migrate_bundles)
### ----- DIRECT CONFIG INTERACTION -----
showConfig = newFunc(bundle.showConfig)
### ----- EXPORTING DATA ----- # the rest of export & import should be here too.. TODO
export_eventdata = newFunc(exports.exEvents)
### ----- INTERNAL SETTINGS -----
def set_uri(uri, fromCLI = False):
comm.setURI(uri)
### ----- MIGRATION -----
mig_winSavedSearch = newFunc(migration.migWinSavedSearches)
### ----- SOME LOCAL FILESYSTEM FUNCTIONS -----
local_moduleStatus = newFunc(module.localModuleStatus)
local_moduleEnable = newFunc(module.localModuleEnable)
local_moduleDisable = newFunc(module.localModuleDisable)
local_appStatus = newFunc(apps.localAppStatus)
local_appEnable = newFunc(apps.localAppEnable)
local_appDisable = newFunc(apps.localAppDisable)
### ----- I18N -----
i18n_extract = newFunc(i18n.i18n_extract)
### ----- OTHER INTERNALISH STUFF -----
checkXmlFiles = newFunc(_internal.checkXmlFiles)
firstTimeRun = newFunc(_internal.firstTimeRun)
preFlightChecks = newFunc(_internal.preFlightChecks)
diagnose = newFunc(info_gather.pclMain)
|
import numpy as np
import matplotlib
# matplotlib.use("TkAgg")
import matplotlib.pyplot as plt
# matplotlib.use("qt5agg")
from typing import *
import pandas as pd
import seaborn as sns
import math
sns.set()
class Accuracy(object):
def at_radii(self, radii: np.ndarray):
raise NotImplementedError()
class ApproximateAccuracy(Accuracy):
def __init__(self, data_file_path: str):
self.data_file_path = data_file_path
def at_radii(self, radii: np.ndarray) -> np.ndarray:
df = pd.read_csv(self.data_file_path, delimiter="\t")
return np.array([self.at_radius(df, radius) for radius in radii])
def at_radius(self, df: pd.DataFrame, radius: float):
return (df["correct"] & (df["radius"] >= radius)).mean()
class ApproximateAccuracy_transfer(Accuracy):
def __init__(self, data_file_path: str):
self.data_file_path = data_file_path
def at_radii(self, radii: np.ndarray) -> np.ndarray:
df = pd.read_csv(self.data_file_path, delimiter="\t")
return np.array([self.at_radius(df, radius*np.sqrt(3*32*32)) for radius in radii])
def at_radius(self, df: pd.DataFrame, radius: float):
return (df["correct"] & (df["radius"] >= radius)).mean()
class HighProbAccuracy(Accuracy):
def __init__(self, data_file_path: str, alpha: float, rho: float):
self.data_file_path = data_file_path
self.alpha = alpha
self.rho = rho
def at_radii(self, radii: np.ndarray) -> np.ndarray:
df = pd.read_csv(self.data_file_path, delimiter="\t")
return np.array([self.at_radius(df, radius) for radius in radii])
def at_radius(self, df: pd.DataFrame, radius: float):
mean = (df["correct"] & (df["radius"] >= radius)).mean()
num_examples = len(df)
return (mean - self.alpha - math.sqrt(self.alpha * (1 - self.alpha) * math.log(1 / self.rho) / num_examples)
- math.log(1 / self.rho) / (3 * num_examples))
class Line(object):
def __init__(self, quantity: Accuracy, legend: str, plot_fmt: str = "", scale_x: float = 1):
self.quantity = quantity
self.legend = legend
self.plot_fmt = plot_fmt
self.scale_x = scale_x
def plot_certified_accuracy(outfile: str, title: str, max_radius: float,
lines: List[Line], radius_step: float = 0.01) -> None:
radii = np.arange(0, max_radius + radius_step, radius_step)
plt.figure()
for line in lines:
plt.plot(radii * line.scale_x, line.quantity.at_radii(radii), line.plot_fmt)
plt.ylim((0, 1))
plt.xlim((0, max_radius))
plt.tick_params(labelsize=14)
plt.xlabel("$\ell_\infty$ radius", fontsize=16)
plt.ylabel("certified accuracy", fontsize=16)
plt.legend([method.legend for method in lines], loc='upper right', fontsize=16)
plt.savefig(outfile + ".pdf")
plt.tight_layout()
plt.title(title, fontsize=20)
plt.tight_layout()
plt.savefig(outfile + ".png", dpi=300)
plt.close()
def smallplot_certified_accuracy(outfile: str, title: str, max_radius: float,
methods: List[Line], radius_step: float = 0.01, xticks=0.5) -> None:
radii = np.arange(0, max_radius + radius_step, radius_step)
plt.figure()
for method in methods:
plt.plot(radii, method.quantity.at_radii(radii), method.plot_fmt)
plt.ylim((0, 1))
plt.xlim((0, max_radius))
plt.xlabel("radius", fontsize=22)
plt.ylabel("certified accuracy", fontsize=22)
plt.tick_params(labelsize=20)
plt.gca().xaxis.set_major_locator(plt.MultipleLocator(xticks))
plt.legend([method.legend for method in methods], loc='upper right', fontsize=20)
plt.tight_layout()
plt.savefig(outfile + ".pdf")
plt.close()
def latex_table_certified_accuracy(outfile: str, radius_start: float, radius_stop: float, radius_step: float,
methods: List[Line]):
radii = np.arange(radius_start, radius_stop + radius_step, radius_step)
accuracies = np.zeros((len(methods), len(radii)))
for i, method in enumerate(methods):
accuracies[i, :] = method.quantity.at_radii(radii)
f = open(outfile, 'w')
for radius in radii:
f.write("& $r = {:.3}$".format(radius))
f.write("\\\\\n")
f.write("\midrule\n")
for i, method in enumerate(methods):
f.write(method.legend)
for j, radius in enumerate(radii):
if i == accuracies[:, j].argmax():
txt = r" & \textbf{" + "{:.4f}".format(accuracies[i, j]) + "}"
else:
txt = " & {:.4f}".format(accuracies[i, j])
f.write(txt)
f.write("\\\\\n")
f.close()
def markdown_table_certified_accuracy(outfile: str, radius_start: float, radius_stop: float, radius_step: float,
methods: List[Line]):
radii = np.arange(radius_start, radius_stop + radius_step, radius_step)
accuracies = np.zeros((len(methods), len(radii)))
for i, method in enumerate(methods):
accuracies[i, :] = method.quantity.at_radii(radii)
f = open(outfile, 'w')
f.write("| | ")
for radius in radii:
f.write("r = {:.3} |".format(radius))
f.write("\n")
f.write("| --- | ")
for i in range(len(radii)):
f.write(" --- |")
f.write("\n")
for i, method in enumerate(methods):
f.write("<b> {} </b>| ".format(method.legend))
for j, radius in enumerate(radii):
if i == accuracies[:, j].argmax():
txt = "{:.2f}<b>*</b> |".format(accuracies[i, j])
else:
txt = "{:.2f} |".format(accuracies[i, j])
f.write(txt)
f.write("\n")
f.close()
if __name__ == "__main__":
plot_certified_accuracy(
"./results/vary_dim_cifar10_trades", "CIFAR-10, ResNet110", 0.01, [
Line(ApproximateAccuracy("./results/output_noise12_size32_l2trades0435_beta6"), "Size 32"),
Line(ApproximateAccuracy("./results/output_noise18_size48_l2trades06525_beta6"), "Size 48"),
Line(ApproximateAccuracy("./results/output_noise24_size64_l2trades087_beta6"), "Size 64"),
], radius_step=0.00001) |
import math
n=int(input(int))
m=int(input(int))
o=m*n
root=math.sqrt(o)
if(int(root+0.5)**2==o):
print("yes")
else:
print("no")
|
#!/usr/bin/env python
# vim: set expandtab tabstop=4 shiftwidth=4:
# Copyright (c) 2019, CJ Kucera
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the development team nor the
# names of its contributors may be used to endorse or promote products
# derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL CJ KUCERA BE LIABLE FOR ANY
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import sys
try:
from modprocessor import ModProcessor
mp = ModProcessor()
except ModuleNotFoundError:
print('')
print('********************************************************************')
print('To run this script, you will need to copy or symlink modprocessor.py')
print('from Apocalyptech\'s BL2 mods directory, so it exists here as well.')
print('Sorry for the bother!')
print('********************************************************************')
print('')
sys.exit(1)
try:
from ftexplorer.data import Data
except ModuleNotFoundError:
print('')
print('****************************************************************')
print('To run this script, you will need to copy or symlink the')
print('"ftexplorer" and "resources" dirs from my ft-explorer project so')
print('they exist here as well. Sorry for the bother!')
print('****************************************************************')
print('')
sys.exit(1)
# Control Vars
mod_name = 'TPS Red Text Explainer'
mod_version = '1.0.0'
output_filename = '{}.blcm'.format(mod_name)
explanation_color = '#5ff5ff'
data = Data('TPS')
DESC = 'Description'
NOC = 'NoConstraintText'
valid_attrs = { DESC, NOC }
ON_CARD = 'All effects listed.'
# Item lists
mod_items = [
('ARs', NOC, [
('KerBoom',
'gd_cork_weap_assaultrifle.Name.Title_Torgue.Title_Legendary_KerBoom:AttributePresentationDefinition_8',
'Releases a child grenade on impact.',
),
('Shredifier',
'gd_cork_weap_assaultrifle.Name.Title_Vladof.Title_Legendary_Shredifier:AttributePresentationDefinition_8',
ON_CARD,
),
('Major Tom',
'gd_cork_weap_assaultrifle.Name.Title_Dahl.Title_Legendary_MajorTom:AttributePresentationDefinition_8',
'5-shot burst, 3 bullets at a time for the price of 2.',
),
('Hammer Buster II',
'gd_cork_weap_assaultrifle.Name.Title_Jakobs.Title_Legendary_HammerBreaker:AttributePresentationDefinition_8',
'Penetrating rounds.',
),
('Fusillade',
'GD_Ma_Weapons.Name.Title.Title__Legendary_AR_Bandit_5_Fusillade:AttributePresentationDefinition_8',
ON_CARD,
),
('Wallop',
'gd_cork_weap_assaultrifle.Name.Title_Jakobs.Title_Unique_Wallop:AttributePresentationDefinition_8',
ON_CARD,
),
('Hail',
'gd_cork_weap_assaultrifle.Name.Title.Title_Unique_Hail:AttributePresentationDefinition_8',
'Projectiles fly in arc, split in two after awhile. Player is healed 3% of damage dealt.',
),
('Ice Scream',
'gd_cork_weap_assaultrifle.Name.Title.Title_Unique_IceScream:AttributePresentationDefinition_8',
'No movement loss while aiming down sights.',
),
("Ol' Painful",
'gd_cork_weap_assaultrifle.Name.Title_Vladof.Title_Unique_OldPainful:AttributePresentationDefinition_8',
'Fires laser bolts instead of bullets.',
),
('Boss Nova',
'GD_Cypressure_Weapons.Name.Title.Title__Unique_BossNova:AttributePresentationDefinition_8',
'High projectile speed. On surface hit, projectiles explode in small nova.',
),
('Cry Baby',
'GD_Petunia_Weapons.ManufacturerMaterials.AssaultRifle.Mat_Bandit_3_CryBaby:AttributePresentationDefinition_8',
'If "Wiggly," slow shots will oscillate up and down. Otherwise, just slow bullets.',
)
]),
('Rocket Launchers', NOC, [
('Badaboom',
'GD_Cork_Weap_Launchers.Name.Title_Legendary_Badaboom:AttributePresentationDefinition_8',
'Fires six rockets for the cost of one.',
),
('Cryophobia',
'GD_Cork_Weap_Launchers.Name.Title_Legendary_Cryophobia:AttributePresentationDefinition_8',
'Projectiles explode multiple times mid-flight.',
),
('Nukem',
'GD_Cork_Weap_Launchers.Name.Title_Torgue.Title_Legendary_Nukem:AttributePresentationDefinition_8',
'Rockets fly in arc and explode in mushroom cloud.',
),
('Mongol',
'GD_Cork_Weap_Launchers.Name.Title_Vladof.Title_Legendary_Mongol:AttributePresentationDefinition_8',
'Large main rocket occasionally releases smaller rockets along path. Consumes 2 ammo.',
),
('Thingy',
'GD_Cork_Weap_Launchers.Name.Title_Legendary_Thingy:AttributePresentationDefinition_8',
'On impact, splits into three homing corrosive grenades.',
),
("Kaneda's Laser",
'GD_Ma_Weapons.Name.Title.Title__Legendary_Launcher_Tediore_5_KanedasLaser:AttributePresentationDefinition_8',
'Fires a fast-travelling laser which can score crits.',
),
('Berrigan',
'GD_Petunia_Weapons.Name.Title.Title__Unique_Menace:AttributePresentationDefinition_8',
'Fires six total rockets in three bursts with single trigger pull, consumes only 1 rocket.',
),
('Volt Thrower',
'GD_Cork_Weap_Launchers.Name.Title.Title__Unique_Rocketeer:AttributePresentationDefinition_8',
'Increased rocket speed, decreased explosion radius.',
),
('Creamer',
'GD_Cork_Weap_Launchers.Name.Title__Unique_Creamer:AttributePresentationDefinition_8',
'Rocket splits into two after a set distance. Player is healed 2% of damage.',
),
]),
('Pistols', NOC, [
('Zim',
'GD_Cork_Weap_Pistol.Name.Title_Bandit.Title_Legendary_Zim:AttributePresentationDefinition_8',
ON_CARD,
),
('Shooterang',
'GD_Cork_Weap_Pistol.Name.Title_Tediore.Title_Legendary_Shooterang:AttributePresentationDefinition_8',
'Flies around like a boomerang, bouncing off surfaces and firing continuously.',
),
('Blowfly',
'GD_Cork_Weap_Pistol.Name.Title_Dahl.Title_Legendary_Blowfly:AttributePresentationDefinition_8',
'Projectiles split in two after awhile and orbit each other. Splash on impact. 7-round burst when zoomed.',
),
('88 Fragnum',
'GD_Cork_Weap_Pistol.Name.Title_Torgue.Title_Legendary_88Fragnum:AttributePresentationDefinition_8',
'Fires 5 bullets at once in accelerating spread, at cost of 3 ammo.',
),
('Maggie',
'GD_Cork_Weap_Pistol.Name.Title_Jakobs.Title_Legendary_Maggie:AttributePresentationDefinition_8',
'6 projectiles for the cost of 1.',
),
("Logan's Gun",
'GD_Weap_Pistol.Name.Title_Hyperion.Title_Legendary_LogansGun:AttributePresentationDefinition_8',
'Rounds explode once on contact then continue until they hit a surface, when they explode again.',
),
('Luck Cannon',
'GD_Ma_Weapons.Name.Title.Title__Legendary_Pistol_Jakobs_5_LuckCannon:AttributePresentationDefinition_8',
'Shots have a chance to deal 400% explosive damage.',
),
('Proletarian Revolution',
'GD_Ma_Weapons.Name.Title.Title__Legendary_Pistol_Vladof_5_Expander:AttributePresentationDefinition_8',
'Magazine size increases while the gun is not fired.',
),
("Gwen's Other Head",
'GD_Cork_Weap_Pistol.Name.Title.Title__Unique_GwensOtherHead:AttributePresentationDefinition_8',
'Fires second round at an angle to the left, 6-round burst when zoomed.',
),
('Fibber (remove global red text)',
'GD_Cork_Weap_Pistol.Name.Title_Hyperion.Title__Unique_Fibber:AttributePresentationDefinition_8',
'',
'',
0,
),
('Fibber #1',
'GD_Cork_Weap_Pistol.Barrel.Pistol_Barrel_Bandit_Fibber_1:AttributePresentationDefinition_1',
'Low-velocity shotgun.',
'<font color="#DC4646">Would I lie to you?</font>',
20,
),
('Fibber #2',
'GD_Cork_Weap_Pistol.Barrel.Pistol_Barrel_Bandit_Fibber_2:AttributePresentationDefinition_1',
'Full-speed ricochet on impact or wall hit.',
'<font color="#DC4646">Would I lie to you?</font>',
20,
),
('Fibber #3',
'GD_Cork_Weap_Pistol.Barrel.Pistol_Barrel_Bandit_Fibber_3:AttributePresentationDefinition_1',
'Arcing projectiles with 700% crit bonus.',
'<font color="#DC4646">Would I lie to you?</font>',
20,
),
('Globber',
'GD_Cork_Weap_Pistol.Name.Title.Title__Unique_Globber:AttributePresentationDefinition_8',
'Projectiles travel in low arc and can bounce twice.',
),
('Lady Fist',
'GD_Cork_Weap_Pistol.Name.Title_Hyperion.Title__Unique_LadyFist:AttributePresentationDefinition_8',
ON_CARD,
),
('Smasher',
'GD_Cork_Weap_Pistol.Name.Title_Jakobs.Title_Unique_Smasher:AttributePresentationDefinition_8',
'Fires 7 bullets in horizontal spread, at cost of 3 ammo.',
),
('Cyber Eagle',
'GD_Cork_Weap_Pistol.Name.Title.Title__Unique_CyberColt:AttributePresentationDefinition_8',
'Shoots bolts of electricity.',
),
('Party Popper',
'GD_Ma_Weapons.Name.Title.Title__Unique_Bandit_Pistol_3_PartyPopper:AttributePresentationDefinition_8',
'7 projectiles at cost of 1 ammo, bullets vanish after a very short distance and release confetti.',
),
('Hard Reboot',
'GD_Ma_Weapons.Name.Title.Title__Unique_Maliwan_Pistol_3_HardReboot:AttributePresentationDefinition_8',
'Wide-radius shock effect on impact.',
),
('T4s-R',
'GD_Petunia_Weapons.Name.Title.Title__Unique_T4sr:AttributePresentationDefinition_8',
'Fires lasers instead of bullets.',
),
('Probe',
'GD_Cork_Weap_Pistol.Name.Title.Title__Unique_Moxxis_Probe:AttributePresentationDefinition_8',
'Heals player at 5% of damage dealt.',
),
]),
('Shotguns', NOC, [
("Sledge's Shotty",
'GD_Weap_Shotgun.Name.Title_Bandit.Title_Legendary_Shotgun:AttributePresentationDefinition_8',
'Two-shot burst, +1 projectile count.',
),
('Flakker',
'GD_Cork_Weap_Shotgun.Name.Title_Torgue.Title_Legendary_Flakker:AttributePresentationDefinition_8',
'Extremely large spread, rounds detonate after reaching a certain distance.',
),
('Striker',
'GD_Cork_Weap_Shotgun.Name.Title_Jakobs.Title_Legendary_Striker:AttributePresentationDefinition_8',
'50% additive crit bonus and a 15% multiplicative crit bonus.',
),
('Viral Marketer',
'GD_Cork_Weap_Shotgun.Name.Title_Hyperion.Title_Legendary_ConferenceCall:AttributePresentationDefinition_8',
'Fires 5 projectiles per shot. Each projectile generates additional projectiles upon impact or after sufficient distance.',
),
('Flayer',
'GD_Ma_Weapons.Name.Title.Title__Legendary_SG_Jakobs_5_Flayer:AttributePresentationDefinition_8',
ON_CARD,
),
('Boganella',
'GD_Cork_Weap_Shotgun.Name.Title__Unique_Boganella:AttributePresentationDefinition_8',
'Unique voice module',
),
('Moonface',
'GD_Cork_Weap_Shotgun.Name.Title.Title__Unique_Moonface:AttributePresentationDefinition_8',
'Fires in oscillating smiley-face pattern, pellets deal 50% explosive splash on impact.',
),
('Boomacorn',
'GD_Cork_Weap_Shotgun.Name.Titles.Title__Unique_Boomacorn:AttributePresentationDefinition_8',
'Shoots spread of 5 random-elemental projectiles',
),
('Too Scoops',
'GD_Cork_Weap_Shotgun.Name.Titles.Title__Unique_TooScoops:AttributePresentationDefinition_8',
'Fires 2 cryo-element spheres which explode after a certain time. Higher elemental chance than listed.',
),
('Bullpup',
'GD_Cork_Weap_Shotgun.Name.Titles.Title__Unique_Bullpup:AttributePresentationDefinition_8',
ON_CARD,
),
('Octo',
'GD_Cork_Weap_Shotgun.Name.Title.Title__Unique_Octo:AttributePresentationDefinition_8',
'Fires 10 slow-moving, oscillating pellets in 3x3 grid',
),
("Jack-o'-Cannon",
'GD_Cork_Weap_Shotgun.Name.Titles.Title__Unique_JackOCannon:AttributePresentationDefinition_8',
"Launches flaming jack-o'-lanterns which bounce. No movement penalty when aiming.",
),
('Torguemada',
'GD_Cork_Weap_Shotgun.Name.Titles.Title__Unique_Torgemada:AttributePresentationDefinition_8',
'Fires 3 explosive projectiles in fixed triangular spread, which also produce smaller, delayed explosions.',
),
('Wombat',
'GD_Cork_Weap_Shotgun.Name.Title.Title__Unique_Wombat:AttributePresentationDefinition_8',
'Fires 5 sticky grenade-like projectiles which explode after 6 seconds or contact with enemy.',
),
('Company Man',
'GD_Cypressure_Weapons.Name.Title.Title__Unique_CompanyMan:AttributePresentationDefinition_8',
ON_CARD,
),
('Moonscaper',
'GD_Cypressure_Weapons.Name.Title.Title__Unique_Landscaper2:AttributePresentationDefinition_8',
'Fires 5 grenades in a square. If hit on ground, they will rise and then explode.',
),
('Party Line',
'GD_Petunia_Weapons.Name.Title.Title__Unique_PartyLine:AttributePresentationDefinition_8',
'Projectiles explode like fireworks, as does the gun when reloaded.',
),
('Heart Breaker',
'GD_Cork_Weap_Shotgun.Name.Title_Hyperion.Title__Unique_HeartBreaker:AttributePresentationDefinition_8',
'Shoots in heart pattern, restores 2% damage dealt as health.',
),
]),
('SMGs', NOC, [
('IVF',
'GD_Cork_Weap_SMG.Name.Title_Legendary_IVF:AttributePresentationDefinition_8',
'When reloaded, explodes and spawns 2 smaller guns which deal increased damage and also explode.',
),
('HellFire',
'GD_Cork_Weap_SMG.Name.Title_Maliwan.Title_Legendary_HellFire:AttributePresentationDefinition_8',
'50% elemental splash damage',
),
('Torrent',
'GD_Cork_Weap_SMG.Name.Title.Title_Legendary_Dahl_Torrent:AttributePresentationDefinition_8',
'No movement penalty while aiming, 5-round burst without delay.',
),
('Fatale',
'GD_Cork_Weap_SMG.Name.Title_Hyperion.Title_Legendary_Bitch:AttributePresentationDefinition_8',
ON_CARD,
),
('Cheat Code',
'GD_Ma_Weapons.Name.Title.Title__Legendary_SMG_Hyperion_5_CheatCode:AttributePresentationDefinition_8',
'When in FFYL, has a chance to not consume ammo.',
),
("Marek's Mouth",
'GD_Cork_Weap_SMG.Name.Title.Title__Unique_MareksMouth:AttributePresentationDefinition_8',
'Bullets have a chance to apply an extra random elemental effect.',
),
('Meat Grinder',
'GD_Cork_Weap_SMG.Name.Title_Bandit.Title__Unique_MeatGrinder:AttributePresentationDefinition_8',
'Fires three bullets.',
),
('Bad Touch',
'GD_Cork_Weap_SMG.Name.Title_Maliwan.Title__Unique_BadTouch:AttributePresentationDefinition_8',
'Heals player at 2% of damage done.',
),
('Good Touch',
'GD_Cork_Weap_SMG.Name.Title_Maliwan.Title__Unique_GoodTouch:AttributePresentationDefinition_8',
'Heals player at 2.5% of damage done.',
),
('Black Snake',
'GD_Cork_Weap_SMG.Name.Title.Title__Unique_BlackSnake:AttributePresentationDefinition_8',
'2 bullets per shot in horizontal pattern.',
),
('Fast Talker',
'GD_Cypressure_Weapons.Name.Title.Title__Unique_FastTalker:AttributePresentationDefinition_8',
ON_CARD,
),
('Boxxy Gunn',
'GD_Petunia_Weapons.Name.Title.Title__Unique_Boxxy:AttributePresentationDefinition_8',
'Bullets ricochet twice. May explode when reloaded, most likely when magazine is fuller.',
),
('Fridgia',
'GD_Weap_SMG.Name.Title.Title__Unique_Fridgia:AttributePresentationDefinition_8',
'2 bullets for the price of 1, fires in the shape of a horse',
),
('Frostfire',
'GD_Weap_SMG.Name.Title.Title__Unique_Frostfire:AttributePresentationDefinition_8',
'Fires 2 projectiles, one cryo and the other incendiary. May apply cryo to player.',
),
('Cutie Killer',
'GD_Ma_Weapons.Name.Title.Title__Unique_SMG_Bandit_6_Glitch_CutieKiller:AttributePresentationDefinition_8',
'Unique voice module',
),
]),
('Snipers', NOC, [
('Pitchfork',
'GD_Cork_Weap_SniperRifles.Name.Title_Dahl.Title_Legendary_Pitchfork:AttributePresentationDefinition_8',
'Fires 5 shots in horizontal line.',
),
('Magma',
'GD_Cork_Weap_SniperRifles.Name.Title_Maliwan.Title_Legendary_Magma:AttributePresentationDefinition_8',
'Elemental damage can spread to other enemies in vicinity.',
),
('Skullmasher',
'GD_Cork_Weap_SniperRifles.Name.Title_Legendary_Skullmasher:AttributePresentationDefinition_8',
'6 bullets for the price of 1.',
),
('Longnail',
'GD_Cork_Weap_SniperRifles.Name.Title_Vladof.Title_Legendary_Longnail:AttributePresentationDefinition_8',
'Shots bypass shields.',
),
('Invader',
'GD_Cork_Weap_SniperRifles.Name.Title_Hyperion.Title_Legendary_Invader:AttributePresentationDefinition_8',
'5-round burst when scoped.',
),
('Omni-Cannon',
'GD_Ma_Weapons.Name.Title.Title__Legendary_Sniper_Hyperion_5_OmniCannon:AttributePresentationDefinition_8',
'Deals unlisted explosive damage.',
),
('Wet Week',
'GD_Cork_Weap_SniperRifles.Name.Title_Dahl.Title__Unique_WetWeek:AttributePresentationDefinition_8',
'Slow projectile speed.',
),
('Razorback',
'GD_Cork_Weap_SniperRifles.Name.Title_Jakobs.Title_Jakobs_Razorback:AttributePresentationDefinition_8',
ON_CARD,
),
('Chere-amie',
'GD_Cork_Weap_SniperRifles.Name.Title_Maliwan.Title__Unique_Chere-amie:AttributePresentationDefinition_8',
'Transfusion effect, and player is healed 2% of damage while weilding.',
# BLCMM doesn't write files in latin1/iso-8859-1, so for now we have to avoid "special" chars. When
# BLCMM gets fixed, I can get rid of this override...
'Je suis enchante. Ou est la bibliotheque?',
),
('Machine',
'GD_Cork_Weap_SniperRifles.Name.Title_Vladof.Title_Unique_TheMachine:AttributePresentationDefinition_8',
'Damage and fire rate increase the longer the trigger is held.',
),
('Plunkett',
'GD_Petunia_Weapons.Name.Title.Title__Unique_Plunkett:AttributePresentationDefinition_8',
ON_CARD,
),
("Fremington's Edge",
'GD_Weap_SniperRifles.Name.Title.Title__Unique_FremingtonsEdge:AttributePresentationDefinition_8',
'Extremely high zoom factor.',
),
]),
('Lasers', NOC, [
('ZX-1',
'GD_Cork_Weap_Lasers.Name.Title.Title__Unique_ZX1:AttributePresentationDefinition_8',
'After a target is hit, subsequent shots will corkscrew towards that target.',
),
('Min Min Lighter',
'GD_Cork_Weap_Lasers.Name.Title.Title__Legendary_Tesla:AttributePresentationDefinition_8',
'Shoots slow, bouncy lightning balls with a large AOE.',
None,
None,
DESC,
),
("Cat o' Nine Tails",
'GD_Cork_Weap_Lasers.Name.Title.Title__Legendary_Ricochet:AttributePresentationDefinition_8',
'Beam ricochets and splits into 3-8 beams.',
),
('Excalibastard',
'GD_Cork_Weap_Lasers.Name.Title.Title__Legendary_Excalibastard:AttributePresentationDefinition_8',
'Crits have a 100% freeze. Meleeing frozen enemies generates a cryo singularity.',
),
('Longest Yard',
'GD_Ma_Weapons.Name.Title.Title__Legendary_Laser_Hyperion_5_LongestYard:AttributePresentationDefinition_8',
ON_CARD,
),
('Absolute Zero',
'GD_Ma_Weapons.Name.Title.Title__Legendary_Laser_Maliwan_5_FusionBeam:AttributePresentationDefinition_8',
ON_CARD,
None,
None,
DESC,
),
('Thunderfire',
'GD_Ma_Weapons.Name.Title.Title__Legendary_Laser_Maliwan_5_Thunderfire:AttributePresentationDefinition_8',
'Beam emits small incendiary nova on hitting enemy or object.',
),
('Laser Disker',
'GD_Ma_Weapons.Name.Title.Title__Legendary_Laser_Tediore_5_LaserDisker:AttributePresentationDefinition_8',
'Fires blue disk in a straight trajectory. Deals more damage to airborne enemies.',
),
('Firestarta',
'GD_Cork_Weap_Lasers.Name.Title.Title__Unique_Firestarta:AttributePresentationDefinition_8',
ON_CARD,
),
('Mining Laser',
'GD_Cork_Weap_Lasers.Name.Title.Title__Unique_Mining:AttributePresentationDefinition_8',
'Fires 3 railgun-like projectiles in a tight triangle.',
),
('Freezeasy',
'GD_Cork_Weap_Lasers.Name.Title.Title__Unique_Freezeasy:AttributePresentationDefinition_8',
ON_CARD,
),
('Vibra-Pulse',
'GD_Cork_Weap_Lasers.Name.Title.Title__Unique_Vibrapulse:AttributePresentationDefinition_8',
'Has a chance to chain lightning to nearby targets. Heals for 2.5% of damage dealt.',
),
('E-GUN',
'GD_Cork_Weap_Lasers.Name.Title.Title__Unique_EGun:AttributePresentationDefinition_8',
'No movement penalty while aiming. Effective against flesh, weak against armor/shields.',
),
("Ol' Rosie",
'GD_Cork_Weap_Lasers.Name.Title.Title__Unique_Rosie:AttributePresentationDefinition_8',
ON_CARD,
),
('Bright Spadroon',
'GD_Cork_Weap_Lasers.Name.Title.Title__Unique_SavorySideSaber:AttributePresentationDefinition_8',
'Extremely short range, lasers shoot to left of crosshair.',
),
('Vandergraffen',
'GD_Cork_Weap_Lasers.Name.Title.Title__Deadlift:AttributePresentationDefinition_8',
ON_CARD,
),
("Tannis' Laser of Enlightenment",
'GD_Ma_Weapons.Name.Title.Title__Unique_Maliwan_Laser_3_Enlightenment:AttributePresentationDefinition_8',
'Short-range flamethrower.',
),
("MINAC's Atonement",
'GD_Ma_Weapons.Name.Title.Title__Unique_Maliwan_Laser_3_Minac:AttributePresentationDefinition_8',
'Randomly selects corrosive, incendiary, or shock for each shot.',
),
('Heartfull Splodger',
'GD_Ma_Weapons.Name.Title.Title__Unique_Maliwan_Laser_6_Glitch_HeartfullSplodger:AttributePresentationDefinition_8',
'Unique voice module.',
# For some reason our data dump doesn't seem to have the full value in here? Weird.
"\\#Splodger'''s ^ere -!",
),
]),
('Grenade Mods', DESC, [
# NOTE: Monster Trap does not have red text (and you wouldn't want it outside that mission anyway)
('Bonus Package',
'GD_Cork_GrenadeMods.Payload.Payload_BonusPackage:AttributePresentationDefinition_4',
'When child grenades explode, they release an additional child.',
),
('Bouncing Bazza',
'GD_GrenadeMods.Payload.Payload_BouncingBonny:AttributePresentationDefinition_4',
'Disperses child grenades as it bounces.',
),
('Fire Bee',
'GD_GrenadeMods.Title.Title_ExterminatorIncendiary:AttributePresentationDefinition_0',
'Spits fire in circular motion and shoots small incendiary missiles.',
),
('Four Seasons',
'GD_GrenadeMods.Payload.Payload_FourSeasons:AttributePresentationDefinition_0',
'Creates a random AOE: Shock, Incendiary, Corrosive, or Cryo.',
),
('Leech',
'GD_GrenadeMods.Payload.Payload_Leech:AttributePresentationDefinition_4',
'Decreased blast radius, transfusion effect when dealing damage.',
),
('Meganade',
'GD_Ma_GrenadeMods.Delivery.Delivery_Meganade:AttributePresentationDefinition_0',
'Creates three singularity pulls',
),
('Nasty Surprise',
'GD_GrenadeMods.Delivery.Delivery_NastySurprise:AttributePresentationDefinition_4',
'Longbow delivery, will drop four child grenades enroute or at final destination.',
),
('Pandemic',
'GD_GrenadeMods.Title.Title_ExterminatorCorrosive:AttributePresentationDefinition_0',
'Launches 3 corrosive-DOT homing grenades on explosion.',
),
('Quasar',
'GD_Cork_GrenadeMods.Payload.Payload_Quasar:AttributePresentationDefinition_4',
'Largest singularity grenade, constant shock DOTs.',
# Have to do an override here thanks to some deficiencies in FT/BLCMM Explorer's data introspection
'E = mc^(OMG)/wtf',
),
('Rolling Thunder',
'GD_GrenadeMods.Delivery.Delivery_RollingThunder:AttributePresentationDefinition_4',
'Low arc, detonates on each bounce, will eventually explode as a MIRV.',
),
('Storm Front',
'GD_GrenadeMods.Title.Title_ExterminatorShock:AttributePresentationDefinition_0',
'Launches sticky child tesla grenades.',
),
('Baby Boomer',
'GD_GrenadeMods.Delivery.Delivery_BabyBoomer:AttributePresentationDefinition_4',
'Rubberized, spawns child grenades with each bounce',
),
('Data Scrubber',
'GD_Ma_GrenadeMods.Delivery.Delivery_DataScrubber:AttributePresentationDefinition_1',
'Slow travel time, regenerates grenade ammo.',
),
('Kiss of Death',
'GD_Cork_GrenadeMods.Payload.Payload_KissOfDeath:AttributePresentationDefinition_4',
'Grenade homes in and sticks to enemies, dealing DOTs. Upon explosion, sounds out healing orbs.',
),
('Snowball',
'GD_GrenadeMods.Delivery.Delivery_Snowball:AttributePresentationDefinition_4',
'Fast projectile speed with very little arc.',
),
('Contraband Sky Rocket',
'GD_GrenadeMods.Delivery.Delivery_SkyRocket:AttributePresentationDefinition_0',
'Flies upwards and releases a large burst of fireworks, increased damage.',
),
]),
('Shields', DESC, [
('Kala',
'GD_Shields.Titles.Title_Absorption04_AbsorptionShieldLegendaryShock:AttributePresentationDefinition_0',
'Shock damage recharges the shield.',
),
('Sham',
'GD_Shields.Titles.Title_Absorption04_AbsorptionShieldLegendaryNormal:AttributePresentationDefinition_0',
ON_CARD,
),
('Prismatic Bulwark',
'GD_Shields.Titles.Title_Absorption04_PrismaticBulwark:AttributePresentationDefinition_0',
ON_CARD,
),
('Whisky Tango Foxtrot',
'GD_Shields.Titles.Title_Booster04_BoosterShieldLegendary:AttributePresentationDefinition_0',
'IED Boosters spawn 3 volleys of shock grenades, can self damage.',
),
('Reogenator',
'GD_Shields.Titles.Title_Chimera04_ChimeraShieldLegendary:AttributePresentationDefinition_0',
ON_CARD,
),
('Rerouter',
'GD_Ma_Shields.Titles.Title_Impact_05_Rerouter:AttributePresentationDefinition_0',
ON_CARD,
),
('Fabled Tortoise',
'GD_Shields.Titles.Title_Juggernaut04_JuggernautLegendary:AttributePresentationDefinition_0',
ON_CARD,
),
('Black Hole',
'GD_Shields.Titles.Title_ShockNova02_Singularity:AttributePresentationDefinition_0',
'Shock nova blast also has a singularity effect.',
),
('Deadly Bloom',
'GD_Shields.Titles.Title_ExplosiveNova02_DeadlyBloom:AttributePresentationDefinition_1',
ON_CARD,
# Bah, more working around deficiencies in my data processing
'What do you mean, theoretically?',
),
('Supernova',
'GD_Shields.Titles.Title_FireNova03_Supernova:AttributePresentationDefinition_0',
ON_CARD,
),
('Bigg Thumppr',
'GD_Shields.Titles.Title_Roid02_RoidShieldLegendary:AttributePresentationDefinition_0',
'On recharge, will damage player if roid effect has been used while down.',
),
('Shooting Star',
'GD_Shields.Titles.Title_Roid06_ShootingStar:AttributePresentationDefinition_0',
'While depleted, a "shooting star" is procced which deals extra explosive damage.',
),
('Avalanche',
'GD_Shields.Titles.Title_Roid07_Avalanche:AttributePresentationDefinition_0',
ON_CARD,
),
("Flyin' Maiden",
'GD_Shields.Titles.Title_CorrosiveSpike02_Legendary:AttributePresentationDefinition_0',
ON_CARD,
),
('Cradle',
'GD_Shields.Titles.Title_Standard05_Legendary:AttributePresentationDefinition_1',
'Discarded shield releases an explosive nova.',
),
('Asteroid Belt',
'GD_Shields.Titles.Title_Booster01_BoosterShieldAsteroidBelt:AttributePresentationDefinition_0',
ON_CARD,
),
('Slammer',
'GD_Shields.Titles.Title_Booster01_BoosterShieldMoxxisSlammer:AttributePresentationDefinition_0',
'Boosters also restore 25% shields.',
),
('Haymaker',
'GD_Shields.Titles.Title_Chimera02_Haymaker:AttributePresentationDefinition_1',
ON_CARD,
),
('M0RQ',
'GD_Ma_Shields.Titles.Title_Chimera_05_M0RQ:AttributePresentationDefinition_1',
'Unique voice module.',
),
('Shield of Ages',
'GD_Ma_Shields.Titles.Title_Juggernaut_03_ShieldOfAges:AttributePresentationDefinition_1',
ON_CARD,
),
('Sunshine',
'GD_Shields.Titles.Title_LaserNova01_Sunshine:AttributePresentationDefinition_0',
ON_CARD,
),
('Rapid Release',
'GD_Cork_Shields.Titles.Title_RapidRelease:AttributePresentationDefinition_0',
ON_CARD,
),
('Naught',
'GD_Ma_Shields.Titles.Title_Naught:AttributePresentationDefinition_0',
ON_CARD,
# Have to work around deficiencies in my data library once again
'5+7+1=Zero',
),
]),
]
# Construct the mod
lines = []
lines.append('TPS')
lines.append('#<{}>'.format(mod_name))
lines.append('')
lines.append(' # {} v{}'.format(mod_name, mod_version))
lines.append(' # by Apocalyptech')
lines.append(' # Licensed under Public Domain / CC0 1.0 Universal')
lines.append(' # Inspired by Ezeith\'s BL2 mod "Red text explainer"')
lines.append(' #')
lines.append(' # All weapons, grenades, and shields with red text will include text describing')
lines.append(' # the extra effects. A lot of shields already have all their effects listed on the')
lines.append(' # card, so those will show up as "{}"'.format(ON_CARD))
lines.append(' #')
lines.append(' # Class Mods and Oz Kits have been left alone, since all those list their effects')
lines.append(' # right on the card.')
lines.append(' #')
lines.append(' # Effect descriptions were largely taken from the Fandom wiki, so take them with a')
lines.append(' # grain of salt, and let me know if anything\'s wrong!')
lines.append('')
for (top_cat, attr_name, items) in sorted(mod_items):
if attr_name not in valid_attrs:
raise Exception('Invalid attribute specified: {}'.format(attr_name))
lines.append('#<{}>'.format(top_cat))
lines.append('')
for item in sorted(items):
if len(item) == 6:
(item_name, obj_name, extra_text, override_text, priority, override_attr) = item
elif len(item) == 5:
(item_name, obj_name, extra_text, override_text, priority) = item
override_attr = attr_name
elif len(item) == 4:
(item_name, obj_name, extra_text, override_text) = item
override_attr = attr_name
priority = None
elif len(item) == 3:
(item_name, obj_name, extra_text) = item
override_attr = attr_name
override_text = None
priority = None
else:
raise Exception('Need at least three items: {}'.format(item))
lines.append('#<{}>'.format(item_name))
lines.append('')
if priority is not None:
lines.append('set {} BasePriority {}'.format(obj_name, priority))
lines.append('')
if override_text is None:
item_struct = data.get_struct_by_full_object(obj_name)
red_text = item_struct[override_attr]
else:
red_text = override_text
if red_text != '' and extra_text != '':
lines.append('set {} {} {} <font color="{}">[{}]</font>'.format(
obj_name,
override_attr,
red_text.replace('(', '[').replace(')', ']'),
explanation_color,
extra_text.replace('(', '[').replace(')', ']'),
))
lines.append('')
lines.append('#</{}>'.format(item_name))
lines.append('')
lines.append('#</{}>'.format(top_cat))
lines.append('')
lines.append('#</{}>'.format(mod_name))
lines.append('')
# Write out to the file
mp.human_str_to_blcm_filename("\n".join(lines), output_filename)
print('Wrote mod to {}'.format(output_filename))
|
import torch
import torch.nn as nn
import argparse
import torchvision
import tqdm
class Logistic_regression(nn.Module):
def __init__(self):
super(Logistic_regression, self).__init__()
self.logistic = nn.Linear(784, 10)
self.sigmoid = nn.Sigmoid()
def forward(self, x):
x = self.logistic(x)
x = self.sigmoid(x)
output = torch.nn.functional.log_softmax(x, dim=1)
return output
def train(args, model, device, train_loader, optimizer, epoch):
model.train()
for batch_idx, (data, target) in enumerate(train_loader):
data = data.view(-1,784) # transform 28 x 28 to 784
# print(data.shape)
data, target = data.to(device), target.to(device)
optimizer.zero_grad()
output = model(data)
loss = torch.nn.functional.nll_loss(output, target)
loss.backward()
optimizer.step()
if batch_idx % args.log_interval == 0:
print('Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}'.format(
epoch, batch_idx * len(data), len(train_loader.dataset),
100. * batch_idx / len(train_loader), loss.item()))
def eval(args, model, device, test_loader):
model.eval()
test_loss = 0
correct = 0
with torch.no_grad():
for data, target in tqdm.tqdm(test_loader):
data = data.view(-1,784)
data, target = data.to(device), target.to(device)
output = model(data) #100s
test_loss += torch.nn.functional.nll_loss(output, target, reduction='sum').item() # sum up batch loss
pred = output.argmax(dim=1, keepdim=True) # get the index of the max log-probability
correct += pred.eq(target.view_as(pred)).sum().item()
test_loss /= len(test_loader.dataset)
print('\nTest set: Average loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)\n'.format(
test_loss, correct, len(test_loader.dataset),
100. * correct / len(test_loader.dataset)))
def main():
parser = argparse.ArgumentParser(description="Logistic regression parser")
parser.add_argument('--batch_size', type=int, default=100, metavar='N', help="Input the batch size") # metavar is the hint
parser.add_argument('--epoch', type=int, default=5)
parser.add_argument('--lr', default=0.01)
parser.add_argument('--log-interval', type=int, default=10, metavar='N',
help='how many batches to wait before logging training status')
args = parser.parse_args()
device = torch.device("cpu")
# train_loader = torch.utils.data.DataLoader(datasets.MNIST('./data', train=False, transform=transforms.Compose))
train_dataset = torchvision.datasets.MNIST(
root='./data',
download=True,
train=True,
transform=torchvision.transforms.Compose([torchvision.transforms.ToTensor(),torchvision.transforms.Normalize((0.1307, ), (0.3081, ))])
)
eval_dataset = torchvision.datasets.MNIST(
root='./data',
download=True,
train=False,
transform=torchvision.transforms.Compose([torchvision.transforms.ToTensor(),torchvision.transforms.Normalize((0.1307, ), (0.3081, ))])
)
train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=args.batch_size, shuffle=True)
eval_loader = torch.utils.data.DataLoader(eval_dataset, batch_size=args.batch_size, shuffle=True)
# print(train_loader.item())
logistic_regression_model = Logistic_regression().to(device)
optimizer = torch.optim.SGD(logistic_regression_model.parameters(), lr=args.lr)
for epoch in range(1, args.epoch):
train(args, logistic_regression_model, device, train_loader, optimizer, epoch)
eval(args, logistic_regression_model, device, eval_loader)
if __name__ == '__main__':
main()
|
#!/usr/bin/env python
import httplib
import re
class Tree(object):
def __init__(self):
self.children = []
self.found = []
self.data = None
def request(url):
conn = httplib.HTTPConnection('localhost:8080')
headers = {
'host': 'localhost:8080',
'upgrade-insecure-requests': '1'
}
conn.request('GET', url, headers=headers)
response = conn.getresponse()
return response
def build(url):
req = request(url)
reqs = req.status
body = req.read()
if reqs == 302:
_, n = map(int, re.findall(r'\d+', body[0:26]))
found = 1
redirect = req.getheader('Location')
tree = Tree()
tree.data = body.decode('utf-8')
tree.found.append(redirect)
tree.children.append(build(redirect))
while(found < n):
req = request(url)
redirect = req.getheader('Location')
if redirect not in tree.found:
tree.found.append(redirect)
tree.children.append(build(redirect))
found = found + 1
return tree
else:
if reqs == 200:
tree = Tree()
tree.data = body.decode('utf-8')
return tree
def read(tree):
if tree.data != None and \
tree.data != 'You\'ve reached the end of the world.' and \
tree.data.find('Redirecting') == -1:
print tree.data
for child in tree.children:
read(child)
root = build('/28158099611aecef2b4405dc75061cb6a217b5d4e25ad3ad256ae0f5e89cdac3')
read(root)
|
#!/usr/bin/env python3
# -*-encoding: utf-8-*-
# by David Zashkol
# 2 course, comp math
# Taras Shevchenko National University of Kyiv
# email: davendiy@gmail.com
class Element:
def __init__(self, item):
self.item = item
self.next = None
self.pre = None
def __repr__(self):
return "Element of list ({})".format(self.item)
def __str__(self):
return "Element of list ({})".format(self.item)
class BayonetList:
def __init__(self):
self._head = None
self._end = None
self._current = None
def empty(self):
return self._head is None and self._end is None
def go_first(self):
self._current = self._head
def go_end(self):
self._current = self._end
def get_current(self):
if self.empty():
raise Exception("BayonetList: 'get_current' applied to empty container")
else:
return self._current.item
def go_next(self):
if self.empty():
return Exception("BayonetList: 'go_next' applied to empty container")
elif self._current.next is None:
return Exception("BayonetList: 'go_next' applied out of range")
else:
self._current = self._current.next
def go_pre(self):
if self.empty():
return Exception("BayonetList: 'go_pre' applied to empty container")
elif self._current.next is None:
return Exception("BayonetList: 'go_pre' applied out of range")
else:
self._current = self._current.pre
def del_curr(self):
if self.empty():
return Exception("BayonetList: 'del_curr' applied to empty container")
tmp = self._current
tmp_pre = self._current.pre
tmp_next = self._current.next
if tmp_pre is not None:
tmp_pre.next = tmp_next
if tmp_next is not None:
tmp_next.pre = tmp_pre
del tmp
self._current = None
if not self.empty():
self.go_first()
def insert_after(self, item):
tmp = Element(item)
if self.empty():
self._current = tmp
self._head = tmp
self._end = tmp
else:
tmp_next = self._current.next
if tmp_next is not None:
tmp_next.pre = tmp
tmp.next = tmp_next
tmp.pre = self._current
self._current = tmp
def insert_before(self, item):
tmp = Element(item)
if self.empty():
self._head = tmp
self._current = tmp
self._end = tmp
else:
tmp_pre = self._current.pre
if tmp_pre is not None:
tmp_pre.next = tmp
tmp.pre = tmp_pre
tmp.next = self._current
self._current.pre = tmp
def __iter__(self):
self.go_first()
return self
def __next__(self):
if self.empty() or self._current is None:
raise StopIteration
self._current = self._current.next
return self.get_current()
def __str__(self):
return "BayonetList(" + ' '.join(map(str, self)) + ')'
def __repr__(self):
return "BayonetList(" + ' '.join(map(str, self)) + ')'
if __name__ == '__main__':
# import random
print(" COMMAND_LIST = ['go_end', 'go_first', 'go_next', 'go_pre', 'del_curr', 'get_current', 'insert_after', 'insert_before']")
test = BayonetList()
# for i in range(50):
# test.insert_after(random.randrange(100))
# test.insert_before(random.randrange(100))
print(test)
while True:
try:
command = input('command:\n--> ')
param = input("param:\n--> ")
# print("command: {}".format(command))
if param:
print(test.__getattribute__(command)(param))
else:
print(test.__getattribute__(command)(param))
print(test)
print('current index: {}'.format(test._current))
input('press enter to continue...')
except Exception as e:
print(e)
|
import sys
class Screen:
def __init__(self, width: int, length: int):
# initialise the 2D array of cells
self._cells = []
for _ in range(length):
row = []
for _ in range(width):
row.append(".")
self._cells.append(row)
# creates an AxB rectangle onto our Screen cells
def rect(self, a: int, b: int):
for h in range(b):
for w in range(a):
self._cells[h][w] = "#"
# shifts a row right
def rotate_row(self, row: int, amount: int):
self._cells[row] = self._shift(self._cells[row][:], amount)
# shifts a column down
def rotate_column(self, col: int, amount: int):
column = [row[col] for row in self._cells]
shifted = self._shift(column, amount)
for h in range(len(shifted)):
self._cells[h][col] = shifted[h]
def lit(self) -> int:
count = 0
for row in self._cells:
for col in row:
if col == "#":
count += 1
return count
@staticmethod
def _shift(row: [str], amount: int) -> [str]:
row_cells = row[:] + row[:]
start = len(row) - amount
end = start + len(row)
return row_cells[start:end]
def __str__(self):
row_strings = []
for h in self._cells:
row_strings.append("".join(h))
return "\n".join(row_strings)
# Command modifies the state of the screen
class Command:
def __init__(self, raw: str):
# parses the raw command string, creates an apply method to modify a Screen
self.command, a, b = self._parse(raw)
if self.command == "rect":
self.apply = lambda s: s.rect(a, b)
elif self.command == "row":
self.apply = lambda s: s.rotate_row(a, b)
elif self.command == "column":
self.apply = lambda s: s.rotate_column(a, b)
elif self.command == "exit":
self.apply = sys.exit
else:
self.apply = lambda _: print("Unknown command ", self.command)
@staticmethod
def _parse(raw: str) -> (str, int, int):
_command, _a, _b = "unk", 0, 0
words = raw.split(" ")
if len(words) == 1:
_command = words[0]
elif len(words) == 2:
_command = words[0]
_a, _b = words[1].split("x")
else:
_command = words[1]
_a = words[2].split("=")[1]
_b = words[4]
return _command, int(_a), int(_b)
if __name__ == "__main__":
screen = Screen(50, 6)
with open("input.txt") as f:
ls = f.readlines()
commands = map(Command, ls)
for command in commands:
command.apply(screen)
print(screen)
print("lit:", screen.lit())
|
# -*- coding: utf-8 -*-
"""
Created on Wed Apr 29 02:07:44 2020
@author: shaol
"""
import DB.dbFetch as dbFetch
import pandas as pd
import datetime as dt
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
def gen_CA_spread(start,end):
#generate bean and meal and oil comparison
myFmt = mdates.DateFormatter('%y/%m') # Dates format
Ticker_1 = "A"
Ticker_2 = "C"
#Get raw market data
index_data = pd.DataFrame(dbFetch.get_index_all()).set_index("Dates")
inv_df = pd.DataFrame(dbFetch.get_historical_inventory()).set_index("Dates")
ccy_df = pd.DataFrame(dbFetch.get_histroical_ccy()).set_index("Dates")
ccy_df = ccy_df[(ccy_df != 0).all(1)]["CNYUSD"]
market_1 = index_data[index_data["name"]==Ticker_1][start:end]
market_1["mid_price"] = 0.5*(market_1["open"]+market_1["close"])
market_1["mid_price"] = market_1["mid_price"]/market_1["mid_price"][0]
market_1 = market_1[["mid_price","r1"]]
market_1 = market_1.join(ccy_df,how="left").fillna(method="ffill")
inventory_1 = inv_df.loc[inv_df["Product"].str.upper()==Ticker_1][start:end]["INV"]
market_1 = market_1.join(inventory_1,how="left")
market_2 = index_data[index_data["name"]==Ticker_2][start:end]
market_2["mid_price"] = 0.5*(market_2["open"]+market_2["close"])
market_2["mid_price"] = market_2["mid_price"]/market_2["mid_price"][0]
market_2 = market_2[["mid_price","r1"]]
inventory_2 = inv_df.loc[inv_df["Product"].str.upper()==Ticker_2][start:end]["INV"]
market_2 = market_2.join(inventory_2,how="left")
# Start plotting
#Fig1: Bean and Bean Meal spread plot
#Subplot 1,2: spread and spread distribution
spread_name = Ticker_1+"_"+Ticker_2+"_Spread"
fig, axes = plt.subplots(nrows=5, ncols=2,figsize=(10,20))
market_1[spread_name] = market_1["mid_price"]-market_2["mid_price"]
axes[0,0].plot(market_1[spread_name],color='C0', label=spread_name)
axes[0,0].legend()
axes[0,0].xaxis.set_major_formatter(myFmt)
ax2 = axes[0,0].twinx()
ax2.plot(market_1["CNYUSD"],color='C1', label="CNY")
axes[0,1].hist(market_1[spread_name],bins=50,color='C1', label=spread_name)
axes[0,1].axvline(market_1[spread_name][-1], color='k', linestyle='dashed', linewidth=3)
bottom, top = axes[0,1].get_ylim()
pct_rank = market_1[spread_name].sort_values().values.searchsorted(market_1[spread_name][-1])/len(market_1[spread_name])
axes[0,1].text(market_1[spread_name][-1], top*0.9, 'Current:{:.1},\nPct:{:.1%}'.format(market_1[spread_name][-1],pct_rank))
#Subplot 3,4: single commodity price and roll yield
axes[1,0].plot(market_1["mid_price"],color='C0', label=Ticker_1)
ax2 = axes[1,0].twinx()
ax2.bar(market_1.index,market_1["r1"],alpha=0.5,width=3,color='C4', label="RollYield")
axes[1,0].xaxis.set_major_formatter(myFmt)
axes[1,0].legend()
axes[1,0].xaxis.set_major_formatter(myFmt)
R1 = market_2["r1"].dropna()
pct_rank = R1.sort_values().values.searchsorted(R1[-1])/len(R1)
axes[1,1].hist(R1,bins=50,color='C4',alpha=0.65)
axes[1,1].axvline(R1[-1], color='k', linestyle='dashed', linewidth=3)
bottom, top = axes[1,1].get_ylim()
axes[1,1].text(R1[-1]*1.1, top*0.9, 'Current:{:.0%},\nPct:{:.1%}'.format(R1[-1],pct_rank))
axes[2,0].plot(market_2["mid_price"],color='C0', label=Ticker_2)
ax2 = axes[2,0].twinx()
ax2.bar(market_2.index,market_2["r1"],alpha=0.5,width=3,color='C4', label="RollYield")
axes[2,0].xaxis.set_major_formatter(myFmt)
axes[2,0].legend()
axes[2,0].xaxis.set_major_formatter(myFmt)
R1 = market_2["r1"].dropna()
pct_rank = R1.sort_values().values.searchsorted(R1[-1])/len(R1)
axes[2,1].hist(R1,bins=50,color='C4',alpha=0.65)
axes[2,1].axvline(R1[-1], color='k', linestyle='dashed', linewidth=3)
bottom, top = axes[2,1].get_ylim()
axes[2,1].text(R1[-1]*1.1, top*0.9, 'Current:{:.0%},\nPct:{:.1%}'.format(R1[-1],pct_rank))
axes[3,0].bar(market_1.index,market_1["INV"],alpha=0.5,width=3,color='C4', label=Ticker_1+"_INV")
axes[3,0].legend()
axes[3,0].xaxis.set_major_formatter(myFmt)
pct_rank = market_1["INV"].sort_values().values.searchsorted(market_1["INV"][-1])/len(market_1["INV"])
axes[3,1].hist(market_1["INV"],bins=50,color='C3',alpha=0.65)
axes[3,1].axvline(market_1["INV"][-1], color='k', linestyle='dashed', linewidth=3)
bottom, top = axes[3,1].get_ylim()
axes[3,1].text(market_1["INV"][-1]*1.1, top*0.9, 'Current:{:,},\nPct:{:.1%}'.format(market_1["INV"][-1],pct_rank))
axes[4,0].bar(market_2.index,market_2["INV"],alpha=0.5,width=3,color='C4', label=Ticker_2+"_INV")
axes[4,0].legend()
axes[4,0].xaxis.set_major_formatter(myFmt)
pct_rank = market_2["INV"].sort_values().values.searchsorted(market_2["INV"][-1])/len(market_2["INV"])
axes[4,1].hist(market_2["INV"],bins=50,color='C3',alpha=0.65)
axes[4,1].axvline(market_2["INV"][-1], color='k', linestyle='dashed', linewidth=3)
bottom, top = axes[4,1].get_ylim()
axes[4,1].text(market_2["INV"][-1]*1.1, top*0.9, 'Current:{:,},\nPct:{:.1%}'.format(market_2["INV"][-1],pct_rank))
fig.suptitle(spread_name+' Strat',y=0.9)
return fig |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'application_gui.ui'
#
# Created by: PyQt5 UI code generator 5.15.2
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file unless you know what you are doing.
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Application(object):
def setupUi(self, Application):
Application.setObjectName("Application")
Application.resize(1600, 1000)
palette = QtGui.QPalette()
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Button, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Light, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.ButtonText, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Base, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Window, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0, 128))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.PlaceholderText, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Button, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Light, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.ButtonText, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Base, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Window, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0, 128))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.PlaceholderText, brush)
brush = QtGui.QBrush(QtGui.QColor(120, 120, 120))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Button, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Light, brush)
brush = QtGui.QBrush(QtGui.QColor(120, 120, 120))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(120, 120, 120))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.ButtonText, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Base, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Window, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0, 128))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.PlaceholderText, brush)
Application.setPalette(palette)
font = QtGui.QFont()
font.setFamily("Noto Sans")
font.setPointSize(10)
Application.setFont(font)
Application.setAutoFillBackground(False)
Application.setStyleSheet("QPushButton {\n"
" color:green;\n"
" background-color: black;\n"
" border-style: double;\n"
" border-width: 2px;\n"
" border-radius: 0px;\n"
" border-color: green;\n"
" font-family: Calibri;\n"
" font: 20px;\n"
" padding: 1px;\n"
"}")
self.stackedWidget = QtWidgets.QStackedWidget(Application)
self.stackedWidget.setGeometry(QtCore.QRect(0, 100, 1600, 900))
palette = QtGui.QPalette()
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
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.Light, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 170, 127))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Midlight, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Dark, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Mid, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.ButtonText, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Base, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Shadow, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.AlternateBase, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.ToolTipBase, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.ToolTipText, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0, 128))
brush.setStyle(QtCore.Qt.NoBrush)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.PlaceholderText, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
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.Light, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 170, 127))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Midlight, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Dark, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Mid, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.ButtonText, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Base, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Shadow, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.AlternateBase, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.ToolTipBase, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.ToolTipText, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0, 128))
brush.setStyle(QtCore.Qt.NoBrush)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.PlaceholderText, 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(0, 0, 0))
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.Light, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 170, 127))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Midlight, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Dark, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Mid, 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(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Base, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Shadow, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.AlternateBase, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.ToolTipBase, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.ToolTipText, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0, 128))
brush.setStyle(QtCore.Qt.NoBrush)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.PlaceholderText, brush)
self.stackedWidget.setPalette(palette)
font = QtGui.QFont()
font.setFamily("Noto Sans")
font.setPointSize(10)
self.stackedWidget.setFont(font)
self.stackedWidget.setObjectName("stackedWidget")
self.page_1 = QtWidgets.QWidget()
font = QtGui.QFont()
font.setFamily("Noto Sans")
font.setPointSize(10)
self.page_1.setFont(font)
self.page_1.setObjectName("page_1")
self.bar_tracker_1 = MplWidget(self.page_1)
self.bar_tracker_1.setGeometry(QtCore.QRect(50, 100, 1000, 700))
palette = QtGui.QPalette()
brush = QtGui.QBrush(QtGui.QColor(26, 255, 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.Light, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Dark, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Mid, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 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.AlternateBase, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.ToolTipBase, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0, 128))
brush.setStyle(QtCore.Qt.NoBrush)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.PlaceholderText, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 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.Light, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Dark, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Mid, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 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.AlternateBase, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.ToolTipBase, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0, 128))
brush.setStyle(QtCore.Qt.NoBrush)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.PlaceholderText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
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.Light, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Dark, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Mid, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.ButtonText, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
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.AlternateBase, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.ToolTipBase, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0, 128))
brush.setStyle(QtCore.Qt.NoBrush)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.PlaceholderText, brush)
self.bar_tracker_1.setPalette(palette)
self.bar_tracker_1.setObjectName("bar_tracker_1")
self.tracker_names = QtWidgets.QLabel(self.page_1)
self.tracker_names.setGeometry(QtCore.QRect(1100, 100, 100, 500))
palette = QtGui.QPalette()
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0, 128))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.PlaceholderText, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0, 128))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.PlaceholderText, brush)
brush = QtGui.QBrush(QtGui.QColor(120, 120, 120))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(120, 120, 120))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0, 128))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.PlaceholderText, brush)
self.tracker_names.setPalette(palette)
font = QtGui.QFont()
font.setFamily("Noto Sans")
font.setPointSize(10)
self.tracker_names.setFont(font)
self.tracker_names.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignTop)
self.tracker_names.setWordWrap(False)
self.tracker_names.setObjectName("tracker_names")
self.tracker_likes = QtWidgets.QLabel(self.page_1)
self.tracker_likes.setGeometry(QtCore.QRect(1200, 100, 100, 500))
palette = QtGui.QPalette()
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0, 128))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.PlaceholderText, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0, 128))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.PlaceholderText, brush)
brush = QtGui.QBrush(QtGui.QColor(120, 120, 120))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(120, 120, 120))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0, 128))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.PlaceholderText, brush)
self.tracker_likes.setPalette(palette)
font = QtGui.QFont()
font.setFamily("Noto Sans")
font.setPointSize(10)
self.tracker_likes.setFont(font)
self.tracker_likes.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignTop)
self.tracker_likes.setWordWrap(False)
self.tracker_likes.setObjectName("tracker_likes")
self.tracker_mentions = QtWidgets.QLabel(self.page_1)
self.tracker_mentions.setGeometry(QtCore.QRect(1300, 100, 100, 500))
palette = QtGui.QPalette()
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0, 128))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.PlaceholderText, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0, 128))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.PlaceholderText, brush)
brush = QtGui.QBrush(QtGui.QColor(120, 120, 120))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(120, 120, 120))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0, 128))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.PlaceholderText, brush)
self.tracker_mentions.setPalette(palette)
font = QtGui.QFont()
font.setFamily("Noto Sans")
font.setPointSize(10)
self.tracker_mentions.setFont(font)
self.tracker_mentions.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignTop)
self.tracker_mentions.setWordWrap(False)
self.tracker_mentions.setObjectName("tracker_mentions")
self.tracker_likes_5 = QtWidgets.QLabel(self.page_1)
self.tracker_likes_5.setGeometry(QtCore.QRect(1400, 100, 100, 500))
palette = QtGui.QPalette()
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0, 128))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.PlaceholderText, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0, 128))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.PlaceholderText, brush)
brush = QtGui.QBrush(QtGui.QColor(120, 120, 120))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(120, 120, 120))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0, 128))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.PlaceholderText, brush)
self.tracker_likes_5.setPalette(palette)
font = QtGui.QFont()
font.setFamily("Noto Sans")
font.setPointSize(10)
self.tracker_likes_5.setFont(font)
self.tracker_likes_5.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignTop)
self.tracker_likes_5.setWordWrap(False)
self.tracker_likes_5.setObjectName("tracker_likes_5")
self.label_company = QtWidgets.QLabel(self.page_1)
self.label_company.setGeometry(QtCore.QRect(1100, 50, 100, 20))
palette = QtGui.QPalette()
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0, 128))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.PlaceholderText, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0, 128))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.PlaceholderText, brush)
brush = QtGui.QBrush(QtGui.QColor(120, 120, 120))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(120, 120, 120))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0, 128))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.PlaceholderText, brush)
self.label_company.setPalette(palette)
font = QtGui.QFont()
font.setFamily("Noto Sans")
font.setPointSize(12)
self.label_company.setFont(font)
self.label_company.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignTop)
self.label_company.setWordWrap(False)
self.label_company.setObjectName("label_company")
self.label_likes = QtWidgets.QLabel(self.page_1)
self.label_likes.setGeometry(QtCore.QRect(1200, 50, 100, 20))
palette = QtGui.QPalette()
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0, 128))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.PlaceholderText, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0, 128))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.PlaceholderText, brush)
brush = QtGui.QBrush(QtGui.QColor(120, 120, 120))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(120, 120, 120))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0, 128))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.PlaceholderText, brush)
self.label_likes.setPalette(palette)
font = QtGui.QFont()
font.setFamily("Noto Sans")
font.setPointSize(12)
self.label_likes.setFont(font)
self.label_likes.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignTop)
self.label_likes.setWordWrap(False)
self.label_likes.setObjectName("label_likes")
self.label_mentions = QtWidgets.QLabel(self.page_1)
self.label_mentions.setGeometry(QtCore.QRect(1300, 50, 100, 20))
palette = QtGui.QPalette()
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0, 128))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.PlaceholderText, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0, 128))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.PlaceholderText, brush)
brush = QtGui.QBrush(QtGui.QColor(120, 120, 120))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(120, 120, 120))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0, 128))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.PlaceholderText, brush)
self.label_mentions.setPalette(palette)
font = QtGui.QFont()
font.setFamily("Noto Sans")
font.setPointSize(12)
self.label_mentions.setFont(font)
self.label_mentions.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignTop)
self.label_mentions.setWordWrap(False)
self.label_mentions.setObjectName("label_mentions")
self.label_likes_5 = QtWidgets.QLabel(self.page_1)
self.label_likes_5.setGeometry(QtCore.QRect(1400, 50, 100, 20))
palette = QtGui.QPalette()
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0, 128))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.PlaceholderText, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0, 128))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.PlaceholderText, brush)
brush = QtGui.QBrush(QtGui.QColor(120, 120, 120))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(120, 120, 120))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0, 128))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.PlaceholderText, brush)
self.label_likes_5.setPalette(palette)
font = QtGui.QFont()
font.setFamily("Noto Sans")
font.setPointSize(12)
self.label_likes_5.setFont(font)
self.label_likes_5.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignTop)
self.label_likes_5.setWordWrap(False)
self.label_likes_5.setObjectName("label_likes_5")
self.stackedWidget.addWidget(self.page_1)
self.page_2 = QtWidgets.QWidget()
self.page_2.setObjectName("page_2")
self.likes_tracker_1 = MplWidget(self.page_2)
self.likes_tracker_1.setGeometry(QtCore.QRect(0, 0, 400, 300))
palette = QtGui.QPalette()
brush = QtGui.QBrush(QtGui.QColor(26, 255, 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.Light, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Dark, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Mid, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 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.AlternateBase, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.ToolTipBase, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0, 128))
brush.setStyle(QtCore.Qt.NoBrush)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.PlaceholderText, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 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.Light, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Dark, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Mid, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 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.AlternateBase, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.ToolTipBase, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0, 128))
brush.setStyle(QtCore.Qt.NoBrush)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.PlaceholderText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
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.Light, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Dark, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Mid, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.ButtonText, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
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.AlternateBase, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.ToolTipBase, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0, 128))
brush.setStyle(QtCore.Qt.NoBrush)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.PlaceholderText, brush)
self.likes_tracker_1.setPalette(palette)
self.likes_tracker_1.setObjectName("likes_tracker_1")
self.likes_tracker_2 = MplWidget(self.page_2)
self.likes_tracker_2.setGeometry(QtCore.QRect(400, 0, 400, 300))
palette = QtGui.QPalette()
brush = QtGui.QBrush(QtGui.QColor(26, 255, 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.Light, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Dark, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Mid, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 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.AlternateBase, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.ToolTipBase, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0, 128))
brush.setStyle(QtCore.Qt.NoBrush)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.PlaceholderText, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 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.Light, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Dark, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Mid, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 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.AlternateBase, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.ToolTipBase, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0, 128))
brush.setStyle(QtCore.Qt.NoBrush)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.PlaceholderText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
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.Light, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Dark, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Mid, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.ButtonText, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
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.AlternateBase, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.ToolTipBase, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0, 128))
brush.setStyle(QtCore.Qt.NoBrush)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.PlaceholderText, brush)
self.likes_tracker_2.setPalette(palette)
self.likes_tracker_2.setObjectName("likes_tracker_2")
self.likes_tracker_3 = MplWidget(self.page_2)
self.likes_tracker_3.setGeometry(QtCore.QRect(800, 0, 400, 300))
palette = QtGui.QPalette()
brush = QtGui.QBrush(QtGui.QColor(26, 255, 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.Light, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Dark, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Mid, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 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.AlternateBase, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.ToolTipBase, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0, 128))
brush.setStyle(QtCore.Qt.NoBrush)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.PlaceholderText, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 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.Light, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Dark, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Mid, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 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.AlternateBase, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.ToolTipBase, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0, 128))
brush.setStyle(QtCore.Qt.NoBrush)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.PlaceholderText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
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.Light, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Dark, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Mid, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.ButtonText, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
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.AlternateBase, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.ToolTipBase, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0, 128))
brush.setStyle(QtCore.Qt.NoBrush)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.PlaceholderText, brush)
self.likes_tracker_3.setPalette(palette)
self.likes_tracker_3.setObjectName("likes_tracker_3")
self.likes_tracker_4 = MplWidget(self.page_2)
self.likes_tracker_4.setGeometry(QtCore.QRect(1200, 0, 400, 300))
palette = QtGui.QPalette()
brush = QtGui.QBrush(QtGui.QColor(26, 255, 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.Light, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Dark, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Mid, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 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.AlternateBase, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.ToolTipBase, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0, 128))
brush.setStyle(QtCore.Qt.NoBrush)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.PlaceholderText, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 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.Light, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Dark, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Mid, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 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.AlternateBase, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.ToolTipBase, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0, 128))
brush.setStyle(QtCore.Qt.NoBrush)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.PlaceholderText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
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.Light, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Dark, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Mid, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.ButtonText, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
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.AlternateBase, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.ToolTipBase, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0, 128))
brush.setStyle(QtCore.Qt.NoBrush)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.PlaceholderText, brush)
self.likes_tracker_4.setPalette(palette)
self.likes_tracker_4.setObjectName("likes_tracker_4")
self.likes_tracker_5 = MplWidget(self.page_2)
self.likes_tracker_5.setGeometry(QtCore.QRect(0, 300, 400, 300))
palette = QtGui.QPalette()
brush = QtGui.QBrush(QtGui.QColor(26, 255, 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.Light, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Dark, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Mid, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 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.AlternateBase, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.ToolTipBase, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0, 128))
brush.setStyle(QtCore.Qt.NoBrush)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.PlaceholderText, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 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.Light, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Dark, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Mid, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 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.AlternateBase, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.ToolTipBase, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0, 128))
brush.setStyle(QtCore.Qt.NoBrush)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.PlaceholderText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
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.Light, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Dark, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Mid, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.ButtonText, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
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.AlternateBase, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.ToolTipBase, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0, 128))
brush.setStyle(QtCore.Qt.NoBrush)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.PlaceholderText, brush)
self.likes_tracker_5.setPalette(palette)
self.likes_tracker_5.setObjectName("likes_tracker_5")
self.likes_tracker_6 = MplWidget(self.page_2)
self.likes_tracker_6.setGeometry(QtCore.QRect(400, 300, 400, 300))
palette = QtGui.QPalette()
brush = QtGui.QBrush(QtGui.QColor(26, 255, 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.Light, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Dark, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Mid, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 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.AlternateBase, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.ToolTipBase, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0, 128))
brush.setStyle(QtCore.Qt.NoBrush)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.PlaceholderText, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 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.Light, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Dark, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Mid, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 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.AlternateBase, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.ToolTipBase, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0, 128))
brush.setStyle(QtCore.Qt.NoBrush)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.PlaceholderText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
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.Light, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Dark, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Mid, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.ButtonText, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
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.AlternateBase, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.ToolTipBase, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0, 128))
brush.setStyle(QtCore.Qt.NoBrush)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.PlaceholderText, brush)
self.likes_tracker_6.setPalette(palette)
self.likes_tracker_6.setObjectName("likes_tracker_6")
self.likes_tracker_7 = MplWidget(self.page_2)
self.likes_tracker_7.setGeometry(QtCore.QRect(800, 300, 400, 300))
palette = QtGui.QPalette()
brush = QtGui.QBrush(QtGui.QColor(26, 255, 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.Light, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Dark, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Mid, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 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.AlternateBase, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.ToolTipBase, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0, 128))
brush.setStyle(QtCore.Qt.NoBrush)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.PlaceholderText, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 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.Light, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Dark, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Mid, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 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.AlternateBase, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.ToolTipBase, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0, 128))
brush.setStyle(QtCore.Qt.NoBrush)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.PlaceholderText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
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.Light, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Dark, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Mid, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.ButtonText, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
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.AlternateBase, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.ToolTipBase, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0, 128))
brush.setStyle(QtCore.Qt.NoBrush)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.PlaceholderText, brush)
self.likes_tracker_7.setPalette(palette)
self.likes_tracker_7.setObjectName("likes_tracker_7")
self.likes_tracker_8 = MplWidget(self.page_2)
self.likes_tracker_8.setGeometry(QtCore.QRect(1200, 300, 400, 300))
palette = QtGui.QPalette()
brush = QtGui.QBrush(QtGui.QColor(26, 255, 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.Light, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Dark, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Mid, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 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.AlternateBase, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.ToolTipBase, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0, 128))
brush.setStyle(QtCore.Qt.NoBrush)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.PlaceholderText, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 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.Light, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Dark, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Mid, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 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.AlternateBase, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.ToolTipBase, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0, 128))
brush.setStyle(QtCore.Qt.NoBrush)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.PlaceholderText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
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.Light, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Dark, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Mid, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.ButtonText, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
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.AlternateBase, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.ToolTipBase, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0, 128))
brush.setStyle(QtCore.Qt.NoBrush)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.PlaceholderText, brush)
self.likes_tracker_8.setPalette(palette)
self.likes_tracker_8.setObjectName("likes_tracker_8")
self.likes_tracker_9 = MplWidget(self.page_2)
self.likes_tracker_9.setGeometry(QtCore.QRect(0, 600, 400, 300))
palette = QtGui.QPalette()
brush = QtGui.QBrush(QtGui.QColor(26, 255, 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.Light, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Dark, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Mid, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 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.AlternateBase, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.ToolTipBase, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0, 128))
brush.setStyle(QtCore.Qt.NoBrush)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.PlaceholderText, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 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.Light, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Dark, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Mid, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 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.AlternateBase, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.ToolTipBase, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0, 128))
brush.setStyle(QtCore.Qt.NoBrush)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.PlaceholderText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
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.Light, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Dark, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Mid, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.ButtonText, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
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.AlternateBase, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.ToolTipBase, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0, 128))
brush.setStyle(QtCore.Qt.NoBrush)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.PlaceholderText, brush)
self.likes_tracker_9.setPalette(palette)
self.likes_tracker_9.setObjectName("likes_tracker_9")
self.likes_tracker_10 = MplWidget(self.page_2)
self.likes_tracker_10.setGeometry(QtCore.QRect(400, 600, 400, 300))
palette = QtGui.QPalette()
brush = QtGui.QBrush(QtGui.QColor(26, 255, 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.Light, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Dark, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Mid, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 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.AlternateBase, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.ToolTipBase, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0, 128))
brush.setStyle(QtCore.Qt.NoBrush)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.PlaceholderText, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 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.Light, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Dark, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Mid, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 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.AlternateBase, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.ToolTipBase, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0, 128))
brush.setStyle(QtCore.Qt.NoBrush)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.PlaceholderText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
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.Light, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Dark, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Mid, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.ButtonText, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
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.AlternateBase, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.ToolTipBase, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0, 128))
brush.setStyle(QtCore.Qt.NoBrush)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.PlaceholderText, brush)
self.likes_tracker_10.setPalette(palette)
self.likes_tracker_10.setObjectName("likes_tracker_10")
self.likes_tracker_11 = MplWidget(self.page_2)
self.likes_tracker_11.setGeometry(QtCore.QRect(800, 600, 400, 300))
palette = QtGui.QPalette()
brush = QtGui.QBrush(QtGui.QColor(26, 255, 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.Light, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Dark, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Mid, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 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.AlternateBase, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.ToolTipBase, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0, 128))
brush.setStyle(QtCore.Qt.NoBrush)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.PlaceholderText, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 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.Light, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Dark, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Mid, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 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.AlternateBase, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.ToolTipBase, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0, 128))
brush.setStyle(QtCore.Qt.NoBrush)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.PlaceholderText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
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.Light, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Dark, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Mid, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.ButtonText, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
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.AlternateBase, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.ToolTipBase, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0, 128))
brush.setStyle(QtCore.Qt.NoBrush)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.PlaceholderText, brush)
self.likes_tracker_11.setPalette(palette)
self.likes_tracker_11.setObjectName("likes_tracker_11")
self.likes_tracker_12 = MplWidget(self.page_2)
self.likes_tracker_12.setGeometry(QtCore.QRect(1200, 600, 400, 300))
palette = QtGui.QPalette()
brush = QtGui.QBrush(QtGui.QColor(26, 255, 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.Light, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Dark, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Mid, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 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.AlternateBase, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.ToolTipBase, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0, 128))
brush.setStyle(QtCore.Qt.NoBrush)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.PlaceholderText, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 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.Light, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Dark, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Mid, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 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.AlternateBase, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.ToolTipBase, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0, 128))
brush.setStyle(QtCore.Qt.NoBrush)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.PlaceholderText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
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.Light, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Dark, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Mid, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.ButtonText, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
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.AlternateBase, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.ToolTipBase, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0, 128))
brush.setStyle(QtCore.Qt.NoBrush)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.PlaceholderText, brush)
self.likes_tracker_12.setPalette(palette)
self.likes_tracker_12.setObjectName("likes_tracker_12")
self.stackedWidget.addWidget(self.page_2)
self.page_3 = QtWidgets.QWidget()
self.page_3.setObjectName("page_3")
self.tweets_user = QtWidgets.QLabel(self.page_3)
self.tweets_user.setGeometry(QtCore.QRect(0, 50, 200, 800))
palette = QtGui.QPalette()
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.ToolTipText, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0, 128))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.PlaceholderText, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.ToolTipText, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0, 128))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.PlaceholderText, brush)
brush = QtGui.QBrush(QtGui.QColor(120, 120, 120))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(120, 120, 120))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.ToolTipText, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0, 128))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.PlaceholderText, brush)
self.tweets_user.setPalette(palette)
font = QtGui.QFont()
font.setFamily("Noto Sans")
self.tweets_user.setFont(font)
self.tweets_user.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignTop)
self.tweets_user.setObjectName("tweets_user")
self.tweets_content = QtWidgets.QLabel(self.page_3)
self.tweets_content.setGeometry(QtCore.QRect(200, 50, 800, 800))
palette = QtGui.QPalette()
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.ToolTipText, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0, 128))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.PlaceholderText, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.ToolTipText, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0, 128))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.PlaceholderText, brush)
brush = QtGui.QBrush(QtGui.QColor(120, 120, 120))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(120, 120, 120))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.ToolTipText, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0, 128))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.PlaceholderText, brush)
self.tweets_content.setPalette(palette)
font = QtGui.QFont()
font.setFamily("Noto Sans")
self.tweets_content.setFont(font)
self.tweets_content.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignTop)
self.tweets_content.setObjectName("tweets_content")
self.tweets_likes = QtWidgets.QLabel(self.page_3)
self.tweets_likes.setGeometry(QtCore.QRect(1000, 50, 200, 800))
palette = QtGui.QPalette()
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.ToolTipText, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0, 128))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.PlaceholderText, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.ToolTipText, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0, 128))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.PlaceholderText, brush)
brush = QtGui.QBrush(QtGui.QColor(120, 120, 120))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(120, 120, 120))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.ToolTipText, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0, 128))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.PlaceholderText, brush)
self.tweets_likes.setPalette(palette)
font = QtGui.QFont()
font.setFamily("Noto Sans")
self.tweets_likes.setFont(font)
self.tweets_likes.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignTop)
self.tweets_likes.setObjectName("tweets_likes")
self.tweets_user_label = QtWidgets.QLabel(self.page_3)
self.tweets_user_label.setGeometry(QtCore.QRect(0, 0, 200, 50))
palette = QtGui.QPalette()
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.ToolTipText, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0, 128))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.PlaceholderText, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.ToolTipText, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0, 128))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.PlaceholderText, brush)
brush = QtGui.QBrush(QtGui.QColor(120, 120, 120))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(120, 120, 120))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.ToolTipText, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0, 128))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.PlaceholderText, brush)
self.tweets_user_label.setPalette(palette)
font = QtGui.QFont()
font.setFamily("Noto Sans")
self.tweets_user_label.setFont(font)
self.tweets_user_label.setAlignment(QtCore.Qt.AlignCenter)
self.tweets_user_label.setObjectName("tweets_user_label")
self.tweets_content_label = QtWidgets.QLabel(self.page_3)
self.tweets_content_label.setGeometry(QtCore.QRect(200, 0, 801, 50))
palette = QtGui.QPalette()
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.ToolTipText, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0, 128))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.PlaceholderText, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.ToolTipText, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0, 128))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.PlaceholderText, brush)
brush = QtGui.QBrush(QtGui.QColor(120, 120, 120))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(120, 120, 120))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.ToolTipText, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0, 128))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.PlaceholderText, brush)
self.tweets_content_label.setPalette(palette)
font = QtGui.QFont()
font.setFamily("Noto Sans")
self.tweets_content_label.setFont(font)
self.tweets_content_label.setAlignment(QtCore.Qt.AlignCenter)
self.tweets_content_label.setObjectName("tweets_content_label")
self.tweets_likes_label = QtWidgets.QLabel(self.page_3)
self.tweets_likes_label.setGeometry(QtCore.QRect(1000, 0, 200, 50))
palette = QtGui.QPalette()
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.ToolTipText, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0, 128))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.PlaceholderText, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.ToolTipText, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0, 128))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.PlaceholderText, brush)
brush = QtGui.QBrush(QtGui.QColor(120, 120, 120))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(120, 120, 120))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.ToolTipText, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0, 128))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.PlaceholderText, brush)
self.tweets_likes_label.setPalette(palette)
font = QtGui.QFont()
font.setFamily("Noto Sans")
self.tweets_likes_label.setFont(font)
self.tweets_likes_label.setAlignment(QtCore.Qt.AlignCenter)
self.tweets_likes_label.setObjectName("tweets_likes_label")
self.tweets_date = QtWidgets.QLabel(self.page_3)
self.tweets_date.setGeometry(QtCore.QRect(1200, 50, 200, 800))
palette = QtGui.QPalette()
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.ToolTipText, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0, 128))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.PlaceholderText, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.ToolTipText, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0, 128))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.PlaceholderText, brush)
brush = QtGui.QBrush(QtGui.QColor(120, 120, 120))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(120, 120, 120))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.ToolTipText, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0, 128))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.PlaceholderText, brush)
self.tweets_date.setPalette(palette)
font = QtGui.QFont()
font.setFamily("Noto Sans")
self.tweets_date.setFont(font)
self.tweets_date.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignTop)
self.tweets_date.setObjectName("tweets_date")
self.tweets_date_label = QtWidgets.QLabel(self.page_3)
self.tweets_date_label.setGeometry(QtCore.QRect(1200, 0, 200, 50))
palette = QtGui.QPalette()
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.ToolTipText, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0, 128))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.PlaceholderText, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.ToolTipText, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0, 128))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.PlaceholderText, brush)
brush = QtGui.QBrush(QtGui.QColor(120, 120, 120))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(120, 120, 120))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.ToolTipText, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0, 128))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.PlaceholderText, brush)
self.tweets_date_label.setPalette(palette)
font = QtGui.QFont()
font.setFamily("Noto Sans")
self.tweets_date_label.setFont(font)
self.tweets_date_label.setAlignment(QtCore.Qt.AlignCenter)
self.tweets_date_label.setObjectName("tweets_date_label")
self.stackedWidget.addWidget(self.page_3)
self.push_button_1 = QtWidgets.QPushButton(Application)
self.push_button_1.setGeometry(QtCore.QRect(0, 0, 180, 100))
self.push_button_1.setAutoFillBackground(False)
self.push_button_1.setObjectName("push_button_1")
self.push_button_3 = QtWidgets.QPushButton(Application)
self.push_button_3.setGeometry(QtCore.QRect(360, 0, 180, 100))
self.push_button_3.setAutoFillBackground(False)
self.push_button_3.setObjectName("push_button_3")
self.push_button_2 = QtWidgets.QPushButton(Application)
self.push_button_2.setGeometry(QtCore.QRect(180, 0, 180, 100))
self.push_button_2.setAutoFillBackground(False)
self.push_button_2.setObjectName("push_button_2")
self.tracker_names_6 = QtWidgets.QLabel(Application)
self.tracker_names_6.setGeometry(QtCore.QRect(1490, 10, 111, 61))
palette = QtGui.QPalette()
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0, 128))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.PlaceholderText, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0, 128))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.PlaceholderText, brush)
brush = QtGui.QBrush(QtGui.QColor(120, 120, 120))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(120, 120, 120))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0, 128))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.PlaceholderText, brush)
self.tracker_names_6.setPalette(palette)
font = QtGui.QFont()
font.setFamily("Noto Sans")
font.setPointSize(12)
font.setItalic(True)
self.tracker_names_6.setFont(font)
self.tracker_names_6.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignTop)
self.tracker_names_6.setWordWrap(False)
self.tracker_names_6.setObjectName("tracker_names_6")
self.label_datetime = QtWidgets.QLabel(Application)
self.label_datetime.setGeometry(QtCore.QRect(1050, 10, 71, 61))
palette = QtGui.QPalette()
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0, 128))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.PlaceholderText, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0, 128))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.PlaceholderText, brush)
brush = QtGui.QBrush(QtGui.QColor(120, 120, 120))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(120, 120, 120))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0, 128))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.PlaceholderText, brush)
self.label_datetime.setPalette(palette)
font = QtGui.QFont()
font.setFamily("Noto Sans")
font.setPointSize(12)
font.setItalic(True)
self.label_datetime.setFont(font)
self.label_datetime.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignTop)
self.label_datetime.setWordWrap(False)
self.label_datetime.setObjectName("label_datetime")
self.label_time = QtWidgets.QLabel(Application)
self.label_time.setGeometry(QtCore.QRect(1130, 10, 241, 61))
palette = QtGui.QPalette()
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0, 128))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.PlaceholderText, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(26, 255, 0, 128))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.PlaceholderText, brush)
brush = QtGui.QBrush(QtGui.QColor(120, 120, 120))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(120, 120, 120))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0, 128))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.PlaceholderText, brush)
self.label_time.setPalette(palette)
font = QtGui.QFont()
font.setFamily("Noto Sans")
font.setPointSize(12)
font.setItalic(True)
self.label_time.setFont(font)
self.label_time.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignTop)
self.label_time.setWordWrap(False)
self.label_time.setObjectName("label_time")
self.retranslateUi(Application)
QtCore.QMetaObject.connectSlotsByName(Application)
def retranslateUi(self, Application):
_translate = QtCore.QCoreApplication.translate
Application.setWindowTitle(_translate("Application", "Form"))
self.tracker_names.setText(_translate("Application", "NO DATA"))
self.tracker_likes.setText(_translate("Application", "NO DATA"))
self.tracker_mentions.setText(_translate("Application", "NO DATA"))
self.tracker_likes_5.setText(_translate("Application", "NO DATA"))
self.label_company.setText(_translate("Application", "Company"))
self.label_likes.setText(_translate("Application", "Likes"))
self.label_mentions.setText(_translate("Application", "Mentions"))
self.label_likes_5.setText(_translate("Application", "Δ Likes"))
self.tweets_user.setText(_translate("Application", "TextLabel"))
self.tweets_content.setText(_translate("Application", "TextLabel"))
self.tweets_likes.setText(_translate("Application", "TextLabel"))
self.tweets_user_label.setText(_translate("Application", "User"))
self.tweets_content_label.setText(_translate("Application", "Content"))
self.tweets_likes_label.setText(_translate("Application", "Likes"))
self.tweets_date.setText(_translate("Application", "TextLabel"))
self.tweets_date_label.setText(_translate("Application", "Date"))
self.push_button_1.setText(_translate("Application", "General"))
self.push_button_3.setText(_translate("Application", "Tweets"))
self.push_button_2.setText(_translate("Application", "Markets"))
self.tracker_names_6.setText(_translate("Application", "S©️RAPED Beta"))
self.label_datetime.setText(_translate("Application", "Datetime:"))
self.label_time.setText(_translate("Application", "NO TIME FOUND"))
from mplwidget import MplWidget
|
import pandas as pd
import numpy as np
from collections import defaultdict
import math
from datetime import datetime
from tqdm import tqdm
import librosa
from sklearn.preprocessing import scale
class Sun:
"""This class is made up of several functions,
the main ones take as input latitude,longitude and a date and calculate the sunrise and sunset times,
while the third takes as input a date which is a string and returns a datatime."""
def getSunriseTime( self, data, coords ):
return self.calcSunTime( data,coords, True )
def getSunsetTime( self, data, coords ):
return self.calcSunTime( data,coords, False )
def getCurrentUTC( self, data):
data = data.split('-')
if data[2] == '00':
data[2] = '01'
data = '-'.join(data)
data = datetime.strptime(data, '%Y-%m-%d')
return [ data.day, data.month, data.year ]
def calcSunTime( self, data, coords, isRiseTime, zenith = 90.8 ):
# isRiseTime == False, returns sunsetTime
day, month, year = self.getCurrentUTC(data)
longitude = coords['longitude']
latitude = coords['latitude']
TO_RAD = math.pi/180
#1. first calculate the day of the year
N1 = math.floor(275 * month / 9)
N2 = math.floor((month + 9) / 12)
N3 = (1 + math.floor((year - 4 * math.floor(year / 4) + 2) / 3))
N = N1 - (N2 * N3) + day - 30
#2. convert the longitude to hour value and calculate an approximate time
lngHour = longitude / 15
if isRiseTime:
t = N + ((6 - lngHour) / 24)
else: #sunset
t = N + ((18 - lngHour) / 24)
#3. calculate the Sun's mean anomaly
M = (0.9856 * t) - 3.289
#4. calculate the Sun's true longitude
L = M + (1.916 * math.sin(TO_RAD*M)) + (0.020 * math.sin(TO_RAD * 2 * M)) + 282.634
L = self.forceRange( L, 360 ) #NOTE: L adjusted into the range [0,360)
#5a. calculate the Sun's right ascension
RA = (1/TO_RAD) * math.atan(0.91764 * math.tan(TO_RAD*L))
RA = self.forceRange( RA, 360 ) #NOTE: RA adjusted into the range [0,360)
#5b. right ascension value needs to be in the same quadrant as L
Lquadrant = (math.floor( L/90)) * 90
RAquadrant = (math.floor(RA/90)) * 90
RA = RA + (Lquadrant - RAquadrant)
#5c. right ascension value needs to be converted into hours
RA = RA / 15
#6. calculate the Sun's declination
sinDec = 0.39782 * math.sin(TO_RAD*L)
cosDec = math.cos(math.asin(sinDec))
#7a. calculate the Sun's local hour angle
cosH = (math.cos(TO_RAD*zenith) - (sinDec * math.sin(TO_RAD*latitude))) / (cosDec * math.cos(TO_RAD*latitude))
if cosH > 1:
return {'status': False, 'msg': 'the sun never rises on this location (on the specified date)'}
if cosH < -1:
return {'status': False, 'msg': 'the sun never sets on this location (on the specified date)'}
#7b. finish calculating H and convert into hours
if isRiseTime:
H = 360 - (1/TO_RAD) * math.acos(cosH)
else: #setting
H = (1/TO_RAD) * math.acos(cosH)
H = H / 15
#8. calculate local mean time of rising/setting
T = H + RA - (0.06571 * t) - 6.622
#9. adjust back to UTC
UT = T - lngHour
UT = self.forceRange( UT, 24) # UTC time in decimal format (e.g. 23.23)
#10. Return
hr = self.forceRange(int(UT), 24)
min = round((UT - int(UT))*60,0)
return {
'status': True,
'decimal': UT,
'hr': hr,
'min': min
}
def forceRange( self, v, max ):
# force v to be >= 0 and < max
if v < 0:
return v + max
elif v >= max:
return v - max
return v
class Cleaner():
"""
This class adjustes some issues that came up after reading the DataFrame for the first time.
Input:
df: the pandas DataFrame containg all the info.
"""
def __init__(self, df):
self.df = df
def transform_columns(self):
"""
This function adjusts some troubles due to wrong data types
and add an extra column to check if a bird is alone in a recording
"""
self.df.elevetaion = self.df.elevetaion.apply(lambda x: int(x) if (x and x.isdigit()) else np.nan)
self.df.latitude = self.df.latitude.apply(lambda x: np.nan if x == 'Not specified' else float(x) * np.pi/180)
self.df.longitude = self.df.longitude.apply(lambda x: np.nan if x == 'Not specified' else float(x) * np.pi/180)
is_alone = self.df.background.apply(lambda x: 'yes' if not x else 'no') # alone = 0
self.df.insert(9, 'is_alone', is_alone)
self.df.loc[self.df['common_name'] == '(?) Mallard', 'common_name'] = 'Mallard'
def clean_type(self, row):
"""
This function check the tags present in agiven column and assign each to the corresponding list.
Input: a row of the pandas df.
"""
# Define the columns domain:
calls = set(['uncertain', 'song', 'subsong', 'call', 'alarm call', 'flight call', 'nocturnal flight call',
'begging call', 'drumming', 'duet', 'dawn song'])
sex = set(['male', 'female', 'sex uncertain'])
stage = set(['adult', 'juvenile', 'hatchling or nestling', 'life stage uncertain'])
special = set(['aberrant', 'mimicry/imitation', 'bird in hand'])
# Start selection:
ca = []
se = []
st = []
sp = []
for tag in row.split(','):
tag = tag.strip()
if tag in calls and tag != 'uncertain':
ca.append(tag)
elif tag in sex and tag != 'sex uncertain':
se.append(tag)
elif tag in stage and tag != 'life stage uncertain':
st.append(tag)
elif tag in special:
sp.append(tag)
return ca, se, st, sp
def transform_lst(self, lst):
"""
Given the length of the list the function decides what to do with it,
ongly if the list is made of only one arguments it is transformed in string.
Otherwise, it returns nan.
Input:
lst: a list of strings (tags) of given ctegory (see the clean_type function for the classes)
output:
new: a string containing the tag
"""
if len(lst) > 1:
new = np.NaN
return new
elif len(lst) == 1:
new = lst[0]
return new
elif len(lst) == 0:
new = np.NaN
return new
def add_type_columns(self):
"""
This function analyze tags in type column, for each row
and generates a column for each tag with the given tag if exists or nan
"""
tags = defaultdict(list)
for row in tqdm(self.df['type'], desc = 'Generate type columns'):
# Add the tag to the corresponding column lst:
ca, se, st, sp = self.clean_type(row)
# Add the tags of the row to the dictionary:
ca = self.transform_lst(ca)
tags['call'].append(ca)
se = self.transform_lst(se)
tags['sex'].append(se)
st = self.transform_lst(st)
tags['stage'].append(st)
sp = self.transform_lst(sp)
tags['special'].append(sp)
type_df = pd.DataFrame.from_dict(tags)
self.df = pd.concat([self.df.iloc[:,0:10], type_df, self.df.iloc[:,11:]], axis = 1)
def calc_gio_not(self):
"""This function takes as input the date, time, latitude and longitude of the observation of a bird,
recalls the functions of the sun class to calculate the time of sunrise and sunset and checks if the observation time is between the two.
the function returns a string 'day' if it is true otherwise it returns the string 'night'."""
gio_not = []
sun = Sun()
for oss in tqdm(self.df.iloc[:,0:15].itertuples(), desc = 'Calculate day-night', total=len(self.df)):
date = oss.date
time = oss.time
lon = oss.longitude
lat = oss.latitude
try:
coords = {'longitude' : lon, 'latitude' : lat }
d_alb = sun.calcSunTime(date,coords,True)
ore_alb,min_alb = d_alb['hr'],d_alb['min']
d_tram = sun.calcSunTime(date,coords,False)
ore_tram,min_tram = d_tram['hr'],d_tram['min']
if time == '?':
gio_not.append(np.NaN)
else:
time_ore,time_min = time.split(":")
if time_min == '00am':
time_min = '00'
elif time_min == '30am':
time_min = '30'
elif time_min == '30pm':
time_min = '30'
time_ore = int(time_ore)
time_min = int(time_min)
if time_ore < ore_tram and time_ore > ore_alb:
gio_not.append('giorno')
elif time_ore == ore_alb:
if time_min >= min_alb:
gio_not.append('giorno')
else:
gio_not.append('notte')
elif time_ore == ore_tram:
if time_min < min_tram:
gio_not.append('giorno')
else:
gio_not.append('notte')
else:
gio_not.append('notte')
except:
gio_not.append(np.NaN)
self.df.insert(9,"gio_not",gio_not)
def emisphere(self,lat):
"""This function takes as input the latitude of the place where the bird was observed
if it is greater than 0 return that was observed in the northern hemisphere otherwise in the southern one."""
if lat >= 0:
e = 'north'
else:
e = 'sud'
return e
def season(self,data, HEMISPHERE):
"""This function takes date and hemisphere as input.
From the date it extracts the day and month in order to calculate
in which season of the year the observation took place."""
seasons = {0: 'spring',
1: 'summer',
2: 'fall',
3: 'winter'}
s = Sun()
date = s.getCurrentUTC(data)
md = date[1] * 100 + date[0]
if ((md > 320) and (md < 621)):
se = 0 #spring
elif ((md > 620) and (md < 923)):
se = 1 #summer
elif ((md > 922) and (md < 1223)):
se = 2 #fall
else:
se = 3 #winter
if not HEMISPHERE == 'north':
se = (se + 2) % 3
return seasons[se]
def calc_season(self):
"Final function that uses the previous two to save season information in the DataFrame"
season_lis = []
for oss in tqdm(self.df.iloc[:,0:16].itertuples(), desc = 'Calculate Season', total=len(self.df)):
date = oss.date
lat = oss.latitude
if not lat:
season_lis.append(np.NaN)
else:
e = self.emisphere(lat)
s = self.season(date,e)
season_lis.append(s)
self.df.insert(10,"season",season_lis)
def binning_elev(self, el):
"""
This function helps to transform elevation in a dummy variable,
for each passed row it determinates in which bin the value is.
Input:
el: an int which represents the elevation
Output:
binn: a string representing the given bin
"""
if el <= 240:
binn = 'bassa'
elif 240 < el <= 500:
binn = 'media'
else:
binn = 'alta'
return binn
def generate_final_db(self):
"""
This function calls all the previous ones and adjusts the DataFrame.
output:
df: the cleaned df
"""
self.add_type_columns()
self.transform_columns()
self.df['elevetaion'] = self.df.elevetaion.apply(lambda x: self.binning_elev(x))
self.df = self.df.rename({'elevetaion':'elevation'}, axis=1)
self.calc_gio_not()
self.calc_season()
return self.df
class Audio_Processing():
"""
This class works only on the waveform and transforms it thanks to Fourier transform
or MCCS, depending on what we want.
"""
def __init__(self, df, quality_rate, hop_length, bins, low_cut, high_cut):
self.df = df.iloc[:,17:]
is_nan = self.df.isnull()
nan_rows = is_nan.all(axis = 1)
self.df = self.df[[not i for i in nan_rows]]
self.df = self.df.fillna(0)
self.other_df = df.iloc[:,:17]
self.tempo = [i/22050 for i in range(df.shape[1])]
self.dt = 1/quality_rate
self.quality_rate = quality_rate
self.hop_length = hop_length
self.bins = bins
self.low_cut = low_cut
self.high_cut = high_cut
def fft_filter(self, signal):
"""
The function use the fast fourier transform to obtain the frequencies power spectrum for each audio,
then it define a threshold given by average + standard deviation of the power spectrum to filter
some noise from the audio.
Input:
signal: the audio wave form
Output:
f_filt: the filtered signal
"""
n = len(self.tempo)
# Calculate Power Spectrum:
fhat = np.fft.fft(signal, n)
PSD = fhat * np.conj(fhat) / n
L = np.arange(1, np.floor(n/2), dtype = int)
# Get info to use to filter:
freq = (1/(self.dt * n)) * np.arange(n)
av, sd = PSD[L].mean(), PSD[L].std() # calcola avg e sd dei PSD
# Filter the signal:
indices = (PSD > av + sd) & (freq >= 4500) # Lista di filtri
fhat_to_inverse = fhat * indices # Filtraggio fourier
f_filt = np.fft.ifft(fhat_to_inverse) # Trasformata inversa (da frequenze a tempo)
return f_filt
def get_mel(self, rows):
"""
The function generates a set of MEL cepstral coefficients and the
Delta-spectral cepstral coefficients
Input:
rows: the audio signal once preprocessed
Output:
mfcc_concat: a numpy array where are concatenated mfcc and delta-scc
"""
# Generate MEL and Delta:
signal = np.array(rows, dtype = np.float32)
signal = np.absolute(self.fft_filter(signal))
mfcc = librosa.feature.mfcc(y = signal, sr = self.quality_rate, n_fft = 2048,
hop_length = self.hop_length, n_mfcc = 20)
mfcc_delta = librosa.feature.delta(mfcc)
# Flatten and concatenate:
mfcc = mfcc.flatten('C')
mfcc_delta = mfcc_delta.flatten('C')
mfcc_concat = np.concatenate([mfcc, mfcc_delta])
return mfcc_concat
def return_ffts(self, ffts_len, decibel = False, mel_scale = True):
"""Returns the fft in original scale or decibel. The len of the fft should be specified.
Can either be decibel of Mel scale. Acts on the waveform part of df.
Input:
ffts_len: integer len of the final array
decibel: bool value , if returning in decibel the spectrum
mel_scale: bool value , if returning in Mel scale the spectrum
Output:
ffts: matrix of the transformed waveforms
"""
ffts = np.empty((self.df.shape[0], ffts_len))
wf_matrix = self.df.values
for i in tqdm(range(wf_matrix.shape[0]), desc = 'Fourier Transformation'):
last_idx = np.sum(~np.isnan(wf_matrix[i]))
ffts[i] = np.abs(np.fft.fft(wf_matrix[i, :last_idx], n=ffts_len))
ffts = ffts[:, : ffts.shape[1]//2]
ffts = ffts[:, self.low_cut:self.high_cut]
if decibel:
ffts = np.log(1+ffts)
elif mel_scale:
ffts = 2595*np.log(1+ffts/700)
return ffts
def eval_spectral_centroid(self, freq):
""" Function that evaluates the spectral centroid.
Input:
freq: array of a single spectrum
Output:
centroid: flaot with the centroid of the spectrum
"""
return np.sum(np.arange(self.low_cut, self.high_cut, 1)*freq)/np.sum(freq)
def bin_data(self, original_idx = False):
"""Function that returns the binned data in matrix form. Original_idx returns also the indices in the original scale.
Acts on the waveform part of df in matrix form.
Input:
original_idx: bool, if returning or not the original index scale
Output:
binned_data: matrix of the binned data
original_idx: array with the original scale if in input original_idx=True
"""
bins_idx = np.linspace(0, self.df.shape[1], self.bins+1).astype(int)
binned_data = np.empty((self.df.shape[0], self.bins))
for i in tqdm(range(1, self.bins + 1), desc = 'Get Bins'):
binned_data[:,i-1] = np.mean(self.df[:,bins_idx[i-1]:bins_idx[i]], axis=1)
#binned_data[:,i-1] = np.quantile(self.df[:,bins_idx[i-1]:bins_idx[i]],0.99, axis=1)
#binned_data[:,i-1] = np.max(self.df[:,bins_idx[i-1]:bins_idx[i]], axis=1)
if original_idx:
return binned_data, bins_idx[:-1]
else:
return binned_data
def transform_df(self, mel = False):
"""
This function get the orginal waveform and trasform it to mels if mel = True or
if mel = False it does the fourier tansformation, bin the data and scale them, then adds
also the centroids.
Output:
final: a dataframe with the the tansformed columns (concerning only the waveform).
"""
if mel:
tqdm.pandas()
df = self.df.progress_apply(lambda row: self.get_mel(row), axis = 1, result_type = 'expand')
df.columns = ['mel_' + str(i) for i in range(df.shape[1])]
final = pd.concat([self.other_df, df], axis = 1)
else:
ffts_len = self.df.shape[1]
self.df= self.return_ffts(ffts_len)
final = self.bin_data()
final = scale(final, axis = 1)
final = pd.DataFrame(final, columns = ['bin_' + str(i) for i in range(final.shape[1])])
final['centroids'] = np.apply_along_axis(self.eval_spectral_centroid, 1, self.df)
final = pd.concat([self.other_df, final], axis = 1)
return final
|
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import unicode_literals
from django.contrib.auth.admin import User
from django.contrib.auth.decorators import login_required
from django.forms.models import inlineformset_factory
from django.shortcuts import render, HttpResponseRedirect
from .forms import EditProfileForm, EditUserProfileForm, CustomLoginForm, CustomSignup
from .models import UserProfile
from plateform.models import BlogPost as posts
from django.shortcuts import reverse
from allauth.account.views import SignupView, AjaxCapableProcessFormViewMixin
from allauth.socialaccount.helpers import SocialLogin
from allauth.account.utils import messages
from allauth.socialaccount.views import SignupView as SocialSignupView
class CustomSocialSignupView(SocialSignupView):
def dispatch(self, request, *args, **kwargs):
self.sociallogin = None
data = request.session.get('socialaccount_sociallogin')
if data:
self.sociallogin = SocialLogin.deserialize(data)
if not self.sociallogin:
return HttpResponseRedirect(reverse('portal'))
# if exists account with same email, redirect to login page with message
user_email = self.sociallogin.user.email
try:
user = User.objects.get(email=user_email)
messages.error(request, (
'للاسف لم تتمكن من تسجيل دخولك عبر الفايسبوك البريد الالكتروني المستخدم مسجل بحساب آخر من قبل يرجى انشاء حساب او تسجيل الدخول'),
extra_tags='safe')
return HttpResponseRedirect(reverse('portal'))
except User.DoesNotExist:
return super(SignupView, self).dispatch(request, *args, **kwargs)
class CustomSignupView(SignupView, AjaxCapableProcessFormViewMixin):
# here we add some context to the already existing context
def get_context_data(self, **kwargs):
# we get context data from original view
context = super(CustomSignupView,
self).get_context_data(**kwargs)
context['login_form'] = CustomLoginForm() # add form to context
context['form'] = CustomSignup()
return context
def profile(request, username):
user = User.objects.get(username=username)
related = posts.objects.filter(author=user)
args = {
'user': user,
'related': related
}
return render(request, 'profile/profile.html', args)
@login_required(login_url='/accounts/portal')
def edit_profile(request):
user = request.user
user_form = EditProfileForm(instance=user)
ProfileInlineFormset = inlineformset_factory(User, UserProfile, form=EditUserProfileForm, can_delete=False)
formset = ProfileInlineFormset(instance=user)
if request.user == user:
if request.method == "POST":
user_form = EditProfileForm(request.POST, request.FILES, instance=user)
formset = ProfileInlineFormset(request.POST, request.FILES, instance=user)
created_user = user_form.save(commit=False)
if formset.is_valid() and user_form.is_valid():
formset = ProfileInlineFormset(request.POST, request.FILES, instance=created_user)
created_user.save()
formset.save()
return HttpResponseRedirect('/accounts/u/' + user.username)
return render(request, "profile/user_update.html",
{"user_form": user_form, 'formset': list(formset[0]), 'management': formset.management_form})
|
# shopping_cart.py
import operator
import pandas
from datetime import datetime
import os
from dotenv import load_dotenv
import csv
load_dotenv()
def to_usd(my_price):
return f"${my_price:,.2f}" #> $12,000.71
"""
Converts a numeric value to usd-formatted string, for printing and display purposes.
Source: https://github.com/prof-rossetti/intro-to-python/blob/master/notes/python/datatypes/numbers.md#formatting-as-currency
Param: my_price (int or float) like 4000.444444
Example: to_usd(4000.444444)
Returns: $4,000.44
"""
products = [
{"id":1, "name": "Chocolate Sandwich Cookies", "department": "snacks", "aisle": "cookies cakes", "price": 3.50},
{"id":2, "name": "All-Seasons Salt", "department": "pantry", "aisle": "spices seasonings", "price": 4.99},
{"id":3, "name": "Robust Golden Unsweetened Oolong Tea", "department": "beverages", "aisle": "tea", "price": 2.49},
{"id":4, "name": "Smart Ones Classic Favorites Mini Rigatoni With Vodka Cream Sauce", "department": "frozen", "aisle": "frozen meals", "price": 6.99},
{"id":5, "name": "Green Chile Anytime Sauce", "department": "pantry", "aisle": "marinades meat preparation", "price": 7.99},
{"id":6, "name": "Dry Nose Oil", "department": "personal care", "aisle": "cold flu allergy", "price": 21.99},
{"id":7, "name": "Pure Coconut Water With Orange", "department": "beverages", "aisle": "juice nectars", "price": 3.50},
{"id":8, "name": "Cut Russet Potatoes Steam N' Mash", "department": "frozen", "aisle": "frozen produce", "price": 4.25},
{"id":9, "name": "Light Strawberry Blueberry Yogurt", "department": "dairy eggs", "aisle": "yogurt", "price": 6.50},
{"id":10, "name": "Sparkling Orange Juice & Prickly Pear Beverage", "department": "beverages", "aisle": "water seltzer sparkling water", "price": 2.99},
{"id":11, "name": "Peach Mango Juice", "department": "beverages", "aisle": "refrigerated", "price": 1.99},
{"id":12, "name": "Chocolate Fudge Layer Cake", "department": "frozen", "aisle": "frozen dessert", "price": 18.50},
{"id":13, "name": "Saline Nasal Mist", "department": "personal care", "aisle": "cold flu allergy", "price": 16.00},
{"id":14, "name": "Fresh Scent Dishwasher Cleaner", "department": "household", "aisle": "dish detergents", "price": 4.99},
{"id":15, "name": "Overnight Diapers Size 6", "department": "babies", "aisle": "diapers wipes", "price": 25.50},
{"id":16, "name": "Mint Chocolate Flavored Syrup", "department": "snacks", "aisle": "ice cream toppings", "price": 4.50},
{"id":17, "name": "Rendered Duck Fat", "department": "meat seafood", "aisle": "poultry counter", "price": 9.99},
{"id":18, "name": "Pizza for One Suprema Frozen Pizza", "department": "frozen", "aisle": "frozen pizza", "price": 12.50},
{"id":19, "name": "Gluten Free Quinoa Three Cheese & Mushroom Blend", "department": "dry goods pasta", "aisle": "grains rice dried goods", "price": 3.99},
{"id":20, "name": "Pomegranate Cranberry & Aloe Vera Enrich Drink", "department": "beverages", "aisle": "juice nectars", "price": 4.25}
] # based on data from Instacart: https://www.instacart.com/datasets/grocery-shopping-2017
print("")
print("WELCOME TO THE GEORGETOWN GROCERY STORE")
print("")
# user INPUT of data
# list holds all the information of the products selected by the user (created using append)
selected_products = []
while True:
prod_id = input("Please input product identifier, or 'DONE' if there are no more items: ")
if prod_id == "DONE":
break
else:
prod_id = int(prod_id)
matching_products = [p for p in products if p["id"] == prod_id]
# validation to check if product exists in the list of products
try:
matching_product = matching_products[0]
print("+ ", matching_product["name"], "(", to_usd(matching_product["price"]), ")")
selected_products.append(matching_product)
except IndexError:
print("Product doesn't exist! Please select another product.")
# computer OUTPUT of results
dateTimeObj = datetime.now() # Returns a datetime object containing the local date and time
subtotal = 0
print("--------------------------------")
print("GEORGETOWN GROCERY STORE")
print("--------------------------------")
print("Website: www.gugrocery.com")
print("Phone: 202-660-3650")
print("DATE: ", dateTimeObj.year, '/', dateTimeObj.month, '/', dateTimeObj.day)
print("TIME: ", dateTimeObj.hour, ':', dateTimeObj.minute)
print("--------------------------------")
print("PRODUCT DETAILS:")
# loop to print products and prices on the receipt
for prod in selected_products:
print("+ ", prod["name"], "(", to_usd(prod["price"]), ")")
price = prod["price"]
subtotal = subtotal + price
print("--------------------------------")
print("SUBTOTAL:", to_usd(subtotal))
# use the tax amount from the .env file
tax = os.getenv("state_tax")
tax = float(tax)
tax_amt = subtotal * tax
print("TAX (", tax * 100, "%): ", to_usd(tax_amt))
total_price = subtotal + tax_amt
print("TOTAL PRICE:", to_usd(total_price))
print("--------------------------------")
print("Thank you for shopping with us!")
print("We hope to see you again soon!")
print("********************************")
# name of the .txt file in which the receipt is written/stored/printed
file_name = "receipts/" + str(dateTimeObj.year) + "-" + str(dateTimeObj.month) + "-" + str(dateTimeObj.day) + "-" + str(dateTimeObj.hour) + "-" + str(dateTimeObj.minute) + "-" + str(dateTimeObj.second) + "-" + str(dateTimeObj.microsecond) + ".txt"
# convert dateTimeObj to str so it can be printed on receipt
year = str(dateTimeObj.year)
month = str(dateTimeObj.month)
day = str(dateTimeObj.day)
hour = str(dateTimeObj.hour)
minute = str(dateTimeObj.minute)
second = str(dateTimeObj.second)
# opens a new .txt file and writes the receipt in it.
with open(file_name, 'w') as file:
file.write("--------------------------------")
file.write("\n")
file.write("GEORGETOWN GROCERY STORE")
file.write("\n")
file.write("--------------------------------")
file.write("\n")
file.write("Website: www.gugrocery.com")
file.write("\n")
file.write("Phone: 202-660-3650")
file.write("\n")
file.write("DATE: ")
file.write(year)
file.write("/")
file.write(month)
file.write("/")
file.write(day)
file.write("\n")
file.write("TIME: ")
file.write(hour)
file.write(":")
file.write(minute)
file.write("\n")
file.write("--------------------------------")
file.write("\n")
file.write("PRODUCT DETAILS:")
file.write("\n")
for prod in selected_products:
file.write("+ ")
file.write(prod["name"])
file.write("(")
file.write(to_usd(prod["price"]))
file.write(")")
file.write("\n")
file.write("--------------------------------")
file.write("\n")
file.write("SUBTOTAL: ")
file.write(to_usd(subtotal))
file.write("\n")
tax = os.getenv("state_tax")
tax = float(tax)
tax_amt = subtotal * tax
file.write("TAX (")
tax = (tax * 100)
tax = str(tax)
file.write(tax)
file.write("%): ")
file.write(to_usd(tax_amt))
file.write("\n")
total_price = subtotal + tax_amt
file.write("TOTAL PRICE: ")
file.write(to_usd(total_price))
file.write("\n")
file.write("--------------------------------")
file.write("\n")
file.write("Thank you for shopping with us!")
file.write("\n")
file.write("We hope to see you again soon!")
file.write("\n")
file.write("********************************") |
from math import ceil
ari_scale = {
1: {'ages': '5-6', 'grade_level': 'Kindergarten'},
2: {'ages': '6-7', 'grade_level': '1st Grade'},
3: {'ages': '7-8', 'grade_level': '2nd Grade'},
4: {'ages': '8-9', 'grade_level': '3rd Grade'},
5: {'ages': '9-10', 'grade_level': '4th Grade'},
6: {'ages': '10-11', 'grade_level': '5th Grade'},
7: {'ages': '11-12', 'grade_level': '6th Grade'},
8: {'ages': '12-13', 'grade_level': '7th Grade'},
9: {'ages': '13-14', 'grade_level': '8th Grade'},
10: {'ages': '14-15', 'grade_level': '9th Grade'},
11: {'ages': '15-16', 'grade_level': '10th Grade'},
12: {'ages': '16-17', 'grade_level': '11th Grade'},
13: {'ages': '17-18', 'grade_level': '12th Grade'},
14: {'ages': '18-22', 'grade_level': 'College'}
}
punc = {'!':'', '.':'', ',':'', ';':'', ':':'', '?':'', "'":'', '"':'', '-':' ', '“':'', '”':'', '‘':'', '’':''}
def sentence_count(text):
sentence = 0
for i in text:
if i == '.' or i == '?' or i == '!':
sentence += 1
return sentence
def remove_punc(dic,string):
for key, value in dic.items():
string = string.replace(key,value)
return string
def char_count(text):
string = remove_punc(punc,text)
string = string.replace(' ','').replace('\n','')
count = len(string)
return count
def word_count(text):
string = remove_punc(punc,text)
lst = string.split()
count = len(lst)
return count
def read_text(file):
with open(file, 'r', encoding='utf-8') as f:
content = f.read()
return content
def ari_score(file):
text = read_text(file)
score = ceil(4.71 * (char_count(text) / word_count(text)) + .5 * (word_count(text)/sentence_count(text)) - 21.43)
print('The ARI for "{}" is {}.\nThis corresponds to a {} level of difficulty that is suitable for an average person {} years old.'.format(file, score, ari_scale[score]['grade_level'], ari_scale[score]['ages']))
file = 'hound-of-baskervilles.txt'
ari_score(file)
|
# coding: utf-8
from collections import Counter
import itertools
import os
import operator
import pickle
import sqlite3
import string
import time
import jieba
import more_itertools
import numpy as np
import zhon.hanzi as zh
CUR_DIR = os.path.dirname(__file__)
PARENT_PATH = os.path.dirname(CUR_DIR)
VOCAB2IX_PATH = os.path.join(PARENT_PATH, 'data', 'vocab2ix.pkl')
IX2VOCAB_PATH = os.path.join(PARENT_PATH, 'data', 'ix2vocab.pkl')
STOPWORDS_PATH = os.path.join(PARENT_PATH, 'data', 'stop_words_chinese.txt')
def read_stopwords(filename):
with open(filename, 'r') as file:
stopwords = file.read().splitlines()
return stopwords
def read_data(filename):
with open(filename) as file:
sequences = file.read().splitlines()
for sequence in sequences:
line = sequence.split('\t')
yield line
def jieba_cut(sequences):
jieba.setLogLevel(20)
jieba.enable_parallel(8)
for sequence in sequences:
data = jieba.cut(sequence)
yield ' '.join(data)
def clean_data(sequences, stopwords):
sequences = (''.join(c for c in x if c not in string.punctuation)
for x in sequences)
sequences = (''.join(c for c in x if c not in zh.punctuation)
for x in sequences)
sequences = (x.split() for x in sequences)
sequences = ([c for c in x if c] for x in sequences)
sequences = ([c for c in x if c not in stopwords] for x in sequences)
return sequences
def get_common_words(words, n):
count = Counter(words)
count_dict = {key: value for key, value in count.items() if value > n}
word_counts = sorted(count_dict.items(),
key=operator.itemgetter(1), reverse=True)
return word_counts
def build_dict(word_counts):
count = [['<UNK>', -1]]
count.extend(word_counts)
vocab2ix = {key: ix for ix, (key, _) in enumerate(count)}
ix2vocab = {value: key for key, value in vocab2ix.items()}
return vocab2ix, ix2vocab
def word_to_number(sequences, word_dict):
data = []
for sequence in sequences:
sequence_data = []
for word in sequence:
try:
sequence_data.append(word_dict[word])
except:
sequence_data.append(0)
data.append(sequence_data)
return data
def pad_crop(sequences, n):
for sequence in sequences:
sequence = more_itertools.padded(
sequence, fillvalue=0, n=n)
sequence = list(itertools.islice(sequence, n))
yield sequence
def save_dict(obj, filename):
with open(filename, 'wb') as output:
pickle.dump(obj, output, pickle.HIGHEST_PROTOCOL)
def load_dict(vocab2ix_path, ix2vacab_path):
with open(vocab2ix_path, 'rb') as f1, open(ix2vacab_path, 'rb') as f2:
vocab2ix = pickle.load(f1)
ix2vocab = pickle.load(f2)
return vocab2ix, ix2vocab
def get_clean_data(path, stopwords):
data = list(zip(*read_data(path)))
sentiment = data[1]
cut_words = jieba_cut(data[0])
# 流向两个地方,1 是制造 word_dict, 2 是转为 numbers
clean_words = list(clean_data(cut_words, stopwords))
return clean_words, sentiment
def build_dataset(train_path, test_path, stopwords_path, n=10, max_words=20):
"""A function to build dataset and save them."""
print('Building dataset...')
# Get words and sentiment
start = time.time()
stopwords = read_stopwords(stopwords_path)
words_train, sentiment_train = get_clean_data(train_path, stopwords)
words_test, sentiment_test = get_clean_data(test_path, stopwords)
data = itertools.chain(words_train, words_test)
words = itertools.chain.from_iterable(data)
# Words to numbers
word_counts = get_common_words(words, n)
vocab2ix, ix2vocab = build_dict(word_counts)
save_dict(vocab2ix, VOCAB2IX_PATH)
save_dict(ix2vocab, IX2VOCAB_PATH)
text_train = word_to_number(words_train, vocab2ix)
text_test = word_to_number(words_test, vocab2ix)
# Pad/crop sequence
text_data_train = np.array(
list(pad_crop(text_train, max_words)))
text_data_test = np.array(
list(pad_crop(text_test, max_words)))
# Get sentiment data
sentiment_data_train = np.fromiter(sentiment_train, int).reshape((-1, 1))
sentiment_data_test = np.fromiter(sentiment_test, int).reshape((-1, 1))
# Concat text and sentiment
train_data = np.concatenate((text_data_train, sentiment_data_train), axis=1)
test_data = np.concatenate((text_data_test, sentiment_data_test), axis=1)
# Save data
train_data_path = os.path.join(PARENT_PATH, 'data', 'train_data.txt')
test_data_path = os.path.join(PARENT_PATH, 'data', 'test_data.txt')
np.savetxt(train_data_path, train_data, fmt='%d')
np.savetxt(test_data_path, test_data, fmt='%d')
stop = time.time()
print(f'Wasted {stop-start:.2f} seconds, Done!!!')
def sqltext_to_number(
X, vocab2ix_path=VOCAB2IX_PATH,
ix2vocab_path=IX2VOCAB_PATH,
stopwords_path=STOPWORDS_PATH,
max_words=20):
# Read dict and stopwords
vocab2ix, _ = load_dict(vocab2ix_path, ix2vocab_path)
stopwords = read_stopwords(stopwords_path)
# Clean data
data_cut = jieba_cut(X)
text_data = clean_data(data_cut, stopwords)
# Words to numbers
num_data = word_to_number(text_data, vocab2ix)
num_data_pad = list(pad_crop(num_data, max_words))
return np.asarray(num_data_pad)
def get_continue_train_dataset(db_path, continue_train_size):
conn = sqlite3.connect(db_path)
c = conn.cursor()
c.execute('SELECT * FROM review_db ORDER BY date DESC')
results = c.fetchmany(continue_train_size)
data = np.array(results)
X = data[:, 0]
y = data[:, 1].astype(int)
x_train = sqltext_to_number(X)
conn.close()
return x_train, y
|
# Passing a List
def greet_users(names):
"""Print a simple greeting to each user in the list."""
for name in names:
print(f"Hello, {name.title()}!")
usernames = ['vasu', 'deva', 'tiru']
greet_users(usernames) |
import os, win32api, win32con
for file in os.listdir("./"):
info = os.stat(file)
attr = win32.api.GetFileAttributes(file)
if NOT (attr & (win32con.FILE_ATTRIBUTE_SYSTEM)):
print(file)
|
# Generated by Django 3.1.3 on 2020-11-25 07:01
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('services', '0003_auto_20201124_0946'),
]
operations = [
migrations.AlterField(
model_name='service',
name='list_info1',
field=models.CharField(max_length=50),
),
]
|
import scrapy
from scrapy.spiders import CrawlSpider, Rule
from scrapy.linkextractors import LinkExtractor
from jandan_xxoo.items import JandanItem
class JandanSpider(CrawlSpider):
name = 'jandan.net'
allowed_domains = ['jandan.net']
start_urls = [
'http://jandan.net/ooxx'
]
rules = (
Rule(LinkExtractor(allow=('.*?/ooxx/page-\d+.*?')), callback='parse_page', follow=True),
)
def parse_page(self, response):
# self.logger.info('A response from %s just arrived!', response.url)
for sel in response.xpath('//ol[@class="commentlist"]/li//div[@class="row"]'):
item = JandanItem()
item['author'] = sel.xpath('div[@class="author"]/strong/text()').extract()
item['id'] = sel.xpath('div[@class="text"]/span/a/text()').extract()
item['image_urls'] = sel.xpath('div[@class="text"]/p/a[@class="view_img_link"]/@href').extract()
item['like'] = sel.xpath('div[@class="text"]/div[@class="vote"]/span[2]/text()').extract()
item['dislike'] = sel.xpath('div[@class="text"]/div[@class="vote"]/span[3]/text()').extract()
yield item |
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
# 等高线画法
# https://www.pynote.info/entry/matplotlib-contour
# def f(x, y):
# return x ** 2 + y ** 2
#
# # X, Y = np.mgrid[-10:11, -10:11]
# X, Y = np.mgrid[-2:2, -2:2]
# print(X)
# # 配列転置
# # print(Y.T)
# print(Y)
#
# Z = f(X, Y)
# print(Z)
#
# # 描画範囲を10段階に分けるように等高線を作成する。
# fig, ax = plt.subplots(figsize=(6, 6), facecolor="w")
# ax.contour(X, Y, Z, levels=5)
# Figureタイトルを設定
# fig.suptitle("contour Functions", fontsize=20)
# Axesのタイトルの設定
# ax.set_title("Contours", size=20, color="red")
# ax.set_xlabel("x", size=20)
# ax.set_ylabel("y", size=20)
# plt.show()
# -------------------------------------------------------------------
def f(x, y):
return x ** 2 + y ** 2
X, Y = np.mgrid[-12:12, -12:12]
Z = f(X, Y)
# f(x, y) = 0, 10, 50, 100, 200 となる等高線を作成する。
fig, ax = plt.subplots(figsize=(7, 7), facecolor="w")
ax.contour(X, Y, Z, levels=[0, 10, 50, 100, 200])
# Figureタイトルを設定
# fig.suptitle("contour Functions", fontsize=20)
# Axesのタイトルの設定
ax.set_title("Contours", size=20, color="red")
ax.set_xlabel("x", size=20)
ax.set_ylabel("y", size=20)
plt.show()
|
"""
argparse
import argparse
parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('integers', metavar='N', type=int, nargs='+',
help='an integer for the accumulator')
parser.add_argument('--sum', dest='accumulate', action='store_const',
const=sum, default=max,
help='sum the integers (default: find the max)')
args = parser.parse_args()
print(args.accumulate(args.integers))
"""
class Bar:
A = "trololo"
@property
def foo(self):
return self.x
@foo.setter
def foo(self, value):
self.x = value ** 2
@foo.deleter
def foo(self):
del self.x
# bar = Bar()
# print(bar.__dict__)
# bar.foo = 5
# print(bar.__dict__)
# print(bar.foo)
# class Bar3:
# def __get__(self, obj, cls=None):
# pass
# def __set__(self, obj, value):
# pass
# def __delete__(self, obj):
# pass
# garbage collector почитати
# дескриптор данных(get, set)
class Property:
def __init__(self, getter, setter, deletter):
self.g = getter
self.s = setter
self.d = deletter
def __get__(self, obj, cls=None):
if self.g is None:
raise AttributeError
return self.g(obj)
def __set__(self, obj, value):
if self.s is None:
raise AttributeError
self.s(obj, value)
def __delete__(self, obj):
if self.d is None:
raise AttributeError
self.d(obj)
class Bar2:
def get_x(self):
return self._x
def set_x(self, x):
self._x = x ** 2
def del_x(self):
del self._x
foo = Property(get_x, set_x, del_x)
# bar2 = Bar2()
# bar2.foo = 2
# print(bar2.foo)
# почитати staticmethod i classmethod i baundmethod
# class Staticmethod:
# def __init__(self, f):
# self.f = f
# def __get__(self, obj, cls=None):
# # ?????
# pass
# obj < Class < MetaClass
class Square(int):
def __new__(cls, n):
return super().__new__(cls, n ** 2)
# print(Square(5))
from collections import namedtuple
Person = namedtuple("Person", ["name", "age"])
# p = Person(name="vasia", age=25)
# print(p.name)
# print(p.age)
class Person(Person):
def __new__(cls, *a, **kw):
kw["name"] = kw["name"].title()
return super().__new__(cls, *a, **kw)
p = Person(name="vasia", age=25)
print(p.name)
|
soma=0
for i in range(20,31):
n1=int(input("Digite um número"))
soma = soma+n1
if(soma%2==0):
print(soma, "= ele é par")
else:
print(soma, "= ele é ímpar")
print(" A somatória é: ", soma)
Pressione Shift + Tab para acessar o histórico do bate-papo.
|
from models.House import House
class Infrastructure(House):
def __init__(self, area, price, rating, adress, number_of_rooms, city):
self.area = area
self.price = price
self.rating = rating
self.adress = adress
self.number_of_rooms = number_of_rooms
self.city = city
def get_is_parking(self):
return self.is_parking
def set_is_parking(self, x):
self.is_parking = x
def get_located_near(self):
return self.located_near
def set_located_near(self, x):
self.located_near = x |
from django.urls import path
from ex03 import views
urlpatterns = [
path('', views.table, name='table'),
] |
import json
import os
import tarfile
import time
import typing
import zipfile
from contextlib import suppress
from pathlib import Path
import requests
from openpyxl import load_workbook
from qtpy.QtCore import QByteArray, Qt
from qtpy.QtGui import QIcon
from qtpy.QtWidgets import (
QCheckBox,
QDialog,
QFormLayout,
QGridLayout,
QLabel,
QLineEdit,
QProgressBar,
QPushButton,
QTextEdit,
QTreeWidget,
QTreeWidgetItem,
QWidget,
)
from superqt import QCollapsible
from superqt.utils import thread_worker
from PartSeg._roi_analysis.partseg_settings import PartSettings
from PartSeg.common_backend.base_settings import IO_SAVE_DIRECTORY
from PartSeg.common_gui.custom_load_dialog import PLoadDialog, SelectDirectoryDialog
from PartSeg.common_gui.custom_save_dialog import PSaveDialog
from PartSeg.common_gui.main_window import OPEN_DIRECTORY
from PartSeg.common_gui.select_multiple_files import IO_BATCH_DIRECTORY
from PartSegCore.io_utils import LoadPlanExcel
from PartSegData import icons_dir
REQUESTS_TIMEOUT = 600
NO_FILES = "No files to export"
MISSING_FILES = "Some files do not exists"
class ExportProjectDialog(QDialog):
"""Export data for zenodo"""
def __init__(
self, excel_path: str, base_folder: str, settings: PartSettings, parent: typing.Optional[QWidget] = None
) -> None:
super().__init__(parent=parent)
self.setWindowTitle("Export batch with data")
self.settings = settings
self._all_files_exists = False
self.info_label = QLabel()
self.info_label.setVisible(False)
self.info_label.setWordWrap(True)
self.info_label.setTextFormat(getattr(Qt.TextFormat, "MarkdownText", Qt.TextFormat.AutoText))
self.info_label.setOpenExternalLinks(True)
self.excel_path = QLineEdit(excel_path)
self.base_folder = QLineEdit(base_folder)
self.zenodo_token = QLineEdit(settings.get("zenodo_token", ""))
self.zenodo_token.setToolTip(
"You can get token from https://zenodo.org/account/settings/applications/."
" The token for sandbox and production are different"
)
self.zenodo_title = QLineEdit()
self.zenodo_author = QLineEdit(settings.get("zenodo_author", ""))
self.zenodo_author.setToolTip(
"Only first author could be used from this widget. Other you need to add manually"
)
self.zenodo_affiliation = QLineEdit(settings.get("zenodo_affiliation", ""))
self.zenodo_orcid = QLineEdit(settings.get("zenodo_orcid", ""))
self.zenodo_description = QTextEdit()
self.zenodo_description.setPlaceholderText("Put your dataset description here")
self.zenodo_description.setSizeAdjustPolicy(QTextEdit.SizeAdjustPolicy.AdjustToContents)
self.zenodo_sandbox = QCheckBox()
self.zenodo_sandbox.setToolTip("Use https://sandbox.zenodo.org instead of https://zenodo.org")
self.excel_path_btn = QPushButton("Select excel file")
self.base_folder_btn = QPushButton("Select base folder")
self.info_box = QTreeWidget()
self.info_box.header().close()
self.zenodo_collapse = QCollapsible("Zenodo export")
self.export_btn = QPushButton("Export")
self.export_btn.setDisabled(True)
self.export_to_zenodo_btn = QPushButton("Export to zenodo")
self.export_to_zenodo_btn.setDisabled(True)
self.progress_bar = QProgressBar()
self.progress_bar.setVisible(False)
self.worker = None
self.zenodo_token.textChanged.connect(self._check_if_enable_zenodo_btn)
self.excel_path.textChanged.connect(self._check_if_enable_zenodo_btn)
self.base_folder.textChanged.connect(self._check_if_enable_zenodo_btn)
self.zenodo_title.textChanged.connect(self._check_if_enable_zenodo_btn)
self.zenodo_author.textChanged.connect(self._check_if_enable_zenodo_btn)
self.zenodo_affiliation.textChanged.connect(self._check_if_enable_zenodo_btn)
self.zenodo_description.textChanged.connect(self._check_if_enable_zenodo_btn)
self.excel_path.textChanged.connect(self._excel_path_changed)
self.base_folder.textChanged.connect(self._excel_path_changed)
self.base_folder_btn.clicked.connect(self.select_folder)
self.excel_path_btn.clicked.connect(self.select_excel)
self.export_btn.clicked.connect(self._export_archive)
self.export_to_zenodo_btn.clicked.connect(self._export_to_zenodo)
self._setup_ui()
def _setup_ui(self):
layout = QGridLayout()
layout.addWidget(self.info_label, 0, 0, 1, 3)
layout.addWidget(QLabel("Excel file"), 1, 0)
layout.addWidget(self.excel_path, 1, 1)
layout.addWidget(self.excel_path_btn, 1, 2)
layout.addWidget(QLabel("Base folder"), 2, 0)
layout.addWidget(self.base_folder, 2, 1)
layout.addWidget(self.base_folder_btn, 2, 2)
layout.addWidget(self.zenodo_collapse, 3, 0, 1, 3)
layout.addWidget(self.info_box, 4, 0, 1, 3)
layout.addWidget(self.progress_bar, 5, 0, 1, 3)
layout.addWidget(self.export_btn, 6, 0)
layout.addWidget(self.export_to_zenodo_btn, 6, 2)
self.setLayout(layout)
zenodo_layout = QFormLayout()
zenodo_layout.addRow("Zenodo token", self.zenodo_token)
zenodo_layout.addRow("Dataset title", self.zenodo_title)
zenodo_layout.addRow("Dataset author", self.zenodo_author)
zenodo_layout.addRow("Affiliation", self.zenodo_affiliation)
zenodo_layout.addRow("ORCID", self.zenodo_orcid)
zenodo_layout.addRow(QLabel("Description:"))
zenodo_layout.addRow(self.zenodo_description)
sandbox_label = QLabel("Upload to sandbox")
sandbox_label.setToolTip(self.zenodo_sandbox.toolTip())
zenodo_layout.addRow(sandbox_label, self.zenodo_sandbox)
widg = QWidget()
widg.setLayout(zenodo_layout)
self.zenodo_collapse.addWidget(widg)
with suppress(KeyError):
geometry = self.settings.get_from_profile("export_window_geometry")
self.restoreGeometry(QByteArray.fromHex(bytes(geometry, "ascii")))
def closeEvent(self, event) -> None:
self.settings.set_in_profile("export_window_geometry", self.saveGeometry().toHex().data().decode("ascii"))
super().closeEvent(event)
def _export_archive(self):
self.info_label.setVisible(False)
self.export_btn.setDisabled(True)
self.export_to_zenodo_btn.setDisabled(True)
dlg = PSaveDialog(
"Archive name (*.tgz *.zip *.tbz2 *.txy)",
settings=self.settings,
path=IO_SAVE_DIRECTORY,
parent=self,
)
if dlg.exec_():
self.progress_bar.setVisible(True)
self.progress_bar.setRange(0, self.info_box.topLevelItemCount() + 1)
self.progress_bar.setValue(0)
export_to_archive_ = thread_worker(
export_to_archive,
connect={
"yielded": self._progress,
"finished": self._export_finished,
"errored": self._export_errored,
"returned": self._export_returned,
},
start_thread=False,
)
self.worker = export_to_archive_(
excel_path=Path(self.excel_path.text()),
base_folder=Path(self.base_folder.text()),
target_path=Path(dlg.selectedFiles()[0]),
)
self.worker.start()
def _export_finished(self):
self.progress_bar.setVisible(False)
self.progress_bar.setValue(0)
self.worker = None
self._check_if_enable_zenodo_btn()
self._check_if_enable_export_btn()
def _export_returned(self, result):
self.info_label.setText(f"Export finished. {result}")
self.info_label.setVisible(True)
def _progress(self, value: int):
self.progress_bar.setValue(value)
def _export_to_zenodo(self):
self.info_label.setVisible(False)
self.export_btn.setDisabled(True)
self.export_to_zenodo_btn.setDisabled(True)
self.progress_bar.setVisible(True)
self.progress_bar.setRange(0, self.info_box.topLevelItemCount() + 1)
self.progress_bar.setValue(0)
export_to_zenodo_ = thread_worker(
export_to_zenodo,
connect={
"yielded": self._progress,
"finished": self._export_finished,
"errored": self._export_errored,
"returned": self._export_returned,
},
start_thread=False,
)
url = "https://zenodo.org/api/deposit/depositions"
if self.zenodo_sandbox.isChecked():
url = "https://sandbox.zenodo.org/api/deposit/depositions"
self.worker = export_to_zenodo_(
excel_path=Path(self.excel_path.text()),
base_folder=Path(self.base_folder.text()),
title=self.zenodo_title.text(),
author=self.zenodo_author.text(),
affiliation=self.zenodo_affiliation.text(),
description=self.zenodo_description.toPlainText(),
zenodo_token=self.zenodo_token.text(),
orcid=self.zenodo_orcid.text(),
zenodo_url=url,
)
self.settings.set("zenodo_token", self.zenodo_token.text())
self.settings.set("zenodo_author", self.zenodo_author.text())
self.settings.set("zenodo_affiliation", self.zenodo_affiliation.text())
self.settings.set("zenodo_orcid", self.zenodo_orcid.text())
self.worker.start()
def _export_errored(self, value):
self.info_label.setText(f"Error: {value}")
self.info_label.setVisible(True)
def _could_export(self):
dir_path = Path(self.base_folder.text())
excel_path = Path(self.excel_path.text())
return self._all_files_exists and dir_path.is_dir() and excel_path.exists() and excel_path.is_file()
def _check_if_enable_zenodo_btn(self):
self.export_to_zenodo_btn.setEnabled(
bool(
self._could_export()
and len(self.zenodo_token.text()) > 5
and self.zenodo_author.text()
and self.zenodo_affiliation.text()
and self.zenodo_title.text()
and self.zenodo_description.toPlainText()
)
)
def _check_if_enable_export_btn(self):
self.export_btn.setEnabled(self._could_export())
def select_folder(self):
dial = SelectDirectoryDialog(
settings=self.settings,
settings_path=[IO_BATCH_DIRECTORY, OPEN_DIRECTORY],
default_directory=str(Path.home()),
parent=self,
)
if dial.exec_():
self.base_folder.setText(dial.selectedFiles()[0])
def select_excel(self):
dial = PLoadDialog(LoadPlanExcel, settings=self.settings, path=IO_SAVE_DIRECTORY)
if dial.exec_():
file_path = str(dial.selectedFiles()[0])
if not os.path.splitext(file_path)[1]:
file_path += ".xlsx"
self.excel_path.setText(file_path)
def _excel_path_changed(self):
excel_path = Path(self.excel_path.text())
if not excel_path.exists() or not excel_path.is_file():
return
not_icon = QIcon(os.path.join(icons_dir, "task-reject.png"))
ok_icon = QIcon(os.path.join(icons_dir, "task-accepted.png"))
file_and_presence_list = _extract_information_from_excel_to_export(excel_path, self.base_folder.text())
self.info_box.clear()
presence_all = bool(file_and_presence_list)
if not presence_all:
self.info_label.setText(NO_FILES)
self.info_label.setVisible(True)
else:
self.info_label.setText("")
self.info_label.setVisible(False)
for file_path, presence in file_and_presence_list:
widget = QTreeWidgetItem(self.info_box)
widget.setText(0, file_path)
if not presence:
widget.setIcon(0, not_icon)
widget.setToolTip(0, "File do not exists")
else:
widget.setIcon(0, ok_icon)
presence_all &= presence
self._all_files_exists = presence_all
self._check_if_enable_zenodo_btn()
self._check_if_enable_export_btn()
def _extract_information_from_excel_to_export(
excel_path: typing.Union[str, Path], base_folder: typing.Union[str, Path]
) -> typing.List[typing.Tuple[str, bool]]:
"""Extract information from Excel file to export"""
file_list = []
file_set = set()
base_folder = Path(base_folder)
xlsx = load_workbook(filename=excel_path, read_only=True)
for sheet in xlsx.worksheets:
if sheet.cell(1, 2).value != "name":
continue
index = 4 # offset
while image_path := sheet.cell(index, 2).value:
index += 1
if image_path in file_set:
continue
file_set.add(image_path)
file_list.append((image_path, (base_folder / image_path).exists()))
return file_list
def export_to_archive(excel_path: Path, base_folder: Path, target_path: Path):
"""
Export files to archive
:param Path excel_path: path to Excel file
:param Path base_folder: base folder from where paths are calculated
:param Path target_path: path to archive
"""
file_list = _extract_information_from_excel_to_export(excel_path, base_folder)
if not file_list:
raise ValueError(NO_FILES)
if not all(presence for _, presence in file_list):
raise ValueError(MISSING_FILES)
ext = target_path.suffix
if ext == ".zip":
with zipfile.ZipFile(target_path, "w") as zip_file:
zip_file.write(excel_path, arcname=excel_path.name)
yield 1
for i, (file_path, _) in enumerate(file_list, start=2):
zip_file.write(base_folder / file_path, arcname=file_path)
yield i
return target_path
mode_dict = {
".tgz": "w:gz",
".gz": "w:gz",
".tbz2": "w:bz2",
".bz2": "w:bz2",
".txz": "w:xz",
".xz": "w:xz",
".tar": "w:",
}
mode = mode_dict.get(ext)
if mode is None:
raise ValueError("Unknown archive type")
with tarfile.open(target_path, mode=mode) as tar:
tar.add(excel_path, arcname=excel_path.name)
yield 1
for i, (file_path, _) in enumerate(file_list, start=2):
tar.add(base_folder / file_path, arcname=file_path)
yield i
return target_path
class ZenodoCreateError(ValueError):
pass
def sleep_with_rate(response: requests.Response):
"""Sleep with rate limit"""
if "X-RateLimit-Remaining" not in response.headers:
return
remaining = int(response.headers["X-RateLimit-Remaining"])
if remaining > 0:
return
reset = int(response.headers["X-RateLimit-Reset"])
sleep_time = reset - time.time()
if sleep_time > 0:
print(f"Sleeping for {sleep_time} seconds")
time.sleep(sleep_time)
def export_to_zenodo(
excel_path: Path,
base_folder: Path,
zenodo_token: str,
title: str,
author: str,
affiliation: str,
orcid: str,
description: str,
zenodo_url: str = "https://zenodo.org/api/deposit/depositions",
):
"""
Export project to Zenodo
:param excel_path: path to Excel file with output from batch processing
:param base_folder: base folder from where paths are calculated
:param zenodo_token: Zenodo API token
:param title: title of the deposition
:param author: author of the deposition
:param affiliation: affiliation of the author
:param orcid: ORCID of the author
:param description: description of the deposition
:param zenodo_url: Zenodo API URL
:return:
"""
file_list = _extract_information_from_excel_to_export(excel_path, base_folder)
if not file_list:
raise ValueError(NO_FILES)
if not all(presence for _, presence in file_list):
raise ValueError(MISSING_FILES)
params = {"access_token": zenodo_token}
headers = {"Content-Type": "application/json"}
initial_request = requests.post(
zenodo_url,
params=params,
json={},
headers=headers,
timeout=REQUESTS_TIMEOUT,
)
if initial_request.status_code != 201:
raise ZenodoCreateError(
"Can't create deposition. Please check your zenodo token."
" Please remember that token for sandbox and production are different. "
f" You could create token at "
f"{zenodo_url.replace('api/deposit/depositions', 'account/settings/applications/')}"
f" {initial_request.status_code} {initial_request.json()['message']}"
)
bucket_url = initial_request.json()["links"]["bucket"]
deposition_id = initial_request.json()["id"]
deposit_url = initial_request.json()["links"]["html"]
data = {
"metadata": {
"title": title,
"upload_type": "dataset",
"creators": [{"name": author, "affiliation": affiliation}],
}
}
if description:
data["metadata"]["description"] = description
if orcid:
data["metadata"]["creators"][0]["orcid"] = orcid
r = requests.put(
f"{zenodo_url}/{deposition_id}",
params=params,
data=json.dumps(data),
headers=headers,
timeout=REQUESTS_TIMEOUT,
)
if r.status_code != 200:
raise ZenodoCreateError(f"Can't update deposition metadata. Status code: {r.status_code}")
with excel_path.open(mode="rb") as fp:
r = requests.put(
f"{bucket_url}/{excel_path.name}",
data=fp,
params=params,
timeout=REQUESTS_TIMEOUT,
)
if r.status_code != 200:
raise ZenodoCreateError(f"Can't upload excel file. Status code: {r.status_code}")
yield 1
for i, (filename, _) in enumerate(file_list, start=2):
sleep_with_rate(r)
with (base_folder / filename).open(mode="rb") as fp:
r = requests.put(
f"{bucket_url}/{filename}",
data=fp,
params=params,
timeout=REQUESTS_TIMEOUT,
)
if r.status_code != 200:
raise ZenodoCreateError(f"Can't upload file {filename}. Status code: {r.status_code}")
yield i
return deposit_url
|
# -*- coding: utf-8 -*-
from core import httptools, scrapertools
from platformcode import logger
def get_video_url(page_url, url_referer=''):
logger.info("(page_url='%s')" % page_url)
video_urls = []
vid = scrapertools.find_single_match(page_url, "(?:e|f)/([A-z0-9_-]+)")
if not vid: return video_urls
page_url = 'https://digiload.live/player/e/' + vid
data = httptools.downloadpage(page_url).data
# ~ logger.debug(data)
url = scrapertools.find_single_match(data, ' data-file="([^"]+)')
if not url:
url = scrapertools.find_single_match(data, '"file": "([^"]+)')
if url:
video_urls.append(['mp4', url])
return video_urls
|
import os
from hackpad_api.hackpad import Hackpad
hackpad = Hackpad(api_scheme = os.getenv('HACKPAD_API_SCHEME'),
api_domain = os.getenv('HACKPAD_API_DOMAIN'),
sub_domain = os.getenv('HACKPAD_SUB_DOMAIN'),
consumer_key = os.getenv('HACKPAD_CLIENT_ID'),
consumer_secret = os.getenv('HACKPAD_SECRET'))
new_html_pad = hackpad.create_hackpad('HTML Pad Title Here', '<html><body><h1>HTML Pad Title Here</h1><p><img class="inline-img" src="https://s3.eu-central-1.amazonaws.com/stekpad/hackpad.com_kqQGLwBTjFe_p.222569_1407665146682_Get_Point.jpg" faketext="*" contenteditable="false"></p><p>And some text in <b>HTML</b>.</p><p><a href="http://cool.com/">Very cool no?</a></p></body></html>', '', 'text/html')
new_txt_pad = hackpad.create_hackpad('Text Pad Title Here', 'And some plain text.\n\nVery cool no?\n', '', 'text/plain')
all_pads = hackpad.list_all()
for padId in all_pads:
# hackpad.do_api_request()
pad = hackpad.get_pad_content(padId)
print(pad.decode('utf-8'))
print('-'*79)
|
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'mainUI.ui'
#
# Created by: PyQt5 UI code generator 5.13.2
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(1232, 811)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(MainWindow.sizePolicy().hasHeightForWidth())
MainWindow.setSizePolicy(sizePolicy)
font = QtGui.QFont()
font.setFamily("黑体")
font.setPointSize(14)
MainWindow.setFont(font)
MainWindow.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu)
MainWindow.setAutoFillBackground(False)
MainWindow.setStyleSheet("background-color:rgb(62, 62, 62);\n"
"color:rgb(232, 232, 232)")
MainWindow.setToolButtonStyle(QtCore.Qt.ToolButtonTextOnly)
MainWindow.setDocumentMode(False)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.gridLayout = QtWidgets.QGridLayout(self.centralwidget)
self.gridLayout.setObjectName("gridLayout")
self.listView_series = QtWidgets.QListView(self.centralwidget)
font = QtGui.QFont()
font.setPointSize(9)
self.listView_series.setFont(font)
self.listView_series.setStyleSheet("background-color:rgb(50, 50, 50)")
self.listView_series.setObjectName("listView_series")
self.gridLayout.addWidget(self.listView_series, 1, 1, 1, 7)
self.pushButton_search = QtWidgets.QPushButton(self.centralwidget)
self.pushButton_search.setMinimumSize(QtCore.QSize(71, 31))
self.pushButton_search.setMaximumSize(QtCore.QSize(71, 31))
self.pushButton_search.setObjectName("pushButton_search")
self.gridLayout.addWidget(self.pushButton_search, 0, 1, 1, 1)
self.lineEdit_search = QtWidgets.QLineEdit(self.centralwidget)
self.lineEdit_search.setMinimumSize(QtCore.QSize(261, 31))
self.lineEdit_search.setMaximumSize(QtCore.QSize(261, 16777215))
self.lineEdit_search.setText("")
self.lineEdit_search.setObjectName("lineEdit_search")
self.gridLayout.addWidget(self.lineEdit_search, 0, 0, 1, 1)
self.listView = QtWidgets.QListView(self.centralwidget)
self.listView.setMaximumSize(QtCore.QSize(261, 16777215))
self.listView.setFocusPolicy(QtCore.Qt.NoFocus)
self.listView.setStyleSheet("background-color:rgb(50, 50, 50)")
self.listView.setObjectName("listView")
self.gridLayout.addWidget(self.listView, 1, 0, 1, 1)
self.pushButton_download = QtWidgets.QPushButton(self.centralwidget)
self.pushButton_download.setMinimumSize(QtCore.QSize(71, 31))
self.pushButton_download.setMaximumSize(QtCore.QSize(71, 31))
self.pushButton_download.setObjectName("pushButton_download")
self.gridLayout.addWidget(self.pushButton_download, 0, 7, 1, 1)
self.pushButton_copyUrl = QtWidgets.QPushButton(self.centralwidget)
self.pushButton_copyUrl.setMinimumSize(QtCore.QSize(71, 31))
self.pushButton_copyUrl.setMaximumSize(QtCore.QSize(71, 31))
self.pushButton_copyUrl.setObjectName("pushButton_copyUrl")
self.gridLayout.addWidget(self.pushButton_copyUrl, 0, 6, 1, 1)
self.pushButton_play = QtWidgets.QPushButton(self.centralwidget)
self.pushButton_play.setMinimumSize(QtCore.QSize(71, 31))
self.pushButton_play.setMaximumSize(QtCore.QSize(71, 31))
self.pushButton_play.setObjectName("pushButton_play")
self.gridLayout.addWidget(self.pushButton_play, 0, 5, 1, 1)
self.comboBox_way = QtWidgets.QComboBox(self.centralwidget)
self.comboBox_way.setMinimumSize(QtCore.QSize(71, 31))
self.comboBox_way.setMaximumSize(QtCore.QSize(111, 31))
font = QtGui.QFont()
font.setFamily("黑体")
font.setPointSize(12)
self.comboBox_way.setFont(font)
self.comboBox_way.setObjectName("comboBox_way")
self.comboBox_way.addItem("")
self.comboBox_way.addItem("")
self.gridLayout.addWidget(self.comboBox_way, 0, 4, 1, 1)
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 1232, 25))
self.menubar.setObjectName("menubar")
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "soand"))
self.pushButton_search.setText(_translate("MainWindow", "search"))
self.pushButton_download.setText(_translate("MainWindow", "Download"))
self.pushButton_copyUrl.setText(_translate("MainWindow", "copyUrl"))
self.pushButton_play.setText(_translate("MainWindow", "play"))
self.comboBox_way.setItemText(0, _translate("MainWindow", "potPlayer"))
self.comboBox_way.setItemText(1, _translate("MainWindow", "webDownload"))
|
from injector import Module
from app.equipment_types.repositories import EquipmentTypeRepository
from tests.equipment_types.mocks import equipment_type_repository
class MockEquipmentTypeModule(Module):
def configure(self, binder):
binder.bind(EquipmentTypeRepository, to=equipment_type_repository)
|
import gym
import matplotlib.pyplot as plt
from CartPole.randomAgent.ReplayMemory import Memory
# parametres
numEpisods = 10
maxStep = 100
bufferSize = 10000
batchSize = 100
# pour calculer la récompense dans chaque épisode
sumreward = 0
# instances
env = gym.make('CartPole-v1')
memory = Memory(bufferSize)
scores= []
def plotting(score):
plt.clf()
plt.plot(score)
plt.title("Suivi évolution")
plt.xlabel("Épisode")
plt.ylabel("Step")
plt.grid()
plt.savefig('evolutionRandomAgent.png')
plt.pause(0.001)
for e in range(numEpisods):
state = env.reset()
done = False
for t in range(maxStep):
env.render()
action = env.action_space.sample()
nextState, reward, done, _ = env.step(action)
# ajout de l'experience dans la memoire de replay
memory.fillMemoryBuffer((state, action, nextState, reward, done))
# mise à jour de l'état vers le nouvel etat ou se trouve l'agent après l'execution de l'action
state = nextState
#calcul récompense
sumreward += reward
if done:
print("Episode finished after {} timesteps".format(t+1))
scores.append(sumreward)
sumreward = 0
break
plotting(scores)
print(memory.getBatch(batchSize))
print("reward:episode")
env.close()
|
from fractions import Fraction
from helpers import memoize
class Num:
def __init__(self, const_val):
self.val = const_val
def compute_value(self):
return self.val
class Add:
def __init__(self, expr1, expr2):
self.expr1 = expr1
self.expr2 = expr2
def compute_value(self, modulus):
val1 = self.expr1.compute_value()
val2 = self.expr2.compute_value()
return (val1 + val2)
class Subtract:
def __init__(self, expr1, expr2):
self.expr1 = expr1
self.expr2 = expr2
@memoize
def compute_value(self):
val1 = self.expr1.compute_value()
val2 = self.expr2.compute_value()
return (val1 - val2)
class Mult:
def __init__(self, expr1, expr2):
self.expr1 = expr1
self.expr2 = expr2
@memoize
def compute_value(self):
val1 = self.expr1.compute_value()
val2 = self.expr2.compute_value()
return (val1 * val2)
class Div:
def __init__(self, expr1, expr2):
self.expr1 = expr1
self.expr2 = expr2
@memoize
def compute_value(self):
val1 = self.expr1.compute_value()
val2 = self.expr2.compute_value()
return fraction(val1, val2)
# Doesn't work: can't get the thing in the example with this format.
@memoize
def reachable_nums(low_num, high_num):
if low_num == high_num:
return set([low_num])
num_with_entire_range = int(''.join([str(i) for i in range(low_num, high_num + 1)]))
nums = set([num_with_entire_range])
for next_low_num in range(low_num + 1, high_num + 1):
for reachable_num2 in reachable_nums(next_low_num, high_num):
for reachable_num1 in reachable_nums(low_num, next_low_num - 1):
nums.add(reachable_num1 + reachable_num2)
nums.add(reachable_num1 - reachable_num2)
nums.add(reachable_num1 * reachable_num2)
if reachable_num2 != 0:
nums.add(Fraction(reachable_num1, reachable_num2))
return nums
# print len(reachable_nums(1, 7))
print sum([i for i in reachable_nums(1, 9) if int(i) == i and i > 0]) |
# To change this license header, choose License Headers in Project Properties.
# To change this template file, choose Tools | Templates
# and open the template in the editor.
__author__="DarkRodry"
__date__ ="$25-sep-2013 16:55:48$"
import glob
from mutagen.mp3 import MP3
from mutagen.id3 import ID3, APIC, TIT2, TPE1, TRCK, TALB, USLT, error
def songEdit(songFileName):
artist = unicode(songFileName.split(' - ')[0].decode('utf8'))
songTitle = unicode(songFileName.split(' - ')[1].split('.mp3')[0].decode('utf8'))
audio = MP3(songFileName, ID3=ID3)
try:
audio.add_tags()
except:
pass
audio.tags.add(TIT2(encoding=3, text=songTitle))
audio.tags.add(TALB(encoding=3, text="".decode('utf-8')))
audio.tags.add(TPE1(encoding=3, text=artist))
audio.tags.add(TRCK(encoding=3, text="".decode('utf-8')))
audio.save()
if __name__ == "__main__":
songList = glob.glob("*.mp3")
i=1
for song in songList:
print "Iterating file", song, "\n",(i)*100/len(songList), "% complete"
songEdit(song)
i+=1
|
from math import sqrt, floor
prime_limit = 2000000
prime_sum = 0
def is_prime(n):
if n == 1:
return False # 1 is not a prime Number
elif n == 2:
return True
elif n > 2 and n % 2 == 0:
return False
else:
maxdivisor = int(floor(sqrt(n)) + 1)
for divisor in range(3, maxdivisor, 2):
if n % divisor == 0:
return False
return True
for i in range(prime_limit):
if is_prime(i):
prime_sum = prime_sum + i
print(prime_sum)
|
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setup(11, GPIO.OUT)
GPIO.setup(13, GPIO.OUT)
GPIO.setup(18, GPIO.OUT)
GPIO.output(13, False)
GPIO.output(11, False)
GPIO.output(18, False)
GPIO.cleanup()
|
from numpy import*
v1 = array(eval(input("v1: ")))
v2 = array(eval(input("v2: ")))
vet = zeros(3, dtype=int)
for i in range(size(v1)):
if v1[i]>v2[i]:
vet[0] = vet[0] + 1
elif v1[i] == v2[i]:
vet[1] = vet[1] + 1
elif v1[i] < v2[i]:
vet[2] = vet[2] + 1
print(vet) |
import pytest
from unittest.mock import patch
from rdftools.scripts import rdf
def test_rdf_script(capfd):
# We use capfd, not capsys, because the output we want to capture comes
# from the subprocess spawned by rdf, not rdf itself.
expected_out = 'usage: rdf-query [-h] [-v] [-b BASE] [-i [INPUT [INPUT ...]]]' # noqa: 501
with patch('sys.argv',
['test_rdf', '-v', 'query', '-h']):
rdf.main()
(out, err) = capfd.readouterr()
assert out.startswith(expected_out)
expected_err = """usage: test_rdf [-h] [-v] {validate,convert,select,shell,query} ...
test_rdf: error: argument command: invalid choice: 'foobar' (choose from 'validate', 'convert', 'select', 'shell', 'query')
""" # noqa: 501
def test_rdf_script_bad_command(capsys):
with patch('sys.argv',
['test_rdf', 'foobar', '-h']):
try:
rdf.main()
pytest.fail('expecting: %s' % expected_err)
except SystemExit:
(out, err) = capsys.readouterr()
assert err == expected_err
|
def calculate_sum(val1, val2):
'''doc string
Parameters
----------
val1 : [type]
[description]
val2 : [type]
[description]
Returns
-------
[type]
[description]
'''
result = val1 + val2
return result |
some_list = list(range(5,10))
print(some_list)
for item in some_list:
print(some_list.index(item))
|
from django.db import models
class Client(models.Model):
fullName = models.CharField('Full name',max_length=50)
email = models.EmailField('Email address')
phone = models.CharField('Phone number', max_length=20)
message = models.TextField()
def __str__(self):
return self.fullName |
import random,numpy as np,cv2
from keras.callbacks import TensorBoard, ModelCheckpoint, Callback,ReduceLROnPlateau
from keras import callbacks
from perception.bases.trainer_base import TrainerBase
from configs.utils.utils import genMasks,visualize,genMasks2
from configs.utils.img_utils import img_process,img_process1
import keras
global gen
#num_list_1 = []
#num_list_2 = []
class SWA(keras.callbacks.Callback):
def __init__(self, filepath, swa_epoch):
super(SWA, self).__init__()
self.filepath = filepath
self.swa_epoch = swa_epoch
def on_train_begin(self, logs=None):
self.nb_epoch = self.params['epochs']
print('Stochastic weight averaging selected for last {} epochs.'
.format(self.nb_epoch - self.swa_epoch))
def on_epoch_end(self, epoch, logs=None):
if epoch == self.swa_epoch:
self.swa_weights = self.model.get_weights()
elif epoch > self.swa_epoch:
for i in range(len(self.swa_weights)):
self.swa_weights[i] = (self.swa_weights[i] *
(epoch - self.swa_epoch) + self.model.get_weights()[i])/((epoch - self.swa_epoch) + 1)
else:
pass
def on_train_end(self, logs=None):
self.model.set_weights(self.swa_weights)
print('Final model parameters set to stochastic weight average.')
self.model.save_weights(self.filepath)
print('Final stochastic averaged weights saved to file.')
class SnapshotCallbackBuilder:
def __init__(self, nb_epochs, nb_snapshots, init_lr=0.1,iter_=0):
self.T = nb_epochs
self.M = nb_snapshots
self.alpha_zero = init_lr
self.iter_ = iter_
def get_callbacks(self, model_prefix='Model'):
callback_list = [
callbacks.ModelCheckpoint("./keras_{}.model".format(self.iter_),monitor='val_loss',
mode = 'min', save_best_only=True, verbose=1),
# SWA('./keras_384_2.model',1),
callbacks.LearningRateScheduler(schedule=self._cosine_anneal_schedule)
]
return callback_list
def _cosine_anneal_schedule(self, t):
cos_inner = np.pi * (t % (self.T // self.M)) # t - 1 is used when t has 1-based indexing.
cos_inner /= self.T // self.M
cos_out = np.cos(cos_inner) + 1
return float(self.alpha_zero / 2 * cos_out)
class SegmentionTrainer(TrainerBase):
def __init__(self,model,data,config,iter_):
super(SegmentionTrainer, self).__init__(model, data, config , iter_)
self.model=model
self.data=data
self.config=config
self.callbacks=[]
self.init_callbacks()
self.iter_ = iter_
def init_callbacks(self):
self.callbacks = SnapshotCallbackBuilder(nb_epochs=2,nb_snapshots=1,init_lr=1e-3,iter_=self.iter_).get_callbacks()
# self.callbacks.append(
# ModelCheckpoint(
# filepath=self.config.hdf5_path+self.config.exp_name+ '_best_weights.h5',
# verbose=1,
# monitor='val_loss',
# mode='auto',
# save_best_only=True
# )
# )
# self.callbacks.append(
# ReduceLROnPlateau(monitor='val_loss', factor=0.5, patience=5, verbose=1, mode='auto'
# )
# )
#
# self.callbacks.append(
# TensorBoard(
# log_dir=self.config.checkpoint,
# write_images=True,
# write_graph=True,
# )
# )
def train(self):
gen=MulticlassDataGenerator(self.data,self.config,self.iter_)
if self.iter_ =='DRIVE_Binary':
gen=DataGeneratorBinary(self.data,self.config,self.iter_)
elif self.iter_ =='DROIVE_MULTICLASS':
gen=MulticlassDataGenerator(self.data,self.config,self.iter_)
#gen.visual_patch()
hist = self.model.fit_generator(gen.train_gen(),
epochs=self.config.epochs,
steps_per_epoch=100,
# steps_per_epoch=self.config.subsample * self.config.total_train / self.config.batch_size,
verbose=1,
callbacks=self.callbacks,
validation_data=gen.val_gen(),
validation_steps=int(self.config.subsample * self.config.total_val / self.config.batch_size)
)
self.model.save_weights(self.config.hdf5_path+self.config.exp_name+'_last_weights.h5', overwrite=True)
class MulticlassDataGenerator():
"""
load image (Generator)
"""
def __init__(self,data,config,iter_):
if iter_ == 'prob' :
self.train_img=img_process1(data[0],data[4])
self.val_img=img_process1(data[2],data[5])
elif iter_ == 'DRIVE_MULTICLASS' :
print('DRIVE_MULTICLASS')
self.train_img=img_process(data[0])
self.val_img=img_process(data[2])
self.train_gt=data[1]
# self.val_img=img_process(data[2])
# self.val_img=data[2]
self.val_gt=data[3]
else:
self.train_img=img_process(data[0])
self.val_img=img_process(data[2])
# self.train_img=data[0]
#self.train_gt=data[1]/255.
# self.val_img=img_process(data[2])
# self.val_img=data[2]
#self.val_gt=data[3]/255.
self.config=config
self.multi_proportion = config.multi_proportion
def _CenterSampler(self,attnlist,class_weight,Nimgs):
"""
围绕目标区域采样
:param attnlist: 目标区域坐标
:return: 采样的坐标
"""
class_weight = class_weight / np.sum(class_weight)
p = random.uniform(0, 1)
psum = 0
for i in range(class_weight.shape[0]):
psum = psum + class_weight[i]
if p < psum:
label = i
break
if label == class_weight.shape[0] - 1:
i_center = random.randint(0, Nimgs - 1)
x_center = random.randint(0 + int(self.config.patch_width / 2), self.config.width - int(self.config.patch_width / 2))
# print "x_center " +str(x_center)
y_center = random.randint(0 + int(self.config.patch_height / 2), self.config.height - int(self.config.patch_height / 2))
else:
t = attnlist[label]
cid = random.randint(0, t[0].shape[0] - 1)
i_center = t[0][cid]
y_center = t[1][cid] + random.randint(0 - int(self.config.patch_width / 2), 0 + int(self.config.patch_width / 2))
x_center = t[2][cid] + random.randint(0 - int(self.config.patch_width / 2), 0 + int(self.config.patch_width / 2))
if y_center < self.config.patch_width / 2:
y_center = self.config.patch_width / 2
elif y_center > self.config.height - self.config.patch_width / 2:
y_center = self.config.height - self.config.patch_width / 2
if x_center < self.config.patch_width / 2:
x_center = self.config.patch_width / 2
elif x_center > self.config.width - self.config.patch_width / 2:
x_center = self.config.width - self.config.patch_width / 2
return i_center, x_center, y_center
def _genDef(self,train_imgs,train_masks,attnlist,class_weight):
"""
图片取块生成器模板
:param train_imgs: 原始图
:param train_masks: 原始图groundtruth
:param attnlist: 目标区域list
:return: 取出的训练样本
"""
while 1:
Nimgs=train_imgs.shape[0]
for t in range(int(self.config.subsample * self.config.total_train / self.config.batch_size)):
if self.multi_proportion:
X = np.zeros([self.config.batch_size,self.config.patch_height, self.config.patch_width,1])
Y = np.zeros([self.config.batch_size, self.config.patch_height * self.config.patch_width, self.config.seg_num + 1])
else:
X = np.zeros([self.config.batch_size,self.config.patch_height, self.config.patch_width,3])
Y = np.zeros([self.config.batch_size, self.config.patch_height * self.config.patch_width, self.config.seg_num + 1])
for j in range(self.config.batch_size):
[i_center, x_center, y_center] = self._CenterSampler(attnlist,class_weight,Nimgs)
patch = train_imgs[i_center, int(y_center - self.config.patch_height / 2):int(y_center + self.config.patch_height / 2),int(x_center - self.config.patch_width / 2):int(x_center + self.config.patch_width / 2),:]
patch_mask = train_masks[i_center, :, int(y_center - self.config.patch_height / 2):int(y_center + self.config.patch_height / 2),int(x_center - self.config.patch_width / 2):int(x_center + self.config.patch_width / 2)]
X[j, :, :, :] = patch
Y[j, :, :] = genMasks2(np.reshape(patch_mask, [1, self.config.seg_num, self.config.patch_height, self.config.patch_width]),self.config.seg_num)
yield (X, Y)
def train_gen(self):
"""
训练样本生成器
"""
class_weight=[1.0,0.0]
attnlist=[np.where(self.train_gt[:,0,:,:]==np.max(self.train_gt[:,0,:,:]))]
return self._genDef(self.train_img,self.train_gt,attnlist,class_weight)
def val_gen(self):
"""
验证样本生成器
"""
class_weight = [1.0,0.0]
attnlist = [np.where(self.val_gt[:, 0, :, :] == np.max(self.val_gt[:, 0, :, :]))]
return self._genDef(self.val_img, self.val_gt, attnlist,class_weight)
def visual_patch(self):
gen=self.train_gen()
(X,Y)=next(gen)
image=[]
mask=[]
print("[INFO] Visualize Image Sample...")
for index in range(self.config.batch_size):
image.append(X[index])
mask.append(np.reshape(Y,[self.config.batch_size,self.config.patch_height,self.config.patch_width,self.config.seg_num+1])[index,:,:,0])
if self.config.batch_size%4==0:
row=self.config.batch_size/4
col=4
else:
if self.config.batch_size % 5!=0:
row = self.config.batch_size // 5+1
else:
row = self.config.batch_size // 5
col = 5
imagePatch=visualize(image,[row,col])
maskPatch=visualize(mask,[row,col])
cv2.imwrite(self.config.checkpoint+"image_patch.jpg",imagePatch)
cv2.imwrite(self.config.checkpoint + "groundtruth_patch.jpg", maskPatch)
class DataGenerator():
"""
load image (Generator)
"""
def __init__(self,data,config,iter_):
if iter_ == 'prob' :
self.train_img=img_process1(data[0],data[4])
self.val_img=img_process1(data[2],data[5])
else:
self.train_img=img_process(data[0])
self.val_img=img_process(data[2])
# self.train_img=data[0]
self.train_gt=data[1]/255.
# self.val_img=img_process(data[2])
# self.val_img=data[2]
self.val_gt=data[3]/255.
self.config=config
self.multi_proportion = config.multi_proportion
def _CenterSampler(self,attnlist,class_weight,Nimgs):
"""
围绕目标区域采样
:param attnlist: 目标区域坐标
:return: 采样的坐标
"""
class_weight = class_weight / np.sum(class_weight)
p = random.uniform(0, 1)
psum = 0
for i in range(class_weight.shape[0]):
psum = psum + class_weight[i]
if p < psum:
label = i
break
if label == class_weight.shape[0] - 1:
i_center = random.randint(0, Nimgs - 1)
x_center = random.randint(0 + int(self.config.patch_width / 2), self.config.width - int(self.config.patch_width / 2))
# print "x_center " +str(x_center)
y_center = random.randint(0 + int(self.config.patch_height / 2), self.config.height - int(self.config.patch_height / 2))
else:
t = attnlist[label]
cid = random.randint(0, t[0].shape[0] - 1)
i_center = t[0][cid]
y_center = t[1][cid] + random.randint(0 - int(self.config.patch_width / 2), 0 + int(self.config.patch_width / 2))
x_center = t[2][cid] + random.randint(0 - int(self.config.patch_width / 2), 0 + int(self.config.patch_width / 2))
if y_center < self.config.patch_width / 2:
y_center = self.config.patch_width / 2
elif y_center > self.config.height - self.config.patch_width / 2:
y_center = self.config.height - self.config.patch_width / 2
if x_center < self.config.patch_width / 2:
x_center = self.config.patch_width / 2
elif x_center > self.config.width - self.config.patch_width / 2:
x_center = self.config.width - self.config.patch_width / 2
return i_center, x_center, y_center
def _genDef(self,train_imgs,train_masks,attnlist,class_weight):
"""
图片取块生成器模板
:param train_imgs: 原始图
:param train_masks: 原始图groundtruth
:param attnlist: 目标区域list
:return: 取出的训练样本
"""
while 1:
Nimgs=train_imgs.shape[0]
for t in range(int(self.config.subsample * self.config.total_train / self.config.batch_size)):
if self.multi_proportion:
X = np.zeros([self.config.batch_size,self.config.patch_height, self.config.patch_width,1])
Y = np.zeros([self.config.batch_size, self.config.patch_height * self.config.patch_width, self.config.seg_num + 1])
else:
X = np.zeros([self.config.batch_size,self.config.patch_height, self.config.patch_width,3])
Y = np.zeros([self.config.batch_size, self.config.patch_height * self.config.patch_width, self.config.seg_num + 1])
for j in range(self.config.batch_size):
[i_center, x_center, y_center] = self._CenterSampler(attnlist,class_weight,Nimgs)
patch = train_imgs[i_center, int(y_center - self.config.patch_height / 2):int(y_center + self.config.patch_height / 2),int(x_center - self.config.patch_width / 2):int(x_center + self.config.patch_width / 2),:]
patch_mask = train_masks[i_center, :, int(y_center - self.config.patch_height / 2):int(y_center + self.config.patch_height / 2),int(x_center - self.config.patch_width / 2):int(x_center + self.config.patch_width / 2)]
X[j, :, :, :] = patch
Y[j, :, :] = genMasks(np.reshape(patch_mask, [1, self.config.seg_num, self.config.patch_height, self.config.patch_width]),self.config.seg_num)
yield (X, Y)
def train_gen(self):
"""
训练样本生成器
"""
class_weight=[1.0,0.0]
attnlist=[np.where(self.train_gt[:,0,:,:]==np.max(self.train_gt[:,0,:,:]))]
return self._genDef(self.train_img,self.train_gt,attnlist,class_weight)
def val_gen(self):
"""
验证样本生成器
"""
class_weight = [1.0,0.0]
attnlist = [np.where(self.val_gt[:, 0, :, :] == np.max(self.val_gt[:, 0, :, :]))]
return self._genDef(self.val_img, self.val_gt, attnlist,class_weight)
def visual_patch(self):
gen=self.train_gen()
(X,Y)=next(gen)
image=[]
mask=[]
print("[INFO] Visualize Image Sample...")
for index in range(self.config.batch_size):
image.append(X[index])
mask.append(np.reshape(Y,[self.config.batch_size,self.config.patch_height,self.config.patch_width,self.config.seg_num+1])[index,:,:,0])
if self.config.batch_size%4==0:
row=self.config.batch_size/4
col=4
else:
if self.config.batch_size % 5!=0:
row = self.config.batch_size // 5+1
else:
row = self.config.batch_size // 5
col = 5
imagePatch=visualize(image,[row,col])
maskPatch=visualize(mask,[row,col])
cv2.imwrite(self.config.checkpoint+"image_patch.jpg",imagePatch)
cv2.imwrite(self.config.checkpoint + "groundtruth_patch.jpg", maskPatch)
class DataGeneratorBinary():
"""
load image (Generator)
"""
def __init__(self,data,config,iter_):
if iter_ == 'prob' :
self.train_img=img_process1(data[0],data[4])
self.val_img=img_process1(data[2],data[5])
self.train_gt=data[1]
# self.val_img=img_process(data[2])
# self.val_img=data[2]
self.val_gt=data[3]
elif iter_ == 'DRIVE_MULTICLASS' :
self.train_img=img_process1(data[0],data[4])
self.val_img=img_process1(data[2],data[5])
self.train_gt=data[1]
# self.val_img=img_process(data[2])
# self.val_img=data[2]
self.val_gt=data[3]
else:
self.train_img=img_process(data[0])
self.val_img=img_process(data[2])
# self.train_img=data[0]
self.train_gt=data[1]/255.
# self.val_img=img_process(data[2])
# self.val_img=data[2]
self.val_gt=data[3]/255.
self.config=config
self.multi_proportion = config.multi_proportion
def _CenterSampler(self,attnlist,class_weight,Nimgs,num_list):
"""
围绕目标区域采样
:param attnlist: 目标区域坐标
:return: 采样的坐标
"""
class_weight = class_weight / np.sum(class_weight)
p = random.uniform(0, 1)
psum = 0
for i in range(class_weight.shape[0]):
psum = psum + class_weight[i]
if p < psum:
label = i
break
if label == class_weight.shape[0] - 1:
# print('Nimg:{}'.format(Nimgs))
i_center = random.randint(0, Nimgs - 1)
x_center = random.randint(0 + int(self.config.patch_width // 2), self.config.width - int(self.config.patch_width // 2))
# print "x_center " +str(x_center)
y_center = random.randint(0 + int(self.config.patch_height // 2), self.config.height - int(self.config.patch_height // 2))
else:
t = attnlist[label]
# while 1:
# cid = random.randint(0, t[0].shape[0] - 1)
#
# if cid not in num_list:
# num_list.append(cid)
# break
# cid = num_id
# print('label:{}'.format(label))
# print('cid:{}'.format(t[0].shape[0]))
cid = random.randint(0, t[0].shape[0] - 1)
i_center = t[0][cid]
y_center = t[1][cid] + random.randint(0 - int(self.config.patch_width // 2), 0 + int(self.config.patch_width // 2))
x_center = t[2][cid] + random.randint(0 - int(self.config.patch_width // 2), 0 + int(self.config.patch_width // 2))
# print('初始点:{} {}'.format(x_center,y_center))
if y_center < self.config.patch_width // 2:
y_center = self.config.patch_width // 2
elif y_center > self.config.height - self.config.patch_width // 2:
y_center = self.config.height - self.config.patch_width // 2
if x_center < self.config.patch_width // 2:
x_center = self.config.patch_width // 2
elif x_center > self.config.width - self.config.patch_width // 2:
x_center = self.config.width - self.config.patch_width // 2
# print('修正后初始点:{} {}'.format(x_center,y_center))
return i_center, x_center, y_center
def _genDef(self,train_imgs,train_masks,attnlist,class_weight,num_list):
"""
图片取块生成器模板
:param train_imgs: 原始图
:param train_masks: 原始图groundtruth
:param attnlist: 目标区域list
:return: 取出的训练样本
"""
# num_id = 0
while 1:
# num_id = 0
Nimgs=train_imgs.shape[0]
# print(train_imgs.shape)
# num_ = at
for t in range(int(self.config.subsample * self.config.total_train / self.config.batch_size)):
if self.multi_proportion:
X = np.zeros([self.config.batch_size,self.config.patch_height, self.config.patch_width,1])
Y = np.zeros([self.config.batch_size,self.config.patch_height, self.config.patch_width,1])
else:
X = np.zeros([self.config.batch_size,self.config.patch_height, self.config.patch_width,3])
Y = np.zeros([self.config.batch_size,self.config.patch_height, self.config.patch_width,1])
# Y = np.zeros([self.config.batch_size,self.config.patch_height, self.config.patch_width,1])
for j in range(self.config.batch_size):
[i_center, x_center, y_center] = self._CenterSampler(attnlist,class_weight,Nimgs,num_list)
# num_id += 1
# if num_id >= 925896:
# num_id = 0
patch = train_imgs[i_center, int(y_center - self.config.patch_height // 2):int(y_center + self.config.patch_height // 2),int(x_center - self.config.patch_width // 2):int(x_center + self.config.patch_width // 2),:]
patch_mask = train_masks[i_center, :, int(y_center - self.config.patch_height // 2):int(y_center + self.config.patch_height // 2),int(x_center - self.config.patch_width // 2):int(x_center + self.config.patch_width // 2)]
# patch = np.expand_dims(cv2.resize(patch,(self.config.patch_height,self.config.patch_width)),-1)
# patch_mask = cv2.resize(patch_mask,(self.config.patch_height,self.config.patch_width))
X[j, :, :, :] = patch
# Y[j, :, :] = genMasks(np.reshape(patch_mask, [1, self.config.seg_num, self.config.patch_height, self.config.patch_width]),self.config.seg_num)
Y[j, :, :] = np.transpose(patch_mask,(1,2,0))
yield (X, Y)
def train_gen(self):
"""
训练样本生成器
"""
class_weight=[1.0,0.0]
train_num_list = []
attnlist=[np.where(self.train_gt[:,0,:,:]==np.max(self.train_gt[:,0,:,:]))]
return self._genDef(self.train_img,self.train_gt,attnlist,class_weight,train_num_list)
def val_gen(self):
"""
验证样本生成器
"""
class_weight = [1.0,0.0]
attnlist = [np.where(self.val_gt[:, 0, :, :] == np.max(self.val_gt[:, 0, :, :]))]
val_num_list = []
return self._genDef(self.val_img, self.val_gt, attnlist,class_weight,val_num_list)
def visual_patch(self):
gen=self.train_gen()
(X,Y)=next(gen)
image=[]
mask=[]
print("[INFO] Visualize Image Sample...")
for index in range(self.config.batch_size):
image.append(X[index])
mask.append(np.reshape(Y,[self.config.batch_size,self.config.patch_height,self.config.patch_width,self.config.seg_num+1])[index,:,:,0])
if self.config.batch_size%4==0:
row=self.config.batch_size/4
col=4
else:
if self.config.batch_size % 5!=0:
row = self.config.batch_size // 5+1
else:
row = self.config.batch_size // 5
col = 5
imagePatch=visualize(image,[row,col])
maskPatch=visualize(mask,[row,col])
cv2.imwrite(self.config.checkpoint+"image_patch.jpg",imagePatch)
cv2.imwrite(self.config.checkpoint + "groundtruth_patch.jpg", maskPatch) |
import pandas as pd
import numpy as np
import requests
from bs4 import BeautifulSoup as BeSo
import lxml
import html
def lastMonthDay (year, month) :
'''La función devuelve el último día del mes del año pasado por parámetros.
El año y el mes han de tener un formato numérico.'''
import calendar
month_list = calendar.monthcalendar(year, month)
lastWeek = month_list[len(month_list)-1]
while lastWeek[len(lastWeek)-1] == 0 :
lastWeek.remove(0)
return lastWeek[len(lastWeek)-1]
def extractData (year, MetStation ):
''' Función para la recuperación de la información de la página de meteorología.
Recupera la información por día y hora para el año indicado de temperatura,
dirección y velocidad del viento.
Parametro de entrada : AÑO, Estacion Meteorológica
Parametro de salida : Data Frame con la información.'''
fecha_indice = []
fecha_fin = []
hora_fin =[]
temp_fin = []
windDir_fin = []
windSpeed_fin = []
#Preparamos un bucle para los meses del año.
for x in range(1,13) :
print('Mes ' + str(x))
# Preparación de los parametros para la consulta a la página.
num_days = lastMonthDay(year,x)
param = {'ord':'REV', 'decoded':'yes', 'ndays':num_days, 'ano':year, 'mes':x, 'day':num_days, 'hora':24, 'ind':MetStation}
res = requests.get('http://www.ogimet.com/cgi-bin/gsynres', param)
sheet = BeSo(res.content, 'html.parser')
table = sheet.find_all('table')[2]
df = pd.read_html(str(table))[0].iloc[:,0:9]
#Incializamos las variables para la incorporacion
fecha = np.array(df.loc[:,'Fecha'][2:])
hora = np.array(df.loc[:]['T(C)'][2:])
temp = np.array(df.loc[:]['Td(C)'][2:])
windDir = np.array(df.loc[:]['ffkmh'][2:])
windSpeed = np.array(df.loc[:]['P0hPa'][2:])
for i in range(len(fecha)-1) :
fecha_indice.append(fecha[i] + ' ' + hora[i])
fecha_fin.append(fecha[i])
hora_fin.append(hora[i])
temp_fin.append(temp[i])
windDir_fin.append(windDir[i])
windSpeed_fin.append(windSpeed[i])
# Tratamos el HTML recibido para incorporarlo en el DataFrame
# Devolvemos la información en el DataFrame
data = {'fecha':pd.Series(fecha_fin, index=fecha_indice),
'hora':pd.Series(hora_fin, index=fecha_indice),
'temp':pd.Series(temp_fin, index=fecha_indice),
'WD':pd.Series(windDir_fin, index=fecha_indice),
'WS':pd.Series(windSpeed_fin, index=fecha_indice)}
return pd.DataFrame(data)
Salida = extractData(2008,'08221')
Salida |
import os
import time
import datetime
import json
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from rest_framework import mixins
from rest_framework import generics
from rest_framework.permissions import IsAuthenticated
from django.contrib.auth.hashers import make_password, check_password
from backend.models import *
from competition.serializers import *
from competition.permissions import *
# Create your views here.
class Create(APIView):
def post(self, request):
serializer = CompetitionSerializer(data=request.data)
if serializer.is_valid():
serializer.save(organizer=self.request.user.organizer_user)
return Response({'returnCode':0, 'id':serializer.data.get('id')}, status=status.HTTP_201_CREATED) #serializer.data
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
class List(generics.ListCreateAPIView):
queryset = Competition.objects.all()
serializer_class = CompetitionSerializer
permission_classes = (permissions.IsAuthenticatedOrReadOnly,)
def perform_create(self, serializer):
serializer.save(organizer=self.request.user.organizer_user)
class HomeCompetition(APIView):
def get(self, request):
query_set = Competition.objects.filter(status__exact=1)
if len(query_set) >= 6:
query_set = query_set[0:6]
serializer = HomeCompetitionSerializer(query_set, many=True)
return Response(serializer.data, status=status.HTTP_200_OK)
class Detail(mixins.RetrieveModelMixin, mixins.UpdateModelMixin, mixins.DestroyModelMixin, generics.GenericAPIView):
queryset = Competition.objects.all()
serializer_class = CompetitionSerializer
#permission_classes = (IsOwnerOrReadOnly,)
def get(self, request, *args, **kwargs):
return self.retrieve(request, *args, **kwargs)
def put(self, request, *args, **kwargs):
return self.update(request, *args, **kwargs)
def delete(self, request, *args, **kwargs):
return self.destroy(request, *args, **kwargs)
class DetailWithPhase(mixins.RetrieveModelMixin, mixins.UpdateModelMixin, mixins.DestroyModelMixin, generics.GenericAPIView):
queryset = Competition.objects.all()
serializer_class = CompetitionDetialSerializer
#permission_classes = (IsOwnerOrReadOnly,)
def get(self, request, *args, **kwargs):
return self.retrieve(request, *args, **kwargs)
def put(self, request, *args, **kwargs):
return self.update(request, *args, **kwargs)
def delete(self, request, *args, **kwargs):
return self.destroy(request, *args, **kwargs)
class CoverUpload(APIView):
def post(self, request):
user = request.user
if user.is_authenticated() and user.first_name == 'organizer':
image = request.data.get('file')
present_time = str(int(time.time()))
present_time.replace('.', '_')
pre_name = image.name.split('.')
image_name = user.username + '_' + pre_name[0] + '_' + present_time + '.' + pre_name[-1]
cover_file = open(os.path.join('frontend/dist/static/static/cover', image_name), "wb")
for chunk in image.chunks():
cover_file.write(chunk)
cover_file.close()
pic_url = 'static/static/cover/' + image_name
return Response({'pic_url': pic_url}, status=status.HTTP_200_OK)
return Response({}, status=status.HTTP_401_UNAUTHORIZED)
class AttachmentUpload(APIView):
def post(self, request):
user = request.user
if user.is_authenticated() and user.first_name == 'organizer':
attachment_file = request.data.get('file')
present_time = str(int(time.time()))
present_time.replace('.', '_')
pre_name = attachment_file.name.split('.')
file_name = user.username + '_' + pre_name[0] + '_' + present_time + '.' + pre_name[-1]
attach_file = open(os.path.join('frontend/dist/static/static/attachment', file_name), "wb")
for chunk in attachment_file.chunks():
attach_file.write(chunk)
attach_file.close()
attachment_url = 'static/static/attachment/' + file_name
return Response({'attachment_url': attachment_url}, status=status.HTTP_200_OK)
return Response({}, status=status.HTTP_401_UNAUTHORIZED)
class SubmitUpload(APIView):
def post(self, request):
user = request.user
if user.is_authenticated() and user.first_name == 'contestant':
submit_file = request.data.get('file')
present_time = str(int(time.time()))
present_time.replace('.', '_')
pre_name = submit_file.name.split('.')
file_name = user.username + '_' + pre_name[0] + '_' + present_time + '.' + pre_name[-1]
sub_file = open(os.path.join('frontend/dist/static/static/submit', file_name), "wb")
for chunk in submit_file.chunks():
sub_file.write(chunk)
sub_file.close()
submit_url = 'static/static/submit/' + file_name
return Response({'submit_url': submit_url}, status=status.HTTP_200_OK)
return Response({}, status=status.HTTP_401_UNAUTHORIZED)
class GetNotice(APIView):
def post(self, request):
competition = Competition.objects.get(id=request.data.get('competition_id'))
if request.user.organizer_user != competition.organizer:
return Response({'reason': 1}, status=status.HTTP_400_BAD_REQUEST)
notice = Notice()
notice.competition = competition
notice.title = request.data.get('title')
notice.content = request.data.get('content')
notice.status = request.data.get('status')
notice.save()
return Response({}, status=status.HTTP_200_OK)
def get(self, request):
competition = Competition.objects.get(id=request.query_params.dict().get('competition_id'))
if request.user.first_name == 'organizer' and request.user.organizer_user == competition.organizer:
saving_notices = []
published_notices = []
deleted_notices = []
for notice in competition.notice.filter(status__exact=0):
saving_notices.append({'id':notice.id, 'title':notice.title, 'content':notice.content})
for notice in competition.notice.filter(status__exact=1):
published_notices.append({'id':notice.id, 'title':notice.title, 'content':notice.content})
for notice in competition.notice.filter(status__exact=2):
deleted_notices.append({'id':notice.id, 'title':notice.title, 'content':notice.content})
return Response({'saving_notices':saving_notices, 'published_notices':published_notices,\
'deleted_notices':deleted_notices}, status=status.HTTP_200_OK)
else:
serializer = NoticeSerializer(competition.notice.filter(status__exact=1), many=True)
for notice in serializer.data:
notice['post_time'] = notice['post_time'].split('.')[0].replace('T', ' ')
return Response({'posted_notices':serializer.data}, status=status.HTTP_200_OK)
class NoticeDetail(mixins.RetrieveModelMixin, mixins.UpdateModelMixin, mixins.DestroyModelMixin, generics.GenericAPIView):
queryset = Notice.objects.all()
serializer_class = NoticeSerializer
permission_classes = (IsNoticeOwnerOrReadOnly,)
def get(self, request, *args, **kwargs):
return self.retrieve(request, *args, **kwargs)
def post(self, request, *args, **kwargs):
return self.update(request, *args, **kwargs)
class NoticeStatus(APIView):
def post(self, request):
notice = Notice.objects.get(id=request.data.get('notice_id'))
if request.user.first_name == 'organizer' and request.user.organizer_user == notice.competition.organizer:
statuses = ['0', '1', '2']
if request.data.get('new_status') in statuses:
notice.status = request.data.get('new_status')
notice.save()
return Response({}, status=status.HTTP_200_OK)
elif request.data.get('new_status') == '3':
notice.delete()
return Response({}, status=status.HTTP_200_OK)
return Response({'reason': 2}, status=status.HTTP_400_BAD_REQUEST)
return Response({'reason': 1}, status=status.HTTP_400_BAD_REQUEST)
class GetEvent(APIView):
#permission_classes = (IsAuthenticated)
def post(self, request):
serializer = PostEventSerializer(data=request.data)
if serializer.is_valid():
phase = Phase.objects.get(id=request.data.get('phase_id'))
if request.data.get('event_type') == '7':
contestant = ContestantUser.objects.get(id=request.data.get('contestant_id'))
personal_letter = PersonalLetter()
personal_letter.receiver = contestant.user
personal_letter.sender = phase.competition.organizer.user
personal_letter.is_read = 0
personal_letter.content = contestant.name + '同学您好,您在比赛 ' + phase.competition.name + ' 中受到警告,警告理由如下: ' + request.data.get('content')
personal_letter.save()
else:
contestant = request.user.contestant_user
serializer.save(phase=phase, contestant=contestant)
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response({}, status=status.HTTP_400_BAD_REQUEST)
def get(self, request):
params = request.query_params.dict()
phase = Phase.objects.get(id=params.get('phase_id'))
if request.user.first_name == 'organizer' and request.user.organizer_user == phase.competition.organizer:
event_query_set = phase.event.all()
event_query_set = event_query_set.exclude(event_type__exact=7)
event_type = int(params.get('event_type'))
event_types = [1, 2, 3, 4, 5, 6, 8]
if event_type in event_types:
event_query_set = event_query_set.filter(event_type__exact=event_type)
event_status = int(params.get('status'))
statuses = [1, 2, 3]
if event_status in statuses:
event_query_set = event_query_set.filter(status__exact=event_status)
if len(event_query_set) <= 0:
return Response({}, status=status.HTTP_200_OK)
current_page = int(params.get('current_page'))
event_num = int(params.get('event_num'))
min_num = event_num * (current_page - 1)
max_num = event_num * current_page - 1
if min_num >= 0 and max_num < len(event_query_set):
event_query_set = event_query_set[min_num:max_num + 1]
serializer = EventSerializer(event_query_set, many=True)
elif min_num >= 0 and max_num > len(event_query_set) and min_num < len(event_query_set):
event_query_set = event_query_set[min_num:len(event_query_set)]
serializer = EventSerializer(event_query_set, many=True)
else:
return Response({}, status=status.HTTP_400_BAD_REQUEST)
for event in serializer.data:
event['time'] = event['time'].split('.')[0].replace('T', ' ')
event['handle_time'] = event['handle_time'].split('.')[0].replace('T', ' ')
return Response(serializer.data, status=status.HTTP_200_OK)
elif request.user.first_name == 'contestant':
contestant = request.user.contestant_user
event_query_set = contestant.event.filter(phase__exact=phase)
serializer = EventSerializer(event_query_set, many=True)
for event in serializer.data:
event['time'] = event['time'].split('.')[0].replace('T', ' ')
event['handle_time'] = event['handle_time'].split('.')[0].replace('T', ' ')
return Response(serializer.data, status=status.HTTP_200_OK)
return Response({}, status=status.HTTP_400_BAD_REQUEST)
class EventNumber(APIView):
def get(self, request):
params = request.query_params.dict()
phase = Phase.objects.get(id=params.get('phase_id'))
if request.user.first_name == 'organizer' and request.user.organizer_user == phase.competition.organizer:
event_query_set = phase.event.filter(event_type__lt=7)
event_type = params.get('event_type')
event_types = [1, 2, 3, 4, 5, 6, 8]
if event_type in event_types:
event_query_set = event_query_set.filter(event_type__exact=event_type)
event_status = params.get('status')
statuses = [1, 2, 3]
if event_status in statuses:
event_query_set = event_query_set.filter(status__exact=event_status)
return Response({'event_number': len(event_query_set)}, status=status.HTTP_200_OK)
return Response({}, status=status.HTTP_400_BAD_REQUEST)
class HandleEvent(APIView):
#permission_classes = (IsAuthenticated)
def post(self, request):
event = Event.objects.get(id=request.data.get('id'))
if request.user.first_name == 'organizer' and request.user.organizer_user == event.phase.competition.organizer:
event.status = request.data.get('status')
event.reason = request.data.get('reason')
event.save()
if event.event_type == 1 or event.event_type == 8:
is_joining = 0
if event.status == '2':
is_joining = 2
elif event.status == '3':
is_joining = 0
queryset = CompetitionAndContestant.objects.filter(competition=event.phase.competition, contestant=event.contestant)
if queryset:
queryset[0].is_joining = is_joining
queryset[0].current_phase = event.phase
queryset[0].save()
else:
competition_and_contestant = CompetitionAndContestant()
competition_and_contestant.contestant = event.contestant
competition_and_contestant.competition = event.phase.competition
competition_and_contestant.current_phase = event.phase
competition_and_contestant.is_joining = is_joining
competition_and_contestant.save()
if (is_joining == 0):
return Response({'status':event.status, 'reason':event.reason}, status=status.HTTP_200_OK)
event.phase.joiner.add(event.contestant)
event.contestant.join_competition.add(event.phase.competition)
event.contestant.save()
if event.is_team >= 1:
if event.event_type == 1:
event_content = json.loads(event.content)
team = Team()
team.team_leader = event.contestant
team.phase = event.phase
team.name = event_content[0][0]
team.introduction = event_content[1][0]
team.save()
if event.event_type == 8:
team = Team.objects.filter(id=event.is_team)
print(event.is_team)
if team:
team[0].team_member.add(event.contestant)
team[0].save()
if event.status == '2':
if event.event_type == 2:
event.phase.joiner.remove(event.contestant)
event.phase.save()
event.contestant.join_competition.remove(event.phase.competition)
event.contestant.save()
queryset = CompetitionAndContestant.objects.filter(competition=event.phase.competition, contestant=event.contestant)
if queryset:
queryset[0].is_joining = 0
queryset[0].save()
team = event.contestant.leader_team.filter(phase__exact=event.phase)
if team:
team[0].delete()
team = event.contestant.member_team.filter(phase__exact=event.phase)
if team:
team[0].team_member.remove(event.contestant)
elif event.event_type == 4:
team = event.contestant.leader_team.filter(phase__exact=event.phase)
if team:
contestant = ContestantUser.objects.get(id=event.is_team)
team[0].team_member.add(team[0].team_leader)
team[0].team_leader = contestant
team[0].team_member.remove(contestant)
team[0].save()
elif event.event_type == 5:
team = event.contestant.member_team.filter(phase__exact=event.phase)
if team:
team[0].team_member.add(team[0].team_leader)
team[0].team_leader = event.contestant
team[0].team_member.remove(event.contestant)
team[0].save()
elif event.event_type == 6:
enrolment = Enrolment.objects.filter(contestant=event.contestant, phase=event.phase)
if enrolment:
enrolment[0].enrolment_info = event.content
enrolment[0].save()
return Response({'status':event.status, 'reason':event.reason}, status=status.HTTP_200_OK)
return Response({}, status=status.HTTP_400_BAD_REQUEST)
class GetGrade(APIView):
#permission_classes = (IsAuthenticated)
def post(self, request):
phase = Phase.objects.get(id=request.data.get('phase_id'))
contestant = request.user.contestant_user
if contestant in phase.joiner.all():
serializer = PostGradeSerializer(data=request.data)
if serializer.is_valid():
grade_contestant = contestant
if(phase.max_group != 1 or phase.min_group != 1):
team = contestant.leader_team.filter(phase__exact=phase)
if len(team) <= 0:
team = contestant.member_team.filter(phase__exact=phase)
if len(team) <= 0:
return Response({}, status=status.HTTP_400_BAD_REQUEST)
grade_contestant = team[0].team_leader
serializer.save(phase=phase, contestant=grade_contestant)
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response({}, status=status.HTTP_400_BAD_REQUEST)
return Response({}, status=status.HTTP_400_BAD_REQUEST)
def get(self, request):
params = request.query_params.dict()
phase = Phase.objects.get(id=params.get('phase_id'))
if request.user.first_name == 'organizer' and request.user.organizer_user == phase.competition.organizer:
grade_type = params.get('grade_type')
if grade_type == '1':
grade_query_set = phase.grade.all()
if len(grade_query_set) <= 0:
return Response([], status=status.HTTP_200_OK)
current_page = int(params.get('current_page'))
grade_num = int(params.get('grade_num'))
min_num = grade_num * (current_page - 1)
max_num = grade_num * current_page - 1
if min_num >= 0 and max_num < len(grade_query_set):
grade_query_set = grade_query_set[min_num:max_num + 1]
elif min_num >= 0 and max_num > len(grade_query_set) and min_num < len(grade_query_set):
grade_query_set = grade_query_set[min_num:len(grade_query_set)]
else:
return Response({}, status=status.HTTP_400_BAD_REQUEST)
serializer = GradeSerializer(grade_query_set, many=True)
for grade in serializer.data:
if(phase.min_group != 1 or phase.max_group != 1):
team_leader = ContestantUser.objects.get(id=grade['contestant']['id'])
grade['contestant']['name'] = team_leader.leader_team.get(phase=phase).name
grade['time'] = grade['time'].split('.')[0].replace('T', ' ')
grade['handle_time'] = grade['handle_time'].split('.')[0].replace('T', ' ')
return Response(serializer.data, status=status.HTTP_200_OK)
else:
if phase.max_group == 1 and phase.min_group == 1:
joiner_query_set = phase.joiner.all()
else:
joiner_query_set = phase.team.all()
if len(joiner_query_set) <= 0:
return Response({'joiners': []}, status=status.HTTP_200_OK)
current_page = int(params.get('current_page'))
grade_num = int(params.get('grade_num'))
min_num = grade_num * (current_page - 1)
max_num = grade_num * current_page - 1
if min_num >= 0 and max_num < len(joiner_query_set):
joiner_query_set = joiner_query_set[min_num:max_num + 1]
elif min_num >= 0 and max_num > len(joiner_query_set) and min_num < len(joiner_query_set):
joiner_query_set = joiner_query_set[min_num:len(joiner_query_set)]
else:
return Response({}, status=status.HTTP_400_BAD_REQUEST)
joiners = []
for joiner in joiner_query_set:
if phase.max_group == 1 and phase.min_group == 1:
grade_query_set = joiner.grade.filter(phase__exact=phase)
else:
grade_query_set = joiner.team_leader.grade.filter(phase__exact=phase)
serializer = GradeSerializer(grade_query_set, many=True)
for grade in serializer.data:
grade['time'] = grade['time'].split('.')[0].replace('T', ' ')
grade['handle_time'] = grade['handle_time'].split('.')[0].replace('T', ' ')
joiners.append({'id': joiner.id, 'name': joiner.name, 'grades': serializer.data})
return Response({'joiners': joiners}, status=status.HTTP_200_OK)
class GradeNumber(APIView):
def get(self, request):
params = request.query_params.dict()
phase = Phase.objects.get(id=params.get('phase_id'))
if request.user.first_name == 'organizer' and request.user.organizer_user == phase.competition.organizer:
grade_type = params.get('grade_type')
if grade_type == '1':
grade_query_set = phase.grade.all()
return Response({'grade_number': len(grade_query_set)}, status=status.HTTP_200_OK)
else:
joiner_query_set = phase.joiner.all()
return Response({'joiner_number': len(joiner_query_set)}, status=status.HTTP_200_OK)
return Response({}, status=status.HTTP_400_BAD_REQUEST)
class HandleGrade(APIView):
#permission_classes = (IsAuthenticated)
def post(self, request):
grade = Grade.objects.get(id=request.data.get('grade_id'))
if request.user.first_name == 'organizer' and request.user.organizer_user == grade.phase.competition.organizer:
#grade.handle_content = request.data.get('handle_content')
grade.is_handled = 1
grade.submit_grade = request.data.get('submit_grade')
grade.save()
return Response({'submit_grade':grade.submit_grade}, status=status.HTTP_200_OK)
return Response({}, status=status.HTTP_400_BAD_REQUEST)
class LeaderBoard(APIView):
def get(self, request):
params = request.query_params.dict()
phase = Phase.objects.get(id=params.get('phase_id'))
grade_query_set = phase.grade.all().order_by('-submit_grade')
serializer = GradeSerializer(grade_query_set, many=True)
for grade in serializer.data:
if phase.min_group != 1 or phase.max_group != 1:
team_leader = ContestantUser.objects.get(id=grade['contestant']['id'])
grade['contestant']['name'] = team_leader.leader_team.get(phase=phase).name
grade['time'] = grade['time'].split('.')[0].replace('T', ' ')
grade['handle_time'] = grade['handle_time'].split('.')[0].replace('T', ' ')
return Response(serializer.data, status=status.HTTP_200_OK)
class SubmitHistory(APIView):
def get(self, request):
params = request.query_params.dict()
phase = Phase.objects.get(id=params.get('phase_id'))
if request.user.first_name == 'contestant':
contestant = request.user.contestant_user
grade_query_set = contestant.grade.filter(phase__exact=phase)
serializer = GetGradeSerializer(grade_query_set, many=True)
for grade in serializer.data:
if phase.min_group != 1 or phase.max_group != 1:
team_leader = ContestantUser.objects.get(id=grade['contestant']['id'])
grade['contestant']['name'] = team_leader.leader_team.get(phase=phase).name
grade['time'] = grade['time'].split('.')[0].replace('T', ' ')
grade['handle_time'] = grade['handle_time'].split('.')[0].replace('T', ' ')
return Response(serializer.data, status=status.HTTP_200_OK)
class SendGroupMessage(APIView):
def post(self, request):
serializer = GroupMessageSerializer(data=request.data)
if serializer.is_valid():
competition = Competition.objects.get(id=request.data.get('competition_id'))
group_message = serializer.save(competition=competition)
contestant_ids = json.loads(request.data.get('contestant_id'))
for contestant_id in contestant_ids:
contestant = ContestantUser.objects.get(id=contestant_id)
group_message.receiver.add(contestant)
group_message.save()
if group_message.status == 1:
for contestant in group_message.receiver.all():
personal_letter = PersonalLetter()
personal_letter.receiver = contestant.user
personal_letter.sender = competition.organizer.user
personal_letter.is_read = 0
personal_letter.content = group_message.title + ' 这是比赛 ' + competition.name + ' 的通知\n ' + group_message.content
personal_letter.save()
return Response({}, status=status.HTTP_201_CREATED)
return Response({}, status=status.HTTP_400_BAD_REQUEST)
def get(self, request):
competition = Competition.objects.get(id=request.query_params.dict().get('competition_id'))
if request.user.first_name == 'organizer' and request.user.organizer_user == competition.organizer:
saving_group_messages = []
published_group_messages = []
for group_message in competition.group_message.filter(status__exact=0):
saving_group_messages.append({'id':group_message.id, 'title':group_message.title, 'content':group_message.content})
for group_message in competition.group_message.filter(status__exact=1):
published_group_messages.append({'id':group_message.id, 'title':group_message.title, 'content':group_message.content})
return Response({'saving_group_messages':saving_group_messages, 'published_group_messages':published_group_messages},\
status=status.HTTP_200_OK)
return Response({'reason': 1}, status=status.HTTP_400_BAD_REQUEST)
class ReceiveGroupMessage(APIView):
permission_classes = (IsAuthenticated)
def get(self, request):
if request.user.first_name == 'organizer':
group_messages = request.user.contestant_user.group_message.filter(status__exact=1)
response = []
for group_message in group_messages:
competition = group_message.competition
competition_dic = {'id': competition.id, 'name': competition.name}
organizer = competition.organizer
organizer_dic = {'id': organizer.id, 'name': organizer.name}
group_message_dic = {'id': group_message.id, 'title':group_message.title, 'content':group_message.content}
response.append({'organizer':organizer_dic, 'competition':competition_dic, 'group_message':group_message_dic})
return Response(response, status=status.HTTP_200_OK)
return Response({'reason': 1}, status=status.HTTP_400_BAD_REQUEST)
class GroupMessageDetail(mixins.RetrieveModelMixin, mixins.UpdateModelMixin, mixins.DestroyModelMixin, generics.GenericAPIView):
queryset = GroupMessage.objects.all()
serializer_class = GroupMessageSerializer
#permission_classes = (IsNoticeOwnerOrReadOnly,)
def put(self, request, *args, **kwargs):
return self.update(request, *args, **kwargs)
def delete(self, request, *args, **kwargs):
return self.destroy(request, *args, **kwargs)
def get(self, request, *args, **kwargs):
return self.retrieve(request, *args, **kwargs)
def post(self, request, *args, **kwargs):
return self.update(request, *args, **kwargs)
class ListPhase(APIView):
def get(self, request):
queryset = Competition.objects.get(id=self.request.query_params.dict().get("id")).phase.all()
serializer = PhaseSerializer(queryset, many=True)
res = serializer.data
for i in res:
i['start_time'] = i['start_time'].split('+')[0].replace('T', ' ')
i['sign_start_time'] = i['sign_start_time'].split('+')[0].replace('T', ' ')
i['end_time'] = i['end_time'].split('+')[0].replace('T', ' ')
i['sign_end_time'] = i['sign_end_time'].split('+')[0].replace('T', ' ')
return Response(serializer.data, status=status.HTTP_200_OK)
class ListPhaseSimple(APIView):
def get(self, request):
queryset = Competition.objects.get(id=self.request.query_params.dict().get("id")).phase.all()
serializer = SimplePhaseSerializer(queryset, many=True)
return Response(serializer.data, status=status.HTTP_200_OK)
class CreatePhase(generics.ListCreateAPIView):
queryset = Competition.objects.all()
serializer_class = PhaseDetialSerializer
permission_classes = (permissions.IsAuthenticatedOrReadOnly,)
def perform_create(self, serializer):
comp = Competition.objects.get(id=self.request.data.get('id'))
serializer.save(competition=comp, start_time=datetime.datetime.fromtimestamp(int(self.request.data.get('starttime')) / 1000),\
end_time=datetime.datetime.fromtimestamp(int(self.request.data.get('endtime')) / 1000),\
sign_start_time=datetime.datetime.fromtimestamp(int(self.request.data.get('signstarttime')) / 1000),\
sign_end_time=datetime.datetime.fromtimestamp(int(self.request.data.get('signendtime')) / 1000))
class DetailPhase(mixins.RetrieveModelMixin, mixins.UpdateModelMixin, mixins.DestroyModelMixin, generics.GenericAPIView):
queryset = Phase.objects.all()
serializer_class = PhaseSerializer
#permission_classes = (IsOwnerOrReadOnly,)
def get(self, request, *args, **kwargs):
return self.retrieve(request, *args, **kwargs)
def post(self, request, *args, **kwargs):
obj = self.get_object()
if self.request.data.get('starttime') is not None:
obj.start_time = datetime.datetime.fromtimestamp(int(self.request.data.get('starttime')) / 1000)
obj.end_time = datetime.datetime.fromtimestamp(int(self.request.data.get('endtime')) / 1000)
obj.sign_start_time = datetime.datetime.fromtimestamp(int(self.request.data.get('signstarttime')) / 1000)
obj.sign_end_time = datetime.datetime.fromtimestamp(int(self.request.data.get('signendtime')) / 1000)
obj.save()
return self.update(request, *args, **kwargs)
def delete(self, request, *args, **kwargs):
return self.destroy(request, *args, **kwargs)
class CreateEnrolment(generics.ListCreateAPIView):
queryset = Enrolment.objects.all()
serializer_class = EnrolmentSerializer
permission_classes = (permissions.IsAuthenticatedOrReadOnly,)
def perform_create(self, serializer):
cont = self.request.user.contestant_user
pha = Phase.objects.get(id=self.request.data.get('id'))
serializer.save(phase=pha, contestant=cont)
class GroupMessageStatus(APIView):
#permission_classes = (IsAuthenticated)
def post(self, request):
group_message = GroupMessage.objects.get(id=request.data.get('group_message_id'))
if request.user.first_name == 'organizer' and request.user.organizer_user == group_message.competition.organizer:
new_status = request.data.get('new_status')
if new_status == '1':
group_message.status = 1
group_message.save()
for contestant in group_message.receiver.all():
personal_letter = PersonalLetter()
personal_letter.receiver = contestant.user
personal_letter.sender = competition.organizer.user
personal_letter.is_read = 0
personal_letter.content = group_message.title + ' ' + competition.name + '\n ' + group_message.content
personal_letter.save()
return Response({}, status=status.HTTP_200_OK)
elif new_status == '2':
group_message.delete()
return Response({}, status=status.HTTP_200_OK)
return Response({'reason': 2}, status=status.HTTP_400_BAD_REQUEST)
return Response({'reason': 1}, status=status.HTTP_400_BAD_REQUEST)
class GetTeam(APIView):
def post(self, request):
if request.user.is_authenticated():
contestant = request.user.contestant
phase = Phase.objects.get(id=request.data.get('phase_id'))
for team in contestant.leader_team:
if team.phase == phase:
return Response({'reason': 1}, status=status.HTTP_400_BAD_REQUEST)
for team in contestant.member_team:
if team.phase == phase:
return Response({'reason': 1}, status=status.HTTP_400_BAD_REQUEST)
team = Team()
team.name = request.data.get('name')
team.introduction = request.data.get('introduction')
team.team_leader = contestant
team.phase = phase
team.save()
return Response({}, status=status.HTTP_200_OK)
return Response({'reason': 0}, status=status.HTTP_401_UNAUTHORIZED)
def get(self, request):
if request.user.is_authenticated():
params = request.query_params.dict()
phase = Phase.objects.get(id=params.get('phase_id'))
if request.user.first_name == 'organizer':
organizer = request.user.organizer_user
if organizer == phase.competition.organizer:
team_list = []
for team in phase.team.all():
team_list.append({'team_name': team.name})
return Response({'team_list': team_list}, status=status.HTTP_200_OK)
return Response({'reason': 1}, status=status.HTTP_400_BAD_REQUEST)
elif request.user.first_name == 'contestant':
team_datas = []
for team in phase.team.all():
leader = team.team_leader
team_leader = {'uid': leader.user.id, 'id': leader.id, 'name': leader.name}
team_number = 1 + len(team.team_member.all())
team_datas.append({'team_id': team.id, 'team_name': team.name, 'team_leader': team_leader, 'team_number': team_number,\
'create_time': team.create_time.strftime("%Y-%m-%d %H:%M:%S")})
return Response({'team_datas': team_datas}, status=status.HTTP_200_OK)
return Response({'reason': 0}, status=status.HTTP_401_UNAUTHORIZED)
class TeamDetail(APIView):
def get(self, request):
if request.user.is_authenticated():
if request.user.first_name == 'contestant':
contestant = request.user.contestant_user
params = request.query_params.dict()
phase = Phase.objects.get(id=params.get('phase_id'))
teams = contestant.leader_team.filter(phase__exact=phase)
if teams:
team = teams[0]
team_player = {'uid': contestant.user.id, 'id': contestant.id, 'name': contestant.name, 'identity': '队长'}
team_datas = []
team_datas.append(team_player)
for team_member in team.team_member.all():
team_datas.append({'uid': team_member.user.id, 'id': team_member.id, 'name':team_member.name, 'identity': '队员'})
return Response({'team_id': team.id, 'team_player': team_player, 'team_datas': team_datas}, status=status.HTTP_200_OK)
teams = contestant.member_team.filter(phase__exact=phase)
if teams:
team = teams[0]
team_player = {'name': contestant.name, 'identity': '队员'}
team_datas = []
team_datas.append({'uid': team.team_leader.user.id, 'id': team.team_leader.id, 'name':team.team_leader.name, 'identity': '队长'})
for team_member in team.team_member.all():
team_datas.append({'uid': team_member.user.id, 'id': team_member.id, 'name':team_member.name, 'identity': '队员'})
return Response({'team_id': team.id, 'team_player': team_player, 'team_datas': team_datas}, status=status.HTTP_200_OK)
return Response({'reason': 1}, status=status.HTTP_401_UNAUTHORIZED)
return Response({'reason': 0}, status=status.HTTP_401_UNAUTHORIZED)
class InvitationCode(APIView):
def get(self, request):
if request.user.is_authenticated() and request.user.first_name == 'contestant':
contestant = request.user.contestant_user
params = request.query_params.dict()
team = Team.objects.get(id=params.get('team_id'))
if team.team_leader != contestant:
return Response({'reason': 1}, status=status.HTTP_400_BAD_REQUEST)
if team.invitation_code == '':
invitation_codes = []
else:
invitation_codes = json.loads(team.invitation_code)
member_number = len(team.team_member.all()) + 1 + len(invitation_codes)
if member_number > 3:
return Response({'reason': 2}, status=status.HTTP_400_BAD_REQUEST)
invitation_code = make_password(team.name, None, 'pbkdf2_sha256')
invitation_codes.append(invitation_code)
team.invitation_code = json.dumps(invitation_codes)
team.save()
return Response({'invitation_code':invitation_code}, status=status.HTTP_200_OK)
return Response({'reason': 0}, status=status.HTTP_401_UNAUTHORIZED)
def post(self, request):
if request.user.is_authenticated() and request.user.first_name == 'contestant':
contestant = request.user.contestant_user
team = Team.objects.get(id=request.data.get('team_id'))
invitation_code = request.data.get('invitation_code')
if team.invitation_code == '':
invitation_codes = []
else:
invitation_codes = json.loads(team.invitation_code)
if invitation_code in invitation_codes:
invitation_codes.remove(invitation_code)
team.invitation_code = json.dumps(invitation_codes)
team.save()
return Response({'is_join': 1}, status=status.HTTP_200_OK)
return Response({'is_join': 0}, status=status.HTTP_200_OK)
return Response({'reason': 0}, status=status.HTTP_401_UNAUTHORIZED)
class CreateAttachment(generics.ListCreateAPIView):
queryset = Attachment.objects.all()
serializer_class = AttachmentSerializer
#permission_classes = (permissions.IsAuthenticatedOrReadOnly,)
def perform_create(self, serializer):
comp = Competition.objects.get(id=self.request.data.get('cmp_id'))
serializer.save(competition=comp)
class ListAttachment(APIView):
def get(self, request):
queryset = Competition.objects.get(id=self.request.query_params.dict().get("id")).attachment
serializer = AttachmentSerializer(queryset, many=True)
return Response(serializer.data, status=status.HTTP_200_OK)
class DeleteAttachment(APIView):
def post(self, request):
atta = Attachment.objects.get(id=self.request.data.get("id"))
if request.user.is_authenticated() and request.user == atta.competition.organizer.user:
os.remove('frontend/dist/' + atta.attachment_url)
atta.delete()
return Response({}, status=status.HTTP_200_OK)
return Response({}, status=status.HTTP_401_UNAUTHORIZED)
class JoinerNumber(APIView):
def get(self, request):
params = request.query_params.dict()
phase = Phase.objects.get(id=params.get('phase_id'))
if request.user.first_name == 'organizer' and request.user.organizer_user == phase.competition.organizer:
if phase.max_group == phase.min_group and phase.max_group == 1:
joiner_number = len(phase.joiner.all())
else:
joiner_number = len(phase.team.all())
return Response({'joiner_number': joiner_number}, status=status.HTTP_200_OK)
return Response({}, status=status.HTTP_400_BAD_REQUEST)
class Joiner(APIView):
def get(self, request):
params = request.query_params.dict()
phase = Phase.objects.get(id=params.get('phase_id'))
if request.user.first_name == 'organizer' and request.user.organizer_user == phase.competition.organizer:
current_page = int(params.get('current_page'))
joiner_num = int(params.get('joiner_num'))
min_num = joiner_num * (current_page - 1)
max_num = joiner_num * current_page - 1
if(phase.max_group == phase.min_group and phase.max_group == 1):
joiner_query_set = phase.joiner.all()
if len(joiner_query_set) <= 0:
return Response({'joiners': []}, status=status.HTTP_200_OK)
if min_num >= 0 and max_num < len(joiner_query_set):
max_num = max_num + 1
elif min_num >= 0 and max_num >= len(joiner_query_set) and min_num < len(joiner_query_set):
max_num = len(joiner_query_set)
else:
return Response({}, status=status.HTTP_400_BAD_REQUEST)
joiner_query_set = joiner_query_set[min_num:max_num]
joiners = []
for joiner in joiner_query_set:
joiners.append({'joiner': {'id': joiner.id, 'name': joiner.name}, 'grade': '123'})
else:
joiner_query_set = phase.team.all()
if len(joiner_query_set) <= 0:
return Response({'joiners': []}, status=status.HTTP_200_OK)
if min_num >= 0 and max_num < len(joiner_query_set):
max_num = max_num + 1
elif min_num >= 0 and max_num >= len(joiner_query_set) and min_num < len(joiner_query_set):
max_num = len(joiner_query_set)
else:
return Response({}, status=status.HTTP_400_BAD_REQUEST)
joiner_query_set = joiner_query_set[min_num:max_num]
joiners = []
for joiner in joiner_query_set:
team = {'id': joiner.id, 'name': joiner.name}
leader = {'id': joiner.team_leader.id, 'name': joiner.team_leader.name, 'identity': '队长'}
members = []
members.append(leader)
for member in joiner.team_member.all():
members.append({'id': member.id, 'name': member.name, 'identity': '队员'})
team_number = len(joiner.team_member.all()) + 1
joiners.append({'stage_id': params.get('phase_id'), 'team': team, 'team_number': team_number,\
'create_date': joiner.create_time, 'leader': leader, 'team_member': members})
return Response({'joiners': joiners}, status=status.HTTP_200_OK)
return Response({}, status=status.HTTP_400_BAD_REQUEST)
class JoinerType(APIView):
def get(self, request):
params = request.query_params.dict()
phase = Phase.objects.get(id=params.get('phase_id'))
if phase:
joiner_type = 1
if phase.max_group == 1 and phase.min_group == 1:
joiner_type = 0
joiner_number = len(phase.joiner.all())
else:
joiner_number = len(phase.team.all())
return Response({'joiner_type': joiner_type, 'joiner_number': joiner_number}, status=status.HTTP_200_OK)
return Response({}, status=status.HTTP_400_BAD_REQUEST)
class AddJoiner(APIView):
def post(self, request):
phase = Phase.objects.get(id=request.data.get('phase_id'))
if request.user.first_name == 'organizer' and request.user.organizer_user == phase.competition.organizer:
contestant_ids = json.loads(request.data.get('contestant_id'))
for contestant_id in contestant_ids:
contestant = ContestantUser.objects.get(id=contestant_id)
phase.joiner.add(contestant)
phase.save()
return Response({}, status=status.HTTP_200_OK)
return Response({}, status=status.HTTP_400_BAD_REQUEST)
class AndContestant(APIView):
def get(self, request):
comp = Competition.objects.get(id=self.request.query_params.dict().get("id"))
user = request.user
try:
queryset = CompetitionAndContestant.objects.get(competition=comp, contestant=user.contestant_user)
serializer = CompetitionAndContestantSerializer(queryset)
return Response(serializer.data, status=status.HTTP_200_OK)
except Exception as exception:
return Response({'error': str(exception)}, status=status.HTTP_400_BAD_REQUEST)
def post(self, request):
comp = Competition.objects.get(id=self.request.data.get('id'))
user = request.user
if user.is_authenticated():
queryset = CompetitionAndContestant.objects.filter(competition=comp, contestant=user.contestant_user)
if queryset:
queryset[0].is_focus = self.request.data.get('is_focus')
queryset[0].is_joining = self.request.data.get('is_joining')
queryset[0].is_remind = self.request.data.get('is_remind')
queryset[0].save()
else:
serializer = CompetitionAndContestantSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
else:
return Response({'returnCode': 0}, status=status.HTTP_401_UNAUTHORIZED)
class Enroll(APIView):
def post(self, request):
user = self.request.user
if user.first_name != 'contestant':
return Response({}, status=status.HTTP_400_BAD_REQUEST)
contestant = self.request.user.contestant_user
serializer = EnrolmentSerializer(data=request.data)
phase = Phase.objects.get(id=request.data.get('phase_id'))
if serializer.is_valid():
serializer.save(contestant=contestant, phase=phase)
event = Event()
event.phase = phase
event.contestant = contestant
if event.phase.max_group == 1:
event.is_team = 0
else:
event.is_team = 1
event.event_type = 1
if request.data.get('join_status') == '1':
event.event_type = 8
event.is_team = request.data.get('team_id')
event.content = request.data.get('enrolment_info')
event.save()
queryset = CompetitionAndContestant.objects.filter(competition=event.phase.competition, contestant=contestant)
if queryset:
queryset[0].is_joining = 1
queryset[0].current_phase = event.phase
queryset[0].save()
else:
competition_and_contestant = CompetitionAndContestant()
competition_and_contestant.contestant = event.contestant
competition_and_contestant.competition = event.phase.competition
competition_and_contestant.current_phase = event.phase
competition_and_contestant.is_joining = 1
competition_and_contestant.save()
return Response({'returnCode':0, 'id':serializer.data.get('id')}, status=status.HTTP_201_CREATED) #serializer.data
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
class StateUpdate(APIView):
def get(self, request):
comp = Competition.objects.get(id=self.request.query_params.dict().get("id"))
now_time = datetime.timedelta(hours=-8) + datetime.datetime.now()
for i in comp.phase.all():
if i.start_time.replace(tzinfo=None) < now_time and i.end_time.replace(tzinfo=None) > now_time:
i.competition_ongoing = i.competition
else:
i.competition_ongoing = None
if i.sign_start_time.replace(tzinfo=None) < now_time and i.sign_end_time.replace(tzinfo=None) > now_time and i.able_to_sign:
i.competition_enrolling = i.competition
else:
i.competition_enrolling = None
i.save()
if not comp.phase_ongoing.all():
comp.category = 0
recent_end_phase = Phase()
recent_end_time = datetime.datetime.fromtimestamp(0)
for i in comp.phase.all():
if i.end_time.replace(tzinfo=None) < now_time and i.end_time.replace(tzinfo=None) > recent_end_time:
recent_end_time = i.end_time
recent_end_phase = i
if recent_end_time.replace(tzinfo=None) > datetime.datetime.fromtimestamp(0):
recent_end_phase.competition_ongoing = recent_end_phase.competition
else:
comp.category = 1
comp.save()
ser = CompetitionDetialSerializer(comp)
data = ser.data
data['organizer']['uid'] = comp.organizer.user.id
if comp.phase_ongoing.all():
data['team_number'] = comp.phase_ongoing.all()[0].joiner.all().count()
data['focus_number'] = comp.followers.all().count()
else:
data['team_number'] = 0
data['focus_number'] = 0
for i in data['phase_enrolling']:
i['start_time'] = i['start_time'].split('+')[0].replace('T', ' ')
i['sign_start_time'] = i['sign_start_time'].split('+')[0].replace('T', ' ')
i['end_time'] = i['end_time'].split('+')[0].replace('T', ' ')
i['sign_end_time'] = i['sign_end_time'].split('+')[0].replace('T', ' ')
for i in data['phase_ongoing']:
i['start_time'] = i['start_time'].split('+')[0].replace('T', ' ')
i['sign_start_time'] = i['sign_start_time'].split('+')[0].replace('T', ' ')
i['end_time'] = i['end_time'].split('+')[0].replace('T', ' ')
i['sign_end_time'] = i['sign_end_time'].split('+')[0].replace('T', ' ')
return Response(data, status=status.HTTP_200_OK)
class EnrolmentInfo(APIView):
def get(self, request):
if request.user.is_authenticated():
contestant = request.user.contestant_user
phase = Phase.objects.filter(id=request.query_params.dict().get("id"))
if phase:
enrolment = Enrolment.objects.filter(phase=phase[0], contestant=contestant)
if enrolment:
serializer = EnrolmentSerializer(enrolment[0])
return Response(serializer.data, status=status.HTTP_200_OK)
return Response({}, status=status.HTTP_404_NOT_FOUND)
return Response({}, status=status.HTTP_404_NOT_FOUND)
return Response({'returnCode':0}, status=status.HTTP_401_UNAUTHORIZED)
class ListContestant(APIView):
def get(self, request):
comp_id = request.query_params.dict().get("comp_id")
phase_id = request.query_params.dict().get("phase_id")
if phase_id == '-1':
competition = Competition.objects.get(id=comp_id)
queryset = competition.joiners.all()
else:
phase = Phase.objects.get(id=phase_id)
queryset = phase.joiner.all()
serializer = SimpleContestantUserSerializer(queryset, many=True)
for i_serializer in serializer.data:
i = ContestantUser.objects.get(id=i_serializer['id'])
grade_max = None
grade_latest = None
if phase_id != '-1':
for j in i.grade.all().filter(phase=phase).exclude(is_handled=0):
if grade_max == None or grade_max.submit_grade < j.submit_grade:
grade_max = j
if grade_latest == None or grade_latest.time < grade_latest.time:
grade_latest = j
i_serializer['grade_max'] = SimpleGradeSerializer(grade_max).data
i_serializer['grade_latest'] = SimpleGradeSerializer(grade_latest).data
return Response(serializer.data, status=status.HTTP_200_OK)
class CreateComment(APIView):
def post(self, request):
serializer = SimpleCompetitionCommentSerializer(data=request.data)
if serializer.is_valid():
competition = Competition.objects.get(id=request.data.get('competition_id'))
floor = len(competition.comment.all()) + 1
comment_id = request.data.get('comment_id')
if comment_id:
link_comment = CompetitionComment.objects.get(id=comment_id)
serializer.save(author=self.request.user, competition=competition, floor=floor, link_comment=link_comment)
else:
serializer.save(author=self.request.user, competition=competition, floor=floor)
return Response({'id':serializer.data.get('id')}, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def get(self, request):
params = request.query_params.dict()
competition = Competition.objects.get(id=params.get('competition_id'))
query_set = competition.comment.all()
current_page = int(params.get('current_page'))
comment_num = int(params.get('comment_num'))
min_num = comment_num * (current_page - 1)
max_num = comment_num * current_page - 1
if len(query_set) <= 0:
return Response({}, status=status.HTTP_200_OK)
if min_num >= 0 and max_num < len(query_set):
max_num = max_num + 1
elif min_num >= 0 and max_num >= len(query_set) and min_num < len(query_set):
max_num = len(query_set)
else:
return Response({}, status=status.HTTP_400_BAD_REQUEST)
query_set = query_set[min_num:max_num]
serializer = CompetitionCommentSerializer(query_set, many=True)
for comment in serializer.data:
comment['post_time'] = comment['post_time'].split('.')[0].replace('T', ' ')
return Response(serializer.data, status=status.HTTP_200_OK)
class CommentNumber(APIView):
def get(self, request):
params = request.query_params.dict()
competition = Competition.objects.get(id=params.get('competition_id'))
query_set = competition.comment.all()
return Response({'comment_number': len(query_set)}, status=status.HTTP_200_OK)
class CommentDetail(mixins.RetrieveModelMixin, mixins.UpdateModelMixin, mixins.DestroyModelMixin, generics.GenericAPIView):
queryset = CompetitionComment.objects.all()
serializer_class = SimpleCompetitionCommentSerializer
#permission_classes = (IsOwnerOrReadOnly,)
def get(self, request, *args, **kwargs):
return self.retrieve(request, *args, **kwargs)
def put(self, request, *args, **kwargs):
return self.update(request, *args, **kwargs)
def delete(self, request, *args, **kwargs):
return self.destroy(request, *args, **kwargs)
|
#!/usr/bin/python
#
# icarusay.py
#
# Written by Earl Cash <erl@codeward.org> in 2014.
import sys, os, getopt, math, time, signal
def sig_handler (signo, frame):
sys.exit (signo)
def usage ():
print "Usage:"
print " "+ os.path.basename (sys.argv[0]) +" [OPTIONS]"
print "\nOptions:"
print " -l=N\tprint N lines of a message (if N is not an even number, addition will occur)"
print " -n=N\tprint a message N times (if N is equal to 0, infinity is assumed)"
print " -m=N\tchoose a message being printed (valid range 0-1)"
print " -s=N\tspeed of typing an individual line in seconds (supports a number with decimal precision)"
print " -h\tdisplay this usage text"
def main (argv):
messages = {
0: [ "ICARUS IS LOOKING FOR YOU" ],
1: [ "ICARUS FOUND YOU!!!", "RUN WHILE YOU CAN!!!" ]
}
opts_data = {
"p": os.path.basename (sys.argv[0]),
"lines": 20,
"repeat": 1,
"message_type": 0,
"speed": 0
}
try:
opts, args = getopt.gnu_getopt (argv[1:], "l:n:m:s:h")
except getopt.GetoptError as err:
usage ()
sys.exit (1)
for opt, arg in opts:
if opt == "-l":
try:
opts_data["lines"] = int (arg)
except ValueError:
print (opts_data["p"]+": invalid number (param -l)")
sys.exit (1)
if (opts_data["lines"] % 2) != 0:
opts_data["lines"] += 1
elif opt == "-n":
try:
opts_data["repeat"] = int (arg)
except ValueError:
print (opts_data["p"]+": invalid number (param -n)")
sys.exit (1)
elif opt == "-m":
try:
opts_data["message_type"] = int (arg)
except ValueError:
print (opts_data["p"]+": invalid number (param -m)")
sys.exit (1)
if not opts_data["message_type"] in messages:
print (opts_data["p"]+": undefined message index")
sys.exit (1)
elif opt == "-s":
try:
opts_data["speed"] = float (arg)
except ValueError:
print (opts_data["p"]+": invalid number (param -s)")
sys.exit (1)
elif opt == "-h":
usage ()
sys.exit (0)
if opts_data["message_type"] == 0:
repeat_counter = 0
while True:
for line in range (opts_data["lines"]):
print ((" " * line)+messages[0][0])
time.sleep (opts_data["speed"])
repeat_counter += 1
if opts_data["repeat"] > 0 and repeat_counter >= opts_data["repeat"]:
break
elif opts_data["message_type"] == 1:
repeat_counter = 0
while True:
for line in range (int (math.floor (float (opts_data["lines"]) / 2.0))):
print ((" " * line)+messages[1][0])
time.sleep (opts_data["speed"])
for line in range (int (math.floor (float (opts_data["lines"]) / 2.0)) - 1, -1, -1):
print ((" " * line)+messages[1][1])
time.sleep (opts_data["speed"])
repeat_counter += 1
if opts_data["repeat"] > 0 and repeat_counter >= opts_data["repeat"]:
break
if __name__ == "__main__":
signal.signal (signal.SIGINT, sig_handler)
signal.signal (signal.SIGTERM, sig_handler)
main (sys.argv);
|
# Viraland is a batch-job control program, especially for bioinfomatics data
# file flow control and analysis. Viraland can be run directly in Python 3
# console or be run with a configuration file.
# This program also supply a good amount of API to make data processing more
# flexible.
# author: Yubing Hou
# license: GPL v3
import os
import sys
# Configuration class: user can configure commands and file path easily in
# Python console or use a configuration file
# TODO: Finishi this class
class VLConfig:
def __init__(self):
self.title = None
self.log = None
self.keep = None
self.velvetcmd = None
self.velvetin = None
self.velvetout = None
self.embosscmd = None
self.embossin = None
self.embossout = None
self.paudacmd = None
self.paudain = None
self.paudaout = None
self.yparsein = None
self.yparseout = None
self.cparsein = None
self.cparseout = None
self.visualin = None
self.visualout = None
def get_title (self):
return self.title
def get_log (self):
return self.log
def set_title (self, title):
self.title = str(title)
def set_log (self, option):
self.log = bool (option)
def set_keep (self, option):
self.keep = bool(option)
def set_velvet (self, cmd):
self.velvetcmd = str(cmd)
def parse_and_set (self, line):
if line.startswith("[TITLE]"):
self.title = line.split("]")[1].strip()
if line.startswith("[LOG]"):
option = line.split("]")[1].strip()
if option == "y":
self.log = True
else:
self.log = False
if line.startswith("[KEEP]"):
option = line.split("]")[1].strip()
if option == "y":
self.keep = True
else:
self.keep = False
print ("In development")
def use_config (self, file):
path = str(file)
fd = open (path)
for line in fd:
self.parse_and_set (line)
# Execution class: instantiate this class by taking a VLConfig instance. This
# allows multiple executions in one session of run.
# TODO: Finish this class
class VLRun:
def __init__ (self, config):
self.config = VLConfig (config)
self.log = None
def getconfig (self):
return self.config
def setlog (self):
if self.config.getlog() == True:
fd = open (self.config.get_title())
self.log = fd
def execute (self):
self.setlog ()
print ("In development")
def yparse (self):
print ("In development")
# Class of managing velvet: instantiate this class so that command of velvet
# can match user's system settings.
# TODO: finish this class
class VelvetPack:
def __init__(self):
self.fasta = []
self.fastq = []
def addfasta(self, path):
self.fasta.append(str(path))
# Class of managing Emboss: instantiate this class so that command of Emboss
# cand mathc user's system setting
# TODO: finish this class
class EmbossPack:
#Josh
def __init__(self, inDirectory):
self.inFiles = inDirectory
# Class of managing FAA file: instantiate this class so that command of FAA
# cand mathc user's system setting
# TODO: finish this class. Also, what is faa exactly is? a file for fasta/fastq?
class FaaPack:
def __init__(self):
self.folder = input('Enter the folder of faas that need to be concatenated')
def concatFiles(self):
subprocess.call(['cd', self.folder])
subprocess.call(['cat', '*', '.faa', '>', '../allTogether.faa'])
# Class of managing Pauda: instantiate this class so that command of Pauda
# cand mathc user's system setting
# TODO: finish this class. Should be expandable to bowtie if needed. Bowtie
# might be more well-known by people than Pauda
class PaudaPack:
#YB
def __init__(self):
self.fasta = []
self.fastq = []
self.out = ""
# Class of managing Parsers: instantiate this class so that command of parsers
# cand mathc user's system setting
# TODO: finish this class. Also, parser must follow the same format!
# Parser must be like this: $ ./parser [input file] [output file]
class ParsePack:
#YB
def __init__(self, name):
"""
ParsePack(name) set a parser for files with a job name
"""
self.name = str(name)
self.prog = None
self.inputs = []
self.outputs = []
def getname (self):
return self.name
def setparser (self, prog):
"""
parser program must be executed in this format:
$ [program] [input] [output]
For example, if [program] is a Java program MyParser, prog should be:
"java MyParser"
If [program] is in /usr/bin, for example, /usr/bin/MyParser, prog
should be:
"/usr/bin/MyParser"
"""
self.prog = str(prog)
def run (self):
for item in self.inputs:
out = self.item + "-output.txt"
exe = self.prog + " " + self.item + " " + out
# Class of managing Karona: instantiate this class so that command of Karona
# can match user's system setting
# TODO: finish this class
class KaronaPack:
#Jon
def __init__(self):
self.output = []
# Class of managing visualization: instantiate this class so that command of
# visualization can match user's system setting
# TODO: finish this class
class VisualPack:
#Need to get GBKs from user
#Have user provide GBK directory
#Use .glob to get all the GBKs
#Write out to a file, send file to Jons program as argument
def __init__(self):
self.paths = []
self.cmd = None
def setplotcmd (self, instr):
self.cmd = str(instr)
def addfile (self, path):
self.paths.append(path)
def plot(self, item):
if item in self.paths:
exe = self.cmd + " " + item
os.system(exe)
else:
print ("[System] Cannot find item:", item)
def plotall(self):
"""
applying plot command on all input file that is in file list.
Example:
>>> visual = VisualPack()
>>> visual.addfile(myfile.txt)
>>> visual.setplotcmd ("java viralplot")
>>> visual.plotall()
"""
for item in self.paths:
exe = self.cmd + " " + item
os.system(exe)
def reset (self):
"""
reset all configuration of an instance of VisualPack. Example:
"""
self.path = []
self.cmd = None
def status (self):
"""
Get the complete configuration of visualization. Example:
>>> visual = VisualPack()
>>> visual.setplotcmd ("java viralplot")
>>> visual.addfile ("data_01.txt")
>>> visual.addfile ("data_02.txt")
>>> visual.status()
command = java viralplot
file(s):
data_01.txt
data_02.txt
>>>
"""
print ("command =", self.cmd)
print ("file(s):")
for item in self.paths:
print ("\t", item)
|
import requests
from almaany.models import Hasil, Pencarian, create_tables
from almaany.parser import Parser
create_tables()
class Endpoint(object):
AL_WASEETH = "http://www.almaany.com/ar/dict/ar-ar/{q}/?c=المعجم الوسيط"
class Almaany(object):
"""class tentang almaany"""
def __init__(self, mujam, expire_after=None):
"""mujam: pilihan mu'jam (waseeth, )
expire_after: setelah berapa lama nanti dia expired"""
self.mujam = mujam
self.expire_after = expire_after
def tarjamah(self, query):
"""terjemahkan query, menurut self.mujam"""
if self.mujam == 'waseeth':
return self.waseeth(query)
return NotImplementedError
def waseeth(self, query):
query_db = Hasil.select(query, self.expire_after)
if len(query_db) > 0:
return query_db
resp_text = requests.get(Endpoint.AL_WASEETH.format(q=query)).text
parser = Parser(resp_text)
entities = parser.get_entities_with_query(query)
if entities:
Pencarian.insert(query)
Hasil.insert_many(entities)
rows = Hasil.select(query, self.expire_after)
return rows
return
|
k, m, n = map(int, input().split())
cook = n // k
if n % k != 0:
cook += 1
cook = cook * m * 2
print(cook) |
import sys
# http://www.techiedelight.com/find-duplicate-element-limited-range-array/
# Given a limited range array of size n where array contains elements in
# range 1 to n-1 with one element repeating, find duplicate number.
# using xor :: O(n) O(1) space
def find_duplicate(arr):
print(arr)
xor = 0
for x in arr:
xor ^= x
return x
# using hashing :: O(n) O(n) space
# using '-' sign :: O(n) O(1) space
def find_duplicate2(arr):
print(arr)
for x in arr:
xx = abs(x)
if arr[xx] < 0:
# restore array here (every value = abs())
return xx
else:
arr[xx] = -arr[xx]
return -1
###############################################################################
if __name__ == "__main__":
arr = [1, 2, 3, 4, 4]
print(find_duplicate(arr))
print(find_duplicate2(arr))
arr = [1, 2, 3, 4, 2]
print(find_duplicate(arr))
print(find_duplicate2(arr))
|
from tkinter import *
import random
from tkinter import messagebox
def generate():
entry.delete(0,END)
pwd = generatepwd()
entry.insert(10,pwd)
def generatepwd():
low = "abcdefghijklmnopqrstuvwxyz"
medium = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890"
strong = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890!@#$%^&*()"
length = var1.get()
choice = var.get()
password = ""
if choice == 1:
for i in range(length):
password += random.choice(low)
return password
elif choice == 2:
for i in range(length):
password += random.choice(medium)
return password
elif choice == 3:
for i in range(length):
password += random.choice(strong)
return password
else:
messagebox.showinfo("Alert", "Please choose Password Complexity")
def printpassword():
password = entry.get()
if password == "":
messagebox.showinfo("Alert", "Please Generate Password First")
else:
messagebox.showinfo("Generated Password", "Generated Password is {}".format(password))
print(password)
root = Tk()
root.resizable(0,0)
var = IntVar()
var1 = IntVar()
root.title("Random Password Generator")
rp=Label(root,text="RandomPass")
rp.grid(row=0,column=0)
entry = Entry(root)
entry.grid(row=0,column=1)
length = Label(root,text="Length")
length.grid(row=1)
copy=Button(root,text="Print",command=printpassword)
copy.grid(row=0,column=2)
generate=Button(root,text="Generate",command=generate)
generate.grid(row=0,column=3)
radio_low = Radiobutton(root, text="Low",variable=var, value=1)
radio_low.grid(row=1, column=2, sticky='E')
radio_middle = Radiobutton(root, text="Medium",variable=var, value=2)
radio_middle.grid(row=1, column=3, sticky='E')
radio_strong = Radiobutton(root, text="Strong",variable=var, value=3)
radio_strong.grid(row=1, column=4, sticky='E')
combo = Combobox(root,textvariable=var1)
#Combo Box for length of your password
combo['values'] = (8, 9, 10, 11, 12, 13, 14, 15, 16,
17, 18, 19, 20, 21, 22, 23, 24, 25,
26, 27, 28, 29, 30, 31, 32)
combo.current(0)
combo.bind('<<ComboboxSelected>>')
combo.grid(column=1, row=1)
root.mainloop()
|
'''
Created on Dec 24, 2015
@author: Sameer Adhikari
'''
from collections import Counter, defaultdict
def freq_dist_imperative(data, divisor):
'''Imperative version of the frequency distribution function.'''
data_divided = [item //divisor for item in data]
counter = Counter(data_divided)
return counter.most_common()
def freq_dist_declarative(data, divisor):
'''Declarative (functional) version of the frequency distribution function.'''
data_divided = [item //divisor for item in data]
sorted_data = iter(sorted(data_divided))
previous, count = next(sorted_data), 1
for item in sorted_data:
if item == previous:
count += 1
elif previous is not None: # and item! = previous
yield previous, count
previous, count = item, 1
else:
raise Exception('Bad data; possible design issue?')
yield previous, count
def group_creation_recursive(key_func, data):
'''Recursive version of the function to group the data using the provided key function.'''
def group_creator_internal(key_func, collection, output_dict):
if len(collection) == 0:
return output_dict
head, *tail = collection
output_dict[key_func(head)].append(head)
return group_creator_internal(key_func, tail, output_dict)
return group_creator_internal(key_func, data, defaultdict(list))
def group_creation_iterative(key_func, data):
'''Tail-call-optimized version of the recursive function to group the data using the provided key function.'''
output_dict = defaultdict(list)
for item in data:
output_dict[key_func(item)].append(item)
return output_dict
def main():
print(82 * '=')
divisor = 3 # Divisor for integer division
print('The divisor for grouping the data is {}'.format(divisor))
datalist = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
print('The original list is \n\t{}'.format(datalist))
print(82 * '=')
print('Frequency distribution of the quantized list using collections.Counter.')
print('This version uses a stateful object to map the keys to groups.')
print(freq_dist_imperative(datalist, divisor))
print(82 * '=')
print('Frequency distribution of the quantized list using sorting and counting.')
print('This is a functional programming version that uses a generator function.')
print(dict(freq_dist_declarative(datalist, divisor)))
print(82 * '=')
key_func = lambda x: x // divisor # integer division
print('Data distribution with actual values in each quanta using recursion')
group_result = group_creation_recursive(key_func, datalist)
for key in group_result:
print('{}: {}'.format(key, group_result[key]))
print(82 * '=')
print('Data distribution with actual values in each quanta using iteration (tco of recursion)')
group_result_tco = group_creation_iterative(key_func, datalist)
for key in group_result_tco:
print('{}: {}'.format(key, group_result_tco[key]))
print(82 * '=')
if __name__ == '__main__':
main()
|
import logging
import redis
from lib.map_traversal.map_traversal_queue import MapTraversalQueue
from lib.string_functions.string_operations import state_postal_codes, strip_state_postal_codes, remove_blacklisted_words
logger = logging.getLogger('')
class StreetNameStatistics():
def __init__(self, queue):
self.queue = queue
if not isinstance(queue, MapTraversalQueue):
raise TypeError,'The Queue needs to be of MapTraversalQueue type'
self.establish_redis_cache()
def establish_redis_cache(self):
logger.info("Establishing Redis Cache")
self.redisObj = redis.StrictRedis(host='localhost', port=6379, db=0)
def wipe_redis(self):
logger.info("Wiping Redis Cache")
keys = ['street_ids', 'county_count', 'streets', 'streets_normalized', 'street_*', 'word_count']
for key in keys:
self.redisObj.delete(key)
def process_node(self, node):
node.process()
if 'ways' in node.response:
for street in node.response['ways']:
''' if the tiger:county key is not defined in the way tags, skip the road and do not process it. '''
if 'tiger:county' not in street['tags']:
continue
'''
Check to see if the state postal codes in the tiger:county key are in the continental US
This excludes roads that are possibly in Canada or Mexico and prevents the rare user defined non existent road from being counted
The strip_state_postal_codes function parses the postal codes out of the tiger:county code
The state_postal_codes function contains a list of valid US government postal codes
'''
valid_postal_codes = state_postal_codes()
street_postal_codes_in_us = map(lambda x: x in valid_postal_codes, strip_state_postal_codes(street['tags']['tiger:county']))
if True not in street_postal_codes_in_us:
continue
'''
if the name key is available, use that as the street name, with the next best option being name:en. Otherwise default to 'n/a'
'''
street_name = 'n/a'
if 'name' in street['tags']:
street_name = street['tags']['name']
elif 'name:en' in street['tags']:
street_name = street['tags']['name:en']
'''
Count the occurrences of the unnormalized street names
This operation increments a key corresponding to the street name in a Redis hash.
I used Redis as it seems to handle memory much more efficiently than the standard python hash implementation
'''
logger.debug(u"Adding Street - {}".format(street_name))
self.redisObj.hincrby('streets', street_name, 1)
logger.debug(u"Street {} - {}".format(street_name, self.redisObj.hget('streets', street_name)))
'''
Count the occurrences of the normalized street name
There were many common prefixes and suffixes that prevented nearly identical street names from being counted as the same street.
It would be interesting to see the relative prevalence of street names if only the main root street name was used.
For example North Main Street, Main Street, and Main Avenue would all be treated as a single street named Main
What would the most common root street names be?
'''
blacklisted_words = ["Road", "Street", "Drive", "Avenue", "Lane", "Court", "North", "East", "West",
"South", "Circle", "Place", "Way", "Northeast", "Northwest", "Southeast",
"Southwest", "Boulevard"]
normalized_street_name = remove_blacklisted_words(street_name, blacklisted_words)
self.redisObj.hincrby('streets_normalized', normalized_street_name, 1)
'''
count the occurrences of a specific words in the street name
'''
for word in street_name.split(' '):
self.redisObj.hincrby('word_count', word, 1)
node.response = {} # clear the node response to free up memory
def count_streets(self):
self.wipe_redis()
logger.info("Counting the Occurrences of Street Names")
for node in self.queue.nodes:
'''
rather than process all nodes at once, process each node individually then eliminate its response to free up memory
'''
self.process_node(node)
''' unnormalized street name count '''
logger.info(u"")
logger.info(u"Steet Name Count")
self.redisObj.hdel('streets', 'n/a') # remove the count of streets with no defined name
self.print_and_store_results('streets', 'street_name_occurances.txt')
''' normalized street name count '''
logger.info(u"")
logger.info(u"Normalized Steet Name Count")
self.redisObj.hdel('streets_normalized', 'n/a', '') # remove the count of streets with no defined name
self.print_and_store_results('streets_normalized', 'normalized_street_name_occurances.txt')
''' word count '''
logger.info(u"")
logger.info(u"Word Count")
self.print_and_store_results('word_count', 'word_occurrences.txt')
def fetch_results(self, redis_key, output_file = None):
'''
Looks into a Redis hash within the key redis_key
Convert the value for each key in the hash from a string to an int (redis returns strings by default)
Stores the results in a tab delimited file specified by output_file
'''
count_hash = self.redisObj.hgetall(redis_key)
for key in count_hash.keys():
count_hash[key] = int(count_hash[key])
sorted_keys = sorted(count_hash, key=count_hash.get, reverse=True)
if output_file:
with open(output_file, 'w') as f:
for k in sorted_keys:
f.writelines('\t'.join([str(k), str(count_hash[k]), '\n']))
return {'sorted_keys': sorted_keys, 'count_hash': count_hash}
def print_and_store_results(self, redis_key, output_file):
'''
Prints the top 10 most common results (if 10 available)
'''
results = self.fetch_results(redis_key, output_file)
count_hash = results['count_hash']
sorted_keys = results['sorted_keys']
max_range = len(sorted_keys)
if max_range > 10:
max_range = 10
logger.info(u"------------------")
for k in range(0, max_range):
print sorted_keys[k], count_hash[sorted_keys[k]]
logger.info(u"------------------")
|
# This file contains the fucntions to import gwas data, filter variants, make bed, and pull gNOMAD data
import sys
import subprocess
import tempfile
# Function 1: Get significant SNPS from GWAS import
# Default p-val = p<5E-8
# Make P-val adjustable
# Input: GWAS table (should define default)
# Output: array of sig SNPs
# Output: number of significant SNPs
def get_intervals(GWAS_infile, Interval_outfile, gNOMAD_outfile, pval_thresh, window_size, gNOMAD_db):
# Args
# GWAS infile is a tab delimited text file
# Expected format:
# Chromosome Position MarkerName Effect_allele Non_Effect_allele Beta SE Pvalue
# Inerval_outfile: merged bedfile with regions containing the significant GWAS calls (can be fixed)
# gNOMAD_oufile: vcf containing gnomAD database information for the significan intervals, user downloads his file
# pval_thresh: float, pval cuffoff, set by user, defaults value to be set
# window_size: interger, determines the total window size around each significant GWAS variant, can be set by user
# gNOMAD_db: fixed file, the gnomAD database.
# read in GWAS file and select the significant genomic loci
infile = open(GWAS_infile, 'r')
header = infile.readline()
GWAS_sig = []
for line in infile:
line = line.strip('\n').split('\t')
chrom = int(line[0])
position = int(line[1])
marker_name = str(line[2])
pval = float(line[7])
if pval < pval_thresh:
GWAS_sig.append([chrom,position,marker_name,pval])
infile.close()
# This section makes a bedfile of all the significant SNPs with a specified window size, overlapping regions are collapsed
window_interval = int(int(window_size)/2)
bedfile_tmp = tempfile.NamedTemporaryFile(mode='w')
for marker in GWAS_sig:
chrom = str(marker[0])
start_pos = str(marker[1]-window_interval)
stop_pos = str(marker[1]+window_interval)
name = marker[2]
score = str(marker[3])
line = [chrom,start_pos,stop_pos,name+','+score]
newline = '\t'.join(line)+'\n'
bedfile_tmp.write(newline)
interval_file=open(Interval_outfile,'w')
merged_intervals=subprocess.run(["bedtools","merge", "-i",bedfile_tmp.name, "-c", "4","-o","collapse","-delim",";"], capture_output=True)
output = merged_intervals.stdout
interval_file.write(output.decode('utf-8'))
interval_file.close()
# This section takes in the bedfile regions and outputs a vcf of all gnomAF within those regions.
# For some reason tabix did not want to run with a bedfile input, so we do each region one at time.
intervals_input=open(Interval_outfile,'r')
gNOMAD_outfile=open(gNOMAD_outfile,'w')
for line in intervals_input:
line = line.strip().split()
location = line[0]+':'+line[1]+'-'+line[2]
gNOMAD_call=subprocess.run(["tabix",gNOMAD_db,location],capture_output=True)
gNOMAD_stdout=gNOMAD_call.stdout
gNOMAD_outfile.write(gNOMAD_stdout.decode('utf-8'))
gNOMAD_outfile.close()
def main():
infile = sys.argv[1]
outfile = sys.argv[2]
gNOMAD_outfile =sys.argv[3]
#pval = sys.argv[3]
#window = sys.argv[4]
pval_default=float(5e-12)
window = 10000
gNOMAD_db='/filestore/gnomad/gnomad.genomes.r2.1.1.sites.vcf.bgz'
get_intervals(infile, outfile, gNOMAD_outfile, pval_default, window, gNOMAD_db)
if __name__ == '__main__':
main()
# Function 2: Make bedfile from significant SNPs
# Default region size:
# Make region size adjustable
# output bedfile
# output region count?
# Function 3:
#
|
# Generated by Django 3.0.7 on 2020-07-14 19:48
import appBookflix.models
import datetime
from django.db import migrations, models
from django.utils.timezone import utc
class Migration(migrations.Migration):
dependencies = [
('appBookflix', '0001_initial'),
]
operations = [
migrations.AlterModelOptions(
name='novedad',
options={'verbose_name': 'Noticia', 'verbose_name_plural': 'Noticias'},
),
migrations.AlterField(
model_name='novedad',
name='imagen',
field=models.ImageField(upload_to='novedades', verbose_name='imagen'),
),
migrations.AlterField(
model_name='updownbook',
name='expiration_normal',
field=models.DateField(default=datetime.datetime(2020, 7, 14, 19, 48, 33, 106937, tzinfo=utc), validators=[appBookflix.models.esCorrecto], verbose_name='programar expiración'),
),
migrations.AlterField(
model_name='updownbook',
name='expiration_premium',
field=models.DateField(default=datetime.datetime(2020, 7, 14, 19, 48, 33, 106937, tzinfo=utc), validators=[appBookflix.models.esCorrecto], verbose_name='expiracion premium'),
),
migrations.AlterField(
model_name='updownbook',
name='up_normal',
field=models.DateField(default=datetime.datetime(2020, 7, 14, 19, 48, 33, 106937, tzinfo=utc), validators=[appBookflix.models.esCorrecto], verbose_name='programar publicación'),
),
migrations.AlterField(
model_name='updownbook',
name='up_premium',
field=models.DateField(default=datetime.datetime(2020, 7, 14, 19, 48, 33, 106937, tzinfo=utc), validators=[appBookflix.models.esCorrecto], verbose_name='pasar a premium'),
),
migrations.AlterField(
model_name='updownbookbychapter',
name='expiration_normal',
field=models.DateField(default=datetime.datetime(2020, 7, 14, 19, 48, 33, 107939, tzinfo=utc), validators=[appBookflix.models.esCorrecto], verbose_name='programar expiración'),
),
migrations.AlterField(
model_name='updownbookbychapter',
name='up_normal',
field=models.DateField(default=datetime.datetime(2020, 7, 14, 19, 48, 33, 107939, tzinfo=utc), validators=[appBookflix.models.esCorrecto], verbose_name='programar publicación'),
),
migrations.AlterField(
model_name='updownchapter',
name='expirationl',
field=models.DateField(default=datetime.datetime(2020, 7, 14, 19, 48, 33, 108939, tzinfo=utc), validators=[appBookflix.models.esCorrecto], verbose_name='DarDeBaja'),
),
migrations.AlterField(
model_name='updownchapter',
name='up',
field=models.DateField(default=datetime.datetime(2020, 7, 14, 19, 48, 33, 108939, tzinfo=utc), validators=[appBookflix.models.esCorrecto], verbose_name='DarDeAlta'),
),
migrations.AlterField(
model_name='updownnovedad',
name='expirationl',
field=models.DateField(default=datetime.datetime(2020, 7, 14, 19, 48, 33, 108939, tzinfo=utc), validators=[appBookflix.models.esCorrecto], verbose_name='DarDeBaja'),
),
migrations.AlterField(
model_name='updownnovedad',
name='up',
field=models.DateField(default=datetime.datetime(2020, 7, 14, 19, 48, 33, 108939, tzinfo=utc), validators=[appBookflix.models.esCorrecto], verbose_name='DarDeAlta'),
),
migrations.AlterField(
model_name='updowntrailer',
name='expirationl',
field=models.DateField(default=datetime.datetime(2020, 7, 14, 19, 48, 33, 109940, tzinfo=utc), validators=[appBookflix.models.esCorrecto], verbose_name='DarDeBaja'),
),
migrations.AlterField(
model_name='updowntrailer',
name='up',
field=models.DateField(default=datetime.datetime(2020, 7, 14, 19, 48, 33, 109940, tzinfo=utc), validators=[appBookflix.models.esCorrecto], verbose_name='DarDeAlta'),
),
]
|
import random
# TODO DA RIFARE LA CLASSE ACTOR. FA SCHIFO.
# ________________________________________________________________________________________
class Actor:
def __init__(self, dir, posX, posY, type):
self.posX = posX
self.posY = posY
self.type = type
self.dir = dir
def getType(self):
return self.type
def setPos(self, x, y):
self.posX = x
self.posY = y
def act(self):
pass
#________________________________________________________________________________________
class Tree(Actor):
def __init__(self, dir, posX, posY, type, treeT=0):
self.type = "TREE"
Actor.__init__(self, dir, posX, posY, self.type)
self.treeTag = treeT
self.age = 0
self.food = random.randint(80, 120) # BOH
def getType(self):
return self.type
def sprawl(self): #oribbbile da rifare tutta
p = random.randint(0, 40)
if p == 1:
vicini = self.dir.getNeighb(self.posX, self.posY)
q = random.randint(0, abs(len(vicini) - 1))
if len(vicini) > 0:
if vicini[q].getActorList() == []:
self.dir.inst(vicini[q].getPos()[0], vicini[q].getPos()[1], "TREE")
def act(self):
self.age = self.age + 1
if (self.age > 12):
if (self.treeTag == 0):
self.treeTag = 1
self.sprawl()
def getPos(self):
return self.posX, self.posY
#________________________________________________________________________________________
class Lumberjack(Actor):
def __init__(self, dir, posX, posY, type):
Actor.__init__(self, dir, posX, posY, type)
self.type = "LUMB"
self.i = True
def act(self):
samePosActs = self.dir.getActList(self.posX, self.posY)
if self.i:
for i in samePosActs:
if i.getType() == "TREE":
self.dir.removeX(i)
self.i = True
nei = self.dir.getNeighb(self.posX, self.posY)
i = random.randint(0, abs(len(nei) -1))
if len(nei) > 0:
self.dir.moveCel(self, nei[i])
def getType(self):
return self.type
def getPos(self):
return self.posX, self.posY
#________________________________________________________________________________________
class Bear(Actor):
def __init__(self):
self.type = "BEAR" |
#!/usr/bin/python3
# coding: utf-8
import time
import random
import sys
import os
tmppath = '/tmp/obd2'
if len(sys.argv) > 1:
if sys.argv[1] == 'php':
tmppath = 'tmp/obd2'
class OBDFetch:
def stop(self):
print("Stopping");
if os.path.exists(tmppath+'/stop'): os.remove(tmppath+'/stop');
f = open(tmppath+'/infos', "w")
f.write("status=Déconnecté;EOF=1")
f.close()
exit("Stopped");
def run(self):
while True:
f = open(tmppath+'/infos', "w")
f.write("status=Connexion en cours;EOF=1")
f.close()
time.sleep(5)
watchdog = 0
data = {}
dataid = 0
slowdata = 0; # Index de la donnée non importante à récupérer
data['dtc'] = '';
while True:
if os.path.exists(tmppath+'/stop'): self.stop()
time.sleep(0.5)
dataid += 1
data['speed'] = 50.0+random.randint(-30,30);
#data['rpm'] = 1200+random.randint(-200,200);
data['rpm'] = 800.0+random.randint(-10,30);
data['engine-load'] = 30.75+random.randint(-20,20);
#data['engine-load-abs'] = 35+random.randint(-10,10);
data['maf'] = 20.25+random.randint(-5,5);
#data['fuel-rate'] = 15+random.randint(-10,10);
#data['throttle-pos'] = 50+random.randint(-10,10);
#data['relative-throttle-pos'] = 50+random.randint(-10,10);
#data['relative-accel-pos'] = 50+random.randint(-10,10);
#data['throttle-actuator'] = 50+random.randint(-10,10);
slowdata += 1
if (slowdata == 1):
data['ambiant-temp'] = 20.0+random.randint(-10,10);
elif (slowdata == 2):
data['intake-temp'] = 25.0+random.randint(-10,10);
elif (slowdata == 3):
data['coolant-temp'] = 90.0+random.randint(-10,10);
#elif (slowdata == 4):
# data['oil-temp'] = 60.0+random.randint(-10,10);
#elif (slowdata == 5):
# data['fuel-level'] = 60.0+random.randint(-10,10);
slowdata = 0
if os.path.exists(tmppath+'/infos'):
try:
os.rename(tmppath+'/infos', tmppath+'/infos.tmp');
except:
pass
watchdog += 1
if (watchdog >= 10):
os.remove(tmppath+'/infos.tmp')
#self.stop()
else: watchdog = 0
f = open(tmppath+'/infos.tmp', "a")
f.write('id='+str(dataid)+';')
f.write(';'.join([k+'='+str(v) for k,v in data.items()]))
f.write(";status=Connecté;EOF=1;")
f.close()
os.rename(tmppath+'/infos.tmp', tmppath+'/infos');
o = OBDFetch();
o.run();
|
import copy
import numpy as np
import torch
def apply_by_index(items, transform, idx=0):
"""Applies callable to certain objects in iterable using given indices.
Parameters
----------
items: tuple or list
transform: callable
idx: int or tuple or or list None
Returns
-------
result: tuple
"""
if idx is None:
return items
if not isinstance(items, (tuple, list)):
raise TypeError
if not isinstance(idx, (int, tuple, list)):
raise TypeError
if isinstance(idx, int):
idx = [idx, ]
idx = set(idx)
res = []
for i, item in enumerate(items):
if i in idx:
res.append(transform(item))
else:
res.append(copy.deepcopy(item))
return res
def numpy2tens(x: np.ndarray, dtype='f') -> torch.Tensor:
"""Converts a numpy array into torch.Tensor
Parameters
----------
x: np.ndarray
Array to be converted
dtype: str
Target data type of the tensor. Can be f - float and l - long
Returns
-------
result: torch.Tensor
"""
x = x.squeeze()
x = torch.from_numpy(x)
if x.dim() == 2: # CxHxW format
x = x.unsqueeze(0)
if dtype == 'f':
return x.float()
elif dtype == 'l':
return x.long()
else:
raise NotImplementedError
|
import base64
import random
from coreapis import cassandra_client
from coreapis.utils import LogWrapper
from coreapis.cache import Cache
def basic_auth(trust):
username = trust['username']
password = trust['password']
base64string = base64.b64encode(
'{}:{}'.format(username, password).encode('UTF-8')).decode('UTF-8')
return "Authorization", "Basic {}".format(base64string)
def auth_header(trust):
ttype = trust['type']
if ttype == 'basic':
return basic_auth(trust)
if ttype == 'bearer':
return 'Authorization', 'Bearer {}'.format(trust['token'])
raise RuntimeError('unhandled trust type {}'.format(ttype))
def set_headers_user(headers, user, subtoken):
if 'userid' in subtoken['scope']:
headers['userid'] = str(user['userid'])
allowed_prefixes = set()
if 'userid-nin' in subtoken['scope']:
allowed_prefixes.add('nin')
if 'userid-feide' in subtoken['scope']:
allowed_prefixes.add('feide')
if allowed_prefixes:
exposed_sec_ids = []
for sec_id in user['userid_sec']:
sec_id_type, _ = sec_id.split(':', 1)
if sec_id_type in allowed_prefixes:
exposed_sec_ids.append(sec_id)
headers['userid-sec'] = ",".join(exposed_sec_ids)
class GkController(object):
def __init__(self, contact_points, keyspace, authz):
self.session = cassandra_client.Client(contact_points, keyspace, authz=authz)
self.log = LogWrapper('gk.GkController')
self._allowed_dn = Cache(1800, 'gk.GkController.allowed_dn_cache')
def allowed_dn(self, dn):
return self._allowed_dn.get(dn, lambda: self.session.apigk_allowed_dn(dn))
def options(self, backend_id):
backend = self.session.get_apigk(backend_id)
headers = dict()
headers['endpoint'] = random.choice(backend['endpoints'])
headers['gatekeeper'] = backend_id
self.log.debug('Gatekeeping OPTIONS call',
gatekeeper=backend_id, endpoint=headers['endpoint'])
return headers
def info(self, backend_id, client, user, scopes, subtokens, acr):
backend = self.session.get_apigk(backend_id)
headers = dict()
headers['endpoint'] = random.choice(backend['endpoints'])
headers['gatekeeper'] = backend_id
if acr is None:
acr = ''
headers['acr'] = acr
if backend.get('allow_unauthenticated', None) and client is None:
self.log.debug('Allowing unauthenticated gatekeeping', gatekeeper=backend_id,
endpoint=headers['endpoint'])
return headers
main_scope = 'gk_{}'.format(backend_id)
if main_scope not in scopes:
self.log.debug('provided token misses scopes to access this api', gatekeeper=backend_id)
return None
if backend['requireuser'] and user is None:
self.log.warn('user required but not in token', gatekeeper=backend_id,
clientid=client['id'])
return None
if backend_id in subtokens:
subtoken = self.session.get_token(subtokens[backend_id])
headers['token'] = str(subtoken['access_token'])
if user:
set_headers_user(headers, user, subtoken)
scope_prefix = main_scope + '_'
scope_prefix_len = len(scope_prefix)
exposed_scopes = [scope[scope_prefix_len:]
for scope in scopes if scope.startswith(scope_prefix)]
headers['scopes'] = ','.join(exposed_scopes)
headers['clientid'] = str(client['id'])
header, value = auth_header(backend['trust'])
headers[header] = value
self.log.debug('Allowing gatekeeping', gatekeeper=backend_id, endpoint=headers['endpoint'],
clientid=client['id'])
return headers
|
#!/usr/bin/env python
# coding: utf-8
"""
gettup - A command-line file sharing utility for ge.tt
usage:
$ gett > show help
$ gett file1 file2 file3 > upload files (in same share)
$ gett *.py > linux globs (upload)
$ gett *.py -p > parallelize uploads
$ gett *.py -z > zips the files and uploads
$ gett *.py -s sharename > upload file in the specific share
$ gett *.py -s sharename -t title > gives the title to the new share
$ gett --list > show list of shares
$ gett -d share1 share2 share3 > deletes the shares
$ gett -r url1 url2 url 3 > deletes the file url
$ gett -q {etc} > quiet mode
$ gett -i sharename > get share info
"""
import requests
import json
import sys
import argparse
import os
import signal
# GETT URLS
LOGIN_URL = "http://open.ge.tt/1/users/login"
SHARE_URL = "http://open.ge.tt/1/shares/create?accesstoken="
VERBOSE = True
def signal_handler(signal, frame):
""" graceful exit on keyboard interrupt """
sys.exit(0)
def logg(msg):
""" print to screen based on VERBOSE toggling """
if VERBOSE: print msg
def refresh_access_token():
""" re-fetches fresh access tokens using the refresh token and writes to the config file """
logg("Updating expired tokens ...")
refreshtoken = read_config('refreshtoken')
r = requests.post(LOGIN_URL, data=json.dumps({'refreshtoken': refreshtoken }))
if r.status_code != 200:
print "Error: Cannot fetch tokens. Try deleting the ~/.gett.cfg file and re-trying"
sys.exit(0)
accesstoken, refreshtoken = r.json().get('accesstoken'), r.json().get('refreshtoken')
write_config({'accesstoken': accesstoken, 'refreshtoken': refreshtoken})
def get_shares():
""" gets the list of all shares using an accesstoken and prints on screen """
accesstoken = get_access_token()
logg("Fetching shares ...")
get_share_url = "http://open.ge.tt/1/shares?accesstoken=" + accesstoken
r = requests.get(get_share_url)
shares = r.json()
if r.status_code != 200:
refresh_access_token()
return get_shares()
if not shares:
print "You don't have any shares. Create a new share by uploading a file"
else:
for shr in shares:
print "%d file(s) in share: %s (%s)" % \
(len(shr['files']), shr['sharename'], shr['getturl'])
def get_share_info(sharename):
""" retrives the information of files stored in a specific share """
logg("Fetching share info ...")
get_share_url = "http://open.ge.tt/1/shares/" + sharename
r = requests.get(get_share_url)
share_info = r.json()
if r.status_code != 200:
print "Error: Share not found"
return
print "Share: %s | gett url: %s | total files: %d" % (sharename, share_info['getturl'], len(share_info['files']))
for f in share_info['files']:
print f['getturl'], humanize(f['size']), f['filename']
def delete_file(sharename, fileid):
""" deletes a file in a specific share and a fileId """
logg("Deleting file ...")
accesstoken = get_access_token()
destroy_url = "http://open.ge.tt/1/files/%s/%s/destroy?accesstoken=%s" % \
(sharename, fileid, accesstoken)
r = requests.post(destroy_url)
if r.status_code != 200:
refresh_access_token()
return delete_file(sharename, fileid)
print "File has been successfully destroyed"
def delete_url(url):
""" deletes the file corresponding to the URL """
fields = url.split('/')
if len(fields) != 6:
print "Error: Invalid url format"
return
delete_file(fields[3], fields[-1])
def create_share(title=None):
""" creates a new share with an optional title and returns the share id """
accesstoken = get_access_token()
logg("Constructing a new share ...")
if title:
r = requests.post(SHARE_URL + accesstoken, data=json.dumps({'title': title}))
else:
r = requests.post(SHARE_URL + accesstoken)
if r.status_code != 200:
refresh_access_token()
return create_share()
return r.json().get('sharename')
def destroy_share(sharename):
logg("Destroying share ...")
accesstoken = get_access_token()
url = "http://open.ge.tt/1/shares/%s/destroy?accesstoken=%s" % (sharename, accesstoken)
r = requests.post(url)
if r.status_code == 200:
print "%s share has been destroyed" % sharename
elif r.status_code == 403:
print "%s share doesn't belong to authenticated user" % sharename
else:
refresh_access_token()
return destroy_share(sharename)
def upload_file(sharename, filename):
""" upload a file in share with the sharename """
accesstoken = get_access_token()
file_url = "http://open.ge.tt/1/files/%s/create?accesstoken=%s" % (sharename, accesstoken)
logg("Setting up a file name ...")
r = requests.post(file_url, data=json.dumps({"filename": filename }))
if r.status_code != 200:
refresh_access_token()
return upload_file(sharename, filename)
gett_url = r.json().get('getturl')
post_upload_url = r.json()['upload']['posturl']
logg("Uploading the file...")
r = requests.post(post_upload_url, files={'file': open(filename, 'rb')})
if r.status_code == 200:
print "Upload successful. Here's your url: %s" % gett_url
else:
print "Error: " + r.json().get('error')
def config_file():
""" returns the location (~/.gett.cfg) of the config file in user's home dir """
home = os.getenv('USERPROFILE') or os.getenv('HOME')
return os.path.join(home, '.gett.cfg')
def read_config(token):
""" reads token values from the configuration file """
file_location = config_file()
if sys.version_info[0] == 3:
import configparser as cp
else:
import ConfigParser as cp
config = cp.RawConfigParser()
if not config.read(file_location) or not config.has_section('TOKENS') \
or not config.has_option('TOKENS', token):
return None
return config.get('TOKENS', token)
def write_config(fields):
""" writes a set of fields into the config file """
if sys.version_info[0] == 3:
import configparser as cp
else:
import ConfigParser as cp
config = cp.RawConfigParser()
config.add_section("TOKENS")
for k in fields:
config.set("TOKENS", k, fields[k])
file_location = config_file()
with open(file_location, 'wb') as configfile:
config.write(configfile)
def bulk_upload(files, sharename=None, title=None):
""" wrapper for uploading more than one files into a share(with optional title) """
sharename = sharename or create_share(title)
for f in files:
print "Uploading file: " + f
upload_file(sharename, f)
logg("----------------------------------------")
def setup_tokens():
""" fetch fresh tokens using user's credentials """
email = raw_input("Please enter your Ge.tt email: ").strip()
password = raw_input("Please enter your Ge.tt password: ").strip()
apikey = raw_input("Please enter your API KEY: ").strip()
logg("Validating credentials ...")
r = requests.post(LOGIN_URL, data=json.dumps({'email': email, 'password': password,
'apikey': apikey}))
accesstoken, refreshtoken = r.json().get('accesstoken'), r.json().get('refreshtoken')
if not accesstoken or not refreshtoken:
print "Error! Your credentials failed validation. Exiting program"
sys.exit(0)
logg("Credentials verified ...")
write_config({'accesstoken': accesstoken, 'refreshtoken': refreshtoken})
return accesstoken
def get_access_token():
""" retrieves access token either from the config file or from the user """
return read_config('accesstoken') or setup_tokens()
def humanize(nbytes):
""" returns the file size in human readable format """
for (exp, unit) in ((9, 'GB'), (6, 'MB'), (3, 'KB'), (0, 'B')):
if nbytes >= 10**exp:
break
return "%.2f %s" % (float(nbytes)/10**exp, unit)
def main():
""" ENTRY METHOD """
signal.signal(signal.SIGINT, signal_handler)
parser = argparse.ArgumentParser(description="Upload files to ge.tt via the command line",
epilog="For more information, examples & source code visit http://github.com/prakhar1989/gettup")
# FILE UPLOADS
file_uploads = parser.add_argument_group("File Uploads")
file_uploads.add_argument("files", metavar="files", nargs="*",
help="list of files you want to upload")
file_uploads.add_argument("-s", "--share", metavar="share_id",
help="upload files to a particular share")
file_uploads.add_argument("-t", "--title", metavar='share_title',
help='title for the new share')
# SHARE RELATED COMMANDS
share_group = parser.add_argument_group('Share Related')
share_group.add_argument("-i", '--info', metavar="share_id",
help="get info for a specific share")
share_group.add_argument('-d', '--delete', metavar="share_id", nargs="+",
help="delete a share & all files in it")
share_group.add_argument('-l', '--list', action="store_true",
help="Lists all shares in your account")
share_group.add_argument('-r', '--remove', metavar="file_url", nargs="+",
help="Delete a list of files with associated urls")
# MISC COMMANDS
misc_group = parser.add_argument_group('Other actions')
misc_group.add_argument('-q', '--quiet', action="store_true",
help="Toggle verbose off (default is on)")
args = parser.parse_args()
global VERBOSE
VERBOSE = not args.quiet
if args.info:
get_share_info(args.info)
if args.list:
get_shares()
if args.delete:
for sharename in args.delete:
destroy_share(sharename)
if args.remove:
for url in args.remove:
delete_url(url)
if args.files:
bulk_upload(args.files, sharename=args.share, title=args.title)
if len(sys.argv) == 1:
parser.print_help()
if __name__ == "__main__":
main()
|
import numpy as np
import operator
class PokerGame:
shared_cards = np.array([])
def __init__(self, NumberOfPlayers = 2):
self.players = np.array([Player(i) for i in range(NumberOfPlayers)])
self.deck = Deck()
def play(self):
self.shared_cards = np.array([])
# self.deck.display_deck()
self.deck.shuffle_deck()
print("START")
# initial draw
for player in self.players:
player.add_cards(self.deck.draw_card(numberOfDraws=2))
print("Initial draw.")
self.display_players()
# flop draw
self.draw_cards(3)
# self.display_table()
# turn draw
self.draw_cards(1)
# self.display_table()
# river draw
self.draw_cards(1)
self.display_table()
# self.display_players()
winner, classification = self.determine_winner()
print(f"#{winner.number} won with {classification}")
def determine_winner(self):
classifications = {}
classification_type = None
winner = None
for player in self.players:
players_hand = player.get_poker_hand()
hand_classifications = players_hand.get_classifications()
print(f"CLASSIFICATIONS FOR PLAYER {player.number}")
for c in hand_classifications:
c.display()
hand_classification = max(hand_classifications)
classifications[player] = hand_classification
winner = max(classifications.items(), key=operator.itemgetter(1))[0]
classification_type = classifications[winner].get_classification()
# 0: Nothing in hand; not a recognized poker hand
# 1: One pair; one pair of equal ranks within five cards
# 2: Two pairs; two pairs of equal ranks within five cards
# 3: Three of a kind; three equal ranks within five cards
# 4: Straight; five cards, sequentially ranked with no gaps
# 5: Flush; five cards with the same suit
# 6: Full house; pair + different rank three of a kind
# 7: Four of a kind; four equal ranks within five cards
# 8: Straight flush; straight + flush
# 9: Royal flush; {Ace, King, Queen, Jack, Ten} + flush
poker_hands = ["Highest card", "One pair", "Two pair", "Three of a kind", "Straight", "Flush", "Full house", "Four of a kind", "Straight flush", "Royal flush"]
classification = poker_hands[classification_type]
return winner, classification
def display_players(self):
for player in self.players:
player.display()
def display_table(self):
print("Table:")
for card in self.shared_cards:
card.display()
def draw_cards(self, numberOfCards):
cards = self.deck.draw_card(numberOfCards)
self.shared_cards = np.append(self.shared_cards, cards)
for player in self.players:
player.add_cards(cards)
class Player:
def __init__(self, number):
self.cards = np.array([])
self.number = number
self.poker_hand = None
def add_cards(self, cards):
self.cards = np.append(self.cards, cards)
self.set_poker_hand(self.cards)
def set_poker_hand(self, cards):
self.poker_hand = PokerHand(cards)
def get_poker_hand(self):
return self.poker_hand
def display(self):
print(f"Player {self.number}")
self.poker_hand.display()
class PokerHand:
def __init__(self, cards):
self.cards = cards
self.classifications = set()
self.classify()
def get_classifications(self):
return self.classifications
def get_cards(self):
return self.cards
def display(self):
for card in self.cards:
card.display()
def classify(self):
sorted_cards = np.sort(self.cards, axis=None)
flush = False
straight = False
ranks = {}
suits = {}
straight_count = 1
straight_cards = np.array([])
ace_present = False
highest_rank = 0
high_card = None
previous_card = None
for i in range(len(sorted_cards)):
card = sorted_cards[i]
rank = card.get_rank()
suit = card.get_suit()
if rank not in ranks:
ranks[rank] = np.array([card])
else:
ranks[rank] = np.append(ranks[rank], card)
if suit not in suits:
suits[suit] = np.array([card])
else:
suits[suit] = np.append(suits[suit], card)
if previous_card is None:
previous_card = card
else:
if highest_rank < rank:
highest_rank = rank
high_card = card
previous_rank = previous_card.get_rank()
# Accumulates points towards a straight classification
if previous_rank == rank - 1:
straight_count += 1
# Resets points
else:
straight_count = 1
# Defines straight
if straight_count >= 5:
straight = True
straight_cards = np.arrays([sorted_cards[i-4], sorted_cards[i-3], sorted_cards[i-2], sorted_cards[i-1], sorted_cards[i]])
# Handles ace high straights
elif straight_count == 4 and rank == 13 and ace_present:
straight = True
straight_cards = np.arrays([sorted_cards[i-3], sorted_cards[i-2], sorted_cards[i-1], sorted_cards[i], sorted_cards[0]])
if straight:
self.assign_classification(handClassification=4, cards=straight_cards)
# Assigns junk card classification
if ace_present:
high_card = sorted_cards[0]
self.assign_classification(handClassification=0, cards=high_card)
# Checking for float classification
for suit, cards in suits.items():
if len(cards) == 5:
flush = True
if flush:
self.assign_classification(handClassification=5, cards=cards)
# Checking for special straight classifications (straight flush, royal flush)
if straight:
if cards == straight_cards:
self.assign_classification(handClassification=8, cards=cards)
if cards[-1].rank == 1:
self.assign_classification(handClassification=9, cards=cards)
# Checking for pair classifications (pair, two pair, 3oak, 4oak, full house)
pairs = np.array([])
for rank, cards in ranks.items():
appearances = len(cards)
# print(f"rank: {rank}, appearances: {appearances}, cards: {cards}")
# Check Pair
if appearances == 2:
# Check for full house
if len(pairs) == 2:
pairs = np.append(pairs, cards)
self.assign_classification(handClassification=2, cards=pairs)
if len(pairs) == 3:
pairs = np.append(pairs, cards)
self.assign_classification(handClassification=6, cards=pairs)
pairs = cards
self.assign_classification(handClassification=1, cards=cards)
# Check 3 of a kind
if appearances == 3:
# Check for full house
if len(pairs) == 2:
pairs = np.append(pairs, cards)
self.assign_classification(handClassification=6, cards=pairs)
pairs = cards
self.assign_classification(handClassification=3, cards=cards)
# Checks 4 of a kind
if appearances == 4:
self.assign_classification(handClassification=7, cards=cards)
def assign_classification(self, handClassification, cards):
classification = CardsClassification(handClassification)
classification.set_cards(cards)
self.classifications.add(classification)
class CardsClassification:
cards = np.array([])
def __init__(self, classification):
self.classification = classification
def set_cards(self, cards):
self.cards = np.append(self.cards, cards)
def get_classification(self):
return self.classification
def display(self):
print()
print(f"classification: {self.classification}")
for card in self.cards:
card.display()
print()
def __lt__(self, other):
return self.classification < other.classification
class Deck:
suits = ['spades', 'clubs', 'hearts', 'diamonds']
def __init__(self):
self.deck = self.new_deck()
def new_deck(self):
deck = np.array([])
for suit in self.suits:
for rank in range(1,14):
card = Card(suit, rank)
deck = np.append(deck, card)
return deck
def shuffle_deck(self):
np.random.shuffle(self.deck)
def display_deck(self, numberOfCards = 52):
for index in range(numberOfCards):
self.deck[index].display()
def draw_card(self, numberOfDraws = 1):
cards = np.random.choice(self.deck, numberOfDraws, replace=False)
return cards
class Card:
card_names = {1: 'Ace', 11: 'Jack', 12: 'Queen', 13: 'King'}
def __init__(self, suit, rank):
self.suit = suit
self.rank = rank
if self.rank in self.card_names:
self.name = self.card_names[self.rank]
else:
self.name = rank
def get_suit(self):
return self.suit
def get_rank(self):
return self.rank
def display(self):
print(f"{self.name} of {self.suit}.")
def __lt__(self, other):
return self.rank < other.rank
def main():
game = PokerGame(NumberOfPlayers=2)
game.play()
if __name__ == "__main__":
main() |
from bs4 import BeautifulSoup
import requests
import os
import json
import sqlite3
from datetime import date
def statFinder():
url = "http://www.espn.com/nba/hollinger/teamstats"
r = requests.get(url)
soup = BeautifulSoup(r.text, 'html.parser')
outer = soup.find('table', class_="tablehead")
trs = outer.find_all('tr')
data = []
for i in range(2, len(trs)):
guy = trs[i]
team = guy.find('a').text
stats = guy.find_all('td')
pace = stats[2].text
to = stats[4].text
orr = stats[5].text
drr = stats[6].text
rebr = stats[7].text
efg = stats[8].text
ts = stats[9].text
offef = stats[10].text
defef = stats[11].text
data.append((team, pace, to, orr, drr, rebr, efg, ts, offef, defef))
return data
def teamConvert(team):
teams = {
"LA Clippers": "LAC",
"Brooklyn": "BKN",
"Utah": "UTAH",
"Denver": "DEN",
"Milwaukee": "MIL",
"Phoenix": "PHX",
"Portland": "POR",
"Atlanta": "ATL",
"Dallas": "DAL",
"New Orleans": "NO",
"Sacramento": "SAC",
"Boston": "BOS",
"Memphis": "MEM",
"Philadelphia": "PHI",
"Toronto": "TOR",
"Chicago": "CHI",
"Indiana": "IND",
"Charlotte": "CHA",
"San Antonio": "SAS",
"Golden State": "GSW",
"LA Lakers": "LAL",
"New York": "NYK",
"Washington": "WAS",
"Miami": "MIA",
"Detroit": "DET",
"Minnesota": "MIN",
"Houston": "HOU",
"Orlando": "ORL",
"Cleveland": "CLE",
"Oklahoma City": "OKC"
}
return teams[team]
def tabMaker(cur, conn):
cur.execute('''CREATE TABLE IF NOT EXISTS AdvStats (Date TEXT, Team_id INTEGER, Pace REAL,
TurnoverRatio REAL, OffRebRate REAL, DefRebRate REAL, RebRate REAL, EffFGPerc REAL, TrueSP REAL,
OffEff REAL, DefEff REAL)''')
conn.commit()
def additionChecker(cur, conn):
cur.execute('''SELECT Date FROM AdvStats WHERE Date = ?''', (str(date.today()),))
if len(cur.fetchall()) > 0:
return False
return True
def tabAddition(cur, conn, line):
cur.execute("SELECT id FROM Teams WHERE Abbreviation = ?", (teamConvert(line[0]),))
tid = int(cur.fetchone()[0])
cur.execute('''INSERT INTO AdvStats (Date, Team_id, Pace, TurnoverRatio, OffRebRate, DefRebRate,
RebRate, EffFGPerc, TrueSP, OffEff, DefEff) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)''',
(str(date.today()), tid, line[1], line[2], line[3], line[4], line[5], line[6], line[7], line[8], line[9]))
conn.commit()
def Printer(lines):
print("TEAM PACE TORat OffRebRate DefRebRate EffFGPerc TrueSP OffEff DefEff")
for i in lines:
print(i[0] + " " + str(i[1]) + " " + str(i[2]) + " " + str(i[3]) + " " + str(i[4]) + " " + str(i[5]) + " " + str(i[6]) + " " + str(i[7]) + " " + str(i[8]) + " " + str(i[9]))
print("Advanced Stats as of " + str(date.today()))
if __name__ == "__main__":
data = statFinder()
path = os.path.dirname(os.path.abspath(__file__))
conn = sqlite3.connect(path+'/'+'stats.db')
cur = conn.cursor()
tabMaker(cur, conn)
if additionChecker(cur, conn):
for i in data:
tabAddition(cur, conn, i)
print("Advanced Data added to database")
else:
print("Database up to date. No need to add found data.")
Printer(data)
|
"""do_qa.py
Purpose: wrapper script for qa module.
"""
from qa import qa_data
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser()
req_named = parser.add_argument_group('Required named arguments')
req_named.add_argument('-m', action='store', dest='dir_mast', type=str,
help='Master directory', required=True)
req_named.add_argument('-t', action='store', dest='dir_test', type=str,
help='Test directory', required=True)
req_named.add_argument('-o', action='store', dest='dir_out', type=str,
help='Output directory', required=True)
parser.add_argument('-x', action='store_true', dest='xml_schema',
help='Path to XML schema', required=False)
parser.add_argument('--no-archive', action='store_false', dest='archive',
help='Look for individual files, instead of g-zipped'
' archives', required=False)
parser.add_argument('--verbose', action='store_true', dest='verbose',
help='Enable verbose logging', required=False)
parser.add_argument('--include-nodata', action='store_true',
dest='incl_nd', help='Do not mask NoData values',
required=False)
arguments = parser.parse_args()
qa_data(**vars(arguments))
|
class BaseDTO:
@staticmethod
def serialize_single(obj):
if hasattr(obj, "to_dict"):
return obj.to_dict()
return obj
def serialize(self, objs):
if type(objs) is list:
return [self.serialize_single(obj) for obj in objs]
return self.serialize_single(objs)
def to_dict(self):
keys = self.__annotations__
return {key: self.serialize(getattr(self, key)) for key in keys} |
def seq_rev(data, start, stop):
if start < stop-1:
data[start], data[stop-1] = data[stop-1], data[start]
seq_rev(data, start+1, stop-1)
return data
seq = [1, 3, 8, 9, 12, 16]
print(seq_rev(seq, 0, 6)) |
# Create a variable savings
savings = 100
# Print out savings
print(savings)
# Create a variable savings
savings = 100
# Create a variable growth_multiplier
growth_multiplier = 1.1
# Calculate result
result = savings * (growth_multiplier**7)
print(result)
# Print out result
# Create a variable desc
desc = "compound interest"
# Create a variable profitable
profitable = True
savings = 100
growth_multiplier = 1.1
desc = "compound interest"
# Assign product of growth_multiplier and savings to year1
year1 = savings * growth_multiplier
# Print the type of year1
print(type(year1))
# Assign sum of desc and desc to doubledesc
doubledesc = desc + desc
# Print out doubledesc
print(doubledesc)
# Definition of savings and result
savings = 100
result = 100 * 1.10 ** 7
# Fix the printout
print("I started with $" + str(savings) + " and now have $" + str(result) + ". Awesome!")
# Definition of pi_string
pi_string = "3.1415926"
# Convert pi_string into float: pi_float
pi_float = float(pi_string)
|
from itertools import combinations
N = int(eval(input()))
S = input().split(' ')
K = int(eval(input()))
num = 0
den = 0
for c in combinations(S,K):
den+=1
num+='a' in c
print(float(num)/den)
|
import tensorflow as tf
from tensorflow.contrib.layers import xavier_initializer
from RNN.conv_gru import ConvGRUCell
from RNN.conv_stlstm import ConvSTLSTMCell
from RNN.PredRNN import PredRNNCell
from config import c
from config import config_gru_fms
from tf_utils import conv2d_act
class Encoder(object):
def __init__(self, batch, seq, gru_filter,
gru_in_chanel, conv_kernel, conv_stride,
h2h_kernel, i2h_kernel, height, width):
if c.DTYPE == "single":
self._dtype = tf.float32
elif c.DTYPE == "HALF":
self._dtype = tf.float16
self._batch = batch
self._seq = seq
self._h = height
self._w = width
self.stack_num = len(gru_filter)
self.rnn_blocks = []
self.rnn_states = []
self.conv_kernels = []
self.conv_bias = []
self.conv_stride = conv_stride
self._gru_fms = config_gru_fms(height, conv_stride)
self._gru_filter = gru_filter
self._conv_fms = conv_kernel
self._gru_in_chanel = gru_in_chanel
self._h2h_kernel = h2h_kernel
self._i2h_kernel = i2h_kernel
self.build_rnn_blocks()
self.init_rnn_states()
self.init_parameters()
def build_rnn_blocks(self):
"""
first rnn changes input chanels
input (b, 180, 180, 8) output (b, 180, 180, 64)
so set the chanel parameter to define gru i2h.
other rnn cells keep the input chanel.
:return:
"""
with tf.variable_scope("Encoder"):
for i in range(len(self._gru_fms)):
if c.RNN_CELL == "conv_gru":
cell = ConvGRUCell(num_filter=self._gru_filter[i],
b_h_w=(self._batch,
self._gru_fms[i],
self._gru_fms[i]),
h2h_kernel=self._h2h_kernel[i],
i2h_kernel=self._i2h_kernel[i],
name="e_cgru_" + str(i),
chanel=self._gru_in_chanel[i])
elif c.RNN_CELL == "st_lstm":
cell = ConvSTLSTMCell(num_filter=self._gru_filter[i],
b_h_w=(self._batch,
self._gru_fms[i],
self._gru_fms[i]),
kernel=self._i2h_kernel[i],
name="e_stlstm_" + str(i),
chanel=self._gru_in_chanel[i])
elif c.RNN_CELL == "PredRNN":
cell = PredRNNCell(num_filter=self._gru_filter[i],
b_h_w=(self._batch,
self._gru_fms[i],
self._gru_fms[i]),
kernel=self._i2h_kernel[i],
name="e_stlstm_" + str(i),
chanel=self._gru_in_chanel[i],
layers=c.PRED_RNN_LAYERS)
else:
raise NotImplementedError
self.rnn_blocks.append(cell)
def init_parameters(self):
with tf.variable_scope("Encoder", auxiliary_name_scope=False):
if c.DOWN_SAMPLE_TYPE == "conv":
for i in range(len(self._conv_fms)):
self.conv_kernels.append(tf.get_variable(name=f"Conv{i}_W",
shape=self._conv_fms[i],
initializer=xavier_initializer(uniform=False),
dtype=self._dtype))
self.conv_bias.append(tf.get_variable(name=f"Conv{i}_b",
shape=[self._conv_fms[i][-1]],
initializer=tf.zeros_initializer))
elif c.DOWN_SAMPLE_TYPE == "inception":
for i in range(len(self._conv_fms)):
conv_kernels = []
biases = []
for j in range(len(self._conv_fms[i])):
kernel = self._conv_fms[i][j]
conv_kernels.append(tf.get_variable(name=f"Conv{i}_W{j}",
shape=kernel,
initializer=xavier_initializer(uniform=False),
dtype=self._dtype))
biases.append(tf.get_variable(name=f"Conv{i}_b{j}",
shape=kernel[-1],
initializer=tf.zeros_initializer))
self.conv_kernels.append(conv_kernels)
self.conv_bias.append(biases)
else:
raise NotImplementedError
def init_rnn_states(self):
for block in self.rnn_blocks:
self.rnn_states.append(block.zero_state())
def rnn_encoder(self, in_data):
with tf.variable_scope("Encoder", auxiliary_name_scope=False, reuse=tf.AUTO_REUSE):
for i in range(self.stack_num):
conv = conv2d_act(input=in_data,
name=f"Conv{i}",
kernel=self.conv_kernels[i],
bias=self.conv_bias[i],
strides=self.conv_stride[i])
output, states = self.rnn_blocks[i].unroll(inputs=conv,
length=self._seq)
self.rnn_states[i] = states
in_data = output
def rnn_encoder_step(self, in_data):
with tf.variable_scope("Encoder", auxiliary_name_scope=False, reuse=tf.AUTO_REUSE):
for i in range(self.stack_num):
conv = conv2d_act(input=in_data,
name=f"Conv{i}",
kernel=self.conv_kernels[i],
bias=self.conv_bias[i],
strides=self.conv_stride[i])
output, states = self.rnn_blocks[i](inputs=conv, state=self.rnn_states[i])
self.rnn_states[i] = states
in_data = output |
import pytest
from wishlist.domain.customer.exceptions import CustomerAlreadyRegisteredError
from wishlist.domain.customer.ports import CreateCustomer
from wishlist.test.helpers import AsyncMock
class TestCreateCustomer:
async def test_create_customer_with_success(
self,
customer_dict,
customer
):
del customer_dict['id']
create_customer = CreateCustomer(
AsyncMock(return_value=customer),
AsyncMock()
)
customer = await create_customer.create(customer_dict)
assert customer == customer
async def test_create_customer_with_duplicated_email(
self,
customer_dict,
customer
):
create_customer = CreateCustomer(
AsyncMock(),
AsyncMock(return_value=customer)
)
with pytest.raises(CustomerAlreadyRegisteredError):
await create_customer.create(customer_dict)
|
#!/usr/bin/env python
# coding:utf-8
# Copyright (C) dirlt
class Solution(object):
def numDistinct(self, s, t):
"""
:type s: str
:type t: str
:rtype: int
"""
n = len(s) + 1
m = len(t) + 1
st = []
for i in range(n):
st.append([1] + [0] * (m - 1))
for i in range(1, n):
for j in range(1, m):
# st[i][j] involves with s[i-1][ and t[j-1]
st[i][j] = st[i-1][j]
if s[i-1] == t[j-1]:
st[i][j] += st[i-1][j-1]
# for i in range(n):
# print st[i]
return st[n-1][m-1]
if __name__ == '__main__':
s = Solution()
print s.numDistinct('rabbbit', 'rabbit')
print s.numDistinct('ccc', 'c')
|
"""empty message
Revision ID: 6a1d5b118d31
Revises: 495a88477b8c
Create Date: 2018-03-07 15:19:31.806238
"""
# revision identifiers, used by Alembic.
revision = '6a1d5b118d31'
down_revision = '495a88477b8c'
from alembic import op
import sqlalchemy as sa
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column('o_auth2_token', sa.Column('id', sa.Integer(), nullable=False))
op.add_column('o_auth2_token', sa.Column('token_type', sa.String(length=100), nullable=True))
op.alter_column('o_auth2_token', 'access_token',
existing_type=sa.VARCHAR(length=48),
type_=sa.String(length=500),
existing_nullable=False)
op.alter_column('o_auth2_token', 'user_id',
existing_type=sa.INTEGER(),
type_=sa.String(length=255),
existing_nullable=False)
op.add_column('user', sa.Column('first_name', sa.String(length=255), nullable=True))
op.add_column('user', sa.Column('last_name', sa.String(length=255), nullable=True))
op.add_column('user', sa.Column('name', sa.String(length=255), nullable=True))
op.add_column('user', sa.Column('picture_url', sa.String(length=500), nullable=True))
op.drop_column('user', 'password')
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column('user', sa.Column('password', sa.VARCHAR(length=255), autoincrement=False, nullable=True))
op.drop_column('user', 'picture_url')
op.drop_column('user', 'name')
op.drop_column('user', 'last_name')
op.drop_column('user', 'first_name')
op.alter_column('o_auth2_token', 'user_id',
existing_type=sa.String(length=255),
type_=sa.INTEGER(),
existing_nullable=False)
op.alter_column('o_auth2_token', 'access_token',
existing_type=sa.String(length=500),
type_=sa.VARCHAR(length=48),
existing_nullable=False)
op.drop_column('o_auth2_token', 'token_type')
op.drop_column('o_auth2_token', 'id')
# ### end Alembic commands ###
|
from .AssetEditor import AssetEditor, AssetEditorModule, getAssetSelectionManager
from .AssetBrowser import AssetBrowser
from .AssetPreviewer import AssetPreviewer
from . import AssetSearchEnumerator
from . import CommonAsset
from . import EngineAsset |
# Generated by Django 3.2 on 2021-06-24 14:30
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('student_profile_app', '0012_fieldreport'),
]
operations = [
migrations.RemoveField(
model_name='studentprofile',
name='profile_image',
),
migrations.AddField(
model_name='studentprofile',
name='has_reported',
field=models.BooleanField(default=False),
),
migrations.AlterField(
model_name='studentprofile',
name='academic_supervisor',
field=models.ForeignKey(default=38, on_delete=django.db.models.deletion.CASCADE, related_name='academic_supervisor', to=settings.AUTH_USER_MODEL),
),
migrations.AlterField(
model_name='studentprofile',
name='field_supervisor',
field=models.ForeignKey(default=38, on_delete=django.db.models.deletion.CASCADE, related_name='field_supervisor', to=settings.AUTH_USER_MODEL),
),
migrations.AlterField(
model_name='studentprofile',
name='organization',
field=models.ForeignKey(default=38, on_delete=django.db.models.deletion.CASCADE, related_name='organization_id', to=settings.AUTH_USER_MODEL),
),
]
|
import datetime
from Generator.ClassicMap import ClassicMap
from Generator.ExtendedMap import ExtendedMap
def dummy():
import json
return json.dumps({"tile": [
{"index": 0, "dice": 0, "resource_type": "DESE"},
{"index": 1, "dice": 5, "resource_type": "OREE"},
{"index": 2, "dice": 2, "resource_type": "WOOL"},
{"index": 3, "dice": 6, "resource_type": "CLAY"},
{"index": 4, "dice": 11, "resource_type": "GRAI"},
{"index": 5, "dice": 10, "resource_type": "LUMB"},
{"index": 6, "dice": 6, "resource_type": "OREE"},
{"index": 7, "dice": 3, "resource_type": "LUMB"},
{"index": 8, "dice": 4, "resource_type": "OREE"},
{"index": 9, "dice": 8, "resource_type": "WOOL"},
{"index": 10, "dice": 12, "resource_type": "GRAI"},
{"index": 11, "dice": 9, "resource_type": "CLAY"},
{"index": 12, "dice": 9, "resource_type": "GRAI"},
{"index": 13, "dice": 3, "resource_type": "LUMB"},
{"index": 14, "dice": 4, "resource_type": "CLAY"},
{"index": 15, "dice": 8, "resource_type": "LUMB"},
{"index": 16, "dice": 10, "resource_type": "WOOL"},
{"index": 17, "dice": 5, "resource_type": "GRAI"},
{"index": 18, "dice": 11, "resource_type": "WOOL"}],
"type": "classic"})
def classic():
no_player = 5 # desert on corner
# no_player = 6 # desert in center
# no_player = 7 # desert in edge
# no_player = 8 # desert in inner circle
start_time = datetime.datetime.now()
catan_map = ClassicMap()
catan_map.generate_map(no_player)
k = 0
while not catan_map.completed():
catan_map.clear()
catan_map.generate_map(no_player)
k += 1
print("completed in:", datetime.datetime.now() - start_time, "seconds, with", k, "attempts")
catan_map.dbg()
dic = catan_map.export()
return dic
def extended():
start_time = datetime.datetime.now()
no_player = 6
catan_map = ExtendedMap()
catan_map.generate_map(no_player)
k = 0
while not catan_map.completed():
# x.dbg()
# sleep(1)
catan_map = ExtendedMap()
catan_map.generate_map(no_player)
k += 1
print("completed in:", datetime.datetime.now() - start_time, "seconds, with", k, "attempts")
catan_map.dbg()
dic = catan_map.export()
return dic
if __name__ == '__main__':
# global_coefficient_records = []
# test()
v = classic()
print(v)
v = extended()
print(v)
# from Statistics import Statistics
# x = Statistics()
# x.coefficients[6] = 10
# x.generate_graph()
|
# Generated by Django 3.1.4 on 2020-12-16 03:29
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('shop', '0022_cupon_amount'),
]
operations = [
migrations.AddField(
model_name='order',
name='received',
field=models.BooleanField(default=False),
),
]
|
"""Unit tests of everything related to retrieving the version
There are four tree states we want to check:
A: sitting on the 1.0 tag
B: dirtying the tree after 1.0
C: a commit after a tag, clean tree
D: a commit after a tag, dirty tree
The tests written in this file use pytest-virtualenv to achieve isolation.
Each test will run inside a different venv in a temporary directory, so they
can execute in parallel and not interfere with each other.
"""
import os
import shutil
from contextlib import contextmanager
from pathlib import Path
from shutil import copyfile
from time import strftime
import pytest
from pyscaffold import dependencies as deps
from pyscaffold import info, shell
from pyscaffold.cli import main as putup
from pyscaffold.file_system import chdir
from pyscaffold.shell import command_exists, git
__location__ = Path(__file__).parent
pytestmark = pytest.mark.slow
untar = shell.ShellCommand(("gtar" if command_exists("gtar") else "tar") + " xvzkf")
# ^ BSD tar differs in options from GNU tar, so make sure to use the correct one...
# https://xkcd.com/1168/
@pytest.fixture
def demoapp(tmpfolder, venv):
return DemoApp(tmpfolder, venv)
@pytest.fixture
def demoapp_data(tmpfolder, venv):
return DemoApp(tmpfolder, venv, data=True)
class DemoApp:
def __init__(self, tmpdir, venv, data=None):
self.name = "demoapp"
if data:
self.name += "_data"
self.pkg_path = Path(str(tmpdir), self.name)
self.built = False
self.installed = False
self.venv = venv
self.venv_path = Path(str(venv.virtualenv))
self.venv_bin = Path(str(venv.python))
self.data = data
self.dist = None
with chdir(str(tmpdir)):
self._generate()
def _generate(self):
putup([self.name])
with chdir(self.name):
demoapp_src_dir = __location__ / self.name
demoapp_dst_root = self.pkg_path
demoapp_dst_pkg = demoapp_dst_root / "src" / self.name
copyfile(demoapp_src_dir / "runner.py", demoapp_dst_pkg / "runner.py")
git("add", demoapp_dst_pkg / "runner.py")
for file in "setup.cfg setup.py pyproject.toml".split():
copyfile(demoapp_src_dir / file, demoapp_dst_root / file)
git("add", demoapp_dst_root / file)
if self.data:
data_src_dir = demoapp_src_dir / "data"
data_dst_dir = demoapp_dst_pkg / "data"
os.mkdir(data_dst_dir)
pkg_file = data_dst_dir / "__init__.py"
pkg_file.write_text("")
git("add", pkg_file)
for file in "hello_world.txt".split():
copyfile(data_src_dir / file, data_dst_dir / file)
git("add", data_dst_dir / file)
git("commit", "-m", "Added basic application logic")
# this is needed for Windows 10 which lacks some certificates
self.run("pip", "install", "-q", "certifi")
def check_not_installed(self):
installed = [
line.split()[0] for line in self.run("pip", "list").split("\n")[2:]
]
dirty = [self.name, "UNKNOWN"]
app_list = [x for x in dirty if x in installed]
if app_list:
raise RuntimeError(
f"Dirty virtual environment:\n{', '.join(app_list)} found"
)
def check_inside_venv(self):
# use Python tools here to avoid problem with unix/win
cmd = f"import shutil; print(shutil.which('{self.name}'))"
cmd_path = self.run("python", "-c", cmd)
if str(self.venv_path) not in cmd_path:
raise RuntimeError(
f"{self.name} found under {cmd_path} should be installed inside the "
f"venv {self.venv_path}"
)
@contextmanager
def guard(self, attr):
if getattr(self, attr):
raise RuntimeError("For simplicity, just build/install once per package")
yield
setattr(self, attr, True)
def run(self, *args, **kwargs):
# pytest-virtualenv doesn't play nicely with external os.chdir
# so let's be explicit about it...
kwargs["cd"] = os.getcwd()
kwargs["capture"] = True
if os.name == "nt":
# Windows 10 needs this parameter seemingly to pass env vars
# correctly.
kwargs["shell"] = True
return self.venv.run(args, **kwargs).strip()
def cli(self, *args, **kwargs):
self.check_inside_venv()
args = [self.name] + list(args)
return self.run(*args, **kwargs)
def setup_py(self, *args, **kwargs):
with chdir(self.pkg_path):
args = ["python", "-Wignore", "setup.py"] + list(args)
# Avoid warnings since we are going to compare outputs
return self.run(*args, **kwargs)
def build(self, dist="bdist", cli_opts=()):
with self.guard("built"), chdir(self.pkg_path):
if "wheel" in dist:
self.run("pip", "install", "wheel")
else:
cli_opts = cli_opts or ["--format", "gztar"]
# ^ force tar.gz (Windows defaults to zip)
self.run("python", "setup.py", dist, *cli_opts)
self.dist = dist
return self
@property
def dist_file(self):
return list((self.pkg_path / "dist").glob(self.name + "*"))[0]
def _install_bdist(self):
setupcfg = info.read_setupcfg(self.pkg_path)
requirements = deps.split(setupcfg["options"]["install_requires"].value)
self.run("pip", "install", *requirements)
with chdir("/"):
# Because of the way bdist works, the tar.gz will contain
# the whole path to the current venv, starting from the
# / directory ...
untar(self.dist_file, "--force-local")
# ^ --force-local is required to deal with Windows paths
# this assumes we have a GNU tar (msys or mingw can provide that but have
# to be prepended to PATH, since Windows seems to ship with a BSD tar)
def install(self, edit=False):
with self.guard("installed"), chdir(self.pkg_path):
self.check_not_installed()
if edit or self.dist is None:
self.run("pip", "install", "-e", ".")
elif self.dist == "bdist":
self._install_bdist()
else:
self.run("pip", "install", self.dist_file)
return self
def installed_path(self):
if not self.installed:
return None
cmd = f"import {self.name}; print({self.name}.__path__[0])"
return Path(self.run("python", "-c", cmd))
def make_dirty_tree(self):
dirty_file = self.pkg_path / "src" / self.name / "runner.py"
with open(dirty_file, "a") as fh:
fh.write("\n\ndirty_variable = 69\n")
return self
def make_commit(self):
with chdir(self.pkg_path):
git("commit", "-a", "-m", "message")
return self
def rm_git_tree(self):
git_path = self.pkg_path / ".git"
shutil.rmtree(git_path)
return self
def tag(self, name, message):
with chdir(self.pkg_path):
git("tag", "-a", name, "-m", message)
return self
def check_version(output, exp_version, dirty=False):
# if multi-line we take the last
output = output.split("\n")[-1]
version = output.strip().split(" ")[-1]
dirty_tag = ".d" + strftime("%Y%m%d")
# ^ this depends on the local strategy configured for setuptools_scm...
# the default 'node-and-date'
# for some setuptools version a directory with + is generated, sometimes _
if dirty:
if "+" in version:
ver, local = version.split("+")
else:
ver, local = version.split("_")
assert local.endswith(dirty_tag) or local[:-1].endswith(dirty_tag[:-1])
# ^ sometimes the day in the dirty tag has a 1-off error ¯\_(ツ)_/¯
assert ver == exp_version
else:
if "+" in version:
ver = version.split("+")
else:
ver = version.split("_")
if len(ver) > 1:
assert not ver[1].endswith(dirty_tag)
assert ver[0] == exp_version
def test_sdist_install(demoapp):
(demoapp.build("sdist").install())
out = demoapp.cli("--version")
exp = "0.0.post1.dev2"
check_version(out, exp, dirty=False)
def test_sdist_install_dirty(demoapp):
(
demoapp.tag("v0.1", "first release")
.make_dirty_tree()
.make_commit()
.make_dirty_tree()
.build("sdist")
.install()
)
out = demoapp.cli("--version")
exp = "0.1.post1.dev1"
check_version(out, exp, dirty=True)
def test_sdist_install_with_1_0_tag(demoapp):
(
demoapp.make_dirty_tree()
.make_commit()
.tag("v1.0", "final release")
.build("sdist")
.install()
)
out = demoapp.cli("--version")
exp = "1.0"
check_version(out, exp, dirty=False)
def test_sdist_install_with_1_0_tag_dirty(demoapp):
demoapp.tag("v1.0", "final release").make_dirty_tree().build("sdist").install()
out = demoapp.cli("--version")
exp = "1.0.post1.dev0"
check_version(out, exp, dirty=True)
# bdist works like sdist so we only try one combination
def test_bdist_install(demoapp):
demoapp.build("bdist").install()
out = demoapp.cli("--version")
exp = "0.0.post1.dev2"
check_version(out, exp, dirty=False)
def test_bdist_wheel_install(demoapp):
demoapp.build("bdist_wheel").install()
out = demoapp.cli("--version")
exp = "0.0.post1.dev2"
check_version(out, exp, dirty=False)
def test_git_repo(demoapp):
out = demoapp.setup_py("--version")
exp = "0.0.post1.dev2"
check_version(out, exp, dirty=False)
def test_git_repo_dirty(demoapp):
(
demoapp.tag("v0.1", "first release")
.make_dirty_tree()
.make_commit()
.make_dirty_tree()
)
out = demoapp.setup_py("--version")
exp = "0.1.post1.dev1"
check_version(out, exp, dirty=True)
def test_git_repo_with_1_0_tag(demoapp):
demoapp.tag("v1.0", "final release")
out = demoapp.setup_py("--version")
exp = "1.0"
check_version(out, exp, dirty=False)
def test_git_repo_with_1_0_tag_dirty(demoapp):
demoapp.tag("v1.0", "final release").make_dirty_tree()
out = demoapp.setup_py("--version")
exp = "1.0.post1.dev0"
check_version(out, exp, dirty=True)
def test_sdist_install_with_data(demoapp_data):
demoapp_data.build("sdist").install()
out = demoapp_data.cli()
exp = "Hello World"
assert out.startswith(exp)
def test_bdist_install_with_data(demoapp_data):
demoapp_data.build("bdist").install()
out = demoapp_data.cli()
exp = "Hello World"
assert out.startswith(exp)
def test_bdist_wheel_install_with_data(demoapp_data):
demoapp_data.build("bdist_wheel").install()
path = demoapp_data.installed_path()
assert path.exists()
assert (path / "data/__init__.py").exists()
assert (path / "data/hello_world.txt").exists()
assert (path / "runner.py").exists()
out = demoapp_data.cli()
exp = "Hello World"
assert out.startswith(exp)
def test_edit_install_with_data(demoapp_data):
demoapp_data.install(edit=True)
out = demoapp_data.cli()
exp = "Hello World"
assert out.startswith(exp)
def test_setup_py_install_with_data(demoapp_data):
demoapp_data.setup_py("install")
out = demoapp_data.cli()
exp = "Hello World"
assert out.startswith(exp)
out = demoapp_data.cli("--version")
exp = "0.0.post1.dev2"
check_version(out, exp, dirty=False)
def test_setup_py_develop_with_data(demoapp_data):
demoapp_data.setup_py("develop")
out = demoapp_data.cli()
exp = "Hello World"
assert out.startswith(exp)
out = demoapp_data.cli("--version")
exp = "0.0.post1.dev2"
check_version(out, exp, dirty=False)
|
# coding=utf-8
# Copyright 2016 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Tests for lexicon_builder."""
# disable=no-name-in-module,unused-import,g-bad-import-order,maybe-no-member
import os.path
import tensorflow as tf
import syntaxnet.load_parser_ops
from tensorflow.python.framework import test_util
from tensorflow.python.platform import googletest
from tensorflow.python.platform import tf_logging as logging
from syntaxnet import sentence_pb2
from syntaxnet import task_spec_pb2
from syntaxnet.ops import gen_parser_ops
FLAGS = tf.app.flags.FLAGS
CONLL_DOC1 = u'''1 बात _ n NN _ _ _ _ _
2 गलत _ adj JJ _ _ _ _ _
3 हो _ v VM _ _ _ _ _
4 तो _ avy CC _ _ _ _ _
5 गुस्सा _ n NN _ _ _ _ _
6 सेलेब्रिटिज _ n NN _ _ _ _ _
7 को _ psp PSP _ _ _ _ _
8 भी _ avy RP _ _ _ _ _
9 आना _ v VM _ _ _ _ _
10 लाजमी _ adj JJ _ _ _ _ _
11 है _ v VM _ _ _ _ _
12 । _ punc SYM _ _ _ _ _'''
CONLL_DOC2 = u'''1 लेकिन _ avy CC _ _ _ _ _
2 अभिनेत्री _ n NN _ _ _ _ _
3 के _ psp PSP _ _ _ _ _
4 इस _ pn DEM _ _ _ _ _
5 कदम _ n NN _ _ _ _ _
6 से _ psp PSP _ _ _ _ _
7 वहां _ pn PRP _ _ _ _ _
8 रंग _ n NN _ _ _ _ _
9 में _ psp PSP _ _ _ _ _
10 भंग _ adj JJ _ _ _ _ _
11 पड़ _ v VM _ _ _ _ _
12 गया _ v VAUX _ _ _ _ _
13 । _ punc SYM _ _ _ _ _'''
TAGS = ['NN', 'JJ', 'VM', 'CC', 'PSP', 'RP', 'JJ', 'SYM', 'DEM', 'PRP', 'VAUX']
CATEGORIES = ['n', 'adj', 'v', 'avy', 'n', 'psp', 'punc', 'pn']
TOKENIZED_DOCS = u'''बात गलत हो तो गुस्सा सेलेब्रिटिज को भी आना लाजमी है ।
लेकिन अभिनेत्री के इस कदम से वहां रंग में भंग पड़ गया ।
'''
CHARS = u'''अ इ आ क ग ज ट त द न प भ ब य म र ल व ह स ि ा ु ी े ै ो ् ड़ । ं'''
COMMENTS = u'# Line with fake comments.'
class LexiconBuilderTest(test_util.TensorFlowTestCase):
def setUp(self):
if not hasattr(FLAGS, 'test_srcdir'):
FLAGS.test_srcdir = ''
if not hasattr(FLAGS, 'test_tmpdir'):
FLAGS.test_tmpdir = tf.test.get_temp_dir()
self.corpus_file = os.path.join(FLAGS.test_tmpdir, 'documents.conll')
self.context_file = os.path.join(FLAGS.test_tmpdir, 'context.pbtxt')
def AddInput(self, name, file_pattern, record_format, context):
inp = context.input.add()
inp.name = name
inp.record_format.append(record_format)
inp.part.add().file_pattern = file_pattern
def WriteContext(self, corpus_format):
context = task_spec_pb2.TaskSpec()
self.AddInput('documents', self.corpus_file, corpus_format, context)
for name in ('word-map', 'lcword-map', 'tag-map',
'category-map', 'label-map', 'prefix-table',
'suffix-table', 'tag-to-category', 'char-map'):
self.AddInput(name, os.path.join(FLAGS.test_tmpdir, name), '', context)
logging.info('Writing context to: %s', self.context_file)
with open(self.context_file, 'w') as f:
f.write(str(context))
def ReadNextDocument(self, sess, doc_source):
doc_str, last = sess.run(doc_source)
if doc_str:
doc = sentence_pb2.Sentence()
doc.ParseFromString(doc_str[0])
else:
doc = None
return doc, last
def ValidateDocuments(self):
doc_source = gen_parser_ops.document_source(self.context_file, batch_size=1)
with self.test_session() as sess:
logging.info('Reading document1')
doc, last = self.ReadNextDocument(sess, doc_source)
self.assertEqual(len(doc.token), 12)
self.assertEqual(u'लाजमी', doc.token[9].word)
self.assertFalse(last)
logging.info('Reading document2')
doc, last = self.ReadNextDocument(sess, doc_source)
self.assertEqual(len(doc.token), 13)
self.assertEqual(u'भंग', doc.token[9].word)
self.assertFalse(last)
logging.info('Hitting end of the dataset')
doc, last = self.ReadNextDocument(sess, doc_source)
self.assertTrue(doc is None)
self.assertTrue(last)
def ValidateTagToCategoryMap(self):
with file(os.path.join(FLAGS.test_tmpdir, 'tag-to-category'), 'r') as f:
entries = [line.strip().split('\t') for line in f.readlines()]
for tag, category in entries:
self.assertIn(tag, TAGS)
self.assertIn(category, CATEGORIES)
def LoadMap(self, map_name):
loaded_map = {}
with file(os.path.join(FLAGS.test_tmpdir, map_name), 'r') as f:
for line in f:
entries = line.strip().split(' ')
if len(entries) == 2:
loaded_map[entries[0]] = entries[1]
return loaded_map
def ValidateCharMap(self):
char_map = self.LoadMap('char-map')
self.assertEqual(len(char_map), len(CHARS.split(' ')))
for char in CHARS.split(' '):
self.assertIn(char.encode('utf-8'), char_map)
def ValidateWordMap(self):
word_map = self.LoadMap('word-map')
for word in filter(None, TOKENIZED_DOCS.replace('\n', ' ').split(' ')):
self.assertIn(word.encode('utf-8'), word_map)
def BuildLexicon(self):
with self.test_session():
gen_parser_ops.lexicon_builder(task_context=self.context_file).run()
def testCoNLLFormat(self):
self.WriteContext('conll-sentence')
logging.info('Writing conll file to: %s', self.corpus_file)
with open(self.corpus_file, 'w') as f:
f.write((CONLL_DOC1 + u'\n\n' + CONLL_DOC2 + u'\n')
.replace(' ', '\t').encode('utf-8'))
self.ValidateDocuments()
self.BuildLexicon()
self.ValidateTagToCategoryMap()
self.ValidateCharMap()
self.ValidateWordMap()
def testCoNLLFormatExtraNewlinesAndComments(self):
self.WriteContext('conll-sentence')
with open(self.corpus_file, 'w') as f:
f.write((u'\n\n\n' + CONLL_DOC1 + u'\n\n\n' + COMMENTS +
u'\n\n' + CONLL_DOC2).replace(' ', '\t').encode('utf-8'))
self.ValidateDocuments()
self.BuildLexicon()
self.ValidateTagToCategoryMap()
def testTokenizedTextFormat(self):
self.WriteContext('tokenized-text')
with open(self.corpus_file, 'w') as f:
f.write(TOKENIZED_DOCS.encode('utf-8'))
self.ValidateDocuments()
self.BuildLexicon()
def testTokenizedTextFormatExtraNewlines(self):
self.WriteContext('tokenized-text')
with open(self.corpus_file, 'w') as f:
f.write((u'\n\n\n' + TOKENIZED_DOCS + u'\n\n\n').encode('utf-8'))
self.ValidateDocuments()
self.BuildLexicon()
if __name__ == '__main__':
googletest.main()
|
stack = []
serving = {}
b = 0
n = int(raw_input())
while n:
s = raw_input().split(" ")
if s[0] == '1':
stack.append(int(s[1]))
else:
serving[stack.pop()] = b
b = b + 1
n = n - 1
for i in serving:
print serving[i], |
#Author: Aritri Paul
#To execute the code, type the following command in your terminal: python3 DOHRange.py
import sys
import pyshark
text_file=open("Commonsubsq.txt",'r')
sizeset=set()
for line in text_file:
for i in range(len(line)):
if(line[i]=='['):
array=[]
s=""
i+=1
while(line[i]!=']'):
s=s+line[i]
i+=1
array=list(s.split(','))
for i in array: #add all sizes into a set, to find the final set of distinct DOH packet sizes
sizeset.add(i)
writef=open('sizeset.txt','w')
for i in sizeset:
writef.write(str(i)+" ")
|
LEGIBLE = ('legibility', 'legible')
ILLEGIBLE = ('legibility','illegible')
ENGLISH = ('language', 'english')
NOT_ENGLISH = ('language', 'not english')
NA = ('langauge', 'na')
MACHINE_PRINTED = ('class', 'machine printed')
HANDWRITTEN = ('class', 'handwritten')
OTHERS = ('class', 'others')
def inter(list1, list2):
return list(set(list1) & set(list2)) |
favorite = "JihongZhang"
for i in favorite:
print(i, end=' \t')
print('\n')
for num in range(2, 9):
print(num, end = '\t')
total = 0
for num2 in range(1, 10, 2):
total += num2
print(total)
|
from django.utils.text import slugify
from django.utils.crypto import get_random_string
def get_generate_slug(instance, new_slug=None):
if new_slug is not None:
slug = new_slug
else:
try:
slug = slugify(instance.title)
except AttributeError:
slug = slugify(instance.name)
Klass = instance.__class__
qs_exists = Klass.objects.filter(slug=slug).exists()
if qs_exists:
new_slug = f'{slug}-{get_random_string()}'
return new_slug
return slug
|
import torch
import numpy as np
from skfuzzy.membership import trimf
class Activations:
"""
Regular activation functions used in the module are defined here.
The activation functions used are:
* Sigmoid
* Relu
* Swish
* Leaky Relu
* tanh
"""
## Sigmoid Activation
@staticmethod
def Sigmoid(z):
z = 1/(1 + np.exp(-z))
return z
## Relu Activation
@staticmethod
def Relu(z):
z = max(0,z)
return z
## Tanh Activation
@staticmethod
def Tanh(z):
z = np.tanh(z)
return z
## Leaky Relu Activation
@staticmethod
def Leaky_Relu(z):
z = np.where(z > 0, z, z * 0.01)
return z
## Swish Activation
@staticmethod
def Swish(z):
z = z*Sigmoid(z)
return z
## Functions for T Norm
"""
Avialble T Norm Activations
* Product T Norm
* Minimum T Norm
* Luckasiewickz T Norm
"""
# Minimum T Norm
@staticmethod
def t_norm_min(mode,device,weight_matrix = 0, input_matrix = 0, z = 0):
if mode == "b":
a = torch.randn(weight_matrix.size()[0], weight_matrix.size()[1], device = device)
j = 0
for i in weight_matrix:
a[j] = torch.min(i,input_matrix.squeeze(1))
j+=1
return a
elif mode == "v":
z = torch.min(z, axis =1).values
z = z.view(-1,1)
return z
# Product T Norm
@staticmethod
def prod_t_norm(mode,device,weight_matrix = 0, input_matrix = 0, z = 0):
if mode == "b":
a = torch.randn(weight_matrix.size()[0], weight_matrix.size()[1], device = device)
j = 0
for i in weight_matrix:
a[j] = torch.mul(i, input_matrix.squeeze(1))
j+=1
return a
elif mode == "v":
# print("Input for Z",z)
z = torch.prod(z, axis = 1)
z = z.view(-1,1)
return z
# Luckasiewickz T Norm
@staticmethod
def luka_t_norm(mode, device, weight_matrix = 0, input_matrix = 0, z = 0):
if mode == "b":
a = torch.rand(weight_matrix.size()[0], weight_matrix.size()[1], device =device)
j=0
for i in weight_matrix:
a[j] = torch.max(i + input_matrix.squeeze(1) - torch.ones(weight_matrix.size()[1], device = device),torch.zeros(weight_matrix.size()[1], device = device))
j+=1
return a
elif mode == "v":
z = torch.max(torch.sum(z, axis =1)-torch.ones(z.size()[0], device = device),torch.zeros(z.size()[0], device = device))
z = z.view(-1,1)
return z
## Functions for T Co Norm or S Norm
"""
Available T Co Norm or S Norm Activations
* Probablistic Sum S Norm
* Luckasiewickz S Norm
* Maximum S Norm
"""
# Maximum S Norm
def s_norm_max(mode,device,weight_matrix = 0, input_matrix = 0, z = 0):
if mode == "b":
a = torch.randn(weight_matrix.size()[0],weight_matrix.size()[1],device = device)
j=0
for i in weight_matrix:
a[j] = torch.max(i, input_matrix.squeeze(1))
j+=1
return a
elif mode == "v":
z = torch.max(z, axis = 1).values
z = z.view(-1,1)
return z
# Probablistic Sum S Norm
def prob_s_norm(mode,device,weight_matrix = 0, input_matrix = 0, z = 0):
# print("Weights", weight_matrix)
# print("Input Mattrix", input_matrix)
if mode == "b":
a = torch.zeros(weight_matrix.size()[0], weight_matrix.size()[1], device = device)
j=0
for i in weight_matrix:
a[j] = torch.sub((i + input_matrix.squeeze(1)),(i*input_matrix.squeeze(1)))
# print(a[j])
j+=1
# print(a)
return a
elif mode == "v":
z = torch.sum(z, axis = 1) - torch.prod(z, axis = 1)
z = z.view(-1,1)
return z
# Luckasiewickz S Norm
def luka_s_norm(mode,device,weight_matrix = 0, input_matrix = 0, z = 0):
if mode == "b":
a = torch.rand(weight_matrix.size()[0], weight_matrix.size()[1], device =device)
j=0
for i in weight_matrix:
a[j] = torch.min(i + input_matrix.squeeze(1),torch.ones(i.size()[0], device = device))
j+=1
return a
elif mode == "v":
z = torch.min(torch.sum(z, axis = 1), torch.ones(z.size()[0]))
z = z.view(-1,1)
return z
class support:
"""This class includes all the support functions used in the package"""
## Function for normalising a vector
@staticmethod
def normalise(x):
maxi = torch.max(x)
mini = torch.min(x)
x = (x-mini)/(maxi-mini)
return x
class Model:
"""Structuring the Neural Network Model"""
@staticmethod
def check_cuda(self):
"""Check if there is CUDA Device available for GPU accelaration"""
if torch.cuda.is_available():
self.device = torch.device("cuda")
print("Cuda Device Available")
print("Name of the Cuda Device: ", torch.cuda.get_device_name())
print("GPU Computational Capablity: ", torch.cuda.get_device_capability())
else:
print("Please check whether you have CUDA supported device")
def __init__(self, input_shape, accelaration = "gpu",):
self.accelaration = accelaration
## Define the parameters for a neural network model
print("Initializing the Network...")
## Check for GPU Accelaration Availablity
if self.accelaration == "gpu":
Model.check_cuda(self)
self.layers = []
self.no_of_layers = 0
self.weights = []
self.activations = []
## Input Shape
self.input_shape = input_shape
## Gradients of Layers
self.grad = []
## Garbage Variables
self.prev_layer_shape = 0
self.iteration = 0
self.iterationt = 0
def add_layer(self, no_of_neurons, layer_activation, t_norm = "prod", s_norm = "prob"):
"""
no_of_neurons ==> Represent the Number of Neurons in that particular layer
activation ==> Represent the activation to be used for that particular layer
"""
## Create the current layer
# layer = torch.empty(no_of_neurons, 1,device = self.device, requires_grad = True)
if self.no_of_layers == 0:
self.prev_layer_shape = self.input_shape
## Initialize weights between the current layer and previous layer
weights = (torch.rand(no_of_neurons, self.prev_layer_shape, device = self.device, requires_grad = True))
## Add the layer to the model architecture
self.no_of_layers +=1
# self.layers.append(layer)
self.prev_layer_shape = no_of_neurons
## Add the intiated weights to weights list
self.weights.append(weights)
## Add the activation to the layer
dict = {'act':layer_activation, 't_norm':t_norm, 's_norm':s_norm}
self.activations.append(dict)
@staticmethod
def compute_layer(self, weight_matrix, input_matrix, layer_number):
## Device is GPU
device = self.device
if self.activations[layer_number]['act'] == 'AND':
"""
AND Neuron ==> T(S(x,y))
"""
if self.activations[layer_number]['s_norm'] == "max":
z = Activations.s_norm_max("b",device, weight_matrix, input_matrix)
elif self.activations[layer_number]['s_norm'] == "luka":
z = Activations.luka_s_norm("b",device, weight_matrix, input_matrix)
elif self.activations[layer_number]['s_norm'] == "prob":
z = Activations.prob_s_norm("b",device, weight_matrix, input_matrix)
if self.activations[layer_number]['t_norm'] == "min":
z = Activations.t_norm_min("v",device, z = z)
elif self.activations[layer_number]['t_norm'] == "luka":
z = Activations.luka_t_norm("v",device, z = z)
elif self.activations[layer_number]['t_norm'] == "prod":
z = Activations.prod_t_norm("v",device, z = z)
elif self.activations[layer_number]['act'] == 'OR':
"""
OR Neuron ==> S(T(x,y))
"""
if self.activations[layer_number]['t_norm'] == "min":
z = Activations.t_norm_min("b",device, weight_matrix, input_matrix)
elif self.activations[layer_number]['t_norm'] == "luka":
z = Activations.luka_t_norm("b",device, weight_matrix, input_matrix)
elif self.activations[layer_number]['t_norm'] == "prod":
z = Activations.prod_t_norm("b",device, weight_matrix, input_matrix)
if self.activations[layer_number]['s_norm'] == "max":
z = Activations.s_norm_max("v",device, z = z)
elif self.activations[layer_number]['s_norm'] == "luka":
z = Activations.luka_s_norm("v",device, z = z)
elif self.activations[layer_number]['s_norm'] == "prob":
z = Activations.prob_s_norm("v",device, z = z)
self.layers.append(z)
def train_model(self, X, Y, lr = 0.00001):
print("No of Layers: ", self.no_of_layers)
self.intermediate = []
for epoch in range(100):
overall_loss = 0
print("Epoch:",epoch+1)
for i in range(len(X)):
self.layers = []
inp = X.iloc[i,:]
output = Y.iloc[i]
## PreProcessing for one input
a = torch.tensor(inp)
# a = torch.from_numpy(trimf(a,[0,3,10]))
a = a.to(device = torch.device('cuda'))
a = a.view(-1,1)
output = torch.tensor(output, device = self.device)
# print("Input Number:",i)
## Feed Forward
for layer in range(self.no_of_layers):
if layer == 0:
inpt = a
else:
inpt = self.layers[layer-1]
Model.compute_layer(self,self.weights[layer],inpt,layer)
pred = self.layers[-1]
## Loss Function
loss = (pred - output)**2
overall_loss +=torch.sum(loss) ## Incase if the output is multidimensional vector
overall_loss = overall_loss/len(X)
## Back Propgation
overall_loss.backward(retain_graph = True)
j = 0
for w in self.weights:
w.data -= (lr*((w.grad-torch.min(w.grad))/(torch.max(w.grad)-torch.min(w.grad))))
w.grad.zero_()
w.data = (w.data - torch.min(w.data))/(torch.max(w.data) - torch.min(w.data))
print("MSE: ", overall_loss.item())
|
import torch
x = torch.randn(4, 4)
print(x.size()) # torch.Size([4, 4])
y = x.view(16)
print(y.size()) # torch.Size([16])
|
import datetime
import random
import re
from django.conf import settings
from django.contrib.auth.models import User
from django.db import models
from django.db import transaction
from django.template.loader import render_to_string
from django.utils.hashcompat import sha_constructor
ACTIVATED = 'ALREADY_ACTIVATED'
SHA1_RE = re.compile('^[a-f0-9]{40}$')
class RegistrationManager(models.Manager):
def activate_user(self, activation_key):
"""
Validate an activation key and activate the corresponding User if valid.
If the key is valid and has not expired, return the User after activating.
If the key is not valid or has expired, return ``False``.
If the key is valid but the ``User`` is already active, return ``False``.
"""
# Make sure the key we're trying conforms to the pattern of a
# SHA1 hash; if it doesn't, no point trying to look it up in
# the database.
if SHA1_RE.search(activation_key):
try:
profile = self.get(activation_key=activation_key)
except self.model.DoesNotExist:
return False
if not profile.activation_key_expired():
user = profile.user
user.is_active = True
user.save()
profile.activation_key = ACTIVATED
profile.save()
return user
return False
@transaction.commit_on_success
def create_inactive_user(self, username, email, password, send_email=True):
""" Create a new, inactive User, generate a RegistrationProfile and email its activation key to the User """
new_user = User.objects.create_user(username, email, password)
new_user.is_active = False
new_user.save()
registration_profile = self.create_profile(new_user)
if send_email:
registration_profile.send_activation_email()
return new_user
def create_profile(self, user):
# The activation key is a SHA1 hash, generated from a combination of the username and a random salt
salt = sha_constructor(str(random.random())).hexdigest()[:5]
activation_key = sha_constructor(salt+user.username).hexdigest()
return self.create(user=user, activation_key=activation_key)
def delete_expired_users(self):
"""
Remove expired instances of RegistrationProfile and their associated User's.
It is recommended that this method be executed regularly as
part of your routine site maintenance; this application
provides a custom management command which will call this
method, accessible as ``manage.py cleanupregistration``.
Regularly clearing out accounts which have never been
activated serves two useful purposes:
1. It alleviates the ocasional need to reset a
``RegistrationProfile`` and/or re-send an activation email
when a user does not receive or does not act upon the
initial activation email; since the account will be
deleted, the user will be able to simply re-register and
receive a new activation key.
2. It prevents the possibility of a malicious user registering
one or more accounts and never activating them (thus
denying the use of those usernames to anyone else); since
those accounts will be deleted, the usernames will become
available for use again.
If you have a troublesome ``User`` and wish to disable their
account while keeping it in the database, simply delete the
associated ``RegistrationProfile``; an inactive ``User`` which
does not have an associated ``RegistrationProfile`` will not
be deleted.
"""
for profile in self.all():
if profile.activation_key_expired():
user = profile.user
if not user.is_active:
user.delete()
class RegistrationProfile(models.Model):
user = models.ForeignKey(User, unique=True)
activation_key = models.CharField(max_length=40)
objects = RegistrationManager()
def __unicode__(self):
return u"Registration information for %s" % self.user
def activation_key_expired(self):
""" Boolean showing whether this RegistrationProfile's activation key has expired """
expiration_date = datetime.timedelta(days=settings.ACCOUNT_ACTIVATION_DAYS)
return self.activation_key==ACTIVATED or \
(self.user.date_joined+expiration_date <= datetime.datetime.now())
activation_key_expired.boolean = True
def send_activation_email(self):
context = {
'activation_key': self.activation_key,
'expiration_days': settings.ACCOUNT_ACTIVATION_DAYS,
}
subject = render_to_string('registration/activation_email_subject.txt', context)
subject = ''.join(subject.splitlines()) # Email subject must not contain newlines
message = render_to_string('registration/activation_email.txt', context)
self.user.email_user(subject, message, settings.DEFAULT_FROM_EMAIL)
|
#!/usr/bin/python3
# -*- coding:utf-8 -*-
"""
:auteur 1: DOUCHET Benjamin
:auteur 2:
:groupe: SESI 12
:date: vendredi 27 mars 2020
:objet: Travail numéro 9 (Nombres premiers et témoins de Fermat)
"""
from matplotlib import pyplot as plt
from math import log
from random import randrange
from tp6_arithmetique import *
from tp1 import *
def expo_mod_rapide(a, b, n):
"""
:param int a:
:param int b: exposant
:param int n: modulus
:return: r dans {0, 1, ..., n-1} tel que a^b = r (mod n)
calcul effectué par l'exponentiation rapide.
:rtype: int
:CU: b >= 0, n > 0
:Exemples:
>>> expo_mod_rapide(2, 10, 100)
24
>>> expo_mod_rapide(14, 3141, 17)
12
"""
return pow(a, b, n)
def est_temoin_non_primalite(a, n):
'''
:param int a, n:
:return:
- True si a est un témoin de non primalité de n
- False sinon
:rtype: bool
:CU: n > 1
Attention, bizarrement cette procédure ne considère comme témoin de non
primalité que les "a<n" avec pgcd(a, n) == 1 (et la condition supplémentaire
du texte).
Pourtant si pgcd(a, n) > 1 avec a < n alors certainement on a prouvé que n
n'était pas premier (on a trouvé un diviseur propre !). Néanmoins il faut
renvoyer False dans ce cas. Il aurait mieux valu que la procédure
s'appelât est_temoin_de_Fermat(a, n).
Personnellement je préférerais une procédure qui ne calculerait pas
pgcd(a, n) mais qui aurait comme *Condition d'Utilisation* que pgcd(a,n)==1.
Cela la rendrait plus utile comme sous-routine générale.
:Exemples:
>>> n = 2**32 + 1
>>> est_temoin_non_primalite(2, n)
False
>>> est_temoin_non_primalite(3, n)
True
'''
res = False
if pgcd(a,n) == 1 and not( expo_mod_rapide(a, n-1, n) == 1 ) :
res = True
return res
# Exercice
# Trouvez l'entier inférieur à 10000 dont le nombre de témoins de non
# primalité est relativement le plus grand, i.e. telle que la fréquence de ce
# nombre de témoins nbre temoins/(n−2) est la plus grande. Même question avec
# la fréquence la plus petite mais non nulle.
def est_carmichael(n):
'''Détermine si n est un nombre de Carmichael par le critère de Korselt
On utilisera la procédure factorise() du module tp6_arithmetique et on
lira attentivement l'énoncé du théorème de Korselt.
:param int n:
:return:
- True si n est un nombre de Carmichael
- False sinon
:rtype: bool
:CU: n > 0
:Exemples:
>>> any(est_carmichael(k) for k in range(1, 561))
False
>>> est_carmichael(561)
True
'''
if est_premier2(n) or n==1 :
return False
facteurs = factorise(n)
for i in range(len(facteurs)):
if n%(facteurs[i][0]**2)==0 :
return False
cond=[]
for i in range(len(facteurs)):
cond.append((n-1)%(facteurs[i][0]-1)==0)
return all(cond)
def est_carmichael_sans_korselt(n):
'''
Détermine si n est un nombre de Carmichael
La méthode consistera à parcourir les a de 2 à n-1 (on s'occupera
donc directement de n égal à 1, 2, 3 ou 4),
à calculer pgcd(a, n) et pour ceux pour lequel ce pgcd vaut 1
à évaluer a**(n-1) modulo n (bien sûr par exponentiation modulaire rapide)
et à regarder si c'est 1 dans tous les cas ; si oui, et si n n'est pas premier,
c'est-à-dire si au moins un "a" a été trouvé avec pgcd(a, n) > 1
(le premier a est le plus petit diviseur de n, en fait), alors
n est un nombre de Carmichael.
La méthode est donc naïve et lente, ne la testez pas avec des
entiers trop grands.
Réfléchir aussi à gagner un facteur 2 d'efficacité. Il faut réfléchir
au cas de a==n-1 et s'il est important de le tester. (Optionnel).
:param int n:
:return:
- True si n est un nombre de Carmichael
- False sinon
:rtype: bool
:CU: n > 0
:Exemples:
>>> est_carmichael_sans_korselt(561)
True
>>> any(est_carmichael_sans_korselt(k) for k in range(1, 561))
False
'''
if est_premier2(n) or n==1 :
return False
for i in range(1,n) :
if est_temoin_non_primalite(i, n)==True and pgcd(i,n)==1 :
return False
return True
# Exercice :
#
# La décomposition en facteurs premiers des nombres de Carmichael comprend au
# moins trois facteurs premiers. Trouvez tous les nombres de Carmichael
# produits de trois nombres premiers inférieurs à 1000. Combien y en a-t-il ?
#
def est_compose(n, nbre_essais=20):
'''
:param int n:
;param int nbre_essais: nbre maximal de tentatives de trouver
un témoin de non primalité
:return:
- True si un témoin de non primalité a été trouvé
- False sinon
:rtype: bool
:CU: n > 2
'''
res = False
for i in range(nbre_essais):
if est_temoin_non_primalite(randint(2,n-1),n) :
res = True
return res
# Exercice: Existe-t-il un nombre de Fermat Fn, avec 8≤n≤14 qui soit premier ?
# Exercice : Utilisez le prédicat est_compose pour trouver un nombre
# (probablement) premier ayant 30 chiffres.
if __name__ == "__main__":
import doctest
doctest.testmod(optionflags=doctest.NORMALIZE_WHITESPACE |
doctest.ELLIPSIS,
verbose=True)
|
from setuptools import setup
with open("README.md", "r") as fh:
long_description = fh.read()
setup(
name="plotapi",
version="1.0.0",
description="Engaging visualisations, made easy.",
long_description=long_description,
long_description_content_type="text/markdown",
url="https://plotapi.com",
author="Dr. Shahin Rostami",
author_email="hello@plotapi.com",
license="MIT",
packages=["plotapi"],
zip_safe=False,
)
|
#!/usr/bin/python
# encoding: utf-8
# -*- coding: utf8 -*-
"""
Created by PyCharm.
File: LinuxBashShellScriptForOps:download_file.py
User: Guodong
Create Date: 2016/9/13
Create Time: 15:41
"""
import hashlib
import os
import socket
import sys
import urllib
from timeout import timeout
try:
from requests.packages import urllib3
except ImportError:
import urllib3
def get_hash_sum(name, method="md5", block_size=65536):
if not os.path.exists(name):
raise RuntimeError("cannot open '%s' (No such file or directory)" % name)
if not os.path.isfile(name):
raise RuntimeError("'%s' :not a regular file" % name)
if "md5" in method:
checksum = hashlib.md5()
elif "sha1" in method:
checksum = hashlib.sha1()
elif "sha256" in method:
checksum = hashlib.sha256()
else:
raise RuntimeError("unsupported method %s" % method)
# if os.path.exists(filename) and os.path.isfile(filename):
with open(name, 'rb') as f:
buf = f.read(block_size)
while len(buf) > 0:
checksum.update(buf)
buf = f.read(block_size)
if checksum is not None:
return checksum.hexdigest()
else:
return checksum
if __name__ == '__main__':
urllib3.disable_warnings()
mswindows = (sys.platform == "win32") # learning from 'subprocess' module
url = "https://raw.githubusercontent.com/racaljk/hosts/master/hosts"
filename = url.split('/')[-1]
save = os.path.join("/tmp", filename).replace("\\", "/")
if mswindows:
# global socket timeout
socket.setdefaulttimeout(10.0)
print "Downloading", url
urllib.urlretrieve(url, filename=save)
else:
assert sys.platform == "linux2", "please run this script on Windows or Linux"
with timeout(timeout=10.0):
urllib.urlretrieve(url, filename=save)
if os.path.isfile(save):
print "Saved: '%s'" % save
print "md5sum:", get_hash_sum(save, method="md5")
print "sha1sum:", get_hash_sum(save, method="sha1sum")
print "sha256sum:", get_hash_sum(save, method="sha256sum")
else:
print "can not download", url
sys.exit(1)
|
from graph import *
import math as m
def alien(x, y, size, mirror):
body(x, y, size, mirror)
apple(x+2.5*size*mirror, y-size*3.3, size / 25, mirror)
def apple(x, y, size, mirror):
r = 25 * size
penColor(245, 84, 84)
penSize(0)
brushColor(245, 84, 84)
circle(x, y, r)
penColor("black")
penSize(2 * size)
line(x, y - r * 0.8, x + r * 0.5 * mirror, y - r * 1.7)
brushColor(100, 225, 100)
penSize(size)
polygon(curve(x + r * 0.1 * mirror, y - r * 1.1, size, not (mirror+1)))
def ufo(x, y, size):
penSize(0)
brushColor(210, 250, 210)
penColor(210, 250, 210)
light = []
light.append((x, y))
light.append((x - 20 * size, y + 20 * size))
light.append((x + 20 * size, y + 20 * size))
polygon(light)
brushColor(168, 168, 168)
penColor(168, 168, 168)
ellips(x, y, 20 * size, 5 * size, 0)
brushColor(180, 220, 220)
penColor(180, 220, 220)
ellips(x, y - 3 * size, 12 * size, 4 * size, 0)
brushColor('white')
penColor('white')
ellips(x, y + 3 * size, 3 * size, 1 * size, 0)
ellips(x - 8 * size, y + 2 * size, 3 * size, 1 * size, 0)
ellips(x + 8 * size, y + 2 * size, 3 * size, 1 * size, 0)
ellips(x - 14 * size, y + 0.05 * size, 3 * size, 1 * size, 0)
ellips(x + 14 * size, y + 0.05 * size, 3 * size, 1 * size, 0)
def curve(x, y, size, mirror):
if mirror:
m = 1
else:
m = -1
res = []
for i in range(int(40 * size)):
res.append((x + m * i * 0.6 * size, y + (-5 * size) * (i**0.3)))
return res
def ellips(x, y, a, b, f):
f = f * m.pi / 180
x_e = [i for i in range(-a, a)]
y1, y2 = [], []
for i in range(len(x_e)):
xy1 = [x_e[i], b * (1 - (x_e[i] / a)**2)**0.5]
xy2 = [x_e[i], -b * (1 - (x_e[i] / a)**2)**0.5]
xy1 = [xy1[0] * m.cos(f) - xy1[1] * m.sin(f), xy1[0]
* m.sin(f) + xy1[1] * m.cos(f)]
xy2 = [xy2[0] * m.cos(f) - xy2[1] * m.sin(f), xy2[0]
* m.sin(f) + xy2[1] * m.cos(f)]
y1.append((xy1[0] + x, xy1[1] + y))
y2.append((xy2[0] + x, xy2[1] + y))
y2 = y2[::-1]
polygon(y1 + y2)
def body(x_b, y_b, S, mirrow):
color = '#67E667'
penColor(color)
brushColor(color)
ellips(x_b, y_b, S, 1.5 * S // 1, 0) # main body
ellips(x_b + 1.1 * S * mirrow, y_b - 1.2 * S, S // 2, S // 2, 0)
ellips(x_b - 1.1 * S * mirrow, y_b - 0.7 * S, S // 2, S // 2, 0)
ellips(x_b - 1.5 * S * mirrow, y_b - 0.2 *
S, S // 2, S * 1.2 // 1, 30 * mirrow)
ellips(x_b - 2.5 * S * mirrow, y_b + 0.5 * S,
S // 2, S * 0.8 // 1, -100 * mirrow)
ellips(x_b + 2.1 * S * mirrow, y_b - 1.4 *
S, int(S / 1.1), S // 2, -20 * mirrow)
ellips(x_b + 2.5 * S * mirrow, y_b - 2.1 * S,
int(S / 1.6), int(S / 2.4), 10 * mirrow)
ellips(x_b, y_b + S * 1.5, S, S, 0)
ellips(x_b + S * mirrow, y_b + S * 2.7, S //
2, S // 1, -10 * mirrow) # left_leg
ellips(x_b + S * mirrow, y_b + S * 4, S // 2, S // 1, -10 * mirrow)
ellips(x_b + 1.6 * S * mirrow, y_b + S * 5,
S // 2, S * 0.9 // 1, -90 * mirrow)
ellips(x_b - S * mirrow, y_b + S * 2.7, S //
2, S // 1, 10 * mirrow) # right_leg
ellips(x_b - 1.3 * S * mirrow, y_b + S * 4, S // 2, S // 1, 10 * mirrow)
ellips(x_b - 1.8 * S * mirrow, y_b + S * 5,
S // 2, S * 0.9 // 1, 70 * mirrow)
penSize(S // 2) # head
polygon([(x_b + 1.6 * S, y_b - 3 * S),
(x_b, y_b + 2 * S - 3 * S), (x_b - 1.6 * S, y_b - 3 * S)])
penSize(1)
brushColor('black')
circle(x_b + 1 * S, y_b - 2.8 * S, S // 2)
circle(x_b - 1 * S, y_b - 2.8 * S, S // 2)
brushColor('white')
circle(x_b + 1.2 * S * mirrow, y_b - 3 * S, S // 4)
circle(x_b - 0.8 * S * mirrow, y_b - 3 * S, S // 4)
def cloud (x, y, S, color):
brushColor(color+50, color+50, color+50)
penColor(color+50, color+50, color+50)
ellips(x-1.2*S, y, S, S, 0)
ellips(x, y, S, S, 0)
ellips(x+1.2*S, y, S, S, 0)
brushColor('#042767')
rectangle(0, 0, 500, 400)
brushColor('green')
rectangle(0, 400, 500, 800)
brushColor(180, 180, 180)
circle(350, 120, 100)
for i in range(100):
cloud(250, 250, 80-i//2, i)
for i in range(100):
cloud(100, 100, 50-i//2, i)
for i in range(70):
cloud(350, 100, 60-i//2, i)
ufo(450, 150, 3)
ufo(120, 100, 5)
ufo(280, 280, 7)
#body(200 - 30, 200 + 30, 25, 1)
#ufo(180, 350, 10)
#polygon(curve(400, 400, 1, False))
#polygon(curve(350, 350, 1, True))
#apple(235, 150, 1, 1)
alien(60, 360, 15, -1)
alien(200, 420, 20, 1)
alien(460, 370, 10, -1)
alien(360, 470, 12, 1)
run()
|
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
# pyre-strict
import asyncio
from typing import Any, Dict, List, Optional, Tuple
from fbpcs.entity.container_instance import ContainerInstance, ContainerInstanceStatus
from fbpcs.gateway.ecs import ECSGateway
from fbpcs.service.container import ContainerService
from fbpcs.util.typing import checked_cast
class AWSContainerService(ContainerService):
def __init__(
self,
region: str,
cluster: str,
subnet: str,
access_key_id: Optional[str] = None,
access_key_data: Optional[str] = None,
config: Optional[Dict[str, Any]] = None,
) -> None:
self.region = region
self.cluster = cluster
self.subnet = subnet
self.ecs_gateway = ECSGateway(region, access_key_id, access_key_data, config)
def create_instance(self, container_definition: str, cmd: str) -> ContainerInstance:
return asyncio.run(self._create_instance_async(container_definition, cmd))
def create_instances(
self, container_definition: str, cmds: List[str]
) -> List[ContainerInstance]:
return asyncio.run(self._create_instances_async(container_definition, cmds))
async def create_instances_async(
self, container_definition: str, cmds: List[str]
) -> List[ContainerInstance]:
return await self._create_instances_async(container_definition, cmds)
def get_instance(self, instance_id: str) -> ContainerInstance:
return self.ecs_gateway.describe_task(self.cluster, instance_id)
def get_instances(self, instance_ids: List[str]) -> List[ContainerInstance]:
return self.ecs_gateway.describe_tasks(self.cluster, instance_ids)
def list_tasks(self) -> List[str]:
return self.ecs_gateway.list_tasks(cluster=self.cluster)
def stop_task(self, task_id: str) -> Dict[str, Any]:
return self.ecs_gateway.stop_task(cluster=self.cluster, task_id=task_id)
def _split_container_definition(self, container_definition: str) -> Tuple[str, str]:
"""
container_definition = task_definition#container
"""
s = container_definition.split("#")
return (s[0], s[1])
async def _create_instance_async(
self, container_definition: str, cmd: str
) -> ContainerInstance:
task_definition, container = self._split_container_definition(
container_definition
)
instance = self.ecs_gateway.run_task(
task_definition, container, cmd, self.cluster, self.subnet
)
# wait until the container is in running state
while instance.status is ContainerInstanceStatus.UNKNOWN:
await asyncio.sleep(1)
instance = self.get_instance(instance.instance_id)
return instance
async def _create_instances_async(
self, container_definition: str, cmds: List[str]
) -> List[ContainerInstance]:
tasks = [
asyncio.create_task(self._create_instance_async(container_definition, cmd))
for cmd in cmds
]
res = await asyncio.gather(*tasks)
return [checked_cast(ContainerInstance, instance) for instance in res]
|
import FWCore.ParameterSet.Config as cms
#AOD content
RecoVertexAOD = cms.PSet(
outputCommands = cms.untracked.vstring('keep *_offlinePrimaryVertices__*',
'keep *_offlinePrimaryVerticesWithBS_*_*',
'keep *_offlinePrimaryVerticesFromCosmicTracks_*_*',
'keep *_nuclearInteractionMaker_*_*',
'keep *_generalV0Candidates_*_*',
'keep *_inclusiveSecondaryVertices_*_*')
)
from Configuration.Eras.Modifier_phase2_timing_cff import phase2_timing
from Configuration.Eras.Modifier_phase2_timing_layer_cff import phase2_timing_layer
_phase2_tktiming_RecoVertexEventContent = [ 'keep *_offlinePrimaryVertices4D__*',
'keep *_offlinePrimaryVertices4DWithBS__*',
'keep *_trackTimeValueMapProducer_*_*' ]
_phase2_tktiming_layer_RecoVertexEventContent = [ 'keep *_offlinePrimaryVertices4DnoPID__*',
'keep *_offlinePrimaryVertices4DnoPIDWithBS__*',
'keep *_tofPID_*_*']
phase2_timing.toModify( RecoVertexAOD,
outputCommands = RecoVertexAOD.outputCommands + _phase2_tktiming_RecoVertexEventContent)
phase2_timing_layer.toModify( RecoVertexAOD,
outputCommands = RecoVertexAOD.outputCommands + _phase2_tktiming_layer_RecoVertexEventContent)
#RECO content
RecoVertexRECO = cms.PSet(
outputCommands = cms.untracked.vstring()
)
RecoVertexRECO.outputCommands.extend(RecoVertexAOD.outputCommands)
#FEVT content
RecoVertexFEVT = cms.PSet(
outputCommands = cms.untracked.vstring()
)
RecoVertexFEVT.outputCommands.extend(RecoVertexRECO.outputCommands)
|
# Script i use to match with Rockyou
# Put RockYou in same folder or change path match
test_pass = input('Enter Password to test: \n')
path = 'rockyou.txt'
rslt = False
print("\nTesting.. {}".format(test_pass))
with open(path, errors="ignore") as fp:
line = fp.readline()
c = 1
while line:
line = fp.readline()
if line.strip() == test_pass:
print('{}: at index {}'.format(line.strip(), c))
rslt = True
break
else:
try:
c += 1
except:
print("ERROR")
if rslt is False:
print("--------------------------------")
print("No matches found!!!")
print("Your password is STRONG")
print(" So tuff - ᕙ(⇀‸↼‶)ᕗ\n")
else:
print("--------------------------------")
print("Seemed it was leaked all along!")
print(" Ah well, gotta run! - ᕕ( ᐛ )ᕗ\n")
input('Press Anykey to exit')
|
class Parent:
def public_method(self):
return 'from Parent.public_method'
def another_public_method(self):
return 'from Parent._private_method'
class Child(Parent):
def public_method(self):
return 'from Child.public_method'
def another_public_method(self):
return 'calling base-class method - ' + Parent.another_public_method(self)
a = Child()
print(a.public_method())
print(a.another_public_method())
class NewStyleParent(object):
def public_method(self):
return 'from NewStyleParent.public_method'
def another_public_method(self):
return 'from NewStyleParent.public_method'
def __mangled_method(self):
return 'from NewStyleParent.mangled_method'
class NewStyleChild(NewStyleParent):
def public_method(self):
super(NewStyleChild, self).public_method()
class AnotherParent(object):
def public_method(self):
return 'from AnotherParent._private_method'
def another_public_method(self):
return 'from AnotherParent._private_method'
def __mangled_method(self):
return 'from AnotherParent.mangled_method'
class AnotherChild(AnotherParent, NewStyleParent):
# In case of multiple inheritance,
def public_method(self):
super(AnotherChild, self).public_method()
def calls_mangled_methods(self):
return super(AnotherChild, self)._AnotherParent__mangled_method() + ' and ' + super(AnotherChild, self)._NewStyleParent__mangled_method()
b = AnotherChild()
print(b.calls_mangled_methods())
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.