import unittest
import numpy as np
import pandas as pd
import tensorflow as tf
from sklearn.metrics import accuracy_score, precision_score, recall_score
from sklearn.model_selection import train_test_split

class AnomalyDetector(tf.keras.Model):
    def __init__(self):
        super(AnomalyDetector, self).__init__()
        self.encoder = tf.keras.Sequential([
            tf.keras.layers.Dense(32, activation="relu"),
            tf.keras.layers.Dense(16, activation="relu"),
            tf.keras.layers.Dense(8, activation="relu")])

        self.decoder = tf.keras.Sequential([
            tf.keras.layers.Dense(16, activation="relu"),
            tf.keras.layers.Dense(32, activation="relu"),
            tf.keras.layers.Dense(140, activation="sigmoid")])

    def call(self, x):
        encoded = self.encoder(x)
        decoded = self.decoder(encoded)
        return decoded

class TestAnomalyDetector(unittest.TestCase):
    def setUp(self):
        dataframe = pd.read_csv('http://storage.googleapis.com/download.tensorflow.org/data/ecg.csv', header=None)
        raw_data = dataframe.values
        labels = raw_data[:, -1]
        data = raw_data[:, 0:-1]
        train_data, test_data, train_labels, test_labels = train_test_split(
            data, labels, test_size=0.2, random_state=21
        )
        min_val = tf.reduce_min(train_data)
        max_val = tf.reduce_max(train_data)

        train_data = (train_data - min_val) / (max_val - min_val)
        test_data = (test_data - min_val) / (max_val - min_val)

        train_data = tf.cast(train_data, tf.float32)
        test_data = tf.cast(test_data, tf.float32)
        train_labels = train_labels.astype(bool)
        test_labels = test_labels.astype(bool)

        self.normal_train_data = train_data[train_labels]
        self.normal_test_data = test_data[test_labels]

        self.anomalous_train_data = train_data[~train_labels]
        self.anomalous_test_data = test_data[~test_labels]

        self.autoencoder = AnomalyDetector()
        self.autoencoder.compile(optimizer='adam', loss='mae')
        self.autoencoder.fit(self.normal_train_data, self.normal_train_data,
                             epochs=20,
                             batch_size=512,
                             validation_data=(self.normal_test_data, self.normal_test_data),
                             shuffle=True)

    def test_anomaly_detection(self):
        reconstructions = self.autoencoder.predict(self.anomalous_test_data)
        test_loss = tf.keras.losses.mae(reconstructions, self.anomalous_test_data)
        threshold = np.mean(test_loss) + np.std(test_loss)
        preds = tf.math.less(test_loss, threshold)
        binary_preds = preds.numpy().astype(int)
        binary_labels = np.ones_like(binary_preds)

        self.print_stats(binary_preds, binary_labels)

    def print_stats(self, predictions, labels):
        accuracy = accuracy_score(labels, predictions)
        precision = precision_score(labels, predictions)
        recall = recall_score(labels, predictions)
        print(f"Accuracy: {accuracy}")
        print(f"Precision: {precision}")
        print(f"Recall: {recall}")

if __name__ == '__main__':
    unittest.main()


import os
import pandas as pd
import requests
import json
import base64

headers = {
        'format': 'json',
        'app_key': 'https://data.phishtank.com/data/8bf7ccdbfb3eb4ad75996fe1d616efc4406f321cba361844b88402f3ee01c8cd/online-valid.csv',
        }

def get_url_with_ip(URI):
    """Returns url with added URI for request"""
    url = "http://checkurl.phishtank.com/checkurl/"
    new_check_bytes = URI.encode()
    base64_bytes = base64.b64encode(new_check_bytes)
    base64_new_check = base64_bytes.decode('ascii')
    url += base64_new_check
    return url

def send_the_request_to_phish_tank(url, headers):
    """This function sends a request."""
    response = requests.request("POST", url=url, headers=headers)
    return response

start_urls = []
input_urls_directory = os.path.abspath("/home/server/QRcode_Crawler/Image_Crawler/Imagecapture/spiders/test_record.csv")
# Read a URL file
df = pd.read_csv(input_urls_directory, usecols = ["image_urls"], encoding= 'unicode_escape')
start_urls = df["image_urls"].tolist()
for url in start_urls:
    #new_check = 'https://gfdsc.3wz0b62.cn'
    new_check = url
    url = get_url_with_ip(new_check)
    r = send_the_request_to_phish_tank(url, headers)
    print(r.text)


import requests
import json
import datetime
import time

def datetime_to_epoch_milliseconds(dt):
    epoch = datetime.datetime.utcfromtimestamp(0)
    return int((dt - epoch).total_seconds() * 1000.0)

# API endpoint and authorization key
BASE_URL = "https://manifold.markets/api/v0"
AUTH_KEY = ""  # Replace with your key

def create_match_market(teamA, teamB, closeTime=None):
    close_time = datetime_to_epoch_milliseconds(closeTime)

    # Prepare the market data
    data = {
        "outcomeType": "MULTIPLE_CHOICE",
        "question": f"{teamA} vs {teamB} : Premier League 2023-24",
        "answers": [f"{teamA} wins", f"{teamB} wins", "Draw"],
        "closeTime": close_time
    }

    headers = {
        "Content-Type": "application/json",
        "Authorization": f"Key {AUTH_KEY}"
    }

    # Send the request to create the market
    response = requests.post(f"{BASE_URL}/market", headers=headers, data=json.dumps(data))

    return response.json()

if __name__ == "__main__":
    # Dictionary of matches organized by date
    matches_by_date = {
        #September
        datetime.datetime(2023, 9, 24): [("Crystal Palace", "Fulham"), ("Luton", "Wolves"), ("Manchester City", "Nottingham Forest"), ("Brentford", "Everton")],
        datetime.datetime(2023, 9, 25): [("Burnley", "Man United"), ("Arsenal", "Tottenham Spurs"), ("Brighton", "Bournemouth"), ("Chelsea", "Aston Villa"), ("Liverpool", "West Ham"), ("Sheffield United", "Newcastle")],
        datetime.datetime(2023, 9, 30): [("Aston Villa", "Brighton"), ("Bournemouth", "Arsenal"), ("Everton", "Luton"), ("Man United", "Crystal Palace"), ("Newcastle", "Burnley"), ("West Ham", "Sheffield United"), ("Wolves", "Manchester City"), ("Tottenham Spurs", "Liverpool")],

        #October

    }

    for date, matches in matches_by_date.items():
        for match in matches:
            result = create_match_market(match[0], match[1], date)
            print(result)
            time.sleep(3)


def minjumps(tab,n):
 if n<=1:
  return 0
 if tab[0]==0:
  return -1
 maxstep=tab[0]
 step=tab[0]
 jumps=1
 for i in range(1,n):
  if i==n-1:
   return jumps
  maxstep=max(maxstep,tab[i]+i)
  step-=1
  if step==0:
   jumps+=1
   if i>=maxstep:
    return -1
   step=maxstep-i
 return jumps

tab=[2,6,3,5,7,1,8,9]
n=8
print(minjumps(tab,n))


import cv2
import time
import json
from threading import Thread

class Detection:
    def __init__(self, name, feed_queue, motor_queue):
        self.frame_counter = 0

        self.write_to_flask_enabled = True
        self.web_fps = 10
        self.feed_queue = feed_queue
        self.motor_queue = motor_queue

    def write_to_flask(self, image, buffer):
        ret, buffer2 = cv2.imencode('.png', image)

        buffer.put(b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + buffer2.tobytes() + b'\r\n')

    def worker(self):
        capture = cv2.VideoCapture(0)

        # capture.set(3, 640)
        # capture.set(4, 480)
        capture.set(3, 320)
        capture.set(4, 240)

        rc, feedTestSize = capture.read()
        print('Feed shape')
        print(feedTestSize.shape)

        rectangleColor = (0, 165, 255)

        # faceCascade = cv2.CascadeClassifier('/home/pi/HAAR-Remote-Control/camera_presence/haarcascade_frontalface_alt2.xml')
        faceCascade = cv2.CascadeClassifier('./camera_presence/cascade_3.xml')

        while True:
            #Capture next frame
            rc, fullSizeBaseImage = capture.read()

            self.frame_counter += 1

            #Resize the image to 320x240
            baseImage = fullSizeBaseImage

            if (self.frame_counter % 5) == 0:
                gray = cv2.cvtColor(baseImage, cv2.COLOR_BGR2GRAY)

                faces = faceCascade.detectMultiScale(
                    gray,
                    # scaleFactor=1.8,
                    scaleFactor=1.1,
                    minNeighbors=5,
                    minSize=(20, 20),
                    # maxSize=(120, 120),
                )
                # faces = faceCascade.detectMultiScale(gray, 50, 50)

                for (_x,_y,_w,_h) in faces:
                    print('GOT IT!')
                    self.motor_queue.put('stop')
                    self.motor_queue.put('beep')
                    x = int(_x)
                    y = int(_y)
                    w = int(_w)
                    h = int(_h)

                    if self.write_to_flask_enabled:
                        cv2.rectangle(baseImage, (x-10, y-10), (x + w+10 , y + h+10), rectangleColor, 2)

            if self.write_to_flask_enabled and self.frame_counter % self.web_fps:
                self.write_to_flask(baseImage, self.feed_queue)
                # self.write_to_flask(gray, self.feed_queue)

    def run(self):
        t1 = Thread(target=self.worker, daemon=True)
        t1.start()


import pandas as pd

train = pd.read_csv("test.csv")
test = pd.read_csv("train.csv")

