"""
    Written by Jonny Hyman, 2020
        www.jonnyhyman.com
        www.github.com/jonnyhyman

    MIT License

This code renders the logistic map and zooms in to show its fractal nature.
There is also infrastructure to plot rulers and labels where each bifurcation
occurs; to hint at the emerging feigenbaum constant 4.669

Code structure is roughly:
    - imports
    - parameters
    - functions
    - runtime stuff
"""

from vispy import app, gloo
import vispy.plot as vp
import vispy.io as io
import numpy as np
import vispy

from vispy.scene.visuals import Text

from pathlib import Path
from time import time

import os

from numba import jit, prange

# --------------------------------------------------------------------------
# --- PARAMETERS

# record frames?
record_project = False

gens = 100
#gens = 1000 # used in final rendering
rates = 5000
#rates = 20000 # used in final rendering

rec_prefix = './frames'
project_name = 'logistic_zoom'

# Adding this in makes the visualization only create bifurcation labels
#project_name += '_labels'

# --- DERIVED PARAMETERS ...

frame_dir = Path(f'{rec_prefix}/{project_name}')

if not frame_dir.exists() and record_project:
    frame_dir.mkdir()

feigens = [
    1.0,        # 1
    3.0,        # 2
    3.4494897,  # 4
    3.5440903,  # 8
    3.5644073,  # 16
    3.5687594,  # 32
    3.5696916,  # 64
    3.5698913,  # 128
    3.569934067807427 # 256 corrected from #3.5699340  # 256
]

feigenys = { # y values of each bifurcation (along our zoom path)
    1  : 0.0,
    2  : .67,
    4  : .85,
    8  : .884,
    16 : .8907,
    32 : .8921,
    64  :.89214,
    128  : .89224,
    256  : .89215,
}

# --------------------------------------------------------------------------
# --- FUNCTIONS

@jit(cache=True, nopython=True)#, parallel=True)
def simulate(num_gens=10, rate_min=0, rate_max=3.99, num_rates=10,
                  num_discard=100, initial_pop=0.5):

    """ create simulation data of bifurcation at various rates.
        performance can improve with parallel = True only at massive scales

        taken from package pynamical by Geoff Boeing
        `https://github.com/gboeing/pynamical`
    """

    pops = np.empty(shape=(num_gens*num_rates, 2), dtype=np.float64)
    rates = np.linspace(rate_min, rate_max, num_rates)

    # for each rate, run the function repeatedly, starting at the initial_pop

    for rate_num in prange(len(rates)):

        rate = rates[rate_num]

        pop = initial_pop

        # first run it num_discard times and ignore the results
        for _ in range(num_discard):
            pop = pop * rate * (1 - pop)

        # now that those gens are discarded, run it num_gens times and keep the results
        for gen_num in range(num_gens):
            row_num = gen_num + num_gens * rate_num
            pops[row_num] = [rate, pop]

            pop = pop * rate * (1 - pop)

    return pops

def feigen_ruler(plt, parent, color, x0, y0, x1, y1, x2=None, y2=None):
    """ add a `ruler` to plot to show distance between Bifurcations """

    serif = 0.1 # serif in percent of vertical difference
    serif = serif * abs(y1-y0)

    verts = np.zeros((6,2))

    verts[0,:] = [x0, y0 + serif]
    verts[1,:] = [x0, y0 - serif]
    verts[2,:] = [x0, y0 + serif*2] # serif/2 dodges text
    # jump x
    verts[3,:] = [x1, y0 + serif*2] # serif/2 dodges text
    verts[4,:] = [x1, y0 + serif]
    verts[5,:] = [x1, y1 - serif]

    ruler = plt.plot(verts, color=color)

    if x2 != None and y2 != None:
        f = x0-x1#(x1-x2)/(x0-x1)

        label = f""#{round(f,5)}"

        t = Text(label, face='Cambria Math', parent=parent, color=color)
        t.font_size = 18
        t.pos = (x1-x0)/2 + x0, y0 + serif
    else:
        t = None

    return {'plt': ruler, 'label': t, 'lims':(x1, x0)}

def feigen_lines(target, parent):
    """ create rulers and labels at each feigenvalue """

    cmap = vispy.color.get_colormap('prism')

    rulers = []

    for f, val in enumerate(feigens):

        if f == 0:
            continue

        c = f / len(feigens)
        c = c**4

        color = cmap[c]
        #color.alpha = (1-f / len(feigens))**0.1

        splits = lambda x: int((2)**(x))

        if f > 1:
            x0 = feigens[f]
            y0 = feigenys[splits(f)]

            x1 = feigens[f-1]
            y1 = feigenys[splits(f-1)]

            x2 = feigens[f-2]
            y2 = feigenys[splits(f-2)]

            # number of decimal places needed to show difference
            d = feigens[f] - feigens[f-1]
            places = (abs(int(np.log10(d))) + 1)

            r = feigen_ruler(target, parent, color, x0, y0, x1, y1, x2, y2)

        else:
            x0 = feigens[f]
            y0 = feigenys[splits(f)]
            places = 1

        label = f"{splits(f)} →"

        t = Text(label, face='Cambria Math',
                    parent=parent, color=color, anchor_x='right')

        t.font_size = 16
        t.pos = x0, y0

        if f > 1:
            r['ptr'] = t
            rulers += [r]

    return rulers

def zoom_plot(target, RATES, ENDS, first=False):

    global gens, rates

    """  ---- CREATE DATA ---- """

    if not first and not 'labels' in project_name:
        start = time()
        print('... Simulating between', RATES, ENDS,'gens, rates', gens, rates)
        pops = simulate(num_gens=gens, num_rates=rates,

                                rate_min=RATES[0], rate_max=RATES[1],

                                num_discard = 1000, initial_pop=0.5)
        print('>>> DONE', round(time()-start,2),'s')

    elif first and 'labels' in project_name:

        mode = 0

        if mode==0:
            start = time()
            print('... Simulating between', RATES, ENDS,'gens, rates', gens, rates)
            pops = simulate(num_gens=gens, num_rates=rates,

                                    rate_min=RATES[0], rate_max=RATES[1],

                                    num_discard = 1000, initial_pop=0.5)
            print('>>> DONE', round(time()-start,2),'s')
        else:
            pops = np.zeros((1,2))

    else:
        pops = None
        pops = np.zeros((1,2))

    """ ---- CREATE PLOT ---- """

    # Bifurcations
    # plot the xy data

    color = vispy.color.ColorArray("black")
    color.alpha = 0.8
    size = 1

    if first:

        line = target[0,0].plot(pops, symbol='o', width=0, edge_width = 0,
                                      face_color=color, edge_color=color,
                                      marker_size=size)
        line.set_gl_state(depth_test=False)

        if 'labels' in project_name:
            rulers = feigen_lines(target[0,0], line.parent)

            return line, rulers
        else:
            return line

    else:

        if pops is not None:
            target.set_data(pops, symbol='o', width=0, edge_width = 0,
                                      face_color=color, edge_color=color,
                                      marker_size=size)
            target.update()

def linear_interp(x, in_min, in_max, out_min, out_max):
    return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min

def smooth(f, start, end):
    f = 0.5*(np.cos(np.pi*(f-1)) + 1) # assumes x between 0-1
    return linear_interp(f, 0,1, start, end)

keyframes = np.array([
    [
                # left
                -0.1,
                # right
                4.0,
                # bottom
                -.1,
                # aspect ratio (w/h)
                4/1.1,
    ],
    [
                # left
                3.56908,
                # right
                3.57056,
                # bottom
                .89206,
                # aspect ratio (w/h)
                4/1.1,
    ]
])

#keyframes = np.flip(keyframes, axis=0) # reverse

class Figure(vp.Fig):
    def __init__(self, *args, **kwargs):

        if 'record' in kwargs:
            self.rec = kwargs['record']
            del kwargs['record']
        else:
            self.rec = False

        super(Figure, self).__init__(*args, **kwargs)
        self.unfreeze()

        self.rec_fps = 24

        if self.rec:
            timer_spf = 'auto'
        else:
            timer_spf = 1 / self.rec_fps

        self.t = app.Timer(timer_spf, connect=self.on_timer, start=True)#, iterations=1)
        self.c_frames = 30 * self.rec_fps # frames per chapter
        self.f_max = self.c_frames * (len(keyframes)-1)
        self.f = 0
        self.on_timer(1)

    def on_key_press(self, event):
        if event.text ==' ':
            self.t.stop() if self.t.running else self.t.start()

        elif event.text ==',':
            self.f -= 2
            self.on_timer(1)

        elif event.text =='.':
            self.on_timer(1)

    def on_draw(self, event):

        # re-alpha the rulers based on zoom level
        rect = self.camera.rect
        rates = [rect.left, rect.right]

        for r, ruler in enumerate(self.rulers):

            b = ruler['lims']
            d = b[1] - b[0]
            a = abs(d) / abs(rates[1] - rates[0])
            a = min(a, 1)
            a = max(a, 0)

            if r < 5:
                peakx = 0.75
            elif r == 5:
                peakx = 0.1
            elif r == 6:
                peakx = 0.01

            a = np.interp(a, [0,peakx,1], [0,1,1])

            if ruler['label'] != None:
                c = ruler['label'].color
                c.alpha = a
                ruler['label'].color = c

            c = ruler['ptr'].color
            c.alpha = a
            ruler['ptr'].color = c

            c = ruler['plt']._line._color
            c.alpha = a
            ruler['plt']._line._color = c

        super(Figure, self).on_draw(event)

    def on_timer(self, event):

        start = time()

        if not hasattr(self, 'plotted'):
            zoom_plot_ret = zoom_plot(self, [0,4], [0,1], first=True)
            if type(zoom_plot_ret) is tuple:
                self.plotted, self.rulers = zoom_plot_ret
            else:
                self.plotted = zoom_plot_ret
                self.rulers = []
            self.camera = self._plot_widgets[0].view.camera

        else:

            C = len(keyframes)
            c = self.f // self.c_frames
            z = (self.f/self.c_frames) % 1
            #print(self.f, z, c, C)

            if c >= C-1:
                if self.rec:
                    self.close()
                self.done()

            else:
                #         0      1     2        3
                # LRBA = left, right, bottom, aspect
                LRBA = smooth(z, keyframes[c], keyframes[c+1])

                left = LRBA[0]
                bottom = LRBA[2]
                width = LRBA[1] - LRBA[0]
                height = width * 1/LRBA[3]

                # left, bottom, width, height
                rect = (left, bottom, width, height)

                self.camera.rect = tuple(rect)

            rect = self.camera.rect
            rates = [rect.left, rect.right]
            ends = [rect.bottom, rect.top]

            zoom_plot(self.plotted, rates, ends)

            if self.rec:
                rec_prefix = self.rec['pre']
                project_name = self.rec['name']

                image = self.render()
                io.write_png(f'{rec_prefix}/{project_name}/{project_name}_{self.f}.png', image)

                ETA = (time() - start) * (self.f_max-self.f) # (time / frame) * frames remaining
                ETA = (ETA / 60) / 60 # seconds to hours
                ETA = np.modf(ETA)
                ETA = int(ETA[1]), int(round(ETA[0]*60))
                ETA = str(ETA[0]) + ":" + str(ETA[1]).zfill(2)

                print(f'>>> FRAME: {project_name}_{self.f}.png, ETA',
                        ETA,',', round(100*self.f/self.f_max,2),'% :',
                        self.f, '/', self.f_max)

            self.f += 1

    def done(self):

        if self.rec:

            rec_prefix = self.rec['pre']
            project_name = self.rec['name']

            convert_cmd = (f"""ffmpeg -f image2 -framerate {self.rec_fps}"""
                               f""" -i {rec_prefix}/{project_name}/{project_name}_%d.png"""
                               f""" -c:v prores_ks -profile:v 3 {project_name}.mov""")

            print('CONVERTING >>>', convert_cmd)

            os.system(convert_cmd)

            dir = (f"./{rec_prefix}/{project_name}")
            filelist = [f for f in os.listdir(dir) if f.endswith(".png") ]
            for f in filelist:
                os.remove(os.path.join(dir, f))

            print("Logistic zoom is completed")
            exit()

