#!/usr/bin/python
import sys
sys.path.append("/home/pi/Desktop/NAVI/WANDER_LUST")

from sense_hat import SenseHat

# To get good results with the magnetometer you must first calibrate it using
# the program in RTIMULib/Linux/RTIMULibCal
# The calibration program will produce the file RTIMULib.ini
# Copy it into the same folder as your Python code

sense = SenseHat()
sense.set_rotation(0)

def navi():
    sense.clear()
    led_loop = [4, 5, 6, 7, 15, 23, 31, 39, 47, 55, 63, 62, 61, 60, 59, 58, 57, 56, 48, 40, 32, 24, 16, 8, 0, 1, 2, 3]

    prev_x = 0
    prev_y = 0

    led_degree_ratio = len(led_loop) / 360.0
    while True:
        try:
            dir = sense.get_compass()
            dir_inverted = 360 - dir  # So LED appears to follow North
            led_index = int(led_degree_ratio * dir_inverted)
            offset = led_loop[led_index]

            y = offset // 8  # row
            x = offset % 8  # column

            if x != prev_x or y != prev_y:
                sense.set_pixel(prev_x, prev_y, 0, 0, 0)

            sense.set_pixel(x, y, 0, 0, 255)

            prev_x = x
            prev_y = y
        except KeyboardInterrupt:
            sense.clear()
            break
            #import Saving_Grace
            #sys.exit()


from pickletools import optimize
import PIL
from PIL import Image
import os
path =  "public/assets/images/gems/"
export_path = "public/assets/images/compressed/"
images = os.listdir(path)

def compress():
    for image in images:
        image_name = image.rsplit('.',1)[0]
        image = Image.open(path+image)
        image = image.resize((800 , 800))
        image.save(export_path+image_name+'.jpeg', 'jpeg', optimize=True, quality=90)
compress()


import socket
import threading

def handle_client(client_socket, player_number):
    client_socket.send("Welcome to Tic Tac Toe! Waiting for the other player to join...".encode())

    while True:
        try:
            message = client_socket.recv(1024).decode()
            if not message:
                break

            # Broadcast the move to the other player
            other_player = 1 if player_number == 2 else 2
            players[other_player - 1].send(message.encode())
        except:
            break

    client_socket.close()

def main():
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server_socket.bind(('127.0.0.1', 12345))
    server_socket.listen(2)
    print("Supervising Server is listening...")

    player_number = 1
    while player_number <= 2:
        client_socket, client_address = server_socket.accept()
        print(f"Player {player_number} connected from {client_address}")
        players[player_number - 1] = client_socket

        client_handler = threading.Thread(target=handle_client, args=(client_socket, player_number))
        client_handler.start()

        player_number += 1

    print("Both players are connected. Game starting...")

    for player_socket in players:
        player_socket.send("Game starting! You are player 1.".encode())

if __name__ == "__main__":
    players = [None, None]
    main()


f=open('Admin\RegisteredStudents.txt','r')
list=[]
i=0
for line in f:
    w1=""
    i=0
    for word in line.strip().split():
        if i==0:
            w1+=word+"_"
        else:
            w1+=word
        i+=1

    list.append(w1)
f.close()
f=open('Admin\AnswerKey.txt','r')
list1=[]
for line in f:
    list1.append(line.strip())

f.close()
lst3=[]
for i in range(0,20):
    temp=str(i+1)+" "+"-"
    lst3.append(temp)

for name in list:
    f=open(' Student\ '.strip()+name+ r'.txt','r')
    list2=[]
    for line in f:
        list2.append(line.strip())

    ct=0
    na=0

    for i in range(0,20):

        if list1[i]==list2[i]:
            ct+=1
        elif list2[i]==lst3[i]:
            na+=1

    f.close()
    score=ct*4-(20-na-ct)
    a,b=name.split("_")
    final_ans=str(a)+" "+str(b)+" "+str(score)+"\n"
    f=open('Admin\FinalReport.txt','a')

    f.writelines(final_ans)
    f.close()


import threading
import time

class XinThread(threading.Thread):
    def __init__(self, num):
        threading.Thread.__init__(self)
        self.num = num
        self.create_time = time.time()

    def run(self):
        time.sleep(1)
        print("Thread", self.num, "created")
        print(time.time() - self.create_time)
        print("Thread", self.num, "terminated")

for item in range(7):
    t = XinThread(item)
    t.start()


from selenium import webdriver
import pandas as pd
from bs4 import BeautifulSoup
import time
import pickle

chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument("--headless")

chrome_path = r"C:\Users\Sebas\PycharmProjects\eSports\venv\chromedriver_win32\chromedriver.exe"

#url = ["https://www.esportsearnings.com/games/231-dota-2/top-players"
#      ]

pickle_in = open("AllGameURLsX100-x400.pickle","rb")
url = pickle.load(pickle_in)

dfall = []