train1 = train.iloc[: , [0,1,3,4,17,18,19,20,26,34,36,37,38,43,44,45,46,47,48,49,50,51,52,54,56,59,61,62,66,67,68,69,70,71,75,76,77]].values
test1 = test.iloc[0:1459 , [0,1,3,4,17,18,19,20,26,34,36,37,38,43,44,45,46,47,48,49,50,51,52,54,56,59,61,62,66,67,68,69,70,71,75,76,77]].values
ytrain = test.iloc[0:1459 , 80:81].values

from sklearn.preprocessing import Imputer
imputer = Imputer(missing_values = 'NaN', strategy = 'median', axis = 0)
imputer = imputer.fit(train1[:,:])
train1[:, :] = imputer.transform(train1[:, :])
imputer = imputer.fit(test1[:,:])
test1[:, :] = imputer.transform(test1[:, :])
imputer = imputer.fit(ytrain[:,:])
ytrain[:, :] = imputer.transform(ytrain[:, :])

'''from sklearn.preprocessing import StandardScaler
ss = StandardScaler()
ss = ss.fit(train1[:,:])
train1[:, :] = ss.transform(train1[:, :])
ss = ss.fit(test1[:,:])
test1[:, :] = ss.transform(test1[:, :])
ss = ss.fit(ytrain[:,:])
ytrain[:, :] = ss.transform(ytrain[:, :])'''

ytrain = ytrain.ravel()

from sklearn.tree import DecisionTreeRegressor
dt = DecisionTreeRegressor()
dt.fit(train1 , ytrain)
ypred = dt.predict(test1) #0.64

from sklearn.ensemble import RandomForestRegressor
rt = RandomForestRegressor()
rt.fit(train1 , ytrain)
ypred1 = dt.predict(test1)#0.64

from sklearn.linear_model import LinearRegression
lr = LinearRegression()
lr.fit(train1, ytrain)
ypred2 = lr.predict(test1)#0.55

from sklearn.svm import SVR
sv = SVR(kernel = 'rbf')
sv.fit(train1 , ytrain)
ypred3 = sv.predict(test1)