if record_project:
    rec_dict = {'pre':rec_prefix, 'name':project_name}
else:
    rec_dict = None

fig = Figure(show=False, title="Log Zoom", size=(2538, 1080),
                record=rec_dict)

if __name__ == '__main__':
    fig.show(run=True)


import os
from setuptools import setup, find_packages

requires = [
    'setuptools',
    'Pillow',
    'ptah >= 0.2.1',
    ]

setup(name='ploud.themegallery',
      version='0.1dev',
      description='ploud theme gallery',
      classifiers=[
          "Programming Language :: Python",
          "Topic :: Internet :: WWW/HTTP",
          "Topic :: Internet :: WWW/HTTP :: WSGI :: Application",
          ],
      author='Nikolay Kim, Enfold Systems Inc',
      author_email='fafhrd91@gmail.com',
      url='',
      keywords='web wsgi ptah',
      packages=find_packages(),
      namespace_packages=['ploud'],
      include_package_data=True,
      zip_safe=False,
      install_requires = requires,
      entry_points = {
          'paste.app_factory': [
              'main = ploud.themegallery.app:main'],
          },
      )


class ProUnit():
	"""
	implements processing unit, which process one pipeline step
	"""

	def __init__(self):

		self._regA = []
		self._regB = []
		self._regP = []
		self._active = False
		self._duration = 1
		self._last = False

	def __str__(self):

		if not self.is_empty():
			regA = list(self._regA)
			regA.reverse()
			regB = list(self._regB)
			regB.reverse()
			regP = list(self._regP)
			regP.reverse()
			return "A: " + " ".join(str(value) for value in regA) + \
				" " + "B: " +  " ".join(str(value) for value in regB) + \
				" " + "P: " +  " ".join(str(value) for value in regP) + \
				" " + str(self._active)
		else:
			return "Empty" + " " + str(self._active)

	def load(self, divident, divider, temp_remainder):
		"""
		loads numbers into processing unit
		"""
		self._regA = list(divident)
		self._regB = list(divider)
		self._regP = list(temp_remainder)

	def reset(self):
		"""
		resets all unit's parameters
		"""
		self._regA = []
		self._regB = []
		self._regP = []
		self._active = False

	def shift(self):
		"""
		performs shift of pair <regP, regA>
		"""
		self._regP.pop()
		self._regP.insert(0, self._regA.pop())

	def subtract(self, minuend, subtrahend):
		"""
		perform subtraction
		"""
		copy_subtrahend = list(subtrahend)
		if len(copy_subtrahend) < len(minuend):
			while len(copy_subtrahend) != len(minuend):
				copy_subtrahend.append(0)

		ones_comp = [(lambda number: 1 if number == 0 else 0)(number)
		 	for number in copy_subtrahend]

		twos_comp = self.add(minuend, ones_comp)
		return self.add(twos_comp, [1])

	def single_digit_add(self, first, second, transfer):
		"""
		accept first and second as binary values and transfer as boolean value
		perform single digit addition, return tuple (result, transfer)
		"""
		value = first + second
		if transfer:
			value += 1

		if value > 2:
				result = 1
				transfer = True
		elif value < 2:
			result = value
			transfer = False
		else:
			result = 0
			transfer = True

		return (result, transfer)

	def add(self, first, second):
		"""
		perform addition
		"""
		copy_first = list(first)
		copy_second = list(second)

		result = []
		transfer = False

		while len(copy_first) > 0 and len(copy_second) > 0:
			temp = self.single_digit_add(copy_first.pop(0), copy_second.pop(0),
				transfer)
			result.append(temp[0])
			transfer = temp[1]

		if len(copy_first) > 0:
			while len(copy_first) > 0:
				temp = self.single_digit_add(copy_first.pop(0), 0, transfer)
				result.append(temp[0])
				transfer = temp[1]
		if len(copy_second) > 0:
			while len(copy_second) > 0:
				temp = self.single_digit_add(0, copy_second.pop(0), transfer)
				result.append(temp[0])
				transfer = temp[1]

		return result

	def is_regP_positive(self):
		"""
		check if regP is positive
		"""
		return True if self._regP[len(self._regP) - 1] == 0 else False

	def perform_step(self):
		"""
		perform one step of non-restoring division
		"""
		if self.is_regP_positive():
			self.shift()
			self._regP = list(self.subtract(self._regP, self._regB))
		else:
			self.shift()
			self._regP = list(self.add(self._regP, self._regB))

		if self.is_regP_positive():
			self._regA.insert(0, 1)
		else:
			self._regA.insert(0, 0)

		if self._last:
			if not self.is_regP_positive():
				self._regP = list(self.add(self._regP, self._regB))

	def get_regP(self):
		return self._regP

	def get_regA(self):
		return self._regA

	def get_regB(self):
		return self._regB

	def is_empty(self):
		return not (len(self._regA) > 0 and len(self._regP) > 0)

	def last(self, value):
		self._last = value

	def get_duration(self):
		return self._duration

	def set_duration(self, value):
		self._duration = value

	def active(self, value):
		self._active = value

	def is_active(self):
		return self._active


# count set bits, the Brian Kernighan way

def count_bit(integer):

    count = 0

    while integer:

        integer &= integer - 1
        count += 1

    return count

n = 12345

print(count_bit(n) == str(bin(n)).count("1"))


import requests
import random

steamApiKey = "YOUR-STEAM-API-KEY"
steamID = "YOUR-STEAM-USER-ID"

#Steam API link formatting for "GetOwnedGames"
slink1 = "https://api.steampowered.com/IPlayerService/GetOwnedGames/v0001/?key="
slink2 = "&steamid=" + steamID + "&include_appinfo=1&format=json"
slink = slink1 + steamApiKey + slink2

#Sent API Get request and save respond to a variable
r = requests.get(slink)

#convert to JSON and save to another variable
steam = r.json()

#JSON output with information about each game owned
print(steam)
#https://developer.valvesoftware.com/wiki/Steam_Web_API#GetOwnedGames_.28v0001.29

#Getting integer value of total games owned
totalGames = str(steam["response"]["game_count"])

#Output total games owned
print(totalGames)

#Some logic for getting a random game from account with over 10 hours playtime
steamGame = ""
steamGames = []

for num,item in enumerate (steam["response"]["games"]):
    num+=1
    if item["playtime_forever"] > 600:
        steamGame = item["name"]
        steamGames.append(steamGame)

steamRec = "".join((random.sample(steamGames, k=1)))

print(steamRec)


import csv

from madress_2023 import constants
from madress_2023.constants import ALL_SPLITS, STANDARDIZED_CSV_HEADER, Split
from madress_2023.csv.transform_csv import transform_csv

def process_raw_csv(split: Split, fold: int = None):

    if fold is None and "2FOLDS" in split.name:
        for _fold in range(2):
            process_raw_csv(split, _fold)
        return

    # Returns a constants.DatasetDir containing information about the dataset.
    dataset = constants.get_dataset(split, fold)
    csv_info = constants.get_csv_info(split, fold)

    # Print split name.
    split_name = str(split).lower().split(".")[1]
    print(f"Processing raw CSVs for split: {split_name}.")

    # Load all CSVs.
    rows = []
    csv_path = csv_info.csv_path

    print(f"Processing raw CSV: {csv_path}")
    rows = transform_csv(
        in_path=csv_path,
        out_feat_dir=dataset.features_dir,
        csv_info=csv_info,
    )

    # Replace header row.
    rows.pop(0)
    rows.insert(0, STANDARDIZED_CSV_HEADER)

    # Write to output CSV.
    with open(dataset.csv_path, mode="w", encoding="utf-8") as f_out:
        csv_writer = csv.writer(f_out)
        csv_writer.writerows(rows)

    print("Finished.")

if __name__ == "__main__":
    for split in ALL_SPLITS:
        process_raw_csv(split)


import cv2, os

class FaceDetector(object):
    def __init__(self, xml_path):
        self.classifier = cv2.CascadeClassifier(xml_path)

    def detect(self, image, biggest_only=True):
        scale_factor = 1.2
        min_neighbors = 5
        min_size = (10, 10)
        faces_coord = self.classifier.detectMultiScale(image,
                                                       scaleFactor=scale_factor,
                                                       minNeighbors=min_neighbors,
                                                       minSize=min_size,
                                                       flags=cv2.CASCADE_SCALE_IMAGE)
        return faces_coord

def cut_faces(image, faces_coord):
    faces = []

    for (x, y, w, h) in faces_coord:
        w_rm = int(0.3 * w / 2)
        faces.append(image[y: y + h, x + w_rm: x + w - w_rm])

    return faces

def resize(images, size=(224, 224)):
    images_norm = []
    for image in images:
        if image.shape < size:
            image_norm = cv2.resize(image, size,
                                    interpolation=cv2.INTER_AREA)
        else:
            image_norm = cv2.resize(image, size,
                                    interpolation=cv2.INTER_CUBIC)
        images_norm.append(image_norm)

    return images_norm

def normalize_faces(image, faces_coord):
    faces = cut_faces(image, faces_coord)
    faces = resize(faces)
    return faces

def get_all_img_paths(path):
    files = []
    for (d, _, filepaths) in os.walk(path):
        files.append('%s/%s' % (d, filepaths[0]))
        # files.extend(['%s/%s' % (d, f) for f in filepaths])
        if len(files) == 200:
            break

    return files

def get_imgs_matrix(folder):
    paths = get_all_img_paths(folder)
    matrices = []
    for path in paths:
        if os.path.splitext(path)[-1] == '.jpg':
            print(path)
            img = cv2.imread(path)
            matrices.append(img)
    return matrices

if __name__ == '__main__':
    images = get_imgs_matrix('./lfw-deepfunneled')
    print(images)
    count = 0
    for image in images:
        detector = FaceDetector("haarcascade_frontalface_default.xml")
        faces_coord = detector.detect(image, True)
        faces = normalize_faces(image, faces_coord)
        for i, face in enumerate(faces):
            cv2.imwrite('faces/not_yang_face/%s.jpeg' % (count), faces[i])
            count += 1


from setuptools import setup, find_packages

long_description = open('README.md').read()

with open('requirements.txt') as f:
    requirements = f.read().splitlines()

version = '0.2.0'

setup(
    name='HuBMAPy',
    version=version,
    url='https://github.com/ccb-hms/HuBMAPy',
    description='A package to query the HuBMAP Human Reference Atlas Ontology',
    long_description=long_description,
    long_description_content_type='text/markdown',
    author='Rafael Goncalves, Center for Computational Biomedicine, Harvard Medical School',
    author_email='rafael_goncalves@hms.harvard.edu',
    license='MIT',
    install_requires=requirements,
    packages=find_packages(),
    package_data={'hubmapy': ['resources/*']},
    include_package_data=True,
    classifiers=[
        'Development Status :: 3 - Alpha',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Programming Language :: Python :: 3',
        'Topic :: Scientific/Engineering',
        'Topic :: Scientific/Engineering :: Bio-Informatics'
    ],
    python_requires=">=3",
)


import tkinter as tk
from threading import *
import random
import time
import ctypes

from host import *

bgC = "#242424"
bgC2 = "#575a61"
fgC = "#f3f3f3"
b = "#09fa9a"

attendanceTime = 10