for url in url:
    browser = webdriver.Chrome(chrome_path, options=chrome_options)
    browser.set_window_size(3840, 6000, browser.window_handles[0])

    browser.get(url)
    time.sleep(3)
    html = browser.page_source
    browser.close()

    soup = BeautifulSoup(html, "html.parser")

    try:
        Country = [item["alt"] for item in soup.find_all("img", width = {16})]
        PlayerID = [item.find(class_ = "format_cell detail_list_player").text for item in soup.find_all("tr", class_ = "format_row highlight")]
        Playername = [item.find(class_ = "format_cell detail_list_player").next_sibling.text for item in soup.find_all("tr", class_ = "format_row highlight")]
        PrizeMoneyTotalGame = [item.find(class_ = "format_cell detail_list_prize border_right").text for item in soup.find_all("tr", class_ = "format_row highlight")]
        PrizeMoneyTotalOverall = [item.find(class_ = "format_cell detail_list_prize border_left").text for item in soup.find_all("tr", class_ = "format_row highlight")]
        PercentOfTotal = [item.find(class_ = "format_cell detail_list_prize").text for item in soup.find_all("tr", class_ = "format_row highlight")]
        Game = [soup.find("h1", class_ = "info_box_title").text for len in range(len(Country))]
    except:
        print("error")

    all = []

    for Country, PlayerID, Playername, PrizeMoneyTotalGame, PrizeMoneyTotalOverall, PercentOfTotal, Game in zip (Country, PlayerID, Playername, PrizeMoneyTotalGame, PrizeMoneyTotalOverall, PercentOfTotal, Game):
      all.append({"Country":Country, "PlayerID":PlayerID, "Playername":Playername, "PrizeMoneyTotalGame":PrizeMoneyTotalGame, "PrizeMoneyTotalOverall":PrizeMoneyTotalOverall, "PercentOfTotal":PercentOfTotal, "Game":Game})

    df = pd.DataFrame(all)
    dfall.append(df)

dfall = pd.concat(dfall)

dfall["PrizeMoneyTotalGame"] = dfall["PrizeMoneyTotalGame"].str.replace("$", "")
dfall["PrizeMoneyTotalGame"] = dfall["PrizeMoneyTotalGame"].str.replace(",", "")
dfall["PrizeMoneyTotalOverall"] = dfall["PrizeMoneyTotalOverall"].str.replace("$", "")
dfall["PrizeMoneyTotalOverall"] = dfall["PrizeMoneyTotalOverall"].str.replace(",", "")

dfall.to_excel("Top500PlayersPerGame.xlsx", index=False)

print(dfall)


from random import randint

from LinkedKList import KList
from LinkedList import List

def make_list_from_file(path="binfile.bin", k=1):
    file_d = open(path, "rb")
    file_content_list = list(file_d.read())

    l_list = KList(k, file_content_list) if k > 1 else List(file_content_list)

    file_d.close()
    return l_list

def create_file(nums=50_000, path="binfile.bin"):
    partition_size = 1000
    partitions = int(nums / partition_size)

    file_d = open(path, "wb")

    for a in range(partitions):
        generated_values = []
        for b in range(partition_size):
            generated_values.append(randint(10, 255))
        file_d.write(bytearray(generated_values))

    file_d.close()


from django.shortcuts import render

from toko.models import Barang, Kategori
from profil.models import Profil
# Create your views here.
def home_page(request):
    barang = Barang.objects.all().order_by("-id")[:4]
    profil = Profil.objects.get(slug="toko-al-aminiy")
    return render(request, "toko/home_page.html", {"barang" : barang,
                  "index":True, "profil":profil})

def produk_detail(request, barang_slug ):
    profil = Profil.objects.get(slug="toko-al-aminiy")
    produk = Barang.objects.get(slug=barang_slug)
    return render(request, "toko/produk_detail.html", {"barang" : produk,
                  "profil":profil})

def kategori(request, kategori_slug):
    profil = Profil.objects.get(slug="toko-al-aminiy")
    kategori = Kategori.objects.get(slug=kategori_slug)

    return render(request, "toko/kategori.html", {"kategori":kategori,
                  "profil":profil})


"""Create a cluster in Databricks."""
import sys
from pathlib import Path

# sys.path.append(str(Path(__file__).parent.parent.joinpath('modules')))
import json
from dbkenv.core import DatabricksResourceManager
from dbkenv.core import Configuration
from dbkenv.core import ResourceClient
from dbkenv.core import Log
import argparse

Log(name=Path(__file__).stem)

def parse_args(args_list=None):
    """
    Parse command line arguments.

    Parameters
    ----------
    args_list : [type], optional
        Argument list, by default None

    Returns
    -------
    ArgumentParser
        Arguments parsed
    """
    parser = argparse.ArgumentParser()
    parser.add_argument('-c', '--config_file', help="Full path of cluster's json configuration", type=str, required=True)
    args_parsed = parser.parse_args(args_list)
    return args_parsed

def main(cluster_config_file):
    """
    Execute the script.

    Parameters
    ----------
    cluster_config_file : str
        Path of the configuration file

    Raises
    ------
    Exception
        Raises when script failes
    """
    configuration = Configuration(file_load=True)
    # cluster_config_file = str(Path(__file__).parent.joinpath('unittest_cluster.json'))

    with open(cluster_config_file.strip(), 'r') as cl:
        cluster_configuration = json.load(cl)

    cluster_name = cluster_configuration['cluster_name']
    # instantiate the logger

    client = ResourceClient(
        host=configuration.DATABRICKS_HOST,
        personal_token=configuration.DATABRICKS_TOKEN
    )
    drm = DatabricksResourceManager(
        client=client,
        cluster_name=cluster_name,
        cluster_configuration=cluster_configuration
    )

    drm.cluster.create_cluster_and_wait()

if __name__ == "__main__":
    args = parse_args()
    main(cluster_config_file=args.config_file)


def main():
    N, M = map(int, input().split())
    point = [0] + list(map(int, input().split()))
    p = {i: point[i] for i in range(1, N + 1)}
    student = []
    for i in range(M):
        score = input().split()
        student.append([int(score[0]), 0])
        for j in range(1, N + 1):
            if score[j] == 'O':
                student[i][1] += p[j]
    student.sort(key=lambda k: (k[1], -k[0]), reverse=True)
    print(student[0][0], student[0][1])

if __name__ == "__main__":
    main()


