#!/usr/bin/env python3

import glob
import pdb
import sys
import numpy as np
from statsmodels.stats.contingency_tables import mcnemar

dev = glob.glob(sys.argv[1] + '/*')
sys1 = glob.glob(sys.argv[2] + '/*')
sys2 = glob.glob(sys.argv[3] + '/*')

corrects = []

for f in dev:
    ifile = open(f + '/dev.tsv', 'r')
    lines = ifile.readlines()
    for line in lines:
        line = line.strip().split('\t')
        corr = line[-1]
        if corr != 'label':
            corrects.append(corr)
    ifile.close()

preds1 = []
preds2 = []

for f1, f2 in zip(sys1, sys2):
    ofile1 = open(f1 + '/scores.txt', 'r')
    ofile2 = open(f2 + '/scores.txt', 'r')
    for line1, line2 in zip(ofile1, ofile2):
        # try:
        line1 = line1.strip()
        line1 = line1.split('\t')
        # assert(len(line1) == 2)
        line2 = line2.strip()
        line2 = line2.split('\t')
        # assert(len(line2) == 2)
        if len(line1) > 1 and len(line2) > 1:
            pred1 = line1[1]
            score1 = line1[0]
            preds1.append(pred1)

            pred2 = line2[1]
            score2 = line2[0]
            preds2.append(pred2)
            # except:
                # continue

    ofile1.close()
    ofile2.close()

def correct(system, gold):
    correct = 0
    total = 0
    for l1, l2 in zip(system, gold):
        total += 1
        if l1 == l2:
            correct += 1
    # print("Acc:", correct / total)
    return correct / total

# pdb.set_trace()
print(sys.argv[2] + " acc:", correct(preds1, corrects))
print(sys.argv[3] + " acc:", correct(preds2, corrects))

bothright = 0
YesNo = 0
NoYes = 0
bothwrong = 0
for c1, c2, gold in zip(preds1, preds2, corrects):
    if c1 == gold and c2 == gold:
        bothright += 1
    elif c1 == gold and c2 != gold:
        YesNo += 1
    elif c1 != gold and c2 == gold:
        NoYes += 1
    elif c1 != gold and c2 != gold:
        bothwrong += 1
    else:
        print("Error")
        pdb.set_trace()

print("statsmodels", mcnemar(np.array([[bothright, YesNo], [NoYes, bothwrong]])))
print("statsmodels exact false", mcnemar(np.array([[bothright, YesNo], [NoYes, bothwrong]]), exact=False))
print("statsmodels correction false", mcnemar(np.array([[bothright, YesNo], [NoYes, bothwrong]]), correction=False))
print("statsmodels exact false correction false", mcnemar(np.array([[bothright, YesNo], [NoYes, bothwrong]]), exact=False, correction=False))


#!/usr/bin/env python3

dictionary = {
    '0': 'Sheldon',
    '1': 'Leonard',
    '2': 'Penny',
    '3': 'Rajesh',
    '4': 'Howard'
}
def whoIsNext(names, r):
    # print(names)
    # print(r)
    queue = [0,1,2,3,4]
    result = 0
    for i in range(r):
        result = queue[0]
        queue = queue[1:]
        queue.append(result)
        queue.append(result)
    #print(result)
    print(queue)
    return dictionary[str(result)]

print(whoIsNext(["Sheldon", "Leonard", "Penny", "Rajesh", "Howard"],75))


import random
from copy import deepcopy, copy
from typing import Tuple

from libs import ActorPosition, BaseClass, reverse_tuple, add_tuples
from libs.greedy_shortest_path import AStar
from libs.layouts import manhattan_distance

class GhostAgent(BaseClass):
    name: str
    initial_position: ActorPosition
    position: ActorPosition
    scared: bool = False
    dead: bool = False
    previous_action: Tuple[int, int] = (0, 0)
    disable_clip: bool = False
    fleeing_since: int = 0
    key: str

    def __init__(self, position: Tuple[int, int]):
        position = ActorPosition(position, (1, 0))
        self.initial_position = deepcopy(position)
        self.position = position

    def set_respawn(self):
        self.dead = True

    def respawn_tick(self):
        if self.position.coordinates == self.initial_position.coordinates:
            self.dead = False
            self.scared = False
            self.fleeing_since = 0

    def get_action(self, state):
        if self.dead:
            return self.go_to_coords(state, self.initial_position.coordinates)
        if self.scared:
            if self.fleeing_since > 10:
                return self.go_to_coords(state, self.initial_position.coordinates)
            self.fleeing_since += 1
            return self.flee_pacman(state)
        if self.disable_clip:
            return self.previous_action

    def flee_pacman(self, state):
        """
        The ghost should flee from Pacman.
        :param state: the game state
        :return: the action that will move the ghost away from Pacman
        """
        pacman_position = state.pacman.position.coordinates
        ghost_position = self.position.coordinates
        actions = self.get_legal_actions(state)
        distances = []
        for action in actions:
            distances.append(manhattan_distance(add_tuples(ghost_position, action), pacman_position))
        return actions[distances.index(max(distances))]

    def get_legal_actions(self, state):
        """
        A ghost can only move in cardinal directions.
        A ghost cannot move backwards.
        A ghost cannot move through a wall.
        A ghost cannot move through a ghost.
        A ghost can only advance one step at a time.

        :return: list of legal actions
        """
        walls = state.layout.walls
        coordinates = self.position.coordinates
        direction = self.position.direction
        actions = []
        if not (coordinates[0] + 1, coordinates[1]) in walls and direction != (-1, 0):
            actions.append((1, 0))
        if not (coordinates[0] - 1, coordinates[1]) in walls and direction != (1, 0):
            actions.append((-1, 0))
        if not (coordinates[0], coordinates[1] + 1) in walls and direction != (0, -1):
            actions.append((0, 1))
        if not (coordinates[0], coordinates[1] - 1) in walls and direction != (0, 1):
            actions.append((0, -1))
        if len(actions) == 0:
            actions.append((direction[0] * -1, direction[1] * -1))
        return actions

    def go_to_coords(self, state, coords):
        actions = self.get_legal_actions(state)
        maze = deepcopy(state.layout.maze)
        if self.position.coordinates != self.initial_position.coordinates:
            previous_position = (self.position.coordinates[1] - self.position.direction[1], self.position.coordinates[0] - self.position.direction[0])
            try:
                maze[previous_position[0]][previous_position[1]] = 1
            except IndexError:
                pass
        shortest_path_to_target = AStar(maze).search((self.position.coordinates[1], self.position.coordinates[0]), (coords[1], coords[0]))
        try:
            next_position = (shortest_path_to_target[1][1], shortest_path_to_target[1][0])
        except (TypeError, IndexError):
            return random.choice(actions)
        vector = (next_position[0] - self.position.coordinates[0], next_position[1] - self.position.coordinates[1])
        if vector in actions:
            return vector
        else:
            return random.choice(actions)

class RandomGhostAgent(GhostAgent):
    """
    A ghost agent that chooses a legal action uniformly at random.
    """

    def get_action(self, state):
        action = super().get_action(state)
        if action is not None:
            return action
        actions = self.get_legal_actions(state)
        return random.choice(actions)

class BlinkyAgent(GhostAgent):
    """
    Chaser ghost, starts outside the box and chases pacman immediately.
    """

    def get_action(self, state):
        action = super().get_action(state)
        if action is not None:
            return action
        return self.go_to_coords(state, state.pacman.position.coordinates)

class PinkyAgent(GhostAgent):
    """
    Ghost that tries to get in front of pacman. Starts inside the box but exits immediately.
    """
    start_at_turn = 5

    def get_action(self, state):
        action = super().get_action(state)
        if action is not None:
            return action
        actions = self.get_legal_actions(state)
        if state.turn < self.start_at_turn:
            if self.previous_action == (0, 0):
                self.previous_action = random.choice(actions)
                return self.previous_action
            else:
                self.previous_action = reverse_tuple(self.previous_action)
                return self.previous_action
        way_ahead = state.predict_pacman_position(3)
        return self.go_to_coords(state, way_ahead.pacman.position.coordinates)

class InkyAgent(GhostAgent):
    """
    Ghost setting up ambushes. Starts inside the box and exits after 30 fruit have been eaten.

    Draw a vector from blinky to 2 tiles in front of pacman, then double it. This is the target position for inky.
    """
    needed_food_to_start = 10

    def get_action(self, state):
        action = super().get_action(state)
        if action is not None:
            return action
        actions = self.get_legal_actions(state)
        if state.layout.initial_food_count - len(state.layout.food) < self.needed_food_to_start:
            if self.previous_action == (0, 0):
                self.previous_action = random.choice(actions)
                return self.previous_action
            else:
                self.previous_action = reverse_tuple(self.previous_action)
                return self.previous_action
        return self.go_to_coords(state, state.pacman.position.coordinates)

class ClydeAgent(GhostAgent):
    """
    Hard to predict ghost. Starts inside the box and exits after a third of the fruit have been eaten.

    If clyde is more than 8 tiles away from pacman, he will target him.
    Else, he will flee him
    """

    def get_action(self, state):
        action = super().get_action(state)
        if action is not None:
            return action
        actions = self.get_legal_actions(state)
        if state.layout.initial_food_count - len(state.layout.food) < state.layout.initial_food_count / 3:
            if self.previous_action == (0, 0):
                self.previous_action = random.choice(actions)
                return self.previous_action
            else:
                self.previous_action = reverse_tuple(self.previous_action)
                return self.previous_action
        if manhattan_distance(state.pacman.position.coordinates, self.position.coordinates) > 8:
            return self.go_to_coords(state, state.pacman.position.coordinates)
        else:
            return self.flee_pacman(state)


import  sqlite3

data_base = sqlite3.connect('db.sqlite3')

b=[]
cursor=data_base.cursor()
# cur=cursor.execute('SELECT * FROM jenkinsjob_jenkinsjob;')
# print(cur.fetchall())
with open('check.txt','r') as f:
    for i in f:
        a=tuple(i.strip('\n').split(','))
        b.append(a)

cursor.executemany('INSERT INTO workorder_projectcheck(business_name,module_title,project_title,hostip,port,check_url) VALUES (?,?,?,?,?,?);',b)
cur=cursor.execute('SELECT * FROM workorder_projectcheck;')
print(cur.fetchall())
cursor.close()
data_base.commit()


from unittest import TestCase
from unittest.mock import MagicMock, patch

from ..management.commands.qworker import Command

class QworkerManagementCommandTest(TestCase):
    def setUp(self) -> None:
        self.command = Command()

    @patch("quantum_web.worker.management.commands.qworker.QuantumListener.run")
    def test_handle(self, run_mock: MagicMock):
        self.command.handle()
        run_mock.assert_called_once()


import sys
import os
import pystache

class Template(object):

    """docstring for Template"""

    def __init__(self, path_template, header, doc, offset=0):
        super(Template, self).__init__()
        if path_template is None:
            path_template = os.path.join(
                sys.path[0], "template", "default_template.html")
        with open(path_template, "r") as template:
            template = template.read()

        renderer = pystache.Renderer()
        self.html = renderer.render(
            template, {"offset": offset, "header": header, "doc": doc})

    def get_html(self):
        return self.html


maxCal  = 0
currCal = 0
with open("./data.txt", "r") as d:
    for data in d.readlines():
        if data != "\n":
            currCal += int(data)
        else:
            maxCal = max(maxCal,currCal)
            currCal = 0

print(maxCal)