driverStartFlag = False

def fromRgb(rgb):
    return "#%02x%02x%02x" % rgb

class ColorAnimation(Thread):
    def run(self):
        while(True):
            r = 9
            g = 250
            b = 153
            while (r < 255 or g < 255 or b < 255):
                global canvas
                global root
                global Title1Frame
                canvas.configure(bg=fromRgb((r,g,b)))
                canvas.configure(highlightbackground=fromRgb((r,g,b)))
                root.configure(background=fromRgb((r,g,b)))
                TitleCanvas.configure(bg=fromRgb((r,g,b)))
                TitleCanvas.configure(highlightbackground=fromRgb((r,g,b)))
                r = min(r + 1, 255)
                g = min(g + 1, 255)
                b = min(b + 1, 255)
                time.sleep(0.005)
            while (r > 9 or g > 250 or b > 153):
                canvas.configure(bg=fromRgb((r,g,b)))
                canvas.configure(highlightbackground=fromRgb((r,g,b)))
                root.configure(background=fromRgb((r,g,b)))
                TitleCanvas.configure(bg=fromRgb((r,g,b)))
                TitleCanvas.configure(highlightbackground=fromRgb((r,g,b)))
                r = max(r - 1, 9)
                g = max(g - 1, 250)
                b = max(b - 1, 153)
                time.sleep(0.005)

class Driver(Thread):
    def run(self):
        count = 0
        while(True):
            if (count >= attendanceTime):
                global maxa
                maxa += 1
                attendanceList = take_attendance(webdriver)
                totalStudents.set(str(len(attendanceList)))
                room.updateAttendance(attendanceList)
                updateTable()
                count = 0
            global maxp
            maxp +=1
            handsList = who_participates(webdriver)
            raisedHands.set(len(handsList))
            room.updateParticipation(handsList)
            time.sleep(1)
            count += 1

def updateTable():
    studentTable.delete(0, tk.END)
    for i in range(len(room.students)):
        global maxa
        global maxp
        if (maxa == 0 or maxp == 0):
            studentTable.insert(0, "")
            studentTable.insert(0, "")
            studentTable.insert(0, room.students[i].name)

        else:
            studentTable.insert(0, "")
            studentTable.insert(0, "Participation Score: " + str(int(100 * room.students[i].pscore/maxp)) + "%")
            studentTable.insert(0, "Attendance Percentage: " + str(int( 100 * room.students[i].ascore/maxa)) + "%")
            studentTable.insert(0, room.students[i].name)

def handleInsert():
    table.insert(0, inputVal.get() + " | hands: " + raisedHands.get())

class Student():
    def __init__(self, name):
        #Participation
        self.pscore = 0
        self.ascore = 0
        self.name = name

class Room():
    def __init__(self):
        self.students = []

    def updateParticipation(self, list):
        for i in range(len(list)):
            studentFound = False
            for j in range(len(self.students)):
                if (self.students[j].name == list[i]):
                    studentFound = True
                    self.students[j].pscore = self.students[j].pscore + 1
                    break
            if (studentFound == False):
                self.students.append(Student(list[i]))

    def updateAttendance(self, list):
        for i in range(len(list)):
            studentFound = False
            for j in range(len(self.students)):
                if (self.students[j].name == list[i]):
                    studentFound = True
                    self.students[j].ascore = self.students[j].ascore + 1
                    break
            if (studentFound == False):
                self.students.append(Student(list[i]))

room = Room()

def linkFunc():
    room_link = "https://us04web.zoom.us/wc/join/8343445317"
    headless = False
    global webdriver
    webdriver = launch(room_link, headless)
    driverStartFlag = True

def timeFunc():
    global attendanceTime
    attendanceTime = int(timeInputVal.get())
    print(attendanceTime)

def firstHandFunc():
    call_first(webdriver)
    print("message sent")

def setCCFunc():
    print("not implemented")

def main():
    global maxa
    maxa= 0
    global maxp
    maxp = 0

    linkFunc()

    global root
    root = tk.Tk()
    root.title("Smart Class")
    x = root.winfo_screenwidth()
    y = root.winfo_screenwidth()
    root.geometry('%dx%d' % (x, y))
    root.configure(background=b)
    global canvas
    canvas = tk.Canvas(root, highlightbackground=b, height=1000, width=300, bg=b)
    canvas.pack()

    #Title1Frame
    global TitleCanvas
    Title1Frame = tk.Frame(root, bg=b)
    Title1Frame.place(width=300, height=100, x=x/2-170, y=0)
    TitleCanvas = tk.Canvas(Title1Frame, highlightbackground=b, bg=b, width = 300, height = 100)
    #tk.Label(Title1Frame, text="Smart Class",fg="black", font=("Helvetica", 40)).pack(fill=tk.X)
    TitleCanvas.pack()

    #LinkFrame
    LFrame = tk.Frame(root, bg=bgC)
    LFrame.place(width=300, height=200, x=2, y=110)
    MCLabel = tk.Label(LFrame, text="Enter Meeting Code", fg=fgC, bg=bgC, font=("Helvetica", 13)).pack(pady=5)
    global linkInputVal
    linkInputVal = tk.StringVar()
    LinkInputBox = tk.Entry(LFrame, bg=bgC, width = 18, textvariable = linkInputVal, fg=fgC, font=("Helvetica", 16))
    LinkInputBox.pack(pady=5)
    MPCLabel = tk.Label(LFrame, text="Enter Meeting PassCode", fg=fgC, bg=bgC, font=("Helvetica", 13)).pack(pady=5)
    global passcodeInputVal
    passcodeInputVal = tk.StringVar()
    passcodeInputBox = tk.Entry(LFrame, bg=bgC, width = 18, textvariable = passcodeInputVal, fg=fgC, font=("Helvetica", 16))
    passcodeInputBox.pack(pady=5)
    sethPhoto = tk.PhotoImage(file = "assets/set.png")
    setButton = tk.Button(LFrame, highlightbackground='black', height=30, width=30, image=sethPhoto, command = linkFunc).pack(pady=5)

    #HandRaisedFrame
    global raisedHands
    raisedHands = tk.StringVar()
    HRFrame = tk.Frame(root, bg=bgC)
    HRFrame.place(width=300, height=100, x=2, y=330)
    raisedHands.set(0)
    HRLabel = tk.Label(HRFrame, text="Number of Raised Hands", fg=fgC, bg=bgC, font=("Helvetica", 13)).pack(fill=tk.X, pady=10)
    HRLabelVal = tk.Label(HRFrame, textvariable=raisedHands, fg=fgC, bg=bgC, font=("Helvetica", 30)).pack(fill=tk.X)

    #StudentsFrame
    global totalStudents
    totalStudents = tk.StringVar()
    totalStudents.set(0)
    SFrame = tk.Frame(root, bg=bgC)
    SFrame.place(width=300, height=575, x=x-302, y=110)
    SLabel = tk.Label(SFrame, text="Students Present", fg=fgC, bg=bgC, font=("Helvetica", 15)).pack(fill=tk.X, pady=10)
    SLabelVal = tk.Label(SFrame, textvariable=totalStudents, fg=fgC, bg=bgC, font=("Helvetica", 30)).pack(fill=tk.X)
    SALabel = tk.Label(SFrame, text="Take Attendance", fg=fgC, bg=bgC, font=("Helvetica", 10)).pack(fill=tk.X, pady=5)
    global attendanceTime
    attendanceTime = 10
    setPhoto = tk.PhotoImage(file = "assets/set.png")
    setButton = tk.Button(SFrame, highlightbackground='black', height=30, width=30, image=setPhoto).pack()
    global studentTable
    studentTable = tk.Listbox(SFrame, borderwidth=0, fg=fgC, bg=bgC2, font=("Helvetica", 10), height=y-600)
    studentTable.pack(fill=tk.X, padx=10, pady=10)

    #CCFrame
    CCFrame = tk.Frame(root, bg=bgC)
    CCFrame.place(width=300, height=100, x=2, y=460)
    CCLabel = tk.Label(CCFrame, text="Closed Captioning", fg=fgC, bg=bgC, font=("Helvetica", 15)).pack(fill=tk.X, pady=2)
    set2Photo = tk.PhotoImage(file = "assets/set.png")
    setButton = tk.Button(CCFrame, highlightbackground='black', height=30, width=30, image=set2Photo).pack(pady=5)

    FFrame = tk.Frame(root, bg=bgC)
    FFrame.place(width=300, height=100, x=2, y=585)
    FLabel = tk.Label(FFrame, text="Get FeedBack", fg=fgC, bg=bgC, font=("Helvetica", 15)).pack(fill=tk.X, pady=2)
    set1Photo = tk.PhotoImage(file = "assets/set.png")
    setButton = tk.Button(FFrame, highlightbackground='black', height=30, width=30, image=set1Photo).pack(pady=5)

    #Thread
    t1 = Driver()
    t1.start()
    print("driver room started")

    t2 = ColorAnimation()
    t2.start()

    root.mainloop()

if __name__ == '__main__':
    main()


from math import radians, cos, sin, asin, sqrt
from zerver.lib import avatar
from zerver.models import UserProfile, ZgDepartmentAttendance, ZgAttendance, ZgPurchase, JobsPlease, ProjectProgress, \
    ZgLeave, ZgReview, ZgReimburse, ZgWorkNotice, Attachment, ZgCorrectzAccessory
from django.http import JsonResponse
import json
import time
# from apscheduler.schedulers.background import BackgroundScheduler
# from django_apscheduler.jobstores import DjangoJobStore, register_events
from datetime import datetime, timezone, timedelta
# from django_apscheduler.jobstores import register_job
from zerver.tornado.event_queue import send_event

import re

def zg_send_tools(zg_dict):
    event = {'type': 'update_message_flags',
             'operation': 'add',
             'flag': 'starred',
             'messages': [1],
             'all': False}
    for k, v in zg_dict.items():
        event[k] = v
    return event

def nuw_time():
    stockpile_time = datetime.utcnow()
    stockpile_time = stockpile_time.replace(tzinfo=timezone.utc)
    tzutc_8 = timezone(timedelta(hours=8))
    stockpile_time = stockpile_time.astimezone(tzutc_8)
    return stockpile_time

def send_approver_observer(user_profile, obj_id,
                           approval_type, approver_list,
                           observer_list, img_url, event,
                           third, cause):
    """
    发送审批人和抄送人的函数，需要传入：用户，创建的报表id，报表类型，审批列表
    抄送人列表，event，二级标题，三级标题
    """

    type_dict = {'evection': '出差申请', 'leave': '请假申请', 'purchase': '采购申请', 'jobs_please': '工作请示',
                 'project_progress': '工程进度汇报'}
    types = type_dict[approval_type]

    # try:
    if img_url:
        for img in img_url:
            path_id = img.split('user_uploads/')[1]
            if path_id[-1] == ')':
                path_id = img.split('user_uploads/')[1][: -1]
                print(path_id)
            print(path_id)
            attachment = Attachment.objects.filter(path_id=path_id)
            print(attachment)
            ZgCorrectzAccessory.objects.create(correctz_type='leave', table_id=obj_id, attachment=attachment[0])

    if approver_list:
        event['theme'] = user_profile.full_name + '的' + types + '需要您的审批'
        for approver in approver_list:
            ZgReview.objects.create(types=approval_type, user=user_profile, send_user_id=approver, table_id=obj_id,
                                    send_time=nuw_time())
            user = UserProfile.objects.get(id=approver)

            ZgWorkNotice.objects.create(user=user, notice_type='审批', stair=event['theme'], second=cause,
                                        third=third,
                                        send_time=nuw_time(),
                                        table_type=approval_type,
                                        table_id=obj_id)
        event = zg_send_tools(event)
        send_event(event, approver_list)
    if observer_list:
        event['theme'] = user_profile.full_name + '的' + types + '需要您知晓'
        for observer in observer_list:
            ZgReview.objects.create(types=approval_type, user=user_profile, send_user_id=observer, duties='inform',
                                    table_id=obj_id, send_time=nuw_time())

            user = UserProfile.objects.get(id=observer)
            ZgWorkNotice.objects.create(user=user, notice_type='审批', stair=event['theme'], second=cause,
                                        third=third, send_time=nuw_time(),
                                        table_type=approval_type,
                                        table_id=obj_id)
        event = zg_send_tools(event)
        send_event(event, observer_list)

    # except Exception as e:
    #     raise e