from django.test import TestCase
from django.urls import reverse, resolve
from bugs_app.views import list_bugs, bug_delete, bug_add  #imports methods from views
# Create your tests here.
# Create your tests here.
class URLTests(TestCase):
    #check if the homepage URL is working
    def test_testbuglistURL(self):
        response=self.client.get('/')
        self.assertEqual(response.status_code,200)
        url=reverse('bug_list')
        self.assertEquals(resolve(url).func, list_bugs)
        print(resolve(url))

    def test_testbug_addURL(self):
        response=self.client.get('/')
        self.assertEqual(response.status_code,200)
        url=reverse('bug_add')
        self.assertEquals(resolve(url).func, bug_add)
        print(resolve(url))

    def test_testbug_deleteURL(self):
        response=self.client.get('/')
        self.assertEqual(response.status_code,200)
        url=reverse('bug_delete')
        self.assertEquals(resolve(url).func, bug_delete)
        print(resolve(url))


class BotDefiner:

  bot:List[Any]
  params:List[Any]
  _index: int
  debug: bool
  def __init__(self, bot = None, debug = False):
      super()
      self.bot = bot
      self.params = []
      self.reset()
      self.debug = debug

  def Boolean(self, name = None):
    return self.Int(0,1, name  = name)

  def Int(self, *args , name = None):
    return self.getRand(lambda: random.randint(args[0],args[1]), name = name)

  def getRand(self, func, name = None):
    if (self.debug):
      print("name = ", name)
    if self.bot != None:
      if (self.debug):
        print("current _index:", self._index)
      return_value = self.bot[self._index]

      if (self.debug):
       print("current _return value:", return_value)
      self._index +=1
      return return_value
    else:
      self.params.append((func, name))
      return func()

  def reset(self, doClean = False):
    self._index = 0
    if doClean:
      self.params = []

  def loadBot(self, bot):
    self.bot = bot
    self.reset()
    return self

  def generateRandomBot(self):
    bot = []
    if (self.debug):
      print("start generating")
    for f, name in self.params:
        if (self.debug):
          print(f, name)
        bot.append(f())
    if (self.debug):
      print("stop generating")
    return botgi


"""
Test AFT Implementation of stiffness of the form X^5
"""

import sys
import numpy as np
import unittest

# Python Utilities
sys.path.append('..')
import verification_utils as vutils

sys.path.append('../..')
from tmdsimpy.nlforces.quintic_stiffness import QuinticForce