"""
967 Numbers With Same Consecutive Differences

Return all non-negative integers of length N such that the absolute difference between every two consecutive digits is K.
Note that every number in the answer must not have leading zeros except for the number 0 itself. For example, 01 has one leading zero and is invalid, but 0 is valid.
You may return the answer in any order.

Example 1:

Input: N = 3, K = 7
Output: [181,292,707,818,929]
Explanation: Note that 070 is not a valid number, because it has leading zeroes.
Example 2:

Input: N = 2, K = 1
Output: [10,12,21,23,32,34,43,45,54,56,65,67,76,78,87,89,98]

Note:

1 <= N <= 9
0 <= K <= 9
"""
class Solution:
    # https://leetcode.com/problems/numbers-with-same-consecutive-differences/solution/
    def numsSameConsecDiff(self, N, K):
        ans = {x for x in range(1, 10)}
        for _ in range(N-1):
            ans2 = set()
            for x in ans:
                d = x % 10  # trick: we don't need a list to store all digits, we just use % to get the digit
                if d - K >= 0:
                    ans2.add(10*x + d-K)
                if d + K <= 9:
                    ans2.add(10*x + d+K)
            ans = ans2

        if N == 1:
            ans.add(0)

        return list(ans)

    # my own solution
    def numsSameConsecDiff2(self, N, K):
        """
        :type N: int
        :type K: int
        :rtype: List[int]
        """
        def num(build):
            """
            convert all digits in build list to an integer
            """
            ans, factor = 0, 1
            for i in range(len(build)-1, -1, -1):
                ans += factor*build[i]
                factor *= 10

            return ans

        def dfs(build, K, remain, res):
            if remain == 0:
                res.append(num(build))
                return
            last = build[-1]
            if last + K < 10:
                build.append(last + K)
                dfs(build, K, remain - 1, res)
                build.pop()
            if K != 0 and last - K > -1:
                build.append(last - K)
                dfs(build, K, remain-1, res)
                build.pop()

        # main
        build, res = [], []
        for x in range(0 if N == 1 else 1, 10): # bug fixed: missed corner case when N == 1, should include 0
            build.append(x)
            dfs(build, K, N-1, res)
            build.pop()

        return res

print(Solution().numsSameConsecDiff(1, 0))


from html.parser import HTMLParser
from collections import Counter, deque
from sys import stdin
accepted = deque([], maxlen=9)
failed = []
out = []
out_append = out.append
ac_append = accepted.append
failed_append = failed.append

class MyHTMLParser(HTMLParser):
    def handle_data(self, data):
        k = [bool(x) for x in accepted]
        data = data.strip()
        if data == 'Accepted':
            datas[accepted[-2]] += 1
        elif len(k) == 9 and k[0] and k[1] and k[2] and k[3] and not k[4] and not k[5] and k[6] and k[7] and k[8]:
            failed_append(accepted[1])
        data = data.replace('\n', '')
        ac_append(data)

parser = MyHTMLParser()
datas = Counter()
parser.feed(''.join(stdin))
t = None
for x, y in datas.most_common():
    if t is None:
        t = y
    elif t != y:
        break
    out_append(x)
out.sort()
try:
    print(out[0], t, sep=': ')
except IndexError:
    failed.sort()
    print('{}: 0'.format(failed[0]))


from .validators import ValidateAPIKey

class Content(object):
    """Content to be included in your email.

    You must specify at least one mime type in the Contents of your email.
    """

    def __init__(self, type_=None, value=None):
        """Create a Content with the specified MIME type and value.

        :param type_: MIME type of this Content (e.g. "text/plain").
        :type type_: string, optional
        :param value: The actual content.
        :type value: string, optional
        """
        self._type = None
        self._value = None
        self._validator = ValidateAPIKey()

        if type_ is not None:
            self.type = type_

        if value is not None:
            self.value = value

    @property
    def type(self):
        """The MIME type of the content you are including in your email.

        For example, "text/plain" or "text/html".

        :rtype: string
        """
        return self._type

    @type.setter
    def type(self, value):
        self._type = value

    @property
    def value(self):
        """The actual content (of the specified mime type).

        :rtype: string
        """
        return self._value

    @value.setter
    def value(self, value):
        self._validator.validate_message_dict(value)
        self._value = value

    def get(self):
        """
        Get a JSON-ready representation of this Content.

        :returns: This Content, ready for use in a request body.
        :rtype: dict
        """
        content = {}
        if self.type is not None:
            content["type"] = self.type

        if self.value is not None:
            content["value"] = self.value
        return content


# Title: Wikipedia Scraper
# Class: CS 361 - Software Engineering I
# Author: Mallory Huston
# Description: A wikipedia scraper microservice that pulls up any information of a
#              category of your choosing.

from tkinter import *
import wikipedia as wiki
import os

root = Tk()
root.title('Game Development Guide - Category Wikipedia')
root.geometry("700x675")

# Clear
def clear():
    my_entry.delete(0, END)
    my_text.delete(0.0, END)

# Search
def search():
    data = wiki.page(my_entry.get())
    # Clear screen
    clear()
    # Output Wikipedia Results to Textbox
    my_text.insert(0.0, data.content)
    print(f"[wiki] Pulling information from {data.title}")

# Write to File
def writeFile():
    save_path = './information'
    file_name = input("Article name: ") + ".txt"
    # Saving .txt file to the /information directory
    completeName = os.path.join(save_path, file_name)
    file = open(completeName, "a+")
    # Output Wikipedia Results to .txt file
    file.write(my_text.get("1.0", 'end-1c') + '\n')
    file.close()

# Create label frame
my_label_frame = LabelFrame(root, text="Search Category")
my_label_frame.pack(pady=20)

# Create entry box
my_entry = Entry(my_label_frame, font=("Helvetica", 18), width=47)
my_entry.pack(pady=20, padx=20)

# Create text box frame
my_frame = Frame(root)
my_frame.pack(pady=5)

# Create vertical scrollbar
text_scroll = Scrollbar(my_frame)
text_scroll.pack(side=RIGHT, fill=Y)

# Create horizontal scrollbar
hor_scroll = Scrollbar(my_frame, orient='horizontal')
hor_scroll.pack(side=BOTTOM, fill=X)

# Create text box
my_text = Text(my_frame, yscrollcommand=text_scroll.set, wrap="none", xscrollcommand=hor_scroll.set)
my_text.pack()

# Configure scrollbars
text_scroll.config(command=my_text.yview)
hor_scroll.config(command=my_text.xview)

# Button Frame
button_frame = Frame(root)
button_frame.pack(pady=10)

# Buttons
search_button = Button(button_frame, text="Lookup", font=("Helvetica", 32), fg="#3a3a3a", command=search)
search_button.grid(row=0, column=0, padx=20)

clear_button = Button(button_frame, text="Clear", font=("Helvetica", 32), fg="#3a3a3a", command=clear)
clear_button.grid(row=0, column=1)

write_button = Button(button_frame, text="Write to File", font=("Helvetica", 32), fg="#3a3a3a", command=writeFile)
write_button.grid(row=0, column=2)

root.mainloop()


from flask_restful import Resource, reqparse
from resources.mongo import MongoDBHoteis
import json

class Hoteis(Resource):

    def __init__(self):
        self.mongo = MongoDBHoteis()
        self.mongo = self.mongo.get_connection_hoteis()

    def get(self):
        hoteis = list()
        #collection_hoteis = self.dbhoteis.get_collection(name='hoteis')
        collection_hoteis = self.mongo.get_collection(name='hoteis')
        for hotel in collection_hoteis.find({}, {"_id": False}):
            hoteis.append(hotel)
        return { 'hoteis': hoteis }, 200

class Hotel(Resource):

    args_req = reqparse.RequestParser(bundle_errors=True)
    args_req.add_argument('nome', type=str, required=True)
    args_req.add_argument('estrelas', type=float, required=True)
    args_req.add_argument('diaria', type=float, required=True)
    args_req.add_argument('cidade', type=str, required=True)

    def __init__(self):
        self.mongo = MongoDBHoteis()
        self.mongo = self.mongo.get_connection_hoteis()
        self._collection_hoteis = self.mongo.get_collection(name='hoteis')

    def get_hotel(self, hotel_id):
        #self._collection_hoteis = self.mongo.get_collection(name='hoteis')
        for hotel in self._collection_hoteis.find({}, {"_id": False}):
            if hotel['hotel_id'] == hotel_id:
                return True
        return False

    def get(self, hotel_id):
        #collection_hoteis = self.mongo.get_collection(name='hoteis')
        for hotel in self._collection_hoteis.find({}, {"_id": False}):
            if hotel['hotel_id'] == hotel_id:
                return hotel, 200
        else:
            return {'message': 'Hotel not found.'}, 404

    def post(self, hotel_id):
        if not hotel_id:
            return {'warnning': 'ERROR'}, 400
        if (self.get_hotel(hotel_id=hotel_id)):
            return {'warnning': 'ID already registred.'}, 409
        hotel = Hotel.args_req.parse_args()
        hotel['hotel_id'] = hotel_id
        try:
            #collection_hoteis = self.mongo.get_collection(name='hoteis')
            self._collection_hoteis.insert_one(hotel)
        except TypeError as err:
            return {'error': str(err)}, 500
        else:
            return {'message': 'success', 'status': 201}, 201

    def put(self, hotel_id):
        if not hotel_id:
            return {'warnning': 'ERROR'}, 400
        hotel = Hotel.args_req.parse_args()
        hotel['hotel_id'] = hotel_id
        try:
            #collection_hoteis = self.mongo.get_collection(name='hoteis')
            if (self.get_hotel(hotel_id=hotel_id)):
                self._collection_hoteis.update_one(filter={ 'hotel_id': hotel_id }, update={ "$set": hotel })
                return { 'new_hotel': hotel }, 200
            self._collection_hoteis.insert_one(hotel)
            return { 'new_hotel': hotel }, 201
        except TypeError as err:
            return {'error': str(err)}, 500

    def delete(self, hotel_id):
        if not hotel_id:
            return {'warnning': 'ERROR'}, 400
        try:
            if (self.get_hotel(hotel_id=hotel_id)):
                self._collection_hoteis.delete_one({'hotel_id': hotel_id})
                return { 'message': 'ID deletado[{}]'.format(hotel_id) }, 200
            return { 'message': 'ID not found.' }, 400
        except TypeError as err:
            return { 'error': str(err) }, 500


# CHAPTER 5: In Depth: k-Means Clustering
# =======================================

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns; sns.set()    # plot formatting

from sklearn.cluster import KMeans
from sklearn.cluster import SpectralClustering
from sklearn.cluster import MiniBatchKMeans
from sklearn.manifold import TSNE

from sklearn.metrics import pairwise_distances_argmin
from sklearn.metrics import accuracy_score
from sklearn.metrics import confusion_matrix

from scipy.stats import mode

from sklearn.datasets import make_blobs
from sklearn.datasets import make_moons
from sklearn.datasets import load_digits
from sklearn.datasets import load_sample_image

# -------------------------------------------------------------

# Clustering algorithms
#   seek to learn, from the properties of the data,
#   an optimal division or discrete labeling of groups of points

# Many clustering algorithms are available in Scikit-Learn and elsewhere,
# perhaps the simplest to understand is an algorithm known as k-means clustering,
#   which is implemented in sklearn.cluster.KMeans

#region Introducing k-Means
# k-means algorithm
#   searches for a predetermined number of clusters
#   within an unlabeled multidimensional dataset

# accomplishes this using a simple conception of what the optimal clustering looks like:
# • The “cluster center”
#       is the arithmetic mean of all the points belonging to the cluster.
# • Each point is closer to its own cluster center than to other cluster centers

# Those two assumptions are the basis of the k-means model

# e.g.
# generate a two-dimensional dataset containing four distinct blobs
# To emphasize that this is an unsupervised algorithm, leave the labels out of the visualization

# from sklearn.datasets import make_blobs
X, y_true = make_blobs(n_samples=300, centers=4, cluster_std=0.60, random_state=0)
plt.scatter(X[:, 0], X[:, 1], s=50); plt.show()