def haversine(lon1, lat1, lon2, lat2):  # 经度1，纬度1，经度2，纬度2 （十进制度数）
    """
    Calculate the great circle distance between two points
    on the earth (specified in decimal degrees)
    """
    # 将十进制度数转化为弧度
    lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2])

    # haversine公式
    dlon = lon2 - lon1
    dlat = lat2 - lat1
    a = sin(dlat / 2) ** 2 + cos(lat1) * cos(lat2) * sin(dlon / 2) ** 2
    c = 2 * asin(sqrt(a))
    r = 6371  # 地球平均半径，单位为公里
    return c * r * 1000

def zg_user_data(user_list):
    user_data_list = []
    for user_id in user_list:
        feedback_dict = {}
        user = UserProfile.objects.get(id=user_id)
        feedback_dict['user_avatar'] = avatar.absolute_avatar_url(user.user)
        feedback_dict['user_name'] = user.user.full_name
        user_data_list.append(feedback_dict)
    return user_data_list

def zg_user_info(ids):
    user_obj = UserProfile.objects.filter(id=ids)
    avatars = avatar.absolute_avatar_url(user_obj[0])
    name = user_obj.full_name
    ids = user_obj.id

    return {'avatar': avatars, 'name': name, 'id': ids}

def req_tools(request):
    req = request.body
    if not req:
        return JsonResponse({'errno': 1, 'message': '缺少参数'})
    req = req.decode()
    req = json.loads(req)
    return req

def judge_pc_or_mobile(ua):
    """
    判断访问来源是pc端还是手机端
    :param ua: 访问来源头信息中的User-Agent字段内容
    :return:
    """
    factor = ua
    is_mobile = False
    _long_matches = r'googlebot-mobile|android|avantgo|blackberry|blazer|elaine|hiptop|ip(hone|od)|kindle|midp|mmp' \
                    r'|mobile|o2|opera mini|palm( os)?|pda|plucker|pocket|psp|smartphone|symbian|treo|up\.(browser|link)' \
                    r'|vodafone|wap|windows ce; (iemobile|ppc)|xiino|maemo|fennec'
    _long_matches = re.compile(_long_matches, re.IGNORECASE)
    _short_matches = r'1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)' \
                     r'|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)' \
                     r'|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw' \
                     r'|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8' \
                     r'|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit' \
                     r'|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)' \
                     r'|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji' \
                     r'|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|e\-|e\/|\-[a-w])|libw|lynx' \
                     r'|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(di|rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi' \
                     r'|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)' \
                     r'|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg' \
                     r'|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21' \
                     r'|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-' \
                     r'|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it' \
                     r'|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)' \
                     r'|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)' \
                     r'|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit' \
                     r'|wi(g |nc|nw)|wmlb|wonu|x700|xda(\-|2|g)|yas\-|your|zeto|zte\-'

    _short_matches = re.compile(_short_matches, re.IGNORECASE)

    if _long_matches.search(factor) != None:
        is_mobile = True
    user_agent = factor[0:4]
    if _short_matches.search(user_agent) != None:
        is_mobile = True

    return is_mobile

#
# try:
#     # 实例化调度器
#     schedulers = BackgroundScheduler()
#     # 调度器使用DjangoJobStore()
#     schedulers.add_jobstore(DjangoJobStore(), "default")
#
#
#     # 'cron'方式循环，周一到周五，每天9:30:10执行,id为工作ID作为标记
#     # ('scheduler',"interval", seconds=1)  #用interval方式循环，每一秒执行一次
#     @register_job(schedulers, 'cron', day_of_week='1-5', hour='11', minute='32', id='task_time1')
#     def timing_attendance():
#         users = UserProfile.objects.all()
#         user_list = list()
#         for user in users:
#             user_list.append(ZgAttendance(user_name=user, create_time=nuw_time()))
#         ZgAttendance.objects.bulk_create(user_list)
#         print('定时自动考勤正在运行', '---------' * 15)
#
#
#     @register_job(schedulers, 'cron', day_of_week='1-5', hour='11', minute='03', id='task_time2')
#     def examine_attendance():
#         print('定时自动考勤校正正在运行', '---------' * 15)
#         sign_in_attendances = ZgAttendance.objects.filter(
#             sign_in_explain=None,
#             create_time__year=nuw_time().year,
#             create_time__month=nuw_time().month,
#             create_time__day=nuw_time().day,
#         )
#         sign_in_attendances.update(sign_in_explain='缺卡')
#         sign_off_attendances = ZgAttendance.objects.filter(
#             sign_off_explain=None,
#             create_time__year=nuw_time().year,
#             create_time__month=nuw_time().month,
#             create_time__day=nuw_time().day,
#         )
#         sign_off_attendances.update(sign_off_explain='缺卡')
#
#
#     # 监控任务
#     register_events(schedulers)
#     # 调度器开始
#     schedulers.start()
#
# except Exception as e:
#     print(e)


#!/usr/bin/env python
# -*- coding: utf-8 -*-
__doc__ = """
Part of the MSFC ART-XC analysis package.
This script takes an image file and compute
based on a given event file. \n
Currently calculate on a box with a given RA/DEC range that can be specified.\n
Since Eulerian distance is used instead of angular distance, the boxsize should
be limited to several deg.
"""

import sys
import numpy as np
import astropy.io.fits as fits
from martxclib.martxcfun import *
from astropy import wcs

parser = Parser(description=__doc__,
	epilog="""Chien-Ting Chen <ct.chen@nasa.gov>""",
	formatter_class=argparse.ArgumentDefaultsHelpFormatter)

# disabled for now. - CTC 20190620
# parser.add_argument('-xmlname', type=str, required=False,
# help='name of the telescope instrument specifications, an XML file.\n If not specified, the fov parameter should be specified.').
#

# Required arguments
parser.add_argument('-img', type=str, required=True,
	help='Name of the event file.')

parser.add_argument('-out', type=str, required=True, default='output.fits',
	help='Name of the output file.')

parser.add_argument('-combine', type=bool, required=True, default=True,
	help='Set to 0 would return the poisson background only. Otherwise a image combined with background would be saved.')

parser.add_argument('-nrate', type=float, required=True, default=1e-3,
	help='Noise count rate in count per second per pixel.')

# optional arguments
parser.add_argument('-exptime', type=float, required=False,
	help='Exposure value for calculating the background.')

parser.add_argument('-exp', type=str, required=False,
	help='Name of the exposure map.')

parser.add_argument('-verbose', type=bool, required=False, default=True,
	help='Add a time constraint to the attitude file. Only the periods within the specified time would be considered.')

parser.add_argument('-overwrite', type=bool, required=False, default=True,
	help='Overwrite if set as True.')

args = parser.parse_args()

verbose = args.verbose
vprint = verboseprint(verbose)
vprint(args)

overwrite = args.overwrite

img = args.img
out = args.out
combine = args.combine
exptime = args.exptime
exp = args.exp
nrate = args.nrate

# noise function
def pnoise(exp, nrate=nrate):
	return np.random.poisson(nrate * exp)

# Reade image, some fits files have a blanck primary HDU, check this
ihdu = fits.open(img)
if len(ihdu) == 1:
	imgtab = ihdu[0].data.copy()
else:
	imgtab = ihdu[1].data.copy()

if exp is not None:
	vprint('Use exposuremap')
	ehdu = fits.open(exp)
	if len(ehdu) == 1:
		expmap = ehdu[0].data
	else:
		expmap = ehdu[1].data
	exptime = np.max(expmap)
	# Now draw poisson noise based on expvalue on a pixel-by-pixel basis
	noise = pnoise(expmap)
	# if exposure value is zero, assume no backgrounds.
	inoexp = np.where(expmap == 0)
	noise[inoexp] = 0.
else:
	# if no exp fits file is provided,
	# use image fits file and assume const. exp time.
	vprint('Use exposure time')
	ishape = np.shape(imgtab)
	noise = np.random.poisson(nrate * exptime, size=ishape)

if combine:
	imgtab += noise
else:
	imgtab = noise

if len(ihdu) == 1:
	ihdu[0].data = imgtab
else:
	ihdu[1].data = imgtab

ihdu.writeto(out, overwrite=overwrite)


import logging
import math
import json
from heapq import heappush

from components.disk import Disk
from components.rack import Rack
from policies.policy import Policy
from helpers.common_math import ncr
from .pdl import slec_local_dp_pdl
from .repair import slec_local_dp_repair