class TestQuinticAFT(unittest.TestCase):

    def __init__(self, *args, **kwargs):
        """
        Define tolerances here for all the tests

        Returns
        -------
        None.

        """
        super(TestQuinticAFT, self).__init__(*args, **kwargs)

        self.analytical_tol = 1e-12 # Comparison to analytical solution tolerance

        self.rtol_grad = 1e-11 # Relative gradient tolerance

    def test_analytical_aft(self):
        """
        Test analytical expansion of nonlinear force for first harmonic motion
        against the AFT values.

        Also check gradients for the simple case

        Returns
        -------
        None.

        """

        #######################
        # Test System

        # Simple Mapping to spring displacements
        Q = np.array([[1.0, 0], \
                      [-1.0, 1.0], \
                      [0, 1.0]])

        # Weighted / integrated mapping back for testing purposes
        T = np.array([[1.0, 0.25, 0.0], \
                      [0.0, 0.25, 1.0]])

        kalpha = np.array([3, 0, 7])

        nl_force = QuinticForce(Q, T, kalpha)

        """
        Case 1:
            -Fix Center DOF
            -Only move the first Harmonic
            -Compare to analytical expansion of cos^3/sin^3
        """
        # h = np.array([0, 1, 2, 3]) # Manual Checking expansion / debugging
        h = np.array([0, 1, 2, 3, 4, 5, 6, 7]) # Automate Checking with this
        Nhc = 2*(h !=0).sum() + (h==0).sum() # Number of Harmonic Components

        Nd = Q.shape[1]

        U = np.zeros((Nd*Nhc, 1))

        # First DOF, Cosine Term, Fundamental
        U[Nd+0, 0] = 4

        # Second DOF, Sine Term, Fundamental
        U[2*Nd+1, 0] = 3

        w = 1 # Test for various w

        # Testing Simple First Harmonic Motion
        Fnl, dFnldU = nl_force.aft(U, w, h)[0:2]

        # # Analytically Verify Force expansion:
        # # X^5*cos^5(x) = X^5*( 10/16*cos(x) + 5/16*cos(3x) + 1/16*cos(5x) )
        # # X^5*sin^5(x) = X^5*( 10/16*sin(x) - 5/16*sin(3x) + 1/16*sin(5x) )
        Fnl_analytical = np.zeros_like(Fnl)
        Fnl_analytical[Nd+0] = T[0,0]*( 10/16*kalpha[0]*(Q[0,0]*U[Nd+0, 0])**5 )
        Fnl_analytical[5*Nd+0] = T[0,0]*( 5/16*kalpha[0]*(Q[0,0]*U[Nd+0, 0])**5 )
        Fnl_analytical[9*Nd+0] = T[0,0]*( 1/16*kalpha[0]*(Q[0,0]*U[Nd+0, 0])**5 )

        Fnl_analytical[2*Nd+1] = T[1,2]*( 10/16*kalpha[2]*(Q[2,1]*U[2*Nd+1, 0])**5 )
        Fnl_analytical[6*Nd+1] = T[1,2]*( -5/16*kalpha[2]*(Q[2,1]*U[2*Nd+1, 0])**5 )
        Fnl_analytical[10*Nd+1] = T[1,2]*( 1/16*kalpha[2]*(Q[2,1]*U[2*Nd+1, 0])**5 )

        error = np.linalg.norm(Fnl - Fnl_analytical)

        self.assertLess(error, self.analytical_tol,
                        'Quintic stiffness does not match analytical AFT.')

        # Numerically Verify Gradient
        fun = lambda U: nl_force.aft(U, w, h)[0:2]
        grad_failed = vutils.check_grad(fun, U, verbose=False,
                                        rtol=self.rtol_grad)

        self.assertFalse(grad_failed,
                         'Incorrect displacement w.r.t. displacement.')

        # Numerically Verify Frequency Gradient
        fun = lambda w: nl_force.aft(U, w[0], h)[0::2]
        grad_failed = vutils.check_grad(fun, np.array([w]), verbose=False,
                                        rtol=self.rtol_grad)

        self.assertFalse(grad_failed,
                         'Incorrect displacement w.r.t. frequency.')

    def test_multiharmonic_grads(self):
        """
        Test derivatives for multiharmonic motion and for mixed sets / skipping
        some harmonic components

        Returns
        -------
        None.

        """

        # np.random.seed(42)
        np.random.seed(1023)
        # np.random.seed(0)

        # Simple Mapping to spring displacements
        Q = np.array([[1.0, 0], \
                      [-1.0, 1.0], \
                      [0, 1.0]])

        h = np.array([0, 1, 2, 3, 5, 6, 7]) # Automate Checking with this
        kalpha = np.array([3, 5, 7])

        # Weighted / integrated mapping back for testing purposes
        T = np.array([[1.0, 0.25, 0.0], \
                      [0.0, 0.25, 0.5]])

        Nhc = 2*(h !=0).sum() + (h==0).sum() # Number of Harmonic Components
        Nd = Q.shape[1]

        U = np.random.rand(Nd*Nhc, 1)

        w = 1.375 # Test for various w

        nl_force = QuinticForce(Q, T, kalpha)

        ######################
        # Test without 4th harmonic

        fun = lambda U: nl_force.aft(U, w, h)[0:2]
        grad_failed = vutils.check_grad(fun, U, verbose=False,
                                        rtol=self.rtol_grad)

        self.assertFalse(grad_failed, 'Incorrect displacement gradient.')

        # Numerically Verify Frequency Gradient
        fun = lambda w: nl_force.aft(U, w[0], h)[0::2]
        grad_failed = vutils.check_grad(fun, np.array([w]), verbose=False,
                                        rtol=self.rtol_grad)

        self.assertFalse(grad_failed, 'Incorrect displacement frequency.')

        ######################
        # Test without zeroth harmonic + skipping 4th harmonic
        h = np.array([1, 2, 3, 5, 6, 7]) # Automate Checking with this

        Nhc = 2*(h !=0).sum() + (h==0).sum() # Number of Harmonic Components
        Nd = Q.shape[1]

        U = np.random.rand(Nd*Nhc, 1)

        fun = lambda U: nl_force.aft(U, w, h)[0:2]
        grad_failed = vutils.check_grad(fun, U, verbose=False,
                                        rtol=self.rtol_grad)

        self.assertFalse(grad_failed, 'Incorrect displacement gradient.')

        # Numerically Verify Frequency Gradient
        fun = lambda w: nl_force.aft(U, w[0], h)[0::2]
        grad_failed = vutils.check_grad(fun, np.array([w]), verbose=False,
                                        rtol=self.rtol_grad)

        self.assertFalse(grad_failed, 'Incorrect frequency gradient.')

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


from display import display_board , save_it , display_sample
from handle_input import Input
from checks import Checkit
import json
import sys

def main():
    print('Welcome to Tic Tac Toe!\n')
    resume = input("Would you like to resume a previous game?(y/n): ").lower()
    i = 1
    players = Input.player_input()
    if resume == 'y':
        data = open('saved_game.json')
        board = json.load(data)
    else:
        board = ['#'] * 10

    while True:
        game_on = Checkit.full_board_check(board)
        print('\nEnter \'q\' to suspend your game. Otherwise, enter a number from 1 to 9 \nwhere the following numbers correspond to the locations on the grid:')
        display_sample()
        display_board(board)
        while not game_on:
            position = Input.player_choice(board)

            if i % 2 == 0:
                marker = players[1]
            else:
                marker = players[0]

            Input.place_marker(board, marker, int(position))

            display_board(board)
            save_it(board)

            i += 1
            if Checkit.win_check(board, marker):
                print('You won!')
                with open('saved_game.json', 'w') as data:
                    json.dump('', data, indent=1)
                    print("Previous game data erased")
                break
            game_on = Checkit.full_board_check(board)
        if not replay():
            break
        else:
            i = 1
            players = Input.player_input()
            board = ['#'] * 10

def replay():
    playagain = input("Do you want to play again (Yes or no)? ")
    if playagain.lower() == "yes":
        return True
    if playagain.lower() == "no":
        return False

main()


import os, json
import datetime as dt
from pprint import pprint
import pandas as pd
import geojson
from django.conf import settings
from django.shortcuts import render
from django.db.models import Sum
from django.http import HttpResponse, JsonResponse, HttpResponseRedirect
from ahhost.Gridding import ShapeFileHandler,NCHandler,RasterHandler
from ahhost.Interpolation import PointSourceInterpolation as PSI
def index(request):
    return render(request,'index.html')

def shapefile_create(request):
    "get ajax POST request and create shapefile with custom parameters"
    parameters = request.POST
    latlon = [float(parameters['miny']), float(parameters['minx']),\
        float(parameters['maxy']), float(parameters['maxx'])]
    sfh = ShapeFileHandler(latlon,
        float(parameters['resolution']))
    filepath = os.path.join('media/shapefiles/grid')
    sfh.export(filepath)

    return JsonResponse({'status': 'OK', 'filename': filepath})