line='lasfasfssvpavafkaksvmaslflasddfksadfmskbfkgmsakasdvkasdafkafmasdkfsmf'
letters=['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
number_l=[]
a=0
for letter in letters:
    number_l.append(a)

for i in line:
    for letter in letters:
        if i == letter:
            number_l[letters.index(letter)]+=1

print(number_l)
print(letters[number_l.index(max(number_l))])


import numpy as np
import networkx as nx
import matplotlib.pyplot as plt
from networkx.utils import py_random_state
from matplotlib.colors import ListedColormap
import random

def connected_ws_graph(n, k, p, tries=100, seed=1):
    """Returns a connected ws-flex graph.
    """
    for i in range(tries):
        # seed is an RNG so should change sequence each call
        G = ws_graph(n, k, p, seed)
        if nx.is_connected(G):
            return G
    raise nx.NetworkXError('Maximum number of tries exceeded')

def ws_graph(n, k, p, seed=1):
    """Returns a ws-flex graph, k can be real number in [2,n]
    """
    np.random.seed(seed)
    assert k >= 2 and k <= n
    # compute number of edges:
    edge_num = int(round(k * n / 2))
    count = compute_count(edge_num, n)
    # print(count)
    G = nx.Graph()
    for i in range(n):
        source = [i] * count[i]
        target = range(i + 1, i + count[i] + 1)
        target = [node % n for node in target]
        # print(source, target)
        G.add_edges_from(zip(source, target))
    # rewire edges from each node
    nodes = list(G.nodes())
    for i in range(n):
        u = i
        target = range(i + 1, i + count[i] + 1)
        target = [node % n for node in target]
        for v in target:
            if np.random.random() < p:
                w = np.random.choice(nodes)
                # Enforce no self-loops or multiple edges
                while w == u or G.has_edge(u, w):
                    w = random.choice(nodes)
                    if G.degree(u) >= n - 1:
                        break  # skip this rewiring
                else:
                    G.remove_edge(u, v)
                    G.add_edge(u, w)
    return G

def compute_count(channel, group):
    divide = channel // group
    remain = channel % group

    out = np.zeros(group, dtype=int)
    out[:remain] = divide + 1
    out[remain:] = divide
    return out

if __name__ == "__main__":
	print(np.linspace(0,1,300))

	g = connected_ws_graph(120,2,0.1111111111111)
	print(len(g.edges))


import setuptools

with open("README.md", "r") as fh:
    long_description = fh.read()

setuptools.setup(
    name="petsafe_scoopfree",
    version="1.0",
    author="Chris Lennon",
    license="MIT",
    author_email="lennonc@gmail.com",
    description="Provides ability to connect and control a PetSafe Scoopfree device using the PetSafe-Scoopfree API.",
    long_description=long_description,
    long_description_content_type="text/markdown",
    url="https://github.com/crslen/petsafe_scoopfree",
    packages=setuptools.find_packages(),
    install_requires=["requests", "boto3"],
    classifiers=[
        "Programming Language :: Python :: 3",
        "License :: OSI Approved :: MIT License",
        "Operating System :: OS Independent",
    ],
    python_requires=">=3.6",
)


def binary2int(binary):
    int_val, i, n = 0, 0, 0
    while(binary != 0):
        a = binary % 10
        int_val = int_val + a * pow(2, i)
        binary = binary//10
        i += 1
    return int_val

N, M = map(int, input().split())
s = input()
j = 0
k = 0
ans = []
if N % M != 0:
    for i in range(M - N & M):
        s = s + '0'

cnt = int(len(s)/M)
print(cnt)
for i in range(cnt):
    j = i*M
    s_int = int(s[j:j+M])
    s_int = binary2int(s_int)
    k = k ^ s_int

    print(bin(k))

ans = bin(k)
print(ans[2:])


import pkg_resources
from prettytable import PrettyTable
from wishbone.error import InvalidComponent, NoSuchComponent
from wishbone.actor import Actor
from wishbone.function.template import TemplateFunction
from wishbone.function.module import ModuleFunction
from wishbone.protocol import Encode
from wishbone.protocol import Decode

class ComponentManager():

    '''
    Loads Wishbone components and information.

    When initiated it indexes all the Wishbone components found in the
    available ``<namespace>.<component_type>.<category>`` combinations.

    A complete component reference would then be something like:
    ``wishbone.module.process.modify``

    - ``wishbone`` is the namespace
    - ``module`` is the component type
    - ``process`` is the component category
    - ``modify`` is the name of the component

    Note:

        The default Wishbone namespaces are ``wishbone``, for the builtin
        modules and ``wishbone_contrib`` or ``wishbone_external`` for
        externally developed components.

        There exist 3 component types:
            - module
            - function
            - protocol

    Args:

        namespace (list): The list of namespaces to search for <categories>
        module_categories (list): The list of module categories to search
        function_categories (list): The list of function categories to search
    '''

    COMPONENT_TYPES = [
        "protocol",
        "module",
        "function",
    ]

    def __init__(self,
                 namespace=["wishbone", "wishbone_contrib", "wishbone_external"],
                 protocol_categories=["encode", "decode"],
                 module_categories=["flow", "input", "output", "process"],
                 function_categories=["template", "module"],
                 ):
        self.namespace = namespace
        self.component_types = ["protocol", "module", "function"]
        self.protocol_categories = protocol_categories
        self.module_categories = module_categories
        self.function_categories = function_categories

    def exists(self, name):

        '''
        Validates whether the component with <name> exists.

        Args:
            name (str): The complete name of the component.

        Returns:
            bool: True if component exists. False otherwise.
        '''

        if self.getComponentByName(name) is None:
            return False
        else:
            return True

    def getComponent(self, namespace, component_type, category, name):
        '''
        Returns the module with name <namespace>.<component_type>.<category>.<name>

        <namespace>.<component_type>.<category>.<name> must be an entrypoint.

        Args:
            namespace (str): The component namespace
            component_type (str): The component type.
            category (str): The component category.
            name (str): The component name.

        Returns:
            class: A ``wishbone.Actor``, ``wishbone.Function`` based class

        Raises:
            NoSuchComponent: The module does not exist.
            InvalidComponent: There was module found but it was not deemed valid.
        '''

        m = None
        for module in pkg_resources.iter_entry_points("%s.%s.%s" % (namespace, component_type, category)):
            if module.name == name:
                m = module.load()
                break

        if m is None:
            raise NoSuchComponent("Component %s.%s.%s.%s cannot be found." % (namespace, component_type, category, name))
        else:
            if issubclass(m, Actor) or issubclass(m, TemplateFunction) or issubclass(m, ModuleFunction) or issubclass(m, Decode) or issubclass(m, Encode):
                return m
            else:
                raise InvalidComponent("'%s.%s.%s.%s' is not a valid wishbone component." % (namespace, component_type, category, name))

    def getComponentByName(self, name):
        '''
        Returns the module with name ``name``.
        ``name`` should be a valid entrypoint.

        Args:
            name (str): The complete module name.

        Returns:
            class: A `wishbone.Actor` or `wishbone.Function` based class

        Raises:
            NoSuchComponent: The module does not exist.
            InvalidComponent: There was module found but it was not deemed valid.
        '''
        self.validateComponentName(name)
        (namespace, component_type, category, name) = name.split('.')
        return self.getComponent(namespace, component_type, category, name)

    def getComponentList(self):
        '''
        Finds and lists all the components found at the defined
        <namespace>.<module_categories>. combinations.

        Yields:
            tuple: A 4 element tuple: (`namespace`, `component_type`, `category`, `name`)
        '''

        for namespace in self.namespace:
            for category in sorted(self.protocol_categories):
                prefix = "%s.protocol.%s" % (namespace, category)
                for item in [m.name for m in pkg_resources.iter_entry_points(group=prefix)]:
                    yield (namespace, "protocol", category, item)
            for category in sorted(self.function_categories):
                prefix = "%s.function.%s" % (namespace, category)
                for item in [m.name for m in pkg_resources.iter_entry_points(group=prefix)]:
                    yield (namespace, "function", category, item)
            for category in sorted(self.module_categories):
                prefix = "%s.module.%s" % (namespace, category)
                for item in [m.name for m in pkg_resources.iter_entry_points(group=prefix)]:
                    yield (namespace, "module", category, item)

    def getComponentDoc(self, namespace, component_type, category, name):
        '''
        Returns the docstring of module `namespace`.`category`.`group`.`name`

        Args:
            namespace (str): The namespace value.
            component_type (str): The component type.
            category (str): The component type category.
            name (str): The component name name.

        Returns:
            str: The docstring of the module.

        Raises:
            InvalidModule: The docstring does not have the correct format.
        '''

        doc = self.getComponent(namespace, component_type, category, name).__doc__

        if doc is None:
            raise InvalidComponent("Component '%s' does not seem to have the expected docstring format." % ())
        else:
            return doc

    def getComponentTitle(self, namespace, component_type, category, name):
        '''
        Returns the title of the module `category`.`group`.`name` docstring.

        Args:
            namespace (str): The namespace value.
            component_type (str): The component type.
            category (str): The component type category.
            name (str): The component name name.

        Returns:
            str: The docstring/module title

        Raises:
            InvalidModule: The docstring does not have the correct format.
        '''

        doc = self.getComponent(namespace, component_type, category, name).__doc__
        if doc is None:
            return "The component doesn't have a docstring."

        title = doc.strip().split('\n')[0].strip('*')
        if title is None:
            raise InvalidComponent("Component '%s' does not seem to have the expected docstring format." % (name))
        else:
            return title

    def getComponentTable(self):
        '''
        Returns an ascii table of all found Wishbone components.

        Returns:
            str: The ascii table containing all modules.
        '''

        table = self.__getComponentTable()
        namespace_header = None
        component_type_header = None
        category_header = None

        for (namespace, component_type, category, name) in self.getComponentList():

            title = self.getComponentTitle(namespace, component_type, category, name)
            version = self.getComponentVersion(namespace, component_type, category, name)

            if namespace_header == namespace:
                namespace = ""
            else:
                namespace_header = namespace
                component_type_header = None
                category_header = None

            if component_type_header == component_type:
                component_type = ""
            else:
                component_type_header = component_type

            if category_header == category:
                category = ""
            else:
                category_header = category
                table.add_row(["", "", "", "", "", ""])

            table.add_row([namespace, component_type, category, name, version, title])

        table.add_row(["", "", "", "", "", ""])
        return table.get_string()

    def getComponentVersion(self, namespace, component_type, category, name):
        '''
        Returns the version of the module.

        Args:
            namespace (str): The namespace value.
            component_type (str): The component type.
            category (str): The component type category.
            name (str): The component name name.

        Returns:
            str: The version of the module.
        '''

        try:
            for module in pkg_resources.iter_entry_points("%s.%s.%s" % (namespace, component_type, category)):
                if module.name == name:
                    return module.dist.version
        except:
            return "?"

    def validateComponentName(self, name):
        '''
        Validates a component reference name for the proper format.

        Args:
            name (str): The name to validate.

        Returns:
            bool: True when valid.  False when invalid.
        '''

        if len(name.split('.')) != 4:
            raise InvalidComponent("Component name '%s' should consist out of 4 parts." % (name))
        if name.split('.')[1] not in self.COMPONENT_TYPES:
            raise InvalidComponent("Component name '%s' has an invalid component type name." % (name))

        return True

    def __getComponentTable(self):
        '''
        Returns a skeleton ascii module table object
        '''

        t = PrettyTable(["Namespace", "Component type", "Category", "Name", "Version", "Description"])
        t.align["Namespace"] = "l"
        t.align["Component type"] = "l"
        t.align["Category"] = "l"
        t.align["Name"] = "l"
        t.align["Version"] = "r"
        t.align["Description"] = "l"
        return t


# 17413. 단어 뒤집기 2
S = list(input())

i = 0 # 인덱스
start = 0 # 시작지점

while i < len(S):
    if S[i] == '<': # <를 만날 경우
        i += 1
        while S[i] !='>': #닫힌 괄호를 만날 때 까지
            i +=1
        i += 1
    elif '0'<=S[i]<='9' or 'a'<=S[i]<='z':
        start = i
        while i < len(S) and ('0'<=S[i]<='9' or 'a'<=S[i]<='z'):
            i+=1
        tmp = S[start:i]
        tmp.reverse()
        S[start:i] = tmp
    else:
        i+=1
print(''.join(S))


import numpy as np
import pickle as pkl
import networkx as nx
import scipy.sparse as sp
from scipy.sparse.linalg.eigen.arpack import eigsh
import sys
import torch
import torch.nn as nn

def parse_skipgram(fname):
    with open(fname) as f:
        toks = list(f.read().split())
    nb_nodes = int(toks[0])
    nb_features = int(toks[1])
    ret = np.empty((nb_nodes, nb_features))
    it = 2
    for i in range(nb_nodes):
        cur_nd = int(toks[it]) - 1
        it += 1
        for j in range(nb_features):
            cur_ft = float(toks[it])
            ret[cur_nd][j] = cur_ft
            it += 1
    return ret

# Process a (subset of) a TU dataset into standard form
def process_tu(data, nb_nodes):
    nb_graphs = len(data)
    ft_size = data.num_features

    features = np.zeros((nb_graphs, nb_nodes, ft_size))
    adjacency = np.zeros((nb_graphs, nb_nodes, nb_nodes))
    labels = np.zeros(nb_graphs)
    sizes = np.zeros(nb_graphs, dtype=np.int32)
    masks = np.zeros((nb_graphs, nb_nodes))

    for g in range(nb_graphs):
        sizes[g] = data[g].x.shape[0]
        features[g, :sizes[g]] = data[g].x
        labels[g] = data[g].y[0]
        masks[g, :sizes[g]] = 1.0
        e_ind = data[g].edge_index
        coo = sp.coo_matrix((np.ones(e_ind.shape[1]), (e_ind[0, :], e_ind[1, :])), shape=(nb_nodes, nb_nodes))
        adjacency[g] = coo.todense()

    return features, adjacency, labels, sizes, masks

def adj_to_bias(adj, sizes, nhood=1):
    nb_graphs = adj.shape[0]
    mt = np.empty(adj.shape)
    for g in range(nb_graphs):
        mt[g] = np.eye(adj.shape[1])
        for _ in range(nhood):
            mt[g] = np.matmul(mt[g], (adj[g] + np.eye(adj.shape[1])))
        for i in range(sizes[g]):
            for j in range(sizes[g]):
                if mt[g][i][j] > 0.0:
                    mt[g][i][j] = 1.0
    return -1e9 * (1.0 - mt)

###############################################
# This section of code adapted from tkipf/gcn #
###############################################

def parse_index_file(filename):
    """Parse index file."""
    index = []
    for line in open(filename):
        index.append(int(line.strip()))
    return index

def sample_mask(idx, l):
    """Create mask."""
    mask = np.zeros(l)
    mask[idx] = 1
    return np.array(mask, dtype=np.bool)

def sparse_to_tuple(sparse_mx, insert_batch=False):
    """Convert sparse matrix to tuple representation."""
    """Set insert_batch=True if you want to insert a batch dimension."""
    def to_tuple(mx):
        if not sp.isspmatrix_coo(mx):
            mx = mx.tocoo()
        if insert_batch:
            coords = np.vstack((np.zeros(mx.row.shape[0]), mx.row, mx.col)).transpose()
            values = mx.data
            shape = (1,) + mx.shape
        else:
            coords = np.vstack((mx.row, mx.col)).transpose()
            values = mx.data
            shape = mx.shape
        return coords, values, shape

    if isinstance(sparse_mx, list):
        for i in range(len(sparse_mx)):
            sparse_mx[i] = to_tuple(sparse_mx[i])
    else:
        sparse_mx = to_tuple(sparse_mx)

    return sparse_mx

def standardize_data(f, train_mask):
    """Standardize feature matrix and convert to tuple representation"""
    # standardize data
    f = f.todense()
    mu = f[train_mask == True, :].mean(axis=0)
    sigma = f[train_mask == True, :].std(axis=0)
    f = f[:, np.squeeze(np.array(sigma > 0))]
    mu = f[train_mask == True, :].mean(axis=0)
    sigma = f[train_mask == True, :].std(axis=0)
    f = (f - mu) / sigma
    return f

def preprocess_features(features):
    """Row-normalize feature matrix and convert to tuple representation"""
    rowsum = np.array(features.sum(1))
    r_inv = np.power(rowsum, -1).flatten()
    r_inv[np.isinf(r_inv)] = 0.
    r_mat_inv = sp.diags(r_inv)
    features = r_mat_inv.dot(features)
    return features.todense(), sparse_to_tuple(features)

def normalize_adj(adj):
    """Symmetrically normalize adjacency matrix."""
    adj = sp.coo_matrix(adj)
    rowsum = np.array(adj.sum(1))
    d_inv_sqrt = np.power(rowsum, -0.5).flatten()
    d_inv_sqrt[np.isinf(d_inv_sqrt)] = 0.
    d_mat_inv_sqrt = sp.diags(d_inv_sqrt)
    return adj.dot(d_mat_inv_sqrt).transpose().dot(d_mat_inv_sqrt).tocoo()

def preprocess_adj(adj):
    """Preprocessing of adjacency matrix for simple GCN model and conversion to tuple representation."""
    adj_normalized = normalize_adj(adj + sp.eye(adj.shape[0]))
    return sparse_to_tuple(adj_normalized)

def sparse_mx_to_torch_sparse_tensor(sparse_mx):
    """Convert a scipy sparse matrix to a torch sparse tensor."""
    sparse_mx = sparse_mx.tocoo().astype(np.float32)
    indices = torch.from_numpy(
        np.vstack((sparse_mx.row, sparse_mx.col)).astype(np.int64))
    values = torch.from_numpy(sparse_mx.data)
    shape = torch.Size(sparse_mx.shape)
    return torch.sparse.FloatTensor(indices, values, shape)


# -*- coding: utf-8 -*-

from gevent import monkey
from flask import Flask, Response, render_template, request
from socketio import socketio_manage
from socketio.namespace import BaseNamespace
from socketio.mixins import BroadcastMixin
from datetime import datetime, time
import pytz
import random
import threading

monkey.patch_all()

app = Flask(__name__)
app.debug = True
app.config['DEBUG'] = True
app.config['PORT'] = 5000

peoples = ['Andy', 'Gordon', 'Heiley', 'Henry', 'Ho', 'Jan', 'Kelvin', 'Kristin', 'Matt', 'Thomas']
shops = ['Garden', 'Coffee', '新境界', 'Factory 99', '開餐達人', 'Food Court', '爭鮮', 'Drink Tea', 'Shabu SEN']
status = {
    'shop': [{
        'name': shop
    } for shop in shops],
    'people': [{
        'name': people,
        'joined': False,
        'shop': None
    } for people in peoples]
}

game_started = False
tz = pytz.timezone('Asia/Hong_Kong')
timer = None
timer_count = 0
lunch_hour = 13
lunch_min = 45
game_length = 45

def set_interval(interval):
    def decorator(function):
        def wrapper(*args, **kwargs):
            stopped = threading.Event()

            def loop(): # executed in another thread
                while not stopped.wait(interval): # until stopped
                    function(*args, **kwargs)

            t = threading.Thread(target=loop)
            t.daemon = True # stop if the program exits
            t.start()
            return stopped
        return wrapper
    return decorator

@set_interval(1)
def check_time():
    global game_started
    global timer_count

    now = datetime.now(tz)
    lunch_time = tz.localize(datetime(now.year, now.month, now.day, lunch_hour, lunch_min, 0), is_dst=None)
    time_left = int((lunch_time - now).total_seconds())

    if time_left > 0 and time_left < (game_length * 60):
        if game_started != True:
            print("GAME JUST STARTED");
            game_started = True
    else:
        if game_started != False:
            print("GAME JUST STOPED");
            game_started = False

    if timer_count % 30 == 0:
        print(time_left, game_started);
    timer_count = timer_count + 1

timer = check_time()

class HungryNamespace(BaseNamespace, BroadcastMixin):

    def log(self, message):
        now = datetime.now(tz)
        self.logger.info("[%s/%s/%s %s:%s:%s] %s" % (now.year, now.month, now.day, now.hour, now.minute, now.second, message))
        # print "[%s:%s:%s] %s" % (now.hour, now.minute, now.second, message);

    def initialize(self):
        self.logger = app.logger
        self.log("Socketio session started")

    def recv_connect(self):
        self.log("New connection")
        self.session['id'] = None
        self.session['name'] = None
        self.session['shop_id'] = None
        self.session['shop_name'] = None
        self.emit("init", (peoples, shops, [lunch_hour, lunch_min, game_length]))
        self.broadcast_event("status", status)

    def recv_disconnect(self):
        if self.session["id"] != None:
            people_id = self.session['id']
            people_name = peoples[people_id]
            status['people'][people_id]['joined'] = False
            # status['people'][people_id]['shop'] = None
            self.log("%s disconnected" % people_name)
            self.broadcast_event_not_me("status", status)
            self.broadcast_event_not_me("system", "%s disconnected" % people_name)
        else:
            self.log("Client disconnected")

    def broadcast_status(self):
        self.emit("status", status)

    def on_join(self, people_id):
        if game_started == False:
            return "not_started", "The game is not started yet"

        self.log(people_id)
        people_name = peoples[people_id]

        # if select his name, means sign out
        if self.session['id'] == people_id:
            status['people'][people_id]['joined'] = False
            status['people'][people_id]['shop'] = None
            self.broadcast_event("status", status)
            self.session['id'] = None
            self.session['name'] = None
            msg = "%s unjoined" % people_name
            self.log(msg)
            return "unjoin", msg
        elif status['people'][people_id]['joined'] == True:
            # can't select someone that already joined
            # this shouldn't happen becoz checked in frontend
            return "cant_join", "You can't select other user"
        else:
            # change to other user
            if self.session['id'] != None:
                original_name = self.session['name']
                status['people'][self.session['id']]['joined'] = False
                status['people'][self.session['id']]['shop'] = None
                status['people'][people_id]['joined'] = True
                self.broadcast_event("status", status)
                self.session['id'] = people_id
                self.session['name'] = people_name
                self.session['shop_id'] = None
                self.session['shop_name'] = None
                msg = "%s changed to %s" % (original_name, people_name)
                self.log(msg)
                return "change_user", msg
            # new join
            else:
                status['people'][people_id]['joined'] = True
                self.broadcast_event("status", status)
                self.session['id'] = people_id
                self.session['name'] = people_name
                self.session['shop_id'] = None
                self.session['shop_name'] = None
                msg = "%s joined" % people_name
                self.log(msg)
                return "join", msg

    def on_vote(self, shop_id):
        if game_started == False:
            return "not_started", "The game is not started yet"

        # must have joined, then can vote
        if self.session['id'] != None:
            shop_name = shops[shop_id]
            people_id = self.session['id']
            people_name = self.session['name']

            # if vote a shop that already voted, means cancel voting this shop
            if self.session['shop_id'] == shop_id:
                status['people'][people_id]['shop'] = None
                self.broadcast_event("status", status)
                self.session['shop_id'] = None
                self.session['shop_name'] = None
                msg = "%s unvoted %s" % (people_name, shop_name)
                self.log(msg)
                return "unvote", msg
            else:
                status['people'][people_id]['shop'] = shop_id
                self.broadcast_event("status", status)
                self.session['shop_id'] = shop_id
                self.session['shop_name'] = shop_name
                msg = "%s voted %s" % (people_name, shop_name)
                self.log(msg)
                return "vote", msg
        else:
            return "cant_vote", "You must join first"

    def on_addshop(self, shop_name):
        if game_started == False:
            return "not_started", "The game is not started yet"

        people_name = self.session['name']

        # check if new suggested shop is in shops list
        if not shop_name.lower() in (shop.lower() for shop in shops):
            shops.append(shop_name)
            status['shop'].append({'name': shop_name})
            self.broadcast_event("status", status)
            msg = "%s added %s" % (people_name, shop_name)
            self.broadcast_event_not_me("system", msg)
            self.log(msg)
            return "addshop", msg
        else:
            return "cant_addshop", "%s is already in the shops list" % shop_name

@app.route('/dev', methods=['GET'])
def index_dev():
    return render_template('index.html', mode='dev', peoples=peoples, shops=shops)

@app.route('/', methods=['GET'])
def index_prod():
    return render_template('index.html', mode='prod', peoples=peoples, shops=shops)

@app.route('/socket.io/<path:remaining>')
def socketio(remaining):
    try:
        socketio_manage(request.environ, {'/hungry': HungryNamespace}, request)
    except:
        app.logger.error("Exception while handling socketio connection",
                         exc_info=True)
    return Response()


# Polynomial linear regression on synthetic dataset of sin function

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression, Lasso
from sklearn.preprocessing import PolynomialFeatures
from sklearn.metrics.regression import r2_score

# create regression dataset with sin and added noise
np.random.seed(0)
n = 15
x = np.linspace(0,10,n) + np.random.randn(n)/5
y = np.sin(x)+x/6 + np.random.randn(n)/10

X_train, X_test, y_train, y_test = train_test_split(x, y, random_state=0)

plt.figure()
plt.scatter(X_train, y_train, label='training data')
plt.scatter(X_test, y_test, label='test data')
plt.legend(loc=4);

# fit polynomial model with various degrees and test on values 0 to 10
values_to_predict = np.linspace(0,10,100)
i = [0, 1, 2, 3]
deg = [1, 3, 6, 9]
results = np.zeros((4,100))

for i, deg in zip(i, deg):
    poly = PolynomialFeatures(degree=deg)
    X_poly = poly.fit_transform(X_train.reshape(len(X_train),1))
    linreg = LinearRegression().fit(X_poly, y_train)
    results[i,:] = linreg.predict(poly.fit_transform(values_to_predict.reshape(100,1)))

# get R2 scores for train and test for models with degrees 0 to 9
i = np.arange(10)
deg = np.arange(10)
r2_train = np.zeros(10,)
r2_test = np.zeros(10,)

for i, deg in zip(i, deg):
    poly = PolynomialFeatures(degree=deg)
    X_poly_train = poly.fit_transform(X_train.reshape(len(X_train),1))
    X_poly_test = poly.fit_transform(X_test.reshape(len(X_test),1))
    linreg = LinearRegression().fit(X_poly_train, y_train)
    r2_train[i] = r2_score(y_train, linreg.predict(X_poly_train))
    r2_test[i] = r2_score(y_test, linreg.predict(X_poly_test))

# compare between polynomial linear model deg=12 and lasso polynomial model deg=12
poly = PolynomialFeatures(degree=12)
X_poly_train = poly.fit_transform(X_train.reshape(len(X_train),1))
X_poly_test = poly.fit_transform(X_test.reshape(len(X_test),1))

model1 = LinearRegression().fit(X_poly_train, y_train)
model2 = Lasso(alpha=0.01,max_iter=10000).fit(X_poly_train, y_train)

LinearRegression_R2_test_score = r2_score(y_test, model1.predict(X_poly_test))
Lasso_R2_test_score = r2_score(y_test, model2.predict(X_poly_test))


import dlib
import cv2
import matplotlib.pyplot as plt
import math
import numpy as np
from imutils import face_utils
import os
import sys

dirname = os.path.dirname(__file__)
head, tail = os.path.split(dirname)
mediapipe_dir = os.path.join(head, 'Utils/Mediapipe')
utils_dir = os.path.join(head, 'Utils')
my_dlib_dir = os.path.join(head, 'face_detection/model1_Dlib')

sys.path.insert(1, mediapipe_dir)
sys.path.insert(1, utils_dir)
sys.path.insert(1, my_dlib_dir)

from fd_dlib import *

from utils_video import *
from mediapipe_face_landmarks import *

ROLL_LOC = 0
PITCH_LOC = 1
YAW_LOC = 2

detector = FaceMeshDetector(maxFaces=1, staticMode=True)

def plot_mesh_mp(img, show=False, text=True):
    img_copy = img.copy()
    img_copy, faces = detector.findFaceMesh(img_copy)
    return img_copy

def head_pose_mediapipe(img, show=False, text=True):
    ''' from img return (roll, pitch, yaw) of face detected with MEDIAPIPE'''

    if img is not None:
        landmarks_res = detector.getLandmarks(img) # mediapipe landmarks
        if landmarks_res is not None:
            landmarks = landmarks_res[0]
            nose, chin, left_eye, right_eye, left_mouth, right_mouth = getLandmarksHeadPose(img, landmarks)

            landmarks_head_pose = np.array([
                            nose,     # Nose tip
                            chin,   # Chin
                            left_eye,     # Left eye left corner
                            right_eye,     # Right eye right corne
                            left_mouth,     # Left Mouth corner
                            right_mouth    # Right mouth corner
                        ], dtype="double")

            imgpts, modelpts, rotate_degree = face_orientation(img, landmarks_head_pose)

            if(show):
                int_landmarks_head_pose = landmarks_head_pose. astype(int)
                nose = tuple(int_landmarks_head_pose[0])

                show_head_pose(img, nose, imgpts, int_landmarks_head_pose, rotate_degree)

            if(text):
                return rotate_degree
            else:
                rotate_degree_float = [float(el) for el in rotate_degree]
                return rotate_degree_float
        else:
            print("Mediapipe's Landmarks = None")
            return None
    else:
        print("Input img is None")
        return None

def head_pose(img, rect, show=False, text=True):
    ''' from img dlib and rect of face return (roll, pitch, yaw) of face'''

    if img is not None:
        landmarks_dlib = dlib_facial_landmarks(img, rect)

        landmarks_head_pose = landmarks_productions(landmarks_dlib)

        imgpts, modelpts, rotate_degree = face_orientation(img, landmarks_head_pose)

        if(show):
            int_landmarks_head_pose = landmarks_head_pose. astype(int)
            nose = tuple(int_landmarks_head_pose[0])

            show_head_pose(img, nose, imgpts, int_landmarks_head_pose, rotate_degree)

        if(text):
            return rotate_degree
        else:
            rotate_degree_float = [float(el) for el in rotate_degree]
            return rotate_degree_float
    else:
        print("Input img is None")
        return None

def dlib_facial_landmarks(img, rect):
    ''' return facial landmarks of dlib's predictor '''
    predictor = dlib.shape_predictor("path of shape_predictor_68_face_landmarks.dat")
    landmarks = predictor(img, rect)

    return landmarks

def landmarks_productions(landmarks_dlib):
    ''' return the landmarks of interest for the estimation of head pose '''
    landmarks_head_pose = np.array([
                            (landmarks_dlib.part(30).x, landmarks_dlib.part(30).y),     # Nose tip
                            (landmarks_dlib.part(8).x, landmarks_dlib.part(8).y),   # Chin
                            (landmarks_dlib.part(36).x, landmarks_dlib.part(36).y),     # Left eye left corner
                            (landmarks_dlib.part(45).x, landmarks_dlib.part(45).y),     # Right eye right corne
                            (landmarks_dlib.part(48).x, landmarks_dlib.part(48).y),     # Left Mouth corner
                            (landmarks_dlib.part(54).x, landmarks_dlib.part(54).y)    # Right mouth corner
                        ], dtype="double")
    return landmarks_head_pose

def face_orientation(frame, image_points):
    size = frame.shape #(height, width, color_channel)

    model_points = np.array([
                            (0.0, 0.0, 0.0),             # Nose tip
                            (0.0, -330.0, -65.0),        # Chin
                            (-165.0, 170.0, -135.0),     # Left eye left corner
                            (165.0, 170.0, -135.0),      # Right eye right corner
                            (-150.0, -150.0, -125.0),    # Left Mouth corner
                            (150.0, -150.0, -125.0)      # Right mouth corner
                        ])

    # Camera internals

    center = (size[1]/2, size[0]/2)
    focal_length = center[0] / np.tan(60/2 * np.pi / 180)
    camera_matrix = np.array(
                         [[focal_length, 0, center[0]],
                         [0, focal_length, center[1]],
                         [0, 0, 1]], dtype = "double"
                         )

    dist_coeffs = np.zeros((4,1)) # Assuming no lens distortion
    (success, rotation_vector, translation_vector) = cv2.solvePnP(model_points, image_points, camera_matrix, dist_coeffs, flags=cv2.SOLVEPNP_ITERATIVE)

    axis = np.float32([[500,0,0],
                          [0,500,0],
                          [0,0,500]])

    imgpts, jac = cv2.projectPoints(axis, rotation_vector, translation_vector, camera_matrix, dist_coeffs)
    modelpts, jac2 = cv2.projectPoints(model_points, rotation_vector, translation_vector, camera_matrix, dist_coeffs)
    rvec_matrix = cv2.Rodrigues(rotation_vector)[0]

    proj_matrix = np.hstack((rvec_matrix, translation_vector))
    eulerAngles = cv2.decomposeProjectionMatrix(proj_matrix)[6]

    pitch, yaw, roll = [math.radians(_) for _ in eulerAngles]

    pitch = math.degrees(math.asin(math.sin(pitch)))
    roll = -math.degrees(math.asin(math.sin(roll)))
    yaw = math.degrees(math.asin(math.sin(yaw)))

    return imgpts, modelpts, (str(int(roll)), str(int(pitch)), str(int(yaw)))

def show_head_pose(frame, nose, imgpts, landmarks, rotate_degree):
    cv2.line(frame, nose, tuple(imgpts[1].ravel()), (0,255,0), 3) #GREEN
    cv2.line(frame, nose, tuple(imgpts[0].ravel()), (255,0,), 3) #BLUE
    cv2.line(frame, nose, tuple(imgpts[2].ravel()), (0,0,255), 3) #RED

    '''
    remapping = [2,3,0,4,5,1]
    for index in range(len(landmarks)//2):
        random_color = tuple(np.random.random_integers(0,255,size=3))
        print((landmarks[index*2], landmarks[index*2+1]))
        cv2.circle(frame, (landmarks[index*2], landmarks[index*2+1]), 5, random_color, -1)
        cv2.circle(frame,  tuple(modelpts[remapping[index]].ravel().astype(int)), 2, random_color, -1)
    '''
    for j in range(len(rotate_degree)):
        cv2.putText(frame, ('{:05.2f}').format(float(rotate_degree[j])), (10, 30 + (50 * j)), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), thickness=2, lineType=2)

    plt.imshow(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))
    plt.show()