# By eye, it is relatively easy to pick out the four clusters
# k-means algorithm does this automatically
from sklearn.cluster import KMeans
kmeans = KMeans(n_clusters=4)
kmeans.fit(X)
y_kmeans = kmeans.predict(X)

# visualize the results by plotting the data colored by these labels
# also plot the cluster centers as determined by the k-means estimator
plt.scatter(X[:, 0], X[:, 1], c=y_kmeans, s=50, cmap='viridis')
centers = kmeans.cluster_centers_
plt.scatter(centers[:, 0], centers[:, 1], c='black', s=200, alpha=0.5)
plt.show()

# how this algorithm finds these clusters so quickly!
# typical approach to k-means involves
#   an intuitive iterative approach known as expectation–maximization

#endregion

#region k-Means Algorithm: Expectation–Maximization
# expectation–maximization approach consists of the following procedure:
# 1. Guess some cluster centers
# 2. Repeat until converged
#   a. E-Step: assign points to the nearest cluster center
#   b. M-Step: set the cluster centers to the mean

# “E-step” or “Expectation step”
#   involves updating our expectation of which cluster each point belongs to

# “M-step” or “Maximization step”
#   involves maximizing some fitness function that defines the location of the cluster centers—
#   in this case, that maximization is accomplished by taking a simple mean of the data in each cluster

# under typical circumstances,
#   each repetition of the E-step and M-step
#   will always result in a better estimate of the cluster characteristics

# k-means algorithm is simple enough that we can write it in a few lines of code.
# The following is a very basic implementation
from sklearn.metrics import pairwise_distances_argmin

def find_clusters(X, n_clusters, rseed=2):
    # 1. Randomly choose clusters
    rng = np.random.RandomState(rseed)
    i = rng.permutation(X.shape[0])[:n_clusters]
    centers = X[i]

    while True:
        # 2a. Assign labels based on closest center
        labels = pairwise_distances_argmin(X, centers)

        # 2b. Find new centers from means of points
        new_centers = np.array([X[labels == i].mean(0) for i in range(n_clusters)])

        # 2c. Check for convergence
        if np.all(centers == new_centers):
            break
        centers = new_centers

    return centers, labels

centers, labels = find_clusters(X, 4)
plt.scatter(X[:, 0], X[:, 1], c=labels, s=50, cmap='viridis'); plt.show()

# Most well-tested implementations will do a bit more than this under the hood,
#   but the preceding function gives the gist of the expectation–maximization approach

#region Caveats of expectation–maximization
# few issues to be aware of when using the expectation–maximization algorithm

# ---------------------------

# 1.
# globally optimal result may not be achieved
#   although the E–M procedure is guaranteed to improve the result in each step,
#   there is no assurance that it will lead to the global best solution

# e.g.
# if we use a different random seed in our simple procedure,
#   the particular starting guesses lead to poor results
centers, labels = find_clusters(X, 4, rseed=0)
plt.scatter(X[:, 0], X[:, 1], c=labels, s=50, cmap='viridis'); plt.show()

# Here the E–M approach has converged,
#   but has not converged to a globally optimal configuration

# For this reason, it is common for the algorithm to be run for multiple starting guesses,
#   as indeed Scikit-Learn does by default
#   (set by the n_init parameter, which defaults to 10)

# ---------------------------

# 2,
# The number of clusters must be selected beforehand
#   must tell it how many clusters you expect:
#   it cannot learn the number of clusters from the data

# e.g.
# if we ask the algorithm to identify six clusters,
#   it will happily proceed and find the best six clusters
labels = KMeans(6, random_state=0).fit_predict(X)
plt.scatter(X[:, 0], X[:, 1], c=labels, s=50, cmap='viridis'); plt.show()

# Whether the result is meaningful is a question that is difficult to answer definitively

# one approach that is rather intuitive is called silhouette analysis

# Alternatively, you might use a more complicated clustering algorithm
#   which has a better quantitative measure of the fitness per number of clusters
#       (e.g., Gaussian mixture models)
#   or which can choose a suitable number of clusters
#       (e.g., DBSCAN, mean-shift, or affinity propagation,
#       all available in the sklearn.cluster submodule)

# ---------------------------

# 3.
# k-means is limited to linear cluster boundaries
# The fundamental model assumptions of k-means
#   (points will be closer to their own cluster center than to others)
# means that the algorithm will often be ineffective
#   if the clusters have complicated geometries

# e.g.
# following data, along with the cluster labels found by the typical k-means approach
from sklearn.datasets import make_moons
X, y = make_moons(200, noise=.05, random_state=0)

labels = KMeans(2, random_state=0).fit_predict(X)
plt.scatter(X[:, 0], X[:, 1], c=labels, s=50, cmap='viridis'); plt.show()

# use a kernel transformation
#   to project the data into a higher dimension
#   where a linear separation is possible

# One version of this kernelized k-means is implemented in Scikit-Learn within the
#   SpectralClustering estimator
# uses the graph of nearest neighbors to compute a higher-dimensional representation of the data,
#   and then assigns labels using a k-means algorithm

from sklearn.cluster import SpectralClustering
model = SpectralClustering(n_clusters=2, affinity='nearest_neighbors', assign_labels='kmeans')
labels = model.fit_predict(X)
plt.scatter(X[:, 0], X[:, 1], c=labels, s=50, cmap='viridis'); plt.show()

# see that with this kernel transform approach,
#   the kernelized k-means is able to find the more complicated nonlinear boundaries between clusters

# ---------------------------

# 4.
# k-means can be slow for large numbers of samples
# Because each iteration of k-means must access every point in the dataset,
#   the algorithm can be relatively slow as the number of samples grows

# might wonder if this requirement to use all data at each iteration can be relaxed
# e.g.
#   might just use a subset of the data to update the cluster centers at each step

# This is the idea behind batch-based k-means algorithms,
#   one form of which is implemented in sklearn.cluster.MiniBatchKMeans
# interface for this is the same as for standard KMeans

#endregion

#endregion

#region Examples
# Being careful about these limitations of the algorithm,
#   can use k-means to our advantage in a wide variety of situations

#region Example 1: k-Means on digits
# will attempt to use k-means to try to identify similar digits
# without using the original label information;
#   this might be similar to a first step
#   in extracting meaning from a new dataset
#   about which you don’t have any a priori label information

from sklearn.datasets import load_digits
digits = load_digits()
digits.data.shape

kmeans = KMeans(n_clusters=10, random_state=0)
clusters = kmeans.fit_predict(digits.data)
kmeans.cluster_centers_.shape

# result is 10 clusters in 64 dimensions
# cluster centers themselves are 64-dimensional points,
#   and can themselves be interpreted as the “typical” digit within the cluster

fig, ax = plt.subplots(2, 5, figsize=(8, 3))
centers = kmeans.cluster_centers_.reshape(10, 8, 8)
for axi, center in zip(ax.flat, centers):
    axi.set(xticks=[],yticks=[])
    axi.imshow(center, interpolation='nearest', cmap=plt.cm.binary)
plt.show()

# even without the labels,
#   KMeans is able to find clusters whose centers are recognizable digits,
#   with perhaps the exception of 1 and 8

# Because k-means knows nothing about the identity of the cluster,
#   the 0–9 labels may be permuted
# can fix this
#   by matching each learned cluster label
#   with the true labels found in them

from scipy.stats import mode

labels = np.zeros_like(clusters)
for i in range(10):
    mask = (clusters == i)
    labels[mask] = mode(digits.target[mask])[0]

# check how accurate our unsupervised clustering was in finding similar digits within the data

from sklearn.metrics import accuracy_score
accuracy_score(digits.target, labels)

# With just a simple k-means algorithm,
#   we discovered the correct grouping for 80% of the input digits!
# check the confusion matrix for this
from sklearn.metrics import confusion_matrix
mat = confusion_matrix(digits.target, labels)
sns.heatmap(mat.T, square=True, annot=True, fmt='d', cbar=False,
            xticklabels=digits.target_names,
            yticklabels=digits.target_names)
plt.xlabel('true label')
plt.ylabel('predicted label')
plt.show()

# As we might expect from the cluster centers we visualized before,
#   the main point of confusion is between the eights and ones
# But this still shows that using k-means,
#   we can essentially build a digit classifier
#   without reference to any known labels!

# can use the t-distributed stochastic neighbor embedding (t-SNE) algorithm
#   to preprocess the data before performing k-means
# t-SNE is a non‐linear embedding algorithm
#   that is particularly adept at preserving points within clusters
from sklearn.manifold import TSNE

# Project the data: this step will take several seconds
tsne =TSNE(n_components=2, init='pca', random_state=0)
digits_proj = tsne.fit_transform(digits.data)

# Compute the clusters
kmeans = KMeans(n_clusters=10, random_state=0)
clusters = kmeans.fit_predict(digits_proj)

# Permute the labels
labels = np.zeros_like(clusters)
for i in range(10):
    mask = (clusters == i)
    labels[mask] = mode(digits.target[mask])[0]

# Compute the accuracy
accuracy_score(digits.target, labels)

# That’s nearly 94% classification accuracy without using the labels
# This is the power of unsupervised learning when used carefully:
#   it can extract information from the data‐set
#   that it might be difficult to do by hand or by eye

#endregion

#region Example 2: k-means for color compression
# One interesting application of clustering is in color compression within images

# e.g.
# image with millions of colors.
# In most images,
#   a large number of the colors will be unused,
#   and many of the pixels in the image will have similar or even identical colors

# e.g.
# Note: this requires the pillow package to be installed
from sklearn.datasets import load_sample_image
china = load_sample_image('china.jpg')
ax = plt.axes(xticks=[], yticks=[])
ax.imshow(china)
plt.show()

# image itself is stored in a three-dimensional array of size (height, width, RGB),
#   containing red/blue/green contributions as integers from 0 to 255
china.shape

# One way we can view this set of pixels
#   is as a cloud of points in a three-dimensional color space
# will reshape the data to [n_samples x n_features],
#   and rescale the colors so that they lie between 0 and 1

data = china / 255.0    # use 0...1 scale
data = data.reshape(427 * 640, 3)
data.shape

# visualize these pixels in this color space,
#   using a subset of 10,000 pixels for efficiency
def plot_pixels(data, title, colors=None, N=10000):
    if colors is None:
        colors = data

    # choose a random subset
    rng = np.random.RandomState(0)
    i = rng.permutation(data.shape[0])[:N]
    colors = colors[i]
    R, G, B = data[i].T

    fig, ax = plt.subplots(1, 2, figsize=(16, 6))
    ax[0].scatter(R, G, color=colors, marker='.')
    ax[0].set(xlabel='Red', ylabel='Green', xlim=(0, 1), ylim=(0, 1))

    ax[1].scatter(R, B, color = colors, marker='.')
    ax[1].set(xlabel='Red', ylabel='Blue', xlim=(0, 1), ylim=(0, 1))

    fig.suptitle(title, size=20)

plot_pixels(data, title='Input color space: 16 million possible colors'); plt.show()

# let’s reduce these 16 million colors to just 16 colors,
#   using a k-means clustering across the pixel space
# Because we are dealing with a very large dataset,
#   we will use the mini batch k-means,
#       which operates on subsets of the data
#       to compute the result much more quickly than the standard k-means algorithm

from sklearn.cluster import MiniBatchKMeans
kmeans = MiniBatchKMeans(16)
kmeans.fit(data)
new_colors = kmeans.cluster_centers_[kmeans.predict(data)]

plot_pixels(data, colors=new_colors, title='Reduced color space: 16 colors'); plt.show()

# result is a recoloring of the original pixels,
#   where each pixel is assigned the color of its closest cluster center
# Plotting these new colors in the image space
#   rather than the pixel space
#   shows us the effect of this
china_recolored = new_colors.reshape(china.shape)