def raster_calculate(request):
    "calculte raster grid based on zonal_stats, then output netCDF4 file"
    parameters = request.POST
    # step 1:zonal_stats and data normalized
    rasterURL = 'media/{0}/{1}/2010.tif'.format(parameters['st'],parameters['AreaID'])
    vectorURL = 'media/shapefiles/grid.shp'
    rh = RasterHandler(rasterURL, vectorURL)
    rh.process()
    rawGeojson = rh.normalized()
    # step 2:export geojson file to 'media/geojson/data.geojson'
    rh.export_geojson('media/geojson/data.geojson')
    # step 3:netCDF4 file export
    nh = NCHandler(rawGeojson, 'media/netcdf4/data.nc')
    resolution = float(parameters['resolution'])/100.0
    pollution = {
        'name': parameters['type'],
        'quantity': float(parameters['sum'])
    }
    latlon = [
        float(parameters['miny']),
        float(parameters['minx']),
        float(parameters['maxy']),
        float(parameters['maxx']),
    ]
    nh.process(latlon, pollution, resolution)

    return JsonResponse({'status': 'OK'})

def upload_file(request):
    # parameters = request.POST
    def handle_uploaded_file(f):
        # save files
        with open('media/excel/data.xlsx', 'wb+') as destination:
            for chunk in f.chunks():
                destination.write(chunk)
        # data import
        data_import(request, request.POST.get('dt'))

    if request.method == 'POST':
        handle_uploaded_file(request.FILES['exfile'])
        # return JsonResponse(parameters)
        return HttpResponseRedirect('/')
    # else:
    #     form = UploadFileForm()
    # return render(request, 'upload.html', {'form': form})
    # return HttpResponseRedirect('/')

def interpolate(request):
    parameters = request.POST
    psi = PSI()
    psi.process(
        variables=json.loads(parameters['var']),
        method=parameters['method'],
        resolution=float(parameters['resolution'])/100.0
        )
    psi.export(storePath=os.path.join(settings.MEDIA_ROOT,'netcdf4'))
    return JsonResponse({'status': 'OK'})


import collections
import time

import six
from six.moves.urllib import parse
try:
    from ws4py.client import WebSocketBaseClient
    from ws4py.manager import WebSocketManager
    _ws4py_installed = True
except ImportError:  # pragma: no cover
    WebSocketBaseClient = object
    _ws4py_installed = False

from pylxd import managers
from pylxd.models import _model as model

class ContainerState(object):
    """A simple object for representing container state."""

    def __init__(self, **kwargs):
        for key, value in six.iteritems(kwargs):
            setattr(self, key, value)

_ContainerExecuteResult = collections.namedtuple(
    'ContainerExecuteResult',
    ['exit_code', 'stdout', 'stderr'])