def save_head_pose_img(img, rect, destination, name):
    landmarks_dlib = dlib_facial_landmarks(img, rect)
    for (x, y) in face_utils.shape_to_np(landmarks_dlib):
        cv2.circle(img, (x, y), 1, (0, 0, 255), 2)

    landmarks_head_pose = landmarks_productions(landmarks_dlib)

    imgpts, modelpts, rotate_degree = face_orientation(img, landmarks_head_pose)

    int_landmarks_head_pose = landmarks_head_pose. astype(int)
    nose = tuple(int_landmarks_head_pose[0])

    cv2.putText(img, ('ROLL = {:05.2f}').format(float(rotate_degree[ROLL_LOC])), (10, 460 - (30 * 2)), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 0, 0), thickness=2, lineType=1)
    cv2.putText(img, ('PITCH = {:05.2f}').format(float(rotate_degree[PITCH_LOC])), (10, 460 - (30 * 1)), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 0, 0), thickness=2, lineType=1)
    cv2.putText(img, ('YAW = {:05.2f}').format(float(rotate_degree[YAW_LOC])), (10, 460 - (25 * 0)), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 0, 0), thickness=2, lineType=1)

    cv2.imwrite(destination+'/'+name+'.jpg', img)


#!/usr/bin/env python3.8
import sys
from typing import Tuple