class SLEC_LOCAL_DP(Policy):
    #--------------------------------------
    # system state consists of disks state
    #--------------------------------------
    def __init__(self, state):
        super().__init__(state)
        self.affected_spools = {}
        self.sys_failed = False

    def update_disk_state(self, event_type: str, diskId: int):
        disk = self.disks[diskId]
        spool = self.spools[disk.spoolId]
        if event_type == Disk.EVENT_FAIL:
            disk.state = Disk.STATE_FAILED
            self.failed_disks[diskId] = 1
            spool.failed_disks[diskId] = 1
            self.affected_spools[disk.spoolId] = 1
            spool.failed_disks_undetected[diskId] = 1

        if event_type == Disk.EVENT_REPAIR:
            # logging.info("Repair event, updating disk %s to be STATE_NORMAL", diskId)
            disk.state = Disk.STATE_NORMAL
            self.failed_disks.pop(diskId, None)
            spool.failed_disks.pop(diskId, None)
            if len(spool.failed_disks) == 0:
                self.affected_spools.pop(disk.spoolId, None)

    #----------------------------------------------
    def update_disk_priority(self, event_type, diskId):
        disk = self.disks[diskId]
        spool = self.spools[disk.spoolId]

        if event_type == Disk.EVENT_DETECT:
            #-----------------------------------------------------
            # calculate repairTime and update priority for decluster
            #-----------------------------------------------------
            if spool.disk_repair_max_priority > 0:
                for dId in spool.disk_priority_queue[spool.disk_repair_max_priority]:
                    self.pause_disk_repair_time(dId, spool.disk_repair_max_priority)

            spool.disk_repair_max_priority = max(spool.disk_repair_max_priority, disk.priority)
            spool.disk_priority_queue[disk.priority][diskId] = 1
            spool.failed_disks_undetected.pop(diskId, None)

            disk.repair_start_time = self.curr_time
            disk.curr_prio_repair_started = False
            disk.failure_detection_time = 0

            if spool.disk_repair_max_priority > 0:
                for dId in spool.disk_priority_queue[spool.disk_repair_max_priority]:
                    self.resume_repair_time(dId, spool.disk_repair_max_priority, spool)

        if event_type == Disk.EVENT_FAIL:
            if spool.disk_repair_max_priority > 0:
                for dId in spool.disk_priority_queue[spool.disk_repair_max_priority]:
                    self.pause_disk_repair_time(dId, spool.disk_repair_max_priority)

            spool.disk_max_priority += 1
            disk.priority = spool.disk_max_priority

            fail_num = len(spool.failed_disks)
            good_num = self.sys.spool_size - fail_num
            disk.good_num = good_num
            disk.fail_num = fail_num
            self.compute_priority_percents(disk)

            disk.failure_detection_time = self.curr_time + self.sys.detection_time
            # logging.info("disk.failure_detection_time: {}".format(disk.failure_detection_time))

            if spool.disk_repair_max_priority > 0:
                for dId in spool.disk_priority_queue[spool.disk_repair_max_priority]:
                    self.resume_repair_time(dId, spool.disk_repair_max_priority, spool)

            #----------------------------------------------
            if spool.disk_max_priority >= self.sys.num_local_fail_to_report:
                self.sys_failed = True
                sys_survive_prob = 0
                if self.sys.num_local_fail_to_report > self.sys.m:
                    sys_survive_prob = (1-disk.priority_percents[disk.priority])**self.sys.num_chunks_per_disk
                    if sys_survive_prob > 0.1:
                        print("sys_survive_prob is as large as {}.. Please report to Meng!".format(sys_survive_prob))
                if self.sys.collect_fail_reports:
                    fail_report = {'curr_time': self.curr_time, 'disk_infos': [], 'trigger_disk': int(diskId)}
                    for failedDiskId in self.failed_disks:
                        failedDisk = self.disks[failedDiskId]

                        fail_report['disk_infos'].append(
                            {
                            'curr_repair_data_remaining': failedDisk.curr_repair_data_remaining,
                            'diskId': int(failedDiskId),
                            'priority': int(failedDisk.priority),
                            'estimate_repair_time': failedDisk.estimate_repair_time,
                            'repair_start_time': failedDisk.repair_start_time,
                            'failure_detection_time': failedDisk.failure_detection_time,
                            'repair_time': json.dumps(failedDisk.repair_time),
                            'priority_percents': json.dumps(failedDisk.priority_percents),
                            'curr_prio_repair_started': failedDisk.curr_prio_repair_started
                            })
                    # logging.info('new fail report: {}'.format(fail_report))
                    self.sys.fail_reports.append(fail_report)
                return

        if event_type == Disk.EVENT_FASTREBUILD or event_type == Disk.EVENT_REPAIR:
            curr_priority = disk.priority
            assert curr_priority == spool.disk_repair_max_priority, "repair disk priority is not spool disk repair max priority"
            del disk.repair_time[curr_priority]
            del disk.priority_percents[curr_priority]

            spool.disk_priority_queue[curr_priority].pop(diskId, None)
            for dId in spool.disk_priority_queue[curr_priority]:
                self.pause_disk_repair_time(dId, curr_priority)

            disk.priority -= 1
            if disk.priority > 0:
                spool.disk_priority_queue[disk.priority][diskId] = 1

            disk.repair_start_time = self.curr_time
            disk.curr_prio_repair_started = False

            if len(spool.disk_priority_queue[spool.disk_repair_max_priority]) == 0:
                spool.disk_repair_max_priority -= 1
                spool.disk_max_priority -= 1
                for dId in spool.failed_disks_undetected:
                    failedDisk = self.disks[dId]
                    failedDisk.priority -= 1
                    # TODO: improve percents computation. Add priority n+1' percents to 1?

            if spool.disk_repair_max_priority > 0:
                for dId in spool.disk_priority_queue[spool.disk_repair_max_priority]:
                    self.resume_repair_time(dId, spool.disk_repair_max_priority, spool)

    def compute_priority_percents(self, disk):
        good_num = disk.good_num
        fail_num = disk.fail_num
        for i in range(disk.priority):
            priority = i+1
            priority_sets = math.comb(good_num, self.sys.n-priority)*math.comb(fail_num-1, priority-1)
            total_sets = math.comb((good_num+fail_num-1), (self.sys.n-1))
            disk.priority_percents[priority] = float(priority_sets)/total_sets

    def pause_disk_repair_time(self, diskId, priority):
        disk = self.state.disks[diskId]
        repaired_time = self.state.curr_time - disk.repair_start_time
        repaired_percent = repaired_time / disk.repair_time[priority]
        disk.curr_repair_data_remaining = disk.curr_repair_data_remaining * (1 - repaired_percent)

    def resume_repair_time(self, diskId, priority, spool):
        disk = self.disks[diskId]
        if not disk.curr_prio_repair_started:
            priority_percent = disk.priority_percents[priority]
            disk.curr_repair_data_remaining = disk.repair_data * priority_percent
            disk.curr_prio_repair_started = True
        good_num = self.sys.spool_size - len(spool.failed_disks)
        repair_time = disk.curr_repair_data_remaining * (self.sys.k+1) / (self.sys.diskIO * good_num / len(spool.disk_priority_queue[priority]))
        disk.repair_time[priority] = repair_time / 3600 / 24
        disk.repair_start_time = self.state.curr_time
        disk.estimate_repair_time = self.state.curr_time + disk.repair_time[priority]

        # logging.info("repair time: {}".format(disk.repair_time[priority]))

    def check_pdl(self):
        return slec_local_dp_pdl(self)

    def update_repair_events(self, event_type, diskId, repair_queue):
        slec_local_dp_repair(self, repair_queue)
        if event_type == Disk.EVENT_FAIL:
            disk = self.disks[diskId]
            heappush(self.simulation.failure_queue, (disk.failure_detection_time, Disk.EVENT_DETECT, diskId))

    def clean_failures(self):
        for spoolId in self.affected_spools:
            spool = self.spools[spoolId]
            for diskId in spool.failed_disks:
                disk = self.disks[diskId]
                disk.state = Disk.STATE_NORMAL
                disk.priority = 0
                disk.failure_detection_time = 0
                disk.repair_time = {}
                disk.priority_percents = {}
                disk.curr_prio_repair_started = False
            spool.failed_disks.clear()
            spool.failed_disks_undetected.clear()
            spool.disk_repair_max_priority = 0
            spool.disk_max_priority = 0
            for i in range(self.sys.m + 1):
                spool.disk_priority_queue[i + 1].clear()

    def manual_inject_failures(self, fail_report, simulate):
        for disk_info in fail_report['disk_infos']:
            diskId = int(disk_info['diskId'])
            disk = self.sys.disks[diskId]
            disk.state = Disk.STATE_FAILED
            disk.curr_repair_data_remaining = float(disk_info['curr_repair_data_remaining'])
            disk.priority = int(disk_info['priority'])
            disk.estimate_repair_time = float(disk_info['estimate_repair_time'])
            disk.repair_start_time = float(disk_info['repair_start_time'])
            disk.failure_detection_time = float(disk_info['failure_detection_time'])

            repair_time = json.loads(disk_info['repair_time'])
            for key, value in repair_time.items():
                disk.repair_time[int(key)] = float(value)

            priority_percents = json.loads(disk_info['priority_percents'])
            for key, value in priority_percents.items():
                disk.priority_percents[int(key)] = float(value)

            self.failed_disks[diskId] = 1
            spool = self.spools[disk.spoolId]
            spool.failed_disks[diskId] = 1
            self.affected_spools[disk.spoolId] = 1

            spool.disk_max_priority = max(disk.priority, spool.disk_max_priority)

            if disk.failure_detection_time >= simulate.curr_time:
                disk.curr_prio_repair_started = False
                spool.failed_disks_undetected[diskId] = 1
                # logging.info("found undetected disk {} on spool {}".format(diskId, disk.spoolId))
            else:
                disk.curr_prio_repair_started = True
                spool.disk_priority_queue[disk.priority][diskId] = 1
                spool.disk_repair_max_priority = max(disk.priority, spool.disk_repair_max_priority)

        for spoolId in self.affected_spools:
            spool = self.spools[spoolId]
            if spool.disk_repair_max_priority > 0:
                for diskId in spool.disk_priority_queue[spool.disk_repair_max_priority]:
                    disk = self.disks[diskId]
                    if disk.priority > 1:
                        heappush(simulate.repair_queue, (disk.estimate_repair_time, Disk.EVENT_FASTREBUILD, diskId))
                    if disk.priority == 1:
                        heappush(simulate.repair_queue, (disk.estimate_repair_time, Disk.EVENT_REPAIR, diskId))

            for diskId in spool.failed_disks_undetected:
                disk = self.disks[diskId]
                heappush(self.simulation.failure_queue, (disk.failure_detection_time, Disk.EVENT_DETECT, diskId))
        #         logging.info("heappush detection for diskId {}".format(diskId))
        # logging.info("failure queue after manual failure injection: {}".format(self.simulation.failure_queue))


import tkinter as tk
import soundfile as sf
import sounddevice as sd

class Mixer:
    """
    mixer class
    """
    def __init__(self):
        self.root = tk.Tk()
        self.root.title("Matrix Multiplication")
        self.root.geometry("600x200")

        self.fs=44100
        """
        Setting sampling Rate
        """

        self.track_0_name="vettah-bgm_0.wav"
        self.track_1_name="vocal.wav"               # These are the  audio files for mixing
        self.track_2_name="bg_0.wav"

        y, fs = sf.read(self.track_0_name, dtype='float32')
        self.track_0_audio=y[slice(0,5*fs,1)]           ## Converting to an array

        y, fs = sf.read(self.track_1_name, dtype='float32')
        self.track_1_audio=y[slice(0,5*fs,1)]           ## Converting to an array

        y, fs = sf.read(self.track_2_name, dtype='float32')
        self.track_2_audio=y[slice(0,5*fs,1)]/3                 ## Converting to an array

        # creating string variable in Tkinter

        self.x =0
        self.y =0
        self.z =0

        # First label-scale pair

        self.label_track_0 = tk.Label(self.root, text="Track 0",width=10,font=("Courier",20))
        self.scale_0=tk.Scale(self.root, from_=0, to=10, orient=tk.HORIZONTAL,command=self.Get_x,activebackground='yellow',bd=3,bg='red')
        self.button_0_play = tk.Button(self.root, text="Play",width=10,font=("Courier",10),bd=3,command=self.Play_track_0)

        # Second label-scale pair

        self.label_track_1 = tk.Label(self.root, text="Track 1",width=10,font=("Courier",20))
        self.scale_1 = tk.Scale(self.root, from_=0, to=10, orient=tk.HORIZONTAL,command=self.Get_y,activebackground='yellow',bd=3,bg='green')
        self.button_1_play=tk.Button(self.root,text="Play",width=10,font=("Courier",10),bd=3,command=self.Play_track_1)

        # Third label-scale pair

        self.label_track_2 = tk.Label(self.root, text="Track 2",width=10,font=("Courier",20))
        self.scale_2 = tk.Scale(self.root, from_=0, to=10, orient=tk.HORIZONTAL,command=self.Get_z,activebackground='yellow',bd=3,bg='blue')
        self.button_2_play = tk.Button(self.root, text="Play",width=10,font=("Courier",10),bd=3,command=self.Play_track_2)

        # Packing Widgets in tkinter window

        self.button_mix=tk.Button(self.root,text="Mix",width=15,font=("Courier",15),command=self.Mix)
        self.button_quit=tk.Button(self.root,text="Quit",width=15,font=("Courier",15),command=self.root.quit)

        self.label_track_0.grid(row=0,column=0)
        self.scale_0.grid(row=0,column=1)
        self.button_0_play.grid(row=0,column=2)

        self.label_track_1.grid(row=1, column=0)
        self.scale_1.grid(row=1, column=1)
        self.button_1_play.grid(row=1, column=2)

        self.label_track_2.grid(row=2, column=0)
        self.scale_2.grid(row=2, column=1)
        self.button_2_play.grid(row=2, column=2)

        self.button_mix.grid(row=3,column=1)
        self.button_quit.grid(row=3, column=2)

        self.root.mainloop()        ## calling the main loop

    def Get_x(self,event):      ## Function to reset the X  variable value
        """
        Function to reset the X  variable value
        """
        self.x=self.scale_0.get()
    def Get_y(self,val):        ## Function to reset the Y  variable value
        """
        Function to reset the Y  variable value
        """
        self.y=self.scale_1.get()
    def Get_z(self,event):      ## Function to reset the Z variable value
        """
        Function to reset the Z variable value
        """
        self.z=self.scale_2.get()
    def Play_track_0(self):         ## Function to play the track 0
        """
        Function to play the track 0
        """
        sd.play(self.track_0_audio,self.fs)         ## for playing the respective track
        sd.wait()       ## Disable all other interrupts
    def Play_track_1(self):         ## Function to play the track 1
        """
        Function to play the track 1
        """
        sd.play(self.track_1_audio, self.fs)## for playing the respective track
        sd.wait()           ## Disable all other interrupts
    def Play_track_2(self):     ## Function to play the track 2
        """
        Function to play the track 2
        """
        sd.play(self.track_2_audio, self.fs)## for playing the respective track
        sd.wait()               ## Disable all other interrupts
    def Mix(self):   ## Function to play the linearly combined track
        """
        Function to play the linearly combined track
        """
        sd.play((self.x*self.track_0_audio)+(self.y*self.track_1_audio)+(self.z*self.track_2_audio), self.fs)
        sd.wait()