class Container(model.Model):
    """An LXD Container.

    This class is not intended to be used directly, but rather to be used
    via `Client.containers.create`.
    """

    architecture = model.Attribute()
    config = model.Attribute()
    created_at = model.Attribute()
    devices = model.Attribute()
    ephemeral = model.Attribute()
    expanded_config = model.Attribute()
    expanded_devices = model.Attribute()
    name = model.Attribute(readonly=True)
    description = model.Attribute()
    profiles = model.Attribute()
    status = model.Attribute(readonly=True)
    last_used_at = model.Attribute(readonly=True)

    status_code = model.Attribute(readonly=True)
    stateful = model.Attribute(readonly=True)

    snapshots = model.Manager()
    files = model.Manager()

    @property
    def api(self):
        return self.client.api.containers[self.name]

    class FilesManager(object):
        """A pseudo-manager for namespacing file operations."""

        def __init__(self, client, container):
            self._client = client
            self._container = container

        def put(self, filepath, data, mode=None, uid=None, gid=None):
            """Push a file to the container.

            This pushes a single file to the containers file system named by
            the `filepath`.

            :param filepath: The path in the container to to store the data in.
            :type filepath: str
            :param data: The data to store in the file.
            :type data: bytes or str
            :param mode: The unit mode to store the file with.  The default of
                None stores the file with the current mask of 0700, which is
                the lxd default.
            :type mode: oct | int | str
            :param uid: The uid to use inside the container. Default of None
                results in 0 (root).
            :type uid: int
            :param gid: The gid to use inside the container.  Default of None
                results in 0 (root).
            :type gid: int
            :returns: True if the file store succeeded otherwise False.
            :rtype: Bool
            """
            headers = {}
            if mode is not None:
                if isinstance(mode, int):
                    mode = format(mode, 'o')
                if not isinstance(mode, six.string_types):
                    raise ValueError("'mode' parameter must be int or string")
                if not mode.startswith('0'):
                    mode = '0{}'.format(mode)
                headers['X-LXD-mode'] = mode
            if uid is not None:
                headers['X-LXD-uid'] = str(uid)
            if gid is not None:
                headers['X-LXD-gid'] = str(gid)
            response = (self._client.api.containers[self._container.name]
                        .files.post(params={'path': filepath},
                                    data=data,
                                    headers=headers or None))
            return response.status_code == 200

        def delete_available(self):
            """File deletion is an extension API and may not be available.
            https://github.com/lxc/lxd/blob/master/doc/api-extensions.md#file_delete
            """
            return u'file_delete' in self._client.host_info['api_extensions']

        def delete(self, filepath):
            if self.delete_available():
                response = self._client.api.containers[
                    self._container.name].files.delete(
                    params={'path': filepath})
                return response.status_code == 200
            else:
                raise ValueError(
                    'File Deletion is not available for this host')

        def get(self, filepath):
            response = (self._client.api.containers[self._container.name]
                        .files.get(params={'path': filepath}))
            return response.content

    @classmethod
    def exists(cls, client, name):
        """Determine whether a container exists."""
        try:
            client.containers.get(name)
            return True
        except cls.NotFound:
            return False

    @classmethod
    def get(cls, client, name):
        """Get a container by name."""
        response = client.api.containers[name].get()

        container = cls(client, **response.json()['metadata'])
        return container

    @classmethod
    def all(cls, client):
        """Get all containers.

        Containers returned from this method will only have the name
        set, as that is the only property returned from LXD. If more
        information is needed, `Container.sync` is the method call
        that should be used.
        """
        response = client.api.containers.get()

        containers = []
        for url in response.json()['metadata']:
            name = url.split('/')[-1]
            containers.append(cls(client, name=name))
        return containers

    @classmethod
    def create(cls, client, config, wait=False):
        """Create a new container config."""
        response = client.api.containers.post(json=config)

        if wait:
            client.operations.wait_for_operation(response.json()['operation'])
        return cls(client, name=config['name'])

    def __init__(self, *args, **kwargs):
        super(Container, self).__init__(*args, **kwargs)

        self.snapshots = managers.SnapshotManager(self.client, self)
        self.files = self.FilesManager(self.client, self)

    def rename(self, name, wait=False):
        """Rename a container."""
        response = self.api.post(json={'name': name})

        if wait:
            self.client.operations.wait_for_operation(
                response.json()['operation'])
        self.name = name

    def _set_state(self, state, timeout=30, force=True, wait=False):
        response = self.api.state.put(json={
            'action': state,
            'timeout': timeout,
            'force': force
        })
        if wait:
            self.client.operations.wait_for_operation(
                response.json()['operation'])
            if 'status' in self.__dirty__:
                del self.__dirty__[self.__dirty__.index('status')]
            if self.ephemeral and state == 'stop':
                self.client = None
            else:
                self.sync()

    def state(self):
        response = self.api.state.get()
        state = ContainerState(**response.json()['metadata'])
        return state

    def start(self, timeout=30, force=True, wait=False):
        """Start the container."""
        return self._set_state('start',
                               timeout=timeout,
                               force=force,
                               wait=wait)

    def stop(self, timeout=30, force=True, wait=False):
        """Stop the container."""
        return self._set_state('stop',
                               timeout=timeout,
                               force=force,
                               wait=wait)

    def restart(self, timeout=30, force=True, wait=False):
        """Restart the container."""
        return self._set_state('restart',
                               timeout=timeout,
                               force=force,
                               wait=wait)

    def freeze(self, timeout=30, force=True, wait=False):
        """Freeze the container."""
        return self._set_state('freeze',
                               timeout=timeout,
                               force=force,
                               wait=wait)

    def unfreeze(self, timeout=30, force=True, wait=False):
        """Unfreeze the container."""
        return self._set_state('unfreeze',
                               timeout=timeout,
                               force=force,
                               wait=wait)

    def execute(self, commands, environment={}):
        """Execute a command on the container.

        In pylxd 2.2, this method will be renamed `execute` and the existing
        `execute` method removed.
        """
        if not _ws4py_installed:
            raise ValueError(
                'This feature requires the optional ws4py library.')
        if isinstance(commands, six.string_types):
            raise TypeError("First argument must be a list.")
        response = self.api['exec'].post(json={
            'command': commands,
            'environment': environment,
            'wait-for-websocket': True,
            'interactive': False,
        })

        fds = response.json()['metadata']['metadata']['fds']
        operation_id = response.json()['operation'].split('/')[-1]
        parsed = parse.urlparse(
            self.client.api.operations[operation_id].websocket._api_endpoint)

        with managers.web_socket_manager(WebSocketManager()) as manager:
            stdin = _StdinWebsocket(self.client.websocket_url)
            stdin.resource = '{}?secret={}'.format(parsed.path, fds['0'])
            stdin.connect()
            stdout = _CommandWebsocketClient(
                manager, self.client.websocket_url)
            stdout.resource = '{}?secret={}'.format(parsed.path, fds['1'])
            stdout.connect()
            stderr = _CommandWebsocketClient(
                manager, self.client.websocket_url)
            stderr.resource = '{}?secret={}'.format(parsed.path, fds['2'])
            stderr.connect()

            manager.start()

            while len(manager.websockets.values()) > 0:
                time.sleep(.1)

            operation = self.client.operations.get(operation_id)

            return _ContainerExecuteResult(
                operation.metadata['return'], stdout.data, stderr.data)

    def migrate(self, new_client, wait=False):
        """Migrate a container.

        Destination host information is contained in the client
        connection passed in.

        If the container is running, it either must be shut down
        first or criu must be installed on the source and destination
        machines.
        """
        if self.api.scheme in ('http+unix',):
            raise ValueError('Cannot migrate from a local client connection')

        return new_client.containers.create(
            self.generate_migration_data(), wait=wait)

    def generate_migration_data(self):
        """Generate the migration data.

        This method can be used to handle migrations where the client
        connection uses the local unix socket. For more information on
        migration, see `Container.migrate`.
        """
        self.sync()  # Make sure the object isn't stale
        response = self.api.post(json={'migration': True})
        operation = self.client.operations.get(response.json()['operation'])
        operation_url = self.client.api.operations[operation.id]._api_endpoint
        secrets = response.json()['metadata']['metadata']
        cert = self.client.host_info['environment']['certificate']

        return {
            'name': self.name,
            'architecture': self.architecture,
            'config': self.config,
            'devices': self.devices,
            'epehemeral': self.ephemeral,
            'default': self.profiles,
            'source': {
                'type': 'migration',
                'operation': operation_url,
                'mode': 'pull',
                'certificate': cert,
                'secrets': secrets,
            }
        }

    def publish(self, public=False, wait=False):
        """Publish a container as an image.

        The container must be stopped in order publish it as an image. This
        method does not enforce that constraint, so a LXDAPIException may be
        raised if this method is called on a running container.

        If wait=True, an Image is returned.
        """
        data = {
            'public': public,
            'source': {
                'type': 'container',
                'name': self.name,
            }
        }

        response = self.client.api.images.post(json=data)
        if wait:
            operation = self.client.operations.wait_for_operation(
                response.json()['operation'])

            return self.client.images.get(operation.metadata['fingerprint'])