fig, ax = plt.subplots(1, 2, figsize=(16, 6), subplot_kw=dict(xticks=[], yticks=[]))
fig.subplots_adjust(wspace=0.05)
ax[0].imshow(china)
ax[0].set_title('Original Image', size=16)
ax[1].imshow(china_recolored)
ax[1].set_title('16-color Image', size=16)
plt.show()

# Some detail is certainly lost in the rightmost panel,
#   but the overall image is still easily recognizable
# This image on the right achieves a compression factor of around 1 million!
# While this is an interesting application of k-means,
#   there are certainly better way to compress information in images

#endregion

#endregion


import random

coinUser, coinBot = 10, 10
roundOfGames = 0

def bet(dice, userin):
    if dice > 7:
        if userin == 's':
            print('the dice is: ' + str(dice), ', you lost!')
            return -1
        else:
            print('the dice is: ' + str(dice), ', you win!')
            return 1
    elif dice == 7:
        print('the dice is: ' + str(dice), ', draw!')
        return 0
    elif dice < 7:
        if userin == 's':
            print('the dice is: ' + str(dice), ', you win!')
            return 1
        else:
            print('the dice is: ' + str(dice), ', you lost!')
            return -1

while True:
    print('your coin: ' + str(coinUser), "'bot's coin: " + str(coinBot))
    dice = random.randrange(2, 13)
    userin = input("what's your bet?")
    if coinUser == 0:
        print("woops, you've lost all, game over!")
        break
    elif coinBot == 0:
        print("woops, bot's lost all, game over!")
        break
    elif userin == 'q':
        print("you quit the game!")
        break
    elif userin in 'bs':
        result = bet(dice, userin)
        coinUser += result
        coinBot -= result
        roundOfGames += 1
    else:
        print('you must input the right things!')

print("you've played " + str(roundOfGames), ' rounds\n',
      "you have " + str(coinUser) + ' coins now. bye!')


from matplotlib import colors
import matplotlib.pyplot as plt

days = [1,2,3,4,5]

sleeping =  [7,8,6,11,7]
eating =    [2,3,4,3,2]
working =   [7,8,7,2,2]
playing =   [8,5,7,8,13]

slices = [7,2,2,13]
activities = ['sleeping','eating','working','playing']
cols = ['c','m','r','b']

# Create pie chart that starts at 90 degress, has one section exploaded out, and percent values
plt.pie(slices,
        labels=activities,
        colors=cols,
        startangle=90,
        shadow=True,
        explode=(0,0.1,0,0),
        autopct='%1.1f%%')

plt.title('Graph')
plt.show()


from django.shortcuts import render
from django.http import HttpResponse, JsonResponse
from django.views.generic import ListView, UpdateView

from .forms import CustomUserForm
from django.contrib.auth.decorators import login_required, permission_required
from .models import ViewHabitaciones, Habitacion, TipoHabitacion, EstadoHabitacion, ViewEmpleados, Empleados, \
    TipoEmpleado, EstadoEmpleado

# Create your views here.

# Usuario
@login_required
def homeadmin(request):
    return render(request, "baseadmin.html")

@login_required
def adminusuario(request):
    data = {
        'form': CustomUserForm()

    }

    if request.method == 'POST':
        formulario = CustomUserForm(request)

    return render(request, 'usuario/Admin_Usuario.html', data)

@login_required
def listausuario(request):
    return render(request, 'usuario/Listado_Usuario.html')

# Habitacion
@login_required
def adminhabit(request):
    tiposhab = TipoHabitacion.objects.all()
    estadohab = EstadoHabitacion.objects.all()
    variables = {
        'tiposhab': tiposhab,
        'estadohab': estadohab
    }
    if request.method == 'POST':
        hab_tam = request.POST["txtTam"]
        hab_prec = request.POST["txtPrecio"]
        hab_banno = request.POST["cbobano"]
        hab_estado = request.POST["cboestado"]
        hab_tipo = request.POST["cbotipo"]
        habitacion = Habitacion(tamanno_hab=hab_tam, banno_privado=hab_banno, precio_hab=hab_prec,
                                id_estado_habitacion=hab_estado, id_tipohabitacion=hab_tipo)
        habitacion.save()
    return render(request, 'habitacion/addhab.html', variables)

class ViewListHabitacion(ListView):
    model = ViewHabitaciones
    template_name = 'habitacion/Listado_Habitacion.html'

    def post(self, request, *args, **kwargs):
        data = {}
        hab = Habitacion.objects.get(id_habitacion=request.POST['id'])
        hab.id_estado_habitacion = 3
        hab.save()
        data['Estado'] = hab.id_estado_habitacion
        return JsonResponse(data)

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['habitaciones'] = ViewHabitaciones.objects.all()
        return context

@login_required
def updatehabit(request, id):
    tiposhab = TipoHabitacion.objects.all()
    estadohab = EstadoHabitacion.objects.all()
    habi = Habitacion.objects.get(id_habitacion=id)
    variables = {
        'tiposhab': tiposhab,
        'estadohab': estadohab,
        'habi': habi
    }
    if request.method == 'POST':
        habi.tamanno_hab = request.POST["txtTam"]
        habi.precio_hab = request.POST["txtPrecio"]
        habi.banno_privado = request.POST["cbobano"]
        habi.id_estado_habitacion = request.POST["cboestado"]
        habi.id_tipohabitacion = request.POST["cbotipo"]
        habi.save()
    return render(request, 'habitacion/updatehab.html', variables)

# Empleado
@login_required
def adminempleado(request):
    tiposemp = TipoEmpleado.objects.all()
    estadoemp = EstadoEmpleado.objects.all()
    variables = {
        'tiposemp': tiposemp,
        'estadoemp': estadoemp
    }
    if request.method == 'POST':
        emp = Empleados()
        emp.rut_emp = request.POST['rut_emp']
        emp.id_tipoempleado = request.POST["cbotipo"]
        emp.id_estadoempleado = request.POST["cboestado"]
        emp.nombres_emp = request.POST["primernombre"] + " " + request.POST["segundonombre"]
        emp.apellidos_emp = request.POST["primerapellido"] + " " + request.POST["segundoapellido"]
        emp.fono_emp = request.POST['fono_emp']
        emp.email_emp = request.POST['email_emp']
        emp.fechanac_emp = request.POST['fechanac']
        emp.save()
    return render(request, 'empleados/addemp.html', variables)

class ViewListaEmpleado(ListView):
    model = ViewEmpleados
    template_name = 'empleados/Listado_Empleado.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['empleados'] = ViewEmpleados.objects.all()
        return context

    def post(self, request, *args, **kwargs):
        data = {}
        emp = Empleados.objects.get(rut_emp=request.POST['rut'])
        emp.id_estadoempleado = 3
        emp.save()
        data['Estado emp'] = emp.id_estadoempleado
        return JsonResponse(data)

@login_required
def updateempleado(request, id):
    tiposemp = TipoEmpleado.objects.all()
    estadoemp = EstadoEmpleado.objects.all()
    emp = Empleados.objects.get(id_empleado=id)
    variables = {
        'tiposemp': tiposemp,
        'estadoemp': estadoemp,
        'emp': emp
    }
    if request.method == 'POST':
        emp.rut_emp = request.POST['rut_emp']
        emp.id_tipoempleado = request.POST["cbotipo"]
        emp.id_estadoempleado = request.POST["cboestado"]
        emp.nombres_emp = request.POST["nombres_emp"]
        emp.apellidos_emp = request.POST["apellidos_emp"]
        emp.fono_emp = request.POST['fono_emp']
        emp.email_emp = request.POST['email_emp']
        emp.fechanac_emp = request.POST['fechanac']
        emp.save(force_update=True)
    return render(request, 'empleados/updemp.html', variables)

@login_required
def pedidos(request):
    return render(request, 'informes/InformePedido.html')

def productos(request):
    return render(request, 'informes/InformeProductos.html')


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

__author__ = 'Quan Zhang'

import time
import subprocess

while True:
    command = 'python ./manage.py email_sender'
    subprocess.call(command, shell=True)
    time.sleep(15)


from random import randint
from typing import Any, Dict

from sqlalchemy.orm import Session

from app.choices.cost_unit import COST_UNIT_TYPES
from app.db_models.item import Item
from app.tests.factory.base import Base

class ItemFactory(Base):
    def __init__(self, shop_id: str, owner_id: int) -> None:
        self.id = None
        self.name = self.random_lower_string()
        self.cost = self.random_integer()
        self.cost_unit = COST_UNIT_TYPES[randint(0, len(COST_UNIT_TYPES) - 1)][0]
        self.shop_id = shop_id
        self.owner_id = owner_id
        self.item_available = None

    def create(self, db: Session):
        item = Item(
            name=self.name,
            cost=self.cost,
            cost_unit=self.cost_unit,
            shop_id=self.shop_id,
            owner_id=self.owner_id,
        )
        db.add(item)
        db.commit()
        db.refresh(item)
        self.id = item.id
        self.item_available = item.item_available

    def update(self, db: Session, values: Dict[str, Any]):
        item: Item = db.query(Item).filter_by(id=self.id).first()
        for key in values:
            setattr(item, key, values[key])
        db.add(item)
        db.commit()
        db.refresh(item)
        for key in values:
            setattr(self, key, getattr(item, key))


import subprocess

def install_libraries(libraries):
    for library in libraries:
        try:
            __import__(library)
        except ImportError:
            print(f"{library} is not installed. Installing now...")
            subprocess.check_call(["pip", "install", library])
required_libraries = ["pyautogui", "mysql.connector", "tqdm", "colorama"]
install_libraries(required_libraries)

from pyautogui import *
import pyautogui
import mysql.connector
from tqdm import tqdm
from datetime import datetime
import time
import keyboard
import win32api, win32con
import mouse
import math
import os
import uuid
from dateutil.relativedelta import relativedelta
import colorama
from colorama import Fore, Back, Style

print(Fore.YELLOW +'''
  /$$$$$$  /$$$$$$$$ /$$$$$$        /$$    /$$       /$$                           /$$
 /$$__  $$|__  $$__//$$__  $$      | $$   | $$      | $$                          | $$
| $$  \__/   | $$  | $$  \ $$      | $$   | $$      | $$$$$$$  /$$   /$$ /$$$$$$$ | $$   /$$ /$$   /$$
| $$ /$$$$   | $$  | $$$$$$$$      |  $$ / $$/      | $$__  $$| $$  | $$| $$__  $$| $$  /$$/| $$  | $$
| $$|_  $$   | $$  | $$__  $$       \  $$ $$/       | $$  \ $$| $$  | $$| $$  \ $$| $$$$$$/ | $$  | $$
| $$  \ $$   | $$  | $$  | $$        \  $$$/        | $$  | $$| $$  | $$| $$  | $$| $$_  $$ | $$  | $$
|  $$$$$$/   | $$  | $$  | $$         \  $/         | $$$$$$$/|  $$$$$$/| $$  | $$| $$ \  $$|  $$$$$$$
 \______/    |__/  |__/  |__/          \_/          |_______/  \______/ |__/  |__/|__/  \__/ \____  $$
                                                                                /$$  | $$
                                                                                |  $$$$$$/
                                                                                \______/

                                                                                GTAV Automatic Bunker Research bot by arkis0

'''+ Style.RESET_ALL)

mydb = mysql.connector.connect(
    host="",
    user="",
    password="",
    database=""
    )
mycursor = mydb.cursor()

mac_address = uuid.UUID(int=uuid.getnode()).hex[-12:]

now = datetime.now()
current_date_str = now.strftime('%Y-%m-%d %H:%M:%S')
current_date = datetime.strptime(current_date_str, '%Y-%m-%d %H:%M:%S')

sql = "SELECT * FROM license_keys WHERE mac_address = %s AND valid = 1"
mycursor.execute(sql, (mac_address,))