import click
from more_termcolor.colors import italic

from igit.branches import Branches
from igit.commits import Commits
from igit.status import Status
from igit.util import misc
from igit import shell, regex
from igit.util.clickex import unrequired_opt
from igit.util.misc import darkprint, redprint, brightwhiteprint
from igit.search import search_and_prompt

tabchar = '\t'

@click.command(help=f"""Examples:\n
                    {italic(tabchar + 'diff mi-mevi-ma "[^.]*.ts"')}\n
                    {italic(tabchar + 'diff -e "js d.ts *.map"')}
                    """)
@click.argument('items', nargs=-1, required=False)
@unrequired_opt('--exclude', '-e')
def main(items: Tuple[str], exclude):
    # TODO: option to view in web like comparebranch
    exclude_exts = []
    if exclude:
        for ex in map(misc.clean, exclude.split(' ')):
            exclude_exts.append(misc.quote(f':!{ex}'))

    cmd = 'git diff --color-moved=zebra --find-copies-harder --ignore-blank-lines --ignore-cr-at-eol --ignore-space-at-eol --ignore-space-change --ignore-all-space '
    darkprint(f'diff.py main(items): {items}')
    if not items:
        # TODO: exclude
        shell.run(cmd, stdout=sys.stdout)

    btree = Branches()
    ctree = Commits()
    formatted = []
    # if exclude_exts:

    gitignore = None
    status = Status()

    any_sha = False
    diff_files = set()

    for i, item in enumerate(map(misc.clean, items)):
        if regex.SHA_RE.fullmatch(item):
            # e.g. 'f5905f1'
            any_sha = True
            if i > 1:
                redprint(f'SHA1 items, if any, must be placed at the most in the first 2 arg slots')
                return
            if item in ctree:
                if i == 1 and formatted[0] not in ctree:
                    redprint(f'When specifying two SHA1 args, both must belong to the same tree. 0th arg doesnt belong to ctree, 1st does')
                    return
                formatted.append(item)
                continue
            if item in btree:
                if i == 1 and formatted[0] not in btree:
                    redprint(f'When specifying two SHA1 args, both must belong to the same tree. 0th arg doesnt belong to btree, 1st does')
                    return
                formatted.append(item)
                continue
            redprint(f'item is SHA1 but not in commits nor branches. item: {repr(item)}')
            return
        else:
            if any_sha:
                # all SHA items have already been appended, and current item is not a SHA
                numstat_cmd = f'git diff --numstat {" ".join(items[:i])}'
            else:
                # no SHA items at all, this is the first item
                numstat_cmd = f'git diff --numstat'
            filestats = shell.runquiet(numstat_cmd).splitlines()
            diff_files = set(line.rpartition('	')[2] for line in filestats)

        # TODO (continue here):
        #  gpdy SHA SHA REGEX -e REGEX
        #  make -e filter out results

        if item in diff_files:
            with_quotes = misc.quote(item)
            formatted.append(with_quotes)
            darkprint(f'appended: {with_quotes}')
        else:
            brightwhiteprint(f'{item} is not in diff_files, searching within diff_files...')
            choice = search_and_prompt(item, diff_files)
            if choice:
                with_quotes = misc.quote(choice)
                formatted.append(with_quotes)
                darkprint(f'appended: {with_quotes}')

        # file = status.search(item, quiet=False)
        # if not file:
        #     brightyellowprint(f'{item} is not in status, skipping')
        #     continue
        # stripped = misc.unquote(file.strip())
        # formatted.append(misc.quote(stripped))
        # darkprint(f'appended: {repr(stripped)}')

    joined = " ".join(formatted)
    cmd += f'{joined} '
    if exclude_exts:
        cmd += " ".join(exclude_exts)

    shell.run(cmd, stdout=sys.stdout)