class _CommandWebsocketClient(WebSocketBaseClient):  # pragma: no cover
    def __init__(self, manager, *args, **kwargs):
        self.manager = manager
        super(_CommandWebsocketClient, self).__init__(*args, **kwargs)

    def handshake_ok(self):
        self.manager.add(self)
        self.buffer = []

    def received_message(self, message):
        if len(message.data) == 0:
            self.close()
            self.manager.remove(self)
        if message.encoding:
            self.buffer.append(message.data.decode(message.encoding))
        else:
            self.buffer.append(message.data.decode('utf-8'))

    @property
    def data(self):
        return ''.join(self.buffer)

class _StdinWebsocket(WebSocketBaseClient):  # pragma: no cover
    """A websocket client for handling stdin.

    The nature of stdin in Container.execute means that we don't
    ever use this connection. It is closed as soon as it completes
    the handshake.
    """

    def handshake_ok(self):
        self.close()

class Snapshot(model.Model):
    """A container snapshot."""

    name = model.Attribute()
    created_at = model.Attribute()
    stateful = model.Attribute()

    container = model.Parent()

    @property
    def api(self):
        return self.client.api.containers[
            self.container.name].snapshots[self.name]

    @classmethod
    def get(cls, client, container, name):
        response = client.api.containers[
            container.name].snapshots[name].get()

        snapshot = cls(
            client, container=container,
            **response.json()['metadata'])
        # Snapshot names are namespaced in LXD, as
        # container-name/snapshot-name. We hide that implementation
        # detail.
        snapshot.name = snapshot.name.split('/')[-1]
        return snapshot

    @classmethod
    def all(cls, client, container):
        response = client.api.containers[container.name].snapshots.get()

        return [cls(
                client, name=snapshot.split('/')[-1],
                container=container)
                for snapshot in response.json()['metadata']]

    @classmethod
    def create(cls, client, container, name, stateful=False, wait=False):
        response = client.api.containers[container.name].snapshots.post(json={
            'name': name, 'stateful': stateful})

        snapshot = cls(client, container=container, name=name)
        if wait:
            client.operations.wait_for_operation(response.json()['operation'])
        return snapshot

    def rename(self, new_name, wait=False):
        """Rename a snapshot."""
        response = self.api.post(json={'name': new_name})
        if wait:
            self.client.operations.wait_for_operation(
                response.json()['operation'])
        self.name = new_name

    def publish(self, public=False, wait=False):
        """Publish a snapshot as an image.

        If wait=True, an Image is returned.

        This functionality is currently broken in LXD. Please see
        https://github.com/lxc/lxd/issues/2201 - The implementation
        here is mostly a guess. Once that bug is fixed, we can verify
        that this works, or file a bug to fix it appropriately.
        """
        data = {
            'public': public,
            'source': {
                'type': 'snapshot',
                'name': '{}/{}'.format(self.container.name, self.name),
            }
        }

        response = self.client.api.images.post(json=data)
        if wait:
            operation = self.client.operations.wait_for_operation(
                response.json()['operation'])
            return self.client.images.get(operation.metadata['fingerprint'])


import os

import torch
from torch import nn
from torch.utils.data._utils.collate import default_collate

def save_trained_model(model, checkpoint):
    os.makedirs(os.path.dirname(checkpoint), exist_ok=True)
    torch.save(model.state_dict(), checkpoint)

def get_params_to_update(model_ft):
    # Gather the parameters to be optimized/updated in this run
    params_to_update = []
    for name, param in model_ft.named_parameters():
        if param.requires_grad:
            params_to_update.append(param)

    return params_to_update

def freeze_all_parameters(model):
    for name, param in model.named_parameters():
        param.requires_grad = False

def freeze_parameters(model, n_parameters):
    """
    Freeze the specific layers for fine tuning

    @param model: nn.Module object
    @param n_parameters: the number of parameters that need to be frozen
        if it is zero, fine tune the whole network
        if it is positive number then freeze first n parameters
        if it is negative, then freeze last n parameters
    """

    layers = []
    names = []
    for name, param in model.named_parameters():
        layers.append(param)
        names.append(name)

    if n_parameters == 0:
        return

    if n_parameters < 0:
        for param in layers[n_parameters:]:
            param.requires_grad = False
    else:
        for param in layers[:n_parameters]:
            param.requires_grad = False

def extract_image_features(dl_model, sequence_images):
    """
    Extracting the features from sequence of images
    @param dl_model: Deep learning model. The fine tuned vgg_faces to be precised
    @param sequence_images: batch of sequence images
    @return: batch of sequence features
    """
    if dl_model is None:
        return sequence_images

    dl_model.eval()

    with torch.set_grad_enabled(False):
        batch, seq, channels, im_h, im_w = tuple(sequence_images.shape)
        features = sequence_images.reshape((-1, channels, im_h, im_w))
        features = dl_model(features)
        features = features.reshape((batch, seq, -1))

    return features