# Get info if license key is valid
myresult = mycursor.fetchone()

if myresult is not None:
    if myresult[2] != '':
        if myresult[4] > current_date:
            print("License key is valid!")
        else:
            print("License key has expired.")
            validation_update_sql = "UPDATE license_keys SET valid = 0 WHERE mac_address = %s"
            mycursor.execute(validation_update_sql, (mac_address,))
            mydb.commit()
            exit()
    else:
        print("License key is empty.")
else:
    print("No valid license key found for this device.")
    print("Do you have a license key? (y/n)")
    answer = input()
    if answer == 'y' or answer == 'Y':
        print("Enter license key:")
        license_key = input()
        key_sql = "SELECT * FROM license_keys WHERE license_key = %s AND valid = 1"
        mycursor.execute(key_sql, (license_key,))

        # Get info if license key is valid
        myresult_key = mycursor.fetchone()
        if myresult_key is None:
            print("License key is not valid.")
            exit()
        elif myresult_key[1] is not None:
            print("License key is already assigned to another device.")
            exit()
        if myresult_key[6] != 0:
            expiration_date = current_date + relativedelta(months=myresult_key[6])
        elif myresult_key[6] == 0:
            expiration_date = datetime.strptime('9999-12-31 23:59:59', '%Y-%m-%d %H:%M:%S')

        sql = "UPDATE license_keys SET mac_address = %s, registration_date = %s, expiration_date = %s WHERE license_key = %s"

        mycursor.execute(sql, (mac_address, current_date, expiration_date, license_key))
        mydb.commit()
        print("License key was assigned to your device! Your key will expire on:", expiration_date)
    if answer == 'n' or answer == 'N':
        print("You can buy license key from owner by contacting him on discord: .arkis / arkis#0001")
        exit()

begin_position = False

def click(x,y):
    win32api.SetCursorPos((x,y))
    win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN,0,0)
    time.sleep(0.5)
    win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP,0,0)

def buy_resources():
    time.sleep(2)
    click(458, 494) #zakładka odnawiania
    time.sleep(2)
    click(967, 791) #przycisk kup zasoby
    time.sleep(2)
    click(1070, 620) #potwierdź zakup
    time.sleep(2)
    keyboard.press_and_release('esc') #powrót na home screen
    keyboard.press_and_release('esc') #swobodny widok
    print("Resources were ordered!")

def check_progress_of_research():

    print("Checking progress of research...")
    mydb = mysql.connector.connect(
    host="",
    user="",
    password="",
    database=""
    )
    mycursor = mydb.cursor()

    x = 993
    y = 329
    matching_pixels_research = 0
    total_pixels = 597
    step_size = 4

    for i in tqdm(range(0, total_pixels, step_size)):
        if pyautogui.pixelMatchesColor(x + i, y, (46,135,46)):
            matching_pixels_research += 4

    research_level = math.ceil((matching_pixels_research / total_pixels) * 100)

    print("You have around", research_level, "% of completion on research")

    sql = "INSERT INTO research (research_level) VALUES (%s)"
    mycursor.execute(sql, (research_level,))

    mydb.commit()

def screenshot_of_current_project():
    mydb = mysql.connector.connect(
    host="",
    user="",
    password="",
    database=""
    )
    mycursor = mydb.cursor()
    #? Usuń ostatni rekord z bazy danych
    sql = "DELETE FROM research_screenshots ORDER BY id DESC LIMIT 1"
    mycursor.execute(sql)
    mydb.commit()

    print("Taking screenshot of current project...")
    click(468, 559)
    sleep(1)
    screenshot = pyautogui.screenshot(region=(1233, 468, 360, 360))
    screenshot.save("screenshot.png")
    print("Sending image to database...")

    command = 'curl -X POST -F "image=@screenshot.png" https://r-dev.pl/save_screenshot.php'
    result = subprocess.run(command, shell=True, capture_output=True, text=True)

    if os.path.exists("screenshot.png"):
        os.remove("screenshot.png")

    if result.returncode == 0:
        print("Screenshot was saved to database")
    else:
        print("Error saving screenshot to database")
    keyboard.press_and_release('esc') #powrót na home screen

def check_amount_of_resources():
    print("Checking amount of resources...")
    mydb = mysql.connector.connect(
    host="",
    user="",
    password="",
    database=""
    )
    mycursor = mydb.cursor()
    x = 993
    y = 380
    matching_pixels_resources = 0
    total_pixels = 597

    step_size = 4
    for i in tqdm(range(0, total_pixels, step_size)):
        if pyautogui.pixelMatchesColor(x + i, y, (179, 57, 9)):
            matching_pixels_resources += 4

    resource_amount = math.ceil((matching_pixels_resources / total_pixels) * 100)

    print("You have around", resource_amount, "% of resources")
    if(resource_amount <= 30):
        print("You need to order more resources")
        buy_resources()
    else:
        print("You have sufficient amount of resources")
        keyboard.press_and_release('esc')

    sql = "INSERT INTO resources (resources_amount) VALUES (%s)"
    mycursor.execute(sql, (resource_amount,))
    mydb.commit()

time.sleep(2)

starting_setup = False
last_buy_time = 0
print("Bot won't start until you enter laptop home screen!")
while keyboard.is_pressed('q') == False:
    while starting_setup == False:
        if pyautogui.locateOnScreen('laptop_home_screen_logo.png', region=(0, 0, 1919, 1079), grayscale=True, confidence=0.8) != None:
            print("Laptop home screen detected! Bot is starting")
            starting_setup = True
            time.sleep(0.5)
            click(941, 645)

    check_progress_of_research()
    screenshot_of_current_project()
    check_amount_of_resources()
    time_of_check = time.time()
    print("Anti-kick started working! Next resource check in 15 minutes. Message from: ", time.ctime())
    while time.time() - time_of_check <= 900:
        if pyautogui.locateOnScreen('kick_time.png', region=(0, 0, 820, 1079), grayscale=True, confidence=0.8) != None:
            print("Kick message detected. Proceeding with activity")
            mouse.drag(0, 630, 1919, 630, absolute=True, duration=2)
            mouse.drag(1919, 630, 0, 630, absolute=True, duration=2)
            activity_detected = False
            while activity_detected == False:
                if pyautogui.locateOnScreen('kick_time.png', region=(0, 0, 820, 1079), grayscale=True, confidence=0.8) == None:
                    print("Activity was detected by game")
                    activity_detected = True

                else:
                    print("Activity was not detected by game! Retrying")
                    mouse.drag(0, 630, 1919, 630, absolute=True, duration=2)
                    mouse.drag(1919, 630, 0, 630, absolute=True, duration=2)
    keyboard.press_and_release('enter')
    time.sleep(3)
    if pyautogui.locateOnScreen('laptop_home_screen_logo.png', region=(0, 0, 1919, 1079), grayscale=True, confidence=0.8) != None:
            print("Laptop home screen detected!")
            time.sleep(0.5)
            click(941, 645)


import sys
import glob
from datetime import datetime, timedelta
from expressions import ExpressionSolver, ExpressionTree, InfixToPostfix

class Loader:
	def __init__(self, message):
		self.message = message

	def __enter__(self):
		print('Loading {}... '.format(self.message), end='')

	def __exit__(self, type, value, traceback):
		print('Done!')

words = {}