"""A module for looking for nearby obs. in lat/long and time space.

This module uses a driver function in conjunction with multiprocessing to find
observations in a DataFrame that are within a certain distance and time period
from a given observation. Distance is defined as plus/minus some distance in
lat/long space, and a time interval is given as anything that `datetime.timedelta`
allows (minutes, hours, weeks, days, etc.). It also allows for the opportunity
to ask if these nearby observations are forest-fires or not.

The only function that is meant to be called externally in this module is the
driver function - `gen_nearby_fires_count`. In this function, there is a use
of the kwargs argument in a somewhat non-traditional way. This has to do
with how the `create_inputs.py` module calls this function. To allow for
flexibility in the function calls in the `create_inputs.py` module, a somewhat
non-traditional use of kwargs helped.
"""

import pandas as pd
import numpy as np
import multiprocessing
import time
from itertools import izip
from datetime import timedelta, datetime
from functools import partial

def gen_nearby_fires_count(df, kwargs):
    """Count nearby fires/non-fires in lat/long and time space.

    For each row in the detected fires data set, create a bunch of new columns:

        * One holding the count of nearby detected fires (regardless of whether
          they are labeled as a forest fire), going back 1-7 days
        * One holding the count of nearby detected fires that are labeled as
          forest-fires (fire_bool = True), going back 1-7 days
        * One holding the count of nearby detected fires that are labeled as
          forest-fires (fire_bool = True), going back 1, 2, and 3 years

    Nearby will be denoted by +/- some distance in lat/long space.

    This function will just act as a driver for this entire process, and as
    the function that is meant to be called external from this module. It will
    drive by calling all of the other helper functions in this module. It will
    also multiprocess this across all available cores be default.

    Args:
    ----
        df: Pandas DataFrame
        kwargs: dct
            Holds arguments to use in the function. Here we expect the
            'time_measures' and 'dist_measure' to keywords to be passed in. See
            the module docstring for an explanation of the use of kwargs variable
            here.

    Return:
    ------
        df: Pandas DataFrame
    """

    time_measures = kwargs.pop('time_measures', None)
    dist_measure = kwargs.pop('dist_measure', None)

    if time_measures is None or dist_measure is None:
        raise RuntimeError('Inappropriate arguments passed to gen_nearby_fires_count')

    keep_cols = ['lat', 'long', 'date_fire', 'fire_bool']
    multiprocessing_df = df[keep_cols]
    multiprocessing_df, dt_percentiles_df_dict = \
            _prep_multiprocessing(multiprocessing_df)
    col_lst = ['lat', 'long', 'date_fire', 'date_fire_percentiles']
    lat_idx, long_idx, date_idx, date_pctile_idx = \
            _grab_col_indices(multiprocessing_df, col_lst)

    for time_measure in time_measures:
        pool = multiprocessing.Pool(multiprocessing.cpu_count())
        execute_query = partial(query_for_nearby_fires, dt_percentiles_df_dict,
                                dist_measure, time_measure, lat_idx, long_idx,
                                date_idx, date_pctile_idx)
        nearby_count_dicts = pool.map(execute_query,
                multiprocessing_df.values)
        pool.close()
        df = _merge_results(df, nearby_count_dicts)

    return df

def _prep_multiprocessing(df):
    """Clean up the inputted df and prepare everything for multiprocessing.

    For multiprocessing, the df needs to be as lightweight as possible. This
    means dropping any duplicate observations in terms of lat/long coordinates
    and date. We also don't want to count any duplicate observations like this
    towards the overall count of nearby fires/obs. This is the first step in
    this function.

    The second step involves prepping everything for multiprocessing. The
    quickest/most efficient method found to multiprocess this was the following:

        * Create a percentile column in the DF corresponding to date
        * Create a dictionary lookup for all rows in a corresponding date
          percentile. This allows for smarter, more efficient querying
          (e.g. it's only necessary to query the nearby percentiles, and
          not every one).

    This is a helper function called from `gen_nearby_fires_count`.

    Args:
    ----
        df: Pandas DataFrame

    Return:
    ------
        multiprocessing_df: Pandas DataFrame
            Holds the modified DataFrame, with duplicates dropped and the date
            percentile column added.
        dt_percentiles_df_dict: dct of DataFrames
            Holds the dictionary lookup for all rows in a corresponding date
            percentile. The key corresponds to the date percentile, and the
            value corresponds to a DataFrame of all rows in that date percentile.
    """

    multiprocessing_df = df.drop_duplicates(['lat', 'long', 'date_fire'])
    multiprocessing_df = multiprocessing_df.reset_index(drop=True)
    multiprocessing_df, dt_percentiles_df_dict = \
            _handle_date_percentiles(multiprocessing_df)

    return multiprocessing_df, dt_percentiles_df_dict

def _handle_date_percentiles(df):
    """Add a column of the date percentile and output dictionary lookup.

    For the inputted DataFrame, partition the data into 100 equal-sized
    percentiles by date, and add a column holding what percentile each row is
    in. In addition, output a dictionary that holds 100 key-value pairs, where
    the key is the percentile and the value is a DataFrame holding only the
    observations in that percentile.

    This is a helper function called from `_prep_multiprocessing`, and itself
    calls helper functions `_setup_percentiles_column` and `_setup_pctiles_df_dct`.

    Args:
    ----
        df: Pandas DataFrame

    Return:
    ------
        df: Pandas DataFrame
            Holds the modified DataFrame, with the date percentile column added.
        dt_percentiles_df_dict: dct of DataFrames
            Holds the dictionary lookup for all rows in a corresponding date
            percentile. The key corresponds to the date percentile, and the value
            corresponds to a DataFrame of all rows in that date percentile.
    """

    new_col_name = 'date_fire_percentiles'
    n_quantiles = 100
    df.sort('date_fire', inplace=True)
    df.reset_index(drop=True, inplace=True)
    step_size = df.shape[0] / n_quantiles
    df[new_col_name] = 0

    df = _setup_pctiles_column(df, step_size, n_quantiles, new_col_name)
    dt_percentiles_df_dct = _setup_pctiles_df_dct(df, n_quantiles, new_col_name)

    return df, dt_percentiles_df_dct

def _setup_pctiles_column(df, step_size, n_quantiles, new_col_name):
    """Create the `date_fire_percentiles` column for the df.

    For each row in the dataframe, figure out what percentile of the date column
    it is in, and input that into the 'date_fire_percentiles' column of the
    dataframe.

    This is a helper function called from `_handle_date_percentiles`.

    Args:
    ----
        df: Pandas DataFrame
        step_size: int
            Holds the number of observations to step through by to get to the
            next percentile/bin.
        n_quantiles: int
            Holds the number of percentiles/bins to make.
        new_col_name: str
            Holds the name to give the newly created column.

    Return:
    ------
        df: Pandas DataFrame
    """

    for quantile in xrange(1, n_quantiles + 1):
        beg_idx = (quantile - 1) * step_size
        end_idx = quantile * step_size
        if quantile == n_quantiles:
            df.loc[beg_idx:, new_col_name] = quantile
        else:
            df.loc[beg_idx:end_idx, new_col_name] = quantile

    return df

def _setup_pctiles_df_dct(df, n_quantiles, new_col_name):
    """Create a lookup dictionary for rows of the DataFrame by date percentile.

    Create a dictionary of DataFrames, where the keys are the integers
    corresponding to percentile of the date column an ob. is in, and the values
    are Pandas DataFrames holding all the obs. in that percentile.

    This is a helper function called from `_handle_date_percentiles`.

    Args:
    ----
        df: Pandas DataFrame
        n_quantiles: int
            Holds how many quantiles/bins the date column was broken into.
        new_col_name: str

    Returns:
    -------
        dt_percentiles_df_dict: dct of DataFrames
            Holds the lookup dictionary.
    """

    dt_percentiles_df_dict = {}
    for percentile in xrange(1, n_quantiles + 1):
        query = new_col_name + ' == ' + str(percentile)
        dt_percentiles_df_dict[percentile] = df.query(query)

    return dt_percentiles_df_dict

def _grab_col_indices(df, col_list):
    """Output a tuple of the column indices for the inputted column names.

    This is a helper function called from `gen_nearby_fires_count`. It allows
    the passing of integers to reference the correct "columns" of the numpy
    array passed during multiprocessing.

    Args:
    ----
        df: Pandas DataFrame
        col_list: list of strings
            Holds the column names to grab the indices of.

    Return:
    ------
        tuple
    """

    df_columns = df.columns
    idx_list = [np.where(df_columns == col)[0][0] for col in col_list]

    return tuple(idx_list)

def query_for_nearby_fires(dt_percentiles_df_dict, dist_measure, time_measure,
                        lat_idx, long_idx, date_idx, date_percentile_idx, row):
    """Query the DataFrame for the nearby obs/fires.
    '''
    Input: Dictionary of DataFrames, Float, Integer,
            Integer, Integer, Integer, Integer, Numpy Array
    Output: Dictionary

    For the inputted row, query the dataframe for the number of 'detected fires'
    (i.e. other rows) that are within dist_measure of the inputted row
    (lat/long wise) and within the time_measure of the inputted row (date wise).
    Also query for the number of actual fires (i.e. other rows with
    fire_bool = True) within the dist_measure and time_measure.

    This is a helper function called and multiprocessed from `gen_nearby_fires_count`.

    Args:
    ----
        dt_percentiles_df_dict: dct of DataFrames
            Holds the key-value pairs corresponding to date percentile and rows of
            a DataFrame in that percentile.
        dist_measure: float
            Holds how far to look in lat/long space for "nearby" obs.
        time_measure: int
            Holds how far back in time to look for "nearby" obs.
        lat_idx: int
            Holds the column index of the latitude value in the inputted row.
        long_idx: int
            Holds the column index of the longitude value in the inputted row.
        date_idx: int
            Holds the column index of the date value in the inputted row.
        date_percentile_idx: int
            Holds the date percentile the inputted row is in.
        row: numpy.ndarray
            Holds all info for the current observation.

    Return:
    ------
        output_dict: dct
            Holds key-value pairs for all of the info. that was queried for.
    """

    # All the indices are passed in so we can grab the right values from the row.
    lat, lng, date = row[lat_idx], row[long_idx], row[date_idx]
    lat_min, lat_max, long_min, long_max = \
            _get_lat_long_range(lat, lng, dist_measure)
    row_dt_percentile = row[date_percentile_idx]

    date_min, date_max = _get_date_range(time_measure, date)

    percentile_df = dt_percentiles_df_dict[row_dt_percentile]
    percentile_date_min = percentile_df['date_fire'].min()
    nearby_fires_count = 0
    all_nearby_count = 0

    all_nearby_query = '''lat >= @lat_min and lat <= @lat_max and long >= @long_min and long <= @long_max and date_fire >= @date_min and date_fire <= @date'''
    # In real time we won't know which rows are actually fires (fire_bool == True)
    # on the day of; we have to wait until after business hours when the fire
    # perimter boundaries are posted.
    nearby_fires_query = '''lat >= @lat_min and lat <= @lat_max and long >= @long_min and long <= @long_max and date_fire >= @date_min and date_fire < @date_max and fire_bool == True'''
    all_nearby_count += percentile_df.query(all_nearby_query).shape[0]
    nearby_fires_count += percentile_df.query(nearby_fires_query).shape[0]

    # If we're doing 1-7 days, we're going to query the date percentile that the
    # given row is in, as well as the above and below. If we're going more days
    # back, it'll be years back, and we'll want to add in all percentiles below
    # (not just the one directly below).
    min_dt_percentile = 1 if time_measure > 7 else max(row_dt_percentile - 1, 1)
    max_dt_percentile = min(100, row_dt_percentile + 1)

    for pctile in range(min_dt_percentile, max_dt_percentile + 1):
        percentile_df = dt_percentiles_df_dict[pctile]
        all_nearby_count += percentile_df.query(all_nearby_query).shape[0]
        nearby_fires_count += percentile_df.query(nearby_fires_query).shape[0]

    all_nearby_count_label = 'all_nearby_count' + str(time_measure)
    nearby_fires_count_label = 'all_nearby_fires' + str(time_measure)
    output_dict = {'lat': lat, 'long': lng, 'date_fire': date,
                    all_nearby_count_label: all_nearby_count,
                    nearby_fires_count_label: nearby_fires_count}

    return output_dict