def id_collate(batch):
    ids = []
    for _batch in batch:
        ids.append(_batch['id'])
    result = default_collate(batch)
    result['id'] = ids
    return result

def weights_init_xavie(m):
    if isinstance(m, torch.nn.Conv2d) or isinstance(m, torch.nn.Linear):
        torch.nn.init.xavier_uniform_(m.weight, gain=nn.init.calculate_gain('relu'))
        if m.bias is not None:
            m.bias.data.zero_()

def get_list_aus(aus, locations):
    result = []
    for au in aus:
        au_id = int(au.replace('au_', ''))
        num_points = len([x for x in locations[au_id] if x is not None])
        for x in range(num_points):
            result.append('%s_%d' % (au, x))
    return result


''' Question:
*   Given a binary tree, return the level order traversal of the
*   nodes' values as an array
*   https://leetcode.com/problems/binary-tree-level-order-traversal/
'''

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right

from collections import deque

def level_order_values(root: TreeNode) -> List[List[int]]:

    if root is None:
        return []

    values = []
    q = deque([root])

    while q:
        level_count = len(q)
        level_values = []
        for i in range(level_count):
            current = q.popleft()
            values.append(current.val)
            if current.left is not None:
                q.append(current.left)
            if current.right is not None:
                q.append(current.right)

        values.append(level_values)

    return values

# Time complexity: O(N)
# Space complexity: O(N)


import re

example_boss = """Hit Points: 12
Damage: 7
Armor: 2"""

example_self = """Hit Points: 8
Damage: 5
Armor: 5"""

weapons = {
	"dagger": {"Au": 8, "Dm": 4},
	"shortsword": {"Au": 10, "Dm": 5},
	"warhammer": {"Au": 25, "Dm": 6},
	"longsword": {"Au": 40, "Dm": 7},
	"greataxe": {"Au": 74, "Dm": 8}
}
armor = {
	"leather": {"Au": 13, "AC": 1},
	"chainmail": {"Au": 31, "AC": 2},
	"splintmail": {"Au": 53, "AC": 3},
	"bandedmail": {"Au": 75, "AC": 4},
	"platemail": {"Au": 102, "AC": 5},
	"[none]": {"Au": 0, "AC": 0}
}
rings = {
	"damage +1": {"Au": 25, "AC": 0, "Dm": 1},
	"damage +2": {"Au": 50, "AC": 0, "Dm": 2},
	"damage +3": {"Au": 100, "AC": 0, "Dm": 3},
	"defense +1": {"Au": 20, "AC": 1, "Dm": 0},
	"defense +2": {"Au": 40, "AC": 2, "Dm": 0},
	"defense +3": {"Au": 80, "AC": 3, "Dm": 0},
	"[none]": {"Au": 0, "AC": 0, "Dm": 0}
}

combos = []

for w in weapons:
	for a in armor:
		for r1 in rings:
			for r2 in rings:
				if r1 != r2 or (r1 == "[none]" and r2 == "[none]"):
					this_combo = {
						"weapon": w,
						"armor": a,
						"ring1": r1,
						"ring2": r2,
						"t_Au": weapons[w]["Au"] + armor[a]["Au"] + rings[r1]["Au"] + rings[r2]["Au"],
						"t_AC": armor[a]["AC"] + rings[r1]["AC"] + rings[r2]["AC"],
						"t_Dm": weapons[w]["Dm"] + rings[r1]["Dm"] + rings[r2]["Dm"]
					}
					combos.append(this_combo)

#for combo in combos:
#	print(combo)

def fight(boss, pc, Au, day):
	while True:
		# PC
		damage = pc["Dm"] - boss["AC"]
		if damage < 1: damage = 1
		boss["HP"] -= damage
		if boss["HP"] <= 0:
			break
		# Boss
		damage = boss["Dm"] - pc["AC"]
		if damage < 1: damage = 1
		pc["HP"] -= damage
		if pc["HP"] <= 0:
			break
	if day == "a":
		if boss["HP"] <= 0:
			return Au
		else:
			return -1
	else:
		if pc["HP"] <= 0:
			return Au
		else:
			return -1

def setup(bi, pi):
	temp = pi.split("\n")
	pc = {
		"HP": int(temp[0].split(" ")[2]),
		"Dm": int(temp[1].split(" ")[1]),
		"AC": int(temp[2].split(" ")[1]),
		"AU": 0
	}
	temp = bi.split("\n")
	boss = {
		"HP": int(temp[0].split(" ")[2]),
		"Dm": int(temp[1].split(" ")[1]),
		"AC": int(temp[2].split(" ")[1])
	}
	return boss, pc

def do_day(test=False, day="a"):
	if test:
		boss_input = example_boss
		pc_input = example_self
	else:
		boss_input = open("d21.txt", "r").read()
		pc_input = """Hit Points: 100
Damage: 0
Armor: 0"""
	boss, pc = setup(boss_input, pc_input)
	if test:
		Au = fight(boss, pc)
		print(Au)
	else:
		min_gold = 9999
		max_gold = 0
		for combo in combos:
			boss, pc = setup(boss_input, pc_input)
			pc["Dm"] = combo["t_Dm"]
			pc["AC"] = combo["t_AC"]
			pc["Au"] = combo["t_Au"]
			Au = fight(boss, pc, pc["Au"], day)
			if Au > -1:
				if day == "a" and Au < min_gold:
					min_gold = Au
				elif day == "b" and Au > max_gold:
					max_gold = Au
		if day == "a":
			print(min_gold)
		else:
			print(max_gold)

do_day(test=False, day="a")
do_day(test=False, day="b")