if __name__ == '__main__':
    main()


import warnings
from glob import glob
import tensorflow as tf
import os
import nibabel as nb
import numpy as np
from nilearn import image
import pandas as pd

def _get_resize_arg(target_shape):
    mni_shape_mm = np.array([144.0, 174.0, 150.0])
    target_resolution_mm = mni_shape_mm / np.array(target_shape)
    target_affine = np.array([[4., 0., 0., -70.],
                              [0., 4., 0., -103.],
                              [0., 0., 4., -65.],
                              [0., 0., 0., 1.]])
    target_affine[0, 0] = target_resolution_mm[0]
    target_affine[1, 1] = target_resolution_mm[1]
    target_affine[2, 2] = target_resolution_mm[2]
    return target_affine, list(target_shape)

def _get_data(batch_size, src_folder, n_epochs, cache_prefix,
              shuffle, target_shape, balance_dataset=True, nthreads=None):
    if nthreads is None:
        import multiprocessing
        nthreads = multiprocessing.cpu_count()

    in_images = glob(os.path.join(src_folder, "*.nii*"))
    assert len(in_images) != 0

    paths = tf.constant(in_images)
    paths_ds = tf.data.Dataset.from_tensor_slices((paths,))

    target_affine, target_shape = _get_resize_arg(target_shape)

    target_affine_tf = tf.constant(target_affine)
    target_shape_tf = tf.constant(target_shape)

    def _read_and_resample(path, target_affine, target_shape):
        path_str = path.decode('utf-8')
        nii = nb.load(path_str)
        data = nii.get_data()
        data[np.isnan(data)] = 0
        nii = nb.Nifti1Image(data, nii.affine)
        with warnings.catch_warnings():
            warnings.simplefilter("ignore")
            nii = image.resample_img(nii,
                                     target_affine=target_affine,
                                     target_shape=target_shape)
        data = nii.get_data().astype(np.float32)

        return data

    data_ds = paths_ds.map(
        lambda path: tuple(tf.py_func(_read_and_resample,
                                      [path, target_affine_tf,
                                       target_shape_tf],
                                      [tf.float32], name="read_and_resample")),
        num_parallel_calls=nthreads)

    def _reshape_images(data):
        return tf.reshape(data, target_shape)

    data_ds = data_ds.map(_reshape_images, num_parallel_calls=nthreads)

    def _get_label(path):
        path_str = path.decode('utf-8')
        df = pd.read_csv(
            "D:/data/PAC_Data/PAC_Data/PAC2018_Covariates_Upload.csv")
        PAC_ID = path_str.split(os.sep)[-1].split('.')[0]
        label = int(df[df.PAC_ID == PAC_ID]['Label']) - 1
        return label

    labels_ds = paths_ds.map(
        lambda path: tuple(tf.py_func(_get_label,
                                      [path],
                                      [tf.int32], name="get_label")),
        num_parallel_calls=nthreads)

    def _reshape_labels(labels):
        return tf.reshape(labels, [])

    labels_ds = labels_ds.map(_reshape_labels, num_parallel_calls=nthreads)

    dataset = tf.data.Dataset.zip((data_ds, labels_ds))

    # Sanity check uncomment those lines to zero values for one label
    # making the classfication task trivial
    #def _zero(data, label):
    #    return tf.multiply(data, tf.cast(label, tf.float32)), label
    #
    #dataset = dataset.map(_zero)

    if cache_prefix:
        dataset = dataset.cache(cache_prefix)

    if balance_dataset:
        # balance classes
        dataset = dataset.apply(tf.contrib.data.rejection_resample(lambda _, label: label,
                                                                   [0.5, 0.5]))
        # see https://stackoverflow.com/a/47056930/616300
        dataset = dataset.map(lambda _, data: (data))

    dataset = dataset.batch(batch_size)
    if shuffle:
        dataset = dataset.apply(tf.contrib.data.shuffle_and_repeat(buffer_size=100,
                                                                   count=n_epochs))
    else:
        dataset = dataset.repeat(n_epochs)
    return dataset

class InputFnFactory:

    def __init__(self, target_shape, batch_size,
                 n_epochs, train_src_folder,
                 train_cache_prefix, eval_src_folder, eval_cache_prefix):
        self.target_shape = target_shape
        self.batch_size = batch_size
        self.n_epochs = n_epochs
        self.train_src_folder = train_src_folder
        self.train_cache_prefix = train_cache_prefix
        self.eval_src_folder = eval_src_folder
        self.eval_cache_prefix = eval_cache_prefix

    def _get_iterator(self, cache_prefix, src_folder, shuffle, n_epochs,
                      balance_dataset):
        dataset = _get_data(batch_size=self.batch_size,
                            src_folder=src_folder,
                            n_epochs=n_epochs,
                            cache_prefix=cache_prefix,
                            shuffle=shuffle,
                            target_shape=self.target_shape,
                            balance_dataset=balance_dataset)
        # You can use feedable iterators with a variety of different kinds of iterator
        # (such as one-shot and initializable iterators).
        training_iterator = dataset.make_one_shot_iterator()
        return training_iterator.get_next()

    def train_input_fn(self):
        return self._get_iterator(cache_prefix=self.train_cache_prefix,
                                  src_folder=self.train_src_folder,
                                  shuffle=True,
                                  n_epochs=self.n_epochs,
                                  balance_dataset=True)

    def eval_input_fn(self):
        return self._get_iterator(cache_prefix=self.eval_cache_prefix,
                                  src_folder=self.eval_src_folder,
                                  shuffle=False,
                                  n_epochs=1,
                                  balance_dataset=False)


from threading import Lock
from werkzeug.wsgi import pop_path_info, peek_path_info
from werkzeug.wsgi import DispatcherMiddleware
from werkzeug.serving import run_simple
import logging
from logging.handlers import RotatingFileHandler
from venus import create_app
from venus import db as venusdb
from cms import app as cmsapp
from cms import dbs as cmsdb