def _get_lat_long_range(lat, lng, dist_measure):
    """Calculate the min/max. lat/long to look for "nearby" obs in.

    This is a helper function called from `query_for_nearby_fires`.

    Args:
    ----
        lat: float
            Latitude of the ob. to look around.
        lng: float
            Longitude of the ob. to look around.
        dist_measure: float
            Holds how far to look around the ob.

    Return:
    ------
        lat_min: float
        lat_max: float
        long_min: float
        long_max: float
    """

    lat_min, lat_max = lat - dist_measure, lat + dist_measure
    long_min, long_max = lng - dist_measure, lng + dist_measure

    return lat_min, lat_max, long_min, long_max

def _get_date_range(time_measure, dt):
    """Calculate the datetime range to look for "nearby" obs in.

    This is a helper function called from `query_for_nearby_fires`.

    Args:
    ----
        time_measure: int
            Holds how many days to go back in time to look for nearby_fires.
        dt: datetime.datetime
            Holds the date of the current ob.

    Return:
    ------
        date_min: datetime.datetime
        date_max: datetime.datetime
    """

    if time_measure == 0:
        hour, minute, second = dt.hour, dt.minute, dt.second
        date_min = dt - timedelta(hours=hour)
        date_min = date_min - timedelta(minutes=minute)
        date_min = date_min - timedelta(seconds = second)
    else:
        date_min  = dt - timedelta(days=time_measure)

    date_max = datetime(dt.year, dt.month, dt.day, 0, 0, 0)

    return date_min, date_max

def _merge_results(df, nearby_count_dicts):
    """Merge the inputted dictionary of data onto the DataFrame.

    Take in the nearby_count_dict, and merge it into the current df. The
    nearby_count_dict holds the information calcalated in the
    query_for_nearby_fires function for each latitude, longitude, and date combo.

    This is a helper function called from `gen_nearby_fires_count`.

    Args:
    ----
        df: Pandas DataFrame
        nearby_count_dicts: list of dcts

    Return:
    ------
        df: Pandas DataFrame
    """

    nearby_fires_df = pd.DataFrame(nearby_count_dicts)
    nearby_fires_df = nearby_fires_df.drop_duplicates()
    df = pd.merge(df, nearby_fires_df, how='inner', on=['lat', 'long', 'date_fire'])

    return df

def calc_perc_fires(df, time_measures):
    """Calculate the percentage of nearby observations that are actually forest-fires

    Args:
    ----
        df: pandas DataFrame
        time_measures: list of ints
            Holds the list of days back that were used to create columns of
            the counts of nearby observations and nearby forest-fires

    Return:
    ------
        df: Pandas DataFrame
    """

    for time_measure in time_measures:
        new_col_name = 'perc_fires{}'.format(time_measure)
        nearby_count_col = 'all_nearby_count{}'.format(time_measure)
        nearby_fires_count_col = 'all_nearby_fires{}'.format(time_measure)
        df[new_col_name] = df[nearby_fires_count_col] / df[nearby_count_col]

    return df


"""This module contains the library utilities and the bindings
to all the C functions
"""
import ctypes
import logging
import os
import time
from ctypes import c_double
from ctypes import c_int
from ctypes import c_long
from ctypes import c_uint8
from ctypes import c_void_p
from pathlib import Path

import numpy as np

logger = logging.getLogger(__name__)
HERE = Path(__file__).absolute().parent

def load_library(name: str) -> ctypes.CDLL:
    """Load ctypes library. Search in the current
    directory for shared library files

    Parameters
    ----------
    name : str
        Name of shared library

    Returns
    -------
    ctypes.CDLL
        The shared library

    Raises
    ------
    FileNotFoundError
        If it cannot find the library
    """

    try:
        libname = next(f.name for f in HERE.iterdir() if f.name.startswith(name))
    except StopIteration:
        raise FileNotFoundError(f"Could not find shared library for {name}")

    lib = np.ctypeslib.load_library(libname, HERE)

    lib_path = lib._name
    lib_mtime_float = os.path.getmtime(lib_path)
    lib_mtime_struct = time.localtime(lib_mtime_float)
    lib_mtime_str = time.asctime(lib_mtime_struct)
    logger.debug(f"Loading library '{lib_path}' last modified {lib_mtime_str}")
    return lib

lib = load_library("libcost_terms")

uint8_array = np.ctypeslib.ndpointer(dtype=c_uint8, ndim=1, flags="contiguous")
float64_array = np.ctypeslib.ndpointer(dtype=c_double, ndim=1, flags="contiguous")
float64_array_2d = np.ctypeslib.ndpointer(dtype=c_double, ndim=2, flags="contiguous")
float64_array_3d = np.ctypeslib.ndpointer(dtype=c_double, ndim=3, flags="contiguous")

lib.apd.argtypes = [float64_array, float64_array, c_int, c_int, float64_array]
lib.apd.restype = c_double

lib.apd_up_xy.argtypes = [
    float64_array,
    float64_array,
    c_int,
    c_int,
    c_int,
    float64_array,
]
lib.apd_up_xy.restype = c_double

lib.cost_terms_trace.argtypes = [float64_array, float64_array, float64_array, c_int]
lib.cost_terms_trace.restype = None

lib.get_num_cost_terms.argtypes = []
lib.get_num_cost_terms.restype = c_int

lib.full_cost_terms.argtypes = [
    float64_array,
    float64_array,
    float64_array,
    float64_array,
    c_int,
]
lib.full_cost_terms.restype = None

lib.all_cost_terms.argtypes = [
    float64_array_2d,
    float64_array_3d,
    float64_array,
    uint8_array,
    c_long,
    c_long,
    c_void_p,
]
lib.all_cost_terms.restype = None


class Node:
    def __init__(self, element):
        self.element = element
        self.pointer = None

class LinkedList:
    def __init__(self):
        self.front = None
        self.back = None
        self.length = 0

    def push(self, node):
        #if the first node
        if (self.front == None):
            self.front = node
            self.back = node

        else:
            (self.back).pointer = node
            self.back = node

        self.length += 1

    def pop(self):
        # if the first node
        if (self.front == None):
            print("list is empty")
            return
        else:
            if (self.length == 1):
                result = self.front.element
                self.front = None
                self.back = None
                self.length = 0
                return result
            #traversing list to find the node that points to the last one
            result = self.back
            start = self.front

            while (start.pointer != result):
                start = start.pointer

            self.back = start
            (self.back).pointer = None
            self.length -= 1
            return result.element

    def insert(self, index, node):

        if (index > self.length):
            return

        if (index == 1):
            current_node = self.front
            node.pointer = current_node
            self.front = node

            self.length += 1
            return

        if (index == self.length):
            self.push(node)
            return

        count = 2
        current_node = self.front
        while (count != index):
            current_node = current_node.pointer
            count += 1
        temp = current_node.pointer
        current_node.pointer = node
        node.pointer = temp
        self.length += 1

    def elementAt(self, index):
        if index > self.length:
            return None
        count = 1
        result = self.front
        while (count != index):
            result = result.pointer
            count += 1

        return result.element

    def size(self):
        return self.length

    def printList(self):
        result = ''
        front = self.front
        back = None
        while (front != None):
            result = result + str(front.element)
            front = front.pointer

        return result

four = Node(4)
three = Node(3)
two = Node(2)
one = Node(1)
onev = Node(1)

myList = LinkedList()
print("length: ", myList.length)
print(myList.printList())
myList.push(four)
print("length: ", myList.length)
print(myList.printList())
myList.push(three)
print("length: ", myList.length)
print(myList.printList())
myList.push(two)
print("length: ", myList.length)
print(myList.printList())
myList.push(one)
print("length: ", myList.length)
myList.insert(2, onev)
print("length: ", myList.length)

print(myList.printList())
#myList.insert(1, three) #insert is broken still

print(myList.elementAt(1))
print(myList.elementAt(2))
print(myList.elementAt(3))
print(myList.elementAt(4))
print(myList.elementAt(5))

print(myList.pop())

print(myList.pop())

print(myList.pop())

print(myList.pop())

print(myList.pop())

#print(myList.pop())


#!/usr/bin/env python

'''
Advent of Code 2022 - Day 10: Cathode-Ray Tube (Part 2)
https://adventofcode.com/2022/day/10
'''

import time

SIGNAL_STRENGTHS = {}

def move_register_row(cycle: int, register: int) -> int:
    if cycle == 0:
        return register

    # Move the register to the next row after 40 cycles
    return register + 40 if cycle % 40 == 0 else register

def draw(screen: list, cycle: int, register: int) -> None:
    """Draw a lit pixel if the sprite '#' is visible"""
    if cycle - 1 in range(register - 1, register + 2):
        screen[cycle - 1] = "#"

def main():

    filename = input("What is the input file name? ")

    try:
        with open(filename, "r") as file:

            start = time.time()

            register_x = 1
            cycle = 0
            screen = ['.' for _ in range(240)]

            # Read the program
            for instruction in file:
                instruction = instruction.strip()

                if instruction == "noop":
                    cycle += 1
                    register_x = move_register_row(
                        cycle=cycle - 1, register=register_x)
                    draw(screen=screen, cycle=cycle, register=register_x)
                    continue

                _, value = instruction.split()
                try:
                    value = int(value)
                except TypeError as e:
                    print(e)
                    continue

                # Loop through 2 cycles of the 'addx' instruction
                for i in range(1, 3):
                    cycle += 1
                    register_x = move_register_row(
                        cycle=cycle - 1, register=register_x)
                    draw(screen=screen, cycle=cycle, register=register_x)
                    if i == 2:  # Add the value to the register after the cycle
                        register_x += value

        # Print the screen
        for i in range(1, 241):
            print(screen[i - 1], end='')
            if i % 40 == 0:
                print()
        print()

        end = time.time()
        print(f"Execution time in seconds: {end - start}\n")

    except FileNotFoundError:
        print(f"No such file or directory: '{filename}'")