units = [
	"zero", "one", "two", "three", "four", "five", "six", "seven", "eight",
	"nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen",
	"sixteen", "seventeen", "eighteen", "nineteen",
]
tens = ["", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"]
scales = ["hundred", "thousand", "million", "billion", "trillion"]

words["and"] = (1, 0)
words["a"] = (1, 2)
words["few"] = (1, 2)
for i, word in enumerate(units): words[word] = (1, i)
for i, word in enumerate(tens): words[word] = (1, i * 10)
for i, word in enumerate(scales): words[word] = (10 ** (i * 3 or 2), 0)

def textToInt(text):
	text = text.replace('-', ' ')

	current = result = 0
	for word in text.split():
		if word not in words:
			return None
		scale, increment = words[word]
		current = current * scale + increment
		if scale > 100:
			result += current
			current = 0

	return result + current

times = {'noon': 12, 'afternoon': 15, 'midnight': 0, 'sunrise': 6, 'sunset': 18, 'dawn': 6, 'dusk': 18}
dayOffsets = {'today': 0, 'tomorrow': 1, 'next week': 7, 'next month': 31, 'next year': 365}

def getDate(date=None):
	if date == None:
		date = datetime.now()
	return date.replace(microsecond=0)

def convertDate(date):
	return date.strftime('%A, %b %d, %Y at %H:%M:%S %p')

def dateFromNow(amount, units):
	try:
		amount = int(amount)
	except:
		amount = textToInt(amount)
	if units[-1] != 's':
		units += 's'
	return getDate() + timedelta(**{ units: amount })

def dateWithOffset(h, m, s, ampm, timeOfDay, offset):
	h = int(h) if h else 0
	m = int(m) if m else 0
	s = int(s) if s else 0
	if timeOfDay:
		date = getDate().replace(hour=times[timeOfDay], minute=0, second=0)
	else:
		date = getDate().replace(hour=h, minute=m, second=s)
		if ampm and ampm == 'pm':
			date += timedelta(hours=12)
	if offset:
		date += timedelta(days=dayOffsets[offset])
	return date

def checkDatabase(info, chatId, public, type):
	db = glob.db
	addChatUser = False
	if (chatId, type) not in glob.chats:
		print('Adding Chat: ' + str(chatId))
		addChatUser = True
		db.addChat(chatId, type, public)
		glob.chats[(chatId, type)] = True
	if (info['id'], type) not in glob.users:
		print('Adding User: ' + str(info['id']))
		addChatUser = True
		db.addUser(info['id'], info['first_name'], info['last_name'], info['username'], type)
		glob.users[(info['id'], type)] = True
		glob.messageAdmins('New {} User: {} {}: {} ({})'.format(glob.PLATFORMS[type], info['first_name'], info['last_name'], info['username'], chatId))
	if addChatUser:
		print('Adding Chat User:', chatId, ',', info['id'])
		db.addChatUser(db.getChat(chatId, type)['id'], db.getUser(info['id'], type)['id'])
	return (db.getUser(info['id'], type), db.getChat(chatId, type))

def hash(s):
	ans = 1125899906842597
	for c in s:
		ans = ans * 31 + ord(c)
	return (ans & 0xFFFFFFFFFFFFFFF) ^ ((ans & (0xFFFFFFFFFFFFFFF << 32)) >> 32)

def getInfix(exp):
	i = InfixToPostfix(exp)
	try:
		return i.genPostfix()
	except:
		return None

def getPostfix(exp):
	try:
		e = ExpressionTree(exp)
		return e.eval()
	except:
		return None

def calculate(exp):
	exp = exp.replace('times', '*').replace('minus', '-').replace('to the', '^').replace('power', '').replace('divided by', '/').replace('plus', '+').replace('th', '')
	try:
		e = ExpressionSolver(exp)
		return e.solve()
	except:
		return None


def example(fun):
    print("Applying the wrapper")

    def wrapper(*args, **kwargs):
        print("Running the wrapped function")
        value = fun(*args, **kwargs)
        print("Calculation done!")
        return value

    # it's good practice to do this
    wrapper.__name__ = fun.__name__
    return wrapper

@example
def hello():
    print("hello!")

if __name__ == "__main__":
    hello()
    print(hello.__name__)


# Python: 3.8.2
# Author: Alex Moffat
# Purpose: Assignments in Tech Academy Boot Camp: Inheritance
# Tags: class, parent, child
#=============================================================
'''
Requirements:
Create two classes that inherit from another class.
Each child should have at least two of their own attributes.
'''

#===== PARENT CLASS - pet
class pet:
    def __init__ (self, iName, iAnimal, iBreed, iAge, iFeed):
        self.name = iName
        self.animal = iAnimal
        self.breed = iBreed
        self.age = iAge
        self.feed = iFeed

#===== CHILD CLASS - chicken <-- pet
class chicken(pet):
    production = False
    daily = 0
    roostPosition = 0

#===== CHILD CLASS - dog <-- pet
class dog(pet):
    tricks = []
    treat = "Greenies"
    bed = "Pillow"

#===== CHILD CLASS - cat <-- pet
class cat(pet):
    def __init__ (self, iName, iAnimal, iBreed, iAge, iFeed, iPlayTime, iNapTime):
        super().__init__(iName, iAnimal, iBreed, iAge, iFeed)
        self.playTime = iPlayTime
        self.napTime = iNapTime

#===== INSTANTIATE - pet objects
def createObjects():
    global petList
    ch1 = chicken('Plurp','Chicken', 'SIlver Wyndotte', 1.2, 'grain with oyster shell')
    ch2 = chicken('Nug','Chicken', 'Rhode Island Red', 1.2, 'grain with oyster shell')
    d1 = dog('Albert','Dog', 'Norwich Terrier', 12.6, 'ground lamb & grain free kibble')
    d2 = dog('Gretchen','Dog', 'Norwich Terrier', 2.5, 'ground lamb & grain free kibble')
    c1 = cat('Zuli','Cat', 'Balinese', 0.8, 'tuna & grain free kibble','11:00', '14:00')
    ch1.roostPosition = 3
    ch2.production, ch2.daily, ch2.roostPosition = True, 1.2, 1
    d1.tricks, d1.treat, d1.bed = ['rollover', 'dance', 'spin', 'stay', 'sit', 'come', 'shake'], 'Cheese', 'Sidecar'
    petList = [ch1, ch2, d1, d2, c1]

#===== PRINT - pet objects
def printObjects():
    pString = ""
    for p in petList:
        pString += '{name} is a {age} year old {breed} {animal} that eats {feed}.\n\t'.format(name = p.name, animal = p.animal, breed = p.breed, age = p.age, feed = p.feed)
        if p.animal == 'Chicken':
            pString += '- {name} sleeps in roosting position {roost} and '.format(name = p.name, roost = p.roostPosition)
            if p.production:
                pString += 'currently lays {prod} eggs per day.\n'.format(prod = p.daily)
            else:
                pString += 'is currently not laying eggs.\n'
        elif p.animal =='Dog':
            pString += '- {name} will perform {trickCount} tricks for {treatName} and sleeps on a {bedName}.\n'.format(name = p.name, trickCount = len(p.tricks), treatName = p.treat, bedName = p.bed)
        elif p.animal =='Cat':
            pString += '- {name} wants to play at {playTime} and nap at {napTime} each day.\n'.format(name = p.name, playTime = p.playTime, napTime = p.napTime)
    print(pString)

#===== MAIN - script to run
if __name__ == '__main__':
    createObjects()
    printObjects()


import math

import pyxel

from ui import UI

class InGameUI(UI):

    UI_ID = "ingameui"

    def __init__(self, gamecore):
        self.gamecore = gamecore

    def draw(self):
        player = self.gamecore.getPlayer()
        base_x = 0
        base_y = 224
        pyxel.rect(base_x, base_y, 256, 32, pyxel.COLOR_WHITE)
        pyxel.rect(base_x + 1, base_y + 1, 254, 30, pyxel.COLOR_BLACK)
        # HP
        health_ratio = player.health / player.maxHealth
        pyxel.text(base_x + 4, base_y + 4, "VIT:", pyxel.COLOR_WHITE)
        pyxel.rect(base_x + 20, base_y + 4, 30, 5, pyxel.COLOR_NAVY)
        pyxel.rect(base_x + 20, base_y + 4, math.ceil(30 * health_ratio), 5, pyxel.COLOR_ORANGE)
        # Calorie
        calorie = player.calorie / player.maxCalorie
        pyxel.text(base_x + 4, base_y + 12, "CAL:", pyxel.COLOR_WHITE)
        pyxel.rect(base_x + 20, base_y + 12, 30, 5, pyxel.COLOR_NAVY)
        pyxel.rect(base_x + 20, base_y + 12, math.ceil(30 * calorie), 5, pyxel.COLOR_YELLOW)
        # 未実装
        pyxel.text(base_x + 4, base_y + 20, "___:", pyxel.COLOR_WHITE)
        pyxel.rect(base_x + 20, base_y + 20, 30, 5, pyxel.COLOR_NAVY)
        # 線
        pyxel.line(base_x + 54, base_y + 4, base_x + 54, base_y + 24, pyxel.COLOR_WHITE)
        # Inventory
        inv_base_x = base_x + 59
        inv_base_y = base_y + 4
        for i in range(int(player.inventory.size / 2)):
            for j in range(2):
                pyxel.blt(inv_base_x + i*11, inv_base_y + j*11, 0, 128, 0, 10, 10, 0)
                pyxel.blt(inv_base_x + i*11 + 1, inv_base_y + j*11 + 1, 0, player.inventory.contents[i * 2 + j].TEXTURE[0], player.inventory.contents[i * 2 + j].TEXTURE[1], 8, 8, 0)
        pyxel.blt(inv_base_x + int(player.inventory.holdIndex / 2) * 11, inv_base_y + int(player.inventory.holdIndex % 2) * 11, 0, 128, 16, 10, 10, 0)
        pyxel.line(base_x + 116, base_y + 14, base_x + 180, base_y + 14, pyxel.COLOR_WHITE)
        pyxel.blt(base_x + 117, inv_base_y + 1, 0, player.inventory.getItemInHand().TEXTURE[0], player.inventory.getItemInHand().TEXTURE[1], 8, 8, 0)
        pyxel.text(base_x + 127, inv_base_y + 3, ": " + player.inventory.getItemInHand().getName(), pyxel.COLOR_WHITE)
        # 線
        pyxel.line(base_x + 184, base_y + 4, base_x + 184, base_y + 24, pyxel.COLOR_WHITE)


dial = {
    1 : "",
    2 : "ABC",
    3 : 'DEF',
    4 : 'GHI',
    5 : 'JKL',
    6 : 'MNO',
    7 : 'PQRS',
    8 : 'TUV',
    9 : 'WxYZ'
}

string = input()
cnt = 0
for i in dial.values():
    for j in string:
        if j in i:
            cnt+= dial
print(cnt)


import re, sys, json

from jasy.js.tokenize.Lang import keywords
from jasy.js.parse.Lang import expressions, futureReserved

all = [ "Compressor" ]

high_unicode = re.compile(r"\\u[2-9A-Fa-f][0-9A-Fa-f]{3}")
ascii_encoder = json.JSONEncoder(ensure_ascii=True)
unicode_encoder = json.JSONEncoder(ensure_ascii=False)

#
# Class
#

class Compressor:
    __semicolonSymbol = ";"
    __commaSymbol = ","

    def __init__(self, format=None):
        if format:
            if format.has("semicolon"):
                self.__semicolonSymbol = ";\n"

            if format.has("comma"):
                self.__commaSymbol = ",\n"

        self.__forcedSemicolon = False

    #
    # Main
    #

    def compress(self, node):
        type = node.type
        result = None

        if type in self.__simple:
            result = type
        elif type in self.__prefixes:
            if getattr(node, "postfix", False):
                result = self.compress(node[0]) + self.__prefixes[node.type]
            else:
                result = self.__prefixes[node.type] + self.compress(node[0])

        elif type in self.__dividers:
            first = self.compress(node[0])
            second = self.compress(node[1])
            divider = self.__dividers[node.type]

            # Fast path
            if node.type not in ("plus", "minus"):
                result = "%s%s%s" % (first, divider, second)

            # Special code for dealing with situations like x + ++y and y-- - x
            else:
                result = first
                if first.endswith(divider):
                    result += " "

                result += divider

                if second.startswith(divider):
                    result += " "

                result += second

        else:
            try:
                result = getattr(self, "type_%s" % type)(node)
            except KeyError:
                print("Compressor does not support type '%s' from line %s in file %s" % (type, node.line, node.getFileName()))
                sys.exit(1)

        if getattr(node, "parenthesized", None):
            return "(%s)" % result
        else:
            return result

    #
    # Helpers
    #

    def __statements(self, node):
        result = []
        for child in node:
            result.append(self.compress(child))

        return "".join(result)

    def __handleForcedSemicolon(self, node):
        if node.type == "semicolon" and not hasattr(node, "expression"):
            self.__forcedSemicolon = True

    def __addSemicolon(self, result):
        if not result.endswith(self.__semicolonSymbol):
            if self.__forcedSemicolon:
                self.__forcedSemicolon = False

            return result + self.__semicolonSymbol

        else:
            return result

    def __removeSemicolon(self, result):
        if self.__forcedSemicolon:
            self.__forcedSemicolon = False
            return result

        if result.endswith(self.__semicolonSymbol):
            return result[:-len(self.__semicolonSymbol)]
        else:
            return result

    #
    # Data
    #

    __simple_property = re.compile(r"^[a-zA-Z_$][a-zA-Z0-9_$]*$")
    __number_property = re.compile(r"^[0-9]+$")

    __simple = ["true", "false", "null", "this", "debugger"]

    __dividers = {
        "plus"        : '+',
        "minus"       : '-',
        "mul"         : '*',
        "div"         : '/',
        "mod"         : '%',
        "dot"         : '.',
        "or"          : "||",
        "and"         : "&&",
        "strict_eq"   : '===',
        "eq"          : '==',
        "strict_ne"   : '!==',
        "ne"          : '!=',
        "lsh"         : '<<',
        "le"          : '<=',
        "lt"          : '<',
        "ursh"        : '>>>',
        "rsh"         : '>>',
        "ge"          : '>=',
        "gt"          : '>',
        "bitwise_or"  : '|',
        "bitwise_xor" : '^',
        "bitwise_and" : '&'
    }

    __prefixes = {
        "increment"   : "++",
        "decrement"   : "--",
        "bitwise_not" : '~',
        "not"         : "!",
        "unary_plus"  : "+",
        "unary_minus" : "-",
        "delete"      : "delete ",
        "new"         : "new ",
        "typeof"      : "typeof ",
        "void"        : "void "
    }

    #
    # Script Scope
    #

    def type_script(self, node):
        return self.__statements(node)

    #
    # Expressions
    #

    def type_comma(self, node):
        return self.__commaSymbol.join(map(self.compress, node))

    def type_object_init(self, node):
        return "{%s}" % self.__commaSymbol.join(map(self.compress, node))

    def type_property_init(self, node):
        key = self.compress(node[0])
        value = self.compress(node[1])

        if type(key) in (int, float):
            pass

        elif self.__number_property.match(key):
            pass

        # Protect keywords and special characters
        elif key in keywords or key in futureReserved or not self.__simple_property.match(key):
            key = self.type_string(node[0])

        return "%s:%s" % (key, value)

    def type_array_init(self, node):
        def helper(child):
            return self.compress(child) if child != None else ""

        return "[%s]" % ",".join(map(helper, node))

    def type_array_comp(self, node):
        return "[%s %s]" % (self.compress(node.expression), self.compress(node.tail))

    def type_string(self, node):
        # Omit writing real high unicode character which are not supported well by browsers
        ascii = ascii_encoder.encode(node.value)

        if high_unicode.search(ascii):
            return ascii
        else:
            return unicode_encoder.encode(node.value)

    def type_number(self, node):
        value = node.value

        # Special handling for protected float/exponential
        if type(value) == str:
            # Convert zero-prefix
            if value.startswith("0.") and len(value) > 2:
                value = value[1:]

            # Convert zero postfix
            elif value.endswith(".0"):
                value = value[:-2]

        elif int(value) == value and node.parent.type != "dot":
            value = int(value)

        return "%s" % value

    def type_regexp(self, node):
        return node.value

    def type_identifier(self, node):
        return node.value

    def type_list(self, node):
        return ",".join(map(self.compress, node))

    def type_index(self, node):
        return "%s[%s]" % (self.compress(node[0]), self.compress(node[1]))

    def type_declaration(self, node):
        names = getattr(node, "names", None)
        if names:
            result = self.compress(names)
        else:
            result = node.name

        initializer = getattr(node, "initializer", None)
        if initializer:
            result += "=%s" % self.compress(node.initializer)

        return result

    def type_assign(self, node):
        assignOp = getattr(node, "assignOp", None)
        operator = "=" if not assignOp else self.__dividers[assignOp] + "="

        return self.compress(node[0]) + operator + self.compress(node[1])

    def type_call(self, node):
        return "%s(%s)" % (self.compress(node[0]), self.compress(node[1]))

    def type_new_with_args(self, node):
        result = "new %s" % self.compress(node[0])

        # Compress new Object(); => new Object;
        if len(node[1]) > 0:
            result += "(%s)" % self.compress(node[1])
        else:
            parent = getattr(node, "parent", None)
            if parent and parent.type is "dot":
                result += "()"

        return result

    def type_exception(self, node):
        return node.value

    def type_generator(self, node):
        """ Generator Expression """
        result = self.compress(getattr(node, "expression"))
        tail = getattr(node, "tail", None)
        if tail:
            result += " %s" % self.compress(tail)

        return result

    def type_comp_tail(self, node):
        """  Comprehensions Tails """
        result = self.compress(getattr(node, "for"))
        guard = getattr(node, "guard", None)
        if guard:
            result += "if(%s)" % self.compress(guard)

        return result

    def type_in(self, node):
        first = self.compress(node[0])
        second = self.compress(node[1])

        if first.endswith("'") or first.endswith('"'):
            pattern = "%sin %s"
        else:
            pattern = "%s in %s"

        return pattern % (first, second)

    def type_instanceof(self, node):
        first = self.compress(node[0])
        second = self.compress(node[1])

        return "%s instanceof %s" % (first, second)

    #
    # Statements :: Core
    #

    def type_block(self, node):
        return "{%s}" % self.__removeSemicolon(self.__statements(node))

    def type_let_block(self, node):
        begin = "let(%s)" % ",".join(map(self.compress, node.variables))
        if hasattr(node, "block"):
            end = self.compress(node.block)
        elif hasattr(node, "expression"):
            end = self.compress(node.expression)

        return begin + end

    def type_const(self, node):
        return self.__addSemicolon("const %s" % self.type_list(node))

    def type_var(self, node):
        return self.__addSemicolon("var %s" % self.type_list(node))

    def type_let(self, node):
        return self.__addSemicolon("let %s" % self.type_list(node))

    def type_semicolon(self, node):
        expression = getattr(node, "expression", None)
        return self.__addSemicolon(self.compress(expression) if expression else "")

    def type_label(self, node):
        return self.__addSemicolon("%s:%s" % (node.label, self.compress(node.statement)))

    def type_break(self, node):
        return self.__addSemicolon("break" if not hasattr(node, "label") else "break %s" % node.label)

    def type_continue(self, node):
        return self.__addSemicolon("continue" if not hasattr(node, "label") else "continue %s" % node.label)

    #
    # Statements :: Functions
    #

    def type_function(self, node):
        if node.type == "setter":
            result = "set"
        elif node.type == "getter":
            result = "get"
        else:
            result = "function"

        name = getattr(node, "name", None)
        if name:
            result += " %s" % name

        params = getattr(node, "params", None)
        result += "(%s)" % self.compress(params) if params else "()"

        # keep expression closure format (may be micro-optimized for other code, too)
        if getattr(node, "expressionClosure", False):
            result += self.compress(node.body)
        else:
            result += "{%s}" % self.__removeSemicolon(self.compress(node.body))

        return result

    def type_getter(self, node):
        return self.type_function(node)

    def type_setter(self, node):
        return self.type_function(node)

    def type_return(self, node):
        result = "return"
        if hasattr(node, "value"):
            valueCode = self.compress(node.value)

            # Micro optimization: Don't need a space when a block/map/array/group/strings are returned
            if not valueCode.startswith(("(","[","{","'",'"',"!","-","/")):
                result += " "

            result += valueCode

        return self.__addSemicolon(result)

    #
    # Statements :: Exception Handling
    #

    def type_throw(self, node):
        return self.__addSemicolon("throw %s" % self.compress(node.exception))

    def type_try(self, node):
        result = "try%s" % self.compress(node.tryBlock)

        for catch in node:
            if catch.type == "catch":
                if hasattr(catch, "guard"):
                    result += "catch(%s if %s)%s" % (self.compress(catch.exception), self.compress(catch.guard), self.compress(catch.block))
                else:
                    result += "catch(%s)%s" % (self.compress(catch.exception), self.compress(catch.block))

        if hasattr(node, "finallyBlock"):
            result += "finally%s" % self.compress(node.finallyBlock)

        return result

    #
    # Statements :: Loops
    #

    def type_while(self, node):
        result = "while(%s)%s" % (self.compress(node.condition), self.compress(node.body))
        self.__handleForcedSemicolon(node.body)
        return result

    def type_do(self, node):
        # block unwrapping don't help to reduce size on this loop type
        # but if it happens (don't like to modify a global function to fix a local issue), we
        # need to fix the body and re-add braces around the statement
        body = self.compress(node.body)
        if not body.startswith("{"):
            body = "{%s}" % body

        return self.__addSemicolon("do%swhile(%s)" % (body, self.compress(node.condition)))

    def type_for_in(self, node):
        # Optional variable declarations
        varDecl = getattr(node, "varDecl", None)

        # Body is optional - at least in comprehensions tails
        body = getattr(node, "body", None)
        if body:
            body = self.compress(body)
        else:
            body = ""

        result = "for"
        if node.isEach:
            result += " each"

        result += "(%s in %s)%s" % (self.__removeSemicolon(self.compress(node.iterator)), self.compress(node.object), body)

        if body:
            self.__handleForcedSemicolon(node.body)

        return result

    def type_for(self, node):
        setup = getattr(node, "setup", None)
        condition = getattr(node, "condition", None)
        update = getattr(node, "update", None)

        result = "for("
        result += self.__addSemicolon(self.compress(setup) if setup else "")
        result += self.__addSemicolon(self.compress(condition) if condition else "")
        result += self.compress(update) if update else ""
        result += ")%s" % self.compress(node.body)

        self.__handleForcedSemicolon(node.body)
        return result

    #
    # Statements :: Conditionals
    #

    def type_hook(self, node):
        """aka ternary operator"""
        condition = node.condition
        thenPart = node.thenPart
        elsePart = node.elsePart

        if condition.type == "not":
            [thenPart,elsePart] = [elsePart,thenPart]
            condition = condition[0]

        return "%s?%s:%s" % (self.compress(condition), self.compress(thenPart), self.compress(elsePart))

    def type_if(self, node):
        result = "if(%s)%s" % (self.compress(node.condition), self.compress(node.thenPart))

        elsePart = getattr(node, "elsePart", None)
        if elsePart:
            result += "else"

            elseCode = self.compress(elsePart)

            # Micro optimization: Don't need a space when the child is a block
            # At this time the brace could not be part of a map declaration (would be a syntax error)
            if not elseCode.startswith(("{", "(", ";")):
                result += " "

            result += elseCode

            self.__handleForcedSemicolon(elsePart)

        return result

    def type_switch(self, node):
        result = "switch(%s){" % self.compress(node.discriminant)
        for case in node:
            if case.type == "case":
                labelCode = self.compress(case.label)
                if labelCode.startswith('"'):
                    result += "case%s:" % labelCode
                else:
                    result += "case %s:" % labelCode
            elif case.type == "default":
                result += "default:"
            else:
                continue

            for statement in case.statements:
                temp = self.compress(statement)
                if len(temp) > 0:
                    result += self.__addSemicolon(temp)

        return "%s}" % self.__removeSemicolon(result)


#!/usr/bin/env python
#-*- coding:utf-8 -*-
"""
焊盘定义
Author: cdhigh <https://github.com/cdhigh>
"""
from comm_utils import pointDistance
from .sprint_element import *

#Pad的形状
PAD_FORM_ROUND = 1
PAD_FORM_OCTAGON = 2
PAD_FORM_SQUARE = 3
PAD_FORM_RECT_ROUND_H = 4
PAD_FORM_RECT_OCTAGON_H = 5
PAD_FORM_RECT_H = 6
PAD_FORM_RECT_ROUND_V = 7
PAD_FORM_RECT_OCTAGON_V = 8
PAD_FORM_RECT_V = 9

sprintPadFormMap = {
    PAD_FORM_ROUND: 'Round',
    PAD_FORM_OCTAGON: 'Octagon',
    PAD_FORM_SQUARE: 'Square',
    PAD_FORM_RECT_ROUND_H: 'RectRH',
    PAD_FORM_RECT_OCTAGON_H: 'RectOH',
    PAD_FORM_RECT_H: 'RectH',
    PAD_FORM_RECT_ROUND_V: 'RectRV',
    PAD_FORM_RECT_OCTAGON_V: 'RectOV',
    PAD_FORM_RECT_V: 'RectV',
}

#sprint的Pad类
class SprintPad(SprintElement):
    def __init__(self, padType: str='PAD', layerIdx: int=1):
        super().__init__(layerIdx)
        self.padType = padType # 'PAD'/'SMDPAD'
        self.pos = (0, 0)
        self.size = 0 #外径
        self.sizeX = 0
        self.sizeY = 0
        self.drill = 0  #钻孔直径
        self.form = PAD_FORM_ROUND
        self.clearance = None
        self.soldermask = None
        self.rotation = None
        self.via = None
        self.thermal = None
        self.thermalTracksWidth = 0
        self.thermalTracksIndividual = None
        self.thermalTracks = 0
        self.padId = None
        self.connectToOtherPads = [] #从此焊盘到特定其他焊盘的网络连线

    def isValid(self):
        return (self.size > 0) if (self.padType == 'PAD') else ((self.sizeX > 0) and (self.sizeY > 0))

    def updateSelfBbox(self):
        self.xMin = self.yMin = 100000.0
        self.xMax = self.yMax = -100000.0
        if (self.padType == 'PAD'):
            size2 = self.size / 2
            self.updateBbox(self.pos[0] - size2, self.pos[1] - size2)
            self.updateBbox(self.pos[0] + size2, self.pos[1] + size2)
        else:
            self.updateBbox(self.pos[0] - self.sizeX / 2, self.pos[1] - self.sizeY / 2)
            self.updateBbox(self.pos[0] + self.sizeX / 2, self.pos[1] + self.sizeY / 2)

    def __str__(self):
        return self.toStr()

    def toStr(self, overwritePadId=None):
        return self.toStrPad(overwritePadId) if self.padType == 'PAD' else self.toStrSmdPad(overwritePadId)

    #生成通孔焊盘的字符串
    def toStrPad(self, overwritePadId=None):
        outStr = ['PAD,LAYER={},POS={}/{},SIZE={},DRILL={},FORM={}'.format(self.layerIdx, self.mm2um01(self.pos[0]),
            self.mm2um01(self.pos[1]), self.mm2um01(self.size), self.mm2um01(self.drill), self.form)]
        if self.clearance is not None:
            outStr.append('CLEAR={}'.format(self.mm2um01(self.clearance)))
        if self.soldermask is not None:
            outStr.append('SOLDERMASK={}'.format(self.booleanStr(self.soldermask)))
        if (self.form != PAD_FORM_ROUND) and (self.rotation is not None):
            outStr.append('ROTATION={:0.0f}'.format(self.rotation * 100)) #焊盘的旋转单位为0.01度
        if self.via is not None:
            outStr.append('VIA={}'.format(self.booleanStr(self.via)))
        if self.thermal is not None:
            outStr.append('THERMAL={}'.format(self.booleanStr(self.thermal)))
        if self.thermalTracksWidth:
            outStr.append('THERMAL_TRACKS_WIDTH={}'.format(self.thermalTracksWidth))
        if self.thermalTracksIndividual is not None:
            outStr.append('THERMAL_TRACKS_INDIVIDUAL={}'.format(self.booleanStr(self.thermalTracksIndividual)))
        if self.thermalTracks:
            outStr.append('THERMAL_TRACKS={}'.format(self.thermalTracks))
        if overwritePadId is not None:
            outStr.append('PAD_ID={}'.format(overwritePadId))
        else:
            if self.padId is not None:
                outStr.append('PAD_ID={}'.format(self.padId))
            for conIdx, con in enumerate(self.connectToOtherPads):
                outStr.append('CON{}={}'.format(conIdx, con))
        if self.name:
            outStr.append('NAME=|{}|'.format(self.justifiedText(self.name)))

        return ','.join(outStr) + ';'

    #生成贴片焊盘的字符串
    def toStrSmdPad(self, overwritePadId=None):
        outStr = ['SMDPAD,LAYER={},POS={}/{},SIZE_X={},SIZE_Y={}'.format(self.layerIdx,
            self.mm2um01(self.pos[0]), self.mm2um01(self.pos[1]), self.mm2um01(self.sizeX), self.mm2um01(self.sizeY))]
        if self.clearance:
            outStr.append('CLEAR={}'.format(self.mm2um01(self.clearance)))
        if self.soldermask is not None:
            outStr.append('SOLDERMASK={}'.format(self.booleanStr(self.soldermask)))
        if self.rotation is not None:
            outStr.append('ROTATION={:0.0f}'.format(self.rotation * 100))
        if self.thermal is not None:
            outStr.append('THERMAL={}'.format(self.booleanStr(self.thermal)))
        if self.thermalTracksWidth:
            outStr.append('THERMAL_TRACKS_WIDTH={}'.format(self.thermalTracksWidth))
        if self.thermalTracks:
            outStr.append('THERMAL_TRACKS={}'.format(self.thermalTracks))
        if overwritePadId is not None:
            outStr.append('PAD_ID={}'.format(overwritePadId))
        else:
            if self.padId is not None:
                outStr.append('PAD_ID={}'.format(self.padId))
            for conIdx, con in enumerate(self.connectToOtherPads):
                outStr.append('CON{}={}'.format(conIdx, con))
        if self.name:
            outStr.append('NAME=|{}|'.format(self.justifiedText(self.name)))

        return ','.join(outStr) + ';'

    #重载等号运算符，用于导出DSN时将所有相同类型的焊盘归类并给一个名字
    def __eq__(self, other):
        if not isinstance(other, SprintPad):
            return False

        if ((self.layerIdx != other.layerIdx) or (self.padType != other.padType) or (self.size != other.size)
            or (self.sizeX != other.sizeX) or (self.sizeY != other.sizeY) or (self.drill != other.drill)
            or (self.form != other.form) or (self.rotation != other.rotation) or (self.clearance != other.clearance)
            or (self.soldermask != other.soldermask) or (self.via != other.via) or (self.thermal != other.thermal)
            or (self.thermalTracksWidth != other.thermalTracksWidth) or (self.thermalTracksIndividual != other.thermalTracksIndividual)
            or (self.thermalTracks != other.thermalTracks)):
            return False
        else:
            return True

    #给焊盘起一个名字，用于DSN导出
    def generateDsnName(self):
        rotation = '' #self.rotation if self.rotation else ''
        if self.padType == 'PAD':
            name = 'PAD_{}_{}_{}x{}{}{}'.format(self.layerIdx, sprintPadFormMap.get(self.form, ''),
                self.mm2um01(self.size), self.mm2um01(self.drill), ('_via' if self.via else ''), rotation)
        else:
            name = 'SMDPAD_{}_{}x{}{}'.format(self.layerIdx, self.mm2um01(self.sizeX), self.mm2um01(self.sizeY), rotation)

        return name

    #复制一个自身，并且将坐标相对某个新原点进行移动，
    #ox/oy: 新的原点坐标
    def cloneToNewOrigin(self, ox: float, oy: float, overwritePadId=None):
        ins = SprintPad(self.padType, self.layerIdx)
        ins.pos = (round(self.pos[0] - ox, 4), round(self.pos[1] - oy, 4))
        ins.size = self.size
        ins.sizeX = self.sizeX
        ins.sizeY = self.sizeY
        ins.drill = self.drill
        ins.form = self.form
        ins.clearance = self.clearance
        ins.soldermask = self.soldermask
        ins.rotation = self.rotation
        ins.via = self.via
        ins.thermal = self.thermal
        ins.thermalTracksWidth = self.thermalTracksWidth
        ins.thermalTracksIndividual = self.thermalTracksIndividual
        ins.thermalTracks = self.thermalTracks
        ins.padId = overwritePadId if overwritePadId is not None else self.padId
        ins.connectToOtherPads = self.connectToOtherPads[:]
        ins.name = self.name
        ins.updateSelfBbox()
        return ins

    #移动自身的位置
    def moveByOffset(self, offsetX: float, offsetY: float):
        self.pos = (round(self.pos[0] - offsetX, 4), round(self.pos[1] - offsetY, 4))
        self.updateSelfBbox()

    #判断一个点是否在本焊盘的范围内，用最简化的算法，到中心的距离小于最小外围尺寸
    #如果y=None，则x为一个点定义(x,y)
    def enclose(self, x, y: float=None):
        if (y is None):
            x, y = x

        dist = pointDistance(x, y, self.pos[0], self.pos[1])
        size = (self.size / 2) if (self.padType == 'PAD') else (min(self.sizeX, self.sizeY) / 2)
        return True if (dist < size) else False

    #计算焊盘的面积
    def area(self):
        padType = self.padType
        padForm = self.form
        if (padType == 'SMDPAD'):
            return self.sizeX * self.sizeY #矩形面积
        elif (padForm in (PAD_FORM_ROUND, PAD_FORM_OCTAGON)):
            return 3.14159 * (self.size / 2) * (self.size / 2) #圆面积
        elif (padForm == PAD_FORM_SQUARE):
            return self.size * self.size #正方形面积
        else: #其他的都当作矩形
            return self.size * self.size * 2


import numpy as np

class WFS:

	def __init__(self, no_users, no_items, no_factors=100):
		"""
		:param no_users: Number of users
		:param no_items: Number of items
		:param no_factors: Number of latent factors to use
		"""
		self.no_users = no_users
		self.no_items = no_items
		self.no_factors = no_factors

		self.X = 5 * np.random.rand(no_users, no_factors)
		self.Y = 5 * np.random.rand(no_factors, no_items)
		self.latent_matrix = np.empty([no_users, no_items])

	def optimise(self, data, alpha=1, eta=0.1, reg_term=0.1, no_iterations=100):
		"""
		Optimise using ALS
		:param data: the data matrix (users, items)
		:param alpha: scale factor
		:param eta: scale factor
		:param no_iterations: number of ALS iterations to perform
		"""
		P = data > 0.5
		C = np.ones_like(P) + alpha * np.log(np.ones_like(P) + (np.zeros_like(P) + 1/eta) * data)

		weighted_errors = []
		for i in range(0, no_iterations):
			self._optimise_step(C, P, reg_term)
			error = self._mse(C, P)
			weighted_errors.append(error)
			print('{}th iteration is completed'.format(i))
			print('Error {}'.format(error))
			print('\n')

		self.latent_matrix = np.dot(self.X, self.Y)

	def _optimise_step(self, C, P, reg_term):
		for u, Wu in enumerate(C):
			self.X[u] = np.linalg.solve(np.dot(self.Y, np.dot(np.diag(Wu), self.Y.T)) + reg_term * np.eye(self.no_factors),
			                       np.dot(self.Y, np.dot(np.diag(Wu), P[u].T))).T
		for i, Wi in enumerate(C.T):
			self.Y[:,i] = np.linalg.solve(np.dot(self.X.T, np.dot(np.diag(Wi), self.X)) + reg_term * np.eye(self.no_factors),
			                         np.dot(self.X.T, np.dot(np.diag(Wi), P[:, i])))

	def _mse(self, C, P):
		"""
		:param C: confidence matrix
		:param P: preference matrix
		:param X: User
		:param Y: Item
		:return: The mean squared error
		"""
		return np.sum((C * (P - np.dot(self.X, self.Y)))**2)

	def write(self, filename, ind_song_map=None):
		"""
		:param filename: the filename to write to
		:param ind_song_map: a numpy array from index to song id
		"""
		np.savetxt(filename + '.txt', self.Y.T, fmt='%f')
		if ind_song_map is not None:
			np.savetxt(filename + '-song-map.txt', ind_song_map, fmt='%s')


from typing import NamedTuple, Optional, Tuple
from uuid import UUID

from pyminehub.mcpe.command.const import CommandPermission, CommandOriginDataType

__all__ = [
    'CommandEnum',
    'CommandParameter',
    'CommandData',
    'CommandSpec',
    'CommandOriginData'
]

CommandEnum = NamedTuple('CommandEnum', [
    ('name', str),
    ('index', Tuple[int, ...])
])

CommandParameter = NamedTuple('CommandParameter', [
    ('name', str),
    ('type', int),
    ('is_optional', bool)
])

CommandData = NamedTuple('CommandData', [
    ('name', str),
    ('description', str),
    ('flags', int),
    ('permission', int),
    ('aliases', int),
    ('overloads', Tuple[Tuple[CommandParameter, ...], ...])
])

CommandSpec = NamedTuple('CommandSpec', [
    ('enum_values', Tuple[str, ...]),
    ('postfixes', Tuple[str, ...]),
    ('enums', Tuple[CommandEnum, ...]),
    ('command_data', Tuple[CommandData, ...]),
    ('permission', CommandPermission)
])

CommandOriginData = NamedTuple('CommandOriginData', [
    ('type', CommandOriginDataType),
    ('uuid', UUID),
    ('request_id', str),
    ('long1', Optional[int])
])


#!/usr/bin/python

import sys

total = 0
min_avg = 101
idx = []

for line in sys.stdin:
	line = line.strip().split()
	for n in range(2, len(line)):
		total += float(line[n][2:-2].split(',')[0])
	avg = total/(len(line) - 2)

	if avg == min_avg:
		idx.append(int(line[0][2:-2]))
	if avg < min_avg:
		min_avg = avg
		idx = []
		idx.append(int(line[0][2:-2]))
	total = 0

if len(idx) == 1:
	print('names: {0} scores: {1}'.format(idx[0], min_avg))
else:
	print('names: {0} scores: {1}'.format(idx, min_avg))


n=int(input())
l=list(map(int,input().split()))
c=0
for i in l:
    a=l.count(0)
    b=l.count(1)
if n==a+b:
    print('True')
else:
    print('False')


class Car():
    airbag_used=False
    def met_acc(self):
        self.airbag_used=True
"""In general, any operation performed using self will always make that operation specific to the instance/object who called the function and the result of which will be not be dedicated to other objects until they themselves call the same function again."""
ferrari=Car()
ferrari.met_acc()
a=ferrari.airbag_used

jaguar=Car()
print(jaguar.airbag_used)

benz=Car()
print(benz.airbag_used)

print(a)

print('Ferrari airbag memory location is: {}'.format(id(ferrari.airbag_used)))
print(' Jaguar airbag memory location is: {}'.format(id(benz.airbag_used)))
"""print('   Benz airbag memory location is: {}'.format(id(Jaguar.airbag_used)))"""