class SubdomainDispatcher(object):

    def __init__(self, domain, create_app):
        self.domain = domain
        self.create_app = create_app
        self.lock = Lock()
        self.instances = {}

    def get_application(self, host):
        host = host.split(':')[0]
        assert host.endswith(self.domain), 'Configuration error'
        subdomain = host[:-len(self.domain)].rstrip('.')
        with self.lock:
            app = self.instances.get(subdomain)
            if app is None:
                app = self.create_app(subdomain)
                self.instances[subdomain] = app
            return app

    def __call__(self, environ, start_response):
        app = self.get_application(environ['HTTP_HOST'])
        return app(environ, start_response)

class PathDispatcher(object):

    def __init__(self, default_app, create_app):
        self.default_app = default_app
        self.create_app = create_app
        self.lock = Lock()
        self.instances = {}

    def get_application(self, prefix):
        with self.lock:
            app = self.instances.get(prefix)
            if app is None:
                app = self.create_app(prefix)
                if app is not None:
                    self.instances[prefix] = app
            return app

    def __call__(self, environ, start_response):
        app = self.get_application(peek_path_info(environ))
        if app is not None:
            pop_path_info(environ)
        else:
            app = self.default_app
        return app(environ, start_response)

def make_app(prefix):
    if prefix == 'venus':
        return venusapp
    elif prefix == 'cms':
        return cmsapp  #cms_app还不存在,暂时用app来替代
    return None

def init_logger(app, filename):
        file_handler = RotatingFileHandler(filename, 'a', 1 * 1024 * 1024, 10)
        file_handler.setFormatter(logging.Formatter('%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]'))
        app.logger.setLevel(logging.INFO)
        file_handler.setLevel(logging.INFO)
        app.logger.addHandler(file_handler)

if __name__ == '__main__':
    venusapp = create_app('settings_dev.py')
    #venusapp.run(debug=venusapp.config['DEBUG'], host='0.0.0.0',port=80)

    application = PathDispatcher(venusapp, make_app)
    #application = DispatcherMiddleware(app, {'/venus': venusapp, '/cms' : cmsapp});
    run_simple('0.0.0.0', 80, application, use_reloader=True, use_debugger=venusapp.config['DEBUG'])
else :
    venusapp = create_app()
    init_logger(venusapp, '/var/log/venus.log')
    app = DispatcherMiddleware(venusapp, {'/venus': venusapp, '/cms' : cmsapp})


class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None

class Solution:
    def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
        dummyHead = ListNode(-1)
        dummyHead.next = head

        fast = dummyHead
        slow = dummyHead

        while n > 0:
            fast = fast.next
            n -= 1

        while fast != None and fast.next != None:
            fast = fast.next
            slow = slow.next

        slow.next = slow.next.next

        return dummyHead.next

s = Solution()
head = ListNode(1)
head.next = ListNode(2)
head.next.next = ListNode(3)
head.next.next.next = ListNode(4)
head.next.next.next.next = ListNode(5)

head = s.removeNthFromEnd(head, 2)
print(head)


#! /usr/bin/env python3 #
# -*- coding: utf-8 -*- #

## Implementação de Funções - - - - - - - - - - - - - - - - - - - - - #
def minmax(data):
    """
Função que retorna os elementos mínimo e máximo de uma sequência de
um ou mais elementos.

Parâmetros
----------
    data (list): uma sequencia de um ou mais inteiros

Retorno
-------
    tuple: contém o mínimo e o máximo de tuple
    """

    minimo = maximo = data[0]

    for elemento in data:
        if elemento > maximo:
            maximo = elemento

        if elemento < minimo:
            minimo = elemento

    return (minimo, maximo)

def main(args):
    """
Write a short Python function, minmax(data), that takes a sequence of
one or more numbers, and returns the smallest and largets numbers, in
the form of tuple of length two. Do not use built-in functions min or
max in implementing your solution.
    """

    n = int(input("Digite o número de elementos: "))
    sequencia = []

    for i in range(n):
        elemento = int(input("Digite um inteiro: "))
        sequencia.append(elemento)

    minimo, maximo = minmax(sequencia)
    print(f'Máximo: {maximo}\n'
          f'Mínimo: {minimo}')
    return EX_OK

## Executa o script como módulo principal - - - - - - - - - - - - - - #
if __name__ == "__main__":
    import sys
    from os import EX_OK

    codigo_retorno = main(sys.argv)
    sys.exit(codigo_retorno)


import deepeye
import numpy as np

imgFile = open("../samples/eye0.jpg", "rb")
img_data = imgFile.read()
npimg = np.frombuffer(img_data, dtype=np.uint8)
print(npimg)

eyetracker = deepeye.DeepEye("/../models/default.ckpt")
ret_json = eyetracker.processSingleImage(npimg)
print(ret_json)


from flask import Flask, render_template,request
import pickle
from services import calculate_BMI, get_nearest_neighbors, recomanded_food, calculate_calory_u

poplar_df = pickle.load(open('result.pkl','rb'))

app = Flask(__name__)

@app.route('/')

def index():
    return render_template('index.html',
                           food_name = list(poplar_df['food_name'].values),
                           food_image = list(poplar_df['image'].values),
                           food_healthlabel = list(poplar_df['food_healthlabel'].values)

                             )

@app.route('/recomanded')
def recomand_ui():
    return render_template('recomanded.html')
    # Get inputs
@app.route('/recommended_foods', methods=['POST'])
def recomand():

    age = request.form.get('age')
    weight = request.form.get('weight')
    height = request.form.get('height')
    gender = request.form.get('gender')
    active = request.form.get('activity_lavel')

    input = {
        'weight': str(weight),
        'height': str(height),
        'age': str(age),
        'sex': str(gender),
        'activity_lavel': str(active)
    }

    user_input = calculate_calory_u(input)
    recommended_food = recomanded_food(user_input)

    return render_template('recomanded.html',data = recommended_food )

if __name__ == '__main__':
     app.run(debug=True)


#!/usr/bin/env python
import numpy as np
from math import floor, cos, sin
from sets import Set
from planning_python.state_lattices.state_lattice import StateLattice

class XYAnalyticLattice(StateLattice):
  def __init__(self, params):
    #unpack all parameters
    self.ndims           = 2
    self.x_lims          = params['x_lims']
    self.y_lims          = params['y_lims']
    self.connectivity    = params['connectivity']
    self.resolution      = np.asarray(params['resolution'])
    self.origin          = np.asarray(params['origin']) #origin of lattice in world
    self.rotation        = params['rotation'] #rotation of lattice about z-axis w.r.t world
    self.path_resolution = params['path_resolution']

    #Define grid connectivity. This describes what nodes in the discrete
    #graph are connected to what other nodes.
    if self.connectivity == "four_connected":
      self.max_movement_id = 4
      self.children = np.array([(1,0), (0, -1), (-1, 0), (0, 1)])
      self.predecessors = self.children
    if self.connectivity == "eight_connected":
      self.max_movement_id = 8
      self.children = np.array([(1, 1), (1,-1), (-1, -1), (-1, 1), (1, 0), (0, -1),  (-1, 0), (0, 1)])
      self.predecessors = self.children

    StateLattice.__init__(self, self.ndims, [self.x_lims[0], self.y_lims[0]], [self.x_lims[1], self.y_lims[1]], self.resolution)

    #Precalculate successors and predecessors
    self.node_to_succs = dict()
    self.node_to_preds = dict()
    self.succ_costs = dict()
    self.pred_costs = dict()
    self.edge_precalc_done = False
    self.costs_precalc_done = False

  def node_to_state(self, node):
    """Convert a discrete node to a world state taking origin and rotation of lattice into account

    @param  node  - a tuple containing discrete (x,y) coordinates
    @return state - np array of state in continuous world coordinates

    """
    xd = node[0]
    yd = node[1]
    state = self.origin + np.array([self.resolution[0]*(cos(self.rotation)*xd - sin(self.rotation)*yd),
                                    self.resolution[1]*(sin(self.rotation)*xd + cos(self.rotation)*yd)])
    return state

  def state_to_node(self, state):
    """Convert a continuous state(in world coordinates) to a discrete node()in lattice coordinates)"""
    node = np.asarray(state)
    node -= self.origin
    node = np.divide(node, self.resolution)
    #we need to rotate the state to lattice coordinates
    node = np.array([ cos(self.rotation)*node[0] + sin(self.rotation)*node[1],
                     -sin(self.rotation)*node[0] + cos(self.rotation)*node[1]])
    node = node.astype(int, copy=False)
    return tuple(node)

  def get_edge(self, parent_node, child_node):
    """Given two discrete nodes, returns an edge(sequence of waypoints) connecting them.
    The returned edge includes the start and end points

    @param : parent_node - discrete node which is the parent
    @param : child_node  - discrete node which is the child
    @return: edge        - list of waypoints(continuous) in world coordinates
    """
    parent_state = self.node_to_state(parent_node)
    child_state = self.node_to_state(child_node)
    num_points = self.distance_bw_states(parent_state, child_state)/self.path_resolution
    return self.interpolate(parent_state, child_state, num_points)

  def get_successors(self, node):
    """Given a discrete node in the lattice, returns the child nodes (discrete) and corresponding
    edges (continuous states)

    The edges use the parameter path_resolution to interpolate between two nodes.

    @param node    - node for which successors are to be queried
    @return succs  - a list of lists, where the first element is a child node (discrete) and second element is
                     an edge connecting current node to child node (continuous states)
    """
    succs = []
    parent_state = self.node_to_state(node)
    for it in self.children:
      child_node  = (node[0] + it[0], node[1] + it[1])
      child_state = self.node_to_state(child_node)
      edge = self.interpolate(parent_state, child_state, self.distance_bw_states(parent_state, child_state)/self.path_resolution)
      succs.append([child_node, edge])
    return succs

  def get_predecessors(self, node):
    """Given a discrete node in the lattice, returns all the predecessor nodes (discrete) and corresponding
    edges (continuous states)

    The edges use the parameter path_resolution to interpolate between two nodes.

    @param node    - node for which successors are to be queried
    @return preds  - a list of lists, where the first element is a parent node (discrete) and second element is
                     an edge connecting current node to parent node (continuous states)
    """
    preds = []
    child_state = self.node_to_state(node)
    for it in self.predecessors:
      parent_node = (node[0] + it[0], node[1] + it[1])
      parent_state = self.node_to_state(parent_node)
      edge = self.interpolate(child_state, parent_state, self.distance_bw_states(child_state, parent_state)/self.path_resolution)
      preds.append([parent_node, edge])
    return preds

  def interpolate(self, s1, s2, num_points):
    """Returns a sequence of states between two states
    given a motion that connects the two states.

    We use a shooting method type approach to interpolate between the two states

    @param: s1         - parent state
    @param: s2         - child state
    @params motion     - control input connecting the two states
    @params num_points - number of intermediate points (excluding the end points)
    @return edge       - sequence of states (including end points)
    """
    edge = [tuple(s1)]
    length = self.distance_bw_states(s1, s2)
    d_l = length/num_points
    curr_len = d_l
    while True:
      #Do linear interpolation
      temp = [s1[i] + (s2[i] - s1[i])*(curr_len/length) for i in range(self.ndims)]
      #Update curr_len
      curr_len+= d_l
      if curr_len > length: break
      #Append temp to edge
      edge.append(tuple(temp))
    #Add final state to edge
    edge.append(tuple(s2))
    return edge

  def distance_bw_states(self, s1, s2):
    return np.linalg.norm(s1-s2)

  def enumerate_lattice(self):
    """For every discrete node in the lattice, we store a dictionary of [successor nodes, successor edges] and
    [predecessor_node, predecessor_edges]"""
    node_to_succs = dict()
    node_to_preds = dict()
    start_node = self.state_to_node([self.x_lims[0], self.y_lims[0]])
    for i in range(self.num_cells[0]):
      x = start_node[0] + i
      for j in range(self.num_cells[1]):
        y = start_node[1] + j
        node = (x,y)
        node_to_succs[node] = self.get_successors(node)
        node_to_preds[node] = self.get_predecessors(node)

    assert(len(node_to_succs.keys()) == self.total_cells), "Did not enumerate all possible successor cells"
    assert(len(node_to_preds.keys()) == self.total_cells), "Did not enumerate all possible predecessor cells"
    return node_to_succs, node_to_preds

  def precalc_edges(self):
    self.node_to_succs, self.node_to_preds = self.enumerate_lattice()
    self.edge_precalc_done = True

  def precalc_costs(self, cost_fn):
    #Do precalculation of costs here
    print('Precalculating Edges and Costs')
    if not self.edge_precalc_done:
      self.precalc_edges()
    for node in self.node_to_succs:
      succs = self.node_to_succs[node]
      costs = []
      for succ_node, succ_edge in succs:
        costs.append(cost_fn.get_cost(succ_edge))
      self.succ_costs[node] = costs

      preds = self.node_to_preds[node]
      costs = []
      for pred_node, pred_edge in preds:
        costs.append(cost_fn.get_cost(pred_edge))
      self.pred_costs[node] = costs

    self.costs_precalc_done = True


import game, collections, os, pygame_gui, time, pprint

# starts the game
def start():
    game.pygame.init()

    # centers the window to be opened
    os.environ["SDL_VIDEO_CENTERED"] = "1"

    date = time.strftime("%Y-%m-%d")

    game.pygame.display.set_caption("j-masci/game-1 | " + game.config.version + " | " + date)

    game.window_surface = game.pygame.display.set_mode((game.window_props.width, game.window_props.height))

    game.gui_manager = pygame_gui.UIManager((game.window_props.width, game.window_props.height))

    # add entities
    game.populator.populate()

    # invisible mouse
    # game.pygame.mouse.set_cursor((8, 8), (0, 0), (0, 0, 0, 0, 0, 0, 0, 0), (0, 0, 0, 0, 0, 0, 0, 0))
    game.pygame.mouse.set_visible(False)

    # font init
    game.pygame.font.init()

    while True:

        game.loop.count += 1

        timer = game.classes.Timer()
        times = collections.OrderedDict()

        # gets and clears queued events
        game.loop.events = game.pygame.event.get()
        game.loop.keys_pressed = game.pygame.key.get_pressed()

        # fill the background
        game.window_surface.fill(game.config.background_color)

        # update/draw
        game.world.process()

        game.on_screen_debugger.draw(game.window_surface)

        times["process_1"] = timer.time_since_start()

        # updates the window with the new stuff
        game.pygame.display.flip()

        end_time = timer.time_since_start()
        times["end_time"] = end_time

        # throttle updates per second
        game.loop.dt = game.clock.tick(game.config.updates_per_second)
        time_delta = game.loop.dt / 1000
        game.gui_manager.update(time_delta)
        game.gui_manager.draw_ui(game.window_surface)

        game.on_screen_debugger.state["frame_time"] = str(round(end_time * 100, 1)) + "ms"

        if game.config.track_times_in_loop:
            game.utils.debug_append("Loop # " + str(game.loop.count), times)

def quit(restart=False):
    if game.config.debug_print_on_exit:
        game.debugger.print()

    if game.config.debug_log_on_exit:
        game.debugger.log()

    raise game.exceptions.QuitGameException("restart" if restart else "quit")


class Node(object):
    def __init__(self, value):
        self.value = value
        self.edges = []

class Edge(object):
    def __init__(self, value, node_from, node_to):
        self.value = value
        self.node_from = node_from
        self.node_to = node_to

class Graph(object):
    def __init__(self, nodes=[], edges=[]):
        self.nodes = nodes
        self.edges = edges

    def insert_node(self, new_node_val):
        new_node = Node(new_node_val)
        self.nodes.append(new_node)

    def insert_edge(self, new_edge_val, node_from_val, node_to_val):
        from_found = None
        to_found = None
        for node in self.nodes:
            if node_from_val == node.value:
                from_found = node
            if node_to_val == node.value:
                to_found = node
        if from_found == None:
            from_found = Node(node_from_val)
            self.nodes.append(from_found)
        if to_found == None:
            to_found = Node(node_to_val)
            self.nodes.append(to_found)
        new_edge = Edge(new_edge_val, from_found, to_found)
        from_found.edges.append(new_edge)
        to_found.edges.append(new_edge)
        self.edges.append(new_edge)

    def get_edge_list(self):
        """Don't return a list of edge objects!
        Return a list of triples that looks like this:
        (Edge Value, From Node Value, To Node Value)"""
        # Start with empty list
        edge_list = []
        # For each edge object, convert to tuple and append to list
        for edge_obj in self.edges:
            edge = (edge_obj.value, edge_obj.node_from.value,
                    edge_obj.node_to.value)
            edge_list.append(edge)
        return edge_list

    def get_adjacency_list(self):
        """Don't return any Node or Edge objects!
        You'll return a list of lists.
        The indecies of the outer list represent
        "from" nodes.
        Each section in the list will store a list
        of tuples that looks like this:
        (To Node, Edge Value)"""
        # Need max index to know the length of the list we will create
        max_index = self.get_max_index()
        adj_list = [None] * (max_index + 1)
        # Set "to node" values and edge values at a specific index
        for edge_obj in self.edges:
            # Check if "from node" exists
            if adj_list[edge_obj.node_from.value]:
                adj_list[edge_obj.node_from.value].append(
                    (edge_obj.node_to.value, edge_obj.value))
            else:
                # If "from node" exists set the value
                adj_list[edge_obj.node_from.value] = [
                    (edge_obj.node_to.value, edge_obj.value)]
        return adj_list

    def get_adjacency_matrix(self):
        """Return a matrix, or 2D list.
        Row numbers represent from nodes,
        column numbers represent to nodes.
        Store the edge values in each spot,
        and a 0 if no edge exists."""
        # Get max index to get list length
        max_index = self.get_max_index()
        adj_mat = []
        # Create a m * n matrix
        for m in range(max_index + 1):
            inner = []
            for n in range(max_index + 1):
                inner.append(0)
            adj_mat.append(inner)
        # Set values from edge object
        for edge_obj in self.edges:
            adj_mat[edge_obj.node_from.value][edge_obj.node_to.value] = edge_obj.value
        return adj_mat

    def get_max_index(self):
        max_index = -1
        if len(self.nodes):
            for node in self.nodes:
                if node.value > max_index:
                    max_index = node.value
        return max_index

graph = Graph()
graph.insert_edge(100, 1, 2)
graph.insert_edge(101, 1, 3)
graph.insert_edge(102, 1, 4)
graph.insert_edge(103, 3, 4)
# Should be [(100, 1, 2), (101, 1, 3), (102, 1, 4), (103, 3, 4)]
print(graph.get_edge_list())
# Should be [None, [(2, 100), (3, 101), (4, 102)], None, [(4, 103)], None]
print(graph.get_adjacency_list())
# Should be [[0, 0, 0, 0, 0], [0, 0, 100, 101, 102], [0, 0, 0, 0, 0], [0, 0, 0, 0, 103], [0, 0, 0, 0, 0]]
print(graph.get_adjacency_matrix())

Lesson 06 - Graphs/06-graph-repr-quiz.py