if __name__ == "__main__":
    main()


# e_x_.py - число со степенью

from WmlEquation_Parser.utils.we import we, doc
from lxml import etree

e = we.run_('e')  # основание
x = we.run_('x')  # степень
e_x = we.e_x_(e, x)
equation = we.equation_(e_x)

xml_equation = etree.fromstring(equation)

p = doc.add_paragraph()
p._element.append(xml_equation)

doc.save('words/e_x_.docx')


import sqlite3
import csv

def initialize(file):
    '''
    Initializes the database for the preset food data table and the internal tables for ingredients and meals.

    :param file: CSV File provided for the preset food data table
    :return: None
    '''
    # Open CSV-File for reading standard food table data
    with open(file) as csvfile:
        reader = csv.reader(csvfile, delimiter=',', quotechar='"')
        lines = [row for row in reader]
        header, body = ', '.join(lines[:1][0]), lines[1:]

    # Removing unsupported characters for sqlite table headers:
    header = header.replace('.', '').replace(' ', '').replace('-', '')
    fdata = sqlite3.connect('database/food_data.db')
    cursor = fdata.cursor()

    # Create preset food data table, if not created
    try:
        cursor.execute(f'CREATE TABLE fooddata(ID INTEGER PRIMARY KEY,{header})')
    except sqlite3.OperationalError:
        pass

    # Test if table has content, if not fill with data
    cursor.execute('SELECT * FROM fooddata')
    if not cursor.fetchall():
        print('Writing into database...', end='')
        uniqid = 0
        for row in body:
            # Removing quotechars from entries. Example: Goat's cheese
            entry = ', '.join(['\'' + value.replace('\'', '').replace('"', '') + '\'' for value in row])
            cursor.execute(f'INSERT INTO fooddata VALUES({uniqid},{entry})')
            uniqid += 1
            fdata.commit()

        print('done.')

    fdata.close()


from piece import Piece

class Knight(Piece):
    """
    Knight inherits from Piece.
    """

    def __init__(self, color: str, board: object, pos: list):
        """
        When a Knight is initialized, it needs 6 attributes.
        4 of them are defined in the piece parent class,
        and they are shared among all pieces.

        Symbol is another common attribute among pieces.
        It's a quick way for something to get the type of piece it's
        referencing.

        _move_diffs defines the movement options for the Knight.
        """
        super().__init__(color, board, pos)
        self.symbol = "N"
        self._move_diffs = [[1, 2], [2, 1], [2, -1], [1, -2],
                            [-1, -2], [-2, -1], [-2, 1], [-1, 2]]

    def moves(self) -> list:
        """
        This methods gets the possible movement options from
        _move_diffs.
        It then checks if those moves are allowed:
        It checks if the new position is valid (on the board) and
        if the position is empty or contains an enemy piece.
        If so, then it adds that move to an array of possible moves.

        The return value is an array of possible movement locations.
        """
        moves = []
        move_diffs = self._move_diffs
        x, y = self.pos
        for move in move_diffs:
            dx, dy = move
            new_pos = [x+dx, y+dy]
            if (self.board.valid(new_pos)
                    and (self.board.empty(new_pos)
                    or self.board.rows[x+dx, y+dy].color != self.color)):
                moves.append(new_pos)
        return moves


from __future__ import print_function
import os, sys

from libtbx import easy_run
import libtbx.load_env
from libtbx.utils import Sorry

from amber_adaptbx.program_template import ProgramTemplate

amber_dir = libtbx.env.dist_path("amber")

input_str = '''parm %(preamble)s.pdb
trajin %(preamble)s.pdb
hbond avgout %(preamble)s.hbond.dat
go
'''

def get_number_of_residues(hierarchy):
  atoms = hierarchy.select(hierarchy.get_peptide_c_alpha_selection()).atoms()
  return len(atoms)

class Program(ProgramTemplate):

  description = '''
  Enumerate the H-bonds in a model
    - requires hydrogen atoms be present
    - requires AmberTools to be installed
'''
  datatypes = ['phil', 'model']

  master_phil_str = '''

  output
  {
    show_number_of_h_bonds_per_1000 = True
      .type = bool
    list_h_bonds = False
      .type = bool
  }
  '''

  def validate(self):
    pass

  def run(self):
    model = self.data_manager.get_model()
    if not model.has_hd():
      raise Sorry('Model has no hydrogen atoms! Please add H/D and try again.')

    cpptraj_exe = os.path.join(amber_dir,
                               'bin',
                               'cpptraj'
                               )
    preamble = self.data_manager.get_model_names()[0].split('.')[0]
    print('''
    Running cpptraj executable
      %s
    on input
"""
%s
"""
    ''' % ( cpptraj_exe,  input_str % locals()))
    rc = easy_run.go(command=cpptraj_exe,
                     stdin_lines=input_str % locals(),
                     )
    rc.show_stdout()

    print('  Writing H-bonds to %(preamble)s.hbond.dat' % locals())

    f=file('%(preamble)s.hbond.dat' % locals(), 'rb')
    lines = f.read()
    f.close()

    if self.params.output.list_h_bonds:
      print()
      print(lines)

    nr = get_number_of_residues(model.get_hierarchy())

    if self.params.output.show_number_of_h_bonds_per_1000:
      h_bonds = len(lines.splitlines())-1
      atoms = len(model.get_hierarchy().atoms())
      print('_'*80)
      print('''
      Number of H-bonds found : %7d
      Number of atoms         : %7d
      H-bonds per 1000 atoms  : %10.2f
      H-bonds per residues    : %10.2f
      ''' % (h_bonds,
             atoms,
             h_bonds/atoms*1000,
             h_bonds/nr,
             ))


# 576. Out of Boundary Paths
# DP / Recursion with Memoization

# https://leetcode.com/problems/out-of-boundary-paths/solution/

# Recursion with Memoization
# runtime: O(mnN)
class Solution1:
    def findPaths(self, m: int, n: int, maxMove: int, startRow: int, startColumn: int) -> int:
        memo = [[[-1] * (maxMove + 1) for i in range(n)] for j in range(m)]

        def helper(m, n, move, i, j):
            if i == m or j == n or i < 0 or j < 0:
                return 1
            if move == 0:
                return 0
            if memo[i][j][move] >= 0:
                return memo[i][j][move]

            memo[i][j][move] = (helper(m, n, move-1, i-1, j) + helper(m, n, move-1, i+1, j) + helper(m, n, move-1, i, j-1) + helper(m, n, move-1, i, j+1)) % (10 ** 9 + 7)
            return memo[i][j][move]

        return helper(m, n, maxMove, startRow, startColumn)

# DP
# runtime: O(Nmn)
class Solution2:
    def findPaths(self, m: int, n: int, maxMove: int, startRow: int, startColumn: int) -> int:
        M = 10 ** 9 + 7
        dp = [[0] * n for _ in range(m)]
        dp[startRow][startColumn] = 1
        count = 0

        for move in range(maxMove):
            tmp = [[0] * n for _ in range(m)]
            for i in range(m):
                for j in range(n):
                    if i == m-1:
                        count = (count + dp[i][j]) % M
                    if j == n-1:
                        count = (count + dp[i][j]) % M
                    if i == 0:
                        count = (count + dp[i][j]) % M
                    if j == 0:
                        count = (count + dp[i][j]) % M
                    tmp[i][j] = ((dp[i-1][j] if i > 0 else 0) + (dp[i+1][j] if i < m-1 else 0) + (dp[i][j-1] if j > 0 else 0) + (dp[i][j+1] if j < n-1 else 0)) % M
            dp = tmp

        return count


from terminaltables import SingleTable
from vendingmachineworks import print_inventory
from term_io import y_or_n as yes_or_no
from account_manage import account
import term_io
# from press_any_key import press_any_key_to_continue

def cal_att(team):
    if len(team) == 0:
        return [0] * 5
    attribute_table = [[0] * 5] * 6
    # player attrs: HP 0, attack 1, defense 2, speed 3, luck 4
    #^_^ att
    attribute_table[0] = [4, 2, 2, 4, 2]
    # T-T att
    attribute_table[1] = [5, 2, 4, 2, 1]
    #@_@ att
    attribute_table[2] = [3, 5, 3, 1, 2]
    #@.@ att
    attribute_table[3] = [4, 3, 3, 3, 1]
    #*-* att
    attribute_table[4] = [5, 4, 2, 1, 2]
    #:p att
    attribute_table[5] = [1, 2, 1, 5, 5]
    att = [1] * 5
    for i in team:
        i = i - 1
        att = [a * b for a, b in zip(att, attribute_table[i])]
    return att

def print_team(team=[1, 2, 3]):
    if len(team) == 0:
        return
    emoji = ["-", "^_^", "T-T", "@_@", "@.@", "*-*", ":P"]
    newlist = [[emoji[_] for _ in team]]
    # print(newlist)
    table = SingleTable(newlist)
    table.inner_row_border = True
    table.inner_heading_row_border = False
    print(table.table)
    att = cal_att(team)
    att[0] *= 5
    newlist = [["HP", "Attack", "Defense", "Speed", "Luck"]]
    newlist.append(att)
    table = SingleTable(newlist)
    table.inner_row_border = True
    table.inner_heading_row_border = False
    table.title = "Stats"
    print(table.table)

def pick_team(user):
    emoji = ["-", "^_^", "T-T", "@_@", "@.@", "*-*", ":P"]
    team = []
    if sum(user.emoji_you_have[1:]) < 3:
        print("Need at least 3 emojis to form a team.")
        return team
    emoji_list = list(user.emoji_you_have)
    while True:
        print_inventory(emoji, emoji_list)
        #try:
        print("Please choose an emoji to add to your team:")
        choose=term_io.select_menu([
            "    ^_^    ",
            "    T-T    ",
            "    @_@    ",
            "    @.@    ",
            "    *-*    ",
            "     :P    ",
            "  Run Away "])+1
        if 1 <= choose <= 6 and emoji_list[choose] > 0:
            team.append(choose)
            emoji_list[choose] -= 1
        if choose==7:
            team = []
            return team
        #except ValueError:
         #   print("Please key in 1 to 6 to choose an emoji.")
        print("Your current team.")
        print_team(team)
        if len(team) == 3:
            print("You are satisfied with your choices?")
            if yes_or_no():
                return team
            else:
                team = []
                return team

def main():
    print_team()
    user = account("test", "test")
    user.emoji_you_have = [3] * 7
    pick_team(user)

if __name__ == "__main__":
    main()


#!/usr/bin/env python
LICENSE="""
Copyright (C) 2011  Michael Ihde

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
"""

from pycommando.commando import command
import os
import yaml

QUANT_DIR=os.path.expanduser("~/.quant")

@command("config")
def getConfig():
    return CONFIG

class _Config(object):
    __CONFIG_FILE = os.path.join(QUANT_DIR, "quant.cfg")
    __YAML = None

    def __init__(self):
        self.load()

    def has_key(self, index):
        return _Config.__YAML.has_key(index)

    def __getitem__(self, index):
        return _Config.__YAML[index]

    def __str__(self):
        return yaml.dump(_Config.__YAML)

    def load(self):
        try:
            _Config.__YAML = yaml.load(open(_Config.__CONFIG_FILE))
        except IOError:
            pass
        # If a configuration is empty or didn't load, create a sample portfolio
        if _Config.__YAML == None:
            _Config.__YAML = {"portfolios": {"cash": {"$": 10000.0}}}
            self.commit()

    def commit(self):
        f = open(_Config.__CONFIG_FILE, "w")
        f.write(yaml.dump(_Config.__YAML))
        f.close()

# Create a global config singleton object
CONFIG = _